blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
0ce96b38ee72f345ea234bb397b6acc45233c7a0
davtoh/advutils
/advutils/counters.py
34,380
3.65625
4
#!/usr/bin/env python # -*- coding: latin-1 -*- """ This module defines counters useful to generate numbers simulating digital counters """ from __future__ import division from __future__ import print_function #from builtins import str from builtins import range from builtins import object from numbers import Number from past.utils import old_div # import exceptions from . import VariableNotSettable, VariableNotDeletable, VariableNotGettable def decima2base(decimal, base, array=None): """ Convert from decimal to any base. :param decimal: number in base 10 :param base: base to convert to e.g. 2 for binary, 16 for hexadecimal :param array: control list :return: list of number in converted base """ if array is None: array = [] array.insert(0, decimal % base) div = old_div(decimal, base) if(div == 0): return array return decima2base(div, base, array) class NumericalCounter(object): """ Simulates a signed integer counter from -Inf to Inf """ def __int__(self, *args, **kwargs): raise NotImplementedError class BaseCounter(object): """ Base class to create counters """ def __init__( self, min_state, max_state, child=None, parent=None, invert_count=False): """ :param max_state: from 1 to inf :param child: counter instance of least significant position :param parent: counter instance of most significant position thus to control. :param invert_count: if True then next method decreases, else increases """ self._master = None # keep track of who is the master self._min_state = min_state self._max_state = max_state self._state = min_state self.stopped = False # recognize when iterations should stop # True to decrease and False to increase when self.count() self._invert_count = invert_count self.count = None # count function self.set_child(child) # set this counter child self.set_parent(parent) # set this counter parent and master @property def count(self): return self._count @count.setter def count(self, value=None): """ restart count function """ # restart each time it is set def set_count_func(): if self.invert_count: self._count = self.decrease_confirm self._count() else: self._count = self.increase_confirm return False # Iterations not stopped # if self.invert_count: # master.decrease() if self.invert_count: self._count = set_count_func else: self._count = set_count_func @property def invert_count(self): return self._invert_count @invert_count.setter def invert_count(self, value): self._invert_count = value @invert_count.deleter def invert_count(self): del self._invert_count @count.deleter def count(self): # restart each time it is deleted self.count = None @property def master(self): if self._master is None: return self # return self if there is no master return self._master @master.setter def master(self, value): if value is not None: value = value.master # get master's master self._master = value @master.deleter def master(self): del self._master @property def min_state(self): return self._min_state @min_state.setter def min_state(self, value): self._min_state = value @min_state.deleter def min_state(self): del self._min_state @property def max_state(self): return self._max_state @max_state.setter def max_state(self, value): self._max_state = value @max_state.deleter def max_state(self): del self._max_state @property def state(self): return self._state @state.setter def state(self, value): self._state = value @state.deleter def state(self): del self._state ## CONTROL METHODS ## def take_place(self, new): """ Changes counter place with another counter. :param new: counter which place is to be taken :return: taken counter, if not successful returns None """ if new is not None and new != self: # confirm if other valid place nparent, nchild = new.parent, new.child sparent, schild = self.parent, self.child if sparent != new: new.set_parent(sparent) else: # works for "nchild != self" too new.set_parent(self) if schild != new: new.set_child(schild) else: # works for "nparent != self" too new.set_child(self) if nparent != self: # no need to implement else, "schild != place" else replaced it self.set_parent(nparent) if nchild != self: # no need to implement else, "sparent != place" else replaced it self.set_child(nchild) return new def demote(self): """ Takes child place. :return: master counter, if not successful returns None """ child = self.child if child is not None: return self.take_place(child) # new master def promote(self): """ Takes parent place. :return: master counter, if not successful returns None """ parent = self.parent if parent is not None: self.take_place(parent) return self # new master def invert_ranks(self): """ Counters in Train are repositioned so that last counter takes first place and vice-versa. :return: master counter of actual counter train """ counterList = self.get_counter_train() last = counterList[-1] l = len(counterList) - 1 for i in range(old_div((l + 1), 2)): counterList[i].take_place(counterList[l - i]) return last # reset functions # def reset(self): """ Resets itself and children. :return: None """ self._state = self._min_state self.reset_children() def reset_children(self): """ Resets only children. :return: None """ if self.child is not None: self.child.reset() def increase(self): """ Increases counter Train state. :return: None, use getting methods to know new states """ value = self._state + 1 if value >= self.max_state: self._state = self._min_state if self.child is not None: self.child.increase() else: self._state = value def decrease(self): """ Decreases counter Train state. :return: None, use getting methods to know new states """ value = self._state - 1 if value < self.min_state: self._state = self._max_state - 1 if self.child is not None: self.child.decrease() else: self._state = value def increase_confirm(self): """ Increases counter Train state and confirms when get_max_state() is depleted. That is when counters overall state change from get_max_state()-1 to 0. :return: True if confirmation otherwise None, use getting methods to know new states """ value = self._state + 1 if value >= self._max_state: self._state = self._min_state if self.child is not None: return self.child.increase_confirm() else: return True else: self._state = value def decrease_confirm(self): """ Decreases counter Train state and confirms when get_max_state() is depleted. That is when counters overall state change from 0 to get_max_state()-1. :return: True if confirmation otherwise None, use getting methods to know new states """ value = self._state - 1 if value < self._min_state: self._state = self._max_state - 1 if self.child is not None: return self.child.decrease_confirm() else: return True else: self._state = value def confirm(self): """ Confirm whether in next count state is truncated """ if (self.state - 1 < self._min_state) or (self.state + 1 >= self._max_state): if self.child is not None: return self.child.confirm() else: return True ## SETTING METHODS ## def set_parent(self, parent): """ Sets parent safely by telling the other counter who is the new child. :param parent: parent counter :return: None """ self.parent = parent if parent is not None and parent.child != self: parent.set_child(self) def set_child(self, child): """ Sets child safely by telling the other counter who is the new parent. :param child: child counter :return: None """ self.child = child if child is not None and child.parent != self: child.set_parent(self) def set_this_state(self, value): """ Sets safely this counter state. :param value: new value state. If value exceeds max_state then value takes max_state-1 or if value is less than 0 it takes 0 :return: None """ if value >= self._max_state: self.state = self._max_state - 1 elif value < self.min_state: self.state = self._min_state else: self.state = value def set_state_train(self, values): """ Sets safely a counter state train. :param values: new train of states (list). If value exceeds max_state then value takes max_state-1 or if value is less than 0 it takes 0 :return: None """ self.set_this_state(values[0]) if self.child is not None and len(values) >= 2: self.child.set_state_train(values[1:]) def set_this_max_state(self, value): """ Sets safely this counter max_state. :param value: new max_state. If state exceeds max_state then state takes max_state-1 :return: None """ self._max_state = value if self.state >= value: self.state = value - 1 def set_max_state_train(self, values): """ Sets safely a counter max_state train. :param value: new train of max_state(list). If state exceeds max_state then state takes max_state-1. :return: None """ self.set_this_max_state(values[0]) if self.child is not None and len(values) >= 2: self.child.set_max_state_train(values[1:]) ## REQUESTING METHODS ## def get_state(self, train=None): """ Get overall state of train. :param train: :return: overall state """ if not train: train = [] iter = self._state for i in train: iter *= i if self.child is not None: train.append(self._max_state) iter += self.child.get_state(train) return iter def get_state_train(self, train=None): """ All states or state train. :param train: list containing parent states :return: list of state from itself and children """ if not train: train = [] train.append(self._state) if self.child is not None: self.child.get_state_train(train) return train def get_max_state(self, train=None): """ Get the overall maximum state of train. :param train: list containing parent maximum states :return: overall maximum state. Note: maximum state is never reached but this.get_max_state()-1 """ iter = self._max_state if train: for i in train: iter *= i if self.child is not None: iter *= self.child.get_max_state() return iter def get_max_state_train(self, train=None): """ Get each max_state of train. :param train: list containing max_state of parents :return: list of max_state from itself and children """ if not train: train = [] train.append(self._max_state) if self.child is not None: self.child.get_max_state_train(train) return train def get_counter_train(self, train=None): """ Get each instance of train. :param train: list containing instances of parents :return: list of instances from itself and children """ if not train: train = [] train.append(self) if self.child is not None: self.child.get_counter_train(train) return train def yield_counter_train(self): """ Get generator of each instance of train. :return: generator of instances from itself and children """ yield self if self.child is not None: for i in self.child.yield_counter_train(): yield i ## OTHER METHODS ## def __str__(self): return str(self.state) def __repr__(self): return str(self.state) def __int__(self): return int(self.state) def __float__(self): return float(self.state) def __iter__(self): self.count = None self.stopped = False return self def __next__(self): if self.stopped: raise StopIteration self.stopped = self.count() # first call is to get the count function if self.stopped: raise StopIteration return self next = __next__ # compatibility with python 2 def __bool__(self): return bool(self.get_state()) __nonzero__ = __bool__ # compatibility with python 2 class IntegerCounter(BaseCounter): """ Simulates an unsigned integer counter from 0 to Inf +------+ | 0 | +------+ to +------+ | Inf | +------+ """ def __init__(self, max_state, child=None, parent=None, invert_count=False): """ :param max_state: from 1 to inf :param child: counter instance of least significant position :param parent: counter instance of most significant position thus to control. :param invert_count: if True then next method decreases, else increases """ super( IntegerCounter, self).__init__( 0, max_state, child, parent, invert_count) self.max_state = max_state @property def max_state(self): return self._max_state @max_state.setter def max_state(self, value): assert value > self.min_state, "number of states must be greater than 0" self._max_state = value @max_state.deleter def max_state(self): del self._max_state @property def state(self): return self._state @state.setter def state(self, value): if value > self.max_state - 1: raise Exception( "Value must not be greater than {}".format( self.max_state - 1)) if value < 0: raise Exception("Value must non negative and got {}".format(value)) self._state = value @state.deleter def state(self): del self._state ## SETTING METHODS ## def set_state(self, state, truncate=True, train=None): """ Sets safely this and all counters state train from the overall state. :param state: overall state :param truncate: it is by default True. If True it calculates the states as if in a for loop:: for i in xrange(state): this.increase() this.get_state() If False it just stops to the last possible state before this.get_max_state() :param train: previously calculated train if this counter is not master ex: if this and master counters maxStates are T and M then extract the trains using get_max_state_train from both this and master, so that master elements reach until previous counter of this counter [M,10, ...,T-1]. Similarly, get_max_state method can be used as [master.get_max_state()/this.get_max_state()] :return: reached_overall_state :: if truncate == True: assert reached_overall_state == state % a.get_max_state() else: remaining = state - reached_overall_state """ # This only works if self.min_state = 0 if not train: # first recursive level assert self.min_state == 0 train = [] if truncate: state = state % self.get_max_state() # truncate max iteration ans, self.state, newval, iter = 0, 0, 0, 1 # init variables if self.child is not None: train.append(self.max_state) ans = self.child.set_state(state, False, train) train.pop() remaining = state - ans for i in train: iter *= i if iter <= remaining: for i in range(self.max_state - 1, -1, -1): newval = iter * i if newval <= remaining: self.state = i break return newval + ans # overall state class DigitCounter(IntegerCounter): """ Simulates a digit counter from 0 to 9 +---+ | 0 | +---+ to +---+ | 9 | +---+ """ @IntegerCounter.max_state.setter def max_state(self, value): assert value < 10, "number of states must be less than 10" assert value > 0, "number of states must be greater than 0" self._max_state = value class MechanicalCounter(BaseCounter): """ Simulates a mechanical counter. It is a wrapper over a train of counters. By default it uses a DigitCounter for each slot in the Train. +---+---+---+---+---+ | 0 | 0 | 0 | 0 | 0 | +---+---+---+---+---+ to +---+---+---+---+---+ | 9 | 9 | 9 | 9 | 9 | +---+---+---+---+---+ """ def __init__(self, values, invert_count=False, invert_order=False, order=None, default_class=DigitCounter): """ :param values: list of maximum states (excluded) or default_class objects inherited from counter :param invert_count: Default is False that begins to increase counters, else decrease counters :param invert_order: if True, take inverted values from order :param order: index order from Train of counters :param default_class: default class of any object to convert from values. """ super(MechanicalCounter, self).__init__(0, None) self.stopped = False self.default_class = default_class #super(MechanicalCounter, self).__setattr__("train", None) #super(MechanicalCounter, self).__setattr__("invert_count", None) #super(MechanicalCounter, self).__setattr__("order", None) self._train = None self._invert_count = None self._order = None self.master = None self.config(values, invert_count, invert_order, order) @property def state(self): return self.get_state_train() # self.master.set_state @property def max_state(self): return self.get_max_state_train() @property def train(self): return self._train @train.setter def train(self, value): self.config(values=value) @train.deleter def train(self): self._train = None @property def invert_count(self): return self._invert_count @invert_count.setter def invert_count(self, value): self.config(invert_count=value) @invert_count.deleter def invert_count(self): self._invert_count = None @property def order(self): return self._order @order.setter def order(self, value): self.config(order=value) @order.deleter def order(self): self._order = None ## CONTROL METHODS ## def config( self, values=None, invert_count=None, invert_order=False, order=None): """ Safely configure MechanicalCounter instance values :param values: list of maximum states (excluded) or default_class objects inherited from counter :param invert_count: Default is False that begins to increase counters, else decrease counters :param invert_order: if True, take inverted values from order :param order: index order from Train of counters :param default_class: default class of any object to convert from values. """ tolink = False # FOR TRAIN if values is not None: if not isinstance(values, list): values = list(values) if self.train != values: #super(MechanicalCounter, self).__setattr__("train", values) self._train = values tolink = True # FOR ORDER l = len(self.train) if order is not None: # replace old order assert l == len(order), "train and order lengths are different" if self.order != order: cmp1, cmp2 = 0, 0 for i, j in enumerate(order): cmp1 += i cmp2 += j assert cmp1 == cmp2, "incomplete order" #super(MechanicalCounter, self).__setattr__("order", order) self._order = order tolink = True if self.order is None: # if order is None then use generic #super(MechanicalCounter, self).__setattr__("order", list(range(l))) self._order = list(range(l)) tolink = True if invert_order: order = self.order for i, item in enumerate(order[::-1]): order[i] = item tolink = True # FOR COUNTING if invert_count is not None and self.invert_count != invert_count: # set decreasing #super(MechanicalCounter, self).__setattr__("invert_count", invert_count) self._invert_count = invert_count tolink = True if tolink: self.link() def link(self): """ Linker method to link counters in the train so that increasing and decreasing methods affect all the counters in the due order. """ # print("linking...") order = self.order trainl = self.train for i, link in enumerate(order): item = trainl[link] if not isinstance(item, self.default_class): item = self.default_class(item) trainl[link] = item item.child = None item.parent = None if i > 0: trainl[order[i - 1]].set_child(item) #super(MechanicalCounter, self).__setattr__("master", trainl[order.index(0)]) self.master = trainl[order.index(0)] self.count = None # self.reset() def invert_real_order(self): """ Counters in Train are repositioned so that last counter takes first place and vice-versa. :return: master counter of actual counter trainl """ trainl = self.train for i, item in enumerate(trainl[::-1]): trainl[i] = item self.link() def invert_ranks(self): """ Counters hierarchy in Train are repositioned so that last counter takes first this.Order and vice-versa. :return: master counter of actual counter train ..Note:: Same as self.invert_link_order() but self.invert_ranks() does not touch the links but the real positions """ #super(MechanicalCounter, self).__setattr__("master", self.master.invert_ranks()) self.master = self.master.invert_ranks() order = self.order for i, item in enumerate(order[::-1]): order[i] = item def invert_link_order(self): """ Counters hierarchy in Train are repositioned so that last counter takes first this.Order and vice-versa. :return: master counter of actual counter train ..Note: Same as self.invert_ranks() """ self.config(invert_order=True) # reseting functions # def reset(self): """ Resets itself and children. :return: None """ return self.master.reset() # reseting functions # def reset_children(self): """ Resets itself and children. :return: None """ return self.master.reset_children() ## COUNTING METHODS ## def increase(self): """ Increases counter Train state. :return: None, use getting methods to know new states """ return self.master.increase() def decrease(self): """ Decreases counter Train state. :return: None, use getting methods to know new states """ return self.master.decrease() def increase_confirm(self): """ Increases counter Train state and confirms when get_max_state() is depleted. That is when counters overall state change from get_max_state()-1 to self.min_state. :return: True if confirmation otherwise None, use getting methods to know new states """ return self.master.increase_confirm() def decrease_confirm(self): """ Decreases counter Train state and confirms when get_max_state() is depleted. That is when counters overall state change from self.min_state to get_max_state()-1. :return: True if confirmation otherwise None, use getting methods to know new states """ return self.master.decrease_confirm() def confirm(self): """ Confirm whether in next count states are truncated """ return self.master.confirm() ## SETTING METHODS ## def set_state_train(self, values): """ Sets safely a counter state train. :param values: new train of states (list). If value exceeds max_state then value takes max_state-1 or if value is less than self.min_state it takes self.min_state :return: None """ return self.master.set_state_train(values) def set_max_state_train(self, values): """ Sets safely a counter max_state train. :param value: new train of max_state(list). If state exceeds max_state then state takes max_state-1 :return: None """ return self.master.set_max_state_train(values) def set_this_max_state(self, value): """ Sets safely this counter max_state. :param value: new max_state. If state exceeds max_state then state takes max_state-1 :return: None """ return self.master.set_this_max_state(value) def set_this_state(self, value): """ Sets safely this counter state. :param value: new value state. If value exceeds max_state then value takes max_state-1 or if value is less than 0 it takes 0 :return: None """ return self.master.set_this_state(value) def set_state(self, state, truncate=True, train=None): """ Sets safely this and all counters state train from the overall state. :param state: overall state :param truncate: it is by default True. If True it calculates the states as if in a for loop:: for i in xrange(state): this.increase() return this.get_state() If False it just stops to the last possible state before this.get_max_state() :param train: previously calculated train if this counter is not master ex: if this and master counters maxStates are T and M then extract the trains using get_max_state_train from both this and master, so that master elements reach until previous counter of this counter [M,10, ...,T-1]. Similarly, get_max_state method can be used as [master.get_max_state()/this.get_max_state()] :return: reached_overall_state :: if truncate == True: assert reached_overall_state == state % a.get_max_state() else: remaining = state - reached_overall_state """ return self.master.set_state(state, truncate, train) ## REQUESTING METHODS ## def get_state(self, train=None): """ Get overall state of train. :param train: :return: overall state """ return self.master.get_state(train) def get_state_train(self, train=None): """ All states or state train. :param train: list containing parent states :return: list of state from itself and children """ return self.master.get_state_train(train) def get_real_state_train(self): """ All states or state train. :return: list of state from itself and children """ return [i.state for i in self.train] def get_max_state(self, train=None): """ Get the overall maximum state of train. :param train: list containing parent maximum states :return: overall maximum state. Note: maximum state is never reached but this.get_max_state()-1 """ return self.master.get_max_state(train) def get_max_state_train(self, train=None): """ Get each max_state of train. :param train: list containing max_state of parents :return: list of max_state from itself and children """ return self.master.get_max_state_train(train) def get_real_max_state_train(self): """ Get each max_state of train. :return: list of max_state from itself and children """ return [i.max_state for i in self.train] def get_counter_train(self, train=None): """ Get each instance of train virtually organized. :param train: list containing instances of parents :return: list of instances from itself and children """ return self.master.get_counter_train(train) def yield_counter_train(self): """ Yield each instance of train virtually organized. :return: generator of instances from itself and children """ return self.master.yield_counter_train() def get_real_counter_train(self): """ Get each instance of train physically organized. :return: list of instances from itself and children """ return self.train ## OTHER METHODS ## def __next__(self): super(MechanicalCounter, self).__next__() return self.get_real_state_train() next = __next__ # compatibility with python 2 def __bool__(self): """ If any state is True it returns True, else False if all states are False """ for item in self.train: if not bool(item): return False return True __nonzero__ = __bool__ # compatibility with python 2 class Bit(DigitCounter): """ Simulates a bit counter from 0 to 1 """ def __init__( self, state=1, name=None, description=None, child=None, parent=None): """ :param state: :param name: :param description: :param child: :param parent: """ super(Bit, self).__init__(2, child, parent) self.name = name self.state = state self.description = description @property def max_state(self): raise VariableNotGettable() @max_state.setter def max_state(self, value): raise VariableNotSettable() @max_state.deleter def max_state(self): raise VariableNotDeletable() class Bitstream(MechanicalCounter): """ Simulates a bitstream of data example:: a = Bitstream([1,1,1]) for i in a: print(i) """ def __init__( self, stream, invert_count=False, invert_order=False, order=None, default_class=Bit): """ :param stream: list of Bits or default_class objects inherited from Bit :param invert_count: Default is False that begins to increase Bitstream, else decrease Bitstream :param invert_order: if True, take inverted Bits from order list :param order: index order from Train of Bits :param default_class: default class of any object to convert from stream """ if isinstance(stream, Number): stream = [default_class() for _ in range(stream)] super( Bitstream, self).__init__( stream, invert_count, invert_order, order, default_class=Bit)
b539b62442ce0f87853c3d7e35b7a381d50a34d7
JasonWorger/QAC_Challenges
/string_gen.py
191
3.5625
4
import random import string def string_gen(): letters = string.ascii_lowercase result = "".join(random.choice(letters) for i in range(5)) return result print(string_gen())
cb6649378c6fe71e046143947e630b64f89e73b3
damienwmartin/MetaLearning2020
/Rebel/games/othello.py
15,048
4.125
4
''' Implementation of Othello. Adapted from https://github.com/suragnair/alpha-zero-general/blob/master/othello Game representation: 2 players, Black (id=0) and White (id=1). Black plays first. Game board is represented by a square 2D np.array corresponding to the rows and columns of a physical othello board. In outputs, a black piece is represented by 'X' and a white piece is represented by 'O'. Because this is a perfect information game, the public belief state is the same as player's private beliefs, and hold total information about the game state. game_states are a np.array of size (1, board_size*board_size+1) The first board_size*board_size entries corresponds to an unraveled board output. blank space is represented with a 0 black piece is represented with a -1 white piece is represented with a 1 The extra 1 entry denotes which player gets to play the next piece (int) -1 for Black, 1 for White Action space is represented by np.array of size (1, board_size*board_size+1) the first board_size*board_size entries correspend to placing piece at that cell. The extra entry is for 'pass', when no valid moves are available this turn Reward for each player is how many pieces of their own color they have placed on the board. ''' import numpy as np class OthelloBoard(): ''' Represents an othello board. board_size (int): game board size is board_size rows by board_size columns. board_size must be an even number >= 4. boards are indexed [row][col], unlike the original AlphaZero implementation. ''' __directions = [(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1)] def __init__(self, board_size=4): #check inputs assert board_size%2==0, 'board_size must be an even integer.' assert board_size>=4, 'board_size must be >= 4.' self.n = board_size # Create the empty board array. self.pieces = [[0]*board_size for _ in range(board_size)] # Set up the initial 4 pieces. self.pieces[int(self.n/2)-1][int(self.n/2)] = -1 self.pieces[int(self.n/2)][int(self.n/2)-1] = -1 self.pieces[int(self.n/2)-1][int(self.n/2)-1] = 1 self.pieces[int(self.n/2)][int(self.n/2)] = 1 def countDiff(self, color): """ Counts the difference between # pieces of the given color color (int): 1 for white, -1 for black """ count = 0 for y in range(self.n): for x in range(self.n): if self[x][y]==color: count += 1 if self[x][y]==-color: count -= 1 return count # add [][] indexer syntax to the Board def __getitem__(self, index): return self.pieces[index] def get_legal_moves(self, color): """Returns all the legal moves for the given color. (1 for white, -1 for black """ moves = set() # stores the legal moves. color = max(0, color) # Get all the squares with pieces of the given color. for y in range(self.n): for x in range(self.n): if self[x][y]==color: newmoves = self.get_moves_for_square((x,y)) moves.update(newmoves) return list(moves) def has_legal_moves(self, color): for y in range(self.n): for x in range(self.n): if self[x][y]==color: newmoves = self.get_moves_for_square((x,y)) if len(newmoves)>0: return True return False def get_moves_for_square(self, square): """Returns all the legal moves that use the given square as a base. That is, if the given square is (3,4) and it contains a black piece, and (3,5) and (3,6) contain white pieces, and (3,7) is empty, one of the returned moves is (3,7) because everything from there to (3,4) is flipped. """ (x,y) = square # determine the color of the piece. color = self[x][y] # skip empty source squares. if color==0: return [] # search all possible directions. moves = [] for direction in self.__directions: move = self._discover_move(square, direction) if move: # print(square,move,direction) moves.append(move) # return the generated move list return moves def execute_move(self, move, color): """Perform the given move on the board; flips pieces as necessary. color gives the color pf the piece to play (1=white,-1=black) """ #Much like move generation, start at the new piece's square and #follow it on all 8 directions to look for a piece allowing flipping. # Add the piece to the empty square. # print(move) flips = [flip for direction in self.__directions for flip in self._get_flips(move, direction, color)] assert len(list(flips))>0 for x, y in flips: #print(self[x][y],color) self[x][y] = color def _discover_move(self, origin, direction): """ Returns the endpoint for a legal move, starting at the given origin, moving by the given increment.""" x, y = origin color = self[x][y] flips = [] for x, y in OthelloBoard._increment_move(origin, direction, self.n): if self[x][y] == 0: if flips: # print("Found", x,y) return (x, y) else: return None elif self[x][y] == color: return None elif self[x][y] == -color: # print("Flip",x,y) flips.append((x, y)) def _get_flips(self, origin, direction, color): """ Gets the list of flips for a vertex and direction to use with the execute_move function """ #initialize variables flips = [origin] for x, y in OthelloBoard._increment_move(origin, direction, self.n): #print(x,y) if self[x][y] == 0: return [] if self[x][y] == -color: flips.append((x, y)) elif self[x][y] == color and len(flips) > 0: #print(flips) return flips return [] @staticmethod def _increment_move(move, direction, n): # print(move) """ Generator expression for incrementing moves """ move = list(map(sum, zip(move, direction))) #move = (move[0]+direction[0], move[1]+direction[1]) while all(map(lambda x: 0 <= x < n, move)): #while 0<=move[0] and move[0]<n and 0<=move[1] and move[1]<n: yield move move=list(map(sum,zip(move,direction))) #move = (move[0]+direction[0],move[1]+direction[1]) class OthelloGame(): square_content = { -1: "X", +0: "-", +1: "O" } @staticmethod def getSquarePiece(piece): return OthelloGame.square_content[piece] def __init__(self, n): self.n = n def getInitBoard(self): # return initial board (numpy board) b = OthelloBoard(self.n) return np.array(b.pieces) def getBoardSize(self): # (a,b) tuple return (self.n, self.n) def getActionSize(self): # return number of actions return self.n*self.n + 1 def getNextState(self, board, player, action): # if player takes action on board, return next (board,player) # action must be a valid move if action == self.n*self.n: return (board, -player) b = OthelloBoard(self.n) b.pieces = np.copy(board) move = (int(action/self.n), action%self.n) b.execute_move(move, player) return (b.pieces, -player) def getValidMoves(self, board, player): # return a fixed size binary vector valids = [0]*self.getActionSize() b = OthelloBoard(self.n) b.pieces = np.copy(board) legalMoves = b.get_legal_moves(player) if len(legalMoves)==0: valids[-1]=1 return np.array(valids) for x, y in legalMoves: valids[self.n*x+y]=1 return np.array(valids) def getGameEnded(self, board, player): # return 0 if not ended, 1 if player 1 won, -1 if player 1 lost # player = 1 b = OthelloBoard(self.n) b.pieces = np.copy(board.pieces) if b.has_legal_moves(player): return 0 if b.has_legal_moves(-player): return 0 if b.countDiff(player) > 0: return 1 return -1 def getCanonicalForm(self, board, player): # return state if player==1, else return -state if player==-1 return player*board def getSymmetries(self, board, pi): # mirror, rotational assert(len(pi) == self.n**2+1) # 1 for pass pi_board = np.reshape(pi[:-1], (self.n, self.n)) l = [] for i in range(1, 5): for j in [True, False]: newB = np.rot90(board, i) newPi = np.rot90(pi_board, i) if j: newB = np.fliplr(newB) newPi = np.fliplr(newPi) l += [(newB, list(newPi.ravel()) + [pi[-1]])] return l def stringRepresentation(self, board): return board.tostring() def stringRepresentationReadable(self, board): board_s = "".join(self.square_content[square] for row in board for square in row) return board_s def getScore(self, board, player): b = OthelloBoard(self.n) b.pieces = np.copy(board) return b.countDiff(player) @staticmethod def display(board): n = board.shape[0] print(" ", end="") for y in range(n): print(y, end=" ") print("") print("-----------------------") for y in range(n): print(y, "|", end="") # print the row # for x in range(n): piece = board[y][x] # get the piece to print print(OthelloGame.square_content[piece], end=" ") print("|") print("-----------------------") class Othello(): ''' wrapper for othello functions to interface with our rebel implementations. Each node refers to a node of the game tree, represented as a tuple of ('root', action1, action2, action3, ..., 1 or -1) last 1 or -1 corresponds to which player goes next. Each action is an integer corresponding to the unraveled index of the square a piece was placed at. thus, action space is size (board_size*board_size + 1), with action board_size*board_size+1 corresponding to 'pass' ''' def __init__(self, board_size=6): self.game = OthelloGame(n=board_size) self.board_size = board_size self.board = self.game.getInitBoard() #required by rebel implementations self.num_actions = board_size*board_size+1 self.num_hands = 1 #perfect information, so only one infostate def move_to_actionID(self, move): ''' Returns actionID corresponding to placing a piece at a given row, col move: (row, col) of square to get actionID of. ''' row, col = move return self.board_size*row + col def actionID_to_move(self, action): ''' Returns the row, col corresponding to a given actionID action (int): actionID to convert ''' return (int(action/self.board_size), action%self.board_size) def node_to_board(self, node): ''' Gets the board corresponding to the histories of actions in node. ''' player = 1 board = OthelloBoard(self.board_size) if node == ('root',): return board #add pieces for each action after root for action in node[1:-1]: move = actionID_to_move(action) board.execute_move(move, player) player = -player return board def get_legal_moves(self, node): ''' get list of valid next actionIDs, given the current node ''' player = self.get_current_player(node) board = self.node_to_board(node) valid_moves = board.get_legal_moves(player) legal_actions = [self.move_to_actionID(move) for move in valid_moves] return legal_actions def get_current_player(self, node): ''' Return player who plays next, given a node ''' if len(node)%2==0: return 0 #white goes on even turns else: return 1 #black goes first at root def node_to_state(self, node): ''' Returns (last action ID, current player) Required by rebel implementation ''' player = self.get_current_player(node) last_action = node[-1] return (last_action, player) def get_rewards(self, terminal_node, traverser): ''' Returns rewards for each player (black, white) given a terminal node Currently reward is difference between number of pieces ''' board = self.node_to_board(terminal_node) white_reward = board.countDiff(1) if traverser == 0: white_reward *= -1 return (white_reward) def is_terminal(self, node): ''' Converts PBS into a readable game state ''' player = self.get_current_player(node) board = self.node_to_board(node) return self.game.getGameEnded(board, player) def get_initial_beliefs(self): ''' Required by rebel implementation. Because othello is perfect information game, there's only one possible 'hand' ''' return np.array([[1.],[1.]]) def take_action(game_state, action): ''' Returns next public state Required by rebel implementation. Because othello is perfect information game, there's only one possible 'hand' ''' return np.array([1]) def sample_hands(self): ''' Required xy rebel implementation. Because othello is perfect information game, there's only one possible 'hand' ''' return 0 @staticmethod def display_board(self): raise NotImplementedError #TODO: make board output prettier ### Testing functions ''' +---+ - + - + | X | O | | +-+-+-+ |X|O| | +-+-+-+ '''
09cf7b81f7c617ef5dac40eafa6d710a44db0c0e
santoshdurgam/DataStructures
/bst.py
1,768
4.09375
4
class node: def __init__(self, value): self.value = value self.left = None self.right = None class binary_search_tree: def __init__(self): self.root = None def insert(self, value): if self.root == None: self.root = node(value) else: self._insert(value, self.root) def _insert(self, value, cur_node): if value < cur_node.value: if cur_node.left ==None: cur_node.left = node(value) else: self._insert(value, cur_node.left) elif value > cur_node.value: if cur_node.right == None: cur_node.right = node(value) else: self._insert(value, cur_node.right) else: print ("Value already in tree") def print_tree(self): if self.root!= None: self._print_tree(self.root) def _print_tree(self, cur_node): if cur_node != None: self._print_tree(cur_node.left) print str(cur_node.value) self._print_tree(cur_node.right) def height(self): if self.root == None: return self._height(self.root, 0) else: return 0 def _height(self, cur_node, cur_height): if cur_node == None: return cur_height left_height = self._height(cur_node.left, cur_height + 1) right_height = self._height(cur_node.right, cur_height + 1) return max(left_height, right_height) tree = binary_search_tree() tree.insert(10) tree.insert(5) tree.insert(15) tree.insert(12) tree.insert(18) tree.insert(200) tree.print_tree() print(tree.height())
780f79f1fca5c5d9e6cf5c9a34989daa1380d01f
Amad1704/lessson1
/answers.py
278
3.703125
4
answers={"привет": "И тебе привет!", "как дела": "Лучше всех", "пока": "Увидимся"} def get_answer(question, answer = answers): question=question.lower() print(answer[question]) question = input() print(get_answer(question))
405b6a62bc0a4326c0201b5d4e795bb2c454711d
MrDrewShep/advent_of_code_2019
/01/puzzle.py
998
3.875
4
# PART ONE # What is the sum of the fuel requirements for all of the modules on your # spacecraft? with open("data.txt") as f: data = f.readlines() data = [i.strip("\n") for i in data] def calc_fuel(module_mass): """Takes in mass of a module and returns the amount of fuel required to launch it""" return (int(module_mass) // 3) -2 total_fuel = 0 for module in data: total_fuel += calc_fuel(module) print(total_fuel) #PART TWO # What is the sum of the fuel requirements for all of the modules on your # spacecraft when also taking into account the mass of the added fuel? def calc_fuel_2(module_mass): """Takes in the mass of a module and returns a recursively derrived amount of fuel required to launch it, and launch the fuel itself""" fuel_req = (int(module_mass) // 3) - 2 if fuel_req < 0: return 0 return fuel_req + calc_fuel_2(fuel_req) total_fuel = 0 for module in data: total_fuel += calc_fuel_2(module) print(total_fuel)
c4d61d1c2fee32068f4d37251ad68ea52004a95e
sedeeki/Numerical-Methods
/Bisection_Newton_QuasiNewton.py
5,780
3.796875
4
import numpy as np import math #---------------------------------------------------- def bisection(f, x1, x2, tol=1e-14, itmax=200, SHOW=False): """ find a solution of f(x)=0 on the interval [x1,x2] by the bisection method. return the results in a tuple (x, k, f(x)), where x is the root, k is the number of iterations. """ if SHOW: print("\n-------- bisection ------------") if f(x1) * f(x2) > 0: print("Out of bound values") return x1, 0, f(x1) xm = x1 for i in range(itmax): xm = (x1+x2)/2 if(x2-x1 <= tol): break if (f(xm) == 0.0): break if (f(xm) * f(x1) < 0): x2 = xm else: x1 = xm print("k = " + str(i) + " x = " + str(xm) + " f(x) = " + str(f(xm))) return xm, i, f(xm) def newton(f, fderivative, x, tol=1e-14, itmax=100, SHOW=False): """ Newton's method, starting from an initial estimate x of the root, """ if SHOW: print("\n-------- Newton's method ------------") for i in range(itmax): x -= f(x) / fderivative(x) if((f(x) / fderivative(x)) <= tol): break print("k = " + str(i) + " x = " + str(x) + " f(x) = " + str(f(x))) return x, i, f(x) def quasi_newton(f, x, h=1e-4, tol=1.0e-14, FD='CFD', itmax=120, SHOW=False): """ Quasi Newton's method, starting from an initial value x. The derivative is automatically computed via numerical differentiation, it defaults to using central finite difference scheme. The default for the grid length used for FD is h=1e-4. """ if SHOW: print("\n-------- Quasi Newton's method, FD scheme ={} ------------".format(FD)) fder = 1 if(FD == 'FFD'): fder = f(x+h) - f(x) elif(FD == 'BFD'): fder = f(x) - f(x-h) else: fder = f(x+(h/2)) - f(x-(h/2)) h1 = f(x) / fder for i in range(itmax): if(abs(h1) <= tol): break if(FD == 'FFD'): fder = f(x+h) - f(x) elif(FD == 'BFD'): fder = f(x) - f(x-h) else: fder = f(x+(h/2)) - f(x-(h/2)) h1 = f(x) / fder x -= h1 print("k = " + str(i) + " x = " + str(x) + " f(x) = " + str(f(x))) return x, i, f(x) def solver_tests(): #f1(x) = x^9 - 8x^6 + 5x + 10 #define this function using variable name f1 (try to use lambda function for all problems here) f1 = lambda x: math.pow(x,9) - 8*math.pow(x,6) + 5*x + 10 #add code to call bisection to solve f1(x)=0 on [-1, 1] (x, k, fx) = bisection(f1, -1, 1) print('\n By bisection: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call newton to solve f1(x)=0, set initial root as -1 #you need to manually get the derivative of f1, pass it as a function named f1der f1der = lambda x: 9*math.pow(x,8)- 48*math.pow(x,5) + 5 (x, k, fx) = newton(f1, f1der, -1) print('\n By Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call quasi_newton to solve f1(x)=0, set initial root as -1 (x, k, fx) = quasi_newton(f1, -1, .5) print('\n By quasi_Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #f2(x) = (x+1)^4 - x e^(sin(x)) + 5x -8 #define this function using variable name f2 f2 = lambda x: math.pow(x+1,4) - x * math.exp(math.sin(x)) + 5*x - 8 #add code to call bisection to solve f2(x)=0 on [-3, 3] (x, k, fx) = bisection(f2, -3, 3) print('\n By bisection: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call newton to solve f2(x)=0, set initial root as 3 #you need to manually get the derivative of f1, pass it as a function named f2der f2der = lambda x: - x * math.exp(math.sin(x)) * math.cos(x) - math.exp(math.sin(x)) + 4 * math.pow(x+1,3) + 5 (x, k, fx) = newton(f2, f2der, 3) print('\n By Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call quasi_newton to solve f2(x)=0, set initial root as 3 (x, k, fx) = quasi_newton(f2, 3, .5) print('\n By quasi_Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #f3(x) = e^(-x^2) + x^3 - 100 #interestingly, for this function, the default tol lead to trouble for newton's method! #so you set tol=1e-13 instead of the default 1e-14 #define this function using variable name f3 f3 = lambda x: math.exp(math.pow(-x,2)) + math.pow(x,3) - 100 #add code to call bisection to solve f3(x)=0 on [-10, 10], call using tol=1e-13 (x, k, fx) = bisection(f3, -10, 10, tol=1.0e-13) print('\n By bisection: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call newton to solve f3(x)=0, set initial root as 10, call using tol=1e-13 #you need to manually get the derivative of f3, pass it as a function named f3der f3der = lambda x: 3 * math.pow(x,2) - 2*x*math.exp(math.pow(-x,2)) (x, k, fx) = newton(f3, f3der, 3, tol=1.0e-13) print('\n By Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call quasi_newton to solve f3(x)=0, set initial root as 10, #call using tol=1e-13, h=0.3, and FD='FFD' (x, k, fx) = quasi_newton(f2, 3, h=.3, FD='FFD', tol=1.0e-13) print('\n By quasi_Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) #add code to call quasi_newton to solve f3(x)=0, set initial root as 10, #call using tol=1e-13, h=0.3, and FD='BFD' (x, k, fx) = quasi_newton(f2, 3, h=.3, FD='BFD', tol=1.0e-13) print('\n By quasi_Newton: x={}, k={}, fx={}\n'.format(x, k, fx)) if __name__=='__main__': solver_tests()
290df5219a8f4a0ece597cb7a9d854e73f5a70f6
icasarino/Rabbit
/BinaryMethods.py
2,995
3.875
4
def rightShift(value, offset): """ Realiza un ciclo en los bits Diferencia con operador setea el primer bit con el valor del ultimo EJ: 21 -> 10101 rightShift(21,1) ==> 26 -> 11010 21 >> 1 ==> 10 -> 01010 """ numBits = value.bit_length() - 1 for i in range(0, offset): bit = value & 1 value = (value >> 1) ^ (bit << numBits) return value def leftShift(value, offset): """ Realiza un ciclo en los bits Diferencia con operador setea el último bit con el valor del primero y no agrega bits al número EJ: 21 -> 10101 leftShift(21,1) ==> 11 -> 01011 21 << 1 ==> 42 -> 101010 """ numBits = value.bit_length() - 1 mostSignificantValue = 2**(numBits + 1) for i in range(0, offset): bit = (value >> numBits) & 1 value = ((value << 1) ^ bit) - mostSignificantValue return value def swapBits(value, offset1, offset2): """ EJ: 60 -> 111100 Modificar pos = 1 con pos = 5 (Segundo bit con ultimo) bit1 = 000001 bit2 = 000000 x (XOR) = 000001 x (OR) = 000001 | 010000 -> 010001 value (XOR) = 111100 ^ 010001 = 101101 -> 45 """ bit1 = (value >> offset1) & 1 # Mueve el bit a resposicionar al lugar del menos significativo AND 1 ==> Resultado 001 o 000 bit2 = (value >> offset2) & 1 # Mueve el bit a resposicionar al lugar del menos significativo AND 1 ==> Resultado 001 o 000 x = bit1 ^ bit2 # XOR entre los dos bits ==> Res 000 o 001 x = (x << offset1) | (x << offset2) # Resposiciona el bit menos significativo return value ^ x # XOR del valor con el reposicionamiento def invertBits(value): bitCount = value.bit_length() - 1 iterations = bitCount >> 1 for i in range(0, iterations): value = swapBits(value,i, bitCount - i) while value.bit_length() < 8: value <<= 1 return value def invertBitsList(lista): return list(map(lambda x: chr(invertBits(ord(x))), lista)) def even(valor): """ & (AND OPERATOR) 01010 (12) (valor) 00001 (1) 00000 (AND) (= 0) ==> valor & 1 === 0 ==> EVEN 01011 (13) (valor) 00001 (1) 00001 (AND) (= 1) ==> valor & 1 === 1 ==> ODD """ return (valor & 1) == 0 def set16bits(value): while value.bit_length() < 16: value <<= 1 return value def set32bits(value): while value.bit_length() < 32: value <<= 1 return value def set64bits(value): while value.bit_length() < 64: value <<= 1 return value def set128bits(value): while value.bit_length() < 128: value <<= 1 return value def MSB(value): MSWbitLen = value.bit_length() >> 1 return value >> MSWbitLen def LSB(value): LSWbitLen = value.bit_length() >> 1 return rightShift(value,LSWbitLen) >> LSWbitLen
fff0498b02beda34d7ba14d5d54e41a7e3a0a27f
FireFox5/FireMonkey-
/First Month/forth lesson 05.07.2021/lesson 4.1.py
177
3.921875
4
#for i in range(10): # print("hello",i) # for k in range(10): # print("hello from USA",k) for q in range(5): name=input(f"you {q} in qoute") print(name)
c9170c803dd94206f248af59fff8f268f766320d
FireFox5/FireMonkey-
/First Month/second lesson 28.06.2021/lesson 2.3.py
227
3.734375
4
age=float(input("your age "))+20.2 print(age) print(type(age)) currency=84.5+0.228+1 print(currency) print(currency) print(int(float(str(currency)))) is_sunny=True is_rainy=False print(type(is_rainy)) print(type(is_sunny))
3edf18972bd8e0d4655a71b0bd87741e1ce00587
FireFox5/FireMonkey-
/First Month/second lesson 28.06.2021/lesson 2.py
118
3.546875
4
name="sultan " print(name) years=20+1/(2*2)-1 years2="20"+"20" years3="20"*4 print(years) print(years2) print(years3)
49e2dc5e5c63205c941f9b8bef6147fb6d5f4586
FireFox5/FireMonkey-
/First Month/second lesson 28.06.2021/lesson2.2.py
182
3.5625
4
name="abc" name2=input() age=input()+20 age2=99.2 print(name2) print(type(name2)) print(name2) print(age) #print(type(age2)) #print(type(age)) #print(type(name)) #print(type(name2))
b140bc588000d49c057e4d954a9ff303997bd942
cristiano-corrado/ipconverter
/ipconverter.py
3,588
3.6875
4
#!/usr/bin/python import os import sys import re import struct import datetime from socket import inet_aton #define list where to add ip addresses. listIP=[] #identify a unique per day file. not great but no waste of time today=datetime.datetime.today() finalFile=str(today.date())+"-ipfile-sanitised.txt" #Validation for correct IP evaluation def validateIP(ip): ValidIpAddressRegex = re.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$") if ValidIpAddressRegex.search(ip): return True else: print "[ERROR] - During the processing we found that the current %s, was in incorrect format. Please review." % (ip) return False #If , or space or - in line remove and set IP on newline def evaluateBadStrings(line): if "-" or "," in line: stripper=[x for x in re.split(r"-|,| ",line) if x != ''] for elem in stripper: return stripper else: return line #Sort ip address from 1.1.1.1 to 255.255.255.255 def sort_ip_list(ip_list): return sorted(ip_list, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0]) #Main Function to read from file and print if __name__ == "__main__": # give user option to decide what separator to use to write the list: try : userInput = raw_input("what is the separator you would like to add to list? (Eg: comma \",\" newline \""+str(chr(92))+"n\": ") comma=("comma",",") newline=("newline","\\n") if any(s in userInput for s in comma): userInput = "," print "Your selection is: ", userInput elif any(s in userInput for s in newline): userInput = '\n' print "Your selection is: newline" else: userInput = userInput.lower() print "Your selection is: ", userInput.lower() # If error will be user forgot to specify arg 1 as file try : if os.path.isfile(sys.argv[1]): readFile=open(sys.argv[1],"r").readlines() for elem in readFile: # Remove blank line if elem.rstrip(): # Evaluate - , " " in line passed for ip in evaluateBadStrings(elem.rstrip()): # If the IP matches regex if validateIP(ip): # Put in a list listIP.append(ip) else: print "Provide a file with a list of ip in it. Eg: python %s ipfile.txt" % sys.argv[0] except Exception, e: print "Provide a file with a list of ip in it. Eg: python %s ipfile.txt" % sys.argv[0] # Always remove if same file. We don't care. if os.path.isfile(finalFile): os.remove(finalFile) # Write list of IPs writeFinal=open(finalFile,"a") for ipsort in sort_ip_list(set(listIP)): writeFinal.write(ipsort+userInput) writeFinal.close() #Print some fancy stats print "The list has %d number of ip addresses." % len(listIP) print "The list has been cleared from duplicates and the current amount is: %d" % len(sort_ip_list(set(listIP))) print "The sanitised list of ip address has been written to:", finalFile #IF we press CTRL+C at any time we exit, byebye. except KeyboardInterrupt,e: print "\nYou pressed CTRL+C, exiting."
cc704a0b6eac68caae0a3f42c9eeb416ddd87add
sgriffith3/python_basics_9-14-2020
/larnin_funcs.py
467
3.890625
4
# Learning Functions # printing x + 33 def func1(): print(33) func1() print("Let's do that again!") func1() def func2(x): print(x + 33) func2(99) func2(1099) def func3(y, z): print(y * z) func3(3, 4) def func4(a, b, c): print(a - (b + c)) return a - (b + c) def main(): answer1 = func4(10, 3, 2) answer2 = func4(100, 20, 3) answer3 = func4(1000, answer1, answer2) print(f"The final answer is: {answer3}") main()
5b9d02e8b3b62588d1de662ef4321b20097c8f10
sgriffith3/python_basics_9-14-2020
/pet_list_challenge.py
843
4.125
4
#Tuesday Morning Challenge: #Start with this list of pets: pets = ['fido', 'spot', 'fluffy'] #Use the input() function three times to gather names of three more pets. pet1 = input("pet 1 name: ") pet2 = input("pet 2 name: ") pet3 = input("pet 3 name: ") #Add each of these new pet names to the pets list. pets.append(pet1) pets.insert(1, pet2) pets = pets + [pet3] #print(pets) #print(enumerate(pets)) #for ind, val in enumerate(pets): # print(ind, val) #Using the pets list, print each out, along with their index. # #The output should look like: # #0 fido #1 spot #2 fluffy print(0, pets[0]) print(1, pets[1]) print(2, pets[2]) print(3, pets[3]) print(4, pets[4]) print(5, pets[5]) counter = 0 for pet in pets: print(counter, pet) counter += 1 # counter = counter + 1 for pe in pets: print(pets.index(pe), pe)
f9cffb3f8d8587963a8c819e63bfccc4a152e639
pinkfluffy855/pendulum
/section3.py
2,730
3.71875
4
""" A stationary damped pendulum For fun. """ import numpy as np import matplotlib.pyplot as plt import pendulum ### Pendulum swings with amplitude smaller than $4 v_c$ #We assume a pendulum length of 20 m and a trolley speed of vc = 1 m/s. The load needs to be transported by 6 m, hence deltat= 3 s. #The initial speed of the pendulum is v0 = 1 m/s # `tau` is calculated according to eq. 25 in the paper. After that value is otained, t1 according to eq. 22 l = 20 g = 9.807 w0 =np.sqrt(g/l) T0 = 2*np.pi/w0 vt = 1 deltat = 3 v0 = 1 tau=T0/np.pi*np.arccos(v0/(-4*vt*np.sin(w0*deltat*0.5))) t1 = T0/4-tau/2-deltat/2 while t1<0: t1=t1+T0/2 t1= t1+T0 # You can delete this line, I just like to observe the pendulum for a period print('tau = {0:6.1f}'.format(tau)) print('t1= {0:6.1f}'.format(t1)) tl1 = [0,t1,t1+deltat,t1+tau,t1+tau+deltat] #times when a change in velocity happens vl1 = [0,vt,0 ,vt ,0] #the velocity it changes to at that time move1 = pendulum.const_vel(tl1,vl1) pend1 = pendulum.simplependulum(x0=0,v0=v0,w0=w0,xi=0.0,trolley_pos=move1.xc) pend1.go(24) fig, ax = plt.subplots(2,sharex=True) ax[0].plot(pend1.out_t,pend1.out_vm,'b-') ax[0].plot(pend1.out_t,pend1.out_vc,'r:') ax[1].plot(pend1.out_t,pend1.out_xm,'b-') ax[1].plot(pend1.out_t,pend1.out_xc,'r:') ax[1].set_xlabel('t/s') ax[0].set_ylabel('v/(m/s)') ax[1].set_ylabel('x/m') fig.show() print("Figure 1: Damping a pendulum with v0<4vc") ## Pendulum swings with amplitude larger than 4 vc #We assume a pendulum length of 20 m and a trolley speed of vc = 1 m/s. The load needs to be transported by 6 m, hence deltat= 3 s. #The initial speed of the pendulum is v0 = 5 m/s #tau is 2*T0. With this value, t1 is calculated according to eq. 22 l = 20 g = 9.807 w0 =np.sqrt(g/l) T0 = 2*np.pi/w0 vt = 1 deltat = 3 v0 = 5 tau=T0*2 t1 = T0/4-tau/2-deltat/2 while t1<0: t1=t1+T0/2 t1= t1+T0 # You can delete this line, I just like to observe the pendulum for a period print('tau = {0:6.1f}'.format(tau)) print('t1= {0:6.1f}'.format(t1)) tl2 = [0,t1,t1+deltat,t1+tau,t1+tau+deltat] #times when a change in velocity happens vl2 = [0,vt,0 ,vt ,0] #the velocity it changes to at that time move2 = pendulum.const_vel(tl2,vl2) pend2 = pendulum.simplependulum(x0=0,v0=v0,w0=w0,xi=0.0,trolley_pos=move2.xc) pend2.go(40) fig, ax = plt.subplots(2,sharex=True) ax[0].plot(pend2.out_t,pend2.out_vm,'b-') ax[0].plot(pend2.out_t,pend2.out_vc,'r:') ax[1].plot(pend2.out_t,pend2.out_xm,'b-') ax[1].plot(pend2.out_t,pend2.out_xc,'r:') ax[1].set_xlabel('t/s') ax[0].set_ylabel('v/(m/s)') ax[1].set_ylabel('x/m') fig.show() print("Figure 1: Damping a pendulum with v0>4vc") print("Press Enter to quit") input()
26afeab27e2cc0dc55d045b0179b17780ecea344
randalong/PyTorchZeroToAll
/2_linear_model.py
499
3.625
4
import numpy as np import matplotlib.pyplot as plt x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] w = 1 def forward(x): return x * w def loss(x,y): y_pred = forward(x) return (y_pred-y)**2 w_list = [] mse_list = [] for w in np.arange(0.0, 4.0, 0.1): loss_sum = 0 for x_val, y_val in zip(x_data, y_data): loss_sum += loss(x_val, y_val) w_list.append(w) mse_list.append(loss_sum/3) plt.plot(w_list, mse_list) plt.xlabel('w') plt.ylabel('loss') plt.show()
ff0c5c38ca1e0d2b8cba59966bfea5cd7a743fc8
PavlovAlx/repoGeekBrains
/dz5.py
516
4.3125
4
string1 = int(input("введите выручку")) string2 = int(input("введите издержки")) if string1 >= string2: print ("вы работаете с прибылью:", string1-string2) print ("рентабельность:", string1/string2) string3 = int(input("численность сотрудников:")) print ("прибыль на сотрудника:", (string1-string2)/string3) else: print("вы работаете с убытком:", string1 - string2)
72a42c7ff9a6b490b96b19147c2db1bedb99d542
anon-cand/nexpreval
/operations/constant.py
811
3.859375
4
from operations.operation import Operation class Constant(Operation): """ Class to represent a constant """ TAG = 'default' __slots__ = 'value' def __init__(self, value = None): self.value = value def __hash__(self): return hash(self.value) def __call__(self): """ Verify and return the constant stored within the object :return: value of this object """ if self.value and isinstance(self.value, (int, float)): return self.value return self.NAN def add_operand(self, operand, _): """ Add an operand for this operation """ try: int(operand) except ValueError: raise TypeError("Operand of type int is expected") self.value = int(operand)
e92f2e8ccb173792b7be00653675a745e6c62a64
Mycodeiskuina/Among-Us-game-0.5
/Segunda_parte.py
10,402
3.890625
4
"""En mi codigo el algoritmo astar recorre una matriz de 0s y 1s, donde los 1 representan obstaculos y retorna un camino, por eso antes de poner la matriz como parametro de la funcion astar convierto la matriz en una matriz de 0s y 1s""" from math import sqrt import random #inicializamos la matriz m = [] for i in range(32): m.append([" "] * 32) def draw_canvas_empty(): """Inicializa los bordes de la cuadricula de 30*30 en la matriz principal.""" for j in range(32): m[j][0] = '| ' m[j][31] = '| ' for i in range(32): m[0][i] = '- ' m[31][i] = '- ' def dibujar(m): """Sirve para imprimir una matriz de manera ordenada. Tiene como parametro una matriz.""" for i in m: for j in i: print(j,end="") print() def ok1(x,y,a,b): """ Verifica si en donde queremos poner las paredes de un espacio las casillas estan vacias y si los alrededores de las paredes tambien estan vacias, ya que asi cumpliria que los espacios esten separados en por lo menos 1 casilla. Tiene como parametros la coordenada de donde empiezo a dibujar el espacio(rectangulo) y las dimensiones del espacio. Retorna False o True segun se cumpla lo anterior mencionado. """ ok=True if x-1<2 or y-1<2 or x+a>29 or y+b>29: ok=False else: for k in range(0,b,1): if m[x-1][y+k]!=" " or m[x+a][y+k]!=" ": ok=False for k in range(-1,a+1,1): if m[x+k][y-1]!=" " or m[x+k][y+b]!=" ": ok=False for k in range(-1,b+1,1): if m[x-2][y+k]!=" " or m[x+a+2][y+k]!=" ": ok=False for k in range(-2,a+2,1): if m[x+k][y-2]!=" " or m[x+k][y+b+1]!=" ": ok=False return ok espacios=[] def init_places(espacios): """Iniciamos las posiciones de las entradas de los espacios al mismo tiempo que generamos los espacios como rectangulos de tal manera que no se intersecten. Recibe como parametro una lista en donde guardaremos las coordenadas de las entradas de los espacios que utilizaremos luego.""" j=1 c=[] for i in range(6): uwu=True while uwu: x = random.randint(2, 28) y = random.randint(2, 28) c.append(random.randint(10,15)) for i in range(int(sqrt(c[j-1])),c[j-1]+1): if c[j-1]%i==0 and ok1(x,y,i,c[j-1]//i): for k in range(0,c[j-1]//i,1): m[x-1][y+k] = '- ' m[x+i][y+k]= '- ' for k in range(-1,i+1,1): m[x+k][y-1] = '| ' m[x+k][y+(c[j-1]//i)] = '| ' uwu=False break if uwu: c.pop() m[x-1][y] = 'E'+str(j) espacios.append((x-1,y)) j+=1 def init_players(tripulantes): """Iniciamos las posiciones de los tripulantes de manera random. Tiene como parametro una lista en donde guardaremos las coordenadas de los tripulantes que utilizaremos luego.""" t1 = [random.randint(1, 29), random.randint(1, 29)] while(m[t1[0]][t1[1]]!=" "): t1 = [random.randint(1, 29), random.randint(1, 29)] m[t1[0]][t1[1]] = "t1" tripulantes.append((t1[0],t1[1])) t2 = [random.randint(1, 29), random.randint(1, 29)] while m[t2[0]][t2[1]] != " ": t2 = [random.randint(1, 29), random.randint(1, 29)] m[t2[0]][t2[1]] = "t2" tripulantes.append((t2[0],t2[1])) t3 = [random.randint(1, 29), random.randint(1, 29)] while m[t3[0]][t3[1]] != " ": t3 = [random.randint(1, 29), random.randint(1, 29)] m[t3[0]][t3[1]] = "t3" tripulantes.append((t3[0],t3[1])) t4 = [random.randint(1, 29), random.randint(1, 29)] while m[t4[0]][t4[1]] != " ": t4 = [random.randint(1, 29), random.randint(1, 29)] m[t4[0]][t4[1]] = "t4" tripulantes.append((t4[0],t4[1])) class Node(): """Clase Node para encontrar un camino cuando utilizamos el algoritmo A*.""" def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def astar(maze, start, end): """Nos sirve para encontrar un camino desde estar hasta end, teniendo en cuenta los obstaculos. Tiene como parametros la matriz, una coodenada inicial y una coordenada final. Retorna una lista de tuplas(coordenadas) como una ruta desde el inicio hasta el final en la cuadricula.""" #Crear nodo inicial y final start_node = Node(None, start) start_node.g = start_node.h = start_node.f = 0 end_node = Node(None, end) end_node.g = end_node.h = end_node.f = 0 #Inicializar tanto la lista abierta como la cerrada open_list = [] closed_list = [] #Agregar el nodo de inicio open_list.append(start_node) #Da vueltas hasta que encuentres el final while len(open_list) > 0: #Obtener el nodo actual current_node = open_list[0] current_index = 0 for index, item in enumerate(open_list): if item.f < current_node.f: current_node = item current_index = index #Quitar actual de la lista abierta, agregar a la lista cerrada open_list.pop(current_index) closed_list.append(current_node) #Encontre la meta if current_node == end_node: path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path[::-1] #Retorna el camino inverso #Generar hijos children = [] for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: #Casilla adyacente #Obtener la posición del nodo node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1]) if Node(current_node, node_position) in closed_list: continue #Asegúrese de que esté dentro del rango if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0: continue #Asegúrese de que el terreno sea transitable if maze[node_position[0]][node_position[1]] != 0: continue #Crear nuevo nodo new_node = Node(current_node, node_position) #adjuntar children.append(new_node) #Bucle a través de los hijos for child in children: #Su hijo está en la lista cerrada for closed_child in closed_list: if child == closed_child: continue #Cree los valores de f, g y h child.g = current_node.g + 1 child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2) child.f = child.g + child.h #Su hijo ya está en la lista abierta for open_node in open_list: if child == open_node and child.g > open_node.g: continue #Agregar hijo a la lista abierta open_list.append(child) def pinta(m,m1): """Convierto m1 en una matriz de 0s y 1s segun m(matriz principal), para poder ponerlo en la funcion astar. Tiene como parametros m1 y m.""" for i in range(32): for j in range(32): if m[i][j]!=" " and m[i][j]!="X ": m1[i][j]=1 tiempo={} def te(tiempo): """Inicializamos el tiempo de espera en cada espacio de manera random.""" tiempo["E1"]=random.randint(1, 6) tiempo["E2"]=random.randint(1, 6) tiempo["E3"]=random.randint(1, 6) tiempo["E4"]=random.randint(1, 6) tiempo["E5"]=random.randint(1, 6) tiempo["E6"]=random.randint(1, 6) while True: option=input() if option=="init": m = [] for i in range(32): m.append([" "] * 32) draw_canvas_empty() X = [random.randint(1, 29), random.randint(1, 29)] m[X[0]][X[1]] = "X " x=X[0] y=X[1] tripulantes=[] espacios=[] init_places(espacios) init_players(tripulantes) dibujar(m) """Hasta aqui solo inicializa la matriz con los espacios y las posiciones de los tripulantes e impostores.""" option1=input() tdi=[] tet=[] trgi=[] if option1=="route": tiempo={} te(tiempo) for k in range(4): start=(X[0],X[1]) end=(tripulantes[k][0],tripulantes[k][1]) m1 = [] for i in range(32): m1.append([0] * 32) """convierto la matriz en 0s y 1s""" for i in range(32): for j in range(32): if m[i][j]=="| " or m[i][j]=="- ": m1[i][j]=1 if k==0 and m[i][j]=="t1": m1[i][j]=0 elif k==1 and m[i][j]=="t2": m1[i][j]=0 elif k==2 and m[i][j]=="t3": m1[i][j]=0 elif k==3 and m[i][j]=="t4": m1[i][j]=0 path=astar(m1,start,end) """Verifico si alguno de los 4 tripulantes esta dentro de algun espacio""" ok=False tmp="" if path!=None: for i in path: for j in espacios: if j==i: ok=True tmp1=j tmp=m[tmp1[0]][tmp1[1]] break """Si esta dentro de un espacio entonces hallo los tdi y tet""" if ok: tdi.append((len(path)-1)/10) tet.append(tiempo[tmp]) """Si el tripulante 1 esta dentro de un espacio -> pinto con 1s Si el tripulante 2 esta dentro de un espacio -> pinto con 2s Si el tripulante 3 esta dentro de un espacio -> pinto con 3s Si el tripulante 4 esta dentro de un espacio -> pinto con 4s Si se pasa mas de 1 vez por el mismo camino -> pinto con 0s""" for i in range(1,len(path)-1): cur=m[path[i][0]][path[i][1]] if cur==" " or cur=="E1" or cur=="E2" or cur=="E3" or cur=="E4" or cur=="E5" or cur=="E6": m[path[i][0]][path[i][1]]=str(k+1)+" " else: m[path[i][0]][path[i][1]]="0 " #Hallando los trgi n=len(tdi) for l in range(n): trgi.append(tdi[l]-tet[l]) dibujar(m) option2=input() if option2=="trgi": ans=float(-1) for i in trgi: if i<0: continue else: ans=max(ans,i) if ans==-1: print("los tripulantes siempre se escapan") else : print(ans)
78e6d0b1ce07844cbc88aab306267d882441b3df
Lt3kr/Liam_Turelid_TE19C
/Introkod_syntax/strings_uppg/Uppgift_5c.py
1,123
3.859375
4
fråga = input("kryptera eller dekryptera?: ") alfabetet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_." if fråga == "kryptera": ROTLösen = input("ROT och ditt lösen: ") seperation = ROTLösen.split(" ") ROT = int(seperation[0]) Meddelande = seperation[1].upper() resultat = "" for letter in Meddelande: PositonAvBokstav = alfabetet.index(letter) PositonAvBokstav += ROT while PositonAvBokstav > len(alfabetet) -1: PositonAvBokstav -= len(alfabetet) resultat += alfabetet[PositonAvBokstav] print(resultat[::-1]) elif fråga == "dekryptera": LösenordOchROT = input("skriv ROT nummer mellanslag Lösen: ") Seperation = LösenordOchROT.split(" ") ROTNummer = int(Seperation[0]) Lösen = Seperation[1].upper() RiktigaLösen = "" for letter in Lösen: Position = alfabetet.index(letter) Position -= ROTNummer while Position > len(alfabetet) -1: Position -= len(alfabetet) RiktigaLösen += alfabetet[Position] print(RiktigaLösen[::-1]) else: print("Endast kryptera eller dekrytera")
7ed442f350732cfdb2ef56f27542bf6fce0e1d0d
Lt3kr/Liam_Turelid_TE19C
/Introkod_syntax/Laxa2/uppg.3.py
251
3.609375
4
tal1 = float(input("Skriv ett tal så ska jag se ifall de är störst: ")) tal2 = float(input("Skriv ditt andra tal: ")) tal3 = float(input("Skriv ditt tredje tal: ")) tal4 = float(input("Skriv ditt fjärde tal: ")) print(max(tal1, tal2, tal3, tal4))
3b82e9fb01b53368c4ffbe7da95f51059072595d
Lt3kr/Liam_Turelid_TE19C
/Introkod_syntax/räkna_med_python/For läxor/For_uppg_5.py
421
3.734375
4
# uppgift 5a for f in range (11): print(f"{5*f}", end=" ") print() #uppgift 5b k = int(input("ge mig ett tal! ")) for n in range(11): print(f"{k*n}", end=" ") print() #uppgift 5c for j in range(11): #gör vad som står under 10 ggr for i in range(11): #gör samma här print(f"{i*j}", end = " ") #tar j och gångrar det med varje i för att sedan printa det print() #detta är hela uppgift 5
7ca9341e3ddc4149c16eb18561457ce179b0b348
Lt3kr/Liam_Turelid_TE19C
/Introkod_syntax/FunktionsUppgifter/Uppgift2.py
500
3.671875
4
# gör en funk som beräknar s = 1 + 3 + 5 + 7 + 9 + ... + (2n +1) Start = int(input("Skriv vad starten är: ")) - 1 n = int(input("Skriv vad du vill ha som den sista delen: ")) def Aritmetisk_summa(n): Summan = 0 for x in range(Start, n+1): Summan += (2*x + 1) return Summan print(f"den aritmetiska summan av det du har givit är {(Aritmetisk_summa(n))} vilket alltså är {Start} + {Start+1} + {Start+3}+ ... enda tills slutet vilket är {2*n + 1}") # hela uppgift 2
d9bd61933eb23e69a2c083fd98bf18ced1e4b868
Lt3kr/Liam_Turelid_TE19C
/Introkod_syntax/Labb/labb.2/uppgift2.py
103
3.6875
4
x=0 for i in range(100): x += 1 if x % 5 != 0: print(x) else: print("burr")
a61fbb95a269c1ad6ed3920988024aefbb001853
DavidLoi/DMOJ
/Uncategorized/Valentine's Day '19 J1 - Rainbow Rating.py
580
3.5625
4
users = int(input()) list = [] for i in range(users): current = int(input()) if current < 1000: list.append("Newbie") elif current < 1200: list.append("Amateur") elif current < 1500: list.append("Expert") elif current < 1800: list.append("Candidate Master") elif current < 2200: list.append("Master") elif current < 3000: list.append("Grandmaster") elif current < 4000: list.append("Target") else: list.append("Rainbow Master") for i in list: print(i)
24c0cdb43ffda5810a383015e0cccf00b3a2d103
DavidLoi/DMOJ
/Uncategorized/CPC '19 Contest 1 P1 - Distance.py
325
3.5
4
num = int(input()) path = [] if num%2 == 0: for i in range((int(num/2))): path.append(i+1) path.append(num-i) elif num % 2 == 1: for i in range(int((num-1)/2)): path.append(i+1) path.append(num-i) path.append(int(num/2) + 1) print(" ".join(str(x) for x in path))
427eb7b7767a36cf6565e6d703b786b4223f61cb
Senofjohan/breathe_and_build_cloud_infrastructure
/mouth_open_algorithm.py
1,058
3.796875
4
import math def get_lip_height(lip): sum=0 for i in [2,3,4]: # distance between two near points up and down distance = math.sqrt( (lip[i][0] - lip[12-i][0])**2 + (lip[i][1] - lip[12-i][1])**2 ) sum += distance return sum / 3 def get_mouth_height(top_lip, bottom_lip): sum=0 for i in [8,9,10]: # distance between two near points up and down distance = math.sqrt( (top_lip[i][0] - bottom_lip[18-i][0])**2 + (top_lip[i][1] - bottom_lip[18-i][1])**2 ) sum += distance return sum / 3 def check_mouth_open(top_lip, bottom_lip): top_lip_height = get_lip_height(top_lip) bottom_lip_height = get_lip_height(bottom_lip) mouth_height = get_mouth_height(top_lip, bottom_lip) # if mouth is open more than lip height * ratio, return true. ratio = 0.5 if mouth_height > min(top_lip_height, bottom_lip_height) * ratio: return True else: return False
ccd5596008603cfa9d615b5485c6ced3b42782fc
wreyesus/Python-For-Beginners---2
/0026. Automate Parsing and Renaming of Multiple Files.py
2,449
3.5
4
#Automate Parsing and Renaming of Multiple Files import os os.chdir('D:\Study\Hadoop\Python\Cory_Schafer youtube videos') print(os.getcwd()) for f in os.listdir(): #print(f) #print all file/folders of file #print(os.path.splitext(f)) #will split file name and ext file_name , file_ext = os.path.splitext(f) #print(file_name) #will print filename only #print(file_name.split('-')) #will split file name with space f_title , f_topic = file_name.split('-') #print(f_topic) f_title=f_title.strip() #removing whitespaces f_topic=f_topic.strip() file_ext=file_ext.strip() #we can use f_title.strip()[1:] to remove 1st char from f_title #Fill Zero like 01 , 02 insted of 1 ,2 #f_title.strip()[1:].zfill(2) #Reformat it again #print('{}-{}{}'.format(f_topic,f_title,file_ext)) new_name = '{}-{}{}'.format(f_topic,f_title,file_ext) os.rename(f, new_name) ''' import os os.chdir('/path/to/files/') # Am I in the correct directory? # print(os.getcwd()) # print(dir(os)) # Print all the current file names for f in os.listdir(): # If .DS_Store file is created, ignore it if f == '.DS_Store': continue file_name, file_ext = os.path.splitext(f) # print(file_name) # One way to do this f_title, f_course, f_number = file_name.split('-') # print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext)) # Need to remove whitespace f_title = f_title.strip() f_course = f_course.strip() # f_number = f_number.strip() # Want to remove the number sign? # f_number = f_number.strip()[1:] # One thing I noticed about this output is that if it was sorted by filename # then the 1 and 10 would be next to each other. How do we fix this? One way we can fix this is to pad # the numbers. So instead of 1, we'll make it 01. If we had hundreds of files then this would maybe need to be 001. # We can do this in Python with zfill f_number = f_number.strip()[1:].zfill(2) # print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext)) # You have the power to reformat in any way you see fit print('{}-{}{}'.format(f_number, f_title.strip(), file_ext.strip())) new_name = '{}-{}{}'.format(file_num, file_title, file_ext) os.rename(fn, new_name) # print(len(os.listdir())) '''
d503092c169f07e614859b581774ae27fc8c058c
wreyesus/Python-For-Beginners---2
/0020. List Comprehensions.py
2,760
4.15625
4
#Comprehensions nums = [1,2,3,4,5,6,7,8,9,10] # I want 'n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n) print(my_list) #Using List Comprihension my_list_com = [n for n in nums] print(my_list_com) ############ #I want 'n*n' for each 'n' in nums my_list1 = [] for n in nums: my_list.append(n*n) print(my_list) #Using List Comprihension my_list1_com = [n*n for n in nums] print(my_list1_com) #Using MAP and LAMBDA my_list_lambda = map(lambda n: n*n , nums) print(my_list_lambda) for i in my_list_lambda: print(i) #List Comprehensionss more examples:- # I want 'n' for each 'n' in nums if 'n' is even my_list = [] for n in nums: if n%2 == 0: my_list.append(n) print(my_list) #Usaing a list Comprehensions my_list_com = [n for n in nums if n%2 == 0] print(my_list_com) #Using Filter and LAMBDA my_list_Filter = filter(lambda n : n%2 == 0 , nums) print(my_list_Filter) for i in my_list_Filter: print(i) # I want a (letter, num) pair for each letter in 'abcd' and each number in '0123' my_list = [] for letter in 'abcd': for num in range(4): my_list.append((letter,num)) print(my_list) #Using List Comprehensions my_list_com = [(letter,num) for letter in 'abcd' for num in range(4)] print(my_list_com) ## Dictionary Comprehensions names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] print(zip(names, heros)) for (name,heros) in zip(names, heros):print(name,heros) # I want a dict{'name': 'hero'} for each name,hero in zip(names, heros) names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] my_dict = {} for name, hero in zip(names, heros): my_dict[name] = hero print(my_dict) #Dictionary Comprihensions: names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] my_dict = {name:hero for name , hero in zip (names, heros)} print(my_dict) # If name not equal to Peter my_dict = {name:hero for name , hero in zip (names, heros) if name != 'Peter'} print(my_dict) #Set Comprehension nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] my_set = set() for n in nums: my_set.add(n) print(my_set) #Using Set Comprehension my_set = {n for n in nums} print(my_set) # Generator Expressions # I want to yield 'n*n' for each 'n' in nums nums = [1,2,3,4,5,6,7,8,9,10] def gen_func(nums): for n in nums: yield n*n my_gen = gen_func(nums) for i in my_gen: print(i) #Using Generator Expressions my_gen = (n*n for n in nums) for i in my_gen: print(i)
900733030503c1011f0df3f2e5ee794499e422b0
wreyesus/Python-For-Beginners---2
/0025. File Objects - Reading and Writing to Files.py
474
4.375
4
#File Objects - Reading and Writing to Files ''' Opening a file in reading / writing / append mode ''' f = open('test.txt','r') #f = open('test.txt','w') --write #f = open('test.txt','r+') --read and write #f = open('test.txt','a') --append print(f.name) #will print file name print(f.mode) #will give r coz it is in reading mode f.close() #another way -- which close file automatically with open('test.txt','r') as f: print(f.read())
41183f1363e0e0c40cc970c7f3a717250a83a872
meg1988/PycharmProjects
/seleniumwd2/excercise/FindPrice.py
576
3.625
4
from selenium import webdriver class FindPrice(): def findprice(self): baseurl = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.get(baseurl) # price = driver.find_element_by_xpath("//table[@id='product']//tr//td[text()='Python Programming Language']//following-sibling::td") price = driver.find_element_by_xpath("//table[@id='product']//td[text()='Python Programming Language']//following-sibling::td") print("price of value is " + str(price.text)) ff = FindPrice() ff.findprice()
2c3cc02032b9864347776d0200de88183c07dc0d
meg1988/PycharmProjects
/Pyproject/classess/exceptionhandling.py
437
4.09375
4
def exceptionhandling(): try: a="aa" b=10 c=0 print(a/c) except ZeroDivisionError: print("this is wrong, cant divide by zero") except TypeError: print("cant add int to str") raise Exception("this is an exception") else: print("there is no exception hence else is executed") finally: print("it will print whatever happens") exceptionhandling()
9fa70f4432995fc59d1ba1d674ff0047fd862b28
meg1988/PycharmProjects
/Pyproject/classess/Car.py
338
3.75
4
class Car(object): wheels = 4 def __init__(self, make, model="Centra"): self.make = make self.model = model def info(self): print("Make of the car " + self.make) print("Model of the car " + self.model) c1 = Car("Nissan") c2 = Car('bmw', 'i550') c1.info() c2.info() print(Car.wheels)
412ac494347bf94d8fc4b42b4775f4516795005d
bryanjulian/Programming-11
/BryanJulianCoding/Operators and Stuff.py
1,028
4.1875
4
# MATH! x = 10 print (x) print ("x") print ("x =",x) x = 5 x = x + 1 print(x) x = 5 x + 1 print (x) # x + 1 = x Operators must be on the right side of the equation. # Variables are CASE SENSITIVE. x = 6 X = 5 print (x) print (X) # Use underscores to name variables! # Addition (+) Subtraction (-) Multiplycation (*) Division (/) Powers (**) x=5*(3/2) x = 5 * (3 / 2) x =5 *( 3/ 2) print (x) # Order of Operations average = (90 + 86 + 71 + 100 + 98) / 5 # Import the math library # This line is done only once, and at the very top # of the program. from math import * # Calculate x using sine and cosine x = sin(0) + cos(0) print (x) m = 294 / 10.5 print(m) m = 294 g = 10.5 m2 = m / g # This uses variables instead print(m2) miles_driven = 294 gallons_used = 10.5 mpg = miles_driven / gallons_used print(mpg) ir = 0.12 b = 12123.34 i = ir * b print (i) # Easy to understand interest_rate = 0.12 account_balance = 12123.34 interest_amount = interest_rate * account_balance print (interest_amount)
c1d10dd9049cd92ba07c427bae1ea2d33a66b786
wangweihao/Python
/6/6-16-2.py
498
3.6875
4
#!/usr/bin/env python #coding:UTF-8 matrix1 = [[1,2,3,4], [1,2,3,4],[1,2,3,4],[1,2,3,4]] matrix2 = [[1,2,3,4], [1,2,3,4],[1,2,3,4],[1,2,3,4]] def matrix_multi(): li = [] for i in range(len(matrix1)): li_ = [] for j in range(len(matrix2[0])): s = 0 for k in range(len(matrix1[0])): s += matrix1[i][k] * matrix2[k][j] li_.append(s) li.append(li_) return li if __name__ == '__main__': print matrix_multi()
8f5be80dca96d0cf478780563ad719ec814678a3
wangweihao/Python
/6/6-8.py
397
3.6875
4
#!/usr/bin/env python #coding:UTF-8 dict = {'0':'zero', '1':'one', '2':'two', '3':'three', '4':'four', '5':'five', '6':'six', \ '7':'seven', '8':'eight', '9':'night'} str = raw_input('please input a number (0-1000):') list = [] for i in range(len(str)): list.append(str[i]) for j in range(len(list)): print dict[list[j]], if j == len(list)-1: break print '-',
35e6049c09ecdc76a1d6c718168fc7429328865e
wangweihao/Python
/6/6-12.py
363
3.921875
4
#!/usr/bin/env python #coding:UTF-8 def findchr(string, char): print string, char for i in range(len(string)): if char == string[i]: break if i == len(string)-1: return -1 else: return i if __name__ == '__main__': str = 'abcdef' c = 'a' d = 'p' print findchr(str, c) print findchr(str, d)
776ad18ff91a475ded5a6dbef9769539767ce5a1
wangweihao/Python
/13/13-8.py
823
4
4
#!/usr/bin/env python #coding:UTF-8 class Stack(object): stack = [] def __init__(self, obj): self.stack = obj def pop(self): if 'pop' in dir(self.stack): return self.stack.pop() else: index = len(self.stack)-1 ret = self.stack(index) self.stack.remove(ret) return ret def push(self, ele): self.stack.append(ele) def isempty(self): return bool(len(self.stack)) def peek(self): return self.stack[len(self.stack)-1] def Print(self): for i in self.stack: print i, print if __name__ == '__main__': s = Stack([1,2,3]) s.Print() s.push(1) s.Print() print 'peek:%d' % (s.peek()) s.pop() s.Print() print 'peek:%d' % (s.peek())
740c59e9a65e7c68650c4883d8025eac5e5750cf
wangweihao/Python
/11/11-14.py
222
3.90625
4
#!/usr/bin/env python #coding:UTF-8 def fiboni(n): if n == 1 or n == 0: return 1 else: return fiboni(n-1) + fiboni(n-2) if __name__ == '__main__': for i in range(20): print fiboni(i)
620286ed9767af19513f32fa39ca723595ce6adc
wangweihao/Python
/6/6-6.py
349
3.765625
4
#!/usr/bin/env python #coding:UTF-8 str = raw_input('please input a string:') list = [] for i in range(0, len(str)): if str[i] != ' ': list.append(i) break for i in range(i, len(str)): if str[i] == ' ': list.append(i) break if list[0] == 0: print str else: ret = str[list[0]:list[1]] print ret
5a48ed02fb8d1100abf955dea24498a1cb530a8a
wangweihao/Python
/7/7-7.py
129
3.625
4
#!/usr/bin/env python #coding:UTF-8 dic = {1:'a', 2:'b', 3:'c'} newdic = {} for k in dic: newdic[dic[k]] = k print newdic
858a56861965e44d0d1b3161957ea9edd11720ef
wangweihao/Python
/2/2-15.py
511
4.1875
4
#!/usr/bin/env python #coding:UTF-8 myTuple = [] for i in range(3): temp = raw_input('input:') myTuple.append(int(temp)) for i in range(3): print myTuple[i] if myTuple[0] > myTuple[1]: temp = myTuple[0] myTuple[0] = myTuple[1] myTuple[1] = temp if myTuple[0] > myTuple[2]: temp = myTuple[0] myTuple[0] = myTuple[2] myTuple[2] = temp if myTuple[1] > myTuple[2]: temp = myTuple[1] myTuple[1] = myTuple[2] myTuple[2] = temp for i in range(3): print myTuple[i],
0a9a79fb3fc07e714d2a87aa9127fd94c44d0d6b
wangweihao/Python
/15/match.py
189
3.9375
4
#!/usr/bin/env python #coding:UTF-8 import re Str = 'hello world' m = re.match('hello', Str) if m is not None: print m.group() print type(m.group()) else: print 'not found'
8f49d9c6ecbbb0ad9a43b820a932a7d5ca7c6095
wangweihao/Python
/6/6-3.py
158
3.78125
4
#!/usr/bin/env python #coding:UTF-8 list = [] while 1: x = input('please input number:') if x == -1: break list.append(x) list.sort()
7882e3aafa815e47e7898a012eb078f33cb3fb2d
MemoryReload/SimplePythonExamples
/Example/Example1_3.py
726
3.734375
4
class Rectangle(object): def __init__(self, color='white', width=10, height=10): super(Rectangle,self).__init__() print 'create a %s\t%r,sized:%d\theight:%d' %(color,self,width,height) class RoundedRectangle(Rectangle): def __init__(self,*k,**kw): k=(self,)+k apply(Rectangle.__init__,k,kw) # super(RoundedRectangle,self).__init__(*k,**kw) rect = Rectangle(color='green', width=100, height=100) rect = RoundedRectangle(color='green', width=100, height=100) rect = Rectangle(*('red',30,30)) rect = RoundedRectangle(*('red',30,30)) rect = Rectangle(**{ 'color' : 'blue', 'width' : 20, 'height' : 40}) rect = RoundedRectangle(**{ 'color' : 'blue', 'width' : 20, 'height' : 40})
3f6c0ac583ec489c61b0d812c8b3bdd37eddaf40
Bmcentee148/PythonTheHardWay
/ex15.py
273
3.8125
4
from sys import argv script, filename = argv txt_file = open(filename) print "Here's your file %r:" % filename print txt_file.read() print "Print the filename again:" filename_again = raw_input('> ') txt_file_again = open(filename_again) print txt_file_again.read()
9d175894ced0e8687bb5724763722efdeb70741f
Bmcentee148/PythonTheHardWay
/ex_15_commented.py
743
4.34375
4
#import argv from the sys module so we can use it from sys import argv # unpack the args into appropriate variables script, filename = argv #open the file and stores returned file object in a var txt_file = open(filename) # Tells user what file they are about to view contents of print "Here's your file %r:" % filename # prints the contents of the file in entirety print txt_file.read() #ask user to print filename again print "Print the filename again:" #prompts user for input and stores it in given var filename_again = raw_input('> ') # opens the file again and stores as object in a new var txt_file_again = open(filename_again) # prints the contents of the file again that is stored in different var print txt_file_again.read()
dcc622587a5c864792d4ab073da0f5ad239907bf
Bmcentee148/PythonTheHardWay
/ex3.py
825
4.375
4
# begin counting chickens print "I will now count my count my chickens" #Hens is 25 + (30 / 6) = 30 print "Hens", 25 + 30.0 / 6 #Roosters is 100 - (25 * 3) % 4 print "Roosters", 100 - 25 * 3 % 4 #begin counting eggs print "Now I will count my eggs" #eggs is 3 + 2 + 1 - 5 + (4 % 2) - (1/4) + 6 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #Test boolean logic print "Is is true that 3 + 2 < 5 - 7?" #prints False print 3 + 2 < 5 - 7 #Asks what is 3 + 2 and then prints the answer print "What is 3 + 2? ", 3 + 2 #Asks what is 5 - 7 and then prints the answer print "What is 5 - 7?", 5 - 7 #you moron print "Oh, thats why its False" print "How about some more" #prints True print "Is is greater?", 5 > -2 #prints True print "Is is greater than or equal to?", 5 >= -2 #prints False print "Is is less than equal to?", 5 <= -2
f8c27ff7a12600945b1a2c24bd55f8326cf5c3c8
Bmcentee148/PythonTheHardWay
/ex34.py
309
4.09375
4
# Learning to index elements contained in a list. Just like arrays in Java! animals = ["bear", "tiger", "penguin", "zebra"] bear = animals[0] print bear nums = range(1,11) # list of ints 1 to 10 my_num = nums[9] # The tenth element ie 10 his_num = nums[0] # The first element ie 1 print my_num, his_num
43b70b64ab6d1e25bf7ffdb497a07bfe72539e2f
Bmcentee148/PythonTheHardWay
/ex5_v2.py
754
3.671875
4
name = "Zed A. Shaw" age = 35 # not a lie print "Let's talk about %s." % name height = 74 # inches height_centimeters = height * 2.54 print height_centimeters print "He's %d inches, or %d centimeters tall." % (height, round(height_centimeters)) weight = 180 # pounds weight_kilograms = weight * 0.453592 print weight_kilograms print "He's %d pounds, or %d kilograms heavy." % (weight, round(weight_kilograms)) print "Actually, thats not too heavy." eyes = 'Blue' teeth = 'White' hair = 'Brown' print "He's got %s eyes and %s hair" % (eyes, hair) print "His teeth are usually %s depending on the coffee" % teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( age, height, weight, age + weight + height)
c4d5cc928ee53ccfdd17c60938a7f9d0ee54e0ba
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/circular/index.py
533
4.1875
4
# --- Directions # Given a linked list, return true if the list # is circular, false if it is not. # --- Examples # const l = new List(); # const a = new Node('a'); # const b = new Node('b'); # const c = new Node('c'); # l.head = a; # a.next = b; # b.next = c; # c.next = b; # circular(l) # true def circular(li): slow = li.head fast = li.head while(fast.next and fast.next.next): slow = slow.next fast = fast.next.next if slow is fast: return True return False
c38d82526b9f5c557ede5a976cb2dcc9e7261842
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/tree/index.py
1,410
3.953125
4
# --- Directions # 1) Create a node class. The constructor # should accept an argument that gets assigned # to the data property and initialize an # empty array for storing children. The node # class should have methods 'add' and 'remove'. # 2) Create a tree class. The tree constructor # should initialize a 'root' property to null. # 3) Implement 'traverseBF' and 'traverseDF' # on the tree class. Each method should accept a # function that gets called with each element in the tree class Node: def __init__(self, data): self.data = data self.children = list() def add(self, data): self.children.append(Node(data)) def remove(self, data): self.children = list(filter(lambda node: node.data != data, self.children)) def __str__(self, level=0): ret = "\t"*level+repr(self.data)+"\n" for child in self.children: ret += child.__str__(level+1) return ret def __repr__(self): return '<tree node representation>' class Tree: def __init__(self): self.root = None def traverseBF(self, fn): arr = [self.root] while arr: node = arr.pop(0) arr.extend(node.children[:]) fn(node) def traverseDF(self, fn): arr = [self.root] while arr: node = arr.pop(0) arr = node.children[:] + arr fn(node)
9f8bc1fa1200b78a9777b0dd40e408d0b2da2c96
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/fromlast/index.py
613
4.03125
4
# --- Directions # Given a linked list, return the element n spaces # from the last node in the list. Do not call the 'size' # method of the linked list. Assume that n will always # be less than the length of the list. # --- Examples # const list = new List(); # list.insertLast('a'); # list.insertLast('b'); # list.insertLast('c'); # list.insertLast('d'); # fromLast(list, 2).data # 'b' def from_last(li, n): slow = li.head fast = li.head while n > 0: fast = fast.next n -= 1 while fast.next: slow = slow.next fast = fast.next return slow
669afade07619df314a48551e17ad102f28b249f
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/fib/index.py
608
4.21875
4
# --- Directions # Print out the n-th entry in the fibonacci series. # The fibonacci series is an ordering of numbers where # each number is the sum of the preceeding two. # For example, the sequence # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] # forms the first ten entries of the fibonacci series. # Example: # fib(4) === 3 def memoize(fn): cache = {} def helper(x): if x not in cache: cache[x] = fn(x) return cache[x] return helper @memoize def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) #memoization decreses rutime from O(2^n) to O(n)
a161ecd3ad0cd0d746a85474f39b92b94f4469ee
muhang/daily-programmer
/7-15.py
560
3.65625
4
def problem(testStr, problemStr): for probLetter in problemStr: if probLetter in testStr: testStr = testStr[testStr.index(probLetter)+1:len(testStr)] else: return False return True if __name__ == "__main__": testA = problem("synchronized", "snond") testB = problem("misfunctioned", "snond") testC = problem("mispronounced", "snond") testD = problem("shotgunned", "snond") testE = problem("snond", "snond") print(testA) print(testB) print(testC) print(testD) print(testE)
0b0b246f748dbf8c7bd314af8f2182c52e9de3d3
breman27/CodeWars
/6 Kyu/Python/is_it_prime.py
205
3.84375
4
from math import sqrt; from itertools import count, islice def is_prime(num): if num is 0 or num is 1: return False return num > 1 and all(num%i for i in islice(count(2), int(sqrt(num)-1)))
2fffc40faf0cfe6bc472e27ab951e8612fa94db4
jhu97/baekjoon
/10870.py
194
3.9375
4
n = int(input()) numbers = [0,1] if n == 0: print(0) elif n == 1: print(1) else: while (len(numbers) - 1) < n: numbers.append(numbers[-2]+numbers[-1]) print(numbers[-1])
14afd0cc9a60afbd927f997f141993c6cb54e1dc
jhu97/baekjoon
/2522.py
193
3.625
4
import sys input = sys.stdin.readline N = int(input()) for n in range(1, N + 1): print("{0:>{1}}".format(n * '*', N)) for i in range(N - 1, 0, -1): print("{0:>{1}}".format(i * '*', N))
ca845eb0d97de9a6b4abd397dbc95564e7ccf8bd
ES2Spring2019-ComputinginEngineering/project-one-grant-and-patrick
/simulation_code.py
5,986
4.28125
4
#Pendulum Simulation # Simulation of a pendulum, graphs position, velocity, and acceleration vs. time using meters and seconds # Created by: Grant Smith and Patrick Wright #his will produce three graphs one with velocity vs. time another with position vs. time and a final of acceleration vs. time #It will print the results at given the given time step and display time, velocity, acceleration, and position. #A .csv file will be output to the current directory with time in milliseconds and acceleration in milli-gs #Variables that should be updated depedning on the test are: #'test_number' this will put the number of the test in the name of the csv file #'length' this is the length of the pendulum arm #'timeinitial' this is if you want the simulation to start at another time than 0 #'timestep' this is the size of time step for the simulation #'mangle' this is the maximum angle of the pendulum (the starting angle) import math import numpy as np import matplotlib.pyplot as plt import csv #global variables test_number = '1' #which number test is being performed length = .15 # length in meters timeinitial = 0 #time starting value timefinal = 5 #ending time value timestep = 0.001 #the 'dt' or how big each time step is mangle = (math.pi/12) # max (starting) angle in rads a = 0 #variables for naming simulation test csv files, don't change data = 'data' L = 'L=' csv.p = '.csv' testing = 'test' file_name = testing + data + test_number + L + str(length) + csv.p #defintion of functions def print_system(time,pos,vel,accl): '''Prints the position ,velocity, and acceleration ''' print("TIME: ", round(time,5), ' s') print("POSITION: ", pos , ' radians') print("VELOCITY: ", vel, ' m/s') print("ACCELERATION: ", accl, 'milli-g', "\n") def position(t): '''returns position of pendulum in radians at given time t ''' sr = (9.8)/(length) cos = math.sqrt(sr)*t pos = mangle * math.cos(cos) #position in radians return pos def posx(t): '''returns x position of pendulum in meters at time t''' position_x = length*math.sin(position(t)) return position_x def posy(t): '''returns y position of pendulum in meters at time t''' position_y = length*(1-math.cos(position(t))) return position_y def velx(t): '''returns x velocity at time t''' velocity_x = (posx(t) - posx(t-timestep))/timestep return velocity_x def vely(t): '''returns y velocity at time t''' velocity_y = (posy(t) - posy(t-timestep))/timestep return velocity_y def velocity(t): '''returns the veloctiy (in m/s) of pendulum at given time t ''' vel = (math.sqrt(velx(t)**2 + vely(t)**2)) return vel def accx(t): '''returns x accel at time t''' acceleration_x = (velx(t) - velx(t-timestep))/timestep return acceleration_x def accy(t): '''returns y accel at time t''' acceleration_y = (vely(t) - vely(t-timestep))/timestep return acceleration_y def acceleration(t): '''returns the acceleration (now in milli-g!) of a pendulum at given time t ''' accl = (math.sqrt(accx(t)**2+accy(t)**2))*(1000/9.8) return accl def movement(): '''returns steps in time starting at time = 0 and ending at time = 1 with time step of .001 seconds ''' time = 0 time_end = 5 while time <= time_end: print_system(time, position(time), velocity(time), acceleration(time)) time += timestep # <--------how large step forward in time def write_csv_data_file(): '''writes simulated data to a list to prepare for .csv''' time = 0 time_end = 10 csvData = [[]] while time <= time_end: csvData.append([time*1000, (acceleration(time))]) # look here ------------11-1-1-1-1-1 time += timestep return csvData def write_csv(data): '''writes data from list to .csv''' with open(file_name, 'a') as csvFile: writer = csv.writer(csvFile) writer.writerows(data) csvFile.close() def plotposition(): '''returns plot of position vs time ''' # Generate time list (x axis): a = 0 timelist = [] while a*timestep < timefinal: timelist.append(timeinitial+(a*timestep)) a += 1 poslist = [] a = 0 while a*timestep < timefinal: poslist.append(position(timeinitial+(a*timestep))) a += 1 plt.subplot(3,1,2) plt.plot(timelist, poslist) plt.ylabel('Position(rads)') plt.xlabel('Time(s)') plt.grid() plt.show() def plotvelocity(): '''returns plot of velocity vs time ''' # Generate time list (x axis): a = 0 timelist = [] while a*timestep < timefinal: timelist.append(timeinitial+(a*timestep)) a += 1 vellist = [] a = 0 while a*timestep < timefinal: vellist.append(velocity(timeinitial+(a*timestep))) a += 1 plt.subplot(3,1,2) plt.plot(timelist, vellist) plt.ylabel('Velocity (m/s)') plt.xlabel('Time(s)') plt.grid() plt.show() def plotacceleration(): '''returns plot of acceleration vs time ''' # Generate time list (x axis): a = 0 timelist = [] while a*timestep < timefinal: timelist.append(timeinitial+(a*timestep)) a += 1 accllist = [] a = 0 while a*timestep < timefinal: accllist.append(acceleration(timeinitial+(a*timestep))) a += 1 plt.subplot(3,1,2) plt.plot(timelist, accllist) plt.ylabel('Acceleration (milli-g)') plt.xlabel('Time(s)') plt.grid() plt.show() #Script that gives position velocity and acceleration plot along with steping throught time #at a time step = 0.001 s row = write_csv_data_file() #data that gets written to csv file plotposition() plotvelocity() plotacceleration() movement() write_csv(row)
1c422a54db9416f308eab05525bf3faea7ac9530
vrastello/Game-Project
/FocusGame.py
8,600
3.9375
4
# Name: Vincent Rastello # Date: 11-27-20 # Description: This is a program for creating a game of Domination. Follow this link to see a description: # https://www.youtube.com/watch?v=DVRVQM9lo9E. My data structure will consist of three classes: Player, Board # and FocusGame. Player and Board will not communicate with each other. FocusGame will communicate with both, # FocusGame will act as the brain for this data structure. class Player: """This represents the player, class responsibilities include: holding, displaying and adding reserve and captured pieces. Has attribute name and color.""" def __init__(self, name, color): """Initializes player with name and color, sets reserved and captured to empty lists.""" self._color = color self._name = name self._reserved = [] self._captured = [] def get_color(self): """returns color""" return self._color def get_name(self): """returns name""" return self._name def show_reserve_list(self): """returns count of pieces in reserve list for player""" return len(self._reserved) def show_captured_list(self): """returns count of opponent pieces captured""" return len(self._captured) def add_reserve(self, piece): """adds reserve piece to reserve list""" self._reserved.append(piece) def add_capture(self, piece): """adds captured piece to captured list""" self._captured.append(piece) def remove_reserve(self): """removes reserved piece, if none returns False""" del self._reserved[0] class Board: """Represents the game board, class responsibilities are: setting data structure for board, initializing board values, holding, displaying, adding, removing and counting pieces at specified locations.""" def __init__(self, r, g): """Sets up board data structure and initializes starting game pieces, pieces accessed using tuples with row and column (a,b)""" self._board = [ [ [r], [r], [g], [g], [r], [r] ], [ [g], [g], [r], [r], [g], [g] ], [ [r], [r], [g], [g], [r], [r] ], [ [g], [g], [r], [r], [g], [g] ], [ [r], [r], [g], [g], [r], [r] ], [ [g], [g], [r], [r], [g], [g] ] ] def show_list(self, pos): """returns list of pieces at position, using tuple to index to position, returns False if invalid position""" if 0 <= pos[0] <= 5 and 0 <= pos[1] <= 5: return self._board[pos[0]][pos[1]] return False def add_piece(self, pos, val): """adds given piece using method show_pieces to access list at position""" self.show_list(pos).append(val) def count_pieces(self, pos): """returns count of elements in list at given position on board""" return len(self.show_list(pos)) class FocusGame: """This represents the game, uses composition to utilize classes Board and Player. Responsibilities are: moving pieces, validating move, resolving add reserve and captured pieces after move, checking for win condition, moving reserved pieces.""" def __init__(self, player_1, player_2): """Initializes game with players as Player objects, board as Board object and turn to None. Parameters are name and color of player in a tuple.""" self._player1 = Player(player_1[0], player_1[1]) self._player2 = Player(player_2[0], player_2[1]) self._player_list = [self._player1, self._player2] self._turn = None self._winner = None self._board = Board(self._player1.get_color(), self._player2.get_color()) def get_turn(self): """Returns private data _turn, is color, this is set after first successful move. Any color can go first.""" return self._turn def get_player_from_name(self, player_name): """Returns player object from player name.""" for player in self._player_list: if player_name == player.get_name(): return player def show_pieces(self, pos): """Returns list from Board object at specified location, uses tuple (row, column) as parameter""" return self._board.show_list(pos) def show_reserve(self, player_name): """Returns reserve list of player, takes player name as parameter.""" return self.get_player_from_name(player_name).show_reserve_list() def show_captured(self, player_name): """Returns capture list of player, takes player name as parameter.""" return self.get_player_from_name(player_name).show_captured_list() def valid_location(self, pos1, pos2, num): """Validates if pos1 and pos2 are within bounds, validates if move is in four cardinal directions only, validates if destination is equal to number of pieces moved.""" if self.show_pieces(pos1) is False or self.show_pieces(pos2) is False: return False if self._board.count_pieces(pos1) < num or num <= 0: return False if pos1[0] == pos2[0] and pos2[1] == pos1[1] - num: return True if pos1[0] == pos2[0] and pos2[1] == pos1[1] + num: return True if pos1[1] == pos2[1] and pos2[0] == pos1[0] - num: return True if pos1[1] == pos2[1] and pos2[0] == pos1[0] + num: return True return False def resolve_move(self, pos2, player_name): """parameters: destination position in tuple, and player name, resolves moving pieces to reserved or captured, sets turn to next player.""" player = self.get_player_from_name(player_name) if self._board.count_pieces(pos2) > 5: num = self._board.count_pieces(pos2) - 5 for piece in range(num): val = self.show_pieces(pos2)[piece] if val == player.get_color(): player.add_reserve(val) else: player.add_capture(val) self.show_pieces(pos2)[:] = self.show_pieces(pos2)[num:] if self.show_captured(player_name) >= 6: self._winner = player_name + " Wins" if player is self._player1: self._turn = self._player2.get_color() else: self._turn = self._player1.get_color() if self._winner is not None: return self._winner return "successfully moved" def move_piece(self, player_name, pos1, pos2, num): """parameters: player name, starting location tuple, ending location tuple, number of pieces moved. Moves piece or pieces from starting location to ending location. Validates if valid position, turn, number of pieces, top piece is current players, resolves reserved or captured pieces from move, checks win condition and sets turn to next player.""" if self._winner is not None: return self._winner if not self.valid_location(pos1, pos2, num): return False player = self.get_player_from_name(player_name) source_height = self._board.count_pieces(pos1) if self.show_pieces(pos1)[source_height - 1] != player.get_color(): return False if self.get_turn() is not None and self.get_turn() != player.get_color(): return False lower = source_height - num for piece in range(lower, source_height): val = self.show_pieces(pos1)[piece] self._board.add_piece(pos2, val) self.show_pieces(pos1)[:] = self.show_pieces(pos1)[:lower] return self.resolve_move(pos2, player_name) def reserved_move(self, player_name, pos2): """parameters are destination location tuple, and player name. Validates destination location then if player has reserve pieces. Adds piece to location specified and resolves adding captured pieces, reserve pieces and checks win condition.""" player = self.get_player_from_name(player_name) if self._winner is not None: return self._winner if self.show_pieces(pos2) is False: return False if self.show_reserve(player_name) == 0: return False if self.get_turn() is not None and self.get_turn() != player.get_color(): return False player.remove_reserve() val = player.get_color() self._board.add_piece(pos2, val) return self.resolve_move(pos2, player_name)
ab679c57ed329a89160ba09ff44e535602c7c4dc
MohamedAdel99/Parallel-HTTP-Proxy
/code.py
10,887
3.625
4
# Don't forget to change this file's name before submission. import sys import os import enum import socket,threading class HttpRequestInfo(object): """ Represents a HTTP request information Since you'll need to standardize all requests you get as specified by the document, after you parse the request from the TCP packet put the information you get in this object. To send the request to the remote server, call to_http_string on this object, convert that string to bytes then send it in the socket. client_address_info: address of the client; the client of the proxy, which sent the HTTP request. requested_host: the requested website, the remote website we want to visit. requested_port: port of the webserver we want to visit. requested_path: path of the requested resource, without including the website name. NOTE: you need to implement to_http_string() for this class. """ def __init__(self, client_info, method: str, requested_host: str, requested_port: int, requested_path: str, headers: list): self.method = method self.client_address_info = client_info self.requested_host = requested_host self.requested_port = requested_port self.requested_path = requested_path # Headers will be represented as a list of lists # for example ["Host", "www.google.com"] # if you get a header as: # "Host: www.google.com:80" # convert it to ["Host", "www.google.com"] note that the # port is removed (because it goes into the request_port variable) self.headers = headers def to_http_string(self): """ TO THE BASE FORM GET path version host: headers.....\r\n """ request_line=self.method+" "+self.requested_path+" HTTP/1.0\r\n" y=[] for i in self.headers: y.append(': '.join(i)) pass mylist = list(dict.fromkeys(y)) fullheaders='\r\n'.join(mylist) Fullstring=request_line+fullheaders+'\r\n'+'\r\n' return Fullstring def to_byte_array(self, http_string): """ Converts an HTTP string to a byte array. """ return bytes(http_string, "UTF-8") def display(self): print(f"Client:", self.client_address_info) print(f"Method:", self.method) print(f"Host:", self.requested_host) print(f"Port:", self.requested_port) stringified = [": ".join([k, v]) for (k, v) in self.headers] print("Headers:\n", "\n".join(stringified)) class HttpErrorResponse(object): """ Represents a proxy-error-response. """ def __init__(self, code, message): self.code = code self.message = message def ERRORstring(self): msg = "HTTP/1.0" +" "+ str(self.code) +" , "+ self.message +"\r\n\r\n" return msg def to_byte_array(self, http_string): """ Converts an HTTP string to a byte array. """ return bytes(http_string, "UTF-8") def display(self): print(self.ERRORstring()) class HttpRequestState(enum.Enum): """ The values here have nothing to do with response values i.e. 400, 502, ..etc. Leave this as is, feel free to add yours. """ INVALID_INPUT = 0 NOT_SUPPORTED = 1 GOOD = 2 PLACEHOLDER = -1 def entry_point(proxy_port_number): """ Entry point, start your code here. Please don't delete this function, but feel free to modify the code inside it. """ setup_sockets(proxy_port_number) return None def setup_sockets(proxy_port_number): """ SOCKET START """ print("Starting HTTP proxy on port:", proxy_port_number) s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('',int(proxy_port_number))) s.listen(10) while True: connection, address = s.accept() threading._start_new_thread(do_socket_logic,(s,connection,address)) pass def do_socket_logic(sock,clientc,address): print('** PROXY RUNNING **') st='' cache={} while True: if(st.endswith('\r\n')): sock.close break else: DATA=clientc.recv(1024).decode("utf-8") st=DATA Process=http_request_pipeline(address,DATA) msg,reqparsed=Process clientc.send(msg) if reqparsed == '': sys.exit sock.close else: w=socket.socket(socket.AF_INET, socket.SOCK_STREAM) host_ip =socket.gethostbyname(reqparsed.requested_host) port = reqparsed.requested_port bytereq=reqparsed.to_byte_array(reqparsed.to_http_string()) if(bytereq in cache): #caching resp=cache[bytereq] clientc.send(resp) else: w.connect((host_ip, port)) #remote host connect w.send(bytereq) while True: response=w.recv(1024) cache[bytereq]=response clientc.send(response) w.close pass def http_request_pipeline(source_addr, http_raw_data): """ validate and then Here we test and check if BAD or NI request then parse sanitize returnes error message , sanitzed form """ # Parse HTTP request validity = check_http_request_validity(http_raw_data) if validity == HttpRequestState.INVALID_INPUT: print("invalid") emsg=HttpErrorResponse(400,'Bad request') emsg2=emsg.to_byte_array(emsg.ERRORstring()) sanitized='' elif validity == HttpRequestState.NOT_SUPPORTED: print("invalid") emsg=HttpErrorResponse(501,'Not Implemented') emsg2=emsg.to_byte_array(emsg.ERRORstring()) sanitized='' else: emsg2=b'' parsed=parse_http_request(source_addr,http_raw_data) sanitized=sanitize_http_request(parsed) return emsg2,sanitized def parse_http_request(source_addr, http_raw_data): """ This function parses a "valid" HTTP request into an HttpRequestInfo object. """ # Replace this line with the correct values. c = http_raw_data.split("\r\n") method = c[0].split(' ')[0] if c[0].split(' ')[1][0]=='/': #relative form host=c[1].split(':')[1][1:] if '/' in host[7:] : path="/"+host[7:].split('/')[1] else: path=c[0].split(' ')[1] pass if ':' in c[1].split(':')[1]: #port splitting res = [int(i) for i in c[0].split(' ')[1].split(":")[1] if i.isdigit()] port = int("".join(map(str, res))) host=host.split(':')[0] else: port=80 elif c[0].split(' ')[1][0]!='/': #absloute form if(c[0].split(' ')[1][0]=='h'): host=c[0].split(' ')[1].split('://')[1] path=host else: host=c[0].split(' ')[1] path=host if ':' in host: res = [int(i) for i in host.split(":")[1] if i.isdigit()] port = int("".join(map(str, res))) host=host.split(':')[0] path=host else: port=80 pass header=[] for i in c[1:]: if(i!=''): x=i.split(': ') header.append(x) else: break pass ret = HttpRequestInfo(source_addr, method, host,port, path, header) return ret def check_http_request_validity(http_raw_data) -> HttpRequestState: """ all test cases passed """ c = http_raw_data.split("\r\n") if c[0].split(" ")[0] not in ['GET','HEAD','POST','PUT'] or len(c[0].split(" ") )< 3 : return HttpRequestState.INVALID_INPUT elif c[0].split(" ")[1][0] =='/' and c[1].split(":")[0]!='Host': return HttpRequestState.INVALID_INPUT elif c[1]!='' and c[0].split(" ")[1][0] =='w' and ':' not in c[1] or c[0].split(" ")[2] not in ['HTTP/1.0','HTTP/1.1','HTTP/2.0']: return HttpRequestState.INVALID_INPUT elif c[0].split(" ")[0] in ['HEAD','POST','PUT']: return HttpRequestState.NOT_SUPPORTED else: return HttpRequestState.GOOD pass def sanitize_http_request(request_info: HttpRequestInfo): """ Puts an HTTP request on the sanitized (standard) form by modifying the input request_info object. for example, expand a full URL to relative path + Host header. returns: nothing, but modifies the input object """ if request_info.requested_path==request_info.requested_host: hosthead="Host:"+request_info.requested_host.split('/')[0] z=hosthead.split(":") request_info.headers.insert(0,z) if(len(request_info.requested_path.split('/'))>1): request_info.requested_path=request_info.requested_host[len(request_info.requested_host.split('/')[0]):] else: request_info.requested_path='/' pass pass if(len(request_info.requested_host.split('/')[0])>1): request_info.requested_host=request_info.requested_host.split('/')[0] return request_info ####################################### # Leave the code below as is. ####################################### def get_arg(param_index, default=None): """ Gets a command line argument by index (note: index starts from 1) If the argument is not supplies, it tries to use a default value. If a default value isn't supplied, an error message is printed and terminates the program. """ try: return sys.argv[param_index] except IndexError as e: if default: return default else: print(e) print( f"[FATAL] The comand-line argument #[{param_index}] is missing") exit(-1) # Program execution failed. def check_file_name(): """ Checks if this file has a valid name for *submission* leave this function and as and don't use it. it's just to notify you if you're submitting a file with a correct name. """ script_name = os.path.basename(__file__) import re matches = re.findall(r"(\d{4}_){,2}lab2\.py", script_name) if not matches: print(f"[WARN] File name is invalid [{script_name}]") else: print(f"[LOG] File name is correct.") def main(): """ Please leave the code in this function as is. To add code that uses sockets, feel free to add functions above main and outside the classes. """ print("\n\n") print("*" * 50) print(f"[LOG] Printing command line arguments [{', '.join(sys.argv)}]") check_file_name() print("*" * 50) # This argument is optional, defaults to 18888 proxy_port_number = get_arg(1, 18888) entry_point(proxy_port_number) if __name__ == "__main__": main()
d417ee88b2aa638a18ff1bbb99cd42d2d96c062c
Gus98/IGL
/alphaEven.py
1,659
3.578125
4
import math import matplotlib.pyplot as plt import numpy as np import random def T(Z, alpha): #this is the natural extension funtion with the input being a 2 element list a = 0 b = 0 if Z[0] > 0: e = 1 else: e = -1 k = math.floor((1/abs(Z[0]) - alpha + 2)/2) a = 1/abs(Z[0]) - 2 * k if (2 * k + e * Z[1]) != 0: b = 1/(2 * k + e * Z[1]) else: b = 0 return [a,b] def addx_toplot(x, P, alpha): #this function is used to add all the (x,y) coordinates for the first #100 iterations of (x,0) to the list of points to be plotted point = [x, 0] x_points = [x] y_points = [0] a = x for i in range(0, 150): point = T(point, alpha) x_points.append(point[0]) y_points.append(point[1]) a = point[0] P[0] = P[0] + x_points P[1] = P[1] + y_points def bound(x, alpha): #this is the function that is graphed y = (2 + (x+1) * ((1 + alpha)/(1 - alpha)))/(2 + (x + 1) * ((3 * alpha - 1)/(1 - alpha))) return y def f(x, alpha): #this uses the bound function to generate the list of points to plot later y = [] for i in x: y = y + [bound(i, alpha)] return y points = [[],[]] M = 1000 #the number of points to be tested alp = 0.5 #the alpha value used in the natural extension t1 = np.arange(alp - 2, alp, 0.001) for n in range(1,M): z = ((n - random.uniform(0,1))/M + alp - 1) addx_toplot(z, points, alp) plt.scatter(points[0],points[1], marker=".") #this plots the natural extension plt.plot(t1, f(t1, alp), 'r') #this plots the function that would ideally be the left bound plt.show()
38a44d9ba0619c8a6f90ad1c82da64eaac4be212
suruisunstat/leetcode_practice
/amazon/python/1. Two Sum.py
674
3.546875
4
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # h = {} # for i, num in enumerate(nums): # n = target - num # if n not in h: # h[num] = i # else: # return [h[n], i] dic = {} for i, num in enumerate(nums): remain = target - num if remain not in dic: dic[num] = i else: return [dic[remain],i] # Time complexity: O(n) # Space complexity: O(n)
fc29de0ee7e96ae3d39e183fe2ad9f1813258c2b
suruisunstat/leetcode_practice
/amazon/python/437. Path Sum III.py
1,479
3.609375
4
# 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 pathSum(self, root, sum): self.numOfPaths = 0 self.dfs(root,sum) return self.numOfPaths def dfs(self, node, sum): if node: self.test(node, sum) self.dfs(node.left, sum) self.dfs(node.right, sum) def test(self, node, sum): if not node: return if node.val == sum: self.numOfPaths += 1 self.test(node.left, sum - node.val) self.test(node.right, sum - node.val) ## Time: O(n^2) ## Space:O(n) # def pathSum(self, root, sum): # """ # :type root: TreeNode # :type sum: int # :rtype: int # """ # self.result = 0 # cache = {0:1} # self.dfs(root, sum, 0, cache) # return self.result # def dfs(self, root, sum, currSum, cache): # if (not root): # return # currSum += root.val # oldSum = currSum - sum # self.result += cache.get(oldSum,0) # cache[currSum] = cache.get(currSum,0) + 1 # self.dfs(root.left, sum, currSum, cache) # self.dfs(root.right, sum, currSum, cache) # cache[currSum] -= 1 # Time: O(n) # Space: O(n)
327a97bcecde8a6f2d385709c0c0bada63674fe5
suruisunstat/leetcode_practice
/amazon/python/24. Swap Nodes in Pairs.py
860
3.84375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(0) dummy.next = head prev_node = dummy while head and head.next: first_node = head second_node = head.next # swap prev_node.next = second_node first_node.next = second_node.next second_node.next = first_node # update for next swap prev_node = first_node head = first_node.next return dummy.next # The challenging part is the rule to swap
a2786e3a176fdaa4abd0eb5c778b314ce873ad6a
suruisunstat/leetcode_practice
/486. Predict the Winner.py
987
3.5
4
## method1: recursion O(2^n) time class Solution(object): def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ return self.winner(nums, 0, len(nums) - 1, 1) >= 0 def winner(self, nums, s, e, turn): if s == e: return turn * nums[s] a = turn * nums[s] + self.winner(nums, s+1, e, -turn) b = turn * nums[e] + self.winner(nums, s, e - 1, -turn) return turn * max(turn * a, turn * b) sol = Solution() nums = [1, 5, 233, 7] res = sol.PredictTheWinner(nums) print(res) ## method2: O(n^2) time class Solution(object): def PredictTheWinner(self,nums): dp = [[0] * len(nums)] * len(nums) for s in range(len(nums)-1,-1,-1): dp[s][s] = nums[s] for e in range(s+1,len(nums)): a = nums[s] - dp[s+1][e] b = nums[e] - dp[s][e-1] dp[s][e] = max(a,b) return dp[0][len(nums)-1] >= 0
2451888fcd98edbc4ee7cf2923e0a560845008dd
suruisunstat/leetcode_practice
/amazon/python/104. Maximum Depth of Binary Tree.py
1,285
3.765625
4
# 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 maxDepth(self, root): # """ # :type root: TreeNode # :rtype: int # """ # if root is None: # return 0 # # if root.left is None and root.right is None: # # return 1 # return max(self.maxDepth(root.right),self.maxDepth(root.left)) + 1 ## Time: O(n) ## Space: O(n) average O(logn) ## iteration def maxDepth(self, root): if not root: return 0 stack = [] depth = 0 next_num = 0 stack.append(root) while stack != []: depth = depth + 1 next_num = len(stack) for i in range(next_num): cur = stack.pop(0) # poll the first element from a queue if cur.left: stack.append(cur.left) if cur.right: stack.append(cur.right) return depth ## use queue for BFS, POP(0) the first element # Time: O(n) # Space: O(n) n/2
b9b084f86706063e46c7bd0579a2758dc7de2553
suruisunstat/leetcode_practice
/amazon/python/9. Palindrome Number.py
482
3.578125
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ #return str(x) == str(x)[::-1] if x < 0 or (x % 10 == 0 and x != 0): return False revert = 0 while x > revert: revert = revert * 10 + x % 10 x = x//10 return x == revert or x == revert // 10 ## remember the trick helps to solve this question: time O(logn) space O(1)
f31db6e9ab43a04d97ad34853681a0c2a95823ff
suruisunstat/leetcode_practice
/amazon/python/208. Implement Trie (Prefix Tree).py
2,703
3.890625
4
# import collections class Node(object): def __init__(self): self.children = collections.defaultdict(Node) self.isword = False def containsKey(self,ch): if self.children.get(ch) == None: return False return True def get(self,ch): return self.children.get(ch) def put(self, ch, node): self.children[ch] = node def setEnd(self): self.isword = True def isEnd(self): return self.isword class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word): # apple """ Inserts a word into the trie. :type word: str :rtype: None """ current = self.root for ch in word: if not current.containsKey(ch): current.put(ch, Node()) current = current.children[ch] current.setEnd() def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ current = self.root for w in word: current = current.children.get(w) if current == None: return False return current.isword def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ current = self.root for w in prefix: current = current.children.get(w) if current == None: return False return True ## Time: o(m) m is the length of word ## Space: o(m) m is the size of the trie, otherwise o(1) # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) """ def searchLongestPrefix(word): current = self.root prefix = "" for w in word: if current.children.get(w) == None: return prefix elif current.isword = True: # need more examination prefix = prefix + w return prefix current = current.children.get(w) prefix = prefix + w return prefix def longestCommonPrefix(q, strs): if strs == []: return "" if len(strs) == 1: return strs[0] trie = Trie() for s in strs: trie.insert(s) return trie.searchLongestPrefix(q) """
8fa85e0a0b64bcf6b2175da13c5414b6f4397e90
cmattox4846/PythonPractice
/Pythonintro.py
2,522
4.125
4
# day_of_week = 'Monday' # print(day_of_week) # day_of_week = 'Friday' # print(f"I can't wait until {day_of_week}!") # animal_input = input('What is your favorite animal?') # color_input = input('What is your favorite color?') # print(f"I've never seen a {color_input} {animal_input}") #**** time of day # time_of_day = 1100 # meal_choice = "" # if time_of_day < 1200: meal_choice = 'Breakfast' # elif time_of_day > 1200 and time_of_day < 1700: meal_choice = 'Lunch' # elif time_of_day > 1700: meal_choice = 'Dinner' # print(meal_choice) # random Number # import random # number = random.randrange(0,10 +1) # print(number) # if number >= 0 and number < 3: # print('Beatles') # elif number > 2 and number < 6: # print('Stones') # elif number > 5 and number < 9: # print('Floyd') # elif number > 8 and number <= 10: # print('Hendrix') # msg = 'Python is cool!' # for number in range(7): # print(msg) # for number2 in range(11): # print(number2) # msg_hello = 'Hello' # msg_goodbye = 'GoodBye' # for count in range(5): # print(msg_hello) # print(msg_goodbye) # height= 40 # while height < 48: # print('Cannot Ride!') # height += 1 # Magic Number Game #import random # magic_numbers = random.randrange(0,100,+1) # guess = 0 # print(magic_numbers) # while guess != magic_numbers: # guess = int(input('Please enter your guess!')) # if guess > magic_numbers: # if guess > (magic_numbers - 10) or guess < magic_numbers: # print('Getting Warmer') # print('Too Low!') # elif guess < magic_numbers: # if guess < (magic_numbers + 10) or guess > magic_numbers: # print('Getting Warmer!') # print('Too High!') # elif guess == magic_numbers: # print(f'{guess} is the correct number!') # def print_movie_name(): # Fav_movie = 'Casino' # print(Fav_movie) # print_movie_name() # def favorite_band (): # band_name_input = input('Please enter your favorite band name') # return band_name_input # band_results = favorite_band() # print(band_results) # def concert_display(musical_act): # my_street = input("Please enter the street you live on") # print(f'It would be great if {musical_act} played a show on {my_street}') # concert_display("Zac Brown Band") desktop_items = ['desk', 'lamp', 'pencil'] #print(desktop_items[1]) desktop_items.append('Infinity Gauntlet') #print(desktop_items[3]) for items in desktop_items: print(items)
17cb8a6cac5b72b252aa421004f17affc7c06b7c
shellhome/mystrategy
/myshell/src/mypython.py
3,513
3.828125
4
# -*- coding:utf-8 -*- ''' Created on 2016年2月16日 @author: shellcom ''' def hello(name): ''' :param name: ''' return "hello," + name + "!" def story(**kwds): return "once upon a time, there was a "\ "%(job)s called %(name)s" % kwds def power(x, y, *others): if others: print "received redundant parameters:", others return pow(x, y) def interval(start, stop=None, step=1): "imitates range() for step>0" if stop is None: start, stop = 0, start result = [] i = start while i < stop: result.append(i + 1) i += step return result def factory(n): if n == 1: return 1 else: return n * factory(n - 1) def search(l, key, lo=0, hi=None): if hi is None: hi = len(l) - 1 if lo == hi: return hi else: mid = (lo + hi) // 2 if key > l[mid]: return search(l, key, mid + 1, hi) else: return search(l, key, lo, mid) def func(a, b, c=0, *tup, **dic): print "a=", a, "b=", b, "c=", c, "tup=", tup, "dic=", dic args = (1, 2, 3, 4, 5) print args kw = {"x":100, "y":200, "z":101, "xx":201} print kw func(1, 2, **kw) seq = [56, 78, 12, 52, 31, 56, 46, 1, 13] print seq seq.sort() print seq print search(seq, 12) class sec: def __inai(self): print "you can't see me" def ai(self): print "message is" self.__inai() s = sec() s.ai() s._sec__inai() class fil: def init(self): self.blk=[] def filter(self,seque): return[x for x in seque if x not in self.blk] class samfil(fil): def init(self): self.blk=["spam"] f=fil() f.init() print f.filter([1,2,3,45,56]) s=samfil() s.init() print s.filter(["spam","spam","sfsf","123","4646"]) from numpy import matrix ss = matrix([[1, 2, 3], [4, 5, 6]]) print(ss) import matplotlib.pyplot as plt1 from mpl_toolkits.mplot3d import axes3d from matplotlib import cm fig = plt1.figure() ax = fig.gca(projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3) cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) ax.set_xlabel('X') ax.set_xlim(-40, 40) ax.set_ylabel('Y') ax.set_ylim(-40, 40) ax.set_zlabel('Z') ax.set_zlim(-100, 100) plt1.show() import numpy as np import matplotlib.pyplot as plt2 import matplotlib.animation as animation def data_gen(t=0): cnt = 0 while cnt < 1000: cnt += 1 t += 0.1 yield t, np.sin(2 * np.pi * t) * np.exp(-t / 10.) def init(): ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 10) del xdata[:] del ydata[:] line.set_data(xdata, ydata) return line, fig, ax = plt2.subplots() line, = ax.plot([], [], lw=2) ax.grid() xdata, ydata = [], [] def run(data): # update the data t, y = data xdata.append(t) ydata.append(y) xmin, xmax = ax.get_xlim() if t >= xmax: ax.set_xlim(xmin, 2 * xmax) ax.figure.canvas.draw() line.set_data(xdata, ydata) return line, ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10, repeat=False, init_func=init) plt2.show()
97a1e6ed08a341e3635ff353181c98ee9f8466e4
erikbrannstrom/advent-of-code-2017
/day11.py
722
3.75
4
MOVEMENT = { "nw": (-0.5, 0.5), "n": (0, 1), "ne": (0.5, 0.5), "se": (0.5, -0.5), "s": (0, -1), "sw": (-0.5, -0.5) } def move(coords, step): move = MOVEMENT[step] return (coords[0] + move[0], coords[1] + move[1]) def distance(coords): diagonal_steps = abs(coords[0]) * 2 straight_steps = abs(coords[1]) - diagonal_steps * 0.5 return diagonal_steps + straight_steps def first(input): steps = input.split(",") coords = (0,0) for step in steps: coords = move(coords, step) return distance(coords) def second(input): steps = input.split(",") coords = (0,0) max_distance = 0 for step in steps: coords = move(coords, step) max_distance = max(max_distance, distance(coords)) return max_distance
8144b865e19d4b533985d435d0be28c52223caf7
12DReflections/PythonWebScraping
/13_newsScrape/main.py
761
3.625
4
import gethtml import articleText # Scrapes a site's context # Come up with keywords of that site # Keywords compare to a list of regular words which are removed def main(): url = "http://www.theage.com.au/world/us-election/donald-trump-talks-and-talks-and-beneath-the-verbal-deluge-themes-emerge-20160325-gnreo1.html" url2 = "http://allrecipes.com.au" # Get top ranked words from article body <p>, print the keywords article = articleText.getArticle(url) print article print articleText.getKeywords(article) # Get htmlText and print the top keywords from a page's text # article = gethtml.getHtmlText(url) # keywordsList = articleText.getKeywords(article) # for keyword in keywordsList[0:10]: # print keyword if __name__ == "__main__": main()
f6ddfe6d2be79149d6a0b7c7fd373e8524990574
Hadiyaqoobi/Python-Programming-A-Concise-Introduction
/week2/problem2_8.py
1,206
4.53125
5
''' Problem 2_8: The following list gives the hourly temperature during a 24 hour day. Please write a function, that will take such a list and compute 3 things: average temperature, high (maximum temperature), and low (minimum temperature) for the day. I will test with a different set of temperatures, so don't pick out the low or the high and code it into your program. This should work for other hourly_temp lists as well. This can be done by looping (interating) through the list. I suggest you not write it all at once. You might write a function that computes just one of these, say average, then improve it to handle another, say maximum, etc. Note that there are Python functions called max() and min() that could also be used to do part of the jobs. ''' hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \ 40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \ 36.0, 35.0, 33.0, 32.0] def problem2_8(temp_list): count_t = 0 sum_t = 0 print("Average:", sum(temp_list)/len(temp_list)) print("High:",max(temp_list)) print("Low:", min(temp_list)) problem2_8(hourly_temp)
3c0f32642e1477fe148b57a56620a1ec54dff419
Hadiyaqoobi/Python-Programming-A-Concise-Introduction
/week1/problem1_1.py
363
3.8125
4
'''Write a function problem1_1() that prints "Problem Set 1". Tip: Be careful that your program outputs this exact phrase with no additional characters. It will be graded automatically and must be precise. Here is the run of my solved problem 1_1: problem1_1() Problem Set 1 ''' def problem1_1(): print("Problem Set 1") #problem1_1
11bee85063a59abe16f76b399c84b46606c8a549
jvastola/DiscreteMathematics
/DiscreteMath/OddEven/oddeven.py
244
3.875
4
arr = [] max = 0 while max < 10: num = int(input('enter an int: ')) if num & 1: arr.append(num) max = max + 1 if len(arr) == 0: print('No odd numbers were entered') else: oddArr = sorted(arr) print(oddArr[-1])
794e49a348841f0b195054649039622bd8c6daea
arifemrecelik/Project-Euler
/10.py
294
4.03125
4
import math result = 0 def isPrime(n): if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True limit = int(input("Enter the limit: "), 10) for i in range(1,limit): if isPrime(i): result += i print(result-1)
aab8e731292be72366b9db81a0906ef40962f2f5
pudal/FirstStep
/palindrome.py
152
3.875
4
word= input("단어를 입력해보세요") result = True for i in range(len(word)): if word[i] != word[-1-i]: result = False break print(result)
5413f9ffa55e90ddd4649be5a78c9366240818c3
FE1979/weatherapp
/weatherapp.core/weatherapp/core/abstract/commands.py
5,284
3.59375
4
""" Application commands ConfigureApp: set provider to show, caching time and way of app output Configure: set Provider options """ from abstract.abstract import Command import config.config as config class ConfigureApp(Command): """ Configures application Options to configure: - what provider application should call - set caching time - type of weather information output """ name = 'ConfigureApp' def run(self): """ Run configuration proccess """ self.app.stdout.write('Set providers to show:\n') providers_list = list(enumerate(self.app.providers.get_list())) for number, item in providers_list: self.app.stdout.write(f"{number} - {item}\n") self.app.stdout.write( "Enter number of providers separately or S to skip\n" ) try: choice = input('').split() if ('s' or 'S') in choice: # skip raise ValueError try: choice = [int(x) for x in choice] except ValueError: self.app.logger.error( 'Only numbers should be entered. ' 'Please, restart app and try again.') for number, item in providers_list: if number in choice: config.PROVIDERS_CONF[providers_list[number][1]]['Show'] = \ True elif number not in choice: config.PROVIDERS_CONF[providers_list[number][1]]['Show'] = \ False elif number < max(choice): # in case if number is wrong continue except ValueError: pass self.app.stdout.write( 'Do you want to set refresh time for all providers?\n') reload_time = input('Type time in minutes or any non-number to skip\n') """ if user entered non-number - quit in other case set refresh time for all providers """ try: reload_time = int(reload_time) for item in config.WEATHER_PROVIDERS: for key in config.WEATHER_PROVIDERS[item]: if key == 'Caching_time': config.WEATHER_PROVIDERS[item][key] = reload_time except ValueError: self.app.logger.info("Skip") display_option = input( "Type '1' for displaying weather " + "info as a table or '2' - as plain text?\n") if display_option == '1': config.WEATHER_PROVIDERS['App']['Display'] = 'table' elif display_option == '2': config.WEATHER_PROVIDERS['App']['Display'] = 'plain' class Configure(Command): """ Configures Provider Options: - location - next day forecast - hourly forecast """ name = 'Configure' def run(self): """ Runs provider configuration proccess If Provider noted in CLI - configure it Configure all Providers if no CLI argument Function calls set_options to set forecast options """ provider_title = '' set_loc = False choice = input('Do you want set up location? Y/N\n') if choice.lower() == 'y': set_loc = True if len(self.app.remaining_args) > 0: # if provider is entered by user provider_title = self.app.remaining_args[0] # run for noted Provider if first argument is provider title if provider_title in self.app.providers.get_list(): not set_loc and self.set_options(provider_title) set_loc and self.set_location(provider_title) # do it for all if no provider chosen else: for provider_title in self.app.providers.get_list(): not set_loc and self.set_options(provider_title) set_loc and self.set_location(provider_title) self.app.stdout.write('Bye-bye!') def set_options(self, provider_title): """ Sets options for provider :param provider_title: Provider title """ for key in config.PROVIDERS_CONF[provider_title]: if key == 'Next_day': choice = input(f"{provider_title}, " + "show next day forecast? Y/N\n") if choice.lower() == 'y': config.PROVIDERS_CONF[provider_title]['Next_day'] = True elif choice.lower() == 'n': config.PROVIDERS_CONF[provider_title]['Next_day'] = False elif key == 'Next_hours': choice = input(f"{provider_title}, " + "show next hours forecast? Y/N\n") if choice.lower() == 'y': config.PROVIDERS_CONF[provider_title]['Next_hours'] = True if choice.lower() == 'n': config.PROVIDERS_CONF[provider_title]['Next_hours'] = False def set_location(self, provider_title): """ Sets location of provider :param provider_title: Provider title """ provider = self.app.providers.get(provider_title) provider(self.app).config_location()
821b6ff69b1b5e95f2ef5080f1804d7ebf3709da
tHeMaskedMan981/coding_practice
/theory/algorithms/binary_search/Find_first_and_last_position_in_sorted_array.py
1,301
3.5625
4
import time nums = [6,8,8,9] target = 8 l,r = 0, len(nums)-1 found = False # > and < conditions are same in both the cases (r = mid-1, l = mid+1) # For leftmost index, when nums[mid]==target, close in from the right side. r = mid. this way we # dont loose the target, and keep on moving towards the leftmost occurence. while l<=r: mid = l + (r-l)//2 if nums[mid]==target: if l==r: found = True break else: r = mid elif nums[mid]<target: l = mid+1 else: r = mid-1 if found: ans = [l] else: print(-1) l,r = 0, len(nums)-1 found = False # For finding the rightmost, can't just invert the process of above one. The reason is calculating # the mid favors l, and if we do l = mid, we might end up in a infinte loop. for ex, [8,8], # l,r=0,1; mid=0, as equal, l=mid=0, thus starting the same loop again. so when equal, move 1 step # ahead from left, chances are will loose the target, but not by more than 1. so when the loop ends, # use l-1 as the result. while l<=r: mid = l + (r-l)//2 if nums[mid]==target: found = True l = mid+1 elif nums[mid]<target: l= mid+1 else: r = mid-1 if found: ans+=[l-1] print(ans) else: print(-1)
c9696e77689ca80b0ec5c1a46f9e5a59857c3b57
tHeMaskedMan981/coding_practice
/problems/dfs_tree/symmetric_tree/recursive.py
995
4.21875
4
# A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None class Solution(object): def isSymmetric(self, root): if root is None: return True return self.isMirror(root.left, root.right) def isMirror(self, root1, root2): if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False if root1.data != root2.data: return False return self.isMirror(root1.left, root2.right) and self.isMirror(root1.right, root2.left) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) print ("Level order traversal of binary tree is -") print(Solution().isSymmetric(root))
aab16a42ae6dc911edc2462b300b52a819a1c39b
tHeMaskedMan981/coding_practice
/theory/algorithms/binary_search/simple_binary_search.py
495
3.859375
4
# Driver Code arr = [ 2, 3, 4, 10, 40 ] x = 3 l,r = 0, len(arr)-1 while l <= r: # Use this to avoid overflow problems mid = l + (r - l) // 2 # Check if x is present at mid if arr[mid] == x: print(mid) break # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 # If x is smaller, ignore right half else: r = mid - 1 # If we reach here, then the element # was not present # print(-1)
99dafa9ed15abd0e7e14a16ca3381c4c3e029abc
IshmaelDojaquez/Python
/First Game/Various_Games.py
4,094
4.21875
4
import random from random import randint print("Welcome to the Game Selector") # Use of a dictionary gameConversion = { 1: "Random Number Guesser", 2: "MadLib", 3: "Rock Paper Scissors" } # Use of methods def gameMenu(): print("1. Random Number Guesser") print("2. MadLib") print("3. Rock Paper Scissors\n") game_selected = int(input("Please Select Your Game: ")) # Use of a while loop while game_selected > 3 or game_selected < 0: print("This was not a value...\n") game_selected = int(input("Select Your Game: ")) # Use of an if statement if game_selected == 1: print(f"You selected: {gameConversion[1]}!\n") elif game_selected == 2: print(f"You selected: {gameConversion[2]}!\n") elif game_selected == 3: print(f"You selected: {gameConversion[3]}!\n") return game_selected def randomNumberGuesser(): # Use of random correct_answer = randint(0, 100) number_guessed = int(input("Choose a random number between 1-100: ")) # Use of while and if while number_guessed > 100 or number_guessed < 1: print("This was not a value...\n") number_guessed = int(input("Choose a random number between 1-100: ")) while number_guessed != correct_answer: if number_guessed < correct_answer: print("Not quiet there... You're too low!") number_guessed = int(input("\nChoose another number: ")) elif number_guessed > correct_answer: print("Oh no... That's too high!") number_guessed = int(input("\nChoose another number: ")) print("Congratulations! You guessed the right answer!") def madLib(): adjective1 = input("Enter an adjective: ") color = input("Enter a color: ") thing = input("Enter a thing:") place = input("Enter a place: ") person = input("Enter the name of a person: ") adjective2 = input("Enter an adjective: ") insect = input("Enter an insect: ") food = input("Enter a type of food: ") verb = input("Enter a verb: ") print(f"Last night I dreamed I was a {adjective1} butterfly with {color} spots that looked like {thing}.\n " f"I flew to {place} with my best-friend and {person} who was a {adjective2} {insect}.\n" f"We ate some {food} when we got there and then decided to {verb} and the dream ended when I said \"Lets {verb}!\".") def rockPaperScissors(): matches_played = 0 computer_won = 0 player_won = 0 # Use of while and if while matches_played != 3: options = ["rock", "paper", "scissors"] computer_choice = random.choice(options) player_choice = input("Choose Your Weapon: ") player_choice.lower() print("Rock... Paper.. Scissors. SHOOT!\n") if player_choice == computer_choice: print(f"Both players selected {player_choice}. It's a tie!") elif player_choice == "rock": if computer_choice == "scissors": print("Rock smashes scissors! You win!") player_won += 1 else: print("Paper covers rock! You lose.") computer_won += 1 elif player_choice == "paper": if computer_choice == "rock": print("Paper covers rock! You win!") player_won += 1 else: print("Scissors cuts paper! You lose.") computer_won += 1 elif player_choice == "scissors": if computer_choice == "paper": print("Scissors cuts paper! You win!") player_won += 1 else: print("Rock smashes scissors! You lose.") computer_won += 1 matches_played += 1 print(f"\nYou have {player_won} wins. The computer has {computer_won} wins.\n" f"There is {3 - matches_played} game left!\n") game_selected = gameMenu() if game_selected == 1: randomNumberGuesser() elif game_selected == 2: madLib() elif game_selected == 3: rockPaperScissors() print("\nI Hope You Had Fun!")
62e3168c128f1d16bef0ec4cc31afa2e05ae9cae
IshmaelDojaquez/Python
/Python101/Lists.py
413
4.25
4
names = ['John', 'Bob', 'Sarah', 'Mat', 'Kim'] print(names) print(names[0]) # you can determine a specific positive or negative index print(names[2:4]) # you can return names at a index to a given index. Does not include that secondary index names[0] = 'Howard' # Practice numbers = [3, 6, 23, 8, 4, 10] max = numbers[0] for number in numbers: if number > max: max = number print(max)
5587f9e0340d5b7d6f83700bf182cb59eec60dce
IshmaelDojaquez/Python
/Pong/Pong.py
5,154
3.953125
4
# Pong game import turtle import os window = turtle.Screen() window.title("Pong") window.bgcolor("black") window.setup(width=800, height=600) window.tracer(0) # forces a manual update rather then allowing the window to update on its own # Score score_player1 = 0 # player 1 score_player2 = 0 # player 2 # Paddle for player 1 paddle_a = turtle.Turtle() paddle_a.speed(0) paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len=1) # size of the paddle paddle_a.penup() # makes sure that the paddle is not leaving a trail behind paddle_a.goto(-350, 0) # Paddle for player 2 paddle_b = turtle.Turtle() paddle_b.speed(0) paddle_b.shape("square") paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len=1) # size of the paddle paddle_b.penup() # makes sure that the paddle is not leaving a trail behind paddle_b.goto(350, 0) # Ball ball = turtle.Turtle() ball.speed(0) ball.shape("square") ball.color("white") ball.penup() # makes sure that the ball is not leaving a trail behind ball.goto(0, 0) # resets ball to the center of the screen ball.dx = 0.1 # direction the ball will start on the x coordinate plane ball.dy = 0.1 # direction the ball will start on the y coordinate plane # Scoreboard scoreboard = turtle.Turtle() scoreboard.speed(0) scoreboard.shape("square") scoreboard.color("white") scoreboard.penup() scoreboard.hideturtle() scoreboard.goto(0, 260) scoreboard.write("Player A: 0 Player B: 0", align="center", font=("Courier", 24, "normal")) # Movement def paddle_a_up(): y = paddle_a.ycor() # current position of the paddle y += 20 # how much the paddle will move, either up or down, per press of the button paddle_a.sety(y) # set the new position of the paddle def paddle_a_down(): y = paddle_a.ycor() # current position of the paddle y -= 20 # how much the paddle will move, either up or down, per press of the button paddle_a.sety(y) # set the new position of the paddle def paddle_b_up(): y = paddle_b.ycor() # current position of the paddle y += 20 # how much the paddle will move, either up or down, per press of the button paddle_b.sety(y) # set the new position of the paddle def paddle_b_down(): y = paddle_b.ycor() # current position of the paddle y -= 20 # how much the paddle will move, either up or down, per press of the button paddle_b.sety(y) # set the new position of the paddle # Keyboard bindings window.listen() # "listen" for the key to be called window.onkeypress(paddle_a_up, "w") window.onkeypress(paddle_a_down, "s") window.onkeypress(paddle_b_up, "Up") window.onkeypress(paddle_b_down, "Down") # Game Loop while True: window.update() # Move the ball ball.setx(ball.xcor() + ball.dx) # updates the movement of the ball in the game ball.sety(ball.ycor() + ball.dy) # updates the movement of the ball in the game # Border checking # Top and bottom ball if ball.ycor() > 290: # hits the border at 290 ball.sety(290) # resets the ball at 290 ball.dy *= -1 # reverses the direction of the ball elif ball.ycor() < -290: # hits the border at -290 ball.sety(-290) # resets the ball at -290 ball.dy *= -1 # reverses the direction of the ball # Top and bottom paddle a if paddle_a.ycor() > 250: # hits the border at 250 paddle_a.sety(250) # resets the paddle at 250 so it cant go past it elif paddle_a.ycor() < -250: # hits the border at -250 paddle_a.sety(-250) # resets the paddle at -250 so it cant go past it # Top and bottom paddle b if paddle_b.ycor() > 250: # hits the border at 250 paddle_b.sety(250) # resets the paddle at 250 so it cant go past it elif paddle_b.ycor() < -250: # hits the border at -250 paddle_b.sety(-250) # resets the paddle at -250 so it cant go past it # Left and right if ball.xcor() > 350: score_player1 += 1 # add score to player 1 scoreboard.clear() # clear board scoreboard.write("Player A: {} Player B: {}".format(score_player1, score_player2), align="center", font=("Courier", 24, "normal")) # reset board with new values ball.goto(0, 0) # reset ball to center ball.dx *= -1 # resets the ball back with a reverse direction on the x coordinate plane elif ball.xcor() < -350: score_player2 += 1 # add score to player 2 scoreboard.clear() # clear board scoreboard.write("Player A: {} Player B: {}".format(score_player1, score_player2), align="center", font=("Courier", 24, "normal")) # resets board with new values ball.goto(0, 0) # reset ball to center ball.dx *= -1 # resets the ball back with a reverse direction on the x coordinate plane # Ball hits the paddle if ball.xcor() < -340 and paddle_a.ycor() + 50 > ball.ycor() > paddle_a.ycor() - 50: # player1 paddle ball.dx *= -1 # reverses direction of the ball elif ball.xcor() > 340 and paddle_b.ycor() + 50 > ball.ycor() > paddle_b.ycor() - 50: # player2 paddle ball.dx *= -1 # reverses the direction of the ball
6354e5a260db818df5bc0cab5b56394aa79aaccd
IanJang/codewars
/junyeong/valid_parentheses.py
850
3.6875
4
from junyeong import Test def valid_parentheses(string): check = 0 for s in string: if s == '(': check += 1 if s == ')': if check <= 0: return False check -= 1 return check == 0 def test_valid_parentheses(): Test.assert_equals(valid_parentheses(" ("), False) Test.assert_equals(valid_parentheses(")test"), False) Test.assert_equals(valid_parentheses(""), True) Test.assert_equals(valid_parentheses("hi())("), False) Test.assert_equals(valid_parentheses("hi(hi)()"), True) Test.assert_equals(valid_parentheses(")("), False) Test.assert_equals(valid_parentheses("if(valid_parentheses('()'))"), True) Test.assert_equals(valid_parentheses("public void run())"), False) if __name__ == '__main__': print(valid_parentheses(")test"))
23176d422e75876e000427cf8234b86747f35b45
IanJang/codewars
/junyeong/integers_recreation_one.py
1,875
3.515625
4
import math def list_squared(m, n): ret = [] for num in range(m, n + 1): sum_ = op_optimized_sum_square(num) if math.sqrt(sum_) % 1 == 0: ret.append([num, sum_]) return ret sum_square_cache = {} def op_optimized_sum_square(n): if n in sum_square_cache: return sum_square_cache[n] i = 1 square_sum = 0 while i ** 2 < n: if n % i == 0: square_sum += (n // i) ** 2 + i ** 2 i += 1 if i ** 2 == n: square_sum += i ** 2 sum_square_cache[n] = square_sum return square_sum def get_one_example(num): sum = 0 ret = [] for i in range(1, num + 1): sq = i * i if num % i == 0: sum += sq if math.sqrt(sum) % 1 == 0: ret = [num, sum] return ret def get_divisors(num): return [i for i in range(1, num + 1) if num % i == 0] def get_squared_divisors(num): return [i * i for i in range(1, num + 1) if num % i == 0] def test_all(): assert get_divisors(42) == [1, 2, 3, 6, 7, 14, 21, 42] assert get_squared_divisors(42) == [1, 4, 9, 36, 49, 196, 441, 1764] assert get_one_example(1) == [1, 1] assert get_one_example(42) == [42, 2500] assert get_one_example(246) == [246, 84100] assert list_squared(1, 250) == [[1, 1], [42, 2500], [246, 84100]] assert list_squared(42, 250) == [[42, 2500], [246, 84100]] assert list_squared(250, 500) == [[287, 84100]] def sum_square(nn): # math.sqrt(1).is_integer() return sum(([i ** 2 for i in range(1, nn + 1) if nn % i == 0])) def optimized_sum_square(n): sum = n ** 2 loop_count = 0 for i in range(1, n // 2 + 1): loop_count += 1 if n % i == 0: sum += i ** 2 print("loop_count %s" % loop_count) return sum if __name__ == '__main__': print(op_optimized_sum_square(1))
896d08e412e0081e9c9944932b87a513c054b447
Arseniy-Popov/DataStructures
/heap/heap.py
3,294
3.984375
4
from collections.abc import Container, Sized class Heap(Container, Sized): """ Priority queue implemented with the heap data structure. Allows for retrieval of the smallest element and insertions in O(logn) time, as well as constant time smallest element access. Ordering of the elements can be customized with the optional 'key' callable. Comparisons utilize the __lt__ method. Provides the .push, .peek, .pop, __len__, __contains__, and __repr__ methods. """ class _Item: """ Used to populate the underlying storage array with pairs of items and keys so that keys are cached. """ def __init__(self, item, key=None): self._item = item self._key = key def __lt__(self, other): if not self._key: return self._item < other._item return self._key < other._key def __init__(self, key=None): self._array = [] self._key = key or (lambda x: x) def __len__(self): return len(self._array) def __contains__(self, item): return any(x._item == item for x in self._array) def __repr__(self): return f"<Heap of lenght {len(self)}, min: {self.peek()}>" def push(self, item): self._array.append(self._Item(item, key=self._key(item))) self._restore_order_insertion() def peek(self): if not len(self): raise IndexError return self._array[0]._item def pop(self): result, self._array[0] = self.peek(), self._array[-1] self._array.pop() self._restore_order_deletion() return result # Non-public utilities def _index_valid(self, index): if index > len(self) - 1 or index < 0: return None return index def _left_child(self, index): return self._index_valid(index * 2 + 1) def _right_child(self, index): return self._index_valid(index * 2 + 2) def _parent(self, index): return self._index_valid((index - 1) // 2) def _item(self, index): return self._array[index] def _swap(self, index1, index2): self._array[index1], self._array[index2] = ( self._array[index2], self._array[index1], ) def _min_child(self, index): if self._left_child(index) is None and self._right_child(index) is None: return None elif self._right_child(index) is None: return self._left_child(index) else: return min( self._left_child(index), self._right_child(index), key=self._item ) def _restore_order_insertion(self): index = len(self._array) - 1 while self._parent(index) is not None and not self._item( self._parent(index) ) < self._item(index): self._swap(index, self._parent(index)) index = self._parent(index) def _restore_order_deletion(self): index = 0 while not ( self._min_child(index) is None or not self._item(self._min_child(index)) < self._item(index) ): min_child = self._min_child(index) self._swap(min_child, index) index = min_child
f3c146b6f76b4faa3744eac23b868b8274d893a6
Arseniy-Popov/DataStructures
/heap/test_heap.py
1,930
3.671875
4
import random import unittest from heap import Heap class TestHeap(unittest.TestCase): def setUp(self): self.heap = Heap() self.items = random.choices(range(100), k=30) def test_push_peek(self): items = [] for i in self.items: self.heap.push(i) items.append(i) self.assertEqual(min(items), self.heap.peek()) def test_peek(self): with self.assertRaises(IndexError): self.heap.peek() def test_pop(self): items = self.items for i in self.items: self.heap.push(i) for i in self.items: self.assertEqual(self.heap.pop(), min(items)) items.remove(min(items)) def test_len(self): n = 5 with self.subTest("push"): for i in range(n): self.heap.push(1) self.assertEqual(len(self.heap), i + 1) with self.subTest("peek"): self.heap.peek() self.assertEqual(len(self.heap), n) with self.subTest("pop"): for i in range(n): self.heap.pop() self.assertEqual(len(self.heap), n - i - 1) def test_contains(self): items = [] for i in self.items: self.heap.push(i) items.append(i) for j in items: self.assertEqual(j in self.heap, True) def test_repr(self): items = [] for i in self.items: self.heap.push(i) items.append(i) length, min_ = len(items), min(items) self.assertEqual(str(self.heap), f"<Heap of lenght {length}, min: {min_}>") def test_key(self): heap = Heap(lambda x: -x) items = [] for i in self.items: heap.push(i) items.append(i) self.assertEqual(heap.peek(), max(items)) if __name__ == "__main__": unittest.main()
e725914c01baf97942a3c581c40e62565bc84b08
ajitg9572/session2
/fomatting.py
151
4.53125
5
name="ajit" age= 23 # print("your name is {} your age is{}".format(name,age))python 3 # python 3.6 below print(f"your name is {name} your age is{age}")
cc58a433d0fa4283925a12288d958ab4ef4ec64d
ajitg9572/session2
/elif.py
225
4.03125
4
age=int(input("enter your age")) if 0<age<=3: print("ticket is free") elif 11<age<=20: print("your ticket price is 200") elif 21<age<=30: print("your tiket price is 300") else: print("your ticke price is 250")
e2ba3d2b834e092bd3675fbcf8dbe5c33a31f729
ajitg9572/session2
/hackerrank_prob.py
206
4.28125
4
#!/bin/python3 # declare and initialize a list fruits = ["apple","mango","guava","grapes","pinapple"] # pritning type of fruits print (type(fruits)) # printing value for fruit in fruits: print(fruit)
1ff664be7c0423695ad6b965d487c5fa57625bbc
ajitg9572/session2
/empty_or_not.py
110
3.9375
4
name=input("enter your name") if name: print("your name is",name) else: print("you not type anything")
6b0cf072761db21b90b5c474d20f42624eb2cd81
ajitg9572/session2
/test.py
290
4.03125
4
def odd_even(l): odd_num =[] even_num=[] for i in l: if i %2==0: even_num.append(i) else: even_num.append(i) output =[odd_num,even_num] return output num =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] print(odd_even(num))
7272a47b347604d33c2e3bcca50099c1976da126
gdof/Amadou_python_learning
/rock_paper_scissor/main.py
1,345
4.34375
4
import random # We are going to create a rock paper scissor game print("Do you want a rock, paper, scissor game?") # create a variable call user_input and port the user a Yes a No user_input = input("Yes or No? ") # if the user select no print out "It is sorry to see you don't want to play" if user_input == "no": print("It is sorry to see you don't want to play") # if the user select yes prompt the user for a input of rock paper sicssor elif user_input == "yes": """ Store the user input from this elif statment into a variable, set the variable name to user_choice using python create a words variable called "choice_list" that have three string ["rock", "paper", "sicssor"] import random using python random get a random choice from the list and store it in a varibles call random_choice compare the user choice and the random choice if the user choice match the random choice print aye you guess right else say guess again """ user_choice = input("select rock, paper, sicssor? ") choice_list = ["rock", "paper", "scissor"] random_choice = random.choice(choice_list) if user_choice == random_choice: print("aye you guess right") else: print("guess again") # else the user don't choice yes or no print out wrong input else: print("wrong input")
1ca78e25659ec812a01a9020871e603f54dd405c
Mzaba014/Hackerrank-Solutions
/30 Days of Code/day20_sorting.py
1,016
4.0625
4
''' Title : Sorting Subdomain : 30 Days of Code Domain : Python 3 Author : Manuel Zabala Created : 2/19/2019 Problem : https://www.hackerrank.com/challenges/30-sorting/problem ''' #!/bin/python3 def bubblesort(arr, n): num_swaps = 0 # Lead pointer iterates over full length for i in range(n): # Second pointer iterates to penultimate index for j in range(n - 1): # If the element to the left is greater than that to the right if arr[j] > arr[j + 1]: # Swap them arr[j], arr[j + 1] = arr[j + 1], arr[j] # Increase total swaps count num_swaps += 1 # Condition to break out if already sorted if not num_swaps: break print('Array is sorted in {} swaps.'.format(num_swaps)) print('First Element: {}'.format(arr[0])) print('Last Element: {}'.format(arr[-1])) n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) bubblesort(arr, n)
dcbf099c9ded9c2242211aea078d54cf1230a5ab
Mzaba014/Hackerrank-Solutions
/30 Days of Code/day15_linkedlists.py
1,204
3.890625
4
''' Title : Linked List Subdomain : 30 Days of Code Domain : Python 3 Author : Manuel Zabala Created : 2/19/2019 Problem : https://www.hackerrank.com/challenges/30-linked-list/problem ''' class Node: def __init__(self, data): self.data = data self.next = None class Solution: def display(self, head): current = head while current: print(current.data, end=' ') current = current.next def insert(self, head, data): node = Node(data) # Create new node to insert current = head # Begin iteration at head of list if current: # If the head is not None while current.next: # Iterate as long as there is a .next aka to end of list current = current.next # Once at the end (tail), insert the newly created node current.next = node else: # If the head is None, simply make the head the new node head = node return head # Return a reference to the first node in the list mylist = Solution() T = int(input()) head = None for i in range(T): data = int(input()) head = mylist.insert(head, data) mylist.display(head)
ea48fc2694ba9ff520544deebc14917870cb20af
Mzaba014/Hackerrank-Solutions
/30 Days of Code/day5_loops.py
425
3.5625
4
''' Title : Loops Subdomain : 30 Days of Code Domain : Python 3 Author : Manuel Zabala Created : 2/19/2019 Problem : https://www.hackerrank.com/challenges/30-loops/problem ''' #!/bin/python import math import os import random import re import sys def multiples(n): for i in range(1, 11): print('{} x {} = {}'.format(n, i, n * i)) if __name__ == '__main__': n = int(raw_input()) multiples(n)
dba34595bddb596bc07dfbfb97971d24fc406586
vikasb7/Data-Structures
/Shuffle String.py
543
3.75
4
''' Vikas Bhat Restored a Shuffled String Time Complexity o(N) ''' class Practice: def restoreString(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ lis = ["a"] * len(indices) for i in range(len(s)): lis[indices[i]] = s[i] ans = "" for i in lis: ans += i return ans if __name__=="__main__": vik=Practice() s = "asvik" indices = [3, 4, 0, 1, 2] print(vik.restoreString(s,indices))