text
stringlengths
37
1.41M
# The following code allowed us to locate and create files. import csv import os # The following code allowed us to locate the employee_data.csv excel file. csvpath = os.path.join("/Users/azpunit/Desktop/Extra-Python-Challenge/PyBoss/employee_data.csv") # The follwing code allowed us to store all the lists that are going to be appended to store the values that # are going to be populated in our new excel file. First_Name = [] Second_Name = [] Name = [] Employee = [] Date = [] New_Date = [] SSN = [] New_SSN = [] States = [] States_Initials = [] # This following code allowed us to create a dictionary to replace the lists of states by a list of the states initials. Rubric = {} us_state_abbrev = { 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', } # The following code was designed to append all the lists that we are going to zip in order to populate our columns in terminal # and then in our new excel file. with open(csvpath) as csvfile: csvreader = csv.reader(csvfile) csv_header = next(csvreader) for row in csvreader: Name = str(row[1]).split(" ") First_Name.append(str(Name[0])) Second_Name.append(str(Name[1])) Employee.append(int(row[0])) Date = str(row[2]).split("/") Date = format(str(Date[0]) + "-" + str(Date[1]) + "-" + str(Date[2])) New_Date.append(Date) SSN = str(row[3]).split("-") SSN = format(f"***-**-{SSN[2]}") New_SSN.append(SSN) States = (f"{us_state_abbrev[row[4]]}") States_Initials.append(States) Zip_Object = zip(Employee, First_Name, Second_Name, New_Date, New_SSN, States_Initials) for Employee_i, First_Name_i, Second_Name_i, New_Date_i, New_SSN_i, States_Initials_i in Zip_Object: print(f"{Employee_i}, {First_Name_i}, {Second_Name_i}, {New_Date_i}, {New_SSN_i}, {States_Initials_i}") # The following code allowed us to create the employee_customized.csv excel file. output_file = os.path.join("/Users/azpunit/Desktop/Extra-Python-Challenge/PyBoss/empleyee_customized.csv") # The following code allowed us to zip all the list that we thereafter populated on our new excel file. cleaned_csv = zip(Employee, First_Name, Second_Name, New_Date, New_SSN, States_Initials) # The following code allowed us to populate all the lists that we previously created and zipped together. with open(output_file, "w") as datafile: writer = csv.writer(datafile) writer.writerow(["Emp ID", "First_Name", "Second_Name", "DOB", "SSN", "State"]) writer.writerows(cleaned_csv)
#main.py # Import the Flask module that has been installed. from flask import Flask, jsonify # Creating a "books" JSON / dict to emulate data coming from a database. books = [ { "id": 1, "title": "Harry Potter and the Goblet of Fire", "author": "J.K. Rowling", "isbn": "1512379298" }, { "id": 2, "title": "Lord of the Flies", "author": "William Golding", "isbn": "0399501487" } ] # Creating a new "app" by using the Flask constructor. Passes __name__ as a parameter. app = Flask(__name__) # Annotation that allows the function to be hit at the specific URL. @app.route("/") # Generic Python function that returns "Hello world!" def index(): return "Hello world!" # Annotation that allows the function to be hit at the specific URL. Indicates a GET HTTP method. @app.route("/library/v1.0/books", methods=["GET"]) # Function that will run when the endpoint is hit. def get_books(): # Returns a JSON of the books defined above. jsonify is a Flask function that serializes the object for us. return jsonify({"books": books}) # Annotation that allows the function to be hit at the specific URL with a parameter. Indicates a GET HTTP method. @app.route("/library/v1.0/books/<int:book_id>", methods=["GET"]) # This function requires a parameter from the URL. def get_book(book_id): # Create an empty dictionary. result = {} # Loops through all the different books to find the one with the id that was entered. for book in books: # Checks if the id is the same as the parameter. if book["id"] == book_id: # Sets the result to the book and makes it a JSON. result = jsonify({"book": book}) # Returns the book in JSON form or an empty dictionary. Should handle the error like 404, but will not cover here. return result # Checks to see if the name of the package is the run as the main package. if __name__ == "__main__": # Runs the Flask application only if the main.py file is being run. app.run()
num = float(input("Input float number: ")) print("'10' - {0:.2f} | 'e' - {0:e}".format(num))
import os import biblioteca_velha def main (): #the principle one, it calls all functions os.system ("clear") define = nome() define = xo(define) matriz = mtz () jogo(define, matriz) novo_jogo() def nome (): # this function recieve the names of players, allocate it, prints and return theses names jogador_1 = raw_input ("Jogador 1, qual o seu nome? ") print jogador_2 = raw_input ("Jogador 2, qual o seu nome? ") print print print ("%s vs %s" % (jogador_1, jogador_2)) print print nomes = {jogador_1: [], jogador_2: []} return nomes def xo (define): #this function let the player choose wich character he/she will use, allocate it and return a dictionary with this information lista_nome = define.keys() while True: define [lista_nome[0]] = raw_input("%s o que voce escolhe, X ou O? " %lista_nome[0]) define[lista_nome[0]] = define[lista_nome[0]].upper() if define [lista_nome[0]] == "X" or define [lista_nome[0]] == "O": break else: print "Resposta Invalida!" os.system ("clear") if define[lista_nome[0]] == "X": define[lista_nome[1]] = "O" print ("\n%s, lhe restou o O" %lista_nome[1]) else: define[lista_nome[1]] = "X" print ("\n%s, lhe restou o X" %lista_nome[1]) print print ("Ficou entao:\n") print ("%s: %s\n" % (lista_nome[0], define[lista_nome[0]])) print ("%s: %s\n" % (lista_nome[1], define[lista_nome[1]])) x = raw_input("Podemos comecar? Y/N? ") return define def mtz (): # this function creates a list of three lists and return it (matrix) mtz_1 = [" ", " ", " "] mtz_2 = [" ", " ", " "] mtz_3 = [" ", " ", " "] matriz = [mtz_1, mtz_2, mtz_3] return matriz def guarda (matriz,coordenada, lista, i, define): #this function allocates the "coordenada" where the player ask to mtz_1 = matriz [0] mtz_2 = matriz [1] mtz_3 = matriz [2] if coordenada[0] == "1": mtz_1 [int(coordenada[1]) - 1] = define [lista[i]] elif coordenada[0] == "2": mtz_2 [int(coordenada[1]) - 1] = define [lista[i]] else: mtz_3 [int(coordenada[1]) - 1] = define [lista[i]] matriz = [mtz_1, mtz_2, mtz_3] return matriz def printf (matriz): #This function prints the matrix in the format of the game mtz_1 = matriz [0] mtz_2 = matriz [1] mtz_3 = matriz [2] print " 1 2 3\n" print "1 %s | %s | %s" % (mtz_1[0], mtz_1[1], mtz_1[2]) print " -----------" print "2 %s | %s | %s" % (mtz_2[0], mtz_2[1], mtz_2[2]) print " -----------" print "3 %s | %s | %s" % (mtz_3[0], mtz_3[1], mtz_3[2]) print def novo_jogo(): #this function ask to the player if he/she wants to play again op = raw_input ("Jogar Novamente? Y/N? ") print op.lower() if op == "y": main () elif op == "n": print else: print "Resposta Invalida\n" novo_jogo() def jogo (define, matriz): #this fuction runs the game lista = define.keys() i = 0 j = 1 lista_1 = ["11", "12", "13", "21", "22", "23", "31", "32", "33"] while True: os.system ("clear") printf (matriz) while True: coordenada = raw_input("%s,qual a coordenada voce deseja? " % lista[i]) if coordenada in lista_1: break else: print "Resposta Invalida" matriz = guarda (matriz,coordenada, lista, i, define) if biblioteca_velha.verify (matriz, define, lista, j): printf (matriz) break j += 1 if i == 0: i = 1 else: i = 0 if __name__ == '__main__': main()
class DropletDoesNotExistsError(Exception): """Raised when a non defined droplet is modified""" def __init__(self, name: str) -> None: """ :param name: name of the droplet :type name: str :returns: nothing :rtype: None """ self.name = name self.msg = f"Droplet {self.name} does not exists..." def __str__(self) -> str: return self.msg class DropletExistsError(Exception): """Raises when the droplet that already exists in a bucket is re initialized.""" def __init__(self, droplet_name: str) -> None: self.name = droplet_name self.message = f"The droplet {self.name} already exists'..." def __str__(self) -> str: return self.message class DropletTypeError(Exception): """Raised when the object type cannot be pickled""" def __init__(self, droplet_name: str, obj: object) -> None: self.droplet_name = droplet_name self.message = f"Droplet of type '{type(obj)}' cannot be saved..." def __str__(self) -> str: return self.message
class Car: _speed: int _color: str _is_police: bool def __init__(self, color, speed, is_police): self._color = color self._speed = speed self._is_police = is_police def go(self): print("ะœะฐัˆะธะฝะฐ ะฟะพะตั…ะฐะปะฐ") def stop(self): print("ะœะฐัˆะธะฝะฐ ะพัั‚ะฐะฝะพะฒะธะปะฐััŒ") def turn(self, direction): print(f"ะœะฐัˆะธะฝะฐ ะฟะพะฒะตั€ะฝัƒะปะฐ {direction}") def show_speed(self): print(self._speed) def get_speed(self): return self._speed def get_color(self): return self._color def get_is_police(self): return self._is_police class TownCar(Car): def __init__(self, color, speed=60): super().__init__(color, speed, False) def go(self): super().go() if self._speed > 60: print("ะŸั€ะตะฒั‹ัˆะตะฝะฐ ัะบะพั€ะพัั‚ัŒ") class SportCar(Car): def __init__(self, color, speed): super().__init__(color, speed, False) class WorkCar(Car): def __init__(self, color, speed): super().__init__(color, speed, False) def go(self): super().go() if self._speed > 40: print("ะŸั€ะตะฒั‹ัˆะตะฝะฐ ัะบะพั€ะพัั‚ัŒ") class PoliceCar(Car): def __init__(self, color, speed): super().__init__(color, speed, True) town_car = TownCar("ะ–ะตะปั‚ั‹ะน", 60) town_car.go() town_car.stop() town_car.turn("ะ’ะปะตะฒะพ") town_car.show_speed() work_car = WorkCar("ะ–ะตะปั‚ั‹ะน", 60) work_car.go() work_car.stop() work_car.turn("ะ’ะปะตะฒะพ") work_car.show_speed() sport_car = SportCar("ะ–ะตะปั‚ั‹ะน", 60) sport_car.go() sport_car.stop() sport_car.turn("ะ’ะปะตะฒะพ") sport_car.show_speed() police_car = PoliceCar("ะ–ะตะปั‚ั‹ะน", 60) police_car.go() police_car.stop() police_car.turn("ะ’ะปะตะฒะพ") police_car.show_speed()
from itertools import count from itertools import cycle def iter_count(start=3, end=10): arr_ = [] for i in count(start): if i == end: return arr_ arr_.append(i) arr = iter_count() print(arr) def iter_cycle(arr_, times=10): i = 0 for x in cycle(arr_): print(x) i += 1 if i == times: exit(0) iter_cycle(arr)
x = 2 y = -2 def my_func(x, y): return x ** y print(my_func(x, y)) def my__func(x, y): temp = 1 for i in range(y, 0): temp = temp/x print(temp) my__func(x, y)
import pygame import pyttsx3 # pip install pyttsx3 # sudo apt install libespeak1 from time import sleep class Audio(object): """ The class used to process and play audio files in the game. Attributes: volume_to_distance -> list object with floats from 0 to 1 indicating volume to play a sound at footstep_volume -> float from 0 to 1 indicating volume to play footstep sound at """ def __init__(self): """Initalize the Audio class with default variable values""" self.volume_to_distance = [.6,.3,.1] self.footstep_volume = .1 self.get_audio_files() def get_audio_files(self): """Gathers audio files Attributes: ping_sound -> ping audio file hollow_sound -> hollow sound audio file stone_step -> list containing a series of six audio files that form the sound of footsteps Return values: None """ self.ping_sound = pygame.mixer.Sound("Sounds/drop.wav") self.hollow_sound = pygame.mixer.Sound("Sounds/bang.wav") self.stone_step = [] for i in range(1,7): self.stone_step.append(pygame.mixer.Sound("Sounds/stoneSteps/stone"+str(i)+".ogg")) def ping(self,sound): """Plays audio file Keyword arguments: sound -> audio file to play Return values: None """ audio_length = pygame.mixer.Sound.get_length(sound) channel = sound.play() channel.set_volume(1,1) sleep(audio_length) def echo(self,distance,direction,sound): """Plays audio file with respect to distance and direction of sound This function takes an audio file and implements stereo sound to give the player a more imersive experience and communicate information auditoraly Keyword arguments: distance -> integer between 1 and 3 indicating distance of sound direction -> string containing the direction that the sound is coming from ('front','back','left','right') sound -> audio file to play Return values: None """ volume = self.volume_to_distance[distance - 1] audio_length = pygame.mixer.Sound.get_length(sound) if direction == 'front' or direction == 'back': channel = sound.play() channel.set_volume(volume,volume) elif direction == 'right': channel = sound.play() channel.set_volume(0,volume) elif direction == 'left': channel = sound.play() channel.set_volume(volume,0) def string_to_speach(self,string,engine): """Converts a string into spoken word and speaks The function takes a string and audio engine and speaks the string with the voice of the audio engine. Keyword arguments: string -> a string of text engine -> engine to speak text that can have variables like rate, volume and volume_to_distance Return values: None """ engine.say(string) engine.runAndWait() def footstep_audio(self,count): """Plays a single footstep audio file The function will take in a count variable and play the respective footstep audio file Keyword arguments: count -> A variable that indicates which audio file to play Return values: None """ step = self.stone_step[count] channel = step.play() channel.set_volume(self.footstep_volume,self.footstep_volume) def home_screen_audio(self,audio_engine): """Audio for home screen """ self.string_to_speach('Sound Labyrinth',audio_engine) self.string_to_speach('Image of Footsteps',audio_engine) self.string_to_speach('Created for Software Design in the Fall of 2019 by Kyle Bertram, SeungU Lyu and Tim Novak ',audio_engine) self.string_to_speach('Press I for Instructions, Press C for credits, Press Space to play', audio_engine) def instruction_page_audio(self,audio_engine): """Audio for instruction page """ self.string_to_speach('The Game',audio_engine) self.string_to_speach("You find yourself trapped in the labyrinth, an endless maze between the world of the living and the dead. A place where souls are kept if they still have unfinished business, ties to the world or regrets for what they've done. In order to resolve your past life, you must now learn to help the other trapped souls move on. Only then can you yourself pass on to the afterlife.",audio_engine) self.string_to_speach('In the game you will navigate using echolocation, and you can see three meters in any direction. Use the A S W D keys to move in a direction, and use the arrow keys to ping in a direction',audio_engine) self.string_to_speach('Press C for credits, Press H to return to the Home screen, Press Space to play', audio_engine) def credits_page_audio(self,audio_engine): """Audio for credits page """ self.string_to_speach('About Sound Labyrinth',audio_engine) self.string_to_speach('Sound Labyrinth is an accessible videogame which is designed to provide the same experience to people with a range of sensory abilities. People with a visual impairment can navigate the game via audio input, while people who have hearing impairments can navigate with visual input.',audio_engine) self.string_to_speach('This game was created by Kyle Bertram, SeungU Lyu and Tim Novak as the final project for Software Design at Olin College of Engineering.',audio_engine) self.string_to_speach('Press H to return to the home screen', audio_engine) if __name__ == "__main__": #engine = pyttsx3.init(); #engine.say("I will speak this text") #engine.runAndWait() ## Walking Audio footstep_count = 0 pygame.init() pygame.mixer.init() audio = Audio() if footstep_count < 6: footstep_count += 1 audio.footstep_audio(footstep_count) else: footstep_count = 0 """ pygame.mixer.init() ping_sound = pygame.mixer.Sound("Sounds/ping_2.wav") hollow_sound = pygame.mixer.Sound("Sounds/drop.wav") stone_step = [] for i in range(1,7): stone_step.append(pygame.mixer.Sound("Sounds/stoneSteps/stone"+str(i)+".ogg")) ping(ping_sound) echo(3,'left',hollow_sound) ping(ping_sound) echo(2,'right',hollow_sound) ping(ping_sound) echo(1,'front',hollow_sound) """ # i = 0 # while i < 6: # #step = random.choice(stone_step) # step = stone_step[i] # step.play() # sleep(.2) # i+=1
import pygame import os import textrect class VisualView(): """ The class used to display the game on to a screen. Attributes: map -> GameMap object with all required objects to play the game width -> width of the screen in pixels height -> height of the screen in pixels img_size -> size to scale images when loaded margin -> margin in pixels screen -> initialized screen for display with width and height game_on -> boolean to check whether the game is running or not font_type -> font used to display dialogues """ def __init__(self, gamemap): """ Initalize the Audio class with default variable values gamemap: GameMap object """ self.map = gamemap self.width = self.map.pixel_size * 7 self.height = self.map.pixel_size * 7 self.img_size = 128 self.margin = 72 self.screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption("Sound Labyrinth") self.game_on = True self.font_type = 'AmaticSC-Regular.ttf' self.load_images() self.show_clicks = True self.tick = 0 def load_images(self): """ Load all the images needed to show instruction page. """ self.control_img_size = 72 self.player = pygame.transform.scale(pygame.image.load('image/player.png'),(self.img_size,self.img_size)) self.wall = pygame.transform.scale(pygame.image.load('image/wall.png'),(self.img_size,self.img_size)) self.reaper = pygame.transform.scale(pygame.image.load('documents/NPCs/reaper/image.png'),(self.img_size,self.img_size)) self.fallen_ruler = pygame.transform.scale(pygame.image.load('documents/NPCs/fallen_ruler/image.png'),(self.img_size,self.img_size)) # load ASWD self.a = pygame.transform.scale(pygame.image.load('image/controls/a.png'),(self.control_img_size,self.control_img_size)) self.s = pygame.transform.scale(pygame.image.load('image/controls/s.png'),(self.control_img_size,self.control_img_size)) self.w = pygame.transform.scale(pygame.image.load('image/controls/w.png'),(self.control_img_size,self.control_img_size)) self.d = pygame.transform.scale(pygame.image.load('image/controls/d.png'),(self.control_img_size,self.control_img_size)) #load arrow NEED TO ADD IN ARROW IMAGE self.arrow = pygame.transform.scale(pygame.image.load('image/controls/a.png'),(self.control_img_size,self.control_img_size)) def clear_screen(self): """ Clear the screen by filling the whole screen with color black """ self.screen.fill((0,0,0)) def refresh_screen(self): """ Refresh the screenStart """ pygame.display.flip() def draw_screen(self): """ Draw all objects inside the GameMap object with respect to the Player object. Using right values for offset, Player is always showed in the center of the screen. """ x_offset = int(self.width/2) - self.map.player.rect.x - self.map.pixel_size/2 y_offset = int(self.height/2) - self.map.player.rect.y - self.map.pixel_size/2 for wall in self.map.wall_list: wall.draw_offset(self.screen, x_offset, y_offset) for NPC in self.map.NPC_list: NPC.draw_offset(self.screen,x_offset, y_offset) self.map.player.draw_offset(self.screen, x_offset, y_offset) def draw_sentence(self,sentence,size,rect_center): """ Draw sentence onto the screen. Arguments: sentence -> string to show on the screen size -> size of the font rect_center -> center coordinate to show the sentence """ pure_white = (255, 255, 255) white = (220,220,220) black = (0, 0, 0) font = pygame.font.Font(self.font_type,size) X = rect_center[0] Y = rect_center[1] text = font.render(sentence, True, white, black) textRect = text.get_rect() textRect.center = (X,Y) self.screen.blit(text,textRect) def draw_paragraph(self,sentence,size,rect): """ Draw paragraph onto the screen. Automatically aligns sentence so that they don't go out of border. Arguments: sentence -> string to show on the screen size -> size of the font rect -> rectangle to put the paragraph in """ white = (220,220,220) black = (0, 0, 0) font = pygame.font.Font(self.font_type,size) my_rect = textrect.render_textrect(sentence,font,rect,white,black,justification = 0) self.screen.blit(my_rect, rect.topleft) def draw_image(self,image,rect_center): """ Draw image onto the screen. Arguments: image -> image to draw rect_center -> center coordinate to show the image """ self.screen.blit(image,rect_center) def draw_rotated_image(self,image,angle,rect_center): """ Rotates an image counterclockwise with units of degrees """ new_image = pygame.transform.rotate(image,angle) self.draw_image(new_image,rect_center) def blink_text(self,sentence,size,rect_center,time): """ Blink a specific sentence with time interval Arguments: sentence -> string to show on the screen size -> size of the font rect_center -> center coordinate to show the sentence time -> time interval in milisecond """ if pygame.time.get_ticks() < self.tick + time: self.draw_sentence(sentence,size,rect_center) elif pygame.time.get_ticks() > self.tick + time*2: self.tick = pygame.time.get_ticks() def draw_aswd(self,aswd_center_x,aswd_center_y): """ Draw ASWD key image """ self.draw_image(self.a, [aswd_center_x-self.control_img_size*2//2, aswd_center_y+self.control_img_size//2]) self.draw_image(self.s, [aswd_center_x, aswd_center_y+self.control_img_size//2]) self.draw_image(self.w, [aswd_center_x, aswd_center_y-self.control_img_size//2]) self.draw_image(self.d, [aswd_center_x+self.control_img_size*2//2, aswd_center_y+self.control_img_size//2]) def draw_arrow(self,arrow_center_x,arrow_center_y): """ Draw arrow key image """ self.draw_rotated_image(self.arrow,90, [arrow_center_x-self.control_img_size*2//2, arrow_center_y+self.control_img_size//2]) self.draw_rotated_image(self.arrow,180, [arrow_center_x, arrow_center_y+self.control_img_size//2]) self.draw_rotated_image(self.arrow,0, [arrow_center_x, arrow_center_y-self.control_img_size//2]) self.draw_rotated_image(self.arrow,270, [arrow_center_x+self.control_img_size*2//2, arrow_center_y+self.control_img_size//2]) def draw_home_screen(self): """ Draw home screen with title, player image, and simple blinking instructions """ self.clear_screen() self.draw_sentence('Sound',96,[self.width//2,self.height//3-48]) self.draw_sentence('Labyrinth',96,[self.width//2,self.height//3+60]) self.draw_image(self.player, [self.width//2-self.img_size//2, self.height//2-self.img_size//2+48]) self.draw_sentence('Software Design - Fall 2019',48,[self.width//2, 3*self.height//4-30]) self.draw_sentence('Kyle Bertram SeungU Lyu Tim Novak',36,[self.width//2, 3*self.height//4+30]) self.draw_sentence('Kyle Bertram SeungU Lyu Tim Novak',36,[self.width//2, 3*self.height//4+30]) #self.blink_text('Press I for Instructions, Press C for Credits, Press Space to Start',36,[self.width//2, self.height - 96], 1000) self.draw_sentence('Press I for Instructions, Press C for Credits, Press Space to Play',36,[self.width//2, self.height - 96]) def draw_instructions(self): """ Draw instruction screen """ self.margin = 72 self.clear_screen() self.draw_paragraph('The Game',72,pygame.Rect((self.margin, 48, self.width - self.margin*2, 300))) self.draw_paragraph("You find yourself trapped in the labyrinth, an endless maze between the world of the living and the dead. A place where souls are kept if they still have unfinished business, ties to the world or regrets for what they've done. In order to resolve your past life, you must now learn to help the other trapped souls move on. Only then can you yourself pass on to the afterlife.", 36, pygame.Rect((self.margin, 144, self.width - self.margin*2, 300))) self.draw_paragraph('In the game you will navigate using echolocation, and are able to see three meters in any direction',36,pygame.Rect((self.margin, self.height//2-48, self.width - self.margin*2, 300))) self.draw_aswd(self.width//4,self.height//2+120) self.draw_sentence('Use ASWD keys to move',24,[self.width//4+48, self.height//2+160+120]) self.draw_arrow(3*self.width//4-self.control_img_size, self.height//2+120) self.draw_sentence('Use arrow keys to ping',24,[3*self.width//4-48, self.height//2+160+120]) self.draw_sentence('Press C for Credits, Press H for Home, Press Space to Start',36,[self.width//2, self.height - 96]) def draw_credits(self): """ Draw credit screen """ #'''CODE TO GENERATE REPRESENTITIVE IMAGES #self.draw_image(self.player, [self.width//2-self.img_size//2, self.height//2-self.img_size//2+48]) #self.draw_image(self.fallen_ruler, [self.width//2-self.img_size//2+2*128, self.height//2-self.img_size//2+48]) self.draw_paragraph('About Sound Labyrinth',72,pygame.Rect((self.margin, 48, self.width - self.margin*2, 200))) self.draw_paragraph('Sound Labyrinth is an accessible videogame which is designed to provide the same experience to people with a range of sensory abilities. People with a visual impairment can navigate the game via audio input, while people who have hearing impairments can navigate with visual input.', 36, pygame.Rect((self.margin, 144, self.width - self.margin*2, 300))) self.draw_paragraph('This game was created by Kyle Bertram, SeungU Lyu and Tim Novak as the final project for Software Design at Olin College of Engineering.', 36, pygame.Rect((self.margin, 144 + 196 + 24, self.width - self.margin*2, 300))) self.draw_sentence('Press H for Home',36,[self.width//2, self.height - 96]) def close_screen(self): """ Check whether the use pressed close button on the window If clicked, set game_on to False so that the game is not being played anymore. """ for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_on = False
import random print("***************WELCOME TO CHATBOT GAME****************") def chatterbot(sentense): ques=input("Say Something Here=") a=ques.lower() # print(a) for word in sentense: # print(word) # break if word == a: print(random.choice(response[word])) again=input("Do you want play again=") if again=='yes': chatterbot(sentense) else: print("no thanks*** nice too meet you") response={"hello":["hi","hey","hello"],"how are you":['i m fine','good',"mast"],"hi":["hii","hey","hello"],"hey":["hi","hey","hello"]} chatterbot(response) # a = {"hello":["hi","hey","hello"]} # for x in a: # print(a[x])
from tkinter import* import random tk=Tk() canvas=Canvas(tk,width=500,height=500) canvas.pack() def rectangle(width,height,fill_color): x1=random.randrange(width) x2=x1+random.randrange(width) y1=random.randrange(height) y2=y1+random.randrange(height) canvas.create_rectangle(x1,x2,y1,y2,fill=fill_color) rectangle(400,400,'green') rectangle(400,400,'red') rectangle(400,400,'blue') rectangle(400,400,'orange') rectangle(400,400,'yellow') rectangle(400,400,'pink') rectangle(400,400,'purple') rectangle(400,400,'violet') rectangle(400,400,'magenta') rectangle(400,400,'cyan') tk.mainloop()
Numbers = 100 primes = [2] isprime = True for x in range(3,100): for d in primes: if x % d == 0: isprime = False if isprime: primes.append(x) print(x) isprime = True
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created Date: March 25. 2021 Author: Dae Jong Jin Description: Rename all files in the directory @example python3 change_filename.py --change $(directory path) --name $(desired_file_name) --type $(file_type) python3 change_filename.py --change test_dir --name file_name_ --type jpg ''' import os import natsort import argparse def changeName(path, afterName, file_type): startNumber = 0 cName_cnt = startNumber file_list = os.listdir(path) natsorted_files = natsort.natsorted(file_list,reverse=False) for filename in natsorted_files: if filename.endswith(file_type): cName_cnt += 1 print(filename, '=>', str(afterName)+str(cName_cnt)+file_type) os.rename(path+filename, path+str(afterName)+str(cName_cnt).zfill(6)+file_type) else: print("{}์€ ํ•ด๋‹นํ•˜๋Š” ํƒ€์ž…์˜ ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.".format(filename)) # shutil.rmtree(path+filename) # print("{}ํด๋”๊ฐ€ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(filename)) print("{}๊ฐœ์˜ ํŒŒ์ผ ์ค‘ {}๊ฐœ์˜ ํŒŒ์ผ์ด ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(len(natsorted_files), cName_cnt - startNumber)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="change_filename") ''' Command line options ''' parser.add_argument( '-ch','--change', type=str, required=True, nargs='+', help='--change file directory' ) parser.add_argument( '--name', type=str, required=True, help='--name Desired Name' ) parser.add_argument( '--type', type=str, required=True, help='--type jpg, txt, png ...' ) args = parser.parse_args() path = ''.join(args.change) + '/' changed_filename = ''.join(args.name) input_type = '.'+''.join(args.type) changeName(path, changed_filename, input_type)
def main(): inp=input() count2=0 count1=0 for each in inp: if(each == '('): count1+=1 elif(each==')'): count2+=1 if(count1<count2): return count1 else: return count2 print(main())
def main(): arr=[1,2,3,4] k=2 pointer=k-1 while(pointer>0): temp=arr[pointer] arr[pointer]=arr[pointer-1] arr[pointer-1]=temp pointer=pointer-1 print(arr) main()
from collections import Counter import numpy as np def generate_user_tweets_dict(names,tweets): '''generate dictionary tweets dictionary, where user is key and number of tweets as value ''' tweets_dict = {} tweets = Counter(tweets) for name in names: tweets_dict[name] = tweets[name] return tweets_dict def check_all_tweets_score_same(tweets_dict): '''checks if users are having same number of tweets and prints all the users in alphabetical order''' for key in sorted(tweets_dict.keys()): print(f'{key} {tweets_dict[key]}') def check_tweets_score_different(tweets_dict): '''Finds the user with max number of tweets and prints user name and total number of tweets.''' sorted_list = sorted(tweets_dict.items(),key=lambda x: x[1], reverse=True) if len(sorted_list) is not 1: for key,value in dict(sorted_list[:len(tweets_dict)-1]).items(): print(f'{key} {value}') else: for key,value in dict(sorted_list).items(): print(f'{key} {value}') def get_most_tweeted_user(tweets_dict): """ identtifys user with max number of tweet and prints user name and total number of tweets """ score = next(iter(tweets_dict.values())) all_equal = all(value == score for value in tweets_dict.values()) if all_equal: check_all_tweets_score_same(tweets_dict) else: check_tweets_score_different(tweets_dict) if __name__ == "__main__": """Read the input from console""" try: input_num = int(input()) tweets = [] for _ in range(input_num): """ Read the number of test cases input from console """ testcases_num = int(input()) while testcases_num > 0: tweet = input() tweets.append(tweet.split(" ")[0]) testcases_num -= 1 tweets = np.array(tweets) names = np.unique(tweets) tweets_dict = generate_user_tweets_dict(names,tweets) get_most_tweeted_user(tweets_dict) except Exception as e: print(e.args) else: print("------THANK YOU---------")
#to find sum of 3 numbers and return zero if two numbers are equal n1=int(input("Enter the value of 1st number")) n2=int(input("Enter the value of 2nd number")) n3=int(input("Enter the value of 3rd number")) s=n1+n2+n3 if n1==n2 or n2==n3 or n1==n3: print("0") else: print(s)
#!/usr/bin/python3 def weight_average(my_list=[]): if not my_list: return 0 return sum(x[0] * x[1] for x in my_list) / sum(x[1] for x in my_list)
#!/usr/bin/python3 """square """ from models.rectangle import Rectangle class Square(Rectangle): """Inherits from Rectangle """ def __init__(self, size, x=0, y=0, id=None): super().__init__(width=size, height=size, x=x, y=y, id=id) @property def size(self): return self.width @size.setter def size(self, value): """size needs to be an int """ self.width = value self.height = value def __str__(self): """Returns formatted information display """ return "[{}] ({}) {}/{} - {}".format(self.__class__.__name__, self.id, self.x, self.y, self.width) def update(self, *args, **kwargs): if len(kwargs) != 0: for k, v in kwargs.items(): setattr(self, k, v) elif len(args) != 0: try: self.id = args[0] self.size = args[1] self.x = args[2] self.y = args[3] except IndexError: pass else: print() def to_dictionary(self): """Returns a dict representation """ return {'id': self.id, 'x': self.x, 'size': self.width, 'y': self.y}
#!/usr/bin/python3 def add_integer(a, b=98): if not isinstance(a,(int, float)): raise TypeError("a must be an integer") if not isinstance(b,(int, float)): raise TypeError("b must be an integer") return int(a) + int(b)
#!/usr/bin/python3 """Student """ class Student: """Contains student data """ def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Retrieves dictionary of Student with conditions to filter """ if attrs is not None or type(attrs) != list: return self.__dict__ else: temp = {} for elem in attrs: if type(elem) != str: return self.__dict__ if elem in self.__dict__.keys(): temp[elem] = self.__dict__[elem] return temp def reload_from_json(self, json): """Replaces all items in `json` """ for items in json.keys(): self.__dict__[items] = json[items]
''' ้›†ๅˆ collectionsๆ˜ฏPythonๅ†…ๅปบ็š„ไธ€ไธช้›†ๅˆๆจกๅ—๏ผŒๆไพ›ไบ†่ฎธๅคšๆœ‰็”จ็š„้›†ๅˆ็ฑปใ€‚ namedtuple ๆˆ‘ไปฌ็Ÿฅ้“tupleๅฏไปฅ่กจ็คบไธๅ˜้›†ๅˆ๏ผŒไพ‹ๅฆ‚๏ผŒไธ€ไธช็‚น็š„ไบŒ็ปดๅๆ ‡ๅฐฑๅฏไปฅ่กจ็คบๆˆ๏ผš ''' p = (1, 2) ''' ไฝ†ๆ˜ฏ๏ผŒ็œ‹ๅˆฐ(1, 2)๏ผŒๅพˆ้šพ็œ‹ๅ‡บ่ฟ™ไธชtupleๆ˜ฏ็”จๆฅ่กจ็คบไธ€ไธชๅๆ ‡็š„ใ€‚ ๅฎšไน‰ไธ€ไธชclassๅˆๅฐ้ข˜ๅคงๅšไบ†๏ผŒ่ฟ™ๆ—ถ๏ผŒnamedtupleๅฐฑๆดพไธŠไบ†็”จๅœบ๏ผš ''' from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x) ''' deque ไฝฟ็”จlistๅญ˜ๅ‚จๆ•ฐๆฎๆ—ถ๏ผŒๆŒ‰็ดขๅผ•่ฎฟ้—ฎๅ…ƒ็ด ๅพˆๅฟซ๏ผŒไฝ†ๆ˜ฏๆ’ๅ…ฅๅ’Œๅˆ ้™คๅ…ƒ็ด ๅฐฑๅพˆๆ…ขไบ†๏ผŒๅ› ไธบlistๆ˜ฏ็บฟๆ€งๅญ˜ๅ‚จ๏ผŒๆ•ฐๆฎ้‡ๅคง็š„ๆ—ถๅ€™๏ผŒๆ’ๅ…ฅๅ’Œๅˆ ้™คๆ•ˆ็އๅพˆไฝŽใ€‚ dequeๆ˜ฏไธบไบ†้ซ˜ๆ•ˆๅฎž็Žฐๆ’ๅ…ฅๅ’Œๅˆ ้™คๆ“ไฝœ็š„ๅŒๅ‘ๅˆ—่กจ๏ผŒ้€‚ๅˆ็”จไบŽ้˜Ÿๅˆ—ๅ’Œๆ ˆ๏ผš ''' from collections import deque q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') print(q) # deque(['y', 'a', 'b', 'c', 'x']) ''' defaultdict ไฝฟ็”จdictๆ—ถ๏ผŒๅฆ‚ๆžœๅผ•็”จ็š„Keyไธๅญ˜ๅœจ๏ผŒๅฐฑไผšๆŠ›ๅ‡บKeyErrorใ€‚ๅฆ‚ๆžœๅธŒๆœ›keyไธๅญ˜ๅœจๆ—ถ๏ผŒ่ฟ”ๅ›žไธ€ไธช้ป˜่ฎคๅ€ผ๏ผŒๅฐฑๅฏไปฅ็”จdefaultdict๏ผš ''' from collections import defaultdict dd = defaultdict(lambda: 'N/A') print(dd['key2']) # N/A ''' Counter Counterๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„่ฎกๆ•ฐๅ™จ๏ผŒไพ‹ๅฆ‚๏ผŒ็ปŸ่ฎกๅญ—็ฌฆๅ‡บ็Žฐ็š„ไธชๆ•ฐ๏ผš ''' from collections import Counter c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print(c) # Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'n': 1, 'i': 1, 'a': 1})
''' ๅŒฟๅๅ‡ฝๆ•ฐ ๅฝ“ๆˆ‘ไปฌๅœจไผ ๅ…ฅๅ‡ฝๆ•ฐๆ—ถ๏ผŒๆœ‰ไบ›ๆ—ถๅ€™๏ผŒไธ้œ€่ฆๆ˜พๅผๅœฐๅฎšไน‰ๅ‡ฝๆ•ฐ๏ผŒ็›ดๆŽฅไผ ๅ…ฅๅŒฟๅๅ‡ฝๆ•ฐๆ›ดๆ–นไพฟใ€‚ ๅœจPythonไธญ๏ผŒๅฏนๅŒฟๅๅ‡ฝๆ•ฐๆไพ›ไบ†ๆœ‰้™ๆ”ฏๆŒใ€‚่ฟ˜ๆ˜ฏไปฅmap()ๅ‡ฝๆ•ฐไธบไพ‹๏ผŒ่ฎก็ฎ—f(x)=x2ๆ—ถ๏ผŒ้™คไบ†ๅฎšไน‰ไธ€ไธชf(x)็š„ๅ‡ฝๆ•ฐๅค–๏ผŒ่ฟ˜ๅฏไปฅ็›ดๆŽฅไผ ๅ…ฅๅŒฟๅๅ‡ฝๆ•ฐ๏ผš ''' l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print(l) # [1, 4, 9, 16, 25, 36, 49, 64, 81] ''' ้€š่ฟ‡ๅฏนๆฏ”ๅฏไปฅ็œ‹ๅ‡บ๏ผŒๅŒฟๅๅ‡ฝๆ•ฐlambda x: x * xๅฎž้™…ไธŠๅฐฑๆ˜ฏ def f(x): return x * x ''' ''' ๅ…ณ้”ฎๅญ—lambda่กจ็คบๅŒฟๅๅ‡ฝๆ•ฐ๏ผŒๅ†’ๅทๅ‰้ข็š„x่กจ็คบๅ‡ฝๆ•ฐๅ‚ๆ•ฐใ€‚ ๅŒฟๅๅ‡ฝๆ•ฐๆœ‰ไธช้™ๅˆถ๏ผŒๅฐฑๆ˜ฏๅช่ƒฝๆœ‰ไธ€ไธช่กจ่พพๅผ๏ผŒไธ็”จๅ†™return๏ผŒ่ฟ”ๅ›žๅ€ผๅฐฑๆ˜ฏ่ฏฅ่กจ่พพๅผ็š„็ป“ๆžœใ€‚ ็”จๅŒฟๅๅ‡ฝๆ•ฐๆœ‰ไธชๅฅฝๅค„๏ผŒๅ› ไธบๅ‡ฝๆ•ฐๆฒกๆœ‰ๅๅญ—๏ผŒไธๅฟ…ๆ‹…ๅฟƒๅ‡ฝๆ•ฐๅๅ†ฒ็ชใ€‚ๆญคๅค–๏ผŒๅŒฟๅๅ‡ฝๆ•ฐไนŸๆ˜ฏไธ€ไธชๅ‡ฝๆ•ฐๅฏน่ฑก๏ผŒไนŸๅฏไปฅๆŠŠๅŒฟๅๅ‡ฝๆ•ฐ่ต‹ๅ€ผ็ป™ไธ€ไธชๅ˜้‡๏ผŒๅ†ๅˆฉ็”จๅ˜้‡ๆฅ่ฐƒ็”จ่ฏฅๅ‡ฝๆ•ฐ๏ผš ''' f = lambda x: x * x print(f) # <function <lambda> at 0x032441E0> print(f(5)) # 25
''' ่ฐƒ็”จๅ‡ฝๆ•ฐ Pythonๅ†…็ฝฎไบ†ๅพˆๅคšๆœ‰็”จ็š„ๅ‡ฝๆ•ฐ๏ผŒๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅ่ฐƒ็”จใ€‚ ่ฆ่ฐƒ็”จไธ€ไธชๅ‡ฝๆ•ฐ๏ผŒ้œ€่ฆ็Ÿฅ้“ๅ‡ฝๆ•ฐ็š„ๅ็งฐๅ’Œๅ‚ๆ•ฐ๏ผŒๆฏ”ๅฆ‚ๆฑ‚็ปๅฏนๅ€ผ็š„ๅ‡ฝๆ•ฐabs๏ผŒๅชๆœ‰ไธ€ไธชๅ‚ๆ•ฐใ€‚ๅฏไปฅ็›ดๆŽฅไปŽPython็š„ๅฎ˜ๆ–น็ฝ‘็ซ™ๆŸฅ็œ‹ๆ–‡ๆกฃ๏ผš ๅ‡ฝๆ•ฐๅคงๅ…จ๏ผšhttp://docs.python.org/3/library/functions.html ๅŸบ็ก€ๅ‡ฝๆ•ฐ๏ผšabs max ๆ•ฐๆฎ็ฑปๅž‹่ฝฌๆข๏ผšint('str') float('str') str(number) bool(1) bool('') ''' # tips:ไนŸๅฏไปฅๅœจไบคไบ’ๅผๅ‘ฝไปค่กŒ้€š่ฟ‡help(abs)ๆŸฅ็œ‹absๅ‡ฝๆ•ฐ็š„ๅธฎๅŠฉไฟกๆฏใ€‚ help(abs) # abs(...) # abs(number) -> number # Return the absolute value of the argument. print(abs(100), abs(-20), abs(12.34)) # 100 20 12.34 print(max(1, 2, -3)) # 2 print(int('123')) # 123 print(int(12.34)) # 12 print(float('12.34')) # 12.34 print(str(100)) # 100 print(bool(1), bool('')) # True False # tips:ๅ‡ฝๆ•ฐๅๅ…ถๅฎžๅฐฑๆ˜ฏๆŒ‡ๅ‘ไธ€ไธชๅ‡ฝๆ•ฐๅฏน่ฑก็š„ๅผ•็”จ๏ผŒๅฎŒๅ…จๅฏไปฅๆŠŠๅ‡ฝๆ•ฐๅ่ต‹็ป™ไธ€ไธชๅ˜้‡๏ผŒ็›ธๅฝ“ไบŽ็ป™่ฟ™ไธชๅ‡ฝๆ•ฐ่ตทไบ†ไธ€ไธชโ€œๅˆซๅโ€๏ผš a = abs print(a(-1)) # 1
''' ๆŽ’ๅบ็ฎ—ๆณ• ๆŽ’ๅบไนŸๆ˜ฏๅœจ็จ‹ๅบไธญ็ปๅธธ็”จๅˆฐ็š„็ฎ—ๆณ•ใ€‚ๆ— ่ฎบไฝฟ็”จๅ†’ๆณกๆŽ’ๅบ่ฟ˜ๆ˜ฏๅฟซ้€ŸๆŽ’ๅบ๏ผŒๆŽ’ๅบ็š„ๆ ธๅฟƒๆ˜ฏๆฏ”่พƒไธคไธชๅ…ƒ็ด ็š„ๅคงๅฐใ€‚ ๅฆ‚ๆžœๆ˜ฏๆ•ฐๅญ—๏ผŒๆˆ‘ไปฌๅฏไปฅ็›ดๆŽฅๆฏ”่พƒ๏ผŒไฝ†ๅฆ‚ๆžœๆ˜ฏๅญ—็ฌฆไธฒๆˆ–่€…ไธคไธชdictๅ‘ข๏ผŸ็›ดๆŽฅๆฏ”่พƒๆ•ฐๅญฆไธŠ็š„ๅคงๅฐๆ˜ฏๆฒกๆœ‰ๆ„ไน‰็š„๏ผŒๅ› ๆญค๏ผŒๆฏ”่พƒ็š„่ฟ‡็จ‹ๅฟ…้กป้€š่ฟ‡ๅ‡ฝๆ•ฐๆŠฝ่ฑกๅ‡บๆฅใ€‚ ''' print(sorted([36, -5, 1, 22])) # [-5, 1, 22, 36] ''' ๆญคๅค–๏ผŒsorted()ๅ‡ฝๆ•ฐไนŸๆ˜ฏไธ€ไธช้ซ˜้˜ถๅ‡ฝๆ•ฐ๏ผŒๅฎƒ่ฟ˜ๅฏไปฅๆŽฅๆ”ถไธ€ไธชkeyๅ‡ฝๆ•ฐๆฅๅฎž็Žฐ่‡ชๅฎšไน‰็š„ๆŽ’ๅบ๏ผŒไพ‹ๅฆ‚ๆŒ‰็ปๅฏนๅ€ผๅคงๅฐๆŽ’ๅบ๏ผš ''' print(sorted([36, -5, 1, 22], key=abs)) # [1, -5, 22, 36] ''' ้ป˜่ฎคๆƒ…ๅ†ตไธ‹๏ผŒๅฏนๅญ—็ฌฆไธฒๆŽ’ๅบ๏ผŒๆ˜ฏๆŒ‰็…งASCII็š„ๅคงๅฐๆฏ”่พƒ็š„๏ผŒ็”ฑไบŽ'Z' < 'a'๏ผŒ็ป“ๆžœ๏ผŒๅคงๅ†™ๅญ—ๆฏZไผšๆŽ’ๅœจๅฐๅ†™ๅญ—ๆฏa็š„ๅ‰้ขใ€‚ ''' print(sorted(['bob', 'about', 'Zoo', 'Credit'])) # ['Credit', 'Zoo', 'about', 'bob'] ''' ็Žฐๅœจ๏ผŒๆˆ‘ไปฌๆๅ‡บๆŽ’ๅบๅบ”่ฏฅๅฟฝ็•ฅๅคงๅฐๅ†™๏ผŒๆŒ‰็…งๅญ—ๆฏๅบๆŽ’ๅบใ€‚่ฆๅฎž็Žฐ่ฟ™ไธช็ฎ—ๆณ•๏ผŒไธๅฟ…ๅฏน็Žฐๆœ‰ไปฃ็ ๅคงๅŠ ๆ”นๅŠจ๏ผŒๅช่ฆๆˆ‘ไปฌ่ƒฝ็”จไธ€ไธชkeyๅ‡ฝๆ•ฐๆŠŠๅญ—็ฌฆไธฒๆ˜ ๅฐ„ไธบๅฟฝ็•ฅๅคงๅฐๅ†™ๆŽ’ๅบๅณๅฏใ€‚ ๅฟฝ็•ฅๅคงๅฐๅ†™ๆฅๆฏ”่พƒไธคไธชๅญ—็ฌฆไธฒ๏ผŒๅฎž้™…ไธŠๅฐฑๆ˜ฏๅ…ˆๆŠŠๅญ—็ฌฆไธฒ้ƒฝๅ˜ๆˆๅคงๅ†™๏ผˆๆˆ–่€…้ƒฝๅ˜ๆˆๅฐๅ†™๏ผ‰๏ผŒๅ†ๆฏ”่พƒใ€‚ ''' print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # ['about', 'bob', 'Credit', 'Zoo'] ''' ่ฆ่ฟ›่กŒๅๅ‘ๆŽ’ๅบ๏ผŒไธๅฟ…ๆ”นๅŠจkeyๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅไผ ๅ…ฅ็ฌฌไธ‰ไธชๅ‚ๆ•ฐreverse=True๏ผš ''' print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) # ['Zoo', 'Credit', 'bob', 'about']
N, M = map(int, input().split()) chess = [] for i in range(N): chess.append([]) for j in range(M): chess[i].append(0) for i in range(N): a = input() for j in range(M): chess[i][j] = a[j] for i in range(N): for j in range(M): print(chess[i][j], end = " ") print()
from enum import Enum class Shipper(Enum): #For python 3.4 and up, class Enum can be used fedex = 1 ups = 2 postal = 3
change = eval(input("Enter the change")) print("quarters :", change//.25) change-=(change//.25)*.25 print("dimes :", change//.10) change-=(change//.10)*.10 print("nickels :",change//.05) change-=(change//.05)*.05 print("pennies :",1+(change//.01)) change-=(change//.01)*.01
# hey dany. i hope this helps #^^^ also you can use this as the string it asks you for # or this one : # 1234567890 # so you can understand what happens to the order much better #strings string = input("Enter your string has to contain a so it doesnt give error: ") print(string.capitalize()) print("") print(string.upper()) print("") print(string.lower()) if string.isdigit(): print("the string is comprised of digits only with no symbol nor alpha") elif string.isalpha(): print("the string may contain only alphabetic letter with no numbers nor symbol") elif string.isalnum(): print("the string may contain both alphabetic letter and numbers") else: print("the string contains symbol too!") print("") #first element only print(string[0]) print("") #between the first and 5 element print(string[:5]) print("") #if you want to skip elements put the step after the 2 colon #also you can leave the first and second colon with nothing print(string[::2]) print("") #revrse the string #notice how the step is -1 which basically means it starts going down rather than up print(string[::-1]) print("") #you can find the index of a certin charecter in a string by : print("first occurance of \"a\" happens at", string.index("a")) # if there is no "a" inside the string then python will show an error print("") # if no a is there the function wont remove anything print(string.replace("a", "b")) print("") #also you see the length of most variable whether they are strings lists or anything: print(len(string)) print("") #also looping over the string for i in range(len(string)): print(string[i]) #there are way more function related to strings but we didnt take them #if you want to learn on your own you can go to this site for more answers #https://www.w3schools.com/python/python_strings.asp #lists # ["abdalrhman", "dany", "ahmed", "laith", "mohammad", "saif"] #^^^ also you can use this as the string it asks you for # or this one : # ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] # so you can understand what happens to the order much better #we put eval so that python treats this as a list rather than a string listofstudents = eval(input("enter your list in this format\n[\"first element\", \"second...\"]\n")) print("") #this turns the list into a string where inbetween the different elements it will have whatever is inside the string print("***".join(listofstudents)) print("") #you can also create a list from a string by spliting it everytime it finds a charecter that you give print("Dany Fawaz".split(" ")) # in this example the result will be ["Dany", "Fawaz"] print("") #indexing works the same as strings #first element only print(listofstudents[0]) print("") #between the first and 3 element print(listofstudents[:3]) print("") #if you want to skip elements put the step after the 2 colon #also you can leave the first and second colon with nothing print(listofstudents[::2]) print("") #revrse the list #notice how the step is -1 which basically means it starts going down rather than up print(listofstudents[::-1]) print("") #ofc you can access the list at any index and change it listofstudents[1] = "changed!!" print(listofstudents) print("") #inserts index value # โ†“ โ†“ listofstudents.insert(2, "i am inserted at two") print(listofstudents) print("") #append listofstudents.append("iam added to the end") print(listofstudents) print("") #removing the last element listofstudents.pop() print(listofstudents) print("") # and the 4 element listofstudents.pop(3) print(listofstudents) print("") #removing the element we added with insert listofstudents.remove("i am inserted at two") print(listofstudents) print("") #ofc as before we can use del #del listsofstudents[5] # looping over the list for i in range(len(listofstudents)): print(listofstudents[i], end=" ") print("\n") # if we want to print the list many times we can do so like this print(listofstudents*2) print("") # sorting a list listofnums = [1, 3, 6, 2, 4, 1, 2 ,4] print(listofnums) listofnums.sort() print("") print(listofnums) print("") print("") # reverse sorting a list listofnums = [1, 3, 6, 2, 4, 1, 2 ,4] print(listofnums) listofnums.sort() listofnums.reverse() print("") print(listofnums) #there are way more function related to lists but we didnt take them #if you want to learn on your own you can go to this site for more answers # https://www.w3schools.com/python/python_lists_methods.asp
import random x= input("give me a number") y = random.randint(1, 10) print(x//y, x%y)
x = int(input("Enter the meal price in AED: ")) y = int(input("Enter the tip you want to leave : ")) print("Total (tip unincluded) : " + str(x) + "\nTip : " + str(y) + "%" + "\nTotal (tip included) : " + str(x+x*(y/100)) + "AED")
from random import randrange from random import random import time import threading print(" ") print(" ") #rounding for 2 decimal points# def myMethod(n): return int(n * 100) / 100 #*****************************# #Making the two Arrays that will hold our values# #MOVES will hold our possible scramble Moves# Moves = [] #Our 6 total moves# #M is not included because its useless# Moves.append("R") Moves.append("U") Moves.append("D") Moves.append("F") Moves.append("L") Moves.append("B") #*************************************# #calling the self-calling function# def scrambling_Method(): #FINAL will hold our result of our algorithem # Final = [] #creating the random moves that will be simplified or improved# for x in range(randrange(20, 30)): y = randrange(6) Final.append(Moves[y]) c = len(Final) a = -c #*************************************************************# #improvind the scramble# for z in range(c): if z != c+1: if c -z > 2: if Final[z] == Final[z + 1] and Final[z + 1] == Final[z + 2]: Final[z] = Final[z] + "'" Final.pop(z + 1) Final.pop(z + 1) a += 1 c -= 2 elif random() < .5: Final[z] = Final[z] + "'" elif random() < .3: Final[z] = Final[z] + "2" if c - z > 1: if Final[z] == Final[z + 1]: Final[z] = Final[z] + "2" Final.pop(z + 1) c -= 1 elif Final[z+1] in Final[z]: Final.pop(z+1) Final.pop(z) a += 1 c -= 2 elif Final[z] in Final[z+1]: Final.pop(z+1) Final.pop(z) a += 1 c -= 2 a += 1 print(Final) #**********************# #Waiting for the user to finish the scramble# print("press when finished the scramble") input() #This is for inspection time# for b in range(15): print("{0} until inspection finishes".format(15 -b)) time.sleep(1) #***************************# #THE FULL TIMER# #Taking the starting time# start_time = time.time() #Taking the ending time# input("Press Enter to stop") end_time = time.time() #Calculating the min and sec from time passed# time_lapsed = end_time - start_time s = myMethod((time_lapsed) % 60) m = int((time_lapsed / 60)) print(str(m) + " Mins " + str(s) + " Sec ") p = input("Do you want to play again y/n \n") if p in "y Y": scrambling_Method() scrambling_Method()
import random wins = 0 draws = 0 choices = ["rock", "Paper", "Siscors"] for i in range(5): player_choice = input("r/p/s") if player_choice == "r": player = 1 elif player_choice == "p": player = 2 elif player_choice == "s": player = 3 computer = random.randint(1, 3) if player - computer == 0: print("draw the opponent chose :", choices[computer - 1]) draws+=1 elif player - computer == -1: print("loss the opponent chose :", choices[computer - 1]) elif player - computer == 2: print("loss the opponent chose :", choices[computer - 1]) elif player - computer == 1: print("win the opponent chose :", choices[computer - 1]) wins+=1 elif player - computer == -2: print("win the opponent chose :", choices[computer - 1]) wins+=1 print("you won :", wins, "wins out of 5") print("you tied :", draws)
while True: print("F(x) = a(x - h)^2 + k") try: a = float(input("input a : \n")) h = float(input("input h : \n")) k = float(input("input k : \n")) print("vertex is : (" + str(h) + ", " + str(k) + ")") print("line of symetry : x = " + str(h)) sum = "" if 0<abs(a)<1: sum+="the parabula is wider than parent function" elif a == 0: sum+="the line is straight" elif a == 1: sum+="the parabula is normal" else: sum+="the parabula is narrower than parent function" if 0<a: sum+=" and facing up" elif 0 > a: sum+=" and facing down" else: sum +=", " if h<0: sum += " shifted left by " + str(abs(h)) + " units" elif h>0: sum += " shifted right by " + str(abs(h)) + " units" else: sum += " not shifted horizontaly" if k<0: sum += " shifted down by " + str(abs(k)) + " units" elif k>0: sum += " shifted up by " + str(abs(k)) + " units" else: sum += " not shifted vertacly" print(sum) print("F(x) = ("+str(a)+")(x - ("+str(h)+"))^2 + ("+str(k)+")") except: print("write something useful")
import random x= int(input("give me a number")) y = random.randint(1, 10) print(abs(x-y)/x-y)
temp = eval(input("the temeprture in C")) print("the temperture in F", 9/5*temp+32)
s = input("input a decimal number") if "." in s: print(s[s.index(".")+1:]) else: print("that doesnt have a decimal point")
# -*- coding: utf-8 -*- import os import csv # Initializing variables total_votes_cast = 0 TRUE = 1 # Setting path to election_data.csv election_data_csv_path = os.path.join("..", "Resources", "election_data.csv") # Opening election_data.csv # with open(udemy_csv, newline="", encoding='utf-8') as csvfile: with open(election_data_csv_path, newline="", encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") # Read the header row first (skip this part if there is no header) csv_header = next(csv_reader) # print(f"Header: {csv_header}") # Declaring lists all_row_values = [] sorted_all_row_values = [] voter_ids = [] counties = [] candidates = [] # Counting the total number of votes for row in csv_reader: # Counting total votes cast total_votes_cast = total_votes_cast + 1 voter_id = row[0] county = row[1] candidate = row[2] row_values = [voter_id, county, candidate] all_row_values.append(row_values) # sorted_all_row_values = all_row_values # The following code creates lists for each column item candidates.append(candidate) counties.append(county) voter_ids.append(voter_id) # the function set() finds unique values in a list c_name = [] c_percent = [] c_votes = [] c_results = [] candidate_list = set(candidates) for x_candidate in candidate_list: candidate_percent = round((((candidates.count(x_candidate))/total_votes_cast)*100),3) candidate_votes = candidates.count(x_candidate) # print((x_candidate) + " " + str("%.3f" % candidate_percent) + " " + str(candidates.count(x_candidate))) c_name = x_candidate c_percent = float(candidate_percent) c_votes = int(candidate_votes) c_values = [c_name, c_percent, c_votes] c_results.append(c_values) # print(c_name) # print(str(c_percent)) # print(str(c_votes)) # print(x_candidate) # print(candidates.count(x_candidate)) #print(c_results[0][0]) #print(str(total_votes_cast)) def sortSecond(val): return val[1] c_results.sort(key = sortSecond, reverse = True) #print(c_results) # can access multidimensional list using # square brackets print(f" ") print(f"Election Results") print(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print(f" ") print("Total Votes: " + str(total_votes_cast)) print(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print(f" ") for i in range(len(c_results)) : # for j in range(len(c_results[i])) : # print(c_results[i][j], end=" ") print(c_results[i][0] + ": " + str("%.3f" % c_results[i][1]) + "% (" + str(c_results[i][2]) + ")") print(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print(f" ") # Creating and opening a txt file named Analysis_Results.txt file2 = open("Election_Results.txt","w") # Write analysis output to file # \n is placed to indicate EOL (End of Line) file2.write(f"Election Results \n") file2.write(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n \n") file2.write("Total Votes: " + str(total_votes_cast) + "\n") file2.write(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n \n") for i in range(len(c_results)) : # for j in range(len(c_results[i])) : # print(c_results[i][j], end=" ") file2.write(c_results[i][0] + ": " + str("%.3f" % c_results[i][1]) + "% (" + str(c_results[i][2]) + ")" + "\n") file2.write(f"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n \n") file2.write(f" ") # Closing Analysis_Results.txt file2.close() #to change file access modes #for i in range(len(c_results)) : # for j in range(len(c_results[i])) : # print(c_results[i][j], end=" ") # print()
total_50 = 10 total_20 = 20 total_10 = 100 total_5 = 100 total_money = { '50':10, '20':20, '10':100, '5':100 } total_cash = sum(int(k) * v for k, v in total_money.items()) print("Total Amount: ", total_cash) provived_cash = {'50': 0, '20': 0, '10': 0, '5': 0} while total_cash >= 0: amount_to_withdraw = int(input("Amount: ")) if amount_to_withdraw % 5 != 0: print("enter amount divisible by 5") break if total_cash > amount_to_withdraw: collected_cash = 0 while collected_cash != amount_to_withdraw: # difference = amount_to_withdraw - collected_cash # add 50 # possible_50 = int(difference / 50) # possible_20 = int(difference / 20) # possible_10 = int(difference / 10) # possible_5 = int(difference / 5) # if total_50 < possible_50: # total_50 -= possible_50 if (collected_cash + 50) <= amount_to_withdraw and total_50 != 0: provived_cash['50'] += 1 total_50 -= 1 collected_cash += 50 if (collected_cash + 20)<= amount_to_withdraw and total_20 != 0: provived_cash['20'] += 1 total_20 -= 1 collected_cash += 20 if (collected_cash + 10)<= amount_to_withdraw and total_10 != 0: provived_cash['10'] += 1 total_10 -= 1 collected_cash += 10 if (collected_cash +5)<= amount_to_withdraw and total_5 != 0: provived_cash['5'] += 1 total_5 -= 1 collected_cash += 5 print("Collected Cash : ", collected_cash) print("Provided Cash : ", provived_cash) print("Provided Sum: ", sum(int(k) * v for k, v in provived_cash.items())) else: print("not enough money...") print("Finshed") def add_cash(collected_cash, total_amount, total_no_cash): if (collected_cash +5)<= total_amount and total_no_cash != 0: provived_cash['5'] += 1 total_no_cash -= 1 collected_cash += 5
# URL: https://www.hackerrank.com/challenges/arrays-ds/problem def reverseArray(a): arr = [] for i in range(len(a)-1,-1,-1): arr.append(a[i]) return arr
print("What integer would you like to square?") base = int(raw_input()) print(base ** 2)
# number 2 # Will say this statement when you run it print("Welcome to the convenience store!") # Ask us for our age print("Enter your age:") # We have to enter our age and age is the variable and an int age = input() age = int(age) if age >= 18: # If our age is greater than 18 then it will ask us do we want to buy a lottery ticket print("Would you like to buy a lottery ticket?") if age < 6: # If our age is less than 6 then it will ask us do we want to buy a lollipop print("Would you like to buy a lollipop?")
#!/usr/bin/python # # Simple XML parser for JokesXML # Jesus M. Gonzalez-Barahona # jgb @ gsyc.es # TSAI and SAT subjects (Universidad Rey Juan Carlos) # September 2009 # # Just prints the jokes in a JokesXML file from xml.sax.handler import ContentHandler from xml.sax import make_parser import sys import string def normalize_whitespace(text): "Remove redundant whitespace from a string" return string.join(string.split(text), ' ') class CounterHandler(ContentHandler): def __init__ (self): self.inContent = 0 self.theContent = "" def startElement (self, name, attrs): if name == 'joke': self.title = normalize_whitespace(attrs.get('title')) print " title: " + self.title + "." elif name == 'start': self.inContent = 1 elif name == 'end': self.inContent = 1 def endElement (self, name): if self.inContent: self.theContent = normalize_whitespace(self.theContent) if name == 'joke': print "" elif name == 'start': print " start: " + self.theContent + "." elif name == 'end': print " end: " + self.theContent + "." if self.inContent: self.inContent = 0 self.theContent = "" def characters (self, chars): if self.inContent: self.theContent = self.theContent + chars # --- Main prog if len(sys.argv)<2: print "Usage: python xml-parser-jokes.py <document>" print print " <document>: file name of the document to parse" sys.exit(1) # Load parser and driver JokeParser = make_parser() JokeHandler = CounterHandler() JokeParser.setContentHandler(JokeHandler) # Ready, set, go! xmlFile = open(sys.argv[1],"r") JokeParser.parse(xmlFile) print "Parse complete"
''' Day 1 _list = [] for i in range(2000, 3201): if i % 7 === 0 and i % 5 != 0: _list.append(str(i)) print(','.join(_list)) Day 2 def factorial(num): if num < 0: return "Must be greater than 0" if num == 0: return 1 return num * factorial(num-1) Day 3 print("Enter a number: ") n = int(input()) d = dict() for i in range(1, n+1): d[i] = i *i print(d) Day 4 values = input("Enter comma seperated values: ") list = values.split(',') tuple = tuple(list) print(list, tuple) Day 5 Class Mom(object): def __init__(self): self.n = '' def getName(self): self.n = str(input("Enter name for Mom: ")) def printMomsName(self): print(self.n.upper()) Day 6 import math c = 50 h = 30 x = [] y = [i for input("Enter a number or numbers: ").split(',')] for d in y: x.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print(','.join(x)) Day 7 input_for_system = input("Enter input: ") dimension = [int(x) for x in input_for_system.split(',')] rowin = dimension[0] colin = dimension[1] list = [[0 for column in range(colin)] for rows in range(rowin)] for row in range(rowin): for col in range(colin): list[row][col] = row*col print(list) ''' #Day 8 # to get each item in list printed I could... pets = ['dog', 'cat', 'bird', 'rabbit', 'fish', 'neighbor'] print(pets[0]) print(pets[1]) print(pets[2]) print(pets[3]) print(pets[4]) print(pets[5], '/n') #or use a for loop to print everything in pets for doodeledy in pets: print(doodeledy) #rock out a conditional statement with a while loop i_got_20_bucks = 20 while i_got_20_bucks < 35: print(i_got_20_bucks) i_got_20_bucks += 1 print("I need more money") # for all numbers between 1500 and 2700, which are divisible by 7 and a multiple of 5 for i in range(1500, 2701): if i % 7 == 0 and i % 5 == 0: print(i) #write a program that will guess a number between 1 and 10 import random target_num, guess_num = random.randint(1,10), 0 while target_num != guess_num: guess_num = int(input('Guess a number between 1 and 10, and keep guessing till correct')) print('game over') #create a cool printed pattern that looks like a sideways triangle count = 0 for num in range(7): count += 1 print('*' * count) for num in range(6): count -= 1 print('*' * count)
''' print("day 1") _list = [] for i in range(2000, 3201): if i % 7 == 0 and i % 5 != 0: _list.append(str(i)) print(",".join(_list)) print("Day 2") def factorial(num): if num = 0: return 1 return num *(factorial(num -1)) print(factorial(5)) Print("Day 3") print("Enter a number: ") n = int(input()) d = dict() for i in range(1, n+1): d[i] = i*i print("d: :, d) print("Day 4") values = input("Enter comma seperated values: ") list = values.split(',') tuple = tuple(list) print(list, tuple) pirnt("Day 5") class Mama(object): def __init__(self): self.s = '' def getString(self): self.s = input() def printGetString(self): print(self.s) m = Mama() m.getString() m.printGetString() print("Day 6") import math c = 50 h = 30 x = [] y = [i for i in input("Enter a number or set of numbers: ").split(',')] for d in y: x.append(str(int(round(math.sqrt(2*c*float(d)/h)))) print(','.join(x)) print("Day 7") input_system = input("Enter input for x and y") dimension = [int(x) for x in input_system.split(',')] rowin = dimension[0] colin = dimension[1] list = [[0 for column in range(colin)]for rows in range(rowin)] for rows in range(rowin): for col in range(colin): list[row][col] = row*col print(list) Print("Day 8") pets = ['dog', 'cat', 'bird', 'rabbit', 'fish', 'neighbor'] for i in pets: print(i) got20 = 20 while got20 < 35: print(got20) got20 += 1 print("Need some mo") print("Day 9") from array import * array_num = array('i', [1,3,5,7,9]) for i in array_num: print(i) array_num.append(11) print(array_num[::-1]) print(array_num.insert(1,4)) array_num.pop(3) array_num.remove(5) print("Day 10") x = input("Type a word: ") b = ''.join(reversed(x)) print(b) print("or") print(x[::-1]) def oddEvenCount(x): odd_count = 0 even_count = 0 for i in x: if i % 2 == 0: even_count +=1 else: odd_count +=1 return" Odd count: " + str(odd_count) + " Even count: " + str(even_count) x = range(1,12) print(oddEVenCount(x)) data = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {'class':'V', 'Section':'A'}] for index in data: print("Type of ", index, "is ", type(index)) for i in range(1,8): if i != 3 and i != 6: print(i) #fibonacci def fibonacci(num): x,y = 0,1 while y < num: x,y = y, x+y print("\n") for ice in range(1, 50): if ice % 3 == 0: print('SUPAA') elif ice % 5 == 0: print('BADASS') elif ice % 3 == 0 and ice % 5 == 0: print('super badass') else: print(str(ice) + " is not") print("Day 11") row_num = int(input("How many rows: ")) col_num = int(input("How many columns: ")) list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): list[row][col] = row*col print(list, '\n') lines = [] while True: l = input("Enter a phrase: ") if l: lines.append(l.upper()) else: break for l in lines: print(l) def dividableBinary(): seq = input("Enter a sequence of c.s 4 didgit binary nums") seq = seq.split(',) for s in seq: if int(str(s),2) % 5 == 0: print("Output: ", s) dividableBinary() print("Day 12") #Accept a string and calculate number of letters and digits sen = input("Enter a sentance: ") num, lett = 0, 0 for s in sen: if s.isalpha(): lett += 1 elif s.isdigit(): num +=1 else: pass print("Letters: ", lett) print("Numbers: ", num) #Check the validity of a password import re # used for matching passw = input("Enter password: ") x = True while x: if(len(passw) < 6 or len(passw) > 16): break elif not re.search('[a-z]', passw): break elif not re.search('[0-9]', passw): break elif not re.search('[A-Z]', passw): break elif not re.search('[$@$_]', passw): break elif re.search('\s', passw): # '\s' matches the whitespaces break else: print("Password check complete. Your password was accepted!") x = False break if x: print("That is a BS password - you are banned for life") #Find numbers between 100 and 400 both included, where each digit is even # print in csv sequence even_digits = [] for i in range(100, 401): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0): even_digits.append(s) print(",".join(even_digits)) #Create a program that will print out a pattern of an 'A' letter_A = '' for row in range(8): for column in range(8): if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5))): letter_A = letter_A + '*' else: letter_A = letter_A + ' ' letter_A = letter_A + '\n' print(letter_A) ''' print("Day 13") #Make a grid and find out how to move the dots to the right to make it on s #lets do the smae for "s" letter_s = '' for row in range(7): for col in range(7): if ((row == 0 or row == 3 or row == 6) and col>0 and col <7): letter_s += '*' elif ((row == 1 or row == 2) and col ==1): letter_s += '*' elif ((row == 4 or row == 5) and col == 6): letter_s += '*' else: letter_s += ' ' letter_s += '\n' print(letter_s) x = '' for row in range(7): for col in range(7): if (((col == 1 or col == 5) and (row > 4 or row < 2)) or row == col and col > 0 and col < 6 or (col -- 2 and row == 4) or (col == 4 and row == 2)): x += '*' else: x += ' ' x += '\n' print(x) # find the error #python program which calculates age in dog years # dog year 0-2 = 10.5 human years each year # after that each dog year = 4 human years human = int(input("How many human years has the dog been alive? ")) if human < 0: print("Age must be a positive number") exit() elif human <= 2: dog_age = human * 10.5 else: dog_age = (human - 2) * 4 + 21 print("The dog's age in dog years is: ", dog_age) # python program to check if letter is a vowel or a consonant x = input("Chose any letter from the alphabet: ") if x in ('a','e','i','o','u'): print('{} is a vowel'.format(x)) elif x == 'y': print("A, E, I, O, U and sometimes Y") else: print(f'{x} is a constonant') # give me a month and i'll share the number of days abr_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'] print(f'List of months: {abr_months}') month = input('Enter an abreviated month: ') if month not in abr_months: month = input("Try entering the month again: ") elif month == 'Feb': print('Number of days: 28/29 days') elif month in ('Apr', 'Jun', 'Sept', 'Nov'): print("Number of days: 30 days") elif month in ('Jan', 'Mar', 'May', 'July', 'Aug', 'Oct', 'Dec'): print("Number of days: 31 days") else: print(f'What did you just type in {month}')
#! python 2 ''' Weather.py - Launches a weather website in the browser depending upon user choice. ''' import webbrowser,sys,os while True: place = raw_input('>>> Enter Place : ') address = 'https://www.google.co.in/?gws_rd=ssl#q=weather+in+'+place print ' 1.) Google Weather' print ' 2.) Exit' choice = input('>>> Enter your Chice : ') if choice == 2: sys.exit() print webbrowser.open(address) os.system('cls')
''' ๋ฌธ์ œ ์„ค๋ช… ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๋ฆฌ์ŠคํŠธ x ์˜ ์ฒซ ์›์†Œ์™€ ๋งˆ์ง€๋ง‰ ์›์†Œ์˜ ํ•ฉ์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜ solution() ์„ ์™„์„ฑํ•˜์„ธ์š”. ''' x = [1, 4, 5, 7] def solution(x): answer = x[0] + x[-1] return answer print(solution(x))
#Project Euler Problem 16 #Power Digit Sum #What is the sum of the digits of 2^1000 #function to sum the digits of the number when we get it def digitSum(n): theSum = 0 for d in n: theSum += int(d) return theSum #program main testNum = 2**1000 num = str(testNum) print(digitSum(num))
fibonacci = [1, 2] sum = fibonacci[1] for i in range(10000): new = fibonacci[i] + fibonacci[i+1] if new > 4000000: break if new % 2 == 0: sum = sum + new fibonacci.append(new) print(sum) print(fibonacci)
def factorial(a): if a == 1: return 1 else: return a * factorial(a-1) checksum = 0 sm = str(factorial(100)) for c in sm: checksum += int(c) print(checksum)
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2ร—12 15 = 7 + 2ร—22 21 = 3 + 2ร—32 25 = 7 + 2ร—32 27 = 19 + 2ร—22 33 = 31 + 2ร—12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ def make_primes(upper_bound): """ returns a list of primes up to the upper bound """ primes = [2] non_primes = [] for i in range(3, upper_bound, 2): for j in range(2, int(i**0.5) + 1): if i % j == 0: non_primes.append(i) break else: primes.append(i) return primes, non_primes def make_2_squares (upper_bound): """ returns a list of double squares up to the upper bound """ squares = [] for i in range(1, upper_bound): total = 2 * i**2 squares.append(total) return squares primes, non_primes = make_primes(10000) # print(non_primes) squares = make_2_squares(50) # print(squares) for i in non_primes: results = True for j in range(min(i, len(primes))): for k in range(len(squares)): if primes[j] + squares[k] == i: results = False break if results == True: print(i) break
""" The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? """ # First create a list of all 4-digit primes # Make combinations of 3 primes being permutations of each other # Check if their difference is the same def make_4_digit_primes(): """ Function that returns a list of all 4 digit primes """ primes = [] for i in range(1001, 10000, 2): for j in range (3, int(i**0.5) + 1): if i % j == 0: break else: primes.append(i) return primes def cluster_permutations(primes): """ cluster all primes in lists of its permutations """ permutations = {} for element in primes: element = str(element) element_list = [element[0], element[1], element[2], element[3]] element_list.sort() element_list = str(element_list) # print(element_list) if element_list not in permutations: permutations[element_list] = [element] else: permutations[element_list].append(element) return permutations def find_solution (permutations): for key, value in permutations.items(): if len(value) >= 3: # print(len(value), value, sep = '\t') for i in range(len(value)): first = value[i] for j in range(len(value)): second = value[j] temp = int(value[j]) - int(value[i]) temp_2 = temp + int(value[j]) # print(temp) if str(temp_2) in value and temp != 0: print(value[i] + value[j] + str(temp_2)) test = make_4_digit_primes() # print(len(test)) permutations = cluster_permutations(test) # print(permutations) find_solution(permutations)
from Deque import Deque class Array_Deque(Deque): def __init__(self): # capacity starts at 1; we will grow on demand. self.__capacity = 1 self.__contents = [None] * self.__capacity self.__front = None #index of the front of the array deque self.__back = None #index of the back of the array deque self.__size = 0 # TODO replace pass with any additional initializations you need. def __str__(self): # TODO replace pass with an implementation that returns a string of # exactly the same format as the __str__ method in the Linked_List_Deque. if self.__size == 0: return ('[ ]') reordered_contents = '[ ' index = self.__front for i in range(self.__size): if index == self.__capacity: #if the index of front reaches the end of the array deque, it wraps around to index 0 index = 0 if i == self.__size - 1: #once the final item in self.__contents has been reached, no more commas are added and an end brace is added to the string reordered_contents = reordered_contents + str(self.__contents[index]) + ' ]' break reordered_contents = reordered_contents + str(self.__contents[index]) + ', ' #adds an item from self.__contents to reordered_contents index+=1 return reordered_contents #reordered contents is the contents of array deque reordered in a string format from front to back def __len__(self): # TODO replace pass with an implementation that returns the number of # items in the deque. This method must run in constant time. return self.__size def __grow(self): # TODO replace pass with an implementation that doubles the capacity # and positions existing items in the deque starting in cell 0 (why is # necessary?) self.__capacity = self.__capacity * 2 new_contents = [None] * self.__capacity index = 0 for i in range(self.__front, self.__front + self.__size): new_contents[index] = self.__contents[i % self.__size] #repositions self.__contents to have the front value be at index 0 in the new contents and back value be at index self.__size - 1 index+=1 self.__contents = new_contents self.__front = 0 self.__back = self.__size - 1 return self.__contents def push_front(self, val): # TODO replace pass with your implementation, growing the array before # pushing if necessary. if self.__size == self.__capacity: self.__grow() if self.__size == 0: self.__front = 0 self.__back = 0 self.__contents[self.__front] = val self.__size += 1 elif self.__front == 0: self.__front = self.__capacity - 1 self.__contents[self.__front] = val self.__size += 1 else: self.__front -= 1 self.__contents[self.__front] = val self.__size += 1 def pop_front(self): # TODO replace pass with your implementation. Do not reduce the capacity. if self.__size == 0: return None temp = self.__contents[self.__front] if self.__size == 1: self.__front = None self.__back = None self.__size = 0 return temp self.__front += 1 self.__size -= 1 if self.__front == self.__capacity: self.__front = 0 return temp def peek_front(self): # TODO replace pass with your implementation. if self.__size == 0: return None return self.__contents[self.__front] def push_back(self, val): # TODO replace pass with your implementation, growing the array before # pushing if necessary. if self.__size == self.__capacity: self.__grow() if self.__size == 0: self.__front = 0 self.__back = 0 self.__contents[self.__front] = val self.__size += 1 else: self.__back += 1 self.__contents[self.__back] = val self.__size += 1 def pop_back(self): # TODO replace pass with your implementation. Do not reduce the capacity. if self.__size == 0: return None temp = self.__contents[self.__back] if self.__size == 1: self.__front = None self.__back = None self.__size = 0 return temp self.__back -= 1 self.__size -= 1 if self.__back < 0: self.__back = self.__capacity return temp def peek_back(self): # TODO replace pass with your implementation. if self.__size == 0: return None return self.__contents[self.__back] # No main section is necessary. Unit tests take its place. #if __name__ == '__main__': #pass
import random ''' I like to play Diablo 3 and I was upset how the random numbers system for augmenting your armor was. It seemed to apply the same stats over and over again. So I made this to try and emulate that system to see for myself how random the numbers actully are. ''' guess= 0 def RNG(number): number = random.randrange(1,100) return number print "Choice of random stats" print "\n" blank_stats = ["Life steal","Life on kill","Arcane Damge", "Stun","Critial Attack Damage", "Attack Speed"] print blank_stats while True: print "\n" user_input = raw_input("Hit enter >> ") print "\n" stats = ["Life steal:+%d" % RNG(guess),"Life on kill:+%d" % RNG(guess),"Arcane Damge:+%d" % RNG(guess), "Stun:+%d" % RNG(guess),"Critial Attack Damage:+%d" % RNG(guess), "Attack Speed:+%d" % RNG(guess)] random.shuffle(stats) choice = random.sample(stats,3) for i in choice: print i
""" File _list_ globbing utility This code is based on glob but varies slightly in that it works on a list of files/paths that is passed rather than a directory/pathname. This is useful for multi-tiered glob rules or applying glob rules to a known set of files. """ # -*- coding: utf-8 -*- import os import re from glob import has_magic __all__ = ["glib", "_iglib"] __author__ = "Grant Hulegaard" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __license__ = "" __maintainer__ = "Grant Hulegaard" __email__ = "grant.hulegaard@nginx.com" # Globals # Match functions (for different match types) def _combined_match(file_pathname, regex): return bool(regex.match(file_pathname)) def _directory_match(file_pathname, regex): # dirname is returned without trailing slash dirname, _ = os.path.split(file_pathname) return bool(regex.match(dirname + '/')) def _filename_match(file_pathname, regex): _, tail = os.path.split(file_pathname) return bool(regex.match(tail)) PATHNAME_MAP = { 'combined': _combined_match, 'directory': _directory_match, 'filename': _filename_match } def glib(file_list, pathname_pattern): """ Return a subset of the file_list passed that contains only files matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' :param file_list: List of string pathnames :param pathname_pattern: String pathname pattern :return: List """ return list(_iglib(file_list, pathname_pattern)) # Helpers def _iglib(file_list, pathname_pattern): """ Return an iterator which yields a subset of the passed file_list matching the pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' :param file_list: List of String pathnames :param pathname_pattern: String pathname pattern :return: Iterator """ try: dirname, tail = os.path.split(pathname_pattern) except: dirname, tail = None, None # Set type based on what info was in pathname pattern pathname_type = None if dirname and tail: pathname_type = 'combined' elif dirname and not tail: pathname_type = 'directory' elif not dirname and tail: pathname_type = 'filename' if not pathname_type: raise TypeError('Expected pathname pattern, got "%s" (type: %s)' % (pathname_pattern, type(pathname_pattern))) glib_regex = _glib_regex(pathname_pattern) for file_pathname in file_list: if PATHNAME_MAP[pathname_type](file_pathname, glib_regex): yield file_pathname def _glib_regex(pathname_pattern): """ Helper for taking pathname patterns and converting them into Python regexes with Unix pathname matching behavior. :param pathname_pattern: String pathname :return: Compiled Regex """ # First escape '.' pathname_pattern.replace('.', '\.') if has_magic(pathname_pattern): # Replace unspecific '*' and '?' with regex appropriate specifiers ('.') for special_char in ('*', '?'): split_pattern = pathname_pattern.split(special_char) new_split_pattern = [] # For each section, if there is no regex appropriate closure, add a generic catch. for bucket in split_pattern: if bucket: # If previous character is not regex closure and is not end of string, then add char... if bucket[-1] != ']' and split_pattern.index(bucket) != len(split_pattern) - 1: bucket += '[^/]' elif split_pattern.index(bucket) == 0: # If match char was beginning of string, add regex char... bucket += '[^/]' new_split_pattern.append(bucket) # Rejoin on special characters pathname_pattern = special_char.join(new_split_pattern) return re.compile(pathname_pattern) # TODO: Add better variable guarantees via type checking/casting, or unicode spoofing (see glob for reference).
#fileList = ["myfile.txt", "myprogram.exe", "yourfile.txt"] #for index in range(len(fileList)): # print(fileList[index].upper()) # print(fileList[index][0].upper()) aList = [34, 45, 67] target = 45 #if target in aList: # print(aList.index(target)) #else: # print(-1) #for index in range(len(aList)): # if target in aList: # print(index, aList[index]) # print(aList.index(target)) first = [10, 20, 30] second = first print(first) print(second) print(first[1]) first[1] = 99 print(second) third = [] for elements in first: third.append(elements) print(third) print(first) fourth = list(first) print(fourth)
class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) def friend(self, friend_name): #return a new student called 'friend_name' in the same school as self return Student(friend_name, self.school) #creating a new instance on the fly anna = Student('Anna', 'Oxford') friend = anna.friend("Greg") print(friend.name) print(friend.school) #inheritance in python, you pass the parent class name in () to the subclass class WorkingStudent(Student): def __init__(self, name, school, salary): super().__init__(name, school) # calling the parent class init function via the super() method and then using it to set the name and the school values of the subclass self.salary = salary anna = WorkingStudent('Anna', 'Oxford', 20.00) print(anna.salary)
lottery_player_dict = { 'name' : 'Rolf', 'numbers': (5,9,12,3,1,21) } class LotteryPlayer: def __init__(self, name): self.name = name self.numbers = (5,9,12,3,1,21) def total(self): return sum(self.numbers) playerOne = LotteryPlayer('Omar') playerOne.numbers = (1,2,4,5,6) playerTwo = LotteryPlayer('Ali') print(playerOne.name) print(playerOne.total()) print(playerOne.numbers == playerTwo.numbers) class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) #@staticmethod & @classmethod are called decerators @staticmethod def go_to_school(): #print("I'm going to {}.".format(self.school)) print("I'm going to school") anna = Student("Anna", "MIT") rolf = Student("Rolf", "Oxford") anna.marks.append(56) print(anna.marks) Student.go_to_school()
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("CONTROL FLOW") # name will be '' (empty) if the user does not type a name name = st.text_input('Name (insert your name here) ') # display inserted name st.write(name) st.write("No subsequent code will be run until some name is inserted (any name different from empty '') ") if name=='': st.warning('Please input a name.') # Make any subsequent code not to run (which includes st.success) st.stop() st.success('Thank you for inputting a name') st.write(f"Your name has {len(name)} letters") if __name__ == "__main__": main()
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("CACHE") st.info("Use st.cache() to speed up loading time of functions with expensive computation") import time @st.cache(suppress_st_warning=True, ttl=None) # ๐Ÿ‘ˆ Changed this def expensive_computation(a, b): # ๐Ÿ‘‡ Added this st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) """ NOTE: You may have noticed that weโ€™ve added the suppress_st_warning keyword to the @st.cache decorators. Thatโ€™s because the cached function above uses a Streamlit command itself (st.write in this case), and when Streamlit sees that, it shows a warning that your command will only execute when you get a cache miss. More often than not, when you see that warning itโ€™s because thereโ€™s a bug in your code. However, in our case weโ€™re using the st.write command to demonstrate when the cache is being missed, so the behavior Streamlit is warning us about is exactly what we want. As a result, we are passing in suppress_st_warning=True to turn that warning off. """ if __name__ == "__main__": main()
def main(): import streamlit as st st.title("DISPLAY OBJECTS / TEXT / CODE / Other inputs") #%% st.write(): FLEXIBLE DISPLAY --------------------------- st.header("[write() function](https://docs.streamlit.io/en/stable/api.html?highlight=streamlit.write#streamlit.write)") st.subheader("st.write() displays appropriate output based on the input type") st.info(''' Arguments are handled as follows: - write(string): Prints the formatted Markdown string, with support for LaTeX expression and emoji shortcodes. See docs for st.markdown for more. - write(data_frame) : Displays the DataFrame as a table. - write(error) : Prints an exception specially. - write(func) : Displays information about a function. - write(module) : Displays information about the module. - write(dict) : Displays dict in an interactive widget. - write(obj) : The default is to print str(obj). - write(mpl_fig) : Displays a Matplotlib figure. - write(altair) : Displays an Altair chart. - write(keras) : Displays a Keras model. - write(graphviz) : Displays a Graphviz graph. - write(plotly_fig) : Displays a Plotly figure. - write(bokeh_fig) : Displays a Bokeh figure. - write(sympy_expr) : Prints SymPy expression using LaTeX. ''') #%% MARKDOWN ----------------------------------------- st.header("MARDKOWN") with st.echo(): st.markdown("## Subheader created with Markdown") #%% CODE ----------------------------------------------------- st.header("CODE") with st.echo(): code = ''' def hello(): print("Hello, Streamlit!") ''' st.code(code, language='python') #%% DATAFRAME ------------------------------------------------- st.header("DATAFRAME") with st.echo(): import streamlit as st import pandas as pd from datetime import datetime df = pd.DataFrame({ 'country': ['Brazil']*3 + ['Ireland']*3, 'date':['2020-01-01','2020-02-01','2020-03-01'] + ['2020-01-01','2020-01-02','2021-01-03'], 'population': [200*10**6]*3 + [6*10**6]*3, 'gdp_growth': [4.2,5,-1,8,7,6.9] }) # Convert into date type df["date2"] = pd.to_datetime(df["date"]) # Convert into specified str format df["date3"] = df["date2"].dt.strftime("%d-%m-%Y") st.write("Method 1 - st.dataframe() - Interactive Table") st.dataframe(df) st.write("Method 2 - st.write() - same result as above") st.write(df) st.write("Method 3 - Static Table") st.table(df) #%% DOCSTRING ------------------------------------------------- st.header("DOCSTRING") with st.echo(): import pandas as pd st.help(pd.DataFrame) if __name__ == "__main__": main()
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("SIDEBAR") st.write("To place an element in the sidebar just add the prefix `sidebar.` to it") st.header("Look at the bottom of the lateral left bar") st.sidebar.title("Sidebar Title") st.sidebar.info( """ ## Sidebar Info BOX This app was built solely for educational purposes. In case of any doubt, [contact me](https://wa.me/<insert-your-whatsapp-number-here>?text=How%20can%20I%20help?). """ ) if __name__ == "__main__": main()
digit_to_area = { 0 : 'Warszawa', 1 : 'Olsztyn', 2 : 'Lublin', 3 : 'Krakรณw', 4 : 'Katowice', 5 : 'Wrocล‚aw', 6 : 'Poznaล„', 7 : 'Szczecin', 8 : 'Gdaล„sk', 9 : 'ลรณdลบ', } def get_city(zip_code): if len(zip_code) !=6: return None if zip_code[2] !='-': return None if not (zip_code[:2] + zip_code[3:]).isdigit(): return None city_code = int(zip_code[0]) return digit_to_area[city_code] if __name__ == '__main__' : code = input('Please provide zip code: ') city = get_city(code) if city: print(f'Witaj goล›ciu z miasta {city}') else: print('Nieprawidล‚owy kod pocztowy')
import random def getAnswer(answerNumber): if answerNumber == 1: return 'To pewne' elif answerNumber == 2: return 'Zdecydowanie tak' elif answerNumber == 3: return 'Tak' elif answerNumber == 4: return 'Niejasna odpowiedลบ, sprรณbuj ponownie' elif answerNumber == 5: return 'Zapytaj ponownie pรณลบniej' elif answerNumber == 6: return 'Skoncentruj siฤ™ i zapytaj ponownie' elif answerNumber == 7: return 'Moja odpowiedลบ brzmi nie' elif answerNumber == 8: return 'To nie wyglฤ…da zbyt dobrze' elif answerNumber == 9: return 'Bardzo wฤ…tpliwe' r = random.randint(1, 9) fortune = getAnswer(r) print(fortune)
''' Created by Roman Beya Created on 6-nov-2017 Created for ICS3U This program plays Black Jack! ''' from numpy import random import ui # generating random cards for dealer(2) and player(3) dealer_card_1 = random.randint(1, 11) dealer_card_2 = random.randint(1, 11) player_card_1 = random.randint(1, 11) player_card_2 = random.randint(1, 11) # Generated if they request a 3rd card player_card_3 = random.randint(1, 11) # creating the variables which hold the sum of each opponents cards, globally dealer_cards_sum = 0 player_cards_sum = 0 def view_cards_touch_up_inside(sender): # When the user presses this button, their cards will appear # calling global variables to be manipulated global player_card_1 global player_card_2 # Displaying player cards view['player_card_label'].text = "My cards: {0}, {1}".format(player_card_1, player_card_2) # disable button if pressed view['view_cards_button'].enabled = False view['view_cards_button'].alpha = 0.25 def draw_card_touch_up_inside(sender): # if the user draws another card, this function will serve as a relay # This function serves to send the 'check cards' function that a new card is being drawn global player_card_1 global player_card_2 global player_card_3 # display new card view['player_card_label'].text = 'My Cards: {0}, {1}, {2}'.format(player_card_1, player_card_2, player_card_3) # disable this button if it is pressed view['draw_cards_button'].enabled = False view['draw_cards_button'].alpha = 0.25 def check_cards_touch_up_inside(sender): # compares the sum of dealers cards vs sum of player cards # call global variables to be manipulated global dealer_card_1 global dealer_card_2 global player_card_1 global player_card_2 global player_card_3 global dealer_cards_sum global player_cards_sum # display the dealers cards view['dealer_card_label'].text = "Dealer's Cards:\n{0}, {1}".format(dealer_card_1, dealer_card_2) # checking if the draw card button is disable implies that it has been pressed # Thus, a new card can now be generated if view['draw_cards_button'].enabled == False: # display new card view['player_card_label'].text = 'My Cards: {0}, {1}, {2}'.format(player_card_1, player_card_2, player_card_3) # summing each opponents cards to determine who is closer to 21 dealer_cards_sum = dealer_card_1 + dealer_card_2 player_cards_sum = player_card_1 + player_card_2 + player_card_3 # comparing their respective sums if dealer_cards_sum >= player_cards_sum and dealer_cards_sum <= 21: # This condition will only run if the dealer is currently winning view['output_label'].text = "Sum of Dealer's Cards: {0}\nSum of Your Cards: {1}\nYou Lose.".format(dealer_cards_sum, player_cards_sum) else: # If the condition tested above is proven false, then that implies that the player is currently winning if player_cards_sum <= 21: view['output_label'].text = "Sum of Dealer's Cards: {0}\nSum of Your Cards: {1}\nYou Win!".format(dealer_cards_sum, player_cards_sum) else: # If the user chooses not to draw another card... # summing each opponents cards to determine who is closer to 21 dealer_cards_sum = dealer_card_1 + dealer_card_2 player_cards_sum = player_card_1 + player_card_2 # comparing their respective sums if dealer_cards_sum >= player_cards_sum and dealer_cards_sum <= 21: # This condition will only run if the dealer is currently winning view['output_label'].text = "Sum of Dealer's Cards: {0}\nSum of Your Cards: {1}\nYou Lose.".format(dealer_cards_sum, player_cards_sum) else: # If the condition tested above is proven false, then that implies that the player is currently winning if player_cards_sum <= 21: view['output_label'].text = "Sum of Dealer's Cards: {0}\nSum of Your Cards: {1}\nYou Win!".format(dealer_cards_sum, player_cards_sum) # if the user choose not the draw another card, disable the button once they have checked their cards against the dealer view['draw_cards_button'].enabled = False view['draw_cards_button'].alpha = 0.25 # disable this button if it is pressed view['check_cards_button'].enabled = False view['check_cards_button'].alpha = 0.25 view = ui.load_view() view.present('full_screen')
''' Created on 12.5.2016 @author: Miko Kari ''' import sys, math import numpy as np # Get minimum distance from A to B using Dijkstra's algorithm. def get_min_distance(graph, start, goal): best_distance = {id: None for id in graph.keys()} # dictionary of current distances to frontier nodes previous_node = {} # dictionary of previous nodes in best paths closed = [] # indicates closed nodes # initialize with start node current = start current_distance = 0 best_distance[current] = current_distance # Start search while best_distance: if current == goal: break # reached the goal # add new nodes to the frontier (defined by nodes with specified distance) for neighbor, distance in graph[current].items(): # deal with this node if not yet closed if neighbor in closed: continue # calculate new distance from start to this node new_distance = current_distance + distance # replace or update previous distance if appropriate if best_distance[neighbor] is None or best_distance[neighbor] > new_distance: best_distance[neighbor] = new_distance previous_node[neighbor] = current # mark source node for this currently best distance # remove current node from frontier and mark it closed closed.append(current) del best_distance[current] # determine best node in frontier to be the next current node try: # find frontier node at minimum distance from start node min_distance = min([value for value in best_distance.values() if not value == None]) # get first item with that minimum value (if multiple with draw) current, current_distance = [(k,v) for k,v in best_distance.items() if v==min_distance][0] except: print('No path found!') break # end while loop, return dictionary with best transitions return previous_node def get_graph(cartesian_data, satellite_ids): # Determine point pairs without ray intersection with Earth mat = np.ones((len(cartesian_data),len(cartesian_data)))*-9 for i in range(len(cartesian_data)-1): for j in range(i+1,len(cartesian_data)): if check_ray(cartesian_data[i],cartesian_data[j],r) == 1: # the two points are connected d = np.linalg.norm(cartesian_data[i]-cartesian_data[j]) mat[i][j] = d mat[j][i] = d with open('mat.txt','w') as outf: outf.writelines(','.join(str(item) for item in inner_list)+"\n" for inner_list in mat) # Build the graph as a dictionary of dictionaries containing neighbors and their distances graph = {} for i in range(len(satellite_ids)): neighbors_dict = {satellite_ids[index]: dist for index, dist in enumerate(mat[i]) if not dist == -9} graph[satellite_ids[i]] = neighbors_dict return graph # Checks whether there's a line-of-sight b/w points p1 and p2 def check_ray(p1,p2, radius): epsilon = 0.05 # error margin in comparisons of floats rounding_digits = 2 # round floats to nearest 10 meters before comparisons unit_vector = (p2-p1)/np.linalg.norm(p2-p1) discriminant = math.pow(np.dot(unit_vector,p1),2) - math.pow(np.linalg.norm(p1),2) + radius**2 # test for intersection between line and sphere if round(discriminant) < 0 - epsilon: # make sure it really is negative # line did not intersect sphere, neither can line segment return 1 # no intersection else: # Still not clear whether SEGMENT and sphere have intersected # Intersections given by |p1|**2 - r**2 + 2d*p1*i + d**2 = 0, where i is the unit vector # check whether intersection occurs on line segment between p1 and p2 by solving for d. # get distance between p1 and p2, this is the upper limit for intersection d-value in x = p1+d(p2-p1)/|p2-p1| d_limit = round(np.linalg.norm(p1-p2),rounding_digits) # solve above quadratic equation for d: d = (-b +- sqrt(b**2 - 4a*c)) / 2a b = np.dot(unit_vector,p1) s = math.sqrt(discriminant) d1 = round(-b + s, rounding_digits) d2 = round(-b - s, rounding_digits) # There is intersection only if both d1 and d2 are within [0,d_limit] if 0 <= d1 and d1 <= d_limit and 0 <= d2 and d2 <= d_limit: return 0 # Intersection else: return 1 # no intersection # Converts spherical coordinates to Cartesian coordinates def spherical_to_cartesian(list,radius): # convert degrees to radians first lat = math.radians(float(list[0])) long = math.radians(float(list[1])) alt = float(list[2]) k = alt + radius # distance from center of sphere return np.array((k*math.cos(lat)*math.cos(long), k*math.cos(lat)*math.sin(long), k*math.sin(lat))) if __name__ == '__main__': # read name of data file given as command line parameter data_file = sys.argv[1] r = 6371 # radius of Earth # Read data from file with open(data_file,'r') as fin: # read first line containing SEED fin.readline() # read data lines line = fin.readline() satellite_ids = [] spherical_data = [] while 'ROUTE' not in line: # append new satellite info to list parts = line.split(',') # gives: ID, latitude, longitude, altitude satellite_ids.append(parts[0]) spherical_data.append(parts[1:]) line = fin.readline() # handle ROUTE line route_data = line.split(',') start_point = route_data[1:3] start_point.append(0) # add altitude field end_point = route_data[3:5] end_point.append(0) # add altitude field # convert start and end points to Cartesian coordinates start_point = spherical_to_cartesian(start_point, r) end_point = spherical_to_cartesian(end_point, r) # Convert satellites' spherical coordinates to Cartesian cartesian_data = [] for item in spherical_data: cartesian_data.append(spherical_to_cartesian(item,r)) # add start and end points to the list of Cartesian coordinates cartesian_data.extend([start_point,end_point]) # add start and end point IDs 'A' and 'B' to the list of satellite IDs satellite_ids.extend(['A','B']) # Determine graph formed by satellites and start and end points, accounting for lines-of-sight graph = get_graph(cartesian_data, satellite_ids) # Find shortest path in resulting graph (minimum length, minimum number of edges) # Dijkstra's algorithm start = 'A' goal = 'B' source = get_min_distance(graph, start, goal) # determine path from start to goal, given one was found if 'B' in source: # Path was found to goal, trace it back to start current = goal path = [current] while current != start: current = source[current] path.append(current) path.reverse() # save path to file with open('route.txt','w') as f: path = ','.join(str(item) for item in path[1:-1]) f.write(path) print('Path stored: %s' % path)
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 03:05:45 2019 @author: marie """ def sumDigits(n): if n == 0: return 0 else: return n % 10 + sumDigits(int(n / 10)) print(sumDigits(345)) print(sumDigits(45))
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 02:21:24 2019 @author: marie """ # This sorts the dictionary by value (either in ascending or descending order) import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True) print('Dictionary in descending order by value : ',sorted_d) # This allows you to add another key into an existing Dictionary d = {0:10, 1:20} print(d) d.update({2:30}) print(d) # This concatenates (joins) dictionaries to make one large Dictionary dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic4 = {} for d in (dic1, dic2, dic3): dic4.update(d) print(dic4) # This checks whether a key is present inside a Dictionary d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} def is_key_present(x): if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary') is_key_present(5) is_key_present(9) # This allows you to iterate of dictionaries using for loops d = {'x': 10, 'y': 20, 'z': 30} for dict_key, dict_value in d.items(): print(dict_key,'->',dict_value) # This generates and prints a dictionary that contains a number between 1 and number n=int(input("Input a number ")) d = dict() for x in range(3,n+1): d[x]=x*x print(d) # This prints a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys d=dict() for x in range(1,16): d[x]=x**2 print(d) # This merges 2 python dictionaries d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(d) # This iterates over a dictionary using for loops d = {'Red': 1, 'Green': 2, 'Blue': 3} for color_key, value in d.items(): print(color_key, 'corresponds to ', d[color_key]) # This sums all the items in a dictionary my_dict = {'data1':100,'data2':-54,'data3':247} print(sum(my_dict.values())) # This multiplies all the items in a dictionary my_dict = {'data1':100,'data2':-54,'data3':247} result=1 for key in my_dict: result=result * my_dict[key] print(result) # This removes a key from a dictionary myDict = {'a':1,'b':2,'c':3,'d':4} print(myDict) if 'a' in myDict: del myDict['a'] print(myDict) # This maps two lists into a dictionary keys = ['red', 'green', 'blue'] values = ['#FF0000','#008000', '#0000FF'] color_dictionary = dict(zip(keys, values)) print(color_dictionary) # This sorts a dictionary by key color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print("%s: %s" % (key, color_dict[key])) # This gets the maximum and minimum value in a dictionary my_dict = {'x':500, 'y':5874, 'z': 560} key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Maximum Value: ',my_dict[key_max]) print('Minimum Value: ',my_dict[key_min]) # This gets a dictionary from an object's fields class dictObj(object): def __init__(self): self.x = 'red' self.y = 'Yellow' self.z = 'Green' def do_nothing(self): pass test = dictObj() print(test.__dict__) # This removes duplicates from Dictionary student_data = {'id1': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id2': {'name': ['David'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id3': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id4': {'name': ['Surya'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, } result = {} for key,value in student_data.items(): if value not in result.values(): result[key] = value print(result) # This checks whether a dictionary is empty or not my_dict = {} if not bool(my_dict): print("Dictionary is empty") # This combines two dictionary adding values for common keys from collections import Counter d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} d = Counter(d1) + Counter(d2) print(d) # This prints all unique values in a dictionary L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}] print("Original List: ",L) u_value = set( val for dic in L for val in dic.values()) print("Unique Values: ",u_value) # This creates and display all combinations of letters, selecting each letter from a different key in a dictionary import itertools d ={'1':['a','b'], '2':['c','d']} for combo in itertools.product(*[d[k] for k in sorted(d.keys())]): print(''.join(combo)) # This finds the highest 3 values in a dictionary from heapq import nlargest my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} three_largest = nlargest(3, my_dict, key=my_dict.get) print(three_largest) # This combines values in python list of dictionaries from collections import Counter item_list = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}] result = Counter() for d in item_list: result[d['item']] += d['amount'] print(result) # This creates a dictionary from a string from collections import defaultdict, Counter str1 = 'w3resource' my_dict = {} for letter in str1: my_dict[letter] = my_dict.get(letter, 0) + 1 print(my_dict) # This prints a dictionary in table format my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]} for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))): print(*row) # This counts the values associated with key in a dictionary student = [{'id': 1, 'success': True, 'name': 'Lary'}, {'id': 2, 'success': False, 'name': 'Rabi'}, {'id': 3, 'success': True, 'name': 'Alex'}] print(sum(d['success'] for d in student)) # This converts a list into a nested dictionary of keys num_list = [1, 2, 3, 4] new_dict = current = {} for name in num_list: current[name] = {} current = current[name] print(new_dict) # This sorts a list alphabetically in a dictionary num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]} sorted_dict = {x: sorted(y) for x, y in num.items()} print(sorted_dict) # This removes spaces from dictionary keys student_list = {'S 001': ['Math', 'Science'], 'S 002': ['Math', 'English']} print("Original dictionary: ",student_list) student_dict = {x.translate({32: None}): y for x, y in student_list.items()} print("New dictionary: ",student_list) # This gets the top three items in a shop from heapq import nlargest from operator import itemgetter items = {'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24} for name, value in nlargest(3, items.items(), key=itemgetter(1)): print(name, value) # This gets the key, value and item in a dictionary dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} print("key value count") for count, (key, value) in enumerate(dict_num.items(), 1): print(key,' ',value,' ', count) # This prints a dictionary line by line students = {'Aex':{'class':'V', 'rolld_id':2}, 'Puja':{'class':'V', 'roll_id':3}} for a in students: print(a) for b in students[a]: print (b,':',students[a][b]) # This checks multiple keys exists in a dictionary student = { 'name': 'Alex', 'class': 'V', 'roll_id': '2' } print(student.keys() >= {'class', 'name'}) print(student.keys() >= {'name', 'Alex'}) print(student.keys() >= {'roll_id', 'name'}) # This counts number of items in a dictionary value that is a list dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} ctr = sum(map(len, dict.values())) print(ctr) # This sorts Counter by value from collections import Counter x = Counter({'Math':81, 'Physics':83, 'Chemistry':87}) print(x.most_common()) # This creates a dictionary from two lists without losing duplicate values from collections import defaultdict class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII'] id_list = [1, 2, 2, 3] temp = defaultdict(set) for c, i in zip(class_list, id_list): temp[c].add(i) print(temp) # This replaces dictionary values with their sum def sum_math_v_vi_average(list_of_dicts): for d in list_of_dicts: n1 = d.pop('V') n2 = d.pop('VI') d['V+VI'] = (n1 + n2)/2 return list_of_dicts student_details= [ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74}, {'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86} ] print(sum_math_v_vi_average(student_details)) # This converts a dictionary to OrderedDict import collections student = [("Student_name", "Alex"), ("ID", 5), ("Class", 'V'), ("Country", 'USA')] student = collections.OrderedDict(student) print(student) # This matches key values in two dictionaries x = {'key1': 1, 'key2': 3, 'key3': 2} y = {'key1': 1, 'key2': 2} for (key, value) in set(x.items()) & set(y.items()): print('%s: %s is present in both x and y' % (key, value))
# -*- coding: utf-8 -*- """ Created on Tue Jun 25 11:53:37 2019 @author: marie """ # return fibonnaci of a certain number def Fibonnaci(iterations): listt=[] summ=0 if iterations==1: return 0 elif iterations==2: return 1 else: return Fibonnaci(iterations-1)+Fibonnaci(iterations-2) #iterative fibonnaci def fibonacci(n): a = 0 b = 1 for i in range(0, n): temp = a a = b b = temp + b return a # Display the first 15 Fibonacci numbers. for c in range(0, 17): print(fibonacci(c)) #print(Fibonnaci(9)) #listt to show fibonnaci sequence def gen_fib(): count = int(input("How many fibonacci numbers would you like to generate? ")) i = 1 if count == 0: fib = [] elif count == 1: fib = [1] elif count == 2: fib = [1,1] elif count > 2: fib = [1,1] while i < (count - 1): fib.append(fib[i] + fib[i-1]) i += 1 return fib print(gen_fib())
#global_variavles #board board=["-","-","-", "-","-","-", "-","-","-",] winner=None #who's turn current_player="X" game_still_going=True #display def display_board(): print(board[0]+" | "+board[1]+" | "+board[2]) print(board[3]+" | "+board[4]+" | "+board[5]) print(board[6]+" | "+board[7]+" | "+board[8]) def play_game(): #dispay board display_board() #while the game is still going while game_still_going: #handle single turn of player handle_turn(current_player) #checks game is over or not check_if_game_over() #flip to other player flip_player() #print winner if winner=="X" or winner=="O": print(winner+" won!") #if the game is tie else: print("tie!") #handle a single turn def handle_turn(player): print(player+"'s turn") position=input("choose from 1 to 9 : ") valid=False while not valid: while position not in ["1","2","3","4","5","6","7","8","9"]: position=input("choose from 1 to 9 : ") position=int(position)-1 if board[position]=="-": valid=True else: print("you cant go there") board[position]=player display_board() def check_if_game_over(): check_win() check_tie() def check_win(): global winner #check rows row_winner=check_rows() #check colums col_winner=check_cols() #check diagonals diag_winner=check_diag() if row_winner: #there was a win winner=row_winner elif col_winner: #there was a win winner=col_winner elif diag_winner: #there was a win winner=diag_winner else: winner=None #there was no win return def check_rows(): global game_still_going row_1=board[0]==board[1]==board[2]!="-" row_2=board[3]==board[4]==board[5]!="-" row_3=board[6]==board[7]==board[8]!="-" if row_1 or row_2 or row_3: game_still_going=False #return the winner if row_1: return board[0] elif row_2: return board[3] elif row_3: return board[6] return def check_cols(): global game_still_going col_1=board[0]==board[3]==board[6]!="-" col_2=board[1]==board[4]==board[7]!="-" col_3=board[2]==board[5]==board[8]!="-" if col_1 or col_2 or col_3: game_still_going=False #return the winner if col_1: return board[0] elif col_2: return board[1] elif col_3: return board[2] return def check_diag(): global game_still_going dag_1=board[0]==board[4]==board[8]!="-" dag_2=board[2]==board[4]==board[6]!="-" if dag_1 or dag_2: game_still_going=False #return the winner if dag_1: return board[0] elif dag_2: return board[2 ] return def check_tie(): global game_still_going if "-" not in board: game_still_going=False return def flip_player(): global current_player if current_player=="X": current_player="O" elif current_player=="O": current_player="X" return play_game() #play game #handle turn # check win #check tie #flip player
# stolen shamelessly from: # http://stackoverflow.com/questions/18262306/quicksort-with-python def quicksort(array): less, equal, greater = [], [], [] if len(array) <= 1: return array else: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x > pivot: greater.append(x) return quicksort(less) + list(equal) + quicksort(greater) print(quicksort([1,2,3,2,54,2,3432,124,54,32]))
""" Logistic regression for multiclass classification Class labels Hypernyms = 0 Co-siblings = 1 Random = 2 See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import tensorflow as tf import gensim import numpy as np FLAGS = None # function which generates WORD vectors and returns training and test feature vectors def word_embeddding(): fname = "datasets/BLESS/BLESS_hyper-new4.txt" model = gensim.models.KeyedVectors.load_word2vec_format('~/MoSIG/2016_data/S2/Summer_internship/Models/GoogleNews-vectors-negative300.bin', binary=True) with open(fname) as f: hyper = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line hyper = [x.strip('\n') for x in hyper] hyper = [x.split('\t') for x in hyper] hyper0 = [x[0].split('-n')[0] for x in hyper] hyper1 = [x[2].split('-n')[0] for x in hyper] v0 = [model[x] for x in hyper0] # Generate vector of word1 of pair (dimension = 300) v1 = [model[x] for x in hyper1] # Generate vector of word2 of pair (dimension = 300) #print("HYPERNYMS") #print(np.array(v0).shape) # Converting to float32 numpy array v0 = np.array(v0, dtype = np.float32) v1 = np.array(v1, dtype = np.float32) v_hyp = np.concatenate((v0,v1), axis=1) # Generating feature vector for word pair by concatenating the vectors (dimension = 600) labels_hyp = np.zeros(v_hyp.shape[0], dtype=np.int) # Class label for hypernym = 0 #print (labels_hyp.size) #print (v_hyp.shape) fname = "datasets/BLESS/BLESS_coord-new6.txt" with open(fname) as f: hyper = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line hyper = [x.strip('\n') for x in hyper] hyper = [x.split('\t') for x in hyper] hyper0 = [x[0].split('-n')[0] for x in hyper] hyper1 = [x[2].split('-n')[0] for x in hyper] hyper2 = [x[1] for x in hyper] v0 = [model[x] for x in hyper0] # Generate vector of word1 of pair (dimension = 300) v1 = [model[x] for x in hyper1] # Generate vector of word2 of pair (dimension = 300) #print("CO SIBLINGS") #print(np.array(v0).shape) v0 = np.array(v0, dtype = np.float32) v1 = np.array(v1, dtype = np.float32) v_coord = np.concatenate((v0,v1), axis=1) # Generating feature vector for word pair by concatenating the vectors (dimension = 600) labels_coord = np.empty(v_coord.shape[0], dtype=np.int) labels_coord.fill(1) # Class label for co-sibling = 1 #print (labels_coord.size) #print (v_coord.shape) fname = "datasets/BLESS/BLESS_random-new5.txt" with open(fname) as f: hyper = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line hyper = [x.strip('\n') for x in hyper] hyper = [x.split('\t') for x in hyper] hyper0 = [x[0].split('-n')[0] for x in hyper] hyper1 = [x[2].split('-n')[0] for x in hyper] hyper2 = [x[1] for x in hyper] v0 = [model[x] for x in hyper0] v1 = [model[x] for x in hyper1] #print("RANDOM") #print(np.array(v0).shape) v0 = np.array(v0, dtype = np.float32) v1 = np.array(v1, dtype = np.float32) v_rand = np.concatenate((v0,v1), axis=1) labels_rand = np.empty(v_rand.shape[0], dtype=np.int32) labels_rand.fill(2) # Class label for random = 2 #print (labels_rand.size) #print (v_rand.shape) v_final = np.concatenate((v_hyp, v_rand, v_coord), axis=0) # Merging all vectors labels_final = np.concatenate((labels_hyp, labels_rand, labels_coord), axis=0) labels_final = np.expand_dims(labels_final, axis=1) #print("FINAL") #print(v_final.shape) #print(labels_final.shape) BIG = np.concatenate((v_final, labels_final), axis=1) #print(BIG.shape) np.random.shuffle(BIG) # Shuffling the dataset #print(BIG.shape) EMBEDD = BIG[:, 0:600] LAB = BIG[:,600] #print(LAB[1:50]) LAB = np.int32(LAB) LAB = np.expand_dims(LAB, axis=1) #one-hot encoding for the labels LABELS = np.zeros((len(LAB), 3)) LABELS[np.arange(len(LAB)), LAB[:,0]] = 1 #print(LABELS.shape) #print(LABELS[1:50,:]) return EMBEDD[:4094,:], LABELS[:4094,:], EMBEDD[4095:,:], LABELS[4095:,:] # splitting training 4094 pairs, test def main(_): # Create the model x = tf.placeholder(tf.float32, [None, 600]) W = tf.Variable(tf.zeros([600, 3])) b = tf.Variable(tf.zeros([3])) y = tf.matmul(x, W) + b # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 3]) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() batch_xs, batch_ys, test_xs, test_ys = word_embeddding() #Using regular gradient descent without batching i.e using the entire training set for each update # Train for _ in range(1000): sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Test trained model after each iteration correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: test_xs, y_: test_ys})) if __name__ == '__main__': tf.app.run(main=main)
def longestCommonPrefix(strs): result = "" temp = "" if len(strs) == 1: return strs[0] if len(strs) > 1: for i in range(len(strs[0])): letter = strs[0][i] for j in xrange(1, len(strs)): temp = "" if len(strs[j]) < 1: return "" elif i >= len(strs[j]): break elif strs[j][i] == letter: #print "haha", j, i, letter, strs[j][i] continue else: temp=strs[0][0:i] result = result + temp return result if __name__ == '__main__': strs = ["a", "a"] print longestCommonPrefix(strs)
#!/usr/bin/env python3 # Created by Malcolm Tompkins # Created on May 4, 2021 # Guess the number game with randomly generated numbers import random # Function that runs Guess the number game def main(): # User input print("Welcome to Guess the number!\nPick a number from 0-100") user_number = int(input("\nYour number is: ")) # Process program_number = random.randint(0, 100) if user_number == program_number: # Output print("\nYou have guessed the correct number, nice!") else: print("\nYou have guessed incorrectly.") print("\nThe correct answer was: {}".format(program_number)) if __name__ == "__main__": main()
#format name = input('์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”:') age = input('๋‚˜์ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”:') print('์ œ ์ด๋ฆ„์€', name, '์ž…๋‹ˆ๋‹ค.' '์ œ ๋‚˜์ด๋Š”', age, '์ž…๋‹ˆ๋‹ค.') #์ฝค๋งˆ๋กœ ์—ฐ๊ฒฐํ•˜๋ฉด space๊ฐ€ ์ž๋™์œผ๋กœ ๋“ค์–ด๊ฐ print('์ œ ์ด๋ฆ„์€ %s์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” %s์ž…๋‹ˆ๋‹ค.'%(name, age)) print('์ œ ์ด๋ฆ„์€ {}์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” {}์ž…๋‹ˆ๋‹ค.'.format(name, age)) print('์ œ ์ด๋ฆ„์€ {0}์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” {0}์ž…๋‹ˆ๋‹ค.'.format(name, age)) #๋’ค์—์„œ ๋„ฃ์„ ๊ฒƒ์˜ index๋กœ ๋„ฃ์Œ. print( f'์ œ ์ด๋ฆ„์€ {name}์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” {age}์ž…๋‹ˆ๋‹ค.' ) s = '์ œ ์ด๋ฆ„์€ {name}์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” {age}์ž…๋‹ˆ๋‹ค.' print(s.format(name='Taeeun', age=23)) #format์˜ ์ž๋ฆฌ์ฐจ์ง€ ##์˜ค๋ฅธ์ชฝ ์ •๋ ฌ print('{0:4} x {1:4} = {2:4}'.format(2, 3, 6)) #4์ž๋ฆฌ์— ๋งž์ถฐ์„œ ์˜ค๋ฅธ์ชฝ ##์™ผ์ชฝ ์ •๋ ฌ print('{0:<4} x {1:<4} = {2:<4}'.format(2, 3, 6)) #4์ž๋ฆฌ์— ๋งž์ถฐ์„œ ์™ผ์ชฝ ##์ค‘์•™์ •๋ ฌ print('{0:^4} x {1:^4} = {2:^4}'.format(2, 3, 6)) #4์ž๋ฆฌ์— ๋งž์ถฐ์„œ ์ค‘์•™ print('{0:#>4} x {1:#>4} = {2:#>4}'.format(2, 3, 6)) print('{0:#<4} x {1:#<4} = {2:#<4}'.format(2, 3, 6)) print('{0:#^4} x {1:#^4} = {2:#^4}'.format(2, 3, 6)) #๋‚˜๋จธ์ง€๊ณต๊ฐ„์„ #์œผ๋กœ ์ฑ„์›Œ๋„ฃ์–ด๋ผ ##์†Œ์ˆ˜์  ์ถœ๋ ฅ print('{0:.3f}'.format(1/4)) #์†Œ์ˆ˜์  ์„ธ ๋ฒˆ์งธ ์ž๋ฆฌ print('{0:,.3f}'.format(8888888888)) #ํŒŒ์ด์ฌ 3.6๋ฒ„์ „๋ถ€ํ„ฐ f๋ฌธ์ž์—ด๋กœ format ๊ฐ€๋Šฅ print(f'์ œ ์ด๋ฆ„์€ {name}์ž…๋‹ˆ๋‹ค. ์ œ ๋‚˜์ด๋Š” {age}์ž…๋‹ˆ๋‹ค.')
#ํ˜• ๋ณ€ํ™˜ #dict a = dict(one=1, two=2, three=3) b = {'one':1, 'two':2, 'three':3} c = dict(zip(['one', 'two', 'three'], [1,2,3])) d = dict([('two',2), ('one',1), ('three',3)]) e = dict({'three':3, 'one':1, 'two':2}) print(a == b == c == d == e) #True print(a, b, c, d, e) #{'one': 1, 'two': 2, 'three': 3}๊ฐ€ 5๋ฒˆ ์ถœ๋ ฅ๋จ ## zip() ### zip(*iterable)์€ ๋™์ผํ•œ ๊ฐœ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ž๋ฃŒํ˜•์„ ๋ฌถ์–ด ์ฃผ๋Š” ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. ### ์—ฌ๊ธฐ์„œ ์‚ฌ์šฉํ•œ *iterable์€ ๋ฐ˜๋ณต ๊ฐ€๋Šฅ(iterable)ํ•œ ์ž๋ฃŒํ˜• ์—ฌ๋Ÿฌ ๊ฐœ๋ฅผ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค. print(list(zip([1, 2, 3], [4, 5, 6]))) # [(1, 4), (2, 5), (3, 6)] print(dict(zip([1, 2, 3], [4, 5, 6]))) # {1: 4, 2: 5, 3: 6} print(list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)] #print(dict(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))) # dictionary update sequence element #0 has length 3; 2 is required print(list(zip("abc", "def"))) # [('a', 'd'), ('b', 'e'), ('c', 'f')] print(dict(zip("abc", "def"))) # {'a': 'd', 'b': 'e', 'c': 'f'} ## map() ### map(f, iterable)์€ ํ•จ์ˆ˜(f)์™€ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ(iterable) ์ž๋ฃŒํ˜•์„ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›๋Š”๋‹ค. ### map์€ ์ž…๋ ฅ๋ฐ›์€ ์ž๋ฃŒํ˜•์˜ ๊ฐ ์š”์†Œ๋ฅผ ํ•จ์ˆ˜ f๊ฐ€ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฌถ์–ด์„œ ๋Œ๋ ค์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค. ### ์˜ˆ์ œ 1 - map() ๋ฏธํ™œ์šฉ def two_times(numberList): result = [ ] for number in numberList: result.append(number*2) return result result = two_times([1, 2, 3, 4]) print(result) # [2, 4, 6, 8] ### ์˜ˆ์ œ 2 - map() ํ™œ์šฉ def two_times_2(x): return x*2 list(map(two_times_2, [1, 2, 3, 4])) # [2, 4, 6, 8] ### ์˜ˆ์ œ 3 - lambda ํ™œ์šฉ list(map(lambda a: a*2, [1, 2, 3, 4])) # [2, 4, 6, 8] ## lambda ์ธ์ž : ํ‘œํ˜„์‹ def hap(x, y): return x + y hap(10, 20) #30 (lambda x,y: x + y)(10, 20) #30 map(lambda x: x ** 2, range(5)) #[0, 1, 4, 9, 16] ## python 2 #python3์—์„œ <map object at 0x00000267E23F3F28> ๋ผ๊ณ  ์ถœ๋ ฅ๋จ list(map(lambda x: x ** 2, range(5))) #[0, 1, 4, 9, 16] ## python 2 ๋ฐ python 3
#ํŒŒ์ผ ์ž…์ถœ๋ ฅ ''' file = open('sample.txt', 'w') # w : ์ƒˆ๋กœ ์“ฐ๊ธฐ(๋ฎ์–ด์“ฐ๊ธฐ), r: ์ฝ๊ธฐ, a : append ์ถ”๊ฐ€ file.write('hello world') file.write('\n') file.write('hello world') file.close() print(dir(file)) ''' file = open('sample.txt', 'r') ''' print(file.read()) #hello world #hello world print(file.readline()) #hello world print(file.readline()) # print(file.readline()) #hello world ''' print(file.readlines()) #['hello world\n', 'hello world'] ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ํ™œ์šฉ ๊ฐ€๋Šฅ file.close() #ํŒŒ์ผ ์ž…์ถœ๋ ฅ ๊ด€๋ จ ์ฑ… <์ธ๊ณต์ง€๋Šฅ์„ ํ™œ์šฉํ•œ ์—…๋ฌด์ž๋™ํ™” With Google Developers Group JEJU>
#range(start:stop:step) ###1. ๋งŽ์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฏธ๋ฆฌ ์ค€๋น„ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค. ###2. ํ•„์š”ํ•œ ์‹œ์ ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. (๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„ ๋ฐฉ์ง€) print(list(range(10))) #0๋ถ€ํ„ฐ 10๊นŒ์ง€. ์‹œ์ž‘๊ฐ’ ์Šคํ‚ตํ•˜๋ฉด 0 print(list(range(10, 20))) #์Šคํ…์€ ์Šคํ‚ตํ•˜๋ฉด 1 print(list(range(1, 100, 1))) #1๋ถ€ํ„ฐ 99๊นŒ์ง€ ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค์–ด์คŒ print(list(range(5, -5, -1))) #5๋ถ€ํ„ฐ -4๊นŒ์ง€ print(type(range(10))) #์ถœ๋ ฅ๊ฐ’ <class 'range'> ###Python 2๋ฒ„์ „์—์„œ type(range(10))๋Š” list ํƒ€์ž…์ด๋‹ค. ###Python 3๋ฒ„์ „์—์„œ range()์˜ ํƒ€์ž…์€ range๋‹ค. ''' ๋งŒ์•ฝ range(1000000)์„ ํ•˜๋ฉด ๋งŽ์€ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์†Œ๋ชจ๋œ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ฆ‰์‹œ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค. ํ•„์š”ํ•œ ์‹œ์ ์—๋งŒ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ Python 3๋ฒ„์ „์—์„œ range ํƒ€์ž…์ด ์ƒ๊ฒผ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ 2๋ฒ„์ „์—๋„ range ํƒ€์ž…์ด ์žˆ๊ธด ํ–ˆ๋‹ค. xrange()๋ผ๋Š” ์ด๋ฆ„์œผ๋กœ. print(type(xrange(100))) #2๋ฒ„์ „ ๊ธฐ์ค€ ์ถœ๋ ฅ๊ฐ’ <type 'xrange'> for i in xrange(10): #2๋ฒ„์ „์—์„œ range()์ฒ˜๋Ÿผ ๋Œ์•„๊ฐ”๋‹ค. print(i) ''' x = iter(range(10)) #0~9 print(next(x)) #0 print(next(x)) #1 print(next(x)) #2
#!/usr/bin/python #-*- coding:utf-8 -*- ###################ๅพช็Žฏ่ฏญๅฅfor####################### names = ['bob', 'james', 'paul'] for name in names: print(name) ################################################## #####################่Œƒๅ›ดๅ‡ฝๆ•ฐrange################################ #range(100)ๅฏไบง็”Ÿ0-99่ฟ™100ไธชๆ•ฐๆฎ sum = 0 tmp = range(100) for i in tmp: sum += i print("sum val:%d" %sum) #listๅ‡ฝๆ•ฐๅฏๅฐ†ๅˆ—่กจไธญ็š„ๆ•ฐๆฎๅˆ—่กจๅŒ–๏ผŒๅญ—็ฌฆไธฒๅˆ—่กจๅŒ–'1234'->'1','2','3','4',ๆ•ฐๅญ—ไธ่ƒฝๅˆ—่กจๅŒ– print(list(tmp)) #################################################### ###################ๅพช็Žฏ่ฏญๅฅwhile####################### #็”จๆณ• sum = 0 n = 99 while n > 0: sum += n n -= 1 print("sum val:%d" %sum) var = input("please input any key to ending")
import os from collections import defaultdict class Person(object): def __init__(self,first_name,last_name): self.first_name = first_name self.last_name = last_name def __repr__(self): return "{first name :" + self.first_name \ + " ; last name :" + self.last_name + "}" a1 = [Person("liu", "xing"), Person("liu", "xu"), Person("zhang", "xing")] a2 = [Person("liu", "qin"), Person("li", "jun"), Person("zhang", "hua")] if __name__=='__main__': print a1 print a2 d = {} for per in a1: if per.first_name not in d: d[per.first_name] = [] d[per.first_name].append(per) for per in a2: if per.first_name not in d: d[per.first_name] = [] d[per.first_name].append(per) print 'normal way group: %s' % d d = {} for per in a1: d.setdefault(per.first_name,[]).append(per) for per in a2: d.setdefault(per.first_name,[]).append(per) print 'dict setdefault: %s' % d d = defaultdict(list) map(lambda per:d[per.first_name].append(per), a1) map(lambda per:d[per.first_name].append(per), a2) print 'defaultdict map: %s' % d
admin={"ๆ–นๅผ€":"123","ๅˆ˜ๆ™จ":"12345"} user={"ๅผ ๆ—ญ":"123321","ๆฒˆ็ซ ":"123456","ๅฐค่ต›่ต›":"123456"} while True: name_=input("่ฏท่พ“ๅ…ฅ็”จๆˆทๅ(ไธ่ƒฝไปฅๆ•ฐๅญ—ๅผ€ๅคด๏ผ)๏ผš") pass_=input("่ฏท่พ“ๅ…ฅๅฏ†็ ๏ผš") if name_ in admin.keys(): if pass_==admin[name_]: print("ๆฌข่ฟŽๆ‚จ๏ผŒ",name_,"!ๆ‚จ็š„็”จๆˆท็ป„ไธบ๏ผš็ฎก็†ๅ‘˜") break else: print("ๅฏ†็ ้”™่ฏฏ๏ผŒ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ๏ผ") else : if name_ in user.keys(): if pass_==user[name_]: print("ๆฌข่ฟŽๆ‚จ๏ผŒ",name_,"!ๆ‚จ็š„็”จๆˆท็ป„ไธบ๏ผš็”จๆˆท") break else: print("ๅฏ†็ ้”™่ฏฏ๏ผŒ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ๏ผ") else: if name_[0] not in ["1","2","3","4","5","6","7","8","9","0"]: if pass_=="guest": print("ๆฌข่ฟŽๆ‚จ๏ผŒ",name_,"!ๆ‚จ็š„็”จๆˆท็ป„ไธบ๏ผšๆธธๅฎข") break else: print("ๅฏ†็ ้”™่ฏฏ๏ผŒ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ๏ผ") else: print("่ฏท่พ“ๅ…ฅๆญฃ็กฎ็š„็”จๆˆทๅ๏ผ")
""" Solution of; Project: Problems vs Algorithms Problem 2: Search in a Rotated Sorted Array """ def binary_search(arr, low, high, target): """ return the target eleents index if it is not exists return -1 """ if low > high: return -1 mid_index = (low + high) // 2 if arr[mid_index] == target: return mid_index elif arr[mid_index] > target: return binary_search(arr, low, mid_index - 1, target) return binary_search(arr, mid_index + 1, high, target) def find_pivot(arr, low, high): """ return the pivot element's index in the given array ex: if array is arr=[4,5,6,7,8,1,2,3] pivot element is 8 which's index is 4 """ if high < low: return -1 if high == low: return low else: mid_index = (low + high) // 2 if mid_index < high and arr[mid_index] > arr[mid_index + 1]: return mid_index if mid_index > low and arr[mid_index - 1] > arr[mid_index]: return mid_index - 1 if arr[low] >= arr[mid_index]: return find_pivot(arr, low, mid_index - 1) return find_pivot(arr, mid_index + 1, high) def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ if input_list == [] or number is None: return -1 arr = input_list low = 0 high = len(input_list) - 1 target = number pivot_index = find_pivot(arr, low, high) # if pivot_index is -1 then arr is not rotated if pivot_index == -1: return binary_search(arr, low, high, target) else: # if pivot_index element equals to target # return pivot_index if arr[pivot_index] == target: return pivot_index # if target element is grater than 0th element # search for left half if target >= arr[0]: return binary_search(arr, 0, pivot_index - 1, target) # if mid element is smaller than 0th element # search right half return binary_search(arr, pivot_index + 1, high, target) def linear_search(input_list, number): if input_list == [] or number is None: return -1 for index, element in enumerate(input_list): if element == number: return index return -1 def test_function(test_case): input_list = test_case[0] number = test_case[1] if linear_search(input_list, number) == rotated_array_search(input_list, number): print("Pass") else: print("Fail") test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6]) test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 8]) test_function([[6, 7, 8, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 10]) test_function([[9999], 9999]) test_function([[], 9999]) test_function([[], None])
from typing import List from pathlib import Path def extract_from_result(filename: str) -> List: """ Function to extract result after running the sat solver :param filename: Path of file containing the SAT solver result :returns: List of variables with true value in the solution. Empty in case there is no possible solution """ if not Path(filename).exists(): raise Exception(f"Results file {filename} could not be found.") with open(filename) as f: result = f.readline().strip() response = [] if result == "s SATISFIABLE": vars = f.readline().split(" ") if vars[0] != "v": line = " ".join(vars) raise Exception(f"Unexpected line '{line}' in file {filename}") # Removing initial v and final 0 vars = vars[1:len(vars) - 1] response = [int(var) for var in filter(lambda x : int(x) > 0, vars)] return response elif result == "s UNSATISFIABLE": return response else: raise Exception(f"Unexpected line '{result}' in file {filename}")
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost", "amit", "amitt", "cpp") # prepare a cursor object using cursor() method cur = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = """CREATE TABLE PROGRAM1(Value1 INT, Value2 INT, Greater INT)""" try: # Execute the SQL command cur.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 20 09:49:20 2018 @author: karips Solves the "Quadrant Selection" Kattis problem """ x = int(input()) y = int(input()) if x > 0 and y > 0: print(1) elif x < 0 and y > 0: print(2) elif x < 0 and y < 0: print(3) else: print(4)
''' Backprop learning layer Change weights Change Biases (Proportional to how far away loss is) Change activations ''' import math import torch def backwards_pass(weights,biases,loss,layers): ind = loss.index(max([abs(x) for x in loss])) for x in range(len(biases)): biases[x] = update_weights(biases[x],loss[ind]) return (weights,biases) def loss(actual,result): losses = [0,0,0] for x in range(len(actual)): losses[x] = (actual[x]-result[x])**2 return losses def average_change(losses,batch_size): return [losses[x] / batch_size for x in range(len(losses))] ''' Determine how sensitive the loss/cost function is to weights and biases Get most bang for buck in changes when updating weights and in turn changing the loss find the derivative of the cost relative to the weight/bias where dz is the derivative of the activation function a is the activation dC dz da dc ___ = ___ ___ ___ dw dw dz da def update_weights(weights,loss): new = [x+calculate_step(loss) for x in weights] return new def chain_rule(start_layer): val = get_gradient(dx,dy) def get_gradient(dy,dx): pass def calculate_step(loss): return 0.001 * loss ^^ Does NOT YET WORK '''
#!/use/bin/python # -*- coding: utf-8 -*- import re, json f1=file("new.txt", "r") line1=f1.readlines() f1.close() class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value # ่ฏปๅ–ๆœ€ๆ–ฐๆ•ฐๆฎไปทๆ ผ row1={} for l in line1: l=l.strip() #print l x=re.split("\s+", l) row1.setdefault(x[0].upper().replace('\s+', ''), []).append(("%s")% (x[1])) print "insert into tb_app_price_list(`outer_sku`,`sell_price`,`buy_price`)VALUES('%s', '%s' ,'%s');" % (x[0].upper(), x[2], x[2]) #!/use/bin/python # -*- coding: utf-8 -*- import re, json # ่ฏปๅ–ๆ—งไปทๆ ผ f=file("old.txt", "r") line=f.readlines() f.close() # ่ฏปๅ–ๆœ€ๆ–ฐๆ•ฐๆฎไปทๆ ผ f1=file("new.txt", "r") line1=f1.readlines() f1.close() class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value # ่ฏปๅ–ๆœ€ๆ–ฐๆ•ฐๆฎไปทๆ ผ row1={} _arr_row1=[] _arr_row2=[] for l in line1: l=l.strip() x=re.split("\s+", l) if len(x) == 3: row1[x[0].upper()]=x[2] _arr_row1.append(x[0].upper()) # ่Žทๅ–ๆ—งไปทๆ ผ,ๅฆ‚ๆžœๆ–ฐไปทๆ ผๅคงไบŽๆ—งไปทๆ ผไธไฟฎๆ”น๏ผŒๅฆ‚ๆžœๅฐไบŽไฟฎๆ”น row_data={} row=AutoVivification() for l in line: l=l.strip() x=re.split("\s+", l) if len(x) == 3: row_data.setdefault(x[0].upper(), []).append(("%s")% (x[2])) _arr_row2.append(x[0].upper()) try: if int(row1[x[0].upper()]) < int(x[2]): print "update tb_app_price_list set buy_price='%s' where outer_sku='%s';" % (row1[x[0].upper()], x[0].upper()) except Exception as error: # print error pass #import json for r in _arr_row1: if r not in _arr_row2: print "insert into tb_app_price_list(`outer_sku`,`sell_price`,`buy_price`)VALUES('%s', '%s' ,'%s');" % (r,row1[r], row1[r]) #print json.dumps(row_data,indent=4,ensure_ascii=False) #for l in row_data: # if len(row_data[l]) >= 2: # print l,row_data[l]
""" Basic knapsack solvers: dynamic programming and various greedy solvers """ from collections import namedtuple from copy import copy from queue import PriorityQueue from typing import List, Tuple Item = namedtuple("Item", ['index', 'value', 'weight', 'density']) Selection = namedtuple('Selection', ['value', 'room', 'max_value', 'items_taken']) def selection_str(selection): return f'Selection(value={selection.value}, room={selection.room}, max_value={round(selection.max_value, 2)})' Neg_Room = Tuple[int] Queue_Elt = Tuple[Neg_Room, Selection] def dynamic_prog(greedy_value, items_count, capacity, density_sorted_items: List[Item], verbose_tracking): """ Run the dynamic programming algorithm. It is right here! :param greedy_value: :param items_count: :param capacity: :param density_sorted_items: :param verbose_tracking :return: """ # Keep only the current and most recent prev queues. # Each PriorityQueue, i.e., column, stores a Selection at each position ordered by available room: more to less. # verbose_tracking = True queue: PriorityQueue[Queue_Elt] = PriorityQueue() fut_density: float = density_sorted_items[0].density base_selection: Selection = Selection(value=0, room=capacity, max_value=capacity*density_sorted_items[0].density, items_taken=[]) queue.put((-base_selection.room, base_selection)) best_selection: Selection = Selection(value=greedy_value, room=0, max_value=capacity*density_sorted_items[0].density, items_taken=[]) if verbose_tracking: print(f'item: {-1}; queue size: {0}; ' f'fut_density: {round(fut_density, 5)}; best_selection: {selection_str(best_selection)}') for index in range(items_count): item: Item = density_sorted_items[index] prev_queue: PriorityQueue[Queue_Elt] = queue queue: PriorityQueue[Queue_Elt] = PriorityQueue() fut_density: float = 0 if index+1 >= items_count else density_sorted_items[index+1].density col_best_val = 0 col_best_max_val = 0 while not prev_queue.empty(): (_, selection) = prev_queue.get() if selection.value < col_best_val or \ selection.value == col_best_val and selection.max_value <= col_best_max_val: continue else: col_best_val = selection.value col_best_max_val = selection.max_value max_value = selection.value + selection.room * fut_density if max_value > best_selection.value: new_decline_selection = Selection(value=selection.value, room=selection.room, max_value=max_value, items_taken=selection.items_taken) queue.put((-new_decline_selection.room, new_decline_selection)) new_take_value = selection.value + item.value new_take_room = selection.room - item.weight new_take_selection = Selection(value=new_take_value, room=new_take_room, max_value=new_take_value + new_take_room * fut_density, items_taken=selection.items_taken + [index]) if new_take_selection.max_value > best_selection.value and new_take_selection.room >= 0: queue.put((-new_take_selection.room, new_take_selection)) if new_take_selection.value > best_selection.value: best_selection = new_take_selection if verbose_tracking: print(f'item: {index}; queue size: {queue.qsize( )}; ' f'fut_density: {round(fut_density, 5)}; best_selection: {selection_str(best_selection)}') return (best_selection.value, best_selection.items_taken) def dynamic_prog_original(_greedy_value, items_count, capacity, density_sorted_items, _verbose_tracking): """ Run the dynamic programming algorithm. It is right here! :param _greedy_value: :param items_count: :param capacity: :param density_sorted_items: :param _verbose_tracking :return: """ # Keep only the current and most recent prev column. # Each column stores a tuple at each position: (val, list_of_taken_elements) verbose_tracking = True col = [(0, [])]*(capacity+1) cur = col for i in range(items_count): prev = cur cur = copy(col) (index, value, weight, density) = density_sorted_items[i] for w in range(capacity+1): (p_val, p_elmts) = prev[w - weight] if weight <= w else (0, []) cur[w] = max(prev[w], (int(weight <= w) * (value + p_val), p_elmts + [i]), key=lambda valElmts: valElmts[0]) if verbose_tracking and items_count >= 1000: if i > 0 and i % 100 == 0: print(f'{i}/{items_count}', end=' ') if i % 1000 == 0: print() if verbose_tracking and items_count >= 1000: print() return cur[capacity]
class Solution: def reverse(self, x): if x < 0: reversed_int = str(x)[0]+str(x)[:0:-1] back_to_it = int(reversed_int) if back_to_it <= -2**31: return 0 return back_to_it else: reversed_int = str(x)[::-1] back_to_it = int(reversed_int) if back_to_it >= 2**31 - 1: return 0 return back_to_it """ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 """
#Made by Z (zhijingeu@yahoo.com) #This is a very simple dungeon explorer game with mostly text graphics built in Py.Processing #Last Edited 14 Jul 2020 import random #initialising a few variables to be used later rand=0 #TO DO in future updates - create a Player class with "health" attribute instead of using health as a global variable health = 3 #Creates a 8 x 8 array for "drawing" the board. Values stored on 'grid' array are meant to turn cells visible/invisible grid = [ [1]*8 for n in range(8)] w = 70 # sets width of each cell #Creates a 8 x 8 array for storing the "values" in each cell. Values stored on 'cell' array are meant to affect player health cell = [ [""]*8 for n in range(8)] #initialises the variables hearts = [] monsters= [] traps= [] blanks = [] #Creates the values to populate the cell array later for i in range(0,8): #SET NO OF HEARTS hearts.append(" <3 ") for i in range(0,24): #SET NO OF MONSTERS monsters.append(" ~www~") for i in range(0,3): #SET NO OF TRAP traps.append("TRAP ") NoOfBlanks= 62 - len(hearts) - len(monsters) - len(traps) for i in range(0,NoOfBlanks): blanks.append(" ") #Merges the values and randomises the order and stores it into a list cellVals=hearts+monsters+blanks+traps cellVals.append("START") cellVals.append(" EXIT") random.shuffle(cellVals) #This loop helps to assign values from the cellVals list into the cell array counter=0 for i in range(0,8): for j in range(0,8): cell[i][j]=cellVals[counter] if cellVals[counter]=="START": StartX=i StartY=j if cellVals[counter]==" EXIT": ExitX=i ExitY=j print(counter) println(cell[i][j]) counter=counter+1 #Ensures the starting cell is visible when game begins grid[StartY][StartX]= -1 #Draws the board and instructions def setup(): size(800,600) def draw(): x,y = 0,0 # starting position for row in grid: for col in row: if col == 1: #fill(250,250,250) UNHIDE fill(128,128,128) else: fill(250,250,250) rect(x, y, w, w) x = x + w # move right y = y + w # move down x = 0 # rest to left edge fill(128) for i in range(0,8): for j in range(0,8): text(cell[i][j],((i)*w+12),((j)*w+40)) text("LO-FI DUNGEON CRAWLER",600,20) text("----------------------------------------",600,35) text("Distance To Exit",600,70) text("Health",600,140) #rect(590,280,170,280) text("INSTRUCTIONS",600,300) text("Use Dist To Exit",600,330) text("to find your way out",600,360) text("Move up/down/left/right",600,390) text("Beware monsters & traps",600,420) text(" ~www~ = -1 Life",600,450) text(" TRAP = -2 Life",600,480) text("Hearts replenish life",600,510) text(" <3 = +1 Life",600,540) def mousePressed(): global health # not best programming practice I know but I had to reference these 2 variables (one for health level and another rand var for flavour text) which were declared outside this function global rand rand=round(random.random()*10,0) # normalised random variable so it's between 0 to 10 background(255) # tests if surrounding cells have been selected or not (i.e so that tge player can only select cells adjacent to an already "uncovered" cell) # handles the edge case where otherwise it would be out of index if mouseY/w==7 and mouseX/w<>7: if grid[mouseY/w-1][mouseX/w]==-1 or grid[mouseY/w][mouseX/w+1] or grid[mouseY/w][mouseX/w-1]: grid[mouseY/w][mouseX/w] = -1 * grid[mouseY/w][mouseX/w] if mouseY/w<>7 and mouseX/w==7: if grid[mouseY/w-1][mouseX/w]==-1 or grid[mouseY/w+1][mouseX/w] or grid[mouseY/w][mouseX/w-1]: grid[mouseY/w][mouseX/w] = -1 * grid[mouseY/w][mouseX/w] #handles all other regular cases if mouseY/w<>7 and mouseX/w<>7: if grid[mouseY/w+1][mouseX/w] == -1 or grid[mouseY/w][mouseX/w+1] == -1 or grid[mouseY/w][mouseX/w-1] == -1 or grid[mouseY/w-1][mouseX/w] == -1: grid[mouseY/w][mouseX/w] = -1 * grid[mouseY/w][mouseX/w] if grid[mouseY/w][mouseX/w] == -1: distanceToExitY=(ExitY-mouseY/w) distanceToExitX=(ExitX-mouseX/w) distanceToExit=(distanceToExitY**2+distanceToExitX**2)**0.5 text(distanceToExit,700,70) for i in range(0,8): for j in range(0,8): if i <> mouseY/w and j <> mouseX/w: grid[i][j]=1 if cell[mouseX/w][mouseY/w]==" ~www~": if rand<=5: text("OUCH!",600,200) if rand>5: text("x_x",600,200) health=health-1 if cell[mouseX/w][mouseY/w]=="TRAP ": if rand<=5: text("AAARGH!",600,200) if rand>5: text(":'(",600,200) health=health-2 if cell[mouseX/w][mouseY/w]==" <3 ": if rand<=5: text("UmU",600,200) if rand>5: text(":)",600,200) health=health+1 if cell[mouseX/w][mouseY/w]==" ": if rand<=2: text("!_!",600,200) if rand>2 and rand<=4: text("^-^",600,200) if rand>4 and rand<=6: text("*Phew*",600,200) if rand>6 and rand<=8: text("~_~",600,200) if rand>8: text("Doobedoobedoo",600,200) if cell[mouseX/w][mouseY/w]==" EXIT": background(0) text("YOU ESCAPED!!!",600,200) if grid[mouseY/w][mouseX/w] <> -1: text("Error Select Only Cell That Is",600,180) text("Up/Down/Left/Right",600,200) text("To Current Position",600,220) if health <= 0: background(0) text("GAME OVER!",600,200) grid[ExitY][ExitX]=-1 if health > 0: text(health,660,140)
# !/usr/bin/env python # -*- coding: utf-8 -*- def fib(n): a = 1 b = 0 ret = 0 for i in range(1, n + 1): ret = a + b a = b b = ret return ret def menu(): n = int(raw_input("Enter the N: ")) print "fib(%d) is: %d" % (n, fib(n)) if __name__ == '__main__': menu()
# !/usr/bin/python # -*- coding: utf-8 -*- def is_palindrome(n): s = str(n) return s == s[::-1] if __name__ == '__main__': output = filter(is_palindrome, range(1, 1000)) print(list(output))
# !/usr/bin/env python # -*- coding: utf-8 -*- def atoc(string): len_string = len(string) for i in range(len_string - 1, 0, -1): if string[i] == '+' or string[i] == '-': real = float(string[:i]) imag = float(string[i:-1]) break number = complex(real, imag) return number ''' # test print atoc('-1.23e+4-5.67j') print atoc('-1.23e-4+5.67j') print atoc('-1.234-5.67j') '''
# !/usr/bin/env python # -*- coding: utf-8 -*- import random def ran(): list1 = []; list2 = [] for N in range(0, random.randint(1, 100)): list1.append(random.randint(0, 2 ** 31 - 1)) for M in range(0, random.randint(1, 100)): list2.append(random.choice(list1)) return sorted(list2)
# !/usr/bin/python # -*- coding: utf-8 -*- from functools import reduce def str2float(s): def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] n = s.find('.') new_s = s[:n] + s[n+1:] l = map(char2num, new_s) return reduce(lambda x, y: 10 * x + y, l) / 10.0 ** n if __name__ == '__main__': print('str2float(\'123.456\') =', str2float('123.456'))
# !/usr/bin/env python # -*- coding: utf-8 -*- def fb(n): if n == 1: res = 1 elif n == 2: res = 2 else: res = fb(n-1) + fb(n-2) return res def main(): for n in range(1, 40): print "fb(%d) = %d" % (n, fb(n)) if __name__ == '__main__': main()
# !/usr/bin/env python # -*- coding: utf-8 -*- def isprime(num): x = num / 2 while x > 1: if num % x == 0: is_prime = False break x -= 1 else: is_prime = True return is_prime def menu(): num = int(raw_input("Enter the number: ")) if isprime(num): print "It is a prime." else: print "It is NOT a prime." if __name__ == '__main__': menu()
# !/usr/bin/env python # -*- coding: utf-8 -*- def sort_key(dict1): sorted_keys = sorted(dict1) n = 0 for k in sorted_keys: print "key%d: %r, value: %r" % (n, k, dict1[k]) n += 1 def sort_value(dict2): sort_values = sorted(dict1.values()) n = 0 for v in sort_values: for k in dict1.keys(): if v == dict1[k]: print "key%d: %r, value: %r" % (n, k, dict1[k]) n += 1 ''' dict1 = dict(zip(('c', 'b', 'a', 'd'), ('gh', 'ab', 'ef', 'cd'))) sort_key(dict1) print "\n" sort_value(dict1) '''
# !/usr/bin/env python # -*- coding: utf-8 -*- def up_side_down(dict1): dict2 = {} keys1 = dict1.keys() for key in keys1: value = dict1[key] dict2[value] = key return dict2 ''' a = {1: 'a', (2, 3): 'c, d, e', '2': (1,3,4)} b = up_side_down(a) c = up_side_down(b) print b print c '''