blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
4e43fa920b2b5f733f1d80d7088e256d6831a8a4
Maxington20/Python-Udemy-Course
/BasicLessons/Tkinter-helloworld.py
293
3.703125
4
from tkinter import * # This imports everything from tkinter root = Tk() # object of tk class called root label1 = Label(root, text="Hello World") # object of label class, pass in root, and text to display label1.pack() root.mainloop() # causes window to only close when we tell it to
b7b32021faa1e5ab3441843e18a8f06d518a6704
WorryingWonton/Monopoly
/tiles.py
20,641
3.90625
4
import attr import monopoly import ownable_item from math import floor from auction import Auction class Structure(ownable_item.OwnableItem): """ My code will handle buying and selling Structures in the following ways: -Buying Structures: -The Option to buy a structure should only appear if the Player is able to place the structure on one of their tiles. -If two or more Players are able to build a structure, and the active player wishes (and is able) to buy a structure, AND the Bank only has one structure of that type left, then: -The structure shall be put up for auction. -This is probably best handled in complete_transaction() -Selling Structures: -Structures can be sold to other eligible Players -Eligibility meaning the Players can both afford to buy the Structure AND have properties which can be developed. -Other Notes: -Players cannot buy structures unless they have a property on which to put them. -This is so players cannot hoard structures -When the game starts (in Monopoly.run_game() specifically), the Bank has a list attribute filled with the following: -32 Houses -12 Hotels -4 Railroads -Modifications: -RailRoadTile and ColorTile will need to have their remove_structure() and build_structure() equivalent methods modified to accommodate the new changes. -Structues could also be unlimited, though for the time being it might not make sense to not implement this feature. With the rules now set, the trick is to figure out how to go about buying a selling Structures. The problem is that Structures need to be removed from a specific Tile and also placed on a specific Tile: -Structures do not know what Tile they're on. -This could be solved by adding a current_tile attribute. -Structure.current_tile would initially be set to None, then set to whatever Tile it's placed on. -If the Structure is sold to the Bank, then the attribute will be set to None again. -There currently is no way to set the current_tile atribute -The changes to enable this need to occur in the following places: -ColorTile.build_structure() and ColorTile.remove_structure() """ def __init__(self, type, price, rent, current_tile=None): self.type = type self.price = price self.rent = rent self.current_tile = current_tile def complete_transaction(self, buyer, seller, amount, game): """ :param Player buyer: :param Player seller: :param amount: :param game: :return: """ if self.price <= buyer.liquid_holdings: if seller == game.bank: pass def add_structure_to_tile(self, buyer): pass def remove_structure_from_tile(self, seller): pass @attr.s class Tile: position = attr.ib(type=int) def perform_auto_actions(self, game): pass def list_options(self, game): return [] def find_properties_of_other_players(self, game): property_tuples = [(list(filter(lambda tile: tile.list_sell_options(owner=player), player.property_holdings)), player) for player in list(filter(lambda player: player != game.active_player, game.players))] option_list = [] for n_tuple in property_tuples: for tile in n_tuple[0]: if tile.mortgaged: option_list.append(monopoly.Option(option_name=f'''Request to buy {tile.name} from {n_tuple[1].name} --- (Property deed price is {tile.price}) --- WARNING: Property IS Mortgaged''', action=tile.start_direct_buy_process, item_name=f'{tile.name}', category='buymortgagedproperty')) else: option_list.append(monopoly.Option(option_name=f'''Request to buy {tile.name} from {n_tuple[1].name} --- (Property deed price is {tile.price}) --- Property IS NOT Mortgaged''', action=tile.start_direct_buy_process, item_name=f'{tile.name}', category='buyownedproperty')) return option_list @attr.s class OwnableTile(Tile, ownable_item.OwnableItem): name = attr.ib(type=str) price = attr.ib(type=int) mortgage_price = attr.ib(type=int) base_rent = attr.ib(type=int) possible_structures = attr.ib(type=list) existing_structures = attr.ib(type=list, default=[]) mortgaged = attr.ib(type=bool, default=False) def perform_auto_actions(self, game): if self.mortgaged: return owner = self.find_owner(game=game) if owner == game.active_player or owner == game.bank: return else: self.assess_rent(owner=owner, game=game) def if_not_owned(self, active_player): buy_mortgage_option_list = [] if self.price <= active_player.liquid_holdings: buy_mortgage_option_list.append(monopoly.Option(option_name=f'Buy {self.name} at position: {self.position} for {self.price}', action=self.buy_property, item_name=self.name, category='buyunownedproperty')) if self.mortgage_price <= active_player.liquid_holdings: buy_mortgage_option_list.append(monopoly.Option(option_name=f'Mortgage {self.name} at position: {self.position} for {self.mortgage_price}', action=self.mortgage_property, item_name=self.name, category='mortgageunownedproperty')) buy_mortgage_option_list.append(monopoly.Option(option_name=f'Auction {self.name} at position: {self.position}', action=self.start_auction_process, item_name=self.name, category='auctionproperty')) return buy_mortgage_option_list def buy_property(self, game): game.active_player.liquid_holdings -= self.price game.active_player.property_holdings.append(self) game.bank.property_holdings.remove(self) def mortgage_property(self, game): game.active_player.liquid_holdings -= self.mortgage_price game.active_player.property_holdings.append(self) game.bank.property_holdings.remove(self) self.mortgaged = True def mortgage_owned_property(self, game): game.active_player.liquid_holdings += self.mortgage_price self.mortgaged = True def lift_mortgage(self, game): game.active_player.liquid_holdings -= 0.1*self.mortgage_price self.mortgaged = False def count_similar_owned_properties(self, owner): num_tiles = 0 for tile in owner.property_holdings: if type(self) == type(tile): num_tiles += 1 return num_tiles def list_sell_options(self, owner): """ :param Player owner: Player object who owns the tile :return list option_list: Returns either an empty list or a list containing an Option object which will start the direct sale process if chosen by the player """ if self.existing_structures: return [] option_list = [] option_list.append(monopoly.Option(option_name=f'Sell {self.name}', action=self.start_direct_sale_process, item_name=self.name, category='selltoplayer')) if self.mortgaged: if owner.liquid_holdings >= 0.1 * self.price + self.mortgage_price: option_list.append(monopoly.Option(option_name=f'Lift Mortgage on {self.name}', action=self.lift_mortgage, item_name=self.name, category='liftmortgage')) else: option_list.append(monopoly.Option(option_name=f'Mortgage {self.name} (Note: This will not permit you to develop {self.name} or enable you to charge rent on it)', action=self.mortgage_owned_property, item_name=self.name, category='mortgageownedproperty')) option_list.append(monopoly.Option(option_name=f'Sell {self.name} to the bank for {self.price / 2}', action=self.sell_to_bank, item_name=self.name, category='selltobank')) return option_list def sell_to_bank(self, game): """Sell to Bank removes an OwnableTile from a Player's property holdings and returns it to the Bank""" owner = self.find_owner(game=game) owner.liquid_holdings += self.price * 0.5 owner.property_holdings.remove(self) game.bank.property_holdings.append(self) def complete_transaction(self, buyer, seller, amount, game): if self.mortgaged: """This is a grey area in the rules. Normally, amount is just the deed price of the property, however the rules do not specify what happens if a mortgaged property is auctioned. Or if, for that matter, if a mortgaged property can be auctioned. I'm designing to the spec that a mortgaged property can be auctioned and the extra 10% assessed is based off the mortgage price.""" if amount + 1.1 * self.mortgage_price <= buyer.liquid_holdings: immediate_unmortgage_decision = game.interface.get_buy_and_lift_mortgage_decision(buyer=buyer, seller=seller, amount=amount, item=self) if immediate_unmortgage_decision: self.mortgaged = False amount = amount + 1.1 * self.mortgage_price else: amount = amount + 0.1*self.mortgage_price if buyer.liquid_holdings < amount: return game.run_bankruptcy_process(debtor=buyer, creditor=seller) seller.liquid_holdings += amount if self in seller.property_holdings: seller.property_holdings.remove(self) buyer.property_holdings.append(self) buyer.liquid_holdings -= amount def remove_structure(self, game): pass def assess_rent(self, owner, game): pass @attr.s class RailRoadTile(OwnableTile): def list_options(self, game): option_list = [] owner = self.find_owner(game=game) if owner == game.active_player: sell_options = self.list_sell_options(owner=owner) option_list += sell_options if sell_options and not self.mortgaged and owner.liquid_holdings >= self.possible_structures[0].price: option_list.append(monopoly.Option(option_name=f'Build Transtation at {self.name}', action=self.build_train_station, item_name=self.name, category='buildstructure')) if self.existing_structures: option_list.append(monopoly.Option(option_name=f'Sell Trainstation at {self.name} to the Bank for {0.5*self.existing_structures[0].price}', action=self.remove_structure, item_name=self.existing_structures[0].type, category='removestructure')) else: if owner == game.bank: option_list += self.if_not_owned(active_player=game.active_player) return option_list def assess_rent(self, owner, game): num_owned_railroads = self.count_similar_owned_properties(owner) multiplier = 1 if game.active_player.dealt_card: multiplier = 2 if self.existing_structures: rent = multiplier * self.existing_structures[0].rent * 2**(num_owned_railroads - 1) else: rent = multiplier * self.base_rent * 2**(num_owned_railroads - 1) if rent > game.active_player.liquid_holdings: game.run_bankruptcy_process(debtor=game.active_player, creditor=owner) else: owner.liquid_holdings += rent game.active_player.liquid_holdings -= rent def build_train_station(self, game): if game.active_player.liquid_holdings >= self.possible_structures[0].price: game.active_player.liquid_holdings -= self.possible_structures[0].price self.existing_structures.append(self.possible_structures[0]) def remove_structure(self, game): self.existing_structures = [] game.active_player.liquid_holdings += self.possible_structures[0].price @attr.s class UtilityTile(OwnableTile): def list_options(self, game): owner = self.find_owner(game=game) option_list = [] if owner == game.active_player: option_list += self.list_sell_options(owner=owner) else: if owner == game.bank: option_list += self.if_not_owned(active_player=game.active_player) return option_list def assess_rent(self, owner, game): num_owned_utilites = self.count_similar_owned_properties(owner) rent_assessed = 0 if num_owned_utilites == 1: rent_assessed = sum(game.dice_roll) * 4 if num_owned_utilites == 2: rent_assessed -= sum(game.dice_roll) * 10 if rent_assessed >= game.active_player.liquid_holdings: game.run_bankruptcy_process(debtor=game.active_player, creditor=owner) else: owner.liquid_holdings += rent_assessed game.active_player.liquid_holdings -= rent_assessed @attr.s class ColorTile(OwnableTile): color = attr.ib(type=str, default=None) def list_options(self, game): owner = self.find_owner(game=game) option_list = [] if owner == game.active_player: option_list += self.list_sell_options(owner=owner) + self.list_buildable_structures(game=game) + self.list_removable_structures(game=game) else: if owner == game.bank: option_list += self.if_not_owned(active_player=game.active_player) return option_list def assess_rent(self, game, owner): if not self.existing_structures: if self.is_color_group_filled(game=game): rent = 2 * self.base_rent else: rent = self.base_rent else: rent = self.existing_structures[-1].rent if rent > game.active_player.liquid_holdings: game.run_bankruptcy_process(creditor=owner, debtor=game.active_player) else: owner.liquid_holdings += rent game.active_player.liquid_holdings -= rent def list_buildable_structures(self, game): if self.is_color_group_filled(game=game): struct_tuples = [(tile, len(tile.existing_structures)) for tile in list(filter(lambda x: isinstance(x, ColorTile) and self.color == x.color and len(x.existing_structures) != len(x.possible_structures), game.active_player.property_holdings))] if not struct_tuples: return [] else: struct_counts = [x[1] for x in struct_tuples] option_list = [] for struct_tuple in struct_tuples: if struct_tuple[1] == min(struct_counts) and struct_tuple[0].possible_structures[struct_tuple[1]].price <= game.active_player.liquid_holdings and struct_tuple[0] == self: option_list.append(monopoly.Option(option_name=f'Build {struct_tuple[0].possible_structures[struct_tuple[1]].type} on {struct_tuple[0].name}', action=self.build_structure, item_name=struct_tuple[0].possible_structures[struct_tuple[1]], category='buildstructure')) return option_list else: return [] def is_color_group_filled(self, game): #Number of each colored tile color_group_dict = {'brown': 2, 'cyan': 3, 'pink': 3, 'orange': 3, 'red': 3, 'yellow': 3, 'green': 3, 'blue': 2} counter = 0 for tile in self.find_owner(game=game).property_holdings: if isinstance(tile, ColorTile) and tile.color == self.color: counter += 1 return color_group_dict[self.color] == counter def list_removable_structures(self, game): struct_tuples = [(tile, len(tile.existing_structures)) for tile in list(filter(lambda x: isinstance(x, ColorTile) and self.color == x.color and len(x.existing_structures) > 0, game.active_player.property_holdings))] if not struct_tuples: return [] else: struct_counts = [x[1] for x in struct_tuples] option_list = [] for struct_tuple in struct_tuples: if struct_tuple[1] == max(struct_counts) and struct_tuple[0] == self: option_list.append(monopoly.Option(option_name=f'Remove {struct_tuple[0].possible_structures[len(struct_tuple[0].existing_structures) - 1].type} on {struct_tuple[0].name}', action=self.remove_structure, item_name=struct_tuple[0].possible_structures[len(struct_tuple[0].existing_structures) - 1], category='removestructure')) return option_list def build_structure(self, game): game.active_player.liquid_holdings -= self.possible_structures[len(self.existing_structures)].price self.existing_structures.append(self.possible_structures[len(self.existing_structures)]) def remove_structure(self, game): game.active_player.liquid_holdings += self.possible_structures[len(self.existing_structures) - 1].price / 2 self.existing_structures.remove(self.existing_structures[-1]) @attr.s class UnownableTile(Tile): pass @attr.s class JailTile(UnownableTile): def list_options(self, game): option_list = [] if game.active_player.jailed: for card in game.active_player.hand: if card.name == 'Get out of Jail Free': option_list.append(monopoly.Option(option_name=f'Use {card.name} card from {card.parent_deck}', action=card.action, item_name=card.name, category='useheldcard')) if game.active_player.liquid_holdings >= 50: option_list.append(monopoly.Option(option_name='Pay Jail Fine ($50)', item_name=None, action=self.pay_jail_fine, category='payjailfine', ends_turn=True)) if game.active_player.position != self.position: option_list += game.board[game.active_player.position].list_options(game=game) return option_list def perform_auto_actions(self, game): if game.active_player.jailed: if game.active_player.jailed_turns < 3: if game.check_for_doubles(): game.active_player.jailed_turns = 0 game.active_player.jailed = False game.active_player.advance_position(amount=sum(game.dice_roll)) game.board[game.active_player.position].perform_auto_actions(game=game) game.end_current_turn() else: game.active_player.jailed_turns += 1 else: self.pay_jail_fine(game=game) def pay_jail_fine(self, game): game.active_player.liquid_holdings -= 50 if game.active_player.liquid_holdings < 0: self.game.run_bankruptcy_process(debtor=game.active_player, creditor=game.bank) else: game.active_player.jailed_turns = 0 game.active_player.jailed = False game.active_player.position = sum(game.roll_dice()) game.board[game.active_player.position].perform_auto_actions(game=game) game.end_current_turn() @attr.s class CardTile(UnownableTile): pass @attr.s class ChanceTile(CardTile): def perform_auto_actions(self, game): game.chance_deck.deal_from_deck(game=game) if game.active_player.dealt_card: game.active_player.dealt_card.consume_card(game=game) @attr.s class CommunityChestTile(CardTile): def perform_auto_actions(self, game): game.community_deck.deal_from_deck(game=game) if game.active_player.dealt_card: game.active_player.dealt_card.consume_card(game=game) @attr.s class GoToJailTile(UnownableTile): def perform_auto_actions(self, game): game.active_player.go_directly_to_jail() game.board[game.active_player.position].perform_auto_actions(game=game) @attr.s class LuxuryTaxTile(UnownableTile): def perform_auto_actions(self, game): if game.active_player.liquid_holdings >= 75: game.active_player.liquid_holdings -= 75 else: game.run_bankruptcy_process(creditor=game.bank, debtor=game.active_player) @attr.s class FreeParking(UnownableTile): pass @attr.s class IncomeTaxTile(UnownableTile): def perform_auto_actions(self, game): gross_worth = game.active_player.calculate_taxable_assets() if gross_worth <= 2000: game.active_player.liquid_holdings -= floor(.1 * gross_worth) else: game.active_player.liquid_holdings -= 200 @attr.s class GoTile(UnownableTile): def perform_auto_actions(self, game): game.active_player.pass_go()
28c6b1981327cbb56e65d23ac856c8205739ffb6
rouemma1/dd-adapter-exercice
/sdk/eventlogger.py
735
3.546875
4
class StringEvent(object): def __init__(self, msg, timestamp): """ :param msg (string): A message that happened :param timestamp (int): The time at which this message happened """ self.timestamp = timestamp self.msg = msg class EventLogger(object): """ EventLogger will write into the event buffer the events it receives. """ def receive(self, event): if not isinstance(event.timestamp, int): raise ValueError("timestamp must be an integer") if not isinstance(event.msg, str): raise ValueError("msg must be an integer") print("Event : {} : {}".format( event.timestamp, event.msg) )
55d72af9652fd818c96f237767bffe4c70b5073d
VishalGohelishere/Python-tutorials-1
/programs/gcd.py
303
4.09375
4
# GCD is we take two numbers and check that the highest number which divides both the values is called as GCD v1 = input("Enter 1st value ") v2 = input("Enter 2nd value ") v1 = int(v1) v2 = int(v2) i=1 while i<v1 and i<v2: if v1%i==0 and v2%i==0: gcd = i i = i+1 print("GCD is ",gcd)
cf25197bdec395ea48e7481dabdda10b09accd53
wesenu/Data-Structures-2
/Data Hiding.py
614
3.78125
4
''' class Demo: def __init__(self,v): self._tu = v self.__tum = 20 #hidden obj = Demo(10) print(obj._tu) #print(obj.__tum) #We can print hidden variables print(obj._Demo__tum) #Fully qualified name (FQN) ''' ''' class SEQ: _x = 949 #static member __h = 666 #static. hidden def __init__(self): self.__a = 100 #private Instance Variable @staticmethod def bar(): print(obj._SEQ__h)#1 ; FQN print(SEQ.__h)#2 print(obj.__h)#3 obj = SEQ() obj.bar() print(obj._x) print(obj.__dict__) #Name Mangling '''
cfc49875f4f2d91fe2947ccb82494f39ef893dfb
EduChancafe/T08_Chancafe.carrion
/longitud.py
1,569
3.546875
4
#ejercicio1 nombre="eduardo" longitud=len(nombre) print("la longitud de la cadena es :",longitud) #ejercicio2 apellido="chancafe" longitud=len(apellido) print("la longitud de la cadena es:",longitud) #ejercicio3 deporte="futbol" longitud=len(deporte) print("la longitud de la cadena es:",longitud) #ejercicio4 curso="programacion" longitud=len(curso) print("la longitud de la cadena es:",longitud) #ejercicio5 enamorada="" longitud=len(enamorada) print("la longitud de la cadena es:",longitud) #ejercicio6 cancion="desconocidos" longitud=len(cancion) print("la longitud de la cancion es:",longitud) #ejercicio7 marca=" ADIDAS " longitud=len(marca) print("la longitud de la cadena es:",longitud) #ejercicio8 operacion=" iteracion" longitud=len(operacion) print("la longitud de la cadena es:",longitud) #ejercicio9 hotel="´Casa Andina´" longitud=len(hotel) print("la longitud de la cadena es:",longitud) #ejercicio10 deporte="voley/playa" longitud=len(deporte) print("la longitud de la cadena es:",longitud) #ejercicio11 operador="claro " longitud=len(operador) print("la longitud de la cadena es:",longitud) #ejercicio12 cantante="´Bruno Mars´" longitud=len(cancion) print("la longitud de la cadena es:",longitud) #ejercicio13 electrodomestico="lavadora " longitud=len(electrodomestico) print("la longitud de la cadena es:",longitud) #ejercicio14 codigo=" 195695D " longitud=len(codigo) print("la longitud de la cadena es:",longitud) #ejercicio15 profesor="FRANK CHIRINOS" longitud=len(profesor) print("la longitud de la cadena es:",longitud)
1b02e74940d6979bfbf21442423e9131dc359e43
dinuionica08/Projects.py
/Basics/operators.py
310
4.40625
4
# arithmetic operators print (1 + 2) print (1 - 2) print (1 * 2) print (1 / 2) print (1 ** 2) print ( 1 % 2) # logical operators if 2 == 2 and 3 > 1: print("True") if 2 == 2 or 3 == 3: print("True") if not (2 < 3): print("False") #comparation operator if 4 < 2 : print("4 is the greater")
798595f5a595150edbe5c9496c45c5ad4d412822
dwhagar/AveryThesisProcessor
/speaker/speaker.py
2,237
3.8125
4
from .age import Age class Speaker: """A class to store information about a speaker.""" def __init__(self, sid = None, role = None, name = None, sex = None, age = None, language = None): self.sid = sid.strip() self.role = role.replace("_", " ").strip() # Some names are not filled in, replace with the role of the person. if name is None: name = self.role self.name = name.strip() if not sex is None: self.sex = sex.strip() else: self.sex = "unknown" if not language is None: self.language = language.strip() self.adult = False self.sibling = False if not age is None: self.age = Age(age) if self.age.decimal >= 18: self.adult = True else: self.age = Age(999) self.adult = True if self.sid == "BRO" or self.sid == "SIS": self.sibling = True def check_speaker(self, speaker_data): """Checks to see if a Speaker is the same as this Speaker.""" if speaker_data.role == self.role\ and speaker_data.name == self.name\ and speaker_data.age.decimal == self.age.decimal\ and speaker_data.sex == self.sex: return True else: return False def data_out(self): """Output the data as a dictionary.""" result = { "sid":self.sid, "role":self.role, "name":self.name, "sex":self.sex, "adult":self.adult, "lang":self.language, "age":self.age.decimal } return result def match_speaker(speaker_list, speaker_ID): """ Checks for a speaker ID against a list of Speaker objects and returns the matching Speaker object, or None Type if not found. :param speaker_list: A list of Speaker objects to search :param speaker_ID: The ID of the speaker being looked for :return: A Speaker object matching the ID or None Type if not found """ result = None for s in speaker_list: if s.sid == speaker_ID: result = s break return result
dcd7cbac66a820aeddf02e430bdbde80af351a9c
lokendra7512/Project-Euler-Solutions
/problem_30.py
437
3.625
4
''' 4*(9**5) = 236196 5*(9**5) = 295245 6*(9**5) = 354394 7*(9**5) = 413343 #So the highest possible sum of a 7-digit no is 6 digits (which is less than the original 7 digit no) so the upper limit is 6 ''' def sum_powers(n,power): sums = 0 while n > 0: remainder = n % 10 n = n / 10 sums = sums + (remainder ** power) return sums print sum(n for n in xrange(2,354394) if sum_powers(n,5) == n)
e63262cb548ff309671c4dc7e5d147b37ee30bfb
marcelo-py/Exercicios-Python
/exercicios-Python/desaf105.py
474
3.5625
4
def notas(*n, sit = False): notas = dict() notas['total'] = len(n) notas['maior'] = max(n) notas['menor'] = min(n) notas['média'] = sum(n)/len(n) if sit: if notas['média'] >= 7: notas['situação'] = 'Boa' if notas['média'] >= 5: notas['situação'] = 'Razoável' else: notas['situção'] = 'Péssimo' return notas #Programa Princiapal resp = notas(4, 5, 5, sit = True ) print(resp)
401d9f8aa09b89dc7fdf298bdafd773774fdfca5
vc2000/python-pandas-basic
/ud-101.py
622
3.9375
4
import pandas df1 = pandas.read_csv("supermarkets.csv") df1 = df1.set_index("Address") #print(df1) #df1_lim =df1.loc["735 Dolores St":"1056 Sanchez St","ID":"City"] #print(df1_lim) #df1_intercep = df1.loc["1056 Sanchez St","State"] #print(df1_intercep) """ #only want everything in country df1_USA = df1.loc[:,"Country"] print(df1_USA) #convert everything to a list lis_usa = list(df1.loc[:,"Country"]) print(lis_usa) """ """ #row , column #row = 735 to3995 #column = City to Country df1 = df1.iloc[1:3,1:3] print(df1) """ #index 3 , Name df1 = df1.ix[3,"Name"] print(df1)
6f000685064cf3e9b58ccde393b7be69e0390db3
Vivianhuan/Python
/data/sitka_deathvalley_comparison.py
1,725
3.515625
4
import csv from datetime import datetime def get_weather_data(filename,dates,highs,lows,date_index,high_index,low_index): with open (filename) as f: reader = csv.reader(f) header_row = next(reader) for row in reader: current_date = datetime.strptime(row[date_index],'%Y-%m-%d') try: high = int(row[high_index]) low = int(row[low_index]) except ValueError: print(f"Missing the value of {current_date}") else: dates.append(current_date) highs.append(high) lows.append(low) import matplotlib.pyplot as plt # Get weather data for Sitka filename = '/Users/Vivian/Desktop/python_work/data/sitka_weather_2018_simple.csv' dates, highs, lows = [],[],[] get_weather_data(filename,dates,highs,lows,date_index=2,high_index=5,low_index=6) plt.style.use('seaborn') fig,ax = plt.subplots() ax.plot(dates,highs,c='red', alpha = 0.6) ax.plot(dates,lows,c='green', alpha = 0.6) plt.fill_between(dates, highs, lows, facecolor = 'red', alpha = 0.15) # Get weather data for Death Valley filename = '/Users/Vivian/Desktop/python_work/data/death_valley_2018_simple.csv' dates, highs, lows = [],[],[] get_weather_data(filename,dates,highs,lows,date_index=2,high_index=4,low_index=5) # Add Death Valley data to current plot. ax.plot(dates,highs,c='yellow', alpha = 0.6) ax.plot(dates,lows,c='blue',alpha = 0.6) plt.fill_between(dates, highs, lows, facecolor = 'blue', alpha = 0.15) # Format plot title = "Daily Rainfall Amounts - 2018\nSitka in AK V.S. Death Valley in CA" plt.title(title, fontsize = 26) plt.xlabel('', fontsize = 16) fig.autofmt_xdate() plt.ylabel("Temperature (F)", fontsize = 16) plt.tick_params(axis = 'both',which='major',labelsize = 16) plt.ylim(10,130) plt.show()
bbb4bd252024758f166f12b814e2311e1124c863
SirSilver/crocobot
/game.py
6,087
3.59375
4
import random import sqlite3 class Game: def __init__(self, dbfile): self.connection = sqlite3.connect(dbfile) self.cursor = self.connection.cursor() self.create_tables() self.words_file = 'categories/words.txt' self.celebrities_file = 'categories/celebrities.txt' self.movies_file = 'categories/movies.txt' def create_tables(self): with self.connection: self.cursor.executescript(""" CREATE TABLE IF NOT EXISTS players( id INTEGER NOT NULL UNIQUE PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS chats( id INTEGER NOT NULL UNIQUE PRIMARY KEY, name TEXT NOT NULL, categories TEXT DEFAULT "movies celebrities general", speaker INTEGER, correct_word TEXT, in_play INTEGER NOT NULL DEFAULT 0, FOREIGN KEY (speaker) REFERENCES players(id) ); CREATE TABLE IF NOT EXISTS scores( chat_id INTEGER NOT NULL, player_id INTEGER NOT NULL, score INTEGER NOT NULL DEFAULT 0, FOREIGN KEY (chat_id) REFERENCES chats(id), FOREIGN KEY (player_id) REFERENCES players(id))""") def player_exists(self, player_id): if self.get_player_name(player_id) is None: return False return True def chat_exists(self, chat_id): if self.get_chat_name(chat_id) is None: return False return True def score_exists(self, chat_id, player_id): if self.get_score(chat_id, player_id) is None: return False return True def add_player(self, player_id, player_name): with self.connection: self.cursor.execute('INSERT INTO players (id, name) VALUES (?,?)', (player_id, player_name)) def add_chat(self, chat_id, chat_name): with self.connection: self.cursor.execute('INSERT INTO chats (id, name) VALUES (?,?)', (chat_id, chat_name)) def add_score(self, chat_id, player_id): with self.connection: self.cursor.execute('INSERT INTO scores (chat_id, player_id) VALUES (?,?)', (chat_id, player_id)) def get_player_name(self, player_id): result = self.cursor.execute('SELECT name FROM players WHERE id = ?', (player_id,)).fetchone() if result is None: return None return result[0] def get_chat_name(self, chat_id): result = self.cursor.execute('SELECT name FROM chats WHERE id = ?', (chat_id,)).fetchone() if result is None: return None return result[0] def get_chat_categories(self, chat_id): result = self.cursor.execute('SELECT categories FROM chats WHERE id = ?', [chat_id]).fetchone() if result is None: return None return result[0].split() def edit_chat_category(self, chat_id, category, action): categories = self.get_chat_categories(chat_id) if action == 'add': categories.append(category) else: categories.remove(category) with self.connection: self.cursor.execute('UPDATE chats SET categories = ? WHERE id = ?', (' '.join(categories), chat_id)) def get_speaker_id(self, chat_id): result = self.cursor.execute('SELECT speaker FROM chats WHERE id = ?', (chat_id,)).fetchone() if result is None: return None return result[0] def get_speaker_name(self, chat_id): result = self.get_player_name(player_id=self.get_speaker_id(chat_id)) return result def set_speaker(self, chat_id, speaker_id): with self.connection: self.cursor.execute('UPDATE chats SET speaker = ? WHERE id = ?', (speaker_id, chat_id)) def get_correct_word(self, chat_id): result = self.cursor.execute('SELECT correct_word FROM chats WHERE id = ?', (chat_id,)).fetchone() if result is None: return None return result[0] def set_correct_word(self, chat_id): WORDS = [] categories = self.get_chat_categories(chat_id=chat_id) if 'celebrities' in categories: WORDS += open(self.celebrities_file).read().splitlines() if 'movies' in categories: WORDS += open(self.movies_file).read().splitlines() if 'general' in categories: WORDS += open(self.words_file).read().splitlines() correct_word = random.choice(WORDS) with self.connection: self.cursor.execute('UPDATE chats SET correct_word = ? WHERE id = ?', (correct_word, chat_id)) def get_score(self, chat_id, player_id): result = self.cursor.execute('SELECT score FROM scores WHERE chat_id = ? AND player_id = ?', (chat_id, player_id)).fetchone() if result is None: return None return result[0] def get_score_table(self, chat_id): result = [] players = self.cursor.execute('SELECT * FROM scores WHERE chat_id = ? ORDER BY score DESC', (chat_id,)).fetchmany(10) for player in players: player_name = self.get_player_name(player[1]) player_score = player[2] result.append([player_name, player_score]) return result def increase_score(self, chat_id, player_id): with self.connection: self.cursor.execute('UPDATE scores SET score = score + 1 WHERE chat_id = ? AND player_id = ?', (chat_id, player_id)) def in_play(self, chat_id): if self.cursor.execute('SELECT in_play FROM chats WHERE id = ?', (chat_id,)).fetchone()[0] == 1: return True return False def change_state(self, chat_id, state): with self.connection: self.cursor.execute('UPDATE chats SET in_play = ? WHERE id = ?', (state, chat_id))
c7bb3801635cdf2e2db0de322819cfbed38b89da
oylumseriner/Codes
/python exercise6 (Ackermann Function).py
544
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #We try to compute the Ackermann Function A(m,n) with m,n. Now, we can use the this formula: #if m=0,then use n+1 #if m>0 and n=0, then use A(m-1,1) #if m>0 and n>0, then use A(m-1,A(m,n-1)) def A(m,n): if m == 0: return (n+1) elif m > 0 and n == 0: return(A(m-1,1)) elif m > 0 and n > 0: return (A(m-1 , A(m,n-1))) m = int(input("Enter number of elements for m : ")) n = int(input("Enter number of elements for n : ")) print("A({})=".format((m,n)),A(m,n))
97a36c47f899388dc0ff134b4b63b301cb265b2a
M-Amin-Mamdouhi/python-class
/Ex 7.py
1,335
4
4
'012' a=input('please enter your first number: ') b=input('please enter your second number: ') if a>b: print(a,b) else: print(b,a) '013' a=int(input('please enter your number: ')) if a<20: print('thank you') else: print('too much') '014' a=int(input('please enter your number: ')) if a<=20 and a>=10: print('thank you') else: print('incorrect answer') '015' a=input('please enter your favorite colour: ') if a.upper()=='RED': print('I like red too') else: print('I dont like ' + a + ',I prefer red') '016' a=input('is it raining? ').lower() if a=='yes': b=input('is it windy? ').lower() if b=='yes': print('its too windy for an umbrella') else: print('take an umbrella') else: print('enjoy your day') '017' a = int(input('please enter your age: ')) if a>=18: print('you can vote') elif a==17: print('you can drive') elif a==16: print('you can buy a lottery ticket') else: print('you can go trick or treating') '018' a = int(input('please enter your number: ')) if a<10: print('too low') elif a>=10 and <=20: print('correct answer') else: print('too high') '019' a = int(input('please enter your number: ')) if a==1: print('Thank you') elif a==2: print('well done') elif a==3: print('correct') else: print('Error message')
5a7af9626f1d5e84e382e8226461f3ffd6715a52
ram5550/Luminardjango
/Luminarproject/flowcontrols/maximumnumber.py
185
4.15625
4
num1=int(input("enter num1")) num2=int(input("enter num2")) if(num1>num2): print("num1 is maximum") elif(num2>num1): print("num2 is maximum") else: print("both are equal")
946ec975c2641f08318d4c7be3090eeb2f67b037
chiheblahouli/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
237
3.640625
4
#!/usr/bin/python3 """ checks if the object is an instance of, or if the object is an instance """ def inherits_from(obj, a_class): """ returns true if object is a subclass of a class """ return(issubclass(type(obj), a_class))
2b224a6004b8f26b68c8d14867ecb60c5e156591
davidknoppers/interview_practice
/dynamic_programming/coin_change.py
1,389
4.28125
4
#!/usr/bin/python3 """ Computes the total number of ways a value can be made with the given coins It is assumed that there are infinite coins for each given denomination Not properly tested for coin lists which exclude 1-cent coins @coins is a list of coin denominations and @value is the $ value you're making change for """ def coin_change(coins, value): coins = sorted(coins) print("finding number of ways to make value: {}\nwith coin array: {}".format(value, coins)) #sort coins to ensure DP algorithm can build on previous calculations as expected result = [1] #initialize list with 1 way to have 0 cents for i in range(value - 1): result.append(0) #use append to increase the list to desired size and ensure that list indexing works properly for i in range(len(coins)): for j in range(1, value): if j >= coins[i]: result[j] += result[j - coins[i]] #only add solutions if the coin is smaller than the value, e.g. we're at 7 and the coin is 5 print("coin totals for max coin {}: {}".format(coins[i], result)) #print at each step to see solution array for given value. List[value] = number of solutions return ("Number of ways to make value {} with given coins is: {}".format (value, result[value - 1])) #because list indexing requires us to count from 0 print(coin_change([1, 2, 3, 4, 5], 8))
46fbdc21b1eea9838e48eb4651634412ec6e3d2b
Newester/MyCode
/Py/Python/Debug.py
980
3.96875
4
#!/usr/bin/env python3 #使用 print 将变量打印出来,简单粗暴 def foo(s): n = int(s) print('>>> n = %d ' % n) return 10 / n def main(): foo('0') #main() #使用断言 assert #如果断言失败会抛出 AssertionError def foo_2(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main_2(): foo('0') #main_2() #可以使用 -0 参数关闭 assert # python3 -0 Debug.py # logging ,不会抛出错误,还能输出到文件 import logging logging.basicConfig(level=logging.INFO) s = '0' n = int(s) logging.info('n = %d' % n) #print(10 / n) # logging 的级别 debug 、info 、warning 、error #只有配置的级别以及高于配置的级别才有效 # pdb python 的调试器 # python3 -m pdb Debug.py # l 显示代码 # 输入代码转到该行 # n 单步执行 # p 查看变量名 # c 继续运行 # q 退出执行 # 设置断点 import pdb s = '0' n = int(s) pdb.set_trace() print(10 / n) # IDE vscode,pycharm
99f0171f860694ccdd16715b8df6e419a363ae26
Madhupreetha98/Python-Programming
/Beginner Level/prime range.py
143
3.703125
4
start=int(input()) end=int(input()) for num in range(start,end+1): if num>1: for i in range(2,num): if num%i==0: break else: print(num)
5bc96feabc3696f00e7b60bb3a33713e3a4d22a9
iamOuko/pythonbasics
/numbers.py
281
3.6875
4
from math import * print(2) print(2.97) print(3 + 4.5) print(3 * 4 + 5) print(10 % 3) my_num = -5 print(my_num) print(str(my_num) + " my favorite number.") print(abs(my_num)) print(pow(4, 2)) print(max(4, 6)) print(min(7, 5)) print(round(3.7)) print(floor(3.7)) print(sqrt(36))
bb5d8b13189a9f773a610fc8b2760afe8a62352e
github5507/geeksforgeeks
/intro_to_tensorflow/basic1.py
385
3.6875
4
# importing tensorflow import tensorflow as tf # creating nodes in computation graph node1 = tf.constant(3, dtype=tf.int32) node2 = tf.constant(5, dtype=tf.int32) node3 = tf.add(node1, node2) # create tensorflow session object sess = tf.Session() # evaluating node3 and printing the result print("Sum of node1 and node2 is:",sess.run(node3)) # closing the session sess.close()
c13f91578b17836fc193b32aa282aa63761974b6
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex03fp.py
1,090
4.21875
4
# statement print "I will now count my chickens:" #statement, followed by math (order of operations places multiplication BEFORE additon) print "Hens", 25 + 30 / 6 #statement, followed by math (order of operations places multiplication & modulo BEFORE subtraction #reading from left to right, multiplication comes first #4 goes into 75(25*3) 18 times (72), so the remainder(modulo) is 3 (75-72) #100 - 3 = 97 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" #modulo and multiplication take priority #2 goes into 4 evenly, meaning modulo is zero #1/4 is 0.25 but since this is not floating point it is rounded down to zero #6-5=1 .... 1+0-0+6=7 #making 1 into 1.0 will show the correct answer of 6.75 print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" #5 is not less than -2 print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > - 2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
34b32c1ea8146aae5b6cc1755b5ecd1376897a49
thomas-hennessy-work/python-exercizes
/easy/isbn.py
976
3.8125
4
isbn = input("Please input the first 12 digits of the ISBN \n") isbnList = [] isbnListClean =[] total = int(0) count = int(-1) # https://www.geeksforgeeks.org/python-split-string-into-list-of-characters/ isbnList = [char for char in isbn] # for x in isbnList: # if x != "-": # if int(x)%2 == 0: # print(str(x) + " is even") # print("add " + str(x)) # total = total + int(x) # print("total is " + str(total)) # else: # print(str(x) + " is odd") # print("add " + str(int(x)*3)) # total = total + (int(x)*3) # print("total is " + str(total)) for x in isbnList: if x != "-": isbnListClean.append(x) for y in isbnListClean: count += 1 if (int(count%2) == 0): total += int(y) print(total) else: total += int(int(y)*3) print(total) total = (10 - (total%10)) print("The last digit will be " + str(total))
fb897fb0f89a729e8aef9ec9a2caa805620f2385
hse-labs/PY111-template
/Tasks/f0_binary_search_tree.py
1,060
3.78125
4
""" You can do it either with networkx ('cause tree is a graph) or with dicts (smth like {'key': 0, value: 123, 'left': {...}, 'right':{...}}) """ from typing import Any, Optional, Tuple # import networkx as nx def insert(key: int, value: Any) -> None: """ Insert (key, value) pair to binary search tree :param key: key from pair (key is used for positioning node in the tree) :param value: value associated with key :return: None """ print(key, value) return None def remove(key: int) -> Optional[Tuple[int, Any]]: """ Remove key and associated value from the BST if exists :param key: key to be removed :return: deleted (key, value) pair or None """ print(key) return None def find(key: int) -> Optional[Any]: """ Find value by given key in the BST :param key: key for search in the BST :return: value associated with the corresponding key """ print(key) return None def clear() -> None: """ Clear the tree :return: None """ return None
3ddc01fc256f29865f3b45678309113313c90fbd
cyh1582081321/python_fuxi
/闰年.py
398
3.875
4
''' 闰年的判断 ''' year = int(input('请输入要判断的年份:')) if year%4 == 0: if year%100 == 0: if year%400 == 0: print("您要查询的年份是闰年!!") else : print("您查询的年份是平年!!") else : print("您要查询的年份是闰年!!") else : print("您查询的年份是平年!!")
60933470da20830620ad8b6e20223c360cb79827
jihye-woo/algorithm-practice
/sort/K번째수.py
298
3.515625
4
def solution(array, commands): answer = [] for i, j, k in commands: target_array = [] for idx in range(i - 1, j): target_array.append(array[idx]) target_array.sort() kth_num = target_array[k - 1] answer.append(kth_num) return answer
28a5568242905f7877d745686d940306cd1385f8
dimasiklrnd/python
/highlighting numbers, if, for, while/List of squares.py
890
4.15625
4
'''По данному натуральному числу N распечатайте все квадраты натуральных чисел, не превосходящие N , в порядке возрастания. ВАЖНО! В данной задаче необходимо использовать цикл. Формат входных данных На вход программе передается целое число N , не превышающее 10000. Формат выходных данных Программа должна распечатать последовательность чисел в порядке возрастания. В качестве разделителя используется побел.''' x = int(input()) if x <= 10000: for i in range(1, (x+1)): i = i**2 if i <= x: print(str(i) + ' ', end='')
8cf16623f31c94326d903ff73caeb78a3acb4bf4
offero/algs
/inversioncount.py
2,061
3.9375
4
""" Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3. """ from binary_indexed_tree import BIT def three_inversions_ctlower(arr): """ Count the number of 3 inversions by counting the number of elements lesser than each element. Time: O(n^2) Extra storage: O(n) """ ct = 0 less = [0] * len(arr) # reverse iteration for i in range(len(arr)-1, -1, -1): for j in range(len(arr)-1, i-1, -1): if arr[j] < arr[i]: less[i] += 1 ct += less[j] return ct def values_to_indices(arr): """For each element of the input list, replace it with it's index position in the sorted version of the input list. This maintains the inversion relationships and turns the list into all positive integers. Pseudocode: arr[i] = indexof(sorted(arr), i) Running time: O(n*log(n)) dominated by the sort Extra space: O(n) """ idxarr = [0] * len(arr) sorted_array = sorted(arr) idxs = {} for i, val in enumerate(sorted_array): if val not in idxs: idxs[val] = i for i, val in enumerate(arr): idxarr[i] = idxs[val] idxs[val] += 1 return idxarr def inversion_count_bit(arr): """Counts the number of 2-inversions using a Binary Indexed Tree""" iarr = values_to_indices(arr) n = len(arr) bit = BIT(n=n) invs = 0 for i in range(n-1, -1, -1): bitidx = iarr[i]+1 bit.update_value(bitidx, 1) print (bit._bit) invs += bit.get_sum(bitidx-1) return invs def test_1(): examples = [ ([5, 1, 2, 4, 2, 1], 5), ([5, 1, 3, 2, 1], 4), ([8, 4, 2, 1], 4), ([9, 6, 4, 5, 8], 2), ] for arr, exp in examples: res = three_inversions_ctlower(arr) if res != exp: print("Failed example: %s expected %d got %d" % (arr, exp, res)) if __name__ == "__main__": test_1()
9db4e984fbcb644f2770dd4e71bbf634e607d71c
mihir20/HackerRank-algo
/catAndMouse.py
559
3.734375
4
#!/bin/python3 import sys def greaterOF( a, b ): if a>b: return a else: return b def catAndMouse(x, y, z): ac = greaterOF(x-z,z-x) bc = greaterOF(y-z,z-y) if ac == bc : return "Mouse C" elif ac > bc: return "Cat B" else: return "Cat A" if __name__ == "__main__": q = int(input().strip()) for a0 in range(q): x, y, z = input().strip().split(' ') x, y, z = [int(x), int(y), int(z)] result = catAndMouse(x, y, z) print ("".join(map(str, result)))
4454863977c63df6e4358172d51c43dfaa23ca78
DonkeyZhang/Python
/stage1/day02/game2.py
971
3.90625
4
#-*-coding:utf-8-*- # way01: import random all_choice = ['石头', '剪刀', '布'] win_list = [['石头','剪刀'], ['剪刀','布'],['布', '石头']] computer = random.choice(all_choice) player = input('请出拳(石头/剪刀/布):') print(('你出拳: %s , 电脑出拳: %s') % (player, computer)) if computer == player: print('平局') elif [player, computer] in win_list: print('YOU WIN!') else: print('YOU LOSE!') #way02: import random all_choice = ['石头', '剪刀', '布'] win_list = [['石头','剪刀'], ['剪刀','布'],['布', '石头']] prompt=""" (0)石头 (1)剪刀 (2)布 Please input your choice(0/1/2):""" # 提示预定义变量 computer = random.choice(all_choice) #电脑取值 ind = int(input(prompt)) player =all_choice[ind] print(('你出拳: %s , 电脑出拳: %s') % (player, computer)) if computer == player: print('平局') elif [player, computer] in win_list: print('YOU WIN!') else: print('YOU LOSE!')
b53ef35c271b457020ec88022cf1e2b112256485
SamyakLuitel/Data_Structure_and_Algorithms
/Groking 's Algorithms/Chapter1/binarySearch.py
433
3.875
4
def binary_search(arr, item): '''This function returns position of item in the list if found''' low = 0 high = len(arr)-1 while low <= high: mid = (low+high)//2 guess = arr[mid] if guess == item: return mid if guess < item: low = mid else: high = mid return None l = [i*3 for i in range(10000)] ans = binary_search(l, 300) print(ans)
512b9c0b288e922fb210f70e4784ae6d687cbfda
Zatyi94/gyakorlas
/3.py
430
4.09375
4
# készíts programot ami kettő számot kér be és abból egy két dimenziós listát csinál # pl: 2,3 -> [[0,1,2], [0,1,2]] outer_list_length = int(input('ird be az elso szamot: ')) inner_list_length = int(input('ird be a masodik szamot: ')) nums = [] inner_nums = [] for num in range(0, inner_list_length): inner_nums.append(num) for num in range(0, outer_list_length): nums.append(inner_nums) print(nums)
e0ef267f32a3c5008ad3d8e4dfc04981691db5b6
dacharat/python-practice
/code/ox_game/main.py
338
3.640625
4
from player import Player from table import Table size = int(input('Enter table size: ')) nb_of_players = int(input('Enter number of players: ')) sym_list = [input(f'Enter player{i+1} symbol: ') for i in range(nb_of_players)] table = Table(size, nb_of_players, sym_list) who_win = table.play() print(f'Player"{who_win}" win!!')
93397fe881721e3554aa13c557ba82daa8e5b480
Ronak912/Programming_Fun
/Bloomberg/SortStringByFrequency.py
428
4
4
#Give a string like "BBBCADDDD", return "DDDDBBBCA" with characters sorted by frequency. def sortByFrequency(instr): hashmap = {} for char in instr: hashmap[char] = hashmap.get(char, 0) + 1 outstr = '' for key, value in sorted(hashmap.items(), key=lambda x: x[1], reverse=True): outstr += key * value return outstr if __name__ == "__main__": print sortByFrequency('EEEEEBBBCADDDD')
52e3612528fd4ef1ff7b1286ffc76db28676f69a
XiaoshuaiGeng/Python-Intro
/Section3/Tuples.py
285
4.09375
4
# Tuples # Tuples are immutable with only 2 methods associated with them newTuple = (1,1,2,3) print(newTuple) # Tuple methods print('The index of number 3 is {}'.format(newTuple.index(3))) print('The number of times that value 1 showing in the tuple is {}'.format(newTuple.count(1)))
1a2a3df6af1ae24aa36efccd49a7aa32132b8c72
mjnorona/codingDojo
/Python/python_fundamentals/compareArrays.py
761
3.953125
4
def compArr(arr1, arr2): if (len(arr1) != len(arr2)): print "The lists are not the same" else: boo = True for i in range(0, len(arr1)): if arr1[i] != arr2[i]: boo = False break if boo is True: print "The lists are the same" else: print "The lists are not the same" list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] compArr(list_one, list_two) list_three = [1,2,5,6,5] list_four = [1,2,5,6,5,3] compArr(list_three, list_four) list_five = [1,2,5,6,5,16] list_six = [1,2,5,6,5] compArr(list_five, list_six) list_seven = ['celery','carrots','bread','milk'] list_eight = ['celery','carrots','bread','cream'] compArr(list_seven, list_eight)
2f0f907c3e94c0f24dc04cba6e994ab1a8f21bae
JBielan/leetcode-py-js
/python/keyboard_row.py
1,197
4
4
class Solution: def findWords(self, words): first_row = ('Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p') second_row = ('A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l') third_row = ('Z', 'X', 'C', 'V', 'B', 'N', 'M', 'z', 'x', 'c', 'v', 'b', 'n', 'm') result = [] for word in words: # for every element of words list first_word = [char for char in word if char in first_row] # word constructed from first_row letters second_word = [char for char in word if char in second_row] # and so on third_word = [char for char in word if char in third_row] if len(first_word) == len( word): # if length is the same, it means only letters from first row were necessary result.append(word) # add word to the list elif len(second_word) == len(word): # and so on result.append(word) elif len(third_word) == len(word): result.append(word) return result
c7f53112bc0c39fa1875fcbdb6b88f07124634fe
BartoszKopec/wsb-pios-python
/src/2020-05-28_raport.py
2,245
4.3125
4
list = ['a', 'b', 'c', 'c'] # stworzenie kolekcji która ma 4 elementy print(list) setFromList = set(list) # stworzenie zbioru z kolekcji który ma 3 elementy, ponieważ zostały zignorowane dane powtarzające się print(setFromList) setFromList.add('d') print(setFromList) setFromList.remove('a') print(setFromList) # dodanie elementu do zbioru i usunięcie elementu ze zbioru print('a' in setFromList) # wyrażenie logiczne pozwalające sprawdzić czy dana wartość jest w zbiorze set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(set1 | set2) # logiczna suma zbiorów print(set1 - set2) # logiczna różnica zbioru 1 i zbioru 2 print(set2 - set1) # logiczna różnica zbioru 2 i zbioru 3 print(set2 ^ set1) # zwrócenie zbioru zawierającego wartości niepowatrzające się w obu zbiorach # -------------------------------------------------------------- class Vehicle: # klasa _wheels = 0 # jej pole "prywatne" def __init__(self, wheels): # metoda inicjalizująca z jednym parametrem self._wheels = wheels def getWheels(self): # getter zwracający wartość pola return self._wheels v1 = Vehicle(2) print(v1) print(v1.getWheels()) # -------------------------------------------------------------- class Car(Vehicle): # klasa dziedzicząca właściwości po klasie Vehicle _name='' def __init__(self, name): # zastąpienie konstruktora rodzica własnym konstruktorem super().__init__(4) # wywołanie konstruktora rodzica self._name = name def getName(self): return self._name c1 = Car('Fiat') print(c1.getName()) print(c1.getWheels()) # -------------------------------------------------------------- class PartVehicle(Vehicle): def __add__(self, secondVehicle): # magiczna metoda - operator dodawania dwóch wartości return PartVehicle(self.getWheels() + secondVehicle.getWheels()) def __eq__(self, secondVehicle): return self.getWheels() == secondVehicle.getWheels() def __len__(self): return self.getWheels() p1 = PartVehicle(4) # pojazd o 4 kołach (np. samochód ciężarowy) p2 = PartVehicle(6) # pojazd o 6 kołach (np. naczepa) p3 = p1 + p2 # zespół pojazdów print(p3.getWheels()) print(p3 == p1 + p2) print(len(p3))
86afc8bcf86640189d4b3f0a953183f37e080e7d
Mayur01/Python-Fun
/L3_1_identifyelement.py
266
3.859375
4
from collections import * def countfreq(list): return Counter(list) print("Enter list of variavbles:") list = [int(x) for x in input().split()] freq = countfreq(list) sortedDict = dict(sorted(freq.items(), key=lambda x: x[1])) print(next(iter(sortedDict)))
94ce852d3acdc47817916f0b220dcd4e878279f1
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/middle-three-digits-1.py
1,481
4.03125
4
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
39c203625a93b204b5b1ce1ff70729d7741e31e8
sistemasmarcelocastro/pruebas-python
/cursoPython1/s7l17-py.py
393
3.625
4
# diccionarios """ gato = {'tamaño': 'gordo', 'color': 'blanco', 'animo': 'apapachero'} print(gato['tamaño']) for k, v in gato.items(): print(k + ' contiene ' + v) """ import pprint mensaje = 'Qué lehabrán hacho mis manos, qué le habrán hecho...' cuenta = {} for letra in mensaje.upper(): cuenta.setdefault(letra, 0) cuenta[letra] = cuenta[letra] + 1 pprint.pprint(cuenta)
0812161b3c7d83389f91c33e0a47e418170f45c7
lavhaleakshay/datastructures-python
/linked-list/reverse_linked_list.py
1,979
4.03125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node def prepend(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def print_helper(self, node, name): if node is None: print(name + ": None") else: print(name + ":" + node.data) # A -> B -> C -> D -> 0 # D -> C -> B -> A -> 0 # A <- B <- C <- D <- 0 # def reverse_iterative(self): prev = None cur = self.head while cur: nxt = cur.next cur.next = prev self.print_helper(prev, "PREV") self.print_helper(cur, "CUR") self.print_helper(nxt, "NXT") print("\n") prev = cur cur = nxt self.head = prev def reverse_recursive(self): def _reverse_recursive(cur, prev): if not cur: return prev nxt = cur.next cur.next = prev prev = cur cur = nxt return _reverse_recursive(cur, prev) self.head = _reverse_recursive(cur = self.head, prev = None) llist = LinkedList() llist.append("A") llist.append("B") llist.append("C") llist.append("D") #llist.swap_nodes("A", "C") #llist.reverse_iterative() llist.reverse_recursive() llist.print_list() #print(llist.len_iterative()) #print(llist.len_recursive(llist.head))
f508b7ed12649dd075a012e2da9c4372bf56f460
TGathman/Codewars
/7 kyu/Isograms/Isograms.py
166
3.734375
4
# Python 3.8, 20 March 2020. def is_isogram(string): for i in string.lower(): if string.lower().count(i) > 1: return False return True
b18213c864bf7f55e357f3c840ea188cd31d5e65
ontheone04/dc-cohort-week-1
/day2/Calculator.py
452
4.1875
4
First_num = input('Enter first number:\n') symbol = input('Enter Operation (+, -, *, /):\n') Second_num = input('Enter Second Number:\n') First_num = float(First_num) Second_num = float(Second_num) out = None if symbol == '+': out = First_num + Second_num elif symbol == '-': out = First_num - Second_num elif symbol == '*': out = First_num *Second_num elif symbol == '/': out = First_num / Second_num print('answer: ' + str(out))
d06d85d049b5e9608090a2e70f95ac4877f12c3d
faheelsattar/Python-for-fun
/recursion/allpossiblepalindromicpartitions.py
696
3.640625
4
def partitions(value ,array:list): if len(value) == 0: print(array) return else: holder='' for val in value: holder+=val if palindrome(holder): array.append(holder) value=value[1 : : ] partitions(value, array) def palindrome(value): high=len(value)-1 low=0 while low < len(value): if value[low] == value[high]: if low == len(value)-1: return True low += 1 high -= 1 else: return False partitions('nitin',[]) # input--> nitin #output --> ['n', 'nitin', 'i', 'iti', 't', 'i', 'n']
5c70b4e5f613c91985f2c468e4f166c3841f601c
KarateJB/Python.Practice
/src/TensorFlow/venv/Lab/Tutorials/Basic/zip.py
137
3.640625
4
a = [11,22,33,44,55,66,77,88,99] b = [1,2,3,4,5,6,7,8,9] print(list(zip(a,b))) print(*zip(range(0, len(a), 2), range(2, len(a)+1, 2)))
d6cd9ae6fbe46ba677d31368ffade1a3a608f44d
vMorane/Excerc-cios
/Exercícios/Ex13.py
193
3.9375
4
a = int (input("Digite o 1º nº:")) b = int (input("Digite o 2º nº:")) if (a > b): print("Primeiro maior") elif: (a = b): print("São iguais") else: print("Segundo maior")
3dd184f72d35c0868cd5066cb720d89b8a2568ca
AlexanderPort/NNToolkit
/gui/VisualElements/utils.py
632
3.71875
4
import math def curve(x1: int, y1: int, x2: int, y2: int) -> list: mx = (x2 - x1) / 2 my = (y2 - y1) / 2 c1 = [x1, y1 + my] c2 = [x2, y2 - my] steps = 0.001 points = [] angle = 1.5 * math.pi goal = 2 * math.pi while angle < goal: x = c1[0] + mx * math.cos(angle) y = c1[1] + my * math.sin(angle) points.extend([x, y]) angle += steps angle = 1 * math.pi goal = 0.5 * math.pi while angle > goal: x = c2[0] + mx * math.cos(angle) y = c2[1] + my * math.sin(angle) points.extend([x, y]) angle -= steps return points
4f029613989461e81e71f0590b41eadd473c3585
chatton/ProgrammingChallengeQuestions
/python/sort-the-odd.py
685
4.25
4
""" Description: You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] """ def sort_array(source_array): if not source_array: return [] new_arr = sorted(list(filter(lambda x: x % 2 == 1, source_array))) current_index = 0 result = list(source_array) for x in range(len(source_array)): if source_array[x] % 2 == 1: result[x] = new_arr[current_index] current_index += 1 return result
45991f492cffdb79a6b1c978671c3e27c23b806f
go2bed/python-functions
/com.go2bed.functions/Functions.py
541
4.09375
4
def my_fun(string): print(string) my_fun('Hello') def greeting(name): print("Hello " + name) greeting('Jose') def add_num(num1, num2): return num1 + num2 x = add_num('goo', 'gle') y = add_num(2, 3) print(x) print(y) def is_prime(num): """ This function checks for prime numbers :param num: :return: """ for n in range(2, num): if num % n == 0: print('{} is not a prime'.format(num)) break else: print('The {} is prime'.format(num)) is_prime(12)
94a311fc5b660db843de5fc391cd1106a47b3738
CaioHRombaldo/PythonClasses
/Ex019 v2.py
422
4.125
4
from random import choice print('=--Student name picker--=') print('How many students do you want to register?') nStudents = int(input('Number of students: ')) students = [] index = 0 while index < nStudents: studentName = input('Enter the name of student number {} '.format(index + 1)) students.append(studentName) index += 1 chosen = choice(students) print('The student selected was: {}'.format(chosen))
c26d2da341500f1dd8513081a00a0de6981da65e
alvinzhu33/6.0002
/PSet 2/graph.py
5,045
4
4
# 6.0002 Problem Set 2 # Graph Optimization # Name: Alvin Zhu # Collaborators: # Time: 4 # # A set of data structures to represent the graphs that you will be using for this pset. # class Node(object): """Represents a node in the graph""" def __init__(self, name): self.name = str(name) def get_name(self): ''' return: the name of the node ''' return self.name def __str__(self): ''' return: The name of the node. This is the function that is called when print(node) is called. ''' return self.name def __repr__(self): ''' return: The name of the node. Formal string representation of the node ''' return self.name def __eq__(self, other): ''' returns: True is self == other, false otherwise This is function called when you used the "==" operator on nodes ''' return self.name == other.name def __ne__(self, other): ''' returns: True is self != other, false otherwise This is function called when you used the "!=" operator on nodes ''' return not self.__eq__(other) def __hash__(self): ''' This function is necessary so that Nodes can be used as keys in a dictionary, Nodes are immutable ''' return self.name.__hash__() ## PROBLEM 1: Implement this class based on the given docstring. class WeightedEdge(object): """Represents an edge with an integer weight""" def __init__(self, src, dest, total_time, color): """ Initialize src, dest, total_time, and color for the WeightedEdge class src: Node representing the source node dest: Node representing the destination node total_time: int representing the time travelled between the src and dest color: string representing the t line color of the edge """ self.src = src; self.dest = dest; self.total_time = int(total_time); self.color = color; def get_source(self): """ Getter method for WeightedEdge returns: Node representing the source node """ return self.src; def get_destination(self): """ Getter method for WeightedEdge returns: Node representing the destination node """ return self.dest; def get_color(self): """ Getter method for WeightedEdge returns: String representing the t-line color of the edge""" return self.color; def get_total_time(self): """ Getter method for WeightedEdge returns: int representing the time travelled between the source and dest nodes""" return self.total_time; def __str__(self): """ to string method returns: string with the format 'src -> dest total_time color' """ return self.src.get_name() +' -> ' + self.dest.get_name() + " " + str(self.total_time) + " " + self.color; ## PROBLEM 1: Implement methods of this class based on the given docstring. ## DO NOT CHANGE THE FUNCTIONS THAT HAVE BEEN IMPLEMENTED FOR YOU. class Digraph(object): """Represents a directed graph of Node and WeightedEdge objects""" def __init__(self): self.nodes = set([]) self.edges = {} # must be a dictionary of Node -> list of edges starting at that node def __str__(self): edge_strs = [] for edges in self.edges.values(): for edge in edges: edge_strs.append(str(edge)) edge_strs = sorted(edge_strs) # sort alphabetically return '\n'.join(edge_strs) # concat edge_strs with "\n"s between them def get_edges_for_node(self, node): ''' param: node object return: a copy of the list of all of the edges for given node. empty list if the node is not in the graph ''' return [item for item in self.edges[node]]; def has_node(self, node): ''' param: node object return: True, if node is in the graph. False, otherwise. ''' return node in self.nodes; def add_node(self, node): """ param: node object Adds a Node object to the Digraph. Raises a ValueError if it is already in the graph.""" if node in self.nodes: raise ValueError; self.nodes.add(node); #Add to a set self.edges[node] = []; #Instantiate a key in edges {}. def add_edge(self, edge): """ param: WeightedEdge object Adds a WeightedEdge instance to the Digraph. Raises a ValueError if either of the nodes associated with the edge is not in the graph.""" #Check if both nodes of an edge are in the digraph and whether the edge has already been added. if edge.get_source() in self.nodes and edge.get_destination() in self.nodes: if edge not in self.edges[edge.get_source()]: self.edges[edge.get_source()] += [edge]; else: raise ValueError;
be0716adeb8791ae142c7c8cec389fa890c9c273
potatoHVAC/leetcode_challenges
/algorithm/988.2_smallest_string_starting_from_leaf.py
1,353
3.765625
4
# Smallest String Starting From Leaf # https://leetcode.com/problems/smallest-string-starting-from-leaf/ # Completed 5/6/19 # I added dynamic # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def to_letter(node: TreeNode) -> str: # Return the letter equivalent of node.val letters = "abcdefghijklmnopqrstuvwxyz" return letters[node.val] class Solution: def __init__(self): self.memoize = {} def smallestFromLeaf(self, root: TreeNode) -> str: def _smallestFromLeaf(root: TreeNode, path: str) -> str: if root is None: return path if root not in self.memoize: path = to_letter(root.val) + path if root.left and root.right: left = _smallestFromLeaf(root.left, path) right = _smallestFromLeaf(root.right, path) self.memoize[root] = min(left, right) elif root.left: self.memoize[root] = _smallestFromLeaf(root.left, path) else: self.memoize[root] = _smallestFromLeaf(root.right, path) return self.memoize[root] return _smallestFromLeaf(root, "")
ce6c764e50e7c800706f9ba27941d4d389734d37
ntupenn/exercises
/medium/356.py
851
3.671875
4
""" Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of points. Example 1: Given points = [[1,1],[-1,1]], return true. Example 2: Given points = [[1,1],[-1,-1]], return false. Follow up: Could you do better than O(n2)? Hint: Find the smallest and largest x-value for all points. If there is a line then it should be at y = (minX + maxX) / 2. For each point, make sure that it has a reflected point in the opposite side. """ def isReflected(points): if not points: return True check = set() l = r = points[0][0] for x, y in points: x *= 1.0 check.add((x, y)) l = min(l, x) r = max(r, x) m = l + (r - l) / 2.0 for x, y in points: xx = m + m - x if (xx, y) not in check: return False return True
ec344f6af3391c9c20ae74fe055c446fac0ecf0d
Arnabsaha6/Chess-with-Python
/Chess Game/board.py
50,564
3.703125
4
#Initiliazes the global variables to keep up with the states in chess KingcastlingStateWhite = True KingcastlingStateBlack = True QueencastlingStateBlack = True QueencastlingStateWhite = True whiteUnderCheck = False blackUnderCheck = False whiteMoveMade = False checkMate = False class Board: #initialize the board and the pieces' position in a 2-D list #lowercase lettes represent the black pieces while uppercase letters represent the white pieces #8X8 sized list chessBoard = [["r", "n" ,"b", "q", "k", "b","n", "r"], ["p", "p" ,"p", "p", "p", "p","p", "p"], #lowercase n = black knight, uppercase N = white knight [" ", " " ," ", " ", " ", " "," ", " "], #lowercase r = black rook, uppercase R = white rook [" ", " " ," ", " ", " ", " "," ", " "], #lowercase b = black bishop, uppercase B = white bishop [" ", " " ," ", " ", " ", " "," ", " "], #lowercase q = black queen, uppercase Q = white queen [" ", " " ," ", " ", " ", " "," ", " "], #lowercase k = black king, uppercase K = white king ["P", "P" ,"P", "P", "P", "P","P", "P"], #lowercase p = black pawn, uppercase P = white pawn ["R", "N" ,"B", "Q", "K", "B","N", "R"]] #this function is evoked by the GUI to determine the position of the piece that was selected to move def determinePiece(self, move2compare): #get the global variables global KingcastlingStateBlack global KingcastlingStateWhite global QueencastlingStateWhite global QueencastlingStateBlack #variable initialization self.move2compare = move2compare Kingcolour = "" colour = "" #get the coordinates of the move that was made self.x1 = self.move2compare[0][0] self.y1 = self.move2compare[0][1] self.x2 = self.move2compare[0][2] self.y2 = self.move2compare[0][3] #get the name of the piece on that particular coordinate self.pieceOnBoard = self.chessBoard[self.x1][self.y1] #get all the possible moves that can be made by that particular piece the_possible_moves = self.possibleMoves(self.pieceOnBoard) #this if-else statement is required to check for castling moves #this following statement checks for king's movement over 1 tiles if (self.pieceOnBoard == "K" or self.pieceOnBoard == 'k') and (self.y2 - self.y1 == 2 or self.y2 - self.y1 == -2): if KingcastlingStateBlack == True or KingcastlingStateWhite == True or QueencastlingStateWhite == True or QueencastlingStateBlack == True : #check for white's castling state if self.pieceOnBoard == "K" and (QueencastlingStateWhite == True or KingcastlingStateWhite == True): #if the above checks are passed, the Castling function will be called by passing the necessary parameters if (self.x2 == 7 and self.y2 == 6) and KingcastlingStateWhite == True: self.Kingcolour = "White" self.Castling(self.Kingcolour, self.x1, self.y1, self.x2, self.y2) #if the above checks are passed, the Castling function will be called by passing the necessary parameters elif (self.x2 == 7 and self.y2 == 2) and QueencastlingStateWhite == True: self.Kingcolour = "White" self.Castling(self.Kingcolour, self.x1, self.y1, self.x2, self.y2) #checck for black's castling state elif self.pieceOnBoard == "k" and (QueencastlingStateBlack == True or KingcastlingStateBlack == True): if (self.x2 == 0 and self.y2 == 6) and KingcastlingStateBlack == True: #if the above checks are passed, the Castling function will be called by passing the necessary parameters self.Kingcolour ="Black" self.Castling(self.Kingcolour, self.x1, self.y1, self.x2, self.y2) elif (self.x2 == 0 and self.y2 == 2) and QueencastlingStateBlack == True: #if the above checks are passed, the Castling function will be called by passing the necessary parameters self.Kingcolour ="Black" self.Castling(self.Kingcolour, self.x1, self.y1, self.x2, self.y2) else: pass #possibleOrNot() function is called to check if the proposed move is in the list of the possible moves elif(self.possibleOrNot(self.move2compare, the_possible_moves)): #if the above check is passed, then makeMove() function will be fired to execute the move. Parameter 3 is simply given to notify that this is not a castling call. self.makeMove(move2compare, 3) else: pass #this function deter4mines whether the move made by the players are possible or not by comparing with all the possible moves on the board for the particular piece def possibleOrNot(self, proposedMove, thepossibleMoves): #variable initialization self.proposedMove = proposedMove self.possibleMoveslist = thepossibleMoves #list initialization proposedMove2compare = [] #get the coordinates of the user's move self.x1 = self.proposedMove[0][0] self.y1 = self.proposedMove[0][1] self.x2 = self.proposedMove[0][2] self.y2 = self.proposedMove[0][3] #if the user made a move to capture the opponent's piece, then the captured piece will be recorded at the end of the string if self.chessBoard[self.x2][self.y2] != " ": proposedMove2compare.append((self.x1, self.y1, self.x2, self.y2, self.chessBoard[self.x2][self.y2])) else: proposedMove2compare.append((self.x1,self.y1,self.x2,self.y2)) #this function will finally return the boolean value produced from the comparison of the move made by the user and the possible moves of the piece on the board return set(proposedMove2compare) <= set(self.possibleMoveslist) #this function is responsible for executing the move made by the user. #the function takes the move made by the user and a number representing whether it's a casting move or not #castling move made for the white piece is denoted by the integer "1", "2" for black and "3" for not castling move def makeMove(self, proposedMove, castlingState): #get the coordinates of the user's move self.x1 = proposedMove[0][0] self.y1 = proposedMove[0][1] self.x2 = proposedMove[0][2] self.y2 = proposedMove[0][3] #this statement will initialize the following variable as "White" if the move was made by the black piece player and "Black" if otherwise colour_to_check_opponent_threat = "White" if ord(self.chessBoard[self.x1][self.y1]) >= 97 else "Black" #get the global variables to update accordingly global whiteMoveMade global QueencastlingStateWhite global KingcastlingStateWhite global KingcastlingStateBlack global QueencastlingStateBlack global blackUnderCheck global whiteUnderCheck tempPiece = "" #get the piece that the user selected to move self.getChar = self.chessBoard[self.x1][self.y1] #if the piece moved was a king or rook, set the castling state to false. If a rook is moved, the rook will be checked first and then set the state accordingly. if self.getChar == "K" or self.getChar == "R": #if it was a rook that has been moved, the rook will be identified first if self.getChar == "R": #if it is the King's side rook, then the King's side castling state will be set to false if self.x1 == 7 and self.y1 == 7: KingcastlingStateWhite = False #if it is the Queen's side rook, then the Queen's side castling state will be set to false. elif self.x1 == 7 and self.y1 == 0: QueencastlingStateWhite = False #if it was the king that has been moved, then both of the castling state will be set to false if self.getChar == "K": QueencastlingStateWhite = False KingcastlingStateWhite = False elif self.getChar == "k" or self.getChar == "r": #if it was a rook that has been moved, the rook will be identified first if self.getChar == 'r': #if it is the Queen's side rook, then the Queen's side castling state will be set to false if self.x1 == 0 and self.y1 == 0: QueencastlingStateWhite = False #if it is the King's side rook, then the King's side castling state will be set to false elif self.x1 == 0 and self.y1 == 7: KingcastlingStateBlack = False #if it was the king that has been moved, then both of the castling state will be set to false if self.getChar == "k": QueencastlingStateBlack = False KingcastlingStateBlack = False else: pass #check if the move is made by the white piece player #the variable whiteMoveMade = False indicates that white piece player has yet to make a move if (ord(self.getChar) >= 65 and ord(self.getChar) <= 90) and whiteMoveMade == False: self.chessBoard[self.x1][self.y1] = " " #make the current tile empty tempPiece = self.chessBoard[self.x2][self.y2] #keep the piece of the tile the move was made to in the variable self.chessBoard[self.x2][self.y2] = self.getChar #make the tile where the move is made occupied with the piece that was selected to make the move whiteMoveMade = True #set the variable to indicate that the white piece player has made a move if self.CheckState("White") == True: #if the white piece player's move exposes the King, then the move will be retreated back self.chessBoard[self.x1][self.y1] = self.getChar self.chessBoard[self.x2][self.y2] = tempPiece whiteMoveMade = False #returns the value back to false else: #check if the pawn has made it to promotion or not self.Promotion_Check("White") #check if the move is made by the black piece player #the variable whiteMoveMade = False indicates that black piece player has yet to make a move elif (ord(self.getChar) >= 97 and ord(self.getChar) <= 122) and whiteMoveMade == True: self.chessBoard[self.x1][self.y1] = " " #make the current tile empty tempPiece = self.chessBoard[self.x2][self.y2] #keep the piece of the tile the move was made to in the variable self.chessBoard[self.x2][self.y2] = self.getChar #make the tile where the move is made occupied with the piece that was selected to make the move whiteMoveMade = False #set the variable to indicate that the black piece player has made a move if self.CheckState("Black") == True: #if the black piece player's move exposes the King, then the move will be retreated back self.chessBoard[self.x1][self.y1] = self.getChar self.chessBoard[self.x2][self.y2] = tempPiece whiteMoveMade = True else: #check if the pawn has made it to promotion or not self.Promotion_Check("Black") else: pass #if the move was a castling move, the whiteMoveMade variable will be set to false to allow the Rook to move for the second time after the King if castlingState == 1: whiteMoveMade = False elif castlingState == 2: whiteMoveMade = True else: pass #CheckState() is a function to check if the move made has "Checked" the opponent's King or not if colour_to_check_opponent_threat == "White": whiteUnderCheck = self.CheckState(colour_to_check_opponent_threat) elif colour_to_check_opponent_threat == "Black": blackUnderCheck = self.CheckState(colour_to_check_opponent_threat) else: pass #if the CheckState() function returns true, Check_Checkmate() is called to check if a checkmate is made or not. if self.CheckState("Black") == True: self.Check_CheckMate("Black") if self.CheckState("White") == True: self.Check_CheckMate("White") #calculate all the legal moves def possibleMoves(self, piece): self.piece = piece #initialize the list to store the legal moves movesList = [] #iterates over all the tiles on the board for i in range(64): #in Python3, int have to be used to floor the value #check if there's a white rook at the coordinate if self.chessBoard[int(i/8)][i%8] == "R" and self.piece == "R": movesList += self.RookMove(i, "White") #check if there's a black rook at the coordinate elif self.chessBoard[int(i/8)][i%8] == 'r' and self.piece == 'r': movesList += self.RookMove(i, "Black") #check if there's a white knight at the coordinate elif self.chessBoard[int(i/8)][i%8] == "N" and self.piece == 'N' : movesList += self.KnightMove(i, "White") #check if there's a black knight at the coordinate elif self.chessBoard[int(i/8)][i%8] == "n" and self.piece == 'n' : movesList += self.KnightMove(i, "Black") #check if there's a white bishop at the coordinate elif self.chessBoard[int(i/8)][i%8] == "B" and self.piece == 'B' : movesList += self.BishopMove(i, "White") #check if there's a black bishop at the coordinate elif self.chessBoard[int(i/8)][i%8] == "b" and self.piece == 'b' : movesList += self.BishopMove(i, "Black") #check if there's a white queen at the coordinate elif self.chessBoard[int(i/8)][i%8] == "Q" and self.piece == 'Q' : movesList += self.QueenMove(i, "White") #check if there's a black queen at the coordinate elif self.chessBoard[int(i/8)][i%8] == "q" and self.piece == 'q' : movesList += self.QueenMove(i, "Black") #check if there's a white king at the coordinate elif self.chessBoard[int(i/8)][i%8] == "K" and self.piece == 'K' : movesList += self.KingMove(i, "White") elif self.chessBoard[int(i/8)][i%8] == "k" and self.piece == 'k' : movesList += self.KingMove(i, "Black") # check if there's a white pawn at the coordinate elif self.chessBoard[int(i/8)][i%8] == "P" and self.piece == 'P' : movesList += self.WhitePawnMove(i) # check if there's a black pawn at the coordinate elif self.chessBoard[int(i/8)][i%8] == 'p' and self.piece == 'p' : movesList += self.BlackPawnMove(i) #returns the list of appended movement lists return movesList ################### MOVEMENT OF PIECES ##################################### ############# BEGINNING OF PAWN'S MOVEMENTS ################# #function to calculate the legal moves for white pawns def WhitePawnMove(self,position): #initialize the list to return later moves = [] #initialize the variable to check if there's a piece in front of the pawn firstStepBlock = False #get the coordinates r = int(position / 8) c = position % 8 # row 6 is white pawn's initial position if r == 6: #looping for 2 boxes ahead for x in range(5, 3, -1): #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #check whether the box in front is empty or not if self.chessBoard[x][c] == " " and firstStepBlock == False: #these 4 lines appends the original position and the target position moves.append((r,c,x,c)) else: #if there is a piece in front, the variable will be set to true firstStepBlock = True except Exception as e: pass else: #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: if self.chessBoard[r-1][c] == " ": #these 4 lines appends the original position and the target position moves.append((r,c,r-1,c)) except Exception as e: pass if r-1 >= 0: #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #test whether the pawns can take any materials or not (ord function cross checks with ASCII characters for lower case characters) if ord(self.chessBoard[r-1][c+1]) >= 97 and ord(self.chessBoard[r-1][c+1]) <= 122: #these 4 lines appends the original position and the target position moves.append((r,c, r-1, c+1, self.chessBoard[r-1][c+1])) except Exception as e: pass if r-1 >= 0 and c-1 >= 0: try: #test whether the pawns can take materials or not (ord function cross checks with ASCII characters for lower case characters) if ord(self.chessBoard[r-1][c-1]) >= 97 and ord(self.chessBoard[r-1][c-1]) <=122: #these 4 lines appends the original position and the target position moves.append((r,c, r-1, c-1, self.chessBoard[r-1][c-1])) except Exception as e: pass #returns all the legal moves return moves ###################### END OF WHITE PAWN'S MOVEMENT ################### ###################### BEGINNING OF BLACK PAWN'S MOVEMENT ############# def BlackPawnMove(self,position): #initialize the list to return later moves = [] #initialize the variable to check if there's a piece in front of the pawn firstStepBlock = False #get the coordinates r = int(position / 8) c = position % 8 # row 1 is black pawn's initial position if r == 1: #looping for 2 boxes ahead for x in range(2, 4): #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #check whether the box in front is empty or not if self.chessBoard[x][c] == " " and firstStepBlock == False: #these 4 lines appends the original position and the target position moves.append((r,c,x,c)) else: #if there is a piece in front, the variable will be set to true firstStepBlock = True except Exception as e: pass else: #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: if self.chessBoard[r+1][c] == " ": #these 4 lines appends the original position and the target position moves.append((r,c, r+1, c)) except Exception as e: pass #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #test whether the pawns can take any materials or not (ord function cross checks with ASCII characters for lower case characters) if r+1 >= 0 and c-1 >= 0: if ord(self.chessBoard[r+1][c+1]) >= 65 and ord(self.chessBoard[r+1][c+1]) <= 90: #these 4 lines appends the original position and the target position moves.append((r,c, r+1, c+1, self.chessBoard[r+1][c+1])) except Exception as e: pass try: #test whether the pawns can take materials or not (ord function cross checks with ASCII characters for lower case characters) if ord(self.chessBoard[r+1][c-1]) >= 65 and ord(self.chessBoard[r+1][c-1]) <=90: #these 4 lines appends the original position and the target position moves.append((r,c, r+1, c-1, self.chessBoard[r+1][c-1])) except Exception as e: pass #returns all the legal moves return moves ###################### END OF BLACK PAWN'S MOVEMENT ################### ###################### BEGINNING OF ROOK'S MOVEMENT ############# def RookMove(self, position, colour): #set the variables according to colour of the piece if colour == "White": #these values represents the range of lowercase letters ordA, ordB = 97, 122 elif colour == "Black": #these values represents the range of uppercase letters ordA, ordB = 65, 90 #list initialization moves = [] #coordinate of the pieces r = int(position / 8) c = position % 8 #variable initialization to iterate until the end of the board temp = 1 #this loop iterates from -1 to 1 to change the direction of the iterations ( bottom, top ,right and left) for j in range (-1, 2, 2): #initialize the variable back to 1 temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iteration to the end of the board until there's a piece in the way while(self.chessBoard[r+temp*j][c] == " " and temp < 8): #if statement to make sure the value of the row does not go below 0 if r+temp*j >= 0: #append the legal moves to the list moves.append((r,c,r+temp*j,c)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if ord(self.chessBoard[r+temp*j][c]) >= ordA and ord(self.chessBoard[r+temp*j][c]) <= ordB: #if statement to make sure the value of the row does not go below 0 if r+temp*j >= 0: #append the legal moves to the list moves.append((r,c,r+temp*j,c, self.chessBoard[r+temp*j][c])) except IndexError: pass #initialize the variable back temp=1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iteration to the end of the board until there's a piece in the way while(self.chessBoard[r][c+temp*j] == " " and temp < 8): #if statement to make sure the value of the column does not go below 0 if c+temp*j >= 0: #append the legal moves to the list moves.append((r,c,r,c+temp*j)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if ord(self.chessBoard[r][c+temp*j]) >= ordA and ord(self.chessBoard[r][c+temp*j]) <= ordB: #if statement to make sure the value of the column does not go below 0 if c+temp*j >= 0: #append the legal moves to the list moves.append((r,c,r,c+temp*j,self.chessBoard[r][c+temp*j])) except IndexError: pass #returns all the legal moves return moves ###################### END OF ROOK'S MOVEMENT ############# ########### BEGINNING OF KNIGHTS' MOVEMENT ######################## def KnightMove(self, position, colour): #set the variables according to colour of the piece if colour == "White": #these values represents the range of lowercase letters ordA, ordB = 97, 122 elif colour == "Black": #these values represents the range of uppercase letters ordA, ordB = 65, 90 #list initialization moves = [] #get the coordinate r = int(position / 8) c = position % 8 #these nested loops will complete all the 8 possible route for a knight for j in range(-1 ,2, 2): for k in range(-1, 2, 2): #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #checks if the target box is empty or occupied with an enemy's piece if self.chessBoard[r+j][c+k*2] == " " or (ord(self.chessBoard[r+j][c+k*2]) >= ordA and ord(self.chessBoard[r+j][c+k*2]) <= ordB): #makes sure the row or column does not have a value less than 0 if r+j >=0 and c+k*2 >= 0: #append the legal moves into the list if self.chessBoard[r+j][c+k*2] == " ": moves.append((r,c,r+j,c+k*2)) else: moves.append((r,c,r+j,c+k*2,self.chessBoard[r+j][c+k*2])) except IndexError: pass #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #checks if the target box is empty or occupied with an enemy's piece if self.chessBoard[r+j*2][c+k] == " " or (ord(self.chessBoard[r+j*2][c+k]) >= ordA and ord(self.chessBoard[r+j*2][c+k]) <= ordB): #makes sure the row or column does not have a value less than 0 if r+j*2 >= 0 and c+k >= 0: #append the legal moves into the list if self.chessBoard[r+j*2][c+k] == " ": moves.append((r,c,r+j*2,c+k)) else: moves.append((r,c,r+j*2,c+k,self.chessBoard[r+j*2][c+k])) except IndexError: pass #return all the possible moves return moves ###### END OF KNIGHT'S MOVEMENT ######################################### ###### BEGINNING OF BISHOP'S MOVEMENT ###################################### def BishopMove(self, position, colour): #set the variables according to colour of the piece if colour == "White": #these values represents the range of lowercase letters ordA, ordB = 97, 122 elif colour == "Black": #these values represents the range of uppercase letters ordA, ordB = 65, 90 #initialize list moves = [] #get the coordinate r = int(position / 8) c = position % 8 #variable initialization to iterate through the diagonal line to the end temp = 1 #these nested loops will be responsible for the movement to top, bottom, right and left by constantly changing from -1 to 1 for j in range(-1,2,2): for k in range(-1,2,2): #initialize it back temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #this while loop will iterate until there is no empty box to the end of the board while (self.chessBoard[r+temp*j][c+temp*k] == " " and temp < 8): #test to make sure the value of the row and column does not go below 0 if r+temp*j >= 0 and c+temp*k >= 0: #append the legal moves into the list moves.append((r,c,r+temp*j,c+temp*k)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if (ord(self.chessBoard[r+temp*j][c+temp*k]) >= ordA and ord(self.chessBoard[r+temp*j][c+temp*k]) <=ordB) and temp < 8 : #test to make sure the value of the row and column does not go below 0 if r+temp*j >= 0 and c+temp*k >= 0: #append the legal moves into the list moves.append((r,c, r+temp*j, c+temp*k, self.chessBoard[r+temp*j][c+temp*k])) except IndexError: pass return moves ########## ENDING OF THE WHITE BISHOP'S MOVEMENT ####################### ########## BEGINNING OF THE WHITE QUEEN'S MOVEMENT ##################### def QueenMove(self, position, colour): #set the variables according to colour of the piece if colour == "White": #these values represents the range of lowercase letters ordA, ordB = 97, 122 elif colour == "Black": #these values represents the range of uppercase letters ordA, ordB = 65, 90 #initialize list moves = [] #get the coordinate r = int(position / 8) c = position % 8 #initialize the variable temp = 1 #nested loop that implements the movement of a rook and bishop #first loop for the horizontal and vertical iteration for j in range(-1,2,2): #initialize the variable to iterate all over again temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iterate through the boxes vertically both way while(self.chessBoard[r+temp*j][c] == " " and temp < 8): #makes sure that the index of the row does not go below 0 if r+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r+temp*j,c)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if (ord(self.chessBoard[r+temp*j][c]) >= ordA and ord(self.chessBoard[r+temp*j][c]) <= ordB) and temp < 8: #makes sure that the index of the row does not go below 0 if r+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r+temp*j,c, self.chessBoard[r+temp*j][c])) except IndexError: pass #initialize back the variable temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iterate through the boxes horizontally both way while (self.chessBoard[r][c+temp*j] == " " and temp < 8): #makes sure that the index of the column does not go below 0 if c+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r,c+temp*j)) temp = temp + 1 if (ord(self.chessBoard[r][c+temp*j]) >= ordA and ord(self.chessBoard[r][c+temp*j]) <= ordB ) and temp < 8: #makes sure that the index of the column does not go below 0 if c+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r,c+temp*j,self.chessBoard[r][c+temp*j])) except IndexError: pass #second loop for the diagonal iteration for k in range(-1,2,2): #initialize back the variable temp = 1 #iterate through the boxes diagonally both way try: while (self.chessBoard[r+temp*j][c+temp*k] == " " and temp < 8): #makes sure that the index of the column and row does not go below 0 if r+temp*j >= 0 and c+temp*k >=0 : #append the legal moves into the list moves.append((r,c, r+temp*j, c+temp*k)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if (ord(self.chessBoard[r+temp*j][c+temp*k]) >= ordA and ord(self.chessBoard[r+temp*j][c+temp*k]) <= ordB) and temp < 8: #makes sure that the index of the column and row does not go below 0 if r+temp*j >= 0 and c+temp*k >= 0: #append the legal moves into the list moves.append((r,c, r+temp*j, c+temp*k, self.chessBoard[r+temp*j][c+temp*k])) except IndexError: pass #returns all the legal moves return moves ################## ENDING OF THE QUEEN'S MOVEMENT ############################ ################## BEGINNING OF THE KING'S MOVEMENT ########################## def KingMove(self, position, colour): #set the variables according to colour of the piece if colour == "White": #these values represents the range of lowercase letters ordA, ordB = 97, 122 elif colour == "Black": #these values represents the range of uppercase letters ordA, ordB = 65, 90 #initialize the list moves = [] #get the coordinate r = int(position / 8) c = position % 8 #initialize the variable temp = 1 #nested loop that implements the movement of a rook and bishop #first loop for the horizontal and vertical iteration for j in range(-1,2,2): #initialize the variable to iterate all over again temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iterate through the boxes vertically both way while(self.chessBoard[r+temp*j][c] == " " and temp < 2): #makes sure that the index of the row does not go below 0 if r+temp*j >= 0: #append the legal moves into the list moves.append((r,c, r+temp*j, c)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if (ord(self.chessBoard[r+temp*j][c]) >= ordA and ord(self.chessBoard[r+temp*j][c]) <= ordB) and temp < 2: #makes sure that the index of the row does not go below 0 if r+temp*j >= 0: #append the legal moves into the list moves.append((r,c, r+temp*j,c, self.chessBoard[r+temp*j][c])) except IndexError: pass #initialize back the variable temp = 1 #Try-Exception is used to avoid errors regarding out of bounds index when the coordinates are beyond the chess board try: #iterate through the boxes horizontally both way while (self.chessBoard[r][c+temp*j] == " " and temp < 2): #makes sure that the index of the column does not go below 0 if c+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r,c+temp*j)) temp = temp + 1 if (ord(self.chessBoard[r][c+temp*j]) >= ordA and ord(self.chessBoard[r][c+temp*j]) <= ordB ) and temp < 2: #makes sure that the index of the column does not go below 0 if c+temp*j >= 0: #append the legal moves into the list moves.append((r,c,r,c+temp*j, self.chessBoard[r][c+temp*j])) except IndexError: pass #second loop for the diagonal iteration for k in range(-1,2,2): #initialize back the variable temp = 1 #iterate through the boxes diagonally both way try: while (self.chessBoard[r+temp*j][c+temp*k] == " " and temp < 2): #makes sure that the index of the column and row does not go below 0 if r+temp*j >= 0 and c+temp*k >=0 : #append the legal moves into the list moves.append((r,c, r+temp*j, c+temp*k)) #increase the value to iterate through the remaining boxes temp = temp + 1 #check whether there is an enemy's piece to be captured or not if (ord(self.chessBoard[r+temp*j][c+temp*k]) >= ordA and ord(self.chessBoard[r+temp*j][c+temp*k]) <= ordB) and temp < 2: #makes sure that the index of the column and row does not go below 0 if r+temp*j >= 0 and c+temp*k >= 0: #append the legal moves into the list moves.append((r,c, r+temp*j, c+temp*k, self.chessBoard[r+temp*j][c+temp*k])) except IndexError: pass return moves ################## END OF THE KING'S MOVEMENT ########################## ######################################## END OF PIECES' MOVEMENT ########################################## ######################## THREAD DETECTION AND CASTLING ################################################## #function to perform castling def Castling(self, colour, x1, y1, x2, y2): #variable initialization KingMove = [] RookMove = [] castlingAbility = True #check to see if the castling move was made by white piece player #x1 = 7 and y1 = 4 indicates that the King is in the initial position if colour == "White" and x1 == 7 and y1 == 4: #x2 = 7 and y2 = 6 indicates that the King is moved to the right side 2 tiles (King's side castling) if x2 == 7 and y2 == 6: #check if there exists a rook at the right end and the tiles between are empty if self.chessBoard[7][7] == "R" and self.chessBoard[7][5] == " " and self.chessBoard[7][6] == " ": #initialize these sets to check if they are attacked setA = [7,5] setB = [7,6] #Check_Opponent_Threat() is a function that detects all the threats that are made by a certain player for every_set in self.Check_Opponent_Threat("White", "Threat"): #if there exists a threat on the tiles that are about to be passed by the King, the castlingAbility variable will be set to false to deny the castling move if setA == every_set: castlingAbility = False if setB == every_set: castlingAbility = False #if there exists no threat on the selected tiles, the castling move can proceed if castlingAbility == True: #calling the makeMove function with parameter 1 to denote the white's castling move #calling the makeMove function for the second time with parameter 3 to denote the end of castling move KingMove.append((x1,y1,x2,y2)) RookMove.append((7,7,7,5)) self.makeMove(KingMove, 1) self.makeMove(RookMove, 3) else: pass #x2 = 7 and y2 = 2 indicates that the King is moved to the left side 2 tiles (Quuen's side castling) elif x2 == 7 and y2 == 2: #check if there exists a rook at the left end and the tiles between are empty if self.chessBoard[7][0] == "R" and self.chessBoard[7][1] == " " and self.chessBoard[7][2] == " " and self.chessBoard[7][3] == " ": #initialize these sets to check if they are attacked setA = [7,2] setB = [7,3] #Check_Opponent_Threat() is a function that detects all the threats that are made by a certain player for every_set in self.Check_Opponent_Threat("White", "Threat"): #if there exists a threat on the tiles that are about to be passed by the King, the castlingAbility variable will be set to false to deny the castling move if setA == every_set: castlingAbility = False if setB == every_set: castlingAbility = False if castlingAbility == True: #calling the makeMove function with parameter 1 to denote the white's castling move #calling the makeMove function for the second time with parameter 3 to denote the end of castling move KingMove.append((x1,y1,x2,y2)) RookMove.append((7,0,7,3)) self.makeMove(KingMove, 1) self.makeMove(RookMove, 3) else: pass #check to see if the castling move was made by black piece player elif colour == "Black" and x1 == 0 and y1 == 4: #x2 = 0 and y2 = 6 indicates that the King is moved to the right side 2 tiles (King's side castling) if x2 == 0 and y2 == 6: #check if there exists a rook at the right end and the tiles between are empty if self.chessBoard[0][7] == "r" and self.chessBoard[0][6] == " " and self.chessBoard[0][5] == " ": #initialize these sets to check if they are attacked setA = [0,6] setB = [0,5] #Check_Opponent_Threat() is a function that detects all the threats that are made by a certain player for every_set in self.Check_Opponent_Threat("Black", "Threat"): #if there exists a threat on the tiles that are about to be passed by the King, the castlingAbility variable will be set to false to deny the castling move if setA == every_set: castlingAbility = False if setB == every_set: castlingAbility = False if castlingAbility == True: #calling the makeMove function with parameter 2 to denote the black's castling move #calling the makeMove function for the second time with parameter 3 to denote the end of castling move KingMove.append((x1,y1,x2,y2)) RookMove.append((0,7,0,5)) self.makeMove(KingMove, 2) self.makeMove(RookMove, 3) else: pass #x2 = 0 and y2 = 2 indicates that the King is moved to the left side 2 tiles (Queen's side castling) elif x2 == 0 and y2 == 2: #check if there exists a rook at the right end and the tiles between are empty if self.chessBoard[0][0] == "r" and self.chessBoard[0][1] == " " and self.chessBoard[0][2] == " " and self.chessBoard[0][3] == " ": #initialize these sets to check if they are attacked setA = [0,2] setB = [0,3] #Check_Opponent_Threat() is a function that detects all the threats that are made by a certain player for every_set in self.Check_Opponent_Threat("Black", "Threat"): #if there exists a threat on the tiles that are about to be passed by the King, the castlingAbility variable will be set to false to deny the castling move if setA == every_set: castlingAbility = False if setB == every_set: castlingAbility = False if castlingAbility == True: #calling the makeMove function with parameter 2 to denote the black's castling move #calling the makeMove function for the second time with parameter 3 to denote the end of castling move KingMove.append((x1,y1,x2,y2)) RookMove.append((0,0,0,3)) self.makeMove(KingMove, 2) self.makeMove(RookMove, 3) else: pass #this function is to check a particular player's threat to the other player #this function is can also be used to return all the possible moves that can be made by a player, thus the paremeter desire is used accordingly #note that this function is not the same as the possibleMoves() function as possiblMoves() function can only be passed with one single character at one time (Means can only calculate the possible moves of one particular piece) def Check_Opponent_Threat(self, colour, desire): #create a list of pieces for black and white players mylists_for_black = ["p","r","n","b","q","k"] mylists_for_white = ["P","R","N","B","Q","K"] all_the_possible_moves = [] threats = [] #if the parameter was passed in with "White" colour, then the possible moves for black will be generated and vice versa if colour == "White": #iterate through all the 6 pieces for i in range(6): all_the_possible_moves += self.possibleMoves(mylists_for_black[i]) elif colour == "Black": #iterate through all the 6 pieces for i in range(6): all_the_possible_moves += self.possibleMoves(mylists_for_white[i]) else: pass #if the desire was only to calculate the possible moves, then the function shall return the possible moves immediately if desire == "PossibleMovesOnly": # print(all_the_possible_moves) return all_the_possible_moves else: #this loop returns just the last 2 values of the coordinate, 3 if there's a piece that can be captured for k in range(len(all_the_possible_moves)): #variable initialization is made here so that it will be emptied everytime a loop of k is made temp=[] temp1 = [] for j in range(2, len(all_the_possible_moves[k])): temp.append(all_the_possible_moves[k][j]) if j == len(all_the_possible_moves[k]) - 1: temp1.append((temp)) threats += temp1 #returns the list of the threats return threats #this function is used to check whether a player is in Check or not def CheckState(self,colour): #initialize the variables check_state = False colour_to_check = "" setA = [] #set the King's character according to the colour if colour == "White": setA = ["K"] colour_to_check = "White" elif colour == "Black": setA = ["k"] colour_to_check = "Black" #get the threats of the opponent player threat = self.Check_Opponent_Threat(colour_to_check, "Threat") #check if there exists a "K" or 'k' in the threats for each in threat: #comparison if set(setA) <= set(each): check_state = True #returns the boolean value of the check_state return check_state #this function is to check whether a player has been checkmated or not #this is the function that fires when a player is in check def Check_CheckMate(self, colour): if colour == "White": #by giving the parameter "PossibleMovesOnly" to the Check_Opponent_Threat() function, the function will return only the possible moves, not the threats. allPossibleMoves = self.Check_Opponent_Threat("Black", "PossibleMovesOnly") #initialize counter counter = 0 #iterate through all the possible moves for each_possible_move in allPossibleMoves: #get the coordinates of the possible moves x1 = each_possible_move[0] y1 = each_possible_move[1] x2 = each_possible_move[2] y2 = each_possible_move[3] self.character = self.chessBoard[x1][y1] #get the piece self.chessBoard[x1][y1] = " " #empty the current tile tempPiece = self.chessBoard[x2][y2] #get the piece in the tile that the move has been made to self.chessBoard[x2][y2] = self.character #replace the tile that the move was made to with the piece that the move was made #for every move of white that ends in check, the counter will be increased by 1 if self.CheckState("White") == True: counter = counter + 1 #undo back the move self.chessBoard[x1][y1] = self.character self.chessBoard[x2][y2] = tempPiece #if every single move of white ends in Check, that denotes Checkmate! if counter == len(allPossibleMoves): print("Checkmate") #Checkmate test for black elif colour == "Black": #by giving the parameter "PossibleMovesOnly" to the Check_Opponent_Threat() function, the function will return only the possible moves, not the threats. allPossibleMoves = self.Check_Opponent_Threat("White", "PossibleMovesOnly") #initialize counter counter = 0 #iterate through all the possible moves for each_possible_move in allPossibleMoves: #get the coordinates of the possible moves x1 = each_possible_move[0] y1 = each_possible_move[1] x2 = each_possible_move[2] y2 = each_possible_move[3] self.character = self.chessBoard[x1][y1]#get the piece self.chessBoard[x1][y1] = " " #empty the current tile tempPiece = self.chessBoard[x2][y2] #get the piece in the tile that the move has been made to self.chessBoard[x2][y2] = self.character #replace the tile that the move was made to with the piece that the move was made #if every single move of black ends in Check, that denotes Checkmate! if self.CheckState("Black") == True: counter = counter + 1 #undo back the move self.chessBoard[x1][y1] = self.character self.chessBoard[x2][y2] = tempPiece #if every single move of black ends in Check, that denotes Checkmate! if counter == len(allPossibleMoves): print("Checkmate") #this function is used to check if there's a pawn that has reached the final rank def Promotion_Check(self, colour): #if the check is performed for the white piece player, then the row that should be checked is row 0 if colour == "White": row = 0 #if the check is performed for the white piece player, then the row that should be checked is row 7 if colour == "Black": row = 7 #this iterates through all the column in that particular row for i in range(8): #check if there is a pawn on that particular row if self.chessBoard[row][i] == "P": #if there exists a white pawn in the final rank, the Promotion_Pick() function will be called by passing three parameters. The colour of the piece, the row and the column the piece is located. self.Promotion_Pick("White", row, i) elif self.chessBoard[row][i] == 'p': #if there exists a black pawn in the final rank, the Promotion_Pick() function will be called by passing three parameters. The colour of the piece, the row and the column the piece is located. self.Promotion_Pick("Black", row, i) #this function is called when there is a promotion move available for any of the two players def Promotion_Pick(self, colour, row, column): #initiliaze the variable promotionpiece="" #these 2 lines is to prompt the players for their desired promotion piece print("What would you like your pawn to be promoted to? Default is Queen") promotionpiece = input() #for players that play the white pieces if colour=="White": if promotionpiece == "Rook": #replaces the pawn's position with a Rook self.chessBoard[row][column] = "R" elif promotionpiece == "Queen": #replaces the pawn's position with a Queen self.chessBoard[row][column] = "Q" elif promotionpiece == "Knight": #replaces the pawn's position with a Knight self.chessBoard[row][column] = "N" elif promotionpiece == "Bishop": #replaces the pawn's position with a Bishop self.chessBoard[row][column] = "B" else: #if the user did not enter anything, or entered something else other than the 4 words above, a Queen will be automatically given self.chessBoard[row][column] = "Q" #for players that play the black pieces if colour=="Black": if promotionpiece == "Rook": #replaces the pawn's position with a Rook self.chessBoard[row][column] = "r" elif promotionpiece == "Queen": #replaces the pawn's position with a Queen self.chessBoard[row][column] = "q" elif promotionpiece == "Knight": #replaces the pawn's position with a Knight self.chessBoard[row][column] = "n" elif promotionpiece == "Bishop": #replaces the pawn's position with a Bishop self.chessBoard[row][column] = "b" else: #if the user did not enter anything, or entered something else other than the 4 words above, a Queen will be automatically given self.chessBoard[row][column] = "q"
7f1fcf06375b00e37d2392f156dca1eed924db7e
PengchongLiu/Algorithms
/w2_grundy_table.py
1,296
3.59375
4
#! python3 def mex(nums) -> int: ''' Find the smallest non-negative integer in a list by create a Python set ''' tmp = set(nums) cnt = 0 for t in tmp: if t != cnt: return cnt cnt += 1 return cnt def findGrundy(G: list, V: int, W: int) -> list: for v in range(1, V + 1): for w in range(1, W+1): if v == w: continue if not G[v][w]: positions = [] for i in range(v): positions.append(G[i][w]) for j in range(w): positions.append(G[v][j]) G[v][w] = mex(positions) if __name__ == "__main__": V = 4 # Size of the first pile W = 4 # Size of the second pile G = [[None for _ in range(W+1)] for _ in range(V+1)] # Grundy Table G(V,W) # Initialize boundary cases: # G(i,0) and G(0,i) are winning positions for i in range(V+1): G[i][0] = i for j in range(W+1): G[0][j] = j # G(i,i) are losing postions for i in range(min(V+1, W+1)): G[i][i] = 0 findGrundy(G, V, W) print("GrundyTable of dimension (V,W):") for i in range(V+1): print(G[i]) # Check mex: # nums = [1, 1, 6, 2] # print(mex(nums))
f05c03f1e56759cf3a119d27dfaee4806b197b2f
leonhanimichi/Evangelion
/references/basicStockTrader.py
17,739
3.671875
4
#!/usr/bin/python ''' Created on Aug 15, 2017 @author: Leon (Jobs), Junaid (Woz) ''' import pandas as pd import numpy as np import random as rrand import math as math from pandas_datareader import data as dreader from pylab import * #Used to calculate Mean and maybe more stuff didn't check, can probably replace/get rid of it #Class for doing trading on historical price data as if you only had data for that day and previous days. class Trader: def __init__(self, init, dailyaction): ''' Just pass in your own init and dailyaction functions. ''' self.init = init self.dailyaction = dailyaction self.portfolio = {'money': 0} self.transactions = [] #No idea what this func is for def actionNum(self,act,stknum): ''' No Idea what this is for... ''' return act+(stknum*10) def run(self, DATA, startmoney=100000, fee=.02, closePriceName='Close'): ''' Runs your trading algorithm. First calls your init function, then runs your code. \ Starting money is 100k default. Fee for trading is set to 2 cents per share. closePriceName is set to "Close", which works when importing data from google, but for yahoo might want to use "Adj Close" for example. some other sites might make it "close" instead. ''' self.DATA = DATA self.fee = fee self.closePriceName = closePriceName self.startmoney = startmoney for stocks in DATA.keys(): self.portfolio[stocks] = 0 for x in np.array(DATA[DATA.keys()[0]][self.closePriceName]): self.transactions.append([]) self.day = 0 self.portfolio['money'] = startmoney self.init(self) for x in range(0,len(np.array(DATA[DATA.keys()[0]][self.closePriceName]))): self.day = x self.dailyaction(self) x = self.lastday() #debug: make sure x isn't out of bounds of the data if you want to print stuff after it runs def buystocks(self,stockname,amount): ''' Buys stocks for the stock name, at most the number given by amount. If too expensive, buys as many as you can. Note fee is added so might be able to buy less than you thought. ''' price = np.array(self.DATA[stockname][self.closePriceName])[self.day] + self.fee amt = int(amount) moneyb4 = self.portfolio['money'] if price*amount > self.portfolio['money']: amt = int(moneyb4/price) self.portfolio['money'] -= amt * price assert self.portfolio['money'] >= 0 self.portfolio[stockname] += amt self.transactions[self.day].append([stockname,amt,price,self.portfolio[stockname],self.portfolio['money']]) return amt, price, self.portfolio[stockname],self.portfolio['money'] def buystockspercentage(self,stockname,perc): ''' perc should be fraction of how much of your portfolio you want to spend, so perc must be between 0-1 Buy stocks for the stockname. Buys as many stocks as you can afford based on perc*cash you have. So if perc is .5, will buy as many stocks as you can afford based on half the cash you have. ''' if perc < 0: "ERROR: Trying to buy stock by percentage but perc is set to less than 0!" perc = 0 if perc> 1: "ERROR: Trying to buy stock by percentage but perc is set to >1. Will buy as if perc = 1" perc = 1 price = np.array(self.DATA[stockname][self.closePriceName])[self.day] + self.fee moneyb4 = self.portfolio['money'] amt = int((perc*moneyb4)/price) self.portfolio['money'] -= amt * price assert self.portfolio['money'] >= 0 self.portfolio[stockname] += amt self.transactions[self.day].append([stockname,amt,price,self.portfolio[stockname],self.portfolio['money']]) return amt, price, self.portfolio[stockname],self.portfolio['money'] def sellstocks(self,stockname, amount): ''' Sells stocks for stockname by amount. If amount is greater than the number of stocks you have, sells all the stocks. For short selling use sellshort function. ''' price = np.array(self.DATA[stockname][self.closePriceName])[self.day] - self.fee amt = int(amount) moneyb4 = self.portfolio['money'] if amount > self.portfolio[stockname]: amt = self.portfolio[stockname] self.portfolio['money'] += amt * price assert self.portfolio['money'] >= 0 self.portfolio[stockname] -= amt #assert self.portfolio[stockname] >= 0 #TODO: comment out for support for short selling self.transactions[self.day].append([stockname,amt,price,self.portfolio[stockname],self.portfolio['money']]) return amt, price, self.portfolio[stockname],self.portfolio['money'] def sellshort(self,stockname,amount): ''' Short sells stocks. Sells stocks you don't have now, but then your portfolio has "negative" stocks. Note, not totally realistic because in real life you have a time limit on when you can pay-back the stocks you borrowed. ''' price = np.array(self.DATA[stockname][self.closePriceName])[self.day] - self.fee amt = int(amount) moneyb4 = self.portfolio['money'] if price*amount > self.portfolio['money']: amt = int(moneyb4/price) if self.portfolio[stockname] < 0: amt = 0 self.portfolio['money'] += amt * price assert self.portfolio['money'] >= 0 self.portfolio[stockname] -= amt #assert self.portfolio[stockname] >= 0 #TODO: comment out for support for short selling self.transactions[self.day].append([stockname,amt,price,self.portfolio[stockname],self.portfolio['money']]) return amt, price, self.portfolio[stockname],self.portfolio['money'] #note fee is subtracted from price def sellstockspercentage(self,stockname, perc): ''' Sells percentage of stocks you have. ''' price = np.array(self.DATA[stockname][self.closePriceName])[self.day] - self.fee moneyb4 = self.portfolio['money'] amt = int(self.portfolio[stockname] * perc) self.portfolio['money'] += amt * price assert self.portfolio['money'] >= 0 self.portfolio[stockname] -= amt assert self.portfolio[stockname] >= 0 #TODO: comment out for support for short selling self.transactions[self.day].append([stockname,amt,price,self.portfolio[stockname],self.portfolio['money']]) return amt, price, self.portfolio[stockname],self.portfolio['money'] def todaysprice(self,stockname): ''' Returns the closing price of the day for given stockname ''' return np.array(self.DATA[stockname][self.closePriceName])[self.day] #Days includes today, so days=1 would be just todays info. def pricehistory(self,stockname,days,key): ''' Returns price history of stockname for the days "days", in the category "key". Including today. So stockname=AAPL, days=2, key="Close" would return closing price of AAPL for today, and yesterday. ''' retlist = [] for x in range(self.day-days+1,self.day+1): retlist.append(np.array(self.DATA[stockname][key])[x]) assert len(retlist) == days return retlist def lastday(self): ''' Returns the last index for "DATA" array provided on initialization ''' return len(self.transactions)-1 def totalmoney(self): ''' Returns: total portfolio value+cash, just portfolio value, stock indexes originally given. Mostly first two are important, last one is for debugging mostly. ''' total = 0 #print total, "start" keys = self.DATA.keys() #print keys for key in keys: #assert self.portfolio[key] >= 0 #print self.portfolio[key] total += self.portfolio[key] * self.todaysprice(key) #print total, key, self.portfolio[key] #print "Stocks checked, total money from stocks: ", keys, total totalstks = total total+= self.portfolio['money'] assert self.portfolio['money'] >= 0 #print total return total, totalstks, keys #doesn't return the extra junk def totalmoneysimple(self): ''' Just returns total portfolio value+cash ''' total = 0 #print total, "start" keys = self.DATA.keys() #print keys for key in keys: #assert self.portfolio[key] >= 0 #print self.portfolio[key] total += self.portfolio[key] * self.todaysprice(key) #print total, key, self.portfolio[key] #print "Stocks checked, total money from stocks: ", keys, total totalstks = total total+= self.portfolio['money'] assert self.portfolio['money'] >= 0 #print total return total #I don't use this anymore I think but useful data structure. Can ignore for now. class circularList: def __init__(self, size, initVal = 0): self.size = size self.clist = [] for x in range (0,size): self.clist.append(initVal) def getElement(self,loc): return self.clist[loc] def getMostRecent(self): return self.clist[self.size-1] def shiftList(self): for x in range(1, self.size): self.clist[x-1] = self.clist[x] def addElement(self,value): self.shiftList() self.clist[self.size-1] = value stocks = ['QQQ','SPY','DIA', 'EBAY','YHOO','EA','GOOG', 'ATVI', ] #Get data for stocks, from google, starting at 2012-01-15 ending at 2016-09-01 testdata = dreader.DataReader(stocks,'google','2012-01-15','2016-09-01') #Use this to print general structure of the data print "DATA: ", testdata exit() #print pnls.keys(), pnls['Close']['GOOG'][0] #Have to swapaxes because my Trader class uses it like data[stockname]['Close'] testdata = testdata.swapaxes(0,2) #The way it works is all you need is an init function and a dailyaction function, which I make here: #This is my init function, given to and then called by "Trader" class later, just sets up some arrays I use for storage later that I use to track what my algo did. def myinit(self): self.i = 0 self.beststk = "YHOO" #No idea why but my example algo bases its STD off of this stock self.holding = [] self.pricelevellow = [] self.pricelevelhigh = [] self.oldprice = [] for x in range(0,len(stocks)): self.holding.append(0) self.pricelevellow.append(0) self.pricelevelhigh.append(0) self.oldprice.append(0) self.movehist = [] self.totaltrades = 0 #Helper function that just calculates STD def getSTD(prices): avg = mean(prices) totalstd = 0 for x in prices: diff = x-avg totalstd += (diff *diff) totalstd = totalstd/len(prices) return math.sqrt(totalstd) #Helper function that tells me if there is a uptrend since yesturday def uptrend(prices): diff = prices[-1] - prices[0] if diff> 0 : return True else: return False #Helper function that gets the price change since yesturday in relation to STD. def stdchange(prices): std = getSTD(prices) diff = prices[-1] - prices[0] return float(diff/std) #This is what my algo's dailyaction function. Its pretty much bullshit, I don't really know why it does what it does but you can use it as example of what you could do. def myAction(self): self.i += 1 #Constants that impact this trading algo minDaysToPredict = 10 sellSTD = 2 buySTD = .5 actSTD = .5 if self.i< (minDaysToPredict) :#going to get shitty training if you don't have a few days of data to look at first. #print "Skipping" #self.actionHistory.addElement(2) self.movehist.append("Wait to start") return moneytot, crap1,crap2= self.totalmoney() #Trader.pricehistory function gives you an array of prices for the given stockname, previous number of days to look at, and price type (open, close, etc). #So for example pricehistory('AAAPL',3,'Close') will give you the closing price aapl had for the previous 3 days. #I only use 'Close" here. opens = self.pricehistory(self.beststk,minDaysToPredict,'Open') closes = self.pricehistory(self.beststk,minDaysToPredict,'Close') highs = self.pricehistory(self.beststk,minDaysToPredict,'High') lows = self.pricehistory(self.beststk,minDaysToPredict,'Low') #get STD of recent days for closing price for "beststk" stdd = getSTD(closes) stknum = -1 for stk in stocks: stknum +=1 self.beststk = stk todaysPrice = self.todaysprice(self.beststk) #I stored how much of a stock I'm holding in self.holding. IDK because I can just use Trader.portfolio[stockName] if self.holding[stknum] != 0: #If you have some of the stock already, decide if you want to buy more, or sell it all if self.holding[stknum] > 0: #here I do some weird algo where I store the highest and lowest prices seen and trade based on that and STD if todaysPrice >= self.pricelevelhigh[stknum]: self.pricelevellow[stknum] = todaysPrice- (stdd* sellSTD) self.pricelevelhigh[stknum] = todaysPrice + (stdd * buySTD) return elif todaysPrice < self.pricelevellow[stknum]: self.sellstockspercentage(self.beststk,1) self.movehist.append("Sell"+self.beststk) print "Sold:", self.beststk, todaysPrice self.holding[stknum] = 0 print "Buy Profit:",todaysPrice-self.oldprice[stknum] self.totaltrades +=1 return else: #Buy back stocks maybe #only make holding positive if you buy back all your stocks if todaysPrice <= self.pricelevelhigh[stknum]: self.pricelevellow[stknum] = todaysPrice + (stdd* sellSTD) self.pricelevelhigh[stknum] = todaysPrice - (stdd * buySTD) return elif todaysPrice > self.pricelevellow[stknum]: #Here I buy stocks using Trader.buystocks self.buystocks(self.beststk,self.portfolio[self.beststk]*-1) self.movehist.append("Buyback"+self.beststk) print "Buyback:", self.beststk, todaysPrice #Here I use Trader.portfolio[stockname] to see if I have any stocks for beststk if self.portfolio[self.beststk] == 0: self.holding[stknum] = 0 print "Fully bought back" self.totaltrades +=1 print "Short Profit:",self.oldprice[stknum]-todaysPrice return else: #If you don't own any of that stock, think about buying more if stdchange(closes) > actSTD: amt = (moneytot / todaysPrice) * (1.0/len(stocks)) #amount of stocks to buy print moneytot, todaysPrice,(1.0/len(stocks)) print "Bought:", self.beststk,todaysPrice, amt self.buystocks(self.beststk,amt) self.pricelevelhigh[stknum] = todaysPrice + (stdd * buySTD) self.pricelevellow[stknum] = todaysPrice - (stdd* sellSTD) self.movehist.append("Buy"+self.beststk) self.holding[stknum] = 1 #set holding to 1 if you bought some stocks. elif stdchange(closes) < -1*actSTD: #shortsell amt = (moneytot / todaysPrice) * (1.0/len(stocks)) print "Short Sold:", self.beststk,todaysPrice, amt self.sellshort(self.beststk,amt) self.pricelevelhigh[stknum] = todaysPrice - (stdd * buySTD) self.pricelevellow[stknum] = todaysPrice + (stdd* sellSTD) self.movehist.append("Shortsell"+self.beststk) self.holding[stknum] = -1 #set holding to -1 if you shortsell a stock self.oldprice[stknum] = todaysPrice #Initialize "Trader". All you have to do is give it a "init" function and "myAction" (short for my action) function. #The trader will then run your dailyaction (myAction) function every day using the data you provide in run. #So for example you can make myAction function just "buy GOOG", and it will buy GOOG every day t = Trader(myinit,myAction) #Runs the Trader algorithm on the test data provided as if each datapoint is 1 day. t.run(testdata) #t.totalmoney() will return: total value of portfolio+cash, value in stocks (not cash), and lastly the stock names supplied in data(for debugging mostly). print "Total Moneys Made:", t.totalmoney() #Movehist is a giant array of every action the algorithm took. Note your dailyaction function should append these values to the array itself! print "MoveList: ", t.movehist #I manually stored how many trades I had in self.totaltrades print "Number of Total Trades: ", t.totaltrades
e758cfe3685fd64fc3bd2e1466e6b278350d5fed
hwang033/job_algorithm
/py/Balanced_Binary_Tree.py
1,001
3.828125
4
#Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a boolean def isBalanced(self, root): if not root: return True #return False if self.height(root) is False else True return self.height(root) def height(self, node): if node is None: return 0 if node.left is None and node.right is None: return 1 lh = self.height(node.left) lr = self.height(node.right) if lh is False or lr is False: return False elif lh - lr >= 2 or lh - lr <= -2: return False return max(lh + 1 , lr + 1) if __name__ == "__main__": n1 = TreeNode(1) n2 = TreeNode(2) n1.left = n2 s = Solution() print s.isBalanced(n1)
1a3110962c2ad63820ff69b0774eb7ba586e8f91
SanGReaL53/Class
/OddEvenSeparator.py
343
3.640625
4
class OddEvenSeparator: def __init__(self): self._odd = [] self._even = [] def add_number(self, num): if num % 2 == 1: self._odd.append(num) else: self._even.append(num) def even(self): print(self._even) def odd(self): print(self._odd)
f23d8c51b7fa1e32ca57e9416719a10fc5efcbd1
storans/as91896-virtual-pet-GBarrand7
/death_checker.py
1,835
4.28125
4
# Function to check if the cat has died or is near death # Parameters: # Weight - weight of pet # Low - lowest possible weight # High - highest possible weight # Boundary - range above the lowest weight or below the highest weight that if the cat's weight is in it is near being too low or high def death_checker(weight, low, high, boundary): # Too_low - message if the cat's weight is too low too_low = "You pet has died from starvation" # Too_high - message if the cat's weight is too high too_high = "Your pet has died from obesity" # Near_low - message is the cat's weight is near being too low near_low = "Make sure to feed your cat soon!" # Near_high - message is the cat's weight is near being too high near_high = "Make sure to exercise your cat soon" # If cat's weight is below the lowest weight if weight < low: print(too_low) # If cat's weight is above the highest weight elif weight > high: print(too_high) # If cat's weight is between the lowest weight and a weight near the lowest weight (e.g 3.5 - 3.8) elif low <= weight <= (low + boundary): print(near_low) # If cat's weight is below the highest weight and a weight near the highest weight (e.g 4.2 - 4.5 elif high >= weight >= (high - boundary): print(near_high) # If the cat is in a healthy weight range else: print("Your pet weighs {}kg".format(weight)) # Loop for testing all possible types of input for i in range(5): # Getting the weight of the pet from the user weight = float(input("How much does your pet weigh?")) # Using death checker to check if the entered weight is too high, too low, near the highest weight, near the lowest weight or fine and providing an appropriate feedback message death_checker(weight, 3.5, 4.5, 0.3)
aa98b3d9a66da7bf667e87fc26d4fa85dc114528
mspontes360/Programacao-Python-Geek-University
/section5/exercicio20.py
892
4.09375
4
""" Dados três valores, A, B, C, verificar se eles podem ser valores dos lados de um triângulo e, se é um triângulo escaleno, equilátero ou isóscele, considerando os seguintes conceitos: # O comprimento de cada lado de um triângulo é menor do que a soma dos outros dois lados. # Chama-se equilátero o triângulo que tem três lados iguais. # Denominam-se isósceles o triângulo que tem o comprimento de dois lados iguais. # Recebe o nome de escaleno o triângulo que tem os três lados diferentes. """ a = int(input("Enter the value of A: ")) b = int(input("Enter the value of B: ")) c = int(input("Enter the value of C: ")) if (a < b + c) or (b < a + c) or (c < a + b): if a == b == c: print("equilateral triangle") elif (a == b) or (a == c) or (c == b): print("isosceles triangle") else: print("scalene triangle")
c4326c4fb16248380e2aa0b857828a6d1e6dbd91
vzamyati/piscine_django
/d01/ex05/all_in.py
1,418
3.9375
4
import sys def look_for_state(trim_param, states, capital_cities): trim_param = trim_param.lower() trim_param = trim_param.title() if not states.get(trim_param): return 0 elif capital_cities.get(states[trim_param]): return(capital_cities[states[trim_param]]) else: return 0 def look_for_capital(trim_param, states, capital_cities): trim_param = trim_param.lower() trim_param = trim_param.title() for key, value in capital_cities.items(): if trim_param == value: for k, v in states.items(): if v == key: return(k) def main(): states = { "Oregon" : "OR", "Alabama" : "AL", "New Jersey": "NJ", "Colorado" : "CO" } capital_cities = { "OR": "Salem", "AL": "Montgomery", "NJ": "Trenton", "CO": "Denver" } params = sys.argv[1].split(",") for i in params: trim_param = i.strip() if trim_param: capital = look_for_state(trim_param, states, capital_cities) state = look_for_capital(trim_param, states, capital_cities) if capital: state = look_for_capital(capital, states, capital_cities) print("{} is the capital of {}".format(capital, state)) elif state: capital = look_for_state(state, states, capital_cities) print("{} is the capital of {}".format(capital, state)) else: print("{} is neither a capital city nor a state".format(trim_param)) if __name__ == '__main__': if len(sys.argv) == 2: main() else: sys.exit(0)
35656a3598781b8da855b8d0c4dd34ffa22a0b4b
dbmccoy/data
/pdx/generators.py
2,154
3.96875
4
def count_above_threshold(filename, threshold=6, column_number=2): with open(filename) as fi: headers = next(fi) return sum(1 for line in fi if float(line.split(",")[column_number]) > threshold) ## CHALLENGE 1: Generate a small CSV and prove to yourself that the above works. from random import normalvariate def random_walk_until(reaches=10, standard_deviation=0.1): last_position = 0 while abs(last_position) < until_reaches: new_position = last_position + normalvariate(0, standard_deviation) yield new_position last_position = new_position # from context_managers import Fig # # def show_random_walk(**keywords): # with Fig(2, clear=True, log_x=False, log_y=False): # for i in range(7): # plot(tuple(random_walk_until(**keywords)), alpha=0.6) ## CHALLENGE 2: Count the number of steps until a random walk reaches some value of interest for the first time. ## CHALLENGE 3: Run that counter many times and generate a histogram of the distribution of travel times to your distance of interest. def golden_ratio_min_finder(x_min, x_max): ratio = 0.5 * (5 ** 0.5 - 1) x_size = x_max - x_min x1 = x_max - ratio * x_size f1 = yield x1 x2 = x_min + ratio * x_size f2 = yield x2 while True: if f1 < f2: # print("switching x_max") x_max = x2 x2 = x1 f2 = f1 x_size = x_max - x_min x1 = x_max - ratio * x_size f1 = yield x1 else: # print("switching x_min") x_min = x1 x1 = x2 f1 = f2 x_size = x_max - x_min x2 = x_min + ratio * x_size f2 = yield x2 from math import inf def find_min(function, x_min, x_max, precision=1e-4, algorithm=golden_ratio_min_finder): finder = algorithm(x_min, x_max) # finder = algorithm(x_min, x_max, function) prior_x = inf current_x = finder.send(None) while abs(current_x - prior_x) > precision: prior_x = current_x current_x = finder.send(function(prior_x)) return current_x def simple_function(x): return 11.7 + x * (2.2 * x - 43.456790124) def second_function(x): return x**3 - 6*x**2 + 4*x + 12 ## CHALLENGE 4: Try another, not-as-simple function to minimize
e13be476a189c97c2dd425c604492f6aaef62ac2
jeffwright13/codewars
/multiple_split.py
1,239
4.5
4
def main(): print multiple_split.__doc__ def multiple_split(str, delimiters=[]): """ Give me a multiple_split ================= https://www.codewars.com/kata/split-string-by-multiple-delimiters ============================================= Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string. Example: -------- multiple_split('Hi, how are you?', [' ']) => # [Hi,', 'how', 'are', 'you?'] multiple_split('1+2-3', ['+', '-']) => ['1', '2', '3'] List of delimiters is optional and can be empty, so take that into account. Result cannot contain empty string. """ import string s = str for delim in delimiters: s = ' '.join(string.split(s, delim)) return string.split(s) if s != '' else None def test_multiple_split(): assert multiple_split('Hi everybody!', [' ','!']) == ['Hi', 'everybody'] assert multiple_split('(1+2)*6-3^9', ['+','-','(', ')','^','*']) == ['1', '2', '6', '3', '9'] assert multiple_split('Solve_this|kata-very\quickly!', ['!','|','\\','_','-']) == ['Solve', 'this', 'kata', 'very', 'quickly'] if __name__ == "__main__": main()
de1874dbdd0006c0660df5d8643cbed7566a0916
Volodymyr-SV/Python_367
/ClassWork1.py
362
3.90625
4
a=int(input("a=")) b=int(input("b=")) if a<b: print(b,">",a,", b bilshe") elif a>b: print(a,">",b,", a bilshe") else: print(a,"=",b,", rivni") ####################### c=int(input("c=")) if c % 2 == 0 : print("parne") else: print("neparne") ######################## d=int(input("d=")) f=1 for i in range(1,d+1): f=f*i print("factorial=",f)
8b0589ae4e32d42cdf071154b7ad1542f93c556a
HighHopes/codewars
/6kyu/Transform To Prime.py
1,390
4.1875
4
"""Given a List [] of n integers , find minimum mumber to be inserted in a list, so that sum of all elements of list should equal the closest prime number . Notes List size is at least 2 . List's numbers will only positives (n > 0) . Repeatition of numbers in the list could occur . The newer list's sum should equal the closest prime number . Input >> Output Examples 1- minimumNumber ({3,1,2}) ==> return (1) Explanation: Since , the sum of the list's elements equal to (6) , the minimum number to be inserted to transform the sum to prime number is (1) , which will make *the sum of the List** equal the closest prime number (7)* .""" import math def isPrime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False for i in range(5, int(math.sqrt(n) + 1), 6): if n % i == 0 or n % (i+2) == 0: return False return True def nextPrime(n): if n <= 1: return 2 prime = n found = False while(not found): prime += 1 if isPrime(prime) == True: found = True return prime def minimum_number(numbers): sum_of_lst = sum(numbers) if isPrime(sum_of_lst): return 0 else: next_prime = nextPrime(sum_of_lst) result = next_prime - sum_of_lst return result print(minimum_number([5,2]))
e33cfea21759fb6adabf13f6ffc36b79e3f18f9b
sehammuqil/python-
/day34.py
743
4.3125
4
def my_function(food): for x in food : print(x) fruits = ["apple","banana","cherry"] my_function(fruits) def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) def my_function(child3, child2 , child1): print("the youngest child is " + child3) my_function(child1="emil",child2="tobias",child3="linus") def my_function(*kids): print("the youngest child is"+ kids[2]) my_function("emil","tobias","linus") def tri_recursion(k): if (k > 0): result = k+tri_recursion(k-1) print(result) else: result = 0 return result print("\n\nRecursion example results") tri_recursion(6)
fc6b2246556488a48b9ff4b0b75ddfdc82decca3
officialstephero/codeforces
/Codeforces solutions/Bit++.py
213
3.59375
4
n = input() operations = [] for i in range(int(n)): k = input() operations.append(k) operations = "".join(operations) plus = operations.count('++') minus = operations.count('--') x = plus - minus print(x)
7d69a3f5fd473da6799f368d38bff6943b9b29de
kkotha4/Machine-Learning
/models/Softmax.py
2,984
3.984375
4
import numpy as np class Softmax(): def __init__(self): """ Initialises Softmax classifier with initializing weights, alpha(learning rate), number of epochs and regularization constant. """ self.w = None self.alpha = 0.2 self.epochs = 300 self.reg_const = 0.01 def calc_gradient(self, X_train, y_train): """ Calculate gradient of the softmax loss Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - X_train: A numpy array of shape (N, D) containing a minibatch of data. - y_train: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. Returns: - gradient with respect to weights W; an array of same shape as W """ grad_w=self.w weight_vector=X_train.dot(grad_w.T) weight_vector=(weight_vector.T-(np.max(weight_vector,axis=1))).T exponential_value=np.exp(weight_vector) for i in range(len(exponential_value)): sum_v=np.sum(exponential_value[i]) exponential_value[i]=exponential_value[i]/sum_v exponential_value[i,y_train[i]]-=1 weights_batch=exponential_value.T.dot(X_train) grad_w=grad_w-weights_batch*(self.alpha*self.reg_const/len(X_train)) return grad_w def train(self, X_train, y_train): """ Train Softmax classifier using stochastic gradient descent. Inputs: - X_train: A numpy array of shape (N, D) containing training data; N examples with D dimensions - y_train: A numpy array of shape (N,) containing training labels; Hint : Operate with Minibatches of the data for SGD """ nrows=len(set(y_train)) ncols=X_train.shape[1] self.w=np.random.random((nrows,ncols)) batch_size_list=[] batchsize=100 batch_size_list=[[X_train[size:size+batchsize],y_train[size:size+batchsize]]for size in range(0,len(X_train),batchsize)] for i in range(self.epochs): for batches in batch_size_list: self.w=self.calc_gradient(batches[0],batches[1]) def predict(self, X_test): """ Use the trained weights of softmax classifier to predict labels for data points. Inputs: - X_test: A numpy array of shape (N, D) containing training data; there are N training samples each of dimension D. Returns: - pred: Predicted labels for the data in X_test. pred is a 1-dimensional array of length N, and each element is an integer giving the predicted class. """ pred=[] for i in range(len(X_test)): value=X_test[i].dot(self.w.transpose()) class_v=np.argmax(value) pred.append(class_v) return pred
f3d31e42f7df36016d2fca4153b2188cb2b82566
RodolpheBeloncle/100-days-Python
/oop-coffee-machine-start/main.py
2,375
3.515625
4
import coffee_maker import menu from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine # Data MyCoffeeMachine = CoffeeMaker() Latte_Item = MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5) Espresso_Item = MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5) Cappuccino_Item = MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3) MenuList = Menu() MenuList.menu = [Latte_Item,Espresso_Item,Cappuccino_Item] MyCashMachine = MoneyMachine() on = True #------------- End Data Coffee Machine -------------- while on: while True: MyCashMachine.report() MyCoffeeMachine.report() id = 0 choice_list = {"1": "latte","2":"espresso","3": "cappuccino"} for choice in MenuList.menu: id += 1 print(f"Choice {id} : {choice.name}, Cost : {choice.cost},Water : {choice.ingredients['water']},milk : {choice.ingredients['milk']}, Coffee: {choice.ingredients['coffee']}") #-------------------------------------------- suggest_drink = int(input("What would you like? : 🧋latte : 1️⃣ / ☕︎ espresso : 2️⃣ /🥤cappuccino : 3️⃣ => press a number ")) MenuList.find_drink(MenuList.menu[suggest_drink - 1].name) if MyCoffeeMachine.is_resource_sufficient(MenuList.menu[suggest_drink - 1]) == False: on = False elif MyCashMachine.make_payment(MenuList.menu[suggest_drink - 1].cost) == False: break else: MyCoffeeMachine.make_coffee(MenuList.menu[suggest_drink - 1]) # ----- angela's solution ------ from menu import Menu from coffee_maker import CoffeeMaker from money_machine import MoneyMachine money_machine = MoneyMachine() coffee_maker = CoffeeMaker() menu = Menu() is_on = True while is_on: options = menu.get_items() choice = input(f"What would you like? ({options}): ") if choice == "off": is_on = False elif choice == "report": coffee_maker.report() money_machine.report() else: drink = menu.find_drink(choice) is_enough_ingredients = coffee_maker.is_resource_sufficient(drink) is_payment_successful = money_machine.make_payment(drink.cost) if is_enough_ingredients and is_payment_successful: coffee_maker.make_coffee(drink)
67390dc60c286926f88a6a6c94a127bf6bf928a8
ajpiter/CodeCombat
/Forest/ThumbBitter.py
447
3.78125
4
# If-statement code only runs when the if’s condition is true. # In a condition, == means "is equal to." if 2 + 2 == 4: hero.say("Hey!") if 2 + 2 == 5: hero.say("Yes, you!") # Change the condition here to make your hero say "Come at me!" if 3 + 4 == 7: # ∆ Make this true. hero.say("Come at me!") if 2 + 18 == 20: # ∆ Make this true. # Add one more taunt to lure the ogre. Be creative! hero.say("over here") pass
e2f785930ffc5a05a99780d4e502b7299f601416
V2xray1024/pyHack
/流程控制.py
1,150
4.25
4
''' Description: python 流程控制练习 Author: yrwang Date: 2021-08-30 18:25:59 LastEditTime: 2021-09-02 21:39:16 LastEditors: yrwang ''' # 单分支/双分支 age = int(input("your age is:")) if age < 25: print("you are a little boy!") else: print("you are old boy!") # 多分支 ''' if elif else ''' girl_age = 30 count = 0 while count < 3: count += 1 your_guess = int(input("输入你的猜测:")) if your_guess > girl_age: print("老娘永远18岁!") elif your_guess < girl_age: print("小嘴真甜!") else: print("看人真准!") break # 练习 打印成绩 while 1: grade = int(input("请输入成绩:")) if 90 <= grade and grade <= 100: print("你的成绩等级为:A!") elif 80 <= grade and grade < 90: print("你的成绩等级为:B!") elif 80 <= grade and grade < 90: print("你的成绩等级为:B!") elif 60 <= grade and grade < 80: print("你的成绩等级为:C!") elif 40 <= grade and grade < 60: print("你的成绩等级为:D!") else: print("你的成绩等级为:E!")
717d1e282f411a8bf9113fb6aa9dd8fc6de4f9af
kcnti/schoolWorks
/hackerrank/findingPercentage.py
351
3.53125
4
nums = int(input('how many: ')) lstName = [] for i in range(nums): _all = input("Put name and number: ") name = _all name = lstName.append(_all[0]) number = [int(x) for x in _all.split() if x.isdigit()] query_name = str(input("Who: ")) print(number) print(lstName) if query_name in lstName: print(sum(number)/len(number))
3e8c12e94ea0cb5dcdac63cf5eb76589f168cae0
SonawaneMayur/Algorithms_using_Data_Structures
/Python Code/Find Kth char.py
495
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 28 17:52:11 2017 @author: Mayur """ #code def getKthBit(bin_digit, blockId, offset): seed_value = int(bin_digit[blockId]) if seed_value: return (1^(bin(offset).count('1') % 2)) else: return ((bin(offset).count('1')) % 2) for i in range(int(input())): m, k, n = [int(i) for i in input().strip().split()] bin_m = bin(m)[2:] pow_n = 1 << n q, r = divmod(k, pow_n) print(getKthBit(bin_m, q,r))
89d24d1adb7792c3b7a6da995ba0361f7d5fac33
Manib92/Codewars
/5 Kyu/Weight for weight.py
2,229
4.0625
4
""" Weight for weight My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits. For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers? Example: "56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99" When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string. All numbers in the list are positive numbers and the list can be empty. Notes it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers Don't modify the input For C: The result is freed. """ def order_weight(strng): # your code # split string into list new_list = sorted(strng.split()) complete_total = [] for y in new_list: # total the digits for each number total = 0 for x in range(len(y)): total += int(y[x]) complete_total.append(total) my_dict_totals = dict(zip([x for x in range(len(complete_total))], complete_total)) # make a dict of the index and total of digits my_dict_weights = dict(zip([x for x in range(len(new_list))], new_list)) # Same for index and weights index_ordered = [key for key in sorted(my_dict_totals.iteritems(), key=lambda (k, v):(v, k))] # order the digits ordered_weights = [my_dict_weights[i] for (i, j) in index_ordered] # order the weights according to the order of the indices of the digits return " ".join(ordered_weights)
e571171f78b0069b529c1e429f8c0a1250323096
gbrayhan/Learn-Python
/Advance_3.py
549
4.15625
4
#Decalracion y conjuntos print('\n' *100) conjunto=set('8794') conjunto2={'3','2','4'}#Conjunto definido print(conjunto) print(conjunto2) #operaciones con conjuntos print(conjunto & conjunto2)#operacion interseccion print(conjunto.intersection(conjunto2))#Otra forma print(conjunto.union(conjunto2))# no se repiten los elementos en la union #Diferencia de conjuntos print(conjunto-conjunto2) print(conjunto.difference(conjunto2)) #Union exclusiva print(conjunto ^ conjunto2) print(conjunto.symmetric_difference(conjunto2)) print("Prueba")
b47ddca4fb16bc61585d6def82a0e704f8215a58
darrencheng0817/AlgorithmLearning
/Python/interview/practiceTwice/KthNumber.py
209
3.796875
4
''' Created on 2015年12月1日 https://leetcode.com/problems/kth-largest-element-in-an-array/ @author: Darren ''' def findKthLargest( nums, k): pass nums=[3,1,4,5,6,2,8,7] print(findKthLargest(nums, 3))
23991770683bfebf659e30db197d5c12b35bb945
Chalmiller/competitive_programming
/python/algorithms/arrays/sort/block_swap.py
399
3.734375
4
def swap(arr, index1, index2): temp = arr[index1] arr[index1] = arr[index2] arr[index2] = temp def leftRotate(arr, d, n): if (d == 0 or d == n): return i = d j = n - d while ( i != j): if (i < j): swap(arr, d - i, d + j - i, i) j -= i else: swap(arr, d - i, d, j) i -= j swap(arr, d - i, d, i)
49ffeaa0641c89b71674ec43a9294a5abdebdb50
peter-tang2015/cplusplus
/PetersPyProjects/PetersPyProjects/Dictionary/DictionaryTrie.py
3,645
3.671875
4
import sys class DictionaryTrie(object): """DictionaryTrie class""" def __init__(self): self.value = None self.children = dict() for idx in range(0, 26): self.children[ord('a') + idx] = None def GetChildren(self): return self.children def GetValue(self): return self.value def AddWords(self, words = None): if words is None: return try: for word in words: self.AddWord(word) except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected Error: ", sys.exc_info()[0]) def AddWord(self, word = None): if word is None: return try: leafNode = self; for char in map(ord, word): if leafNode.children[char] is None: leafNode.children[char] = DictionaryTrie() leafNode = leafNode.children[char] if leafNode.value is None: leafNode.value = word; except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected error: ", sys.exc_info()[0]) def FindWord(self, word): foundNode = self.FindWordAndGetNode(word) return foundNode is not None def FindWordAndGetNode(self, word): try: tempNode = self; for char in map(ord, word): if tempNode.children[char] is None: return None tempNode = tempNode.children[char] if tempNode.value == word: return tempNode return None except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected error: ", sys.exc_info()[0]) def RemoveWord(self, word): try: wordNode = self.FindWordAndGetNode(word) if wordNode is not None: wordNode.value = None except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected error: ", sys.exc_info()[0]) def __Traverse(self, root, result): try: for char in range(0, 26): tmpNode = root.children[ord('a') + char] if tmpNode is not None: if tmpNode.value is not None: result.append(tmpNode.value) self.__Traverse(tmpNode, result) except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected error: ", sys.exc_info()[0]) def Traverse(self): result = [] self.__Traverse(self, result) if len(result) == 0: return None return result def __FindPrefix(self, prefix): try: tempNode = self; for char in map(ord, prefix): if tempNode.children[char] is None: return None tempNode = tempNode.children[char] return tempNode except AttributeError as e: print ("AttributeError: {0}".format(e)) except: print ("Unexpected error: ", sys.exc_info()[0]) def QueryPrefix(self, prefix): tempNode = self.__FindPrefix(prefix) if tempNode is not None: result = [] self.__Traverse(tempNode, result) if len(result) > 0: return result return None
1e44b3da8ab5626dcf427a3ee3e9967df60f7cd7
Angelpacman/codecademy-py3
/Unit 05 Lists & Dictionaries/02 A Day at the Supermarket/1 Looping and lists/1-beFOR we begin.py
1,117
4.8125
5
"""BeFOR We Begin Before we begin our exercise, we should go over the Python for loop one more time. For now, we are only going to go over the for loop in terms of how it relates to lists and dictionaries. We'll explain more cool for loop uses in later courses. for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as follows: a = ["List", "of", "some", "sort"] for x in a: # Do something for every x This loop will run all of the code in the indented block under the for x in a: statement. The item in the list that is currently being evaluated will be x. So running the following: for item in [1, 3, 21]: print item would print 1, then 3, and then 21. The variable between for and in can be set to any variable name (currently item), but you should be careful to avoid using the word list as a variable, since that's a reserved word (that is, it means something special) in the Python language. """ names = ["Adam","Alex","Mariah","Martine","Columbus"] for word in names: print (word)
50d370309add178cdcc66fdc5880e60c1351f407
cs-fullstack-2019-fall/python-review2-cw-dekevion-hamida
/Dekevion.py
1,734
4.625
5
# Create a task list. A user is presented with the text below. #Congratulations! You're running [YOUR NAME]'s Task List program. # What would you like to do next? # 1. List all tasks. # 2. Add a task to the list. # 3. Delete a task. # 0. To quit the program # Let them select an option to list all of their tasks, add a task to their list, delete a task, or quit the program. # Make each option a different function in your program. # Do <strong>NOT</strong> use Google. Do <strong>NOT</strong> use other students. Try to do this on your own. #Extra Credit. Save the user's list in a text file. When the program is run again, # input that text file so their task list is not lost. taskList=["sweep the floor","clean the bathroom","do the laundry","cut the grass"] def listAlltasksfunc(): for i in taskList: print(i) def addToList(newtask): taskList.append(newtask) # add newtask to tasklist def deleteTask(taskTodelete): taskList.remove(taskTodelete) # remove instead of pop menu = -1 while menu != 4: menu = int(input('What would you like to do next \n' '1. List all tasks \n' '2. Add a task to the list \n' '3. Delete a task. \n' '4. To quit the program')) if menu == 1: print('The task List is:') listAlltasksfunc() if menu == 2: taskNew= input('Add to the task list here: ') f = open("file.txt","a") # opens file > file name> a for append f.write(taskNew) # writes file f.close() addToList(taskNew) # adds to task to original list if menu == 3: removeTask=input('what task would you like to delete ? ') deleteTask(removeTask)
183ed6ab72e9d462ef70605f7df6f085bff96a99
1992kly/grab-test
/first1.py
377
3.546875
4
def sumto(nums, tar): if len(nums): dic = {} for num in nums: dic[num] = num for num in nums: diff = tar - num if diff in dict.keys(): print("[%d,%d]" % (num, diff)) else: print("no exit") else: print("nums is empty") nums = [1,2] tar = 10 sumto(nums, tar)
20cb3eac9f9dbff9c1f13773d28d5949462f9d74
ztxcyk/python_test
/python100/20190527/def2.py
955
3.703125
4
# def gcd(x, y): # (x, y) = (y, x) if x > y else (x, y) # for factor in range(x, 0, -1): # if x % factor == 0 and y % factor == 0: # return factor #def lcm(x, y): # return x * y // Mygcd(x, y) # # #def Mygcd(x, y): # (x, y) = (y, x) if x > y else (x, y) # a=1 # for factor in range(1, x+1): # if x % factor == 0 and y % factor == 0: # a=factor # return a # #if __name__ == '__main__': # a = int(input('Please input the zhengzhengshu:')) # b = int(input('Please input the zhengzhengshu:')) # x = Mygcd(a,b) # print(x) # y = lcm(a,b) # print(y) def foo(): b = 'hello' def bar(): # Python中可以在函数内部再定义函数 c = True print(a) print(b) print(c) bar() #print(c) # NameError: name 'c' is not defined if __name__ == '__main__': a = 100 foo() #print(b) # NameError: name 'b' is not defined
229159b871beb70d22781a6503d06696e2608689
KlimchukNikita/Software_Engineering
/Lab 4/Sketch 7.py
859
4
4
#«Второй максимум» # Ввести последовательность S и вывести второй максимум этой последовательности, # т. е. элемент a∈S : ∃ b∈S : b>a и a⩾c ∀c∈S, c≠b # Если второго максимума нет, вывести NO # Пользоваться функциями наподобие max() или sorted() нельзя mas = [7, 7, 7, 7, 7, 7] maximum = mas[0] for i in range(1, len(mas)): if mas[i] > maximum: maximum = mas[i] maximums = maximum mas1 = mas for i in range(0, len(mas1)): if mas1[i] < maximum: maximums = mas1[i] if maximums == maximum: print("No") else: for i in range(0, len(mas1)): if mas[i] > maximums and mas1[i] < maximum: maximums = mas1[i] print(maximums)
85425de022e851591a1d0417744e30942b11a7a9
MaroderKo/Labs
/Kolokvium/Dopolnitelnie/39.py
711
3.71875
4
"""39. Дані про температуру повітря і кількості опадів за декаду квітня зберігаються в масивах. Визначити кількість опадів, що випали у вигляді дощу і у вигляді снігу за цю декаду.""" import random A = list() rain = 0 snow = 0 for n in range(10): nap = random.randint(0, 1) if nap == 1: A.append([True, random.randint(-30,30)]) if nap == 1: A.append([False, random.randint(-30,30)]) for n in A: if n[0] == True: if n[1] >-3: rain+=1 else: snow+=1 print("Rain:"+str(rain)) print("Snow:"+str(snow))
f18ff381f42d2735fb8d58a6620bf4b23d1435f0
VamshiPriyaVoruganti/HackerRank
/Programs/Introduction to Regex/hex color code.py
162
3.609375
4
import re for _ in range(int(raw_input())): color = "\n".join(re.findall(r':?.(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})',raw_input())) if color!='': print(color)
6023187ab4a68a4a76cceafa9d64fe11d583b858
mdolancode/Intro-To-Pytest
/tests/test_accum.py
5,844
3.578125
4
""" This module contains basic unit tests the the accum module. Their purpose is to show how to use the pytest framework by example """ # ------------------------------------------------------------------ # imports # ------------------------------------------------------------------ import pytest from stuff.accum import Accumulator # ------------------------------------------------------------------- # Fixture # ------------------------------------------------------------------- """ * Fixtures are special functions that pytest can call before test case functions. * They're the best way to handle "Arrange" steps shared by multiple tests in the context of the "Arrange-Act-Assert" pattern. * Fixtures are functions. * This accum fixture is concise because the only thing it needs to do is create a new Accumulator object. * Importantly, note that the function _returns _the newly constructed object. It does not assign the object to a global variable. A fixture should always return a value. * Remove the object creation line accum = Accumulator() and add a parameter to the test function signature named accum. * When pytest discovers a test case function, it looks at the function's parameter list. * If the function has parameters, then it will search for fixtures to match each parameter's name. * In our case, the test function has a parameter named accum, so pytest looks for a fixture named accum which it will find in the same module. * Pytest will then execute the fixture and pass the fixture's return value into the test case function. * Thus, in our test case, the accum variable will refer to the new Accumulator object created by the accum fixture. * This is a clever form of dependency injection. * The test case doesn't set up or "arrange" the test objects itself. * Instead, the fixture handles setup and injects the required objects as dependencies into the test function. * This separation of concerns makes test cases more readable, more consistent, and more maintainable. * It also makes new test cases easier to write. * pytest avoids the limitations of classes by structuring tests as functions. * Fixtures are simply the function-based way to handle setup and cleanup operations. * Fixtures can be used by any test function in any module, so they are universally shareable since they use dependency injection to share state, they protect tests against unintended side effects. Advanced Fixture Features * There are a few advanced tricks you can do with fixtures as well. If you want to share fixtures between multiple test modules, you can move it to a module in the "tests" directory named "conftest.py". * Conftest modules share test code for pytest. The name of the module is important. Pytest will automatically pick up any fixtures here. * A test case can also use multiple fixtures, just make sure each fixture has a unique name: @pytest.fixture def accum(): return Accumulator() @pytest.fixture def accum2(): return Accumulator() def test_accumulator_init(accum, accum2): assert accum.count == 0 * I also mentioned that fixtures can handle both setup _and _cleanup. If you use a yield statement instead of a return statement in a fixture, then the fixture function becomes something known in Python as a "generator". @pytest.fixture def accum(): yield Accumulator() print("DONE-ZO!") """ @pytest.fixture def accum(): return Accumulator() # ------------------------------------------------------------------ # Tests # ------------------------------------------------------------------ """ * Method test_accumulator_init() verifies that the new instance of the Accumulator class has a starting count of zero. * Method test_accumulator_add_one() verifies that the add() method adds one to the internal count when it is called with no other arguments. * Method test_accumulator_add_three() verifies that the add() method adds 3 to the count when it is called with the argument of 3. * Method test_accumulator_add_twice() verifies that the count increases appropriately with multiple add() calls. * Finally, method test_accumulator_cannot_set_count_directly() verifies that the count attribute cannot be assigned directly because it is a read-only property. Notice how we use pytest.raises to verify the attribute error. * Take a moment to review and study these tests functions. * You will notice that all of these unit tests follow a common pattern. * They construct an Accumulator object, they make calls to the Accumulator object, and they verify the counts of the Accumulator objects or else verify some error. """ @pytest.mark.accumulator def test_accumulator_init(accum): assert accum.count == 0 @pytest.mark.accumulator def test_accumulator_add_one(accum): accum.add() assert accum.count == 1 @pytest.mark.accumulator def test_accumulator_add_three(accum): accum.add(3) assert accum.count == 3 @pytest.mark.accumulator def test_accumulator_add_twice(accum): accum.add() accum.add() assert accum.count == 2 @pytest.mark.accumulator def test_accumulator_cannot_set_count_directly(accum): with pytest.raises(AttributeError, match=r"can't set attribute") as e: accum.count = 10 """ * This pattern is called "Arrange-Act-Assert". It is the classic three-step pattern for functional test cases. 1. Arrange assets for the test (like a setup procedure). 2. Act by exercising the target behavior. 3. Assert that expected outcomes happened. * Remember this pattern whenever you write test cases. Following this pattern will keep your tests simple, focused, and valuable. It will also help you separate tests by unique behaviors. * Notice how none of our tests take any more Act steps after their Assert steps. * Separate, small, independent tests make failure analysis easier in the event of a regression. """
e8497fb8b6f1614a01ff5387157a0acfb5049950
dsubhransu/pythonbeginner
/Day3_assingment/square_number.py
184
4.03125
4
def square_number_in_dictonary(): elements = int(input("Enter the elements")) for i in range(1,elements+1): print('{}:{}'.format(i,i*i)) square_number_in_dictonary()
9166772718b968ef75ab357a5199e81c128ca4c5
irfanmaulana126/hacktiv8_py43
/part_2/contoh_kondisi_2.py
155
3.578125
4
a = input("masukan angka: ") a = eval(a) # ini langsung menentukan tipe data if a % 2 == 0 and a > 5: print("masukan kedalam kondisi") else: pass
b756a91132488a7f03327ed64a443a42aa9e6647
StreamlitTest1/TeamPurple_Movie-Recommender-App
/views/main.py
1,796
3.546875
4
import streamlit as st # To make things easier later, we're also importing numpy and pandas for # working with sample data import numpy as np import pandas as pd import random class MainView(object): def __init__(self): self.load_data() def load_data(self): movies_df = pd.read_csv( 'movies.csv', encoding='latin-1', skiprows=1, index_col=0, sep='\t', names=['movie_id', 'title', 'genres'] ) self.movies_list = movies_df['title'].to_list() self.movies_list.sort() users_df = pd.read_csv( 'users.csv', encoding='latin-1', skiprows=0, index_col=0, sep='\t' ) self.user_list = users_df['user_id'].to_list() self.user_list.sort() def render(self): st.title('MovieRecommender App') form = st.form(key='my-form') form.markdown('Please choose a user from the list below') hint_text = 'Select or type to search' user = form.selectbox( 'User', [ hint_text, *self.user_list ] ) submit = form.form_submit_button('Submit') self.user_recommendations = st.empty() if submit: if hint_text in [user]: st.write('Please choose a user') else: self.show_prior_ratings(user) def show_prior_ratings(self,user): random_movies = random.choices(self.movies_list, k=10) movie_titles = "" for movie_title in random_movies: if len(movie_titles) > 0: movie_titles += "\n" movie_titles += movie_title self.user_recommendations.text(movie_titles)
0de29b2cf3730aeb6f7f498f568fe06d13f8bd49
songjiabin/PyDemo
/2爬虫/1、urllib爬虫网页.py
1,558
3.609375
4
import urllib.request # 向指定的url地址发起请求 ,并返回服务器响应的数据(文件的对象) respose = urllib.request.urlopen("http://www.jjmima.top") """ 这中读取方式不是很常用 # 得到二进制的数据 读取的事网页中的全部内容 会把读取到的内容赋值给一个字符串变量 data = respose.read() # 得到 指定编码的数据 data =respose.read().encode("utf-8") # 将得到的 data存储到文件中 path = r"E:\py_project_path\2爬虫\res\file.html" with open(path, "wb") as f: f.write(data) """ """ #使用这种方式需要循环操作 data =respose.readline() """ # 读取文件的全部内容 将读取到的数据给一个列表 变量 data = respose.readlines() # 需要一行一行的写 path = r"E:\py_project_path\2爬虫\res\基本密码博客.html" for i in data: with open(path, "a") as f: f.write(i.decode("utf-8")) print(data) print(type(data)) print(len(data)) # 返回当前环境的有关信息 print(respose.info()) # 返回状态码 print(respose.getcode()) # 返回当前正在爬去的url地址 print(respose.geturl()) # 解码 BDurl = r"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=%E5%9F%BA%E6%9C%AC%E5%AF%86%E7%A0%81&rsv_pq=ce8b339e0008217c&rsv_t=418bvgyIbahFPS%2F9KJoyaeyIJHdgL55o5LdhC9bHesV4zdD5gye5aJYbmrY&rqlang=cn&rsv_enter=1&rsv_sug3=11&rsv_sug1=13&rsv_sug7=101&rsv_sug2=0&inputT=5476&rsv_sug4=6404" newUrl=urllib.request.unquote(BDurl) print(newUrl) #编码 newUrl2=urllib.request.quote(newUrl) print(newUrl2)
a6132b53c2c9df1071b97ea449342d4de1d2ee93
dada99/python-learn
/builtin/string1.py
353
4.03125
4
str1 = '"Isn\'t," she said.' print(str1) s = 'First line.\nSecond line.' # \n means newline print(s) # with print(), \n produces a new line format_str = "this is {}'s books".format("Chris") print(format_str) print(format_str.capitalize()) print(format_str.count("s")) first_name = "Chris" last_name = "Liu" print(f'Hello, {first_name} {last_name}')
451bcef21f5541df1f3c7e84f9e986642442fe93
Carbocarde/learn-python
/1 - Hello World/unittests.py
741
3.859375
4
""" Check if your script is correct using this file. Run in the command line by typing: python unittests.py If you are in the PyCharm IDE, run this file by clicking the green arrow next to the main method: if __name__ == "__main__": """ import unittest from helloworld import hello class TestHello(unittest.TestCase): def test_steve(self): self.assertEqual("Hello Steve", hello("Steve")) def test_janette(self): self.assertEqual("Hello Janette", hello("Janette")) def test_lowercase_steve(self): self.assertEqual("Hello Steve", hello("steve")) def test_lowercase_janette(self): self.assertEqual("Hello Janette", hello("janette")) if __name__ == "__main__": unittest.main()
17d8c454ae1a1735bd95513d20557c50bbf55121
MridulGangwar/Leetcode-Solutions
/Python/Easy/543. Diameter of Binary Tree.py
729
3.65625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: def dfs(node): nonlocal diam if not node: return 0 leftTree = dfs(node.left) rightTree = dfs(node.right) diamNode = leftTree+rightTree+1 diam = max(diamNode,diam) return max(leftTree,rightTree)+1 diam = 0 dfs(root) if diam: diam-=1 return diam
84e0dc5fbd9764c6e7c08154c2d3b5d2fb7eddb6
ryfeus/lambda-packs
/Pdf_docx_pptx_xlsx_epub_png/source/pptx/compat/python3.py
812
3.75
4
# encoding: utf-8 """ Provides Python 3 compatibility objects """ from io import BytesIO # noqa def is_integer(obj): """ Return True if *obj* is an int, False otherwise. """ return isinstance(obj, int) def is_string(obj): """ Return True if *obj* is a string, False otherwise. """ return isinstance(obj, str) def is_unicode(obj): """ Return True if *obj* is a unicode string, False otherwise. """ return isinstance(obj, str) def to_unicode(text): """ Return *text* as a unicode string. All text in Python 3 is unicode, so this just returns *text* unchanged. """ if not isinstance(text, str): tmpl = 'expected unicode string, got %s value %s' raise TypeError(tmpl % (type(text), text)) return text Unicode = str
62d96ca31a2b08d8b1670be007b5c9e471f1a796
vishnupsatish/CCC-practice
/2012/J5/J5.py
3,278
3.9375
4
""" Problem: CCC 2012 S4/J5 Name: Vishnu Satish Solution: For each list, find all of the possible moves then perform a BFS for all of the possible moves. Eventually, either return IMPOSSIBLE or the current level """ # Find all of the possible moves def get_possible_moves(original): possible_moves = [] # Iterate over the list to find all possible moves for i, e in enumerate(original): # If the current element is the middle, set neighbours to each side, but if the # current element is the first or the last one, set it to the one after or before if i == 0: neighbours = [i + 1] elif i == len(original) - 1: neighbours = [i - 1] else: neighbours = [i - 1, i + 1] # For each neighbour, add a possible move to the list to be returned for n in neighbours: possible_moves.append(original.copy()) # If both the neighbour and current element have no coin, continue if possible_moves[-1][n] == '' and possible_moves[-1][i] == '': pass # If the neighbour is empty, place the coin at the top of the stack into the neighbour elif possible_moves[-1][n] == '': possible_moves[-1][n] = possible_moves[-1][i][0] possible_moves[-1][i] = possible_moves[-1][i].replace(possible_moves[-1][i][0], "") # If the current stack is empty, continue elif possible_moves[-1][i] == '': pass # If both the neighbour and the stack have a coin, then add the top of the # stack from the current to the top of the neighbour, if there is a possibility else: if possible_moves[-1][n][0] < possible_moves[-1][i][0]: continue possible_moves[-1][n] = "".join(sorted(list(possible_moves[-1][i][0] + possible_moves[-1][n]))) possible_moves[-1][i] = possible_moves[-1][i].replace(possible_moves[-1][i][0], "") unique_p = [] # Make sure the list of moves is unique for move in possible_moves: if move not in unique_p: unique_p.append(move) # Remove the original (input) list from the return list return list(filter(original.__ne__, unique_p)) # Run a BFS while finding the possible moves of a given list def determine_bfs(l): # Create a visited array visited = [l] # Track the level to eventually be returned h = [(l, 0)] while h: # Get all moves for a given list, then if it is not # visited, add it to the queue and mark it as visited to_get_moves = h.pop(0) all_moves = get_possible_moves(to_get_moves[0]) for m in all_moves: if m == sorted(m) and '' not in m: return to_get_moves[1] + 1 if m not in visited: h.append((m, to_get_moves[1] + 1)) visited.append(m) # If there is no possible answer, return IMPOSSIBLE return "IMPOSSIBLE" # Process the input, then print the value of the BFS for each test case while True: n = int(input()) if n == 0: break l = input().split() if sorted(l) != l: print(determine_bfs(l)) else: print(0)
478e763acf55aa5d3b95eeb64476d42e34a445b1
SoumyaDey1994/JS-Exercises
/Python/OOP Concepts/Class & Object/self parameter.py
1,036
3.59375
4
class ITCEmployees: companyName="ITC Infotech" def set_EmployeeDetails(self,name,designation,department,grade): self.name=name; self.designation=designation; self.department=department; self.grade=grade; def print_EmployeeDetails(self): print("Employee Name: " +self.name); print("Employee Designation: " +self.designation); print("Employee Department: " +self.department); print("Employee grade: " +self.grade); employeeSKD= ITCEmployees(); employeeSKD.set_EmployeeDetails("Soumya Dey", "Associate IT Consultant", "Innoruption", "IS1"); employeeGanesh= ITCEmployees(); employeeGanesh.set_EmployeeDetails("Ganesh Subhramanium","Delivery Manager", "BFSI_ADM", "IS6") print("\n Details of Employee 1:\n"); employeeSKD.print_EmployeeDetails() print("\n\n Details of Employee 2:\n"); employeeGanesh.print_EmployeeDetails() employeeSKD.age=23 print("\n Age of Employee 1: "+ str(employeeSKD.age)); employeeGanesh.age=41; print("\n Age of Employee 2: "+ str(employeeGanesh.age));
3cb1035408cfe7d536cc1bebf991d5d407aacce0
LakshmiManasaNuthalapati/manas
/Largest.py
209
4.09375
4
num1=input("") num2=input("") num3=input("") if(num1 >= num2) and (num1>=num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else largest = num3 print(largest)
787868ef0259be160061bd8f980304bcb5c919b9
gucky92/loris
/loris/app/wiki/utils.py
1,836
3.671875
4
""" """ import re from flask import url_for def clean_url(url): """ Cleans the url and corrects various errors. Removes multiple spaces and all leading and trailing spaces. Changes spaces to underscores and makes all characters lowercase. Also takes care of Windows style folders use. :param str url: the url to clean :returns: the cleaned url :rtype: str """ url = re.sub('[ ]{2,}', ' ', url).strip() url = url.lower().replace(' ', '_') url = url.replace('\\\\', '/').replace('\\', '/') return url def wikilink(text, url_formatter=None): """ Processes Wikilink syntax "[[Link]]" within the html body. This is intended to be run after content has been processed by markdown and is already HTML. :param str text: the html to highlight wiki links in. :param function url_formatter: which URL formatter to use, will by default use the flask url formatter Syntax: This accepts Wikilink syntax in the form of [[WikiLink]] or [[url/location|LinkName]]. Everything is referenced from the base location "/", therefore sub-pages need to use the [[page/subpage|Subpage]]. :returns: the processed html :rtype: str """ if url_formatter is None: url_formatter = url_for link_regex = re.compile( r"((?<!\<code\>)\[\[([^<].+?) \s*([|] \s* (.+?) \s*)?]])", re.X | re.U ) for i in link_regex.findall(text): title = [i[-1] if i[-1] else i[1]][0] url = clean_url(i[1]) html_url = u"<a href='{0}'>{1}</a>".format( url_formatter('wikidisplay', url=url), title ) text = re.sub(link_regex, html_url, text, count=1) return text