text
stringlengths
37
1.41M
def calculate_len(input_str): if type(input_str) == int: print ("Intergers don't have lengths") elif type(input_str) == float: print("Floats don't have lengths") else: return len(input_str) input_str=input("Enter input string: ") print (calculate_len(input_str))
#!/usr/bin/env python3 # @AUTHUR: Kingsley Nnaji <[email protected]> # @LICENCE: MIT # Creation Date: 03.09.2019 def is_Vowel(char): ''' is_Vowel() -> boolean Checks to see is a given character is a vowel and returns a True or False. >>> is_Vowel("b") False >>> is_Vowel("i") True >>> is_Vowel("a") True ''' vowels = "aeiou" to_lower_case = char.lower() result = to_lower_case in vowels return result; if __name__ == "__main__": print("Is the character i a Vowel? : ", is_Vowel("i")) print("Is the character b a Vowel? : ", is_Vowel("b")) print("Is the character a a Vowel? : ", is_Vowel("a"))
#opens csv file input_file = open("songs.csv", "r") FILES = input_file.readlines() #intitiating all attributes required for proper function of class class SongList: def __init__(self, list = []): self.list = list self.file = FILES self.count_list = [] self.learnt_count = [] self.remainder = [1] self.sort_list = [] self.sort_list_2 = [] self.sort_artist_list = [] self.sort_artist_list_2 = [] self.sort_year_list = [] self.sort_year_list_2 = [] self.learnt_list = [] self.not_learnt_list = [] #method gets song based on input def get_song(self, title): for lines in self.list: if title in lines: return (lines) #method adds song into universal list def add_song(self, song_name_add, artist_name_add, year_add): new_status = "*\n" if self.remainder[-1] == 0: self.remainder.remove(self.remainder[-1]) song_to_add = ("{},{},{},{}".format(song_name_add, artist_name_add, year_add, new_status)) self.file.append(song_to_add) self.list.append(song_to_add) # self.export.append(song_to_add) #method gets the number of songs still required to learn def get_num_required(self): songs_left = max(self.count_list) - max(self.learnt_count) self.remainder.append(songs_left) return (songs_left) #method gets the number of songs learnt def get_num_learnt(self): songs_learnt = max(self.learnt_count) return (songs_learnt) #method gets the total number of songs def get_num_total(self): total_songs = max(self.count_list) return (total_songs) #method marks songs in list as learnt def mark_learnt(self): for songs in self.list: component = songs.split(',') status = component[3] if status == "*": new_status = "Learnt" new = component[0] + "," + component[1] + "," + component[2] + "," + new_status self.learnt_list.append(new) print(self.learnt_list) #method mark songs in list as not learnt (not used too much) def mark_not_learnt(self): for songs in self.list: component = songs.split(',') status = component[3] if status == "": new_status = "Not Learnt" new = component[0] + "," + component[1] + "," + component[2] + "," + new_status self.not_learnt_list.append(new) print(self.not_learnt_list) #method loads the song from the csv file and then appending them to the universal list def load_songs(self): input_file = open("songs.csv", "r") file_read = input_file.readlines() count_list = [] learnt_count = 0 song_number_count = 0 for lines in self.file: song_number_count += 1 new_lines = lines.split(",") song_name = new_lines[0] artist_name = new_lines[1] year = new_lines[2] status = new_lines[3].replace("n", "*").replace("y", "").replace("\n", "") final_song_list = ("{},{},{},{}".format(song_name, artist_name, year, status)) count_list.append(song_number_count) if "*" not in status: learnt_count += 1 self.list.append(final_song_list) # self.export.append(final_song_list) self.learnt_count.append(learnt_count) self.count_list.append(max(count_list)) #method which sorts song in a particular order (title, artist, year) def sort(self): for lines in self.list: each_line = lines.split(",") list_sort = each_line[0] + "," + each_line[1] + "," + each_line[2] + "," + each_line[3] self.sort_list.append(list_sort) self.sort_list.sort() for sorted_items in self.sort_list: order = sorted_items.split(",") final_sort = order[0] + "," + order[1] + "," + order[2] + "," + order[3] self.sort_list_2.append(final_sort) return (self.sort_list_2) def sort_artist(self): for lines in self.list: each_line = lines.split(",") artist_sort = each_line[1] + "," + each_line[0] + "," + each_line[2] + "," + each_line[3] self.sort_artist_list.append(artist_sort) self.sort_artist_list.sort() for sorted_items in self.sort_artist_list: order = sorted_items.split(",") final_artist_sort = order[1] + "," + order[0] + "," + order[2] + "," + order[3] self.sort_artist_list_2.append(final_artist_sort) return (self.sort_artist_list_2) def sort_year(self): for lines in self.list: each_line = lines.split(",") year_sort = each_line[2] + "," + each_line[0] + "," + each_line[1] + "," + each_line[3] self.sort_year_list.append(year_sort) self.sort_year_list.sort() for sorted_items in self.sort_year_list: order = sorted_items.split(",") final_year_sort = order[1] + "," + order[2] + "," + order[0] + "," + order[3] self.sort_year_list_2.append(final_year_sort) return (self.sort_year_list_2) #method saves all songs added into the csv file def save_songs(self): input_file = open("songs.csv", "w") for songs in self.list: lines = songs + '\n' input_file.write("{}".format(lines)) #str method returns universal list def __str__(self): return ("{}".format(self.list))
# What will the output of this be? term1 = 5 term2 = 10 sum = term1+term2 print(sum)
### The answer is: # 26 # The way this works is it makes a function that takes to arguments aka the two terms. It then stores the math equation # ValueOne+ValueTwo in a variable called sum. When we return the sum using 'return sum' that makes it so you can store # the functions output in a variable. The value that will be stored in the variable is the sum.
import itertools it = [2,4,8,10,12,14,16,18,19,20,22,24] def even(i): return not i % 2 x = itertools.takewhile(even, it) for e in x: print(e)
""" From a series of points on a time sequence that represents stock profit points, select the times to buy and sell to maximize profits. Since it is a time series, you can only sell after you have bought. """ source = [36,10,3,18,3,7,8,9,6] profit = {} # d[sum of b - a] = (a, b) for i in source: for j in source[source.index(i)+1:]: if j > i: profit[j - i] = (i, j) buy, sell = profit[max(profit.keys())] print("Buy at {b} and sell at {s}.".format(b=buy, s=sell))
name = input("Please enter your name: ") lname = input("Please enter your last name: ") age = int(input("Please enter your age: ")) birth = int(input("Please enter your date of birth(just year): ")) myList = list() myList = [name,lname,age,birth] i=0 for i in myList: print(i) if age<18: print("You can't go out because it's too dangerous") else: print("You can go out to the street.")
#=============================================================================== # Robert Mitchell # # Computer Science - CSUF #=============================================================================== import pygame import time import random # initialize pygame. pygame.init() # environment colors blackColor = (0,0,0) whiteColor = (255,255,255) # seed random for pipe position generation. random.seed(time.time()) # define and create the game surface. world_height = 350 # height of background.png world_width = 640 # width of background.png koopas_world = pygame.display.set_mode((world_width, world_height)) # set title of window. pygame.display.set_caption('Koopa\'s Hunt for Flappy Bird') # define pipe obstacle. Consists of bottom and top pipe class Pipe: # - 284 pixels of vertical height between the sky and the ground. # - 284/2 = 142 pixels for top and bottom pipe. # - Each pipe should be separated by 127.5 pixels as calculated by the actual ratio between # pipe width and separation form the actual game. Lets use choose a value of 125 pixels for separation. # - Each pipe points to a different image,we use five different pipe heights. # - A random number pointsf the the pipe object to the pipe image. break_position = None position = None width = None top_end_y = None bottom_end_y = None sprite = None def randomize(self): # randomly set the height position of the pipe. There are 6 height positions a pipe may be located. self.break_position = random.randint(0,5) # set proper pipe image and passage area based on position. Passages are hard coded to correspond to the images. # if the koopa passes between pipe.top_end_y and pipe.bottom_end_y while # being between pipe.position and pipe.position+pipe.width, koopa is free. if self.break_position == 0: self.sprite = pygame.image.load('sprites/pipe_0.png') self.top_end_y = 40 self.bottom_end_y = self.top_end_y + 80 elif self.break_position == 1: self.sprite = pygame.image.load('sprites/pipe_1.png') self.top_end_y = 50 self.bottom_end_y = self.top_end_y + 80 elif self.break_position == 2: self.sprite = pygame.image.load('sprites/pipe_2.png') self.top_end_y = 80 self.bottom_end_y = self.top_end_y + 80 elif self.break_position == 3: self.sprite = pygame.image.load('sprites/pipe_3.png') self.top_end_y = 110 self.bottom_end_y = self.top_end_y + 80 elif self.break_position == 4: self.sprite = pygame.image.load('sprites/pipe_4.png') self.top_end_y = 140 self.bottom_end_y = self.top_end_y + 80 elif self.break_position == 5: self.sprite = pygame.image.load('sprites/pipe_5.png') self.top_end_y = 170 self.bottom_end_y = self.top_end_y + 80 def __init__(self, position): # specify x,y coordinates of pipe. Pipe is always drawn from the top y=0, but the x coordinate varies as it scrolls or is initialized. self.position = (position, 0) # all pipes are the same with, 60px. self.width = 60 # set proper pipe image based on position. self.randomize() # level 1. class PipeLevel: position = None length = None pipes = None finish_location = None mario_position = None # update this with scrolling mario_sprite = None mario_walking = None mario_standing = None mario_peace = None flappy_bird_position = None # update this with scrolling flappy_bird_sprite = None level_complete = None # initialize all obstacles. def __init__(self): self.position = 0 self.length = 640*6 # level is 7040px long. self.finish_location = int((640*1.2) + (10*150)) # the finish is 1/5 a level's length past the last pipe. self.pipes = [] self.mario_position = 2350 self.mario_walking = pygame.image.load('sprites/mario_walking.png') self.mario_standing = pygame.image.load('sprites/mario_standing.png') self.mario_peace = pygame.image.load('sprites/mario_peace.png') self.mario_sprite = self.mario_standing self.flappy_bird_sprite = pygame.image.load('sprites/flappy_bird_in_cage.png') self.flappy_bird_position = self.mario_position + 50 # 50 pixels behind mario. self.level_complete = False # how many pipes? for x in range(0, 10): # Creat pipes whose position starts at the edge of the screen, and are separated by 90 pixels each. self.pipes.append(Pipe(640 + x*150)) # level must be at least 5040px long. self.finish_location must lie beyond 5040px. print 'level initialized' # if the level is complete, flip boolean. def is_compelete(self): return self.level_complete # given the dimensions of a sprite, and its position, determine if it has collided with a pipe. def detect_collision(self, sprite_width, sprite_height, sprite_position): # uncomment this vvvvv to pass through all the pipes. #return False # get sprite position (sprite_x, sprite_y) = sprite_position # compare the position of the pipes to the object's position. Return true or false if there is a collision. for pipe in self.pipes: # get pipe position (pipe_x, pipe_y) = pipe.position # if sprite is between a pipe's x coordinates, make sure that it is also between the gap in the pipe, its y coordinates. if (pipe_x <= (sprite_x+sprite_width)) and ((pipe_x+pipe.width) >= sprite_x): if (pipe.top_end_y <= sprite_y) and (pipe.bottom_end_y >= (sprite_y+sprite_height-10)): # -10 to make it a bit easier. # Return true because the sprite is betwen the gap in the pipe. return False else: # Return true because the sprite is not between the gap, there has been a collision. return True # this is here for testing without pipes. return False # restart the level from the beginning. def restart(self): self.position = 0 self.length = 640*6 # level is 7040px long. self.finish_location = int((640*1.2) + (10*150)) # the finish is 1/5 a level's length past the last pipe. self.pipes = [] self.mario_position = 2350 self.mario_walking = pygame.image.load('sprites/mario_walking.png') self.mario_standing = pygame.image.load('sprites/mario_standing.png') self.mario_peace = pygame.image.load('sprites/mario_peace.png') self.mario_sprite = self.mario_standing self.flappy_bird_sprite = pygame.image.load('sprites/flappy_bird_in_cage.png') self.flappy_bird_position = self.mario_position + 50 # 50 pixels behind mario. self.level_complete = False # how many pipes? for x in range(0, 10): # Creat pipes whose position starts at the edge of the screen, and are separated by 90 pixels each. self.pipes.append(Pipe(640 + x*150)) # level must be at least 5040px long. self.finish_location must lie beyond 5040px. print 'level initialized' # draw all pipes without moving them. def draw(self): # any pipe whose x coordinate is on the screen will be drawn. for pipe in self.pipes: # get pipe position. (x,y) = pipe.position # draw all the pipes that are in the screen space. if (x <= 640) and (x >= 0): koopas_world.blit(pipe.sprite, pipe.position) # scroll obstacles right to left based on their position. def scroll(self): # draw the pipes if we haven't passed the finish location. #if self.position <= self.finish_location: # update mario and flappy bird's positions. if self.mario_position > (int((world_width/3)+60)): # update the level position as long as mario hasn't moved upto a point. self.position += 1 # move mario to the left only upto a point. self.mario_position -= 1 # move flappy bird to the left only upto a point. self.flappy_bird_position -= 1 # any pipe whose x coordinate is on the screen, should be drawn and updated, else just update the coordinates. for pipe in self.pipes: # get pipe position. (x,y) = pipe.position # draw all the pipes that are on the screen and update their position. if (x <= 640) and (x >= 0): koopas_world.blit(pipe.sprite, pipe.position) pipe.position = (x-1,y) else: pipe.position = (x-1,y) #else: #draw mario when he is on screen. if self.mario_position < 640: # if mario has stopped walking if self.mario_position == (int((world_width/3)+60)): self.mario_sprite = self.mario_peace koopas_world.blit(self.mario_sprite, (self.mario_position, world_height-(66+45))) self.level_complete = True else: # if mario is walking, animate his walking. if (int((640%(self.mario_position/10))/10) % 2 == 0): # <----- Whew* wipes sweat off forehead. self.mario_sprite = self.mario_walking koopas_world.blit(self.mario_sprite, (self.mario_position, world_height-(66+45))) else: self.mario_sprite = self.mario_standing koopas_world.blit(self.mario_sprite, (self.mario_position, world_height-(66+45))) # draw caged flappy bird when on screen. if self.flappy_bird_position < 640: koopas_world.blit(self.flappy_bird_sprite, (self.flappy_bird_position, world_height-(66+106))) # protagonist class Koopa_paratroopa: lives = None sprite = None height = None width = None resting_koopa = None flapping_koopa = None dead_koopa = None position = None speed = None def jump(self): (x,y) = self.position self.speed = -8 self.position = (x, y+self.speed) def reset(self): self.position = (world_width/3, 0) self.sprite = self.resting_koopa self.speed = 0 def __init__(self): self.lives = 3 self.resting_koopa = pygame.image.load('sprites/koopa_paratroopa.png') self.flapping_koopa = pygame.image.load('sprites/koopa_paratroopa_flapping.png') self.dead_koopa = pygame.image.load('sprites/koopa_paratroopa_dead.png') self.sprite = self.resting_koopa # the sprite images are 30x45px self.height = 45 self.width = 30 self.position = (world_width/3, 0) self.speed = 0 # exit game. call this from anywhere to exit the game. def exit_game(): # uninitialize pygame. pygame.quit() # quit python. quit() # create clock to control frames per second. FRAMES_PER_SECOND = 60 clock = pygame.time.Clock() # initialize game level. level = PipeLevel() # initialize koopa. koopa = Koopa_paratroopa() # display intro screen and backstory. user_ready = False while not user_ready: # set background as black koopas_world.fill((0,0,0)) # draw intro sprite. intro_sprite = pygame.image.load('sprites/intro_screen.png') koopas_world.blit(intro_sprite, (0,0)) #update pygame.display.update() # get user input to continue for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: user_ready = True if event.type == pygame.QUIT: exit_game() # set up game background. background_image = pygame.image.load('sprites/background.png') # koopas_world.blit(background_image, (100,100)) # main game loop. while True: # get user input for gameplay. for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: koopa.jump() if event.type == pygame.QUIT: exit_game() # render background image first, so it is behind everything. koopas_world.blit(background_image, (0,0)) # if koopa has not collided with anything, keep game play going. if not level.detect_collision(koopa.width, koopa.height, koopa.position): # move enemies/obstacles right to left. when to scroll the level? Hmmmmmmmm... level.scroll() # enact gravity upon koopa. (x,y) = koopa.position if y >= world_height-(66+45): # if koopa has hit the the ground, stop falling. koopa.speed = 0 koopa.position = (x, world_height-(66+45)) koopas_world.blit(koopa.sprite, koopa.position) else: # else fall at an increasing rate. koopa.position = (x, y+int((koopa.speed/4))) # for 60 fps and level speed, 4 seems good. Very CPU intensive though. Consider lowering frame rate and moving level faster than 1 pixel per frame. koopa.speed += 1 # if koopa is traveling upwards, that is if the koopa has a negative speed, spread wings, else just let koopa rest. if koopa.speed <= 0: koopa.sprite = koopa.flapping_koopa else: koopa.sprite = koopa.resting_koopa # draw koopa koopas_world.blit(koopa.sprite, koopa.position) # if we beat the level, show the winning koopa. if level.is_compelete(): # update koopa to dead koopa. He dies of fright. koopa.sprite = koopa.dead_koopa koopas_world.blit(koopa.sprite, koopa.position) # show game over. game_over_sprite = pygame.image.load('sprites/game_over.png') koopas_world.blit(game_over_sprite, (int((world_width/2)-150), int((world_height/2))-150) ) # update the new blits. pygame.display.update() # just sit here until the user quits. while True: # quit upon user pressing enter for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: exit_game() # render lives. koopa_life_text_sprite = pygame.image.load('sprites/koopa_life_text.png') koopas_world.blit(koopa_life_text_sprite, (0,0)) koopa_life_sprite = pygame.image.load('sprites/koopa_life.png') for x in range(0,koopa.lives): koopas_world.blit(koopa_life_sprite, (100+(50*x),0)) # update display. pygame.display.flip() # clock clock.tick(FRAMES_PER_SECOND) else: # koopa has died, remove 1 life. koopa.lives -= 1 # if the koopa still has lives left, show dead koopa and restart the level when user presses enter. if koopa.lives > 0: koopa_is_alive = False while not koopa_is_alive: # draw background image koopas_world.blit(background_image, (0,0)) # draw the level as it was when koopa died. i.e. do not scroll the level. level.draw() # koopa is not alive so make koopa a dead koopa. koopa.sprite = koopa.dead_koopa # draw dead koopa koopas_world.blit(koopa.sprite, koopa.position) # update display pygame.display.flip() # clock clock.tick(FRAMES_PER_SECOND) # keep showing dead koopa until user presses enter or clicks quit. for event in pygame.event.get(): # quit the game gracefully. if event.type == pygame.QUIT: exit_game() # reset koopa and restart the level. if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: # reset koopa koopa.reset() # restart level level.restart() # exit death loop to begin game play again. koopa_is_alive = True else: # else show game over. # make backgorund black. koopas_world.fill((0,0,0)) # fill with black. # set sprite image. game_over_sprite = pygame.image.load('sprites/game_over.png') # do not blit in the center of the screen, but move over 150 to accomodate the size of the image. Just hardcode it for now. koopas_world.blit(game_over_sprite, (int((world_width/2)-150), int((world_height/2))-150) ) pygame.display.update() # just wait until the user presses enter. while True: # quit upon user pressing enter for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: exit_game() #===============================================================================
def LaticePath(n): L = [1] * n for i in range(n): for j in range(i): L[j] = L[j] + L[j-1] L[i] = 2 * L[i - 1] return L[n -1] print LaticePath(1) print LaticePath(2) print LaticePath(3) print LaticePath(20)
age = 10 #One way statement if age == 10: print("ten") name = "Melanie" if name == "Melanie": print("the same") letter = "C" #Alphabetical if letter < "D": print("Less than D") if letter > "B": print("Greater than B") age = eval(input("Enter your age: ")) #Else statment if age >= 18: print("You are old enough to vote") else: print ("You are not old enough to vote") year = eval(input("Enter year: ")) #Elif Else IF if year == 1: print ("Freshman") elif year == 2: print ("Sophomore") elif year == 3: print ("Junior") elif year == 4: print ("Senior") else: print("Not a valid year") VotingAge = eval(input("How old are you? ")) #Multiple conditions registered = input("Are you registered? (y/n) ") if VotingAge >= 18: if registered == "y": print("You are ready to vote!") else: print("You are not ready to vote.") ageVote = eval(input("How old are you? ")) #compond conditions voteRegistered = input("Are you registered? (y/n) ") if ageVote >= 18 and voteRegistered == "y": print("You are ready to vote!") else: print("You are not ready to vote!") rate = eval(input("what is your hourly wage? ")) hours = eval(input("How many hours did you work? ")) if hours < 40: pay = hours * rate else: pay = hours * rate overtimeHours = hours - 40 overtimePay = overtimeHours * (rate * 0.5) pay = pay + overtimePay print("your weekly pay is:", pay) #comma windspeed = eval(input("Enter wind speed in MPH: ")) #Activity Lesson 3 if windspeed < 74: print("Not a hurricane") elif windspeed <= 95: print("Category 1 Hurricane.") elif windspeed <= 110: print("Category 2 Hurricane.") elif windspeed <= 130: print("Category 3 Hurricane.") elif windspeed <= 155: print("Category 4 Hurricane.") else: print("Category 5 Hurricane.")
cidade = str(input("A cidade começa com Santo: ")).strip() print("SANTO" in cidade[:5].upper())
# Given two sentences A and B return a list of all uncommon words. # A word is uncommon if it appears EXACTLY ONCE in one of the sentences, # and DOES NOT appear in the other sentence. # Each sentence is a string of space separated words. # Each word consists only of lowercase letters. # Order in the final array is not important. # Example: # Input: A = "orange orange", B = "apple" # Output: ["apple"] A = 'you used to love basketball but then you quit ' B = 'we used to enjoy basketball but then we quit' def solution(A, B): import collections a_split, b_split = A.split(), B.split() uncommon_words = set(a_split)^set(b_split) #or set(a_split).symmetric_difference(b_split) a_counter,b_counter = collections.Counter(a_split), collections.Counter(b_split) return [x for x in uncommon_words if x in a_counter and a_counter[x] == 1 or b_counter[x] == 1] solution(A, B)
import unittest from palindrome import palindrome class TestPalindrome(unittest.TestCase): def test_racecar(self): self.assertEqual(palindrome('racecar'), True) def test_noon(self): self.assertEqual(palindrome('noon'), True) def test_civic(self): self.assertEqual(palindrome('civic'), True) def test_nice(self): self.assertEqual(palindrome('nice'), False) def test_434(self): self.assertEqual(palindrome('434'), True) def test_123(self): self.assertEqual(palindrome('123'), False) def test_bomb(self): self.assertEqual(palindrome('bomb'), False) def test_challenge_1(self): self.assertEqual(palindrome('Sore was I ere I saw Eros'), True) # def test_challenge_2(self): # self.assertEqual(palindrome('racecar'), Tru # def test_challenge_3(self): # self.assertEqual(palindrome('racecar'), Tru # print(palindrome('racecar') == True) # print(palindrome('Noon') == True) # print(palindrome('ciVic') == True) # print(palindrome('nice') == False) # print(palindrome(434) == True) # print(palindrome(123) == False) # print(palindrome('bomb') == False) # print("The following should be True if you're trying to do the extra portion of this challenge") # print(palindrome('Sore was I ere I saw Eros.') == True) # print(palindrome('A man, a plan, a canal -- Panama') == True)
# -*- coding: utf-8 -*- """ @author: NightRoadIx """ # Manejo de grandes cantidades de datos import pandas as pd import numpy as np import matplotlib.pyplot as mp # Cargar el enlace a descargar enlace = "https://covid.ourworldindata.org/data/owid-covid-data.csv" # Mi recomendación es bajar el archivo y colocar después la dirección local # donde se encuentra el archivo # Obtener los datos directamente con la librería pandas df = pd.read_csv(enlace) #%% # Obtener la lista de los países disponiblees listaPaises = df["location"].unique().astype(str).tolist() # Pedir al usuario que escoja algún país while True: # Ingresar datos pais = input("País a analizar: ") # comparar si la cadena se encuentra en la lista if pais in listaPaises: # Crear la cadena de análisis # fillna(0) funciona para rellenar los valores que están como NA # (esto es que no existen o tienen algún valor) con 0 subdf = df[df['location'] == pais].fillna(0) break print("<El país no fue hallado>") # Una vez hallado el país, se procede a analizar # Por ejemplo, ver el total de casos # Para un mejor análisis, se convierte en un arreglo numpy y = np.array(subdf['total_cases'].tolist()) #%% # Graficar entonces estos valores mp.plot(y, 'r-') mp.xlabel('Datos') mp.ylabel('Total Casos') mp.grid() mp.show() #%% # Obtener un "pedazo de los datos" mp.plot(y[400:500], 'r-') mp.xlabel('Datos') mp.ylabel('Total Casos') mp.grid() mp.show()
import time def ran(): if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: print(asm2 + ' winner') time.sleep(5) quit() else: print(asm1+' turn') #hina ana ba carete al player we al instraction bta3t player 1 while True: #while (b) #this while to make the user choose 1 or 2 if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: break print('how many number will you take 1 or 2 ?') while True: #this while if the user was bad and think to put letter or word when i ask about number a=str(input()) if a=='1' or a=='2': break print('Please Enter 1 or 2 only') #here when the user enter 1 if a=='1': print(x) print('choose the number from the list :') while True : #we will called this while (R) #this while to make the user choose from the list not from his mind i=int(input()) if i in x : break print("please choose the number from the list ") while x[i]=='.': #this while to not repeat the same num while playing #we called this while (a) print('please choose another number this number was taken') i=int(input()) if x[i]!='.': x[i]='.' print(x) break #the end of wihle (a) if x[i]=='.': break #the end of while (b) x[i]='.' print(x) san() break #here when the user choose 2 elif a=='2': print(x) print('choose The First number : ') while True : #This is while (R) i=int(input()) if i in x: break print("Please Enter another Number (your choice was taken) ; ") while True: h=int(input("Enter the secound number : ")) if h in x: break print("Please Enter another Number (your choice was taken) :") while True: while (x[i]-x[h])==1 or (x[i]-x[h])==-1 or (x[h]-x[i])==1 or (x[h]-x[i])==-1: x[i]='.' x[h]='.' print(x) break if x[i]=='.': san() break print('this 2 number isn\'t adjcent number please enter new 2 number ') print(x) while True: #This is while (R) if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: break print('Do you want to change the number which you choose 1-yes 2-no') while True: i=str(input()) if i=='1' or i=='2': break print("please choose 1 or 2 only") if i=='1': print(x) print('choose the number from the list :') while True : #we will called this while (R) #this while to make the user choose from the list not from his mind i=int(input()) if i in x : break print("please choose the number from the list ") while x[i]=='.': #this while to not repeat the same num while playing #we called this while (a) print('please choose another number this number was taken') i=int(input()) if x[i]!='.': x[i]='.' print(x) break #the end of wihle (a) if x[i]=='.': break #the end of while (b) x[i]='.' print(x) san() if i=='2': while True: i=int(input("Enter the first number : ")) if i in x: break while True: h=int(input("Enter the secound number : ")) if h in x: break while (x[i]-x[h])==1 or (x[i]-x[h])==-1 or (x[h]-x[i])==1 or (x[h]-x[i])==-1: x[i]='.' x[h]='.' print(x) break if x[i]=='.': break san() break def san(): if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: #hina nafs al instraction bta3t player 2 print(asm1 +' winner') time.sleep(5) quit() else: print(asm2+' turn') while True: #while (b) print('how many number will you take 1 or 2 ?') while True: #this while if the user was bad and think to put letter or word when i ask about number a=str(input()) if a=='1' or a=='2': break print('Please Enter 1 or 2 only') if a=='1': print(x) print('choose the number from the list :') while True : #while(R) i=int(input()) if i in x : break print("please choose the number from the list ") while x[i]=='.': #while (a) print('please choose another number this number was taken') i=int(input()) if x[i]!='.': x[i]='.' print(x) break #the end of wihle (a) if x[i]=='.': break #the end of while (b) x[i]='.' print(x) ran() break #here when the user choose 2 elif a=='2': print(x) print('choose The First number : ') while True : #This is while (R) i=int(input()) if i in x: break print("Please Enter another Number (your choice was taken) ; ") while True: h=int(input("Enter the secound number : ")) if h in x: break print("Please Enter another Number (your choice was taken) :") while True: while (x[i]-x[h])==1 or (x[i]-x[h])==-1 or (x[h]-x[i])==1 or (x[h]-x[i])==-1: x[i]='.' x[h]='.' print(x) break if x[i]=='.': ran() break print('this 2 number isn\'t adjcent number please enter new 2 number ') print(x) while True: #This is while (R) if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: break print('Do you want to change the number which you choose 1-yes 2-no') while True: i=str(input()) if i=='1' or i=='2': break print("please choose 1 or 2 only") if i=='1': print(x) print('choose the number from the list :') while True : #we will called this while (R) #this while to make the user choose from the list not from his mind i=int(input()) if i in x : break print("please choose the number from the list ") while x[i]=='.': #this while to not repeat the same num while playing #we called this while (a) print('please choose another number this number was taken') i=int(input()) if x[i]!='.': x[i]='.' print(x) break #the end of wihle (a) if x[i]=='.': break #the end of while (b) x[i]='.' print(x) san() if i=='2': while True: i=int(input("Enter the first number : ")) if i in x: break while True: h=int(input("Enter the secound number : ")) if h in x: break while (x[i]-x[h])==1 or (x[i]-x[h])==-1 or (x[h]-x[i])==1 or (x[h]-x[i])==-1: x[i]='.' x[h]='.' print(x) break if x[i]=='.': break ran() break x=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] #the program will start from here print(x,'\n') print("this game is very easy every player take one or two num but the num which taken will be like this '.' and who takes the final one or two num will win \n") asm1=str(input('Enter the player 1 name : ')) asm2=str(input('Enter the player 2 name : ')) while x!=['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: #this loop must be true until all num finsh print('who will start 1- '+asm1,' or 2- '+asm2) while True: player=str(input('choose (1,2) ')) if player=='1' or player=='2' : break print('please Enter only 1 or 2 ') if player=='1': ran() elif player=='2': san() #enddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
import random # import platform # print(platform.architecture()) print('---石头剪刀布游戏开始---') print('请按下面的提示出拳:') print('石头【1】剪刀【2】布【3】结束【4】') while True: x = int(input('请输入你的选项:')) if x == '4': break map = {1:'石头', 2:'剪刀', 3:'布'} mapp = {1:2, 2:3, 3:1} y = random.randint(1, 3) print('您的出拳为:'+map.get(x)+', 电脑出拳为:'+ map.get(y), end=' ') if mapp.get(x) == y: print('您赢了!') elif x == y: print('平局') else: print('您输了。')
''' Introduction to Neural Engineering (Fall, 2020) Implementation of Population Coding of Smell Sensing with Artificial Neural Network (ANN) ''' ''' PLEASE FILL UP BELOW (PERSONAL INFO) ''' # Full Name (last name first) : '''Park seung joo''' # Student Number : '''2018250029''' # import modules (can't be added) from scipy import io import numpy as np import math import matplotlib.pyplot as plt ''' Function definition (Any function can be added) ''' # fuction to return sigmoid value(node function) def sigmoid(X): a = 1/(1+np.exp(-X)) return a # function to compute feedforward calculation def feedforward(X, W1, W2, W3): '''reform this function''' Z1 = np.matmul(W1, X) a1 = sigmoid(Z1) Z2 = np.matmul(W2, a1) a2 = sigmoid(Z2) Z3= np.matmul(W3,a2) a3= sigmoid(Z3) return Z1, a1, Z2, a2, Z3, a3 # function to compute costs def getCost(label, output): one_hot = np.zeros((num_class, 1)) one_hot[label-1] = 1 loss = np.sum((one_hot-output)**2) return loss # function to compute gradients using back-propagation def getGradient(data, w2, w3, a1, a2, a3, label): '''reform this function''' one_hot = np.zeros((num_class, 1)) one_hot[label-1] = 1 dw3 = -2 * np.matmul(((one_hot - a3) * a3 * (1 - a3)), a2.T) dw2 = -2 * np.matmul(a2 * (1 - a2) * np.matmul(w3.T, ((one_hot - a3) * a3 * (1 - a3))), a1.T) k1= np.matmul(np.transpose((one_hot-a3) * a3 * (1-a3)), w3) * np.transpose(a2 * (1-a2)) dw1 = -2 * np.matmul(a1 * (1 - a1) * np.transpose(np.matmul(k1, w2)), data.T) return dw1, dw2, dw3 # function to compute accuracy of network def get_accuracy(correct, data_len): accuracy = correct / data_len * 100 return accuracy def predict(output): predict_label = np.argmax(output) return predict_label '''Main''' # Load Data file = io.loadmat('OlfactoryData.mat') X_data = file['olf'][0, 0]['Signals'] idx = list(np.arange(42277)) idx = idx[:40000] np.random.shuffle(idx) X_data = X_data[idx, :] X_data = (X_data-np.mean(X_data))/np.std(X_data) # pre-processing, normalization y_data = file['olf'][0, 0]['SmellTypes'] y_data = y_data[idx] print("Total X_dataset shape: ", X_data.shape) # 40000, 400 print("Total y_dataset shape: ", y_data.shape, '\n') # 40000, 1 # Split train and validation set X_train = X_data[:int(X_data.shape[0]*0.9*0.8), :] y_train = y_data[:int(X_data.shape[0]*0.9*0.8)] print("Train X_dataset shape: ", X_train.shape) # 28800, 400 print("Train y_dataset shape: ", y_train.shape) # 28800, 1 X_val = X_data[int(X_data.shape[0]*0.9*0.8):int(X_data.shape[0]*0.9), :] y_val = y_data[int(X_data.shape[0]*0.9*0.8):int(X_data.shape[0]*0.9)] print("Validation X_dataset shape: ", X_val.shape) # 7200, 400 print("Validation y_dataset shape: ", y_val.shape, '\n') # 7200, 1 X_test = X_data[int(X_data.shape[0]*0.9):, :] y_test = y_data[int(X_data.shape[0]*0.9):] print("Test X_dataset shape: ", X_test.shape) # 4000, 400 print("Test y_dataset shape: ", y_test.shape, '\n') # 4000, 1 # Construct network # 1) parameters initialization # 1-1) variable initialization num_input_features = X_data.shape[1] # 400 num_class = len(np.unique(y_data)) # 7 train_data_len = X_train.shape[0] val_data_len = X_val.shape[0] test_data_len = X_test.shape[0] losses_tr = [] losses_val = [] accs_tr = [] accs_val = [] # 1-2) hyper-parameters setting learning_rate = 0.01 epoch = 50 num_hidden1_node = 256 num_hidden2_node= 64 # 1-3) weights initialization weights_in2hid1 = np.random.normal(0, 0.01, (num_hidden1_node, num_input_features)) weights_hid12hid2 = np.random.normal(0, 0.01, (num_hidden2_node, num_hidden1_node)) weights_hid22out = np.random.normal(0, 0.01, (num_class, num_hidden2_node)) '''Fill in this line''' # 2) Learning for it in range(epoch): print('Epoch: ', it) correct_tr = 0 loss_tr = 0 correct_val = 0 loss_val = 0 # Training for i in range(train_data_len): # Stochastic gradient descent (SGD) _, a1, _, a2, _, a3 = feedforward(X_train[i, :].reshape(-1, 1), weights_in2hid1, weights_hid12hid2, weights_hid22out) # Reform this line loss = getCost(y_train[i, 0], a3) # Reform this line dw1, dw2, dw3 = getGradient(X_train[i, :].reshape(-1, 1), weights_hid12hid2 ,weights_hid22out, a1, a2, a3, y_data[i, 0]) # Reform this line # Weights update weights_in2hid1 -= learning_rate * dw1 weights_hid12hid2-= learning_rate * dw2 weights_hid22out -= learning_rate * dw3 '''Fill in this line''' # Get training accuracy for i in range(train_data_len): _, a1, _, a2, _, a3 = feedforward(X_train[i, :].reshape(-1, 1), weights_in2hid1, weights_hid12hid2, weights_hid22out) # Reform this line loss = getCost(y_train[i, 0], a3) # Reform this line prediction = predict(a3) # Reform this line loss_tr += loss if y_train[i, 0] - 1 == prediction: correct_tr += 1 accuracy_tr = get_accuracy(correct_tr, train_data_len) loss_tr = loss_tr / train_data_len print("Train_loss: %.04f" % loss_tr) print("Train_acc: %.02f %% ( %d / %d ) " % (accuracy_tr, correct_tr, train_data_len )) # Validation for i in range(val_data_len): _, a1, _, a2, _, a3 = feedforward(X_val[i, :].reshape(-1, 1), weights_in2hid1, weights_hid12hid2, weights_hid22out) # Reform this line loss = getCost(y_val[i, 0], a3) # Reform this line prediction = predict(a3) # Reform this line loss_val += loss if y_val[i, 0] - 1 == prediction: correct_val += 1 # Get validation accuracy accuracy_val = get_accuracy(correct_val, val_data_len) loss_val = loss_val / val_data_len print("Validation_loss: %.04f" % loss_val) print("Validation_acc: %.02f %% ( %d / %d ) " % (accuracy_val, correct_val, val_data_len)) losses_tr.append(loss_tr) losses_val.append(loss_val) accs_tr.append(accuracy_tr) accs_val.append(accuracy_val) # 3) Show results # 3-1) Get test accuracy (final accuracy) loss_test = 0 correct_test = 0 for i in range(test_data_len): _, a1, _, a2, _, a3 = feedforward(X_test[i, :].reshape(-1, 1), weights_in2hid1, weights_hid12hid2, weights_hid22out) # Reform this line loss = getCost(y_test[i, 0], a3) # Reform this line prediction = predict(a3) # Reform this line loss_test += loss if y_test[i, 0] - 1 == prediction: correct_test += 1 accuracy_test = get_accuracy(correct_test, test_data_len) loss_test = loss_test / test_data_len print("\nTest accuracy: %.02f %% ( %d / %d ) " % (accuracy_test, correct_test, test_data_len)) # 3-2) Plot loss and accuracy curve plt.figure() plt.plot(losses_tr, 'y', label='Train_loss') plt.plot(losses_val, 'r', label='Validation_loss') plt.xlabel('epoch') plt.ylabel('loss') plt.legend(['Train_loss', 'Validation_loss']) plt.show() plt.figure() plt.plot(accs_tr, 'y', label='Train_accuracy') plt.plot(accs_val, 'r', label='Validation_accuracy') plt.xlabel('epoch') plt.ylabel('accuracy') plt.legend(['Train_acc', 'Validation_acc']) plt.show()
""" Given a string, sort it in decreasing order based on the frequency of characters Time complexity = O(n) space Complexity = O(n) """ __author__ = "Ravi Kiran Chadalawada" __email__ = "[email protected]" __credits__ = ["Leetcode.com"] __status__ = "Prototype" from collections import defaultdict def sort_string(s): alphabet_count = defaultdict(int) count_to_alphabet = {} result = '' for i in range(len(s)+1): count_to_alphabet[i] = [] for char in s: alphabet_count[char] += 1 for key,value in alphabet_count.items(): count_to_alphabet[value].append(key) for i in range(len(s),0,-1): temp_list = count_to_alphabet[i] for char in temp_list: result += (char * i) return result if __name__=='__main__': print(sort_string('raviaar'))
import numpy as np def var(X,Y,V,num0,scale): #-----------------------Matriz Triangular de Distancias---------------------------# D = np.array([[0]*len(Y)]*(len(X)),float) # D = matriz de distancias for j in range (len(Y)): for i in range (len(X)): D[j,i] = scale*(np.sqrt((Y[j] - Y[i])**2 + (X[j] - X[i])**2)) print np.max(D),' max D' DU = np.triu(D) # funcao matriz retangular/Matriz de distancias sem repeticao print np.max(DU),' max DU' #----------------------------------Variograma-------------------------------------# #------------------------------------------------------------------------------- num = num0+1 rang = np.linspace(np.min(DU),np.max(DU),num) # escolhe o range de valores print 'range determinado pelos valores maximos e minimos:',len(rang),'elementos' print print rang range1 = [] # range da base range2 = [] # range da ponta #------------------------------------------------------------------------------- for i in range(num-1): range1.append(rang[i]) range2.append(rang[i+1]) #------------------------------------------------------------------------------- SH = np.shape(D) print SH,'forma da matriz de distancias' d1 = [] # Codigo d2 = [] # Range superior d3 = [] # Range Inferior d4 = [] # Valor da distancia d5 = [] # F(V[j],V[i]) for k in range (num-1): for j in range (SH[0]): for i in range (SH[1]): if DU[j,i] > range1[k] and DU[j,i] <= range2[k]: # maior ao inves de maior e igual, retira os zeros d1.append(k) d2.append(range1[k]) d3.append(range2[k]) d4.append(DU[j,i]) d5.append((V[j] - V[i])**2) cod1 = np.linspace(min(d1),max(d1),max(d1)+1) # ou max(d1)+1, depende do valor de 'num' print print 'as ',num0,' categorias escolhidas em codigo ' print print cod1 print print '!!!ATENCAO!!!: estes numeros devem ser inteiros. Exemplo: (0. 1. 2. ... n.)' print 'se nao forem inteiros, altere o valor de num0' vall = [0.0]*len(cod1) #------------------------------------------------------------------# SSD = [1]*(len(d1)) ES = np.array([[0.0]*len(d1)]*len(cod1),float) EO = np.array([[0.0]*len(d1)]*len(cod1),float) for j in range (len(cod1)): for i in range (len(d1)): if d1[i] == j: ES[j,i] = d5[i] EO[j,i] = SSD[i] #------------------------------------------------------------------# SS = ES.sum(axis=1) # soma dos valores das propriedades SSO = EO.sum(axis=1) # numero de ocorrencias da pripriedade no intervalo VI = [] for i in range (len(SS)): VI.append((1/(2.0000*SSO[i]))*SS[i]) rang_mid = [] # range de valor medio for i in range(len(range1)): rang_mid.append( (range1[i]+range2[i])/2.0 ) print print SS print SSO result = np.array([[0.0]*2]*len(VI),float) for i in range (len(VI)): result[i,0] = rang_mid[i] result[i,1] = VI[i] return(result) return(SS)
# This is a program to visually plot sets of X & Y coordinates. # Written by: Jason Bierbrauer, 1-20-2017 import os import turtle # Location of Random_XY on local computer. A program I made to supplement the need for XY text files. rxy = "C:\\Users\\Jason\\Blue\\plot_data\\Random_XY.jar" def prompt(): """Main prompt when to display when program is run.""" print("""\n\tWelcome to plot_data.py, this program is intended to allow you to visually plot data based off of X & Y coordinates from a text file. Please select a file or use Random_XY to create one.""") def print_tree(dir_path): """Print full tree""" for name in os.listdir(dir_path): full_path = os.path.join(dir_path, name) print(full_path) if os.path.isdir(full_path): print_tree(full_path) def draw_points(): jason.pencolor("green") for line in lines: jason.penup() value = line.split() x = float(value[0]) y = float(value[1]) jason.goto(x, y) jason.stamp() def plot_regression(): bill.pencolor("blue") for line in lines: bill.penup() value = line.split() x = float(value[0]) y = float(value[1]) y2 = (mean_y + m) * (x - mean_x) bill.goto(x, y2) bill.stamp() while True: prompt() # Get current working directory and display it. cwd = os.getcwd() print("\nCurrent working directory,") print(cwd) print_tree(cwd) # User input. choice = input("\nEnter Directory, Dir\\\Filename.ext, RandomXY, or exit: ") # Load selected file conditions. if str(choice).__contains__('.'): print("Here is your selected file,\n") # Attempts to open text file and parse line by line for two numbers. # Using turtle to plot data. jason = turtle.Turtle() jason.pencolor("blue") bill = turtle.Turtle() bill.pencolor("green") window = turtle.Screen() window.screensize(50000, 50000) try: f_obj = open(choice, 'r') lines = f_obj.readlines() n = len(lines) for line in lines: value = line.split() x = float(value[0]) y = float(value[1]) x += x y += y mean_x = x / n mean_y = y / n m1 = (x * y) - (n * mean_x * mean_y) m2 = (x ** 2) - (n * (mean_x ** 2)) m = m1 / m2 draw_points() plot_regression() window.exitonclick() exit() except FileNotFoundError: print("Sorry, " + choice + " is not valid.") except EnvironmentError: print("Sorry, error has happened.") # Load Random_XY.jar conditions. elif str(choice).__contains__('RandomXY'): try: os.system(rxy) except FileNotFoundError: print("Sorry, " + choice + " is not valid.") elif str(choice).__contains__('randomXY'): try: os.system(rxy) except FileNotFoundError: print("Sorry, " + choice + " is not valid.") elif str(choice).__contains__('Randomxy'): try: os.system(rxy) except FileNotFoundError: print("Sorry, " + choice + " is not valid.") elif str(choice).__contains__('randomxy'): try: os.system(rxy) except FileNotFoundError: print("Sorry, " + choice + " is not valid.") # Exit conditions. elif str(choice).__contains__('exit'): exit() elif str(choice).__contains__("Exit"): exit() elif str(choice).__contains__("EXIT"): exit() # Change Directory conditions. else: os.chdir(choice)
tablero = [ [" "," ", " ", "|"," "," ", " ", "|"," "," ", " "], #1 5 9 ["-","-", "-", "+","-","-", "-", "+","-","-", "-"], [" "," ", " ", "|"," "," ", " ", "|"," "," ", " "], #23 27 31 ["-","-", "-", "+","-","-", "-", "+","-","-", "-"], [" "," ", " ", "|"," "," ", " ", "|"," "," ", " "] #45 49 53gi ] jugador = True def print_tblro(tablero): ###funcion para dibujar tablero for fila in tablero: for slot in fila: print(slot,end = "") print("") def exit (accion): ##funcion para terminar programa if accion.lower() == "q": return True else: return False def check_accion(accion): ##funcion comprobar input (dentro del rango y que sea un numero if not isnum(accion): return False if not rango(accion): return False return True def isnum(accion): ##funcion que revisa si es un numero if not accion.isnumeric(): print(f"el espacio {accion} no existe ...") return False else: return True def rango (accion): ##funcion que revisa si esta entre 1 y 9 if int(accion) > 9 or int(accion) < 1: print (f"la posición {accion} no existe en el tablero") return False else: return True def ocupado (cordenadas, tablero): # fila = cordenadas[0] columna = cordenadas[1] if tablero[fila][columna] != " ": print("Amigue date cuenta, el espacio esta ocupado ...") return True else: return False def cordenadas (accion): ## (esta funcion asigna las posiciones del tablero a los numeros) fila = 0 ## ESTO SE PUEDE HACER MEJOR ....!!!!! columna = 0 if accion == 1: fila = 0 columna = 1 elif accion == 2: fila = 0 columna = 5 elif accion == 3: fila = 0 columna = 9 elif accion == 4: fila = 2 columna = 1 elif accion == 5: fila = 2 columna = 5 elif accion == 6: fila = 2 columna = 9 elif accion == 7: fila = 4 columna = 1 elif accion == 8: fila = 4 columna = 5 elif accion == 9: fila = 4 columna = 9 return (fila,columna) def add_jugada(cordenada,tablero, jugando): ##añade jugada al tablero fila = cordenada[0] columna = cordenada[1] tablero[fila][columna] = jugando def jugador_actual(jugador): ## funcion cambia de jugador if jugador: return "X" else: return "O" def revisa_fila(jugador, tablero): for fila in tablero: fila_completa = True for slot in fila: if slot != jugador: fila_completa = False break if fila_completa: return True return False def ganador(jugador, tablero): if revisa_fila(jugador, tablero): return True return False while True: jugando = jugador_actual(jugador) print_tblro(tablero) accion = input("seleccione el lugar donde desea jugar(1 - 9) o presione Q para salir:") if exit(accion): break if not check_accion(accion): print("introduce una movida aceptada ... -_-") continue accion = int(accion) cordenada = cordenadas(accion) if ocupado(cordenada,tablero): print("Ingresa nuevamente una posición en el tablero") continue add_jugada(cordenada,tablero, jugando) if ganador (jugando, tablero): print(f"{jugando} has ganado!!!") break jugador = not jugador
def rowReduce(A,b): ''' Row reduce a matrix that is assumed to be in good form, aka no pivoting strategies. :param A: The Matrix to be reduced :param b: The b vector in Ax = b :return: A tuple containing both A and b. ''' numRows = len(A) numColumns = len(A[0]) for k in range(numRows - 1): for i in range(k + 1, numColumns): factor = A[i][k] / A[k][k] for j in range(k, numColumns): A[i][j] = A[i][j] - factor * A[k][j] b[i] = b[i] - factor * b[k] return A,b if __name__ == '__main__': testMatrix = [ [1, -3, 1], [2, -8, 8], [-6, 3, -15] ] testB = [4,-2,9] A,b = rowReduce(testMatrix,testB) for row in A: print(row) print(b)
from numpy import float64 def doublePoint(): one = float64(1.0) seps = float64(1.0) appone = float64(1.0) for ipow in range(1, 1000): seps = seps / 2 seps = float64(seps) appone = one + seps if (abs(appone) == 1): return ipow print("Didn't make it after 1000 Iterations") if __name__ == "__main__": print(f"The number of binary digits that can be printed is {doublePoint()}") print(f"The smallest number this corresponds to is {2 ** -doublePoint()}")
def mostfreq(str): result={} for i in str: if i in result: continue result[i]=str.count(i) list = result.values() return max(list) print(mostfreq("AsssAAA"))
import re def rever(s): list = s.split() newlist = '' for i in range(len(list)-1,-1,-1): print(i) if i==0: newlist = newlist+list[i] else: newlist = newlist+list[i]+' ' return newlist print(rever("how are you?"))
# !\usr\bin\python3 # _*_ coding _*_ """ 计算字符串中,指定字符出现的次数 """ def count_char(s, char): s_dict = {} for si in s: if si in s_dict: s_dict[si] += 1 else: s_dict[si] = 1 return s_dict[char] count_char('abcdefgdcbaa', 'a')
def non_repeating(given_string): dictionary = {} for c in given_string: if c in dictionary: dictionary[c] += 1 else: dictionary[c] = 1 for c in dictionary: if dictionary[c] == 1: return c return None def test(): assert non_repeating("abcab") == 'c' assert non_repeating("abab") is None assert non_repeating("aabbbc") == 'c' assert non_repeating("aabbdbc") == 'd' if __name__ == "__main__": test()
def is_one_away(s1, s2): min_length = min(len(s1), len(s2)) max_length = max(len(s1), len(s2)) if max_length - min_length > 1: return False dif_counter = 0 index1 = 0 index2 = 0 while min_length > min(index1, index2): if s1[index1] == s2[index2]: index1 += 1 index2 += 1 else: dif_counter += 1 if dif_counter > 1: return False if len(s1) > len(s2): index1 += 1 elif len(s1) < len(s2): index2 += 1 else: index1 += 1 index2 += 1 return True def test(): assert is_one_away("abcde", "abcd") is True assert is_one_away("abde", "abcde") is True assert is_one_away("a", "a") is True assert is_one_away("abcdef", "abqdef") is True assert is_one_away("abcdef", "abccef") is True assert is_one_away("abcdef", "abcde") is True assert is_one_away("aaa", "abc") is False assert is_one_away("abcde", "abc") is False assert is_one_away("abc", "abcde") is False assert is_one_away("abc", "bcc") is False if __name__ == "__main__": test()
a = 2 b = 0.5 print(a+b) name = 'Denis' print(f"Привет , {name} !") #v = int(input('Введите число от 1 до 10 ')) #print(int(v + 10)) #name = input("Введите Ваше имя ") #print(f'Привет, {name}. Как дела? ') print(int(1.0)) a = [3 , 5 , 7 , 9 , 10.5] print(a) a.append("Python") print(a) del a[5] print(a) meteo = {'city' : 'Москва', 'temperature' : '20' } print (meteo['city']) meteo['temperature'] = str(int(meteo['temperature']) - 5) print(meteo) print(meteo.get('country')) #print(meteo['country']) meteo.get('country','Россия') #print(meteo['country']) meteo['date'] = '2020.09.10' #meteo = {'city' : 'Москва', 'temperature' : '20', # 'country' } print(meteo) print(len(meteo))
#3. Escribe el código que solicite números al usuario hasta que éste ingrese -1. #Cuando se ingrese -1, el programa debe imprimir el promedio de todos los números ingresados # hasta ese momento (sin contar con el -1). num = int(input("ingrese un numero cualquiera : ")) acum = 0 cont = 0 while num != (-1) : acum = num + acum cont += 1 num = int(input("ingrese un numero cualquiera : ")) r= (acum)/(cont) print(f"el promedio de los numeros ingresados es: " , r )
print("actividad1") #Escribe el código que imprima un comando dada la luz del semáforo #Verde = Siga #Amarillo = Precaución #Rojo = Pare luz = input("ingrese color del semaforo: verde 'v' / amarillo 'a' / rojo 'r' ") if luz.lower() == "v" : print("siga") else : if luz.lower() == "a" : print("precaucion") else : if luz.lower() == "r": print("pare")
print("actividad3") #Escribe el código para dos numeros a y b, el usuario va a seleccionar una opcion: #1 para sumar, 2 para multiplicar, 3 para restar (a-b) y 4 para dividir (a/b) y #retornar el resultado de la operación indicada. a = float(input("ingrese valor de la variable a. : ")) b = float(input("ingrese valor de la variable b. : ")) p = int(input("que operacion desea realizar : \n 1.) sumar 2.) multiplicar 3.) resta (a-b) 4.) dividir (a/b) \n")) if p == 1 : r = a+b print("resultado es : " , r) elif p == 2 : r = a*b print("resultado es : " , r) elif p == 3 : r = (a-b) print("resultado es : " , r) elif p == 4 : r = a/b print("resultado es : " , r) else : print("error en la digitacion")
#Actividad 1 #Escribamos un programa que nos permita crear con una lista de 6 números aleatorios entre 1 y 20, #y luego creemos tres funciones que reciban la lista como parámetro de la siguiente forma: # # mayor(x) - Una función que imprima el número mayor valor de una lista x # primos(x) - Una función que imprima los números de la lista que son números primos # orden(x) - Una función que ordene los datos de una lista x ascendentemente y la imprima en orden from array import array from random import randrange import os os.system("cls") def mayor(list): print() print(" --- Funcion que haya el mayor valor de una lista.. ") mayor=0 for i in list: if i > mayor: mayor = i print() print(f" --- El mayor valor es {mayor}") print() def primos(list): print() print(" --- Funcion que imprime el/los valores primo(s) de una lista.. ") for i in list: primo = True for j in range(2,i): if i% j == 0: primo = False break if primo: print(i) print() def ordenar(list): print(" --- Funcion que organiza de forma ascendente los valores de la lista --- ") for i in range(len(list)): for m in range(len(list)): if list[i] < list[m]: tmp = list[i] list[i] = list[m] list[m] = tmp print("Lista ordenada: ", list) print() def menu(): lista = [] for i in range(6): lista.append(randrange(1,20)) print(f" Litsa generada: {lista}") print() opc = 0 while opc != 4: print("***** Menu de opciones *****") print() print("1. - Hallar el mayor valor de la lista. ") print("2. - Obtener los numeros primos de una lista. ") print("3. - Ordenar Ascendentemente los numeros de una lista. ") print("4. - Salir. ") print() opc =int(input("--- Elija una opcion del menu. ----")) print() if opc ==1: mayor(lista) elif opc ==2: primos(lista) elif opc==3: ordenar(lista) elif opc ==4: print("--- Final ---") else : print(" --- Opcion invalida ---") menu()
## Tower of Hanoi ## move n pieces from source to destination ## using a temporary location ## Program: def tower(n,start,end,middle): if n==1: print("Move %i from tower %s to tower %s" %(n,start,end)) else: tower(n-1,start,middle,end) print("Move %i from tower %s to tower %s" %(n,start,end)) tower(n-1,middle,end,start) tower(4,"A","C","B")
from preprocess import * import pickle import os def lm_train(data_dir, language, fn_LM): """ This function reads data from data_dir, computes unigram and bigram counts, and writes the result to fn_LM INPUTS: data_dir : (string) The top-level directory continaing the data from which to train or decode. e.g., '/u/cs401/A2_SMT/data/Toy/' language : (string) either 'e' (English) or 'f' (French) fn_LM : (string) the location to save the language model once trained OUTPUT LM : (dictionary) a specialized language model The file fn_LM must contain the data structured called "LM", which is a dictionary having two fields: 'uni' and 'bi', each of which holds sub-structures which incorporate unigram or bigram counts e.g., LM['uni']['word'] = 5 # The word 'word' appears 5 times LM['bi']['word']['bird'] = 2 # The bigram 'word bird' appears 2 times. """ # TODO: Implement Function LM = {} LM['uni'] = {} LM['bi'] = {} for (dirpath, dirnames, filenames) in os.walk(data_dir): for filename in filenames: if(filename.endswith(language)): with open(data_dir + "/" + filename) as train_data: for line in train_data: line = preprocess(line, language, add_null=True) words = line.split() for word in line.split(): if word in LM['uni']: LM['uni'][word] = LM['uni'][word] + 1 else: LM['uni'][word] = 1 for i in range(len(words)-1): if not words[i] in LM['bi']: LM['bi'][words[i]] = {} if words[i+1] in LM['bi'][words[i]]: LM['bi'][words[i]][words[i+1]] = LM['bi'][words[i]][words[i+1]] + 1 else: LM['bi'][words[i]][words[i+1]] = 1 prevWord = word #Save Model with open(fn_LM+'.pickle', 'wb') as handle: pickle.dump(LM, handle, protocol=pickle.HIGHEST_PROTOCOL) ''' for key, val in LM['uni'].items(): print("Key: " + key + " Val: " + str(val)) for key, val in LM['bi'].items(): print("First word: " + key) for key2, val2 in val.items(): print(" Second word: " + key2 + " with total count: " + str(val2)) ''' return LM
import random deck = [] player1_hand = [] player2_hand = [] def makedeck(deck): SUITS = ["hearts", "diamonds", "clubs", "spades"] VALUES = ["A","1","2","3","4","5","6","7","8","9","10","J","Q","K"] for e in SUITS: for i in VALUES: card = i + " " + e deck.append(card) def shuffledeck(deck): for i in range(len(deck)): j = random.randrange(len(deck)) temp = deck[i] deck[i] = deck[j] deck[j] = temp def dealcard(deck, player1_hand, player2_hand): for i in range(5): card = deck.pop(0) player1_hand.append(card) card = deck.pop(0) player2_hand.append(card) makedeck(deck) print(deck) shuffledeck(deck) print(deck) dealcard(deck, player1_hand, player2_hand) print(player1_hand) print(player2_hand)
# JoshBothell # 1/19 class Human(object): def __init__(self, name, hair_color, eye_color, height, weight, iq, gender, race): self.name = name self.hair_color = hair_color self.eye_color = eye_color self.height = height self.weight = weight self.iq = iq self.gender = gender self.race = race def introduce_self(self): print("Hello my name is ", self.name) def describe_self(self): print("I have", self.hair_color, "hair") print("I have", self.eye_color, "eye") print("I am", self.height, "cm tall") print("I am", self.weight, "kg") print("I have an IQ of", self.iq,) print("I am", self.gender) print("I am", self.race) def insult_self(self): thicc = None short_king = None idiot = None if int(self.weight) > 200: thicc = True if int(self.height) < 72: short_king = True if int(self.iq) < 90: idiot = True if thicc: print(self.name, "is disgustingly gargantuan at a sickening", self.weight, "kg") if short_king: print(self.name, "is practically a child at a pathetic", self.height, "centimeters") if idiot: print(self.name, "has a pathetically low iq which is below average at", self.iq) def bmi_calc(self): heightSqrd = int(self.height) * int(self.height) bmiraw = (int(self.weight) / heightSqrd) * 10000 bmi = round(bmiraw, 1) print(self.name,"'s BMI is ", bmi) if bmi < 18.5: print(self.name, "is underweight") elif bmi < 24.9: print(self.name, "is normal weight") elif bmi < 29.9: print(self.name, "is overweight") elif bmi > 30: print(self.name, "is obese") josh = Human("Josh", "Blonde", "Blue", "180", "55", "0","Male", "White") josh.bmi_calc()
print("python terms") puzzle = """ fjvfloatdy yopxednins mspfycnnal xeaeeukgei slufryprlc abeeiagcoi buclqttbon gojlivxobg admyahgerj stringwvrs """ print(puzzle) print("word list") word_list = "float, while, if, boolean, doubled, operators, string, slicing, index" print (word_list) word1_length = len("float") word2_length = len("while") word3_length = len("if") word4_length = len("boolean") word5_length = len("double") word6_length = len("operators") word7_length = len("string") word8_length = len("slicing") word9_length = len("index") word1 = input("enter the index position of float: ") i = 0 foundword = "" while i < word1_length: index = word1[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word2 = input("enter the index position of while: ") i = 0 foundword = "" while i < word2_length: index = word2[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word3 = input("enter the index position of while: ") i = 0 foundword = "" while i < word3_length: index = word3[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word4 = input("enter the index position of while: ") i = 0 foundword = "" while i < word4_length: index = word4[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word5 = input("enter the index position of while: ") i = 0 foundword = "" while i < word5_length: index = word5[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word6 = input("enter the index position of while: ") i = 0 foundword = "" while i < word6_length: index = word6[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word7 = input("enter the index position of while: ") i = 0 foundword = "" while i < word7_length: index = word7[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word8 = input("enter the index position of while: ") i = 0 foundword = "" while i < word8_length: index = word8[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) word9 = input("enter the index position of while: ") i = 0 foundword = "" while i < word9_length: index = word9[i] index = int(index) foundword = foundword + puzzle[index + 1] i+=1 print(foundword) input("press enter to exit")
import urllib.request from bs4 import BeautifulSoup url="https://sarnesh444.github.io/COVID-19-Mask-Detector-Web-App/" #opening and reading url #read eliminates the need for a loop html=urllib.request.urlopen(url).read() #print(html.decode())#gives the entire page print(html) #initiating parser #html-content of the file #html.parser-used to parse the scraped html file soup=BeautifulSoup(html,'html.parser') #tag to look/search for #returns a list of the searched word here:button tags=soup('button') #print(tags) for tag in tags: print(tag.get)
print ("1 milla = 1609.344 metros.") print ("1 galón = 3.785411784 litros.") litros = float(input("cuantos litros consume tu coche a los 100: ")) millas = float(input("cuantas millas recorre tu coche por galon: ")) def l100kmtompg(litros): millas = 100 * 1000 / 1609.344 galones = litros / 3.785411784 return millas/galones def mpgtol100km(millas): cienkm = millas * 1609.344 / 1000 / 100 litros = 3.785411784 return litros / cienkm print(l100kmtompg(3.9)) print(l100kmtompg(7.5)) print(l100kmtompg(10.)) print(mpgtol100km(60.3)) print(mpgtol100km(31.4)) print(mpgtol100km(23.5)) print(l100kmtompg(litros)) print(mpgtol100km(millas))
''' 函数和模块的使用 ''' ''' m = int(input('m = ')) n = int(input('n = ')) fm = 1 for num in range(1,m + 1): fm *= num fn = 1 for num in range(1,n + 1): fn *= num fmn = 1 for num in range(1,m - n + 1): fm *= num print(fm // fn // fmn) ''' ''' 定义函数 def ''' ''' def factorial(num): """求阶乘""" result = 1 for n in range(1,num + 1): result *= n return result m = int(input('m = ')) n = int(input('n = ')) #当需要计算阶乘的时候不用再写循环求阶乘而是直接调用已经定义好的函数 print(factorial(m) // factorial(n) // factorial(m - n)) ''' ''' 函数的参数 ''' ''' from random import randint def roll_dice(n=2): """摇色子""" total = 0 for _ in range(n): total += randint(1,6) return total def add(a=0,b=0,c=0): """三个数相加""" return a + b + c #如果没有指定参数那么使用默认值摇两颗色子 print(roll_dice()) #摇三颗色子 print(roll_dice(3)) print(add()) print(add(1)) print(add(1,2)) print(add(1,2,3)) #传递参数时可以不按照设定的顺序进行传递 print(add(c=50,a=100,b=200)) ''' #在参数名前面的*表示args是一个可变参数 ''' def add(*args): total = 0 for val in args: total += val return total #在调用add函数是可以传入0个或多个参数 print(add()) print(add(1)) print(add(1,2)) print(add(1,2,3)) print(add(1,3,5,7,9)) ''' ''' def foo(): print('hello,world!') def foo(): print('goodbye,world!') foo() ''' ''' 练习1:实现计算求最大公约数和最小公倍数的函数 ''' ''' def gcd(x, y): """求最大公约数""" (x, y) = (y, x) if x > y else (x, y) for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: return factor def lcm(x, y): """求最小公倍数""" return x * y // gcd(x, y) ''' ''' 练习2:实现判断一个数是不是回文数的函数 ''' ''' def is_palindrome(num): "判断一个数是不是回文数" temp = num total = 0 while temp > 0: total = total * 10 + temp % 10 temp //= 10 return total == num ''' ''' 练习3:实现判断一个数是不是素数的函数 ''' ''' def is_prime(num): "判断一个数是不是素数" for factor in range(2,num): if num % factor == 0: return False return True if num != 1 else False ''' ''' 练习4:写一个程序判断输入的正整数是不是回文素数 ''' ''' if __name__ == '__main__': num = int(input('请输入正整数:')) if is_palindrome(num) and is_palindrome(num): print('%d是回文素数' % num) ''' ''' #Python中有关变量作用域的问题 def foo(): b = 'hello' #python中可以在函数内部再定义函数 def bar(): C = True print(a) print(b) print(c) bar() #print(c) #NameError:name 'c' is not defined if __name__ == '__main__': a = 100 #print(b) #NameError: name 'b' is not defined foo() ''' ''' def foo(): global a a = 200 print(a) # 200 if __name__ == '__main__': a = 100 foo() print(a) # 200 ''' ''' def main(): # Todo: Add your code here pass if __name__ == '__main__': main() '''
# %% #Tokenization import re import string def tokenization(text): text_token = re.split('\W+',text) #Returns a match where the string does contain only word characters return text_token def tokenization_apply(Series): Series = Series.apply(lambda x: tokenization(x.lower())) return Series
n = int(input("enter a number")) i=2 c=0 while(i<=n/2): if(n%i==0): c=c+1 break i=i+1 if(c==0 and n!=1): print(n,"is prime") else: print(n,"is not prime")
""" An example that finds all L3 travel regions overlapping with Germany/Bavaria and the nodes they contain organized by country """ from travel_regions.admin_regions import get_country_codes, get_admin_region_geoms from travel_regions import TravelRegions import os import json # Initialize travel regions travel_regions = TravelRegions() # Get top-level administrative regions of Germany de_admin_regions = get_admin_region_geoms("de") # Organize all nodes by country country_nodes = {} for node in travel_regions.nodes.values(): if (country := get_country_codes(node.country)) is not None: if country.name in country_nodes: country_nodes[country.name].append(node) else: country_nodes[country.name] = [node] level = 3 # TODO Decide whether to perform overlap comparison Germany or Bavaria by commenting out the corresponding statement """ regions_overlap = travel_regions.compare_overlap(level, de_admin_regions["Germany"]) overlap_threshold = 2 """ regions_overlap = travel_regions.compare_overlap( level, de_admin_regions["Freistaat Bayern"] ) overlap_threshold = 10 # TODO Decide whether threshold applies to overlap as percentage of region or as percentage # of country, by commenting out the corresponding statement regions_overlap = { k: v for k, v in regions_overlap.items() if v[1] >= overlap_threshold } # only include overlapping regions whose overlap with Germany makes up at least 2% of the country's area """ regions_overlap = { k: v for k, v in regions_overlap.items() if v[0] >= overlap_threshold } # only include overlapping regions whose overlap with Germany makes up at least 2% of their area """ region_country_nodes = {} overlapping_regions = {} overlapping_region_geoms = [] overlapping_region_nodes = [] for overlapping_region_ID in regions_overlap: overlapping_region_nodes.append([]) region_country_nodes[overlapping_region_ID] = {} overlapping_regions[overlapping_region_ID] = travel_regions.get_region( overlapping_region_ID ) overlapping_region_geoms.append( ( overlapping_regions[overlapping_region_ID].community_id, overlapping_regions[overlapping_region_ID].geometry, ) ) for node in overlapping_regions[overlapping_region_ID].nodes: if node.name == "Munich": overlapping_region_nodes[-1].append({"id": node.id, "latlng": node.latlng}) if (country := get_country_codes(node.country)) is not None: if country.name in region_country_nodes[overlapping_region_ID]: region_country_nodes[overlapping_region_ID][country.name].append(node) else: region_country_nodes[overlapping_region_ID][country.name] = [node] print(f"Region ID: {overlapping_region_ID}") for country, nodes in region_country_nodes[overlapping_region_ID].items(): print( f"\t{country}: {len(nodes)}/{len(country_nodes[country])} nodes ({(len(nodes)/len(country_nodes[country]))*100:.2f}\%)" ) # TODO Update output path and uncomment to export regions """ serialized_IDs, serialized_geoms = zip(*overlapping_region_geoms) regions_serialized = { "level": level, "community_IDs": list(serialized_IDs), "nodes": overlapping_region_nodes, "geometries": list(serialized_geoms), } path = None with open(path, "w",) as f: json.dump(regions_serialized, f, indent=4) """
#!/usr/bin/env python import struct file = raw_input("the file you want identfy:") f = open(file,'rb') s = f.read(30) print('0-30:',s) ss = struct.unpack('<ccIIIIIIHH',s) if ss[0] == 'B' and ss[1] == 'M': print 'This is a bmp file! It has ',ss[6],'*', ss[7],', It is color is ',ss[9],'.' else: print 'This is not a bmp file!' f.close()
#!/usr/bin/env python def normalize(name): return name.title() L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) def is_palindrome(n): sn = str(n) for i in range(len(sn)/2): if sn[i] != sn[len(sn)-i-1]: return False return True output = filter(is_palindrome, range(1, 1000)) print(list(output))
number = int(input("Enter the numeric grade: ")) if number >= 0 and number <= 100: if number > 89: letter = "A" elif number > 79: letter = "B" elif number > 69: letter = "C" elif number <60: letter = "F" print("The letter grade is ", letter) else: print("Error: grade must be between 100 and 0")
""" Program: Surface area calculator Author: Kevin Tran The purpose of this program is to calculate the surface are of a cube. 1. Get user input for the length of single edge of a cube. 2. Calculate surface area of cube from the given input. surface_area = 6 (length**) 3. Print out put of surface area. """ # Get user input for cube edge length length = int(input("Enter the length of the cubes edge(inches): ")) # Calculate surface area surface_area = 6 * length**2 # Print output print("The surface area of the cube is " + str(surface_area) + " inches")
""" Program: Employee pay calculator Author: Kevin Tran The purpose of this program is calculate an employees pay considering overtime 1. Get input of employees hours 2. Calculate hourly pay. If there are more than 40 hours then pay is 1.5 times the hourly rate for those hours 3. Print output of the calculated paycheck. """ # Constants pay_rate = 15 # Get inputs emp_name = input("Enter employees name: ") print("How many hours did " + emp_name + " work this week? ") hours_clocked = int(input()) # Calculate pay of the employee if hours_clocked > 40: overtime_hours = hours_clocked - 40 overtime_pay = overtime_hours * (pay_rate*1.5) total_pay = (40 * pay_rate) + overtime_pay else: total_pay = hours_clocked * pay_rate # Print outputs if hours_clocked > 40: print(emp_name + "'s total pay this week is $" + str(total_pay) + " with " + str(overtime_hours) + " hours of overtime") else: print(emp_name + "'s total pay this week is $" + str(total_pay))
""" File: dotprod.py Author: James Lawson """ import numpy as np import random import time import matplotlib.pyplot as plt # Dot Product Function - stack overflow linked that helped me: # https://stackoverflow.com/questions/32669855/dot-product-of-two-lists-in-python def dotProduct(a, b): return sum(i[0] * i[1] for i in zip(a, b)) if __name__ == "__main__": # 2 lists are created a = [] b = [] # 1 million elements are added to both of the lists for k in range(1000000): a.append(random.random()) b.append(random.random()) # Lists are convered to a NumPy array a = np.asarray(a) b = np.asarray(b) # Takes start time startTime = time.time() # Calls the dot product function dotProduct = dotProduct(a,b) # Takes end time endTime = time.time() # Total time is calculated and rounded totalTime = endTime - startTime totalTime = round(totalTime, 5) # Prints the NP dot product dotProduct = round(dotProduct, 5) print("We expect the result to be ~250,000, a quarter of 1 million values in each NumPy array") print("The dot product is: ", dotProduct) # Takes start time startTimeNP = time.time() # Calls the NP dot product function dotProductNP = np.dot(a,b) # Takes end time endTimeNP = time.time() # Prints the NP dot product dotProductNP = round(dotProductNP, 5) print("The dot product calculated using NP is: ", dotProductNP) # Total time is calculated, rounded, and printed totalTimeNP = endTimeNP - startTimeNP totalTimeNP = round(totalTimeNP, 5) print("The time taken by the dot-product calculation is: ", totalTime) print("The time taken by the NP dot-product function is: ", totalTimeNP) # Part 3 ---------------------------------------------------------------- # 2 NumPy arrays are created to store values a = np.array([]) b = np.array([]) # 2 empty numpy arrays are initialized rollYourOwn = np.array([]) NumPy = np.array([]) print("Creating Visualization......................") # Step 10 times from 10,000 to 100,000 in increments of 10,000 for x in range(10): # 10,000 random values are added to the empty numpy arrays for k in range(10000): a = np.append(a, random.random()) b = np.append(b, random.random()) # Takes start time startTime = time.time() # Calculates the dot product dotProduct = sum(i[0] * i[1] for i in zip(a, b)) # Takes end time endTime = time.time() # Total time is calculated and rounded totalTime = endTime - startTime totalTime = round(totalTime, 5) # Append the time to the empty array rollYourOwn = np.append(rollYourOwn, totalTime) #------------------------------------------------------- # Takes start time startTimeNP = time.time() # Calls the NP dot product function dotProductNP = np.dot(a,b) # Takes end time endTimeNP = time.time() # Total time is calculated and rounded totalTimeNP = endTimeNP - startTimeNP totalTimeNP = round(totalTimeNP, 5) # Append the time to the empty array NumPy = np.append(NumPy, totalTimeNP) # Numpy arrays are printed print("Roll Your Own Times: ", rollYourOwn) print("NumPy Times: ", NumPy) # Graph Visualization is created # linked that helped me - https://www.sitepoint.com/plot-charts-python-matplotlib/ plt.plot(rollYourOwn, label="Roll Your Own") plt.plot(NumPy, label="NumPy") plt.title("Time Taken: Roll Your Own vs. NumPy") plt.xlabel("Number of Values") plt.ylabel("Time (sec)") plt.legend(loc="best") plt.show()
import re def compute_paths(array, start_node, finish_node, not_found = 1000000): """ Naive implementation of dijkstra algorithm, without heap So the running time here is n * m, where n is number of vertices, and m is number of edges Array has the following format: [ '1 2,3 4,5, 7,5', '2 1,3 4,4 5,1', ... ] The first number in the string is the vertex number Following pairs (x,y): x -- number of vertex which has edge with the initial vertex and y is the length of this edge """ # we put it to the same type to avoid problems in the future start_node = str(start_node) finish_node = str(finish_node) # we transform graph representation to the dict one # with vertices as keys and lists of edges as values graph = {} for line in array: splitted_string = re.split('\t|\s', line) vertex = splitted_string[0] graph[vertex] = splitted_string[1:] # check input correctness, that nodes are inside graph if start_node not in graph: raise TypeError("no start node in the presented graph!") if finish_node not in graph: raise TypeError("no finish node in the presented graph!") vertices = set(graph.keys()) vertices.remove(start_node) vertex = start_node discovered = { start_node: True } while len(vertices) > 0: edges = graph[vertex] current_length = None current_vertex = None for edge in edges: [second_vertex, length] = edge.split(",") length = int(length) if second_vertex not in discovered: if current_length is None or length < current_length: current_length = length current_vertex = second_vertex if current_vertex in vertices: discovered[current_vertex] = True if current_vertex == finish_node: return current_length vertices.remove(current_vertex) def update_edges(edge): [second_vertex, length] = edge.split(",") length = int(length) return "{0}, {1}".format(second_vertex, length + current_length) updated_values = [update_edges(edge) for edge in graph[current_vertex]] graph[vertex] = graph[vertex] + updated_values def filter_edges(edge): [second_vertex, length] = edge.split(",") return second_vertex not in discovered graph[vertex] = filter(filter_edges, graph[vertex]) else: return not_found return not_found
def merge(tuple1, tuple2): """ Merging subroutine of merge sort We have two sorted arrays, which we have to merge into one sorted array Also, we calculate number of inversions, so we keep track of them during merging too, adding to the existing number Each tuple has structure (sorted_array, number_of_inversions) """ arr1 = tuple1[0] arr2 = tuple2[0] firstArrayLength = len(arr1) secondArrayLength = len(arr2) result = [] firstIndex = 0 secondIndex = 0 inversions = tuple1[1] + tuple2[1] for i in range(0, firstArrayLength + secondArrayLength): # if we took all from the first array if firstIndex == firstArrayLength: result.append(arr2[secondIndex]) secondIndex = secondIndex + 1 # if we took everything from the second array elif secondIndex == secondArrayLength: result.append(arr1[firstIndex]) firstIndex = firstIndex + 1 # if the next number is from the first array # no need to increase inversions elif (arr1[firstIndex] <= arr2[secondIndex]): result.append(arr1[firstIndex]) firstIndex = firstIndex + 1 elif (arr2[secondIndex] < arr1[firstIndex]): result.append(arr2[secondIndex]) secondIndex = secondIndex + 1 # we have to increase number of inversions by all left # elements in the left array, because they are guaranteed # higher than this element inversions = inversions + firstArrayLength - firstIndex return (result, inversions) def mergeSort(arr): """ Partitioning subroutine of merge sort Also, it counts number if inversions (though they are counted in merging subrouting) """ arrayLength = len(arr) # base case: same array, 0 inversions if arrayLength == 1: return (arr, 0) # just separating into two parts of the same size separator = arrayLength / 2 leftArr = arr[:separator] rightArr = arr[separator:] return merge(mergeSort(leftArr), mergeSort(rightArr))
import collections import heapq import queue import threading import time class SkipQueue(queue.Queue): """ Implementation of blocking queue which can queue urgent items to the beginning of the queue instead of at the end. """ def __init__(self): super().__init__() self.queue = collections.deque() def enqueue(self, x, skip=False): item = x, skip self.put(item) def dequeue(self, block=True, timeout=None): return self.get(block, timeout) def _put(self, item): x, skip = item if skip: self.queue.appendleft(x) else: self.queue.append(x) class TimedQueue(SkipQueue): def __init__(self): super().__init__() self.delayed = [] self._WAIT = .1 def enqueue(self, x, delay=0): deadline = time.time() + delay super().enqueue((deadline, delay, x), skip=delay > 0) def dequeue(self, block=True, timeout=None): while True: now = time.time() timeout = self._WAIT if self.delayed: nearest = self.delayed[0] timeout = max(0, nearest[0] - now) try: deadline, delay, x = super().dequeue(block=block, timeout=timeout) except queue.Empty: if not block: raise else: if delay > 0: heapq.heappush(self.delayed, (deadline, x)) else: return x delayed = [] while self.delayed and self.delayed[0][0] <= now: delay, x = heapq.heappop(self.delayed) delayed.append(x) while delayed: x = delayed.pop() super().enqueue((0, 0, x)) class Done(Exception): pass class Container: def __init__(self): self._queue = self._make_queue() self.__thread = None def _make_queue(self): return SkipQueue() def start(self): self._react() def stop(self): # Can't stop this! pass def spawn(self, wait): self.__thread = threading.Thread(target=self._synchronized_start, args=[wait]) self.__thread.start() def join(self): self.__thread.join() def _synchronized_start(self, wait): result = None try: self.start() except Exception as err: result = err else: result = Done wait.put((self, result)) def invoke(self, function, *a, **k): event = self._make_event(function, *a, **k) self._queue.enqueue(event) def _make_event(self, function, *a, **k): return function, a, k def _react(self): event = self._queue.dequeue() function, a, k = event function(*a, **k) class LoopContainer(Container): def __init__(self): super().__init__() self.__running = False def stop(self): self.__running = False # Flush the queue with empty event self.invoke(lambda: None) def _react(self): self.__running = True while self.__running: super()._react() class TimerContainer(LoopContainer): def _make_queue(self): return TimedQueue() def invoke(self, function, *a, _delay=0, **k): if "_delay" in k: del k["_delay"] if _delay >= 0: event = self._make_event(function, *a, **k) self._queue.enqueue(event, delay=_delay) else: raise ValueError("'delay' must be a non-negative number!")
""" Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? """ from linked_list import LinkedList def deduplicate_with_hash(node): """ Makes use of temporary "hash table" (dictionary) to keep track of all the values seen so far. Worst case running time of O(n) """ tracker = {} previous = None while node is not None: if node.value in tracker.keys(): previous.next = node.next else: tracker[node.value] = True previous = node node = node.next def deduplicate_without_hash(head): """ Removes nodes with duplicate values. Uses two "pointers" to keep track of current location. Wrost case running time of O(n**2). """ if head is None: return current = head while current is not None: runner = current while runner.next is not None: if runner.next.value == current.value: runner.next = runner.next.next else: runner = runner.next current = current.next if __name__ == '__main__': linked_list = LinkedList() linked_list.insert_front(11) linked_list.insert_front(300) linked_list.insert_front(72) linked_list.insert_front(72) print("{}".format(linked_list)) deduplicate_with_hash(linked_list.head) print("{}".format(linked_list)) linked_list = LinkedList() linked_list.insert_front(72) linked_list.insert_front(300) linked_list.insert_front(72) linked_list.insert_front(11) print("{}".format(linked_list)) deduplicate_without_hash(linked_list.head) print("{}".format(linked_list))
""" Q: Given two strings, write a method to decide if one is a permutaion of the other. """ def permutation_naive(a, b): """ A naive implementation iterating over. This has worst case running time of O(n ** 2). """ if len(a) != len(b): return False chars = [c for c in a] for char in b: for x in chars: if char == x: chars.remove(x) break if chars: return False return True def permutation_sorted(a, b): """ Efficient solution that sorts both strings and then compares them. This has a worst running tmie of O(n * log(n)) """ if len(a) != len(b): return False for i, j in zip(sorted(a), sorted(b)): if i != j: return False return True if __name__ == '__main__': a = 'aaabbbccc' b = 'babacabcc' print("'{}' is a permutation of '{}': {}".format(b, a, permutation_naive(a, b))) print("'{}' is a permutation of '{}': {}".format(b, a, permutation_sorted(a, b))) # Test when not a permutation, off by one char c = 'aaaabbbccc' d = 'aaabbbbccc' print("'{}' is a permutation of '{}': {}".format(c, d, permutation_naive(c, d))) print("'{}' is a permutation of '{}': {}".format(c, d, permutation_sorted(c, d)))
import random def openList(): try: with open('lista.txt') as f: lines = f.read().splitlines() return lines except FileNotFoundError as e: print("File not found") def randomWord(): lines = openList() i = len(lines) i = i-1 a =random.randint(0,i) return lines[a].lower() def letterList(word): x = 0 letterL =[] size = len(word) for x in range (0,size): letter = str(word[x]) letterA = {letter: False} letterL.append(letterA) return letterL def printWord(letterL): wword = "" for x in letterL: for y in x: if x[y]: wword = str(wword)+str(y) else: wword = str(wword)+"*" print("\n"+wword+"\n") def checkLetter(letter, letterL): for x in letterL: for y in x: if y.lower() == letter.lower(): x[y] = True return letterL def checkVictory(letterL): for x in letterL: for y in x: if not x[y]: return False return True def checkHP(letter, letterL): for x in letterL: for y in x: if letter.lower() == y.lower(): return True return False
import turtle import random # set up the screen window = turtle.Screen() # creates a window window.title("Likun's Snake Game") # give title to the window window.bgcolor("black") # set the background color window.setup(width=600, height=600) # sets the window dimensions window.tracer(0) # turns off the screen updates # create snake's head head = turtle.Turtle() # create a turtle (python notation) head.speed(0) # we don't want the head to move head.shape("square") # set the head shape head.color("white") # set the head color head.penup() # we don't want the path to be drawn head.goto(0, 100) # position of the snake's head head.direction = "stop" # functions to move the snake def move(): if head.direction == "up": y = head.ycor() # y coordinate of the turtle head.sety(y+20) if head.direction == "down": y = head.ycor() # y coordinate of the turtle head.sety(y-20) if head.direction == "right": x = head.xcor() # x coordinate of the turtle head.setx(x+20) if head.direction == "left": x = head.xcor() # x coordinate of the turtle head.setx(x-20) import time # to represent time in code delay = 0.1 def move_up(): # the snake cannot go up from down and vica-versa if head.direction != "down": head.direction = "up" def move_down(): # the snake cannot go down from up and vica-versa if head.direction != "up": head.direction = "down" def move_right(): # the snake cannot go right from left and vica-versa if head.direction != "left": head.direction = "right" def move_left(): # the snake cannot go left from right and vica-versa if head.direction != "right": head.direction = "left" # keyboard bindings window.listen() # the program now listens to key press # assigning keys to function calls window.onkey(move_up, "Up") window.onkey(move_down, "Down") window.onkey(move_right, "Right") window.onkey(move_left, "Left") # food for our snake food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.shapesize(0.50, 0.50) # stretch value in width and length food.goto(0, 0) # initialize an empty list for snake's body segs = [] # scores c_score = 0 high_score = 0 # scoring system score = turtle.Turtle() score.speed(0) score.shape("square") score.color("white") score.penup() score.hideturtle() score.goto(0, 260) score.write("Score: 0 High Score: 0", align="center", font=("Courier", 20, "normal")) # main game loop while True: window.update() time.sleep(delay) # sleep function in time module adds delay to the code # halts the excecution of the program for the given no of secs # when snake eats the food if head.distance(food) < 15.75: # relocate the food to a random position # randomization x = random.randint(-280, 280) y = random.randint(-280, 280) food.goto(x, y) # relocate coordinates # add a segment new_seg = turtle.Turtle() new_seg.speed(0) new_seg.shape("square") new_seg.color("grey") new_seg.penup() # elongation of snake's body segs.append(new_seg) # as the snake eats food, it's speed increases delay -= 0.001 # update current score c_score = c_score+10 if c_score > high_score: high_score = c_score # update score tab score.clear() score.write("Score: {} High Score: {}".format(c_score, high_score), align="center", font=("Courier", 20, "normal")) # move the end segments first in reverse order for index in range(len(segs)-1, 0, -1): x = segs[index-1].xcor() y = segs[index-1].ycor() segs[index].goto(x, y) # move segment 0 to where the head is if len(segs) > 0: x = head.xcor() y = head.ycor() segs[0].goto(x, y) # case handling for border collision if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: time.sleep(1) head.goto(0, 0) head.direction = "stop" # relocate the segments outside the window coordinates for s in segs: s.goto(1000, 1000) # clear the segs list segs.clear() # reset current score c_score = 0 # reset delay delay = 0.1 # update score tab score.clear() score.write("Score: {} High Score: {}".format(c_score, high_score), align="center", font=("Courier", 20, "normal")) move() # when snake bites itself for segment in segs: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" # hide the segments for segment in segs: segment.goto(1000, 1000) # clear the segments list segs.clear() # reset current score c_score = 0 # reset delay delay = 0.1 # update score tab score.clear() score.write("Score: {} High Score: {}".format(c_score, high_score), align="center", font=("Courier", 20, "normal"))
import os with os.scandir('images') as entries: print("###############_start_###############") for entry in entries: # List all files in a directory using os.listdir basepath = "images/" + entry.name for entry1 in os.listdir( basepath): if os.path.isfile(os.path.join(basepath, entry1)): print(entry1) print("_____________________________________") print("################_end_################")
#programm to take a single no from user and print it in string num= int(input("enter single digit no please=")) days= ["one","two","three","fourth", "fifth","six","seven","eight","nine"] if num > 9: print("you have entered number more then 9 please enter again but less then 9") elif num==1: print("one") elif num==2: print("two") elif num==3: print("three") elif num==4: print("four") elif num==5: print("five") elif num==6: print("six") elif num==7: print("seven") elif num==8: print("eight") elif num==9: print("nine")
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-Power of 2 @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-18-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import math useInput=int(input("Enter a Integer number to check for its power of 2=")) #5 if useInput > 0 and useInput<31: for i in range(1, useInput+1): print("power of 2**",i,"=",2**i) else: print(" please enter value between 1 to 30 THNKYOU")
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-Computes the prime factorization of N @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-18-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ userInput=int(input("enter a number to check for prime factorial=")) prime_number=[] devisor=2 while devisor<=userInput: if userInput%devisor==0: prime_number.append(devisor) userInput=userInput/devisor else: devisor+=1 print(prime_number)
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-programm for stop watch @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-22-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import time # importing time module while True: #while loop will run untill condition false try: # try block is used to handle excepon input("please ENTER to start , CTRL_C to exit") start_time=time.time() # time.time() method give us current time print("timer has started") while True: print("Timer elapsed=",round(time.time()-start_time,0),"sec",end="\n") time.sleep(1) #sleep method will pause execution for 1 second every iteration except KeyboardInterrupt: print("Timer has stopped") end_time=time.time() print("The time elapsed is",round(end_time-start_time),"sec") break
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Purpose: Program To find second max variable in a given list * @author: Sheevendra Singh Singraul * @version: 3.8.6 * @since: 19-03-2021 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ list=[23,21,43,45,0,8,6,54,53] if list[0] > list[1]: mx = list[0] else: mx = list[1] secondmx = list[0] n=len(list) for i in range (2,n): if list[i]>mx: secondmx=mx mx=list[i] elif list[i] > secondmx and mx != list[i] : secondmx = list[i] print (secondmx)
class ArrayHandler: # returns a flattened list + the starting indices of each sublist @staticmethod def flatten(list_of_indices): list = [] indices = [] index = 0 for sublist in list_of_indices: list.extend(sublist) indices.append(index) index += len(sublist) indices.append(index) return list, indices # converts a flattened list to a list of lists @staticmethod def listify(list, indices): list_of_lists = [] for i in range(1, len(indices)): sublist = list[indices[i-1] : indices[i]] list_of_lists.append(sublist) return list_of_lists
print("Be happy\nWork hard and eat healthy food") def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def modu(a,b): return a%b name=input("Enter your name-->") print("insert operation") print("Addition (+)") print("Substraction (-)") print("multiplication(*)") print("division(/)") print("modulo(%)") sign=input("insert operation here->") first=float(input("Enter 1st number--->")) second=float(input("enter 2nd number-->")) if sign=='+': print(add(first,second)) elif sign=='-': print(sub(first,second)) elif sign=='*': print(mul(first,second)) elif sign=='/': print(div(first,second)) elif sign=='%': print(modu(first,second)) else: print(name,"please Enter valid operation") print("Happy coading") print("please run code again (f5)")
from itertools import chain def sort_sequence(sequence): x, y = [], [] for i in sequence: if i == 0: x+=[sorted(y) + [0]] y=[] else: y+=[i] return list(chain.from_iterable(sorted(x, key=lambda n: sum(n))))
# Hangman def Hangman(guess, word): ans = "" for letter in word.lower(): if letter == guess.lower(): ans += letter else: ans += "_" return ans
def descending_order(num): converted_num = str(num) li = list(converted_num) li.sort(reverse=True) maxNumStr = ''.join(li) #toStr = str(li) #print(toStr) maxNum = int(maxNumStr) return maxNum
def tribonacci(signature, n): #your code here if n == 0: return [] if n == 1: return signature[:1] if n == 2: return signature[:2] else: for i in range(2, n-1): signature.append(sum(signature[i-2:i+1])) return signature
def to_camel_case(text): s = text.replace("-", " ").replace("_", " ") s = s.split() if len(text) == 0: return text return s[0] + ''.join(i.capitalize() for i in s[1:])
#Link: https://practice.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array/0 t = int(input()) for i in range (t): n=int(input()) a=map(int,input().split()) c=0 for i in a: if i!=0: print(i,end=' ') c=c+1 for i in range(n-c): print(0,end=' ') print('')
import merge_sort class point(): def __init__(self, name, x, y): self.name = name self.x = x self.y = y def points_to_XY(P): X = [] Y = [] for i in range(len(P)): X.append(P[i].x) Y.append(P[i].y) return X, Y def divide_points(X, Y): Px = merge_sort.div_merge(X)
import os import shutil from tkinter import filedialog from tkinter import * from tkinter import messagebox root = Tk() root.withdraw() directory = filedialog.askdirectory(initialdir="C:\\") if directory == "": quit() result = messagebox.askquestion("File Organizer", directory + " will be organized. Continue?", icon="warning") if result == "no": quit() filelist = [] count = 0 for filename in os.listdir(directory): extension = os.path.splitext(filename)[1][1:] #ignore folders if os.path.isdir(directory + "/" + filename): continue #create a folder for each extension if not os.path.exists(directory + extension): os.makedirs(directory + extension) filelist.append([filename, directory + "/" + extension + "/" + filename]) shutil.move(directory + "/" + filename, directory + "/" + extension + "/" + filename) count += 1 if count == 0: messagebox.showinfo("File Organizer", "No files were found in " + directory) quit() okcancel = messagebox.askokcancel("File Organizer", str(count) + " files were moved. Press Cancel to undo these changes or OK to continue.") if okcancel == False: for f in filelist: shutil.move(f[1], directory + "/" + f[0])
""" CP1404/CP5632 - Practical Program to display all odd values between 1 and 21. """ for i in range(1, 21, 2): print(i, end=' ') print() """ CP1404/CP5632 - Practical a. Program to display all values on 10 between 0 and 100. """ for i in range(0, 101, 10): print(i, end=' ') print() """ CP1404/CP5632 - Practical b. Program to display values counting down from 20 to 1. """ for i in range(20, 0, -1): print(i, end=' ') print() """ CP1404/CP5632 - Practical c. Program to display the requested amount of stars from the user. """ num_stars = int(input("Enter star amount: ")) for i in range(num_stars): print('*', end=' ') print() """ CP1404/CP5632 - Practical d. Program to display the requested rows of stars from the user. Because of the previous question num_stars is already defined. As such the inital line in the script doesn't need to be written. """ for i in range(1, num_stars + 1): print('*' * i) print()
import sys import string import math class NbClassifier(object): """ A Naive Bayes classifier object has three parameters, all of which are populated during initialization: - a set of all possible attribute types - a dictionary of the probabilities P(Y), labels as keys and probabilities as values - a dictionary of the probabilities P(F|Y), with (feature, label) pairs as keys and probabilities as values """ def __init__(self, training_filename, stopword_file): self.attribute_types = set() self.label_prior = {} self.word_given_label = {} # print(self.tuning(training_filename, stopword_file)) self.collect_attribute_types(training_filename) if stopword_file is not None: self.remove_stopwords(stopword_file) self.train(training_filename) # def tuning(self,training_filename,stopword_file): # max_rate = -1 # m_k = [1,1] # for m in range(1, 10): # self.collect_attribute_types(training_filename, m=m) # for n in range(50, 0, -1): # k = n/50 # self.train(training_filename, k) # rate = self.evaluate(sys.argv[2]) # if rate > max_rate: # max_rate = rate # m_k[0] = m # m_k[1] = k # print(m_k,max_rate) # return max_rate, m_k """ A helper function to transform a string into a list of word strings. You should not need to modify this unless you want to improve your classifier in the extra credit portion. """ def extract_words(self, text): no_punct_text = "".join([x for x in text.lower() if not x in string.punctuation]) return [word for word in no_punct_text.split()] """ Given a stopword_file, read in all stop words and remove them from self.attribute_types Implement this for extra credit. """ def remove_stopwords(self, stopword_file): with open(stopword_file, "r", encoding="UTF-8") as f: lines = f.readlines() stop = set() for line in lines: stop.add(line.strip('\n')) self.attribute_types = self.attribute_types.difference(stop) """ Given a training datafile, add all features that appear at least m times to self.attribute_types """ def collect_attribute_types(self, training_filename, m=1): self.attribute_types = set() word_time = {} with open(training_filename, 'r', encoding="UTF-8") as f: for line in f: text = line.split('\t')[1] words = self.extract_words(text) for word in words: if word in word_time: word_time[word] +=1 else: word_time[word] = 1 for word, time in word_time.items(): if time >= m: self.attribute_types.add(word) """ Given a training datafile, estimate the model probability parameters P(Y) and P(F|Y). Estimates should be smoothed using the smoothing parameter k. """ def train(self, training_filename, k=1): self.label_prior = {} self.word_given_label = {} f = open(training_filename, 'r', encoding='UTF-8') lines = f.readlines() for line in lines: label = line.split('\t')[0] text = line.split('\t')[1] self.label_prior[label] = 0 self.label_prior for label in self.label_prior.keys(): for word in self.attribute_types: self.word_given_label[(word, label)] = 0 for line in lines: label = line.split('\t')[0] text = line.split('\t')[1] words = self.extract_words(text) self.label_prior[label] += 1 for word in words: if word in self.attribute_types: self.word_given_label[(word, label)] += 1 for word_label, value in self.word_given_label.items(): label = word_label[1] self.word_given_label[word_label] = (value + k) / (self.label_prior[label] + k * len(self.attribute_types)) for label, value in self.label_prior.items(): self.label_prior[label] = value / len(lines) """ Given a piece of text, return a relative belief distribution over all possible labels. The return value should be a dictionary with labels as keys and relative beliefs as values. The probabilities need not be normalized and may be expressed as log probabilities. """ def predict(self, text): words = self.extract_words(text) beliefs = {} for label in self.label_prior: beliefs[label] = math.log(self.label_prior[label]) for word in words: if (word, label) in self.word_given_label: beliefs[label] += math.log(self.word_given_label[(word, label)]) return beliefs """ Given a datafile, classify all lines using predict() and return the accuracy as the fraction classified correctly. """ def evaluate(self, test_filename): error_count = 0 with open(test_filename, 'r', encoding='UTF-8') as f: lines = f.readlines() for line in lines: label = line.split("\t")[0] text = line.split("\t")[1] beliefs = self.predict(text) prediction_value = max(beliefs.values()) for belief in beliefs: if beliefs[belief] == prediction_value: prediction = belief if label != prediction: error_count += 1 return 1 - error_count / len(lines) if __name__ == "__main__": if len(sys.argv) < 3 or len(sys.argv) > 4: print("\nusage: ./hmm.py [training data file] [test or dev data file] [(optional) stopword file]") exit(0) elif len(sys.argv) == 3: classifier = NbClassifier(sys.argv[1], None) else: classifier = NbClassifier(sys.argv[1], sys.argv[3]) print(classifier.evaluate(sys.argv[2]))
#!/usr/bin/env python import re # This function removes new line & return carriages from tweets def stripNewLineAndReturnCarriage(tweetText): return tweetText.replace('\n', ' ').replace('\r', '').strip().lstrip() # This function is used to remove all the URL's in a tweet def removeURL(tweetText): return re.sub('((www\.[^\s]+)|(https?://[^\s]+))','',tweetText) # This function is used to remove user mentions in a tweet def removeUserMentions(tweetText): return re.sub('@[^\s]+','',tweetText) # This function replaces words with repeating 'n' or more same characters with a single character def replaceRepeatedCharacters(tweetText): return re.sub(r"(.)\1{3,}",r"\1", tweetText) # This function is used to convert multiple white spaces into a single white space def convertMultipleWhiteSpacesToSingleWhiteSpace(tweetText): return re.sub('[\s]+', ' ', tweetText) # This function replaces any hash tag in a tweet with the word def replaceHashTagsWithWords (tweetText): return re.sub(r'#([^\s]+)', r'\1', tweetText) # This function is used to chack if a word occurs in a tweet def isWordInTweet(tweetText, FilterWord, splitBy): flag = False strArray = tweetText.lower().split(splitBy) print strArray for word in strArray: if FilterWord.lower() == word.lower(): flag = True break return flag # This function is used to chack if a word occurs in a tweet def isArrayOfFilterWordsInTweet(tweetText, filterWords, tweetSplitBy, filterWordSplitBy): flag = False wordsArray = tweetText.lower().split(tweetSplitBy) filterWordsArray = filterWords.lower().split(filterWordSplitBy) for word in wordsArray: for filterWord in filterWordsArray: if filterWord.lower() == word.lower(): flag = True break return flag # Extract date from timestamp def extractDateFromTimestamp(timestamp): from dateutil import parser d = parser.parse(timestamp.strip().lstrip()) return str(d.date()) # Extract time from timestamp def extractTimeFromTimestamp(timestamp): from dateutil import parser d = parser.parse(timestamp.strip().lstrip()) return str(d.time()) # Convert String to timestamp def convertStringToTimestamp(timestamp): from dateutil import parser return parser.parse(timestamp.strip().lstrip()) # This function is used to split a string and return an array based on a passed delimiter def splitStringAndReturnArray(text, delimiter): return text.lstrip().strip().split(delimiter) # This function removes items from a list in a tweet text def removeItemsInTweetContainedInAList(tweet_text,stop_words,splitBy): wordsArray = splitStringAndReturnArray(tweet_text,splitBy) StopWords = list(set(wordsArray).intersection(set(stop_words))) return_str="" for word in wordsArray: if word not in StopWords: return_str += word + splitBy return return_str.strip().lstrip() # This function reads a file and returns its contents as an array def readFileandReturnAnArray(fileName, readMode, isLower): myArray=[] with open(fileName, readMode) as readHandle: for line in readHandle.readlines(): lineRead = line if isLower: lineRead = lineRead.lower() myArray.append(lineRead.strip().lstrip()) readHandle.close() return myArray
class Option: def __init__(self, json_list): self.text = '' # the text of the option self.chosen = False # whether this option was chosen by the user self.parse_json(json_list) def parse_json(self, json_list): raise NotImplementedError class MultipleChoiceOption(Option): def __init__(self, json_list): self.is_correct = False # whether this is the correct answer to the question Option.__init__(self, json_list) def parse_json(self, json_list): self.text = json_list[0] if len(json_list) > 1: self.is_correct = json_list[1] else: self.is_correct = False self.chosen = False class SorterOption(Option): def __init__(self, json_list): self.points_toward = '' Option.__init__(self, json_list) def parse_json(self, json_list): self.text = json_list[0] if len(json_list) > 1: self.points_toward = json_list[1] else: self.points_toward = None class Question: def __init__(self, json_dict): self.text = '' # the text of the question self.parse_json(json_dict) def parse_json(self, json_dict): raise NotImplementedError def grade(self): raise NotImplementedError class MultipleChoiceQuestion(Question): def __init__(self, json_dict): self.options = [] self.answered_correctly = False Question.__init__(self, json_dict) def parse_json(self, json_dict): self.text = json_dict['text'] self.options = [] for option_json in json_dict['options']: new_option = MultipleChoiceOption(option_json) self.options.append(new_option) self.answered_correctly = False def grade(self): self.answered_correctly = True for option in self.options: print("{}: {} {}".format(option.text, option.is_correct, option.chosen)) if option.is_correct != option.chosen: self.answered_correctly = False break return self.answered_correctly class SorterQuestion(Question): def __init__(self, json_dict): self.options = [] Question.__init__(self, json_dict) def parse_json(self, json_dict): self.text = json_dict['text'] self.options = [] for option_json in json_dict['options']: new_option = SorterOption(option_json) self.options.append(new_option) def grade(self): results = [] for option in self.options: if option.chosen: results.extend(option.points_toward) return results class Quiz: def __init__(self, json_dict): self.questions = [] self.name = '' self.description = '' self.style_name = '' self.question_type = '' self.tags = [''] # the empty string allows for filtering for all quizzes when tag = '' self.id = '' self.likes = 0 self.highscore = {} self.parse_json(json_dict) def make_new_question(self, question_json): raise NotImplementedError def parse_json(self, json_dict): self.name = json_dict['name'] self.description = json_dict.get('description', '') self.style_name = json_dict.get('style_name', 'style') self.tags.extend(json_dict.get('tags', '')) self.questions = [] for question_json in json_dict['questions']: new_question = self.make_new_question(question_json) # new_question = Question(question_json) self.questions.append(new_question) self.question_type = json_dict.get('question_type', 'checkbox') # ['checkbox', 'radio', 'text'] def get_num_questions(self): return len(self.questions) def check_quiz(self, answers): raise NotImplementedError def get_number_correct(self): return 0 def get_template(self): raise NotImplementedError
class MaxHeap: def __init__(self, items=[]): self.name = None super().__init__() self.heap = [0] for i in items: self.heap.append(i) self.__floatUp(len(self.heap) - 1) def insert(self, data): self.heap.append(data) self.__floatUp(len(self.heap) - 1) def peek(self): if self.heap[1]: return self.heap[1] else: return False def delMax(self): if len(self.heap) > 2: self.__swap(1, len(self.heap) - 1) max = self.heap.pop() self.__bubbleDown(1) elif len(self.heap) == 2: max = self.heap.pop() else: max = False return max def getMax(self): if len(self.heap) > 2: max = self.heap[1] elif len(self.heap) == 2: max = self.heap[2] else: max = False return max def __swap(self, i, j): self.heap[i], self.heap[j] = self.heap[j], self.heap[i] def __floatUp(self, index): parent = index // 2 if index <= 1: return elif self.heap[index] > self.heap[parent]: self.__swap(index, parent) self.__floatUp(parent) def __bubbleDown(self, index): left = index * 2 right = index * 2 + 1 largest = index if len(self.heap) > left and self.heap[largest] < self.heap[left]: largest = left if len(self.heap) > right and self.heap[largest] < self.heap[right]: largest = right if largest != index: self.__swap(index, largest) self.__bubbleDown(largest) def insertnumbersinheap(aheap, alist): for i in range(len(alist)): aheap.insert(alist[i]) return aheap def maxelement(aheap): maxnodevalue = aheap.getMax() return maxnodevalue def delmaxelement(aheap): aheap.delMax() def genrandomnumbers(length, maxval): # GENERATE length RANDOM NUMBERS IN RANGE 1-maxval string = "" for n in range(length): string += str(randint(1, maxval)) + " " L = list(map(int, string.split())) return L def gettime(funcname, param, param2): if param2 == "": fn = funcname.__name__ + "(" + param.name + ")" else: fn = funcname.__name__ + "(" + param.name + "," + str(param2) + ")" setpar = "from __main__ import " + funcname.__name__ + "," + param.name t1 = Timer(fn, setpar) time = str(t1.timeit(1)) + " " return time def writef(filename, myres): with open(filename, "w") as f: text = myres f.write('{}'.format(text)) return def readf(filename): with open(filename, "r") as f: r_n = f.readline() return r_n from timeit import Timer # import timeit import random from random import randint import os import matplotlib.pyplot as plt import matplotlib.patches as mpatches # import math if __name__ == '__main__': path = os.path.dirname(os.path.realpath(__file__)) os.chdir(path) if not os.path.exists("Data"): os.makedirs("Data") os.chdir(path + "\Data") maxpoweroften = 6 numberoftests = 5 maxvalue = 10000000 filenames = ["maxheapinsertion", "maxheapfindmax", "maxheapdelmax"] insertion_times = "" findmax_times = "" delmaxelement_times = "" for nrtest in range(numberoftests): for dim in [10 ** p for p in range(1, maxpoweroften + 1)]: L = genrandomnumbers(dim, maxvalue) myheap = MaxHeap() myheap.name="myheap" time = gettime(insertnumbersinheap, myheap, L) insertion_times += time time = gettime(maxelement,myheap, "") findmax_times += time time = gettime(delmaxelement, myheap, "") delmaxelement_times += time insertion_times += "\n" findmax_times += "\n" delmaxelement_times += "\n" writef("maxheapinsertion.txt", insertion_times) writef("maxheapfindmax.txt", findmax_times) writef("maxheapdelmax.txt", delmaxelement_times) for filein in filenames: filename = filein + ".txt" t = [] with open(filename, "r") as f: for i in range(numberoftests): t.append(list(map(float, f.readline().split()))) meantimes = [] for j in range(maxpoweroften): sumt = sum(t[i][j] for i in range(numberoftests)) meantimes.append(sumt / numberoftests) if filein == "maxheapinsertion": insertiontimes = meantimes elif filein == "maxheapfindmax": maxheaptimes = meantimes elif filein == "maxheapdelmax": delmaxtimes = meantimes N = [10 ** p for p in range(1, maxpoweroften + 1)] fig = plt.figure() plt.plot(N, insertiontimes, "vb--") plt.plot(N, maxheaptimes, "vg--") plt.plot(N, delmaxtimes, "vc--") plt.xscale('log', basex=10) plt.yscale('log', basey=10) plt.title("Max Heap") plt.xlabel("Length of list of random numbers") plt.ylabel("Times") blue_patch = mpatches.Patch(color = "blue", label = "Max Heap- Insertion") green_patch = mpatches.Patch(color = "green", label = "Max Heap- Get the max ") cyan_patch = mpatches.Patch(color = "cyan", label = "Max Heap- Delete the max") plt.legend(handles = [blue_patch, green_patch, cyan_patch]) axes = plt.gca() axes.set_ylim([10**(-6), 10**2]) fig.savefig("Max Heap.png")
import turtle class WinTurtle: def checkWin(grid): diags = ((0, 4, 8), (2, 4, 6)) for n in range(3): test = grid[n] test2 = grid[n + 3] test3 = grid[n + 6] if test != '_': if test == test2 == test3: if test == 'x' or test == 'o': return True for j in range(0, 7, 3): test = grid[j] test2 = grid[j + 1] test3 = grid[j + 2] if test != '_': if test == test2 == test3: if test == 'x' or test == 'o': return True for tup in diags: test = grid[tup[0]] test2 = grid[tup[1]] test3 = grid[tup[2]] if test != '_': if test == test2 == test3: return True return False def isDraw(grid): if '_' not in grid: TicTacToe.checkWin(grid) if not TicTacToe.checkWin(grid): print('It is a draw!') return True else: return False def drawLine(self, grid, cellsize, triplets, diags, rows, columns): for trip in triplets: test1 = grid[trip[0]] test2 = grid[trip[1]] test3 = grid[trip[2]] self.t.width(3) self.t.color('red') self.t.hideturtle() if test1 == test2 == test3 and test1 != '_': if trip in rows: winRow = trip[0] self.t.up() self.t.home() self.t.lt(90) self.t.fd((2.5 - winRow // 3) * cellsize) self.t.rt(90) self.t.down() self.t.fd(3 * cellsize) if trip in columns: winCol = trip[0] self.t.up() self.t.home() self.t.fd((0.5 + winCol % 3) * cellsize) self.t.lt(90) self.t.down() self.t.fd(3 * cellsize) if trip == diags[0]: self.t.up() self.t.home() self.t.lt(90) self.t.fd(3 * cellsize) self.t.rt(135) self.t.down() self.t.fd(cellsize * 4.5) elif trip == diags[1]: self.t.up() self.t.home() self.t.fd(3*cellsize) self.t.lt(90) self.t.fd(3*cellsize) self.t.lt(135) self.t.down() self.t.fd(4.5 * cellsize)
# Given an array of integers, find two numbers such that they add up to a specific target number. # The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (# both index1 and index2) are not zero-based. # You may assume that each input would have exactly one solution. # Input: numbers={2, 7, 11, 15}, target=9 # Output: index1=1, index2=2 # LeetCode: Two Sum, Algorithm Question #1 class Solution(object): ## Linear search solution # Leetcode rank: 89.15%, time: 40ms # enumerate Array = [3, 5, 2, 1, 4, 7] # enumerate(Array) def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ processed = {} for i in range(0, len(nums)): if target-nums[i] in processed: return [processed[target-nums[i]]+1,i+1] processed[nums[i]]=i ''' ## Sorting and Search Solution # Leetcode rank: 52.58%, time: 48ms # enumerate Array = [3, 5, 2, 1, 4, 7] # enumerate(Array) # [(0, 3), (1, 5), (2, 2), (3, 1), (4, 4), (5, 7)] # lambda: # Defining a function to return the second element of an array of a tuple # g = lambda x: x(1) # g((0, 4)) = 4 # sorted(array, key) # Here, key is to sort with the second element of a tuple in the enumerated array. def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ L = sorted(enumerate(nums), key=lambda x:x[1]) i = 0; j = len(nums)-1 while i < j: if L[i][1]+L[j][1] == target: if L[i][0] < L[j][0]: return L[i][0]+1, L[j][0]+1 else: return L[j][0]+1, L[i][0]+1 elif L[i][1]+L[j][1] > target: j -= 1 else: i += 1 return -1,-1 ''' sol = Solution() ## Question Test nums = [2, 7, 11, 15] target = 9 index1, index2 = sol.twoSum(nums, target) print index1, index2
# def outer_func(): # message = 'Hi' # def inner_func(): # print(message) # return inner_func def outer_func(msg): message = msg def inner_func(): print(message) return inner_func i_f = outer_func('Hi') i_f_2 = outer_func('Hello') print(i_f) print(i_f.__name__) # inner_funct still has acces to message variable i_f() i_f_2()
# Jared Spector # 08/22/2021 # This program plays the classic Rock, Paper, Scissors game with the user. # The user makes a choice and then indicates the number of times the # computer should make a choice. The results of all games played are # shown along with a summary of results. import random # Constants WIN = 1 LOSE = 2 TIE = 3 ROCK = 0 PAPER = 1 SCISSORS = 2 def main(): choices = ['rock', 'paper', 'scissors'] print("Let's play Rock Paper Scissors!") print() user_choice = get_user_choice() number_plays = get_number_plays() print(f'User chooses {choices[user_choice]}') wins = 0 ties = 0 losses = 0 for i in range(number_plays): computer_choice = random.randint(0, 2) print(f'Game {i + 1}: {choices[user_choice]} vs. {choices[computer_choice]} - ', end='') result = declare_results(user_choice, computer_choice) if result == WIN: print('Player wins!') wins += 1 elif result == TIE: print('Tie') ties += 1 else: # LOSE print('Player loses.') losses += 1 print(f"Results for Player: {wins} wins, {losses} losses, {ties} ties") def get_user_choice(): """ This function asks whether the player chooses Rock, Paper, or Scissors for their play. It will be used in all the games with the computer. :return: user_choice """ while True: try: user_choice = int( input('Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ')) if user_choice not in [1, 2, 3]: raise ( ) except: print('You choice should be 1, 2, or 3.') else: user_choice -= 1 # account for zero-indexing break return user_choice def get_number_plays(): """ This function asks for the number of times the computer should play the game against the player's choice. :return: number_plays """ while True: try: number_plays = int( input("How many times for computer to choose (1-50): ")) if number_plays < 1 or number_plays > 50: raise () except: print("Choose a number between 1 and 50.") else: break return number_plays def declare_results(user_choice, computer_choice): """ This function determines whether a player wins against the computer. :param user_choice:Choice made by player :param computer_choice:Choice made by computer :return:result of game """ win_combos = [(ROCK, SCISSORS), (PAPER, ROCK), (SCISSORS, PAPER)] if (user_choice, computer_choice) in win_combos: return WIN elif (computer_choice, user_choice) in win_combos: return LOSE else: return TIE main()
#!/usr/bin/python from sets import Set # Minglish lesson # =============== # # Welcome to the lab, minion. Henceforth you shall do the bidding of Professor Boolean. Some say he's mad, trying to develop a zombie serum and all... but we think he's brilliant! # # First things first - Minions don't speak English, we speak Minglish. Use the Minglish dictionary to learn! The first thing you'll learn is how to use the dictionary. # # Open the dictionary. Read the page numbers, figure out which pages come before others. You recognize the same letters used in English, but the order of letters is completely different in Minglish than English (a < b < c < ...). # # Given a sorted list of dictionary words (you know they are sorted because you can read the page numbers), can you find the alphabetical order of the Minglish alphabet? For example, if the words were ["z", "yx", "yz"] the alphabetical order would be "xzy," which means x < z < y. The first two words tell you that z < y, and the last two words tell you that x < z. # # Write a function answer(words) which, given a list of words sorted alphabetically in the Minglish alphabet, outputs a string that contains each letter present in the list of words exactly once; the order of the letters in the output must follow the order of letters in the Minglish alphabet. # # The list will contain at least 1 and no more than 50 words, and each word will consist of at least 1 and no more than 50 lowercase letters [a-z]. It is guaranteed that a total ordering can be developed from the input provided (i.e. given any two distinct letters, you can tell which is greater), and so the answer will exist and be unique. # # Languages # ========= # # To provide a Python solution, edit solution.py # To provide a Java solution, edit solution.java # # Test cases # ========== # # Inputs: # (string list) words = ["y", "z", "xy"] # Output: # (string) "yzx" # # Inputs: # (string list) words = ["ba", "ab", "cb"] # Output: # (string) "bac" def answer(words): # Build the grap and keep track of entry points graph, start = dag(words) # Place to store the final alphabet alphabet = [] # Place to store nodes we have visited whe traversign the graph (Depth First) visited = Set() # Visit the nodes def visit(node): # If node has not been visited if node not in visited: # Mark it as visited visited.add(node) # If node is in graph if node in graph: # Visit each of this nodes edges for edge in graph[node]: visit(edge) alphabet.insert(0, node) # For each node in the entry point set... This should be only ONE node becuase the question stated there is a single unique solution. for node in start: visit(node) # Return the alphabet return ''.join(alphabet) def dag(words): # The graph graph = {} # Where to enter the graph start = Set() def find_edge(word1, word2): # look over the letter pairs (shorter word of course) for l in range(min(len(word1), len(word2))): # if letters do not match, we found a new edge connection if word1[l] != word2[l]: # Keep track of possible entry points start.add(word1[l]) start.add(word2[l]) # return the edge return word1[l], word2[l] for i in range(len(words) - 1): # make sure the graph will contain all nodes if not graph.has_key(words[i]): graph[words[i]] = Set() if not graph.has_key(words[i+1]): graph[words[i+1]] = Set() # Find an edge edge = find_edge(words[i], words[i+1]) # If we found an edge, make sure to add it if edge is not None: a,b = edge # Dont forget to remove the edge node from the potential starting points list if b in start: start.remove(b) # If node is already in graph, add the edge if a in graph: graph[a].add(b) # If not, add them both... this might be redundant... else: graph[a] = Set(b) # Return teh graph and start position return graph, start words = ["y", "z", "xy"] # output = "yzx" words1 = ["z", "yx", "yz"] # output = "xzy" words2 = ["ba", "ab", "cb"] # output = "bac" words3 = ["bbc", "bac", "cba"] # output = "bac" print(answer(words1))
#!/bin/python import sys import random import os print 'Guess Number between 1 - 10' print 'You have 5 attempts !!' guess=random.randint(0,10) j=5 i=0 while i < j : num = input('Enter your Guess : ') if num < guess: print 'YOUR GUESS IS LOWER' i+=1 elif num > guess: print 'YOUR GUESS IS HIGHER' i+=1 elif num == guess : print 'YOU ARE RIGHT ! YOU WON' break
import numpy arr=array([45,97,6],[154,5557,175]) print(arr) from array import * #array build from user input import sys ip=['192.168.50.45','192.168.50.46'] for i in ip: print (i) arr=array('i',[]) size=int(input('hi user how many numbers u want : ')) for i in range(size): print (i+1, end=" ") x=int(input("Enter ur value : ")) arr.append(x) print (arr) # vals = array('i',[455,79,9,64,78]) # newvals = array(vals.typecode(a for a in vals)) # for i in range(len(vals)): # print (newvals[i])
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min = [] def push(self, val): """ :type val: int :rtype: None """ if len(self.min) == 0: self.min.append(val) else: idx = len(self.min) - 1 insert = False while idx >= 0: if self.min[idx] > val: insert = True self.min.insert(idx + 1, val) break idx -= 1 if insert is False: self.min.insert(0, val) self.stack.append(val) def pop(self): """ :rtype: None """ val = self.stack.pop() self.min.remove(val) def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ return self.min[-1] minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) print(minStack.getMin()) print(minStack.pop()) print(minStack.top()) print(minStack.getMin()) # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
#Write a function taking in a string like WOW this is REALLY amazing and returning Wow this is really amazing. String should be capitalized and properly spaced. Using re and string is not allowed. def filter_words(st): # Your code here. text = " ".join(st.split()) return text.capitalize() print(filter_words("HELLO world")) #text = "HELLO world" #text1 = " ".join(text.split()) #print(text1.capitalize())
#1. Напишіть програму, яка пропонує користувачу ввести ціле число і визначає чи це число парне чи непарне, чи введені дані коректні. num = int(input("PLease put the number: ")) def digit(num): try: if num%2 == 0 : return "This is the even number" return "this is the odd number" except ValueError as e : return e print(digit(num)) #2. class CustomError(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) def person_age(): try: num = int(input("PLease put your age: ")) if num < 1: raise CustomError("Your age can't be less than 1") return digit(num) except CustomError as e: print("We obtain error:", e.data) print(person_age())
#2. Написати скрипт, який перевірить чи введене число парне чи непарне і вивести відповідне повідомлення. num= int(input("please enter the number : ")) if num%2 == 0: print("This number {} is even". format(num)) else: print("This number {} is odd". format(num))
#1. Спробуйте переписати наступний код через map. Він приймає список реальних імен і замінює їх хеш-прізвищами, використовуючи більш надійний метод-хешування. names = ['Sam', 'Don', 'Daniel'] for i in range(len(names)): names[i] = hash(names[i]) print(names) print(map(lambda i: hash(names[i]), names)) print(list(map(hash, names))) # => [6306819796133686941, 8135353348168144921, -1228887169324443034] #3. Всі ці числа в списку мають стрічковий тип даних, наприклад [‘1’,’2’,’3’,’4’,’5’,’7’], перетворити цей список в список, всі числа якого мають тип даних integer: #1) використовуючи метод append #2) використовуючи метод map str_list = ['1','2','3','4','5','7'] str_list1= [] for x in str_list: str_list1.append(int(x)) print(str_list1) print(list(map(int,str_list))) #44. Перетворити список, який містить милі , в список, який містить кілометри (1 миля=1.6 кілометра) #a) використовуючи функцію map # b) використовуючи функцію map та lambda miles = [1,4,5,4] def mile (x): return x *1.6 print(list(map(mile, miles))) print(list(map(lambda x: x*1.6, miles)))
upper = 0 lower = 0 digit = 0 num = 0 space = 0 spaceU = 0 res = "si" res2 = "si" nombre = {} #Function that prompts the user for his or her name def nombre_u(): global nombre name = input("\nIntroduce your name: ") nombre = name print("\nFuck, what a great name") usuario() #Function that requests a user and validates that it has no spaces. def usuario(): #function to repeat the cycle if the user is invalid def repite(): global res2 while res2 == "yes": autentica() imprime() contraseña() #Function that request the user def pide_usuario(): usu = input("Introduce an user: ") return usu #function que autentica que no tenga espacios def autentica(): global spaceU user = pide_usuario () luser = len(user) for pos in range (0,luser): if user[pos].isspace() == True: spaceU += 1 #function that warns if it has spaces def imprime(): global spaceU global res2 if spaceU == 0: print ("Valid User") res2 = "no" else: print("There are spaces") print("Invalid user") spaceU -= spaceU repite() #function requesting and authenticating the password def contraseña(): #function to repeat the cycle if the password is invalid def repite(): global res while res == "yes": autentica() imprime() respuesta_n() #Function asking for password def pide_contraseña(): print(''' Remember that your password must contain at least - a capital letter - a lower case letter - a number - a symbol - minimum 8 digits ''') cont = input("Introduce a password: ") return cont #function that authenticates the password def autentica(): global upper global lower global digit global num global space psw = pide_contraseña () lpsw = len(psw) if lpsw >=8: for pos in range (0,lpsw): if psw[pos].isupper() == True: upper += 1 elif psw[pos].islower() == True: lower += 1 elif psw[pos].isalnum() == True: num += 1 elif psw[pos].isspace() == True: space += 1 else: digit += 1 else: print("There's no enough characters") #function that warns if the password is wrong def imprime(): global upper global lower global digit global num global space global res if upper >= 1: if lower >= 1: if digit >=1: if num >=1: if space == 0: print ("Valid Password") res = "no" else: print("There's spaces") print("Invalid password") else: print("There's no numbers") print ("Invalid password") else: print("There's no symbols") print ("Invalid password") else: print("There's no lower case") print ("Invalid password") else: print("There's no upper case") print ("Invalid password") repite() #welcoming function def bienvenida_total(): print(''' !Bloody Math, Son! ''') print(''' Welcome to bloody maths, son, a game in which you will not only learn about math. We hope you have fun! But first...''') nombre_u() #function to stop or end the program def respuesta_n(): respuesta = "yes" while respuesta == "yes": menu() respuesta = input("Wanna play again?: ") print("See you soon!") input("Press ENTER to exit") respuesta = "no" #function prompting the user for the menu option def menu(): print(''' Now, to decide... 1) Review division with decimal point. 2) Review division of fractions 3) Go straight to levels ''') opc = int(input("What option would you like to choose?: ")) if opc == 1 or opc == 2 or opc == 3: desvio(opc) else: print("Invalid number") respuesta_n() #Option that sends the user's answer to the menu def desvio(opcion): if opcion == 1: divisiones_con_decimales() elif opcion == 2: divisiones_con_fracciones2() else: nivel1() #Function that activates the explanation of divisions with a decimal point. def divisiones_con_decimales(): #Function welcoming explanation def hola(): hello = open("hola.txt","r",encoding="utf8") holi = hello.read() print(holi) cual() #function asking the user for the case he/she wants to see def cual(): opcion = input("\nWhich case do you wanna see?: ") print("") casos(opcion) #Function to continue viewing cases def seguir(): ans = input("Do you wish to continue checking cases?: ") if ans.lower() == "Yes" or ans == "yes": cual() else: print("Returning to main menu") menu() #Function that filters the option chosen by the user. def casos(caso): if caso >= "1" and caso <= "5": if caso == "1": uno() elif caso == "2": dos() elif caso == "3": tres() elif caso == "4": cuatro() else: todo() else: print("Invalid option, try again") cual() #Function explaining all cases def todo(): expli = open("todos.txt","r",encoding="utf8") todoo = expli.read() print(todoo) seguir() #Function explaining the first case def uno(): caso1 = open("uno.txt","r",encoding="utf8") unoo = caso1.read() print(unoo) seguir() #Function explaining the second case def dos(): caso2 = open("dos.txt","r",encoding="utf8") doss = caso2.read() print(doss) seguir() #Function explaining the third case def tres(): caso3 = open("tres.txt","r",encoding="utf8") tress = caso3.read() print(tress) seguir() #Function explaining the fourth case def cuatro(): caso4 = open("cuatro.txt","r",encoding="utf8") cuatroo = caso4.read() print(cuatroo) seguir() hola() #Function for the explanation of division of fractions def divisiones_con_fracciones2(): #function that welcomes, asks for the case to choose and filters it def divisiones_con_fracciones(): welcome = open("bienvenida.txt", "r", encoding = "UTF8") bienvenida = welcome.read() print(bienvenida) options = open("opciones.txt", "r", encoding = "UTF8") opciones = options.read() print(opciones) opcion = int(input("\nWhich option do you wish to check? ")) print("") if opcion == 1: multiplicacion_en_cruz() print(" ") continuar_o_niveles() elif opcion == 2: invertir_y_multiplicar() print(" ") continuar_o_niveles() elif opcion == 3: ambos_metodos() print("") continuar_o_niveles() else: print("That is not an option") print(" ") #show explanation for case1 def multiplicacion_en_cruz(): first = open("multiplicacionEnCruz.txt", "r", encoding = "UTF8") primera = first.read() print(primera) #show explanation for case2 def invertir_y_multiplicar(): second = open("invertirYMultiplicar.txt", "r", encoding = "UTF8") segunda = second.read() print(segunda) #show explanation for both cases def ambos_metodos(): multiplicacion_en_cruz() invertir_y_multiplicar() #function to continue choosing cases or go to game levels def continuar_o_niveles(): c = open("continuar.txt", "r", encoding = "UTF8") conti = c.read() print(conti) continuar = int(input("\nWhich option do you wanna choose?: ")) if continuar == 1: menu() elif continuar == 2: print("") divisiones_con_fracciones() elif continuar == 3: nivel1() else: print("That's not an option") print(" ") divisiones_con_fracciones() #Level 1 of the game def nivel1(): #indications of the game def indicaciones(): indications = open("indicaciones.txt", "r", encoding = "UTF8") indicaciones = indications.read() print(indicaciones) ejercicio1() #LEVEL 1 def ejercicio1(): print("\nNivel 1: \n(1/6)/(5/9)") respuesta1 = input("\nWhat is the result?: ") if respuesta1 == "9/30" or respuesta1 == "3/10": print("¡Correct!") nivel2() else: print("Incorrect answer") print("") ejercicio1() indicaciones() #lEVEL 2 def nivel2(): print("\nNivel 2: \n2.35/5") respuesta1 = float(input("\nWhat is the result?: ")) if respuesta1 == .47: print("¡Correct!") nivel3() else: print("Incorrect answer") print("") nivel1() #lEVEL 3 def nivel3(): print("\n¡Nivel3!, You are halfway there\n(347/38)/(255/32): ") resp = input("What is the simplified resultant fraction?: ") if resp == "5552/4845": print("HERO") nivel4() else: print("Nooooo, comeee baaaackkk") nivel2() #LEVEL 4 def nivel4(): print("\nYA NIVEL 4 WUUUU\n345.654/32.987") resp = float(input("What is the result of the division? Round to 3 decimal places: ")) if resp == 10.478 or resp == 10.479: print("HERO") nivel5() else: print("Noooooo, comeee baaackk") nivel3() #LEVEL 5 def nivel5(): #Displays the level problem def cinco(): print("\nNIVEL 5") notanfeo = open("decimalnotanfeo.txt","r",encoding="utf8") notanfeoo = notanfeo.read() print(notanfeoo) cincoans() #asks for level response and filters it def cincoans(): respues = float(input("Introduce your answer: ")) #correct answer: 344.38 if respues == 344.38: print("\n¡Correct, You go to next level :)\n") nivel6() #Send this level to Call else: print("\nInvalid answer.\nyou return to the previous level.\n") #And here it returns to the previous level nivel4() cinco() #LEVEL 6 def nivel6(): #Displays the level problem def seis(): print("\nNIVEL 6") feo = open("decimalfeo.txt","r",encoding="utf8") feoo = feo.read() print(feoo) seisans() #ask and filter the answer def seisans(): respuest = float(input("Introduce your answer: ")) #correct answer: 49.81 if respuest == 49.81: print("\n¡Correct! You have completed Bloody maths, son! :)\n") #CERTIFICATE certificado() else: print("\nWrong answer. You return to the previous leveL.\n") #And here it returns it to the previous level nivel5() seis() #function that provides a certificate to the user def certificado(): global nombre input("Press ENTER to view your certificate") print(f''' -------------------------------------------------------------------------------- DIPLOMA Bloody Maths, son! is proud to award this diploma to: {nombre} for having successfully completed all 6 levels of the game. MANY CONGRATULATIONS And never forget... Bloody Maths, SON! -------------------------------------------------------------------------------- ''') #End of the program #Calling to function bienvenida_total()
import random import time random = random.sample(range(20), 20) # range of 20 items including the numbers from 0 to 20 print(random) searching_for = 15 def linear_search(arr, target): # Your code here for i in range(0, len(arr)): if arr[i] == target: return i return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): #Your code here first = 0 last = len(arr) - 1 while first <= last: # Find the middle of the data. mid = (first + last) // 2 if arr[mid] == target: return mid else: if target < arr[mid]: last = mid - 1 else: first = mid + 1 return -1 # not found print("Linear Search =", linear_search(random, searching_for)) #print(binary_search([2, 4, 6, 4, 67, 988, 43, 56], [10])) print("Binary Search =", binary_search(random, searching_for))
import json from queue import PriorityQueue # dictionaries of json files energy_cost_btw_2_nodes_dictionary = {} dist_btw_2_nodes_dictionary = {} # this is for g(n) graph_dictionary = {} # this is to find neighbours of node def convert_json_files_to_dictionaries(): f = open('Cost.json', ) global energy_cost_btw_2_nodes_dictionary energy_cost_btw_2_nodes_dictionary = json.load(f) f = open('Dist.json', ) global dist_btw_2_nodes_dictionary dist_btw_2_nodes_dictionary = json.load(f) f = open('G.json', ) global graph_dictionary graph_dictionary = json.load(f) class Node: # generated_nodes_dictionary will have Nodes as values expanded : bool = False def __init__(self, path_cost_from_starting_node_to_current_node : int, previous_node : str, energy_cost_from_starting_node_to_current_node : int) -> None: self.path_cost_from_starting_node_to_current_node = path_cost_from_starting_node_to_current_node self.previous_node = previous_node self.energy_cost_from_starting_node_to_current_node = energy_cost_from_starting_node_to_current_node def uniform_cost_search_2(start_node : str, end_node : str, energy_budget : int): # Impt Data Structures nodes_to_expand : PriorityQueue = PriorityQueue() # node with the lowest distance will be expanded generated_nodes_dictionary = {} # Set up starting node nodes_to_expand.put((0, start_node)) # first element is f(n)/total cost, second element is node_label generated_nodes_dictionary[start_node] = Node(0, "0", 0) while nodes_to_expand.not_empty: current_expanded_node = nodes_to_expand.get()[1] generated_nodes_dictionary[current_expanded_node].expanded = True # terminating condition if current_expanded_node == end_node: break # get neighbours of current_expanded_node neighbours_of_expanded_node = graph_dictionary[current_expanded_node] for i in neighbours_of_expanded_node: # don't explore expanded nodes, prevents traversal of nodes from looping if generated_nodes_dictionary.get(i) is not None and generated_nodes_dictionary.get(i).expanded: continue # g(n) path_cost_from_starting_node_to_neighbour = generated_nodes_dictionary[current_expanded_node].path_cost_from_starting_node_to_current_node two_nodes_string : str = current_expanded_node + "," + i path_cost_from_starting_node_to_neighbour += dist_btw_2_nodes_dictionary[two_nodes_string] # energy cost energy_cost_from_starting_node_to_neighbour = generated_nodes_dictionary[current_expanded_node].energy_cost_from_starting_node_to_current_node energy_cost_from_starting_node_to_neighbour += energy_cost_btw_2_nodes_dictionary[two_nodes_string] if energy_cost_from_starting_node_to_neighbour > energy_budget: continue if generated_nodes_dictionary.get(i) is not None: if path_cost_from_starting_node_to_neighbour < generated_nodes_dictionary[i].path_cost_from_starting_node_to_current_node: # you found a better route to node i!! # update node i in generated_nodes_dictionary generated_nodes_dictionary[i].path_cost_from_starting_node_to_current_node = path_cost_from_starting_node_to_neighbour generated_nodes_dictionary[i].previous_node = current_expanded_node generated_nodes_dictionary[i].energy_cost_from_starting_node_to_current_node = energy_cost_from_starting_node_to_neighbour # update node i in nodes_to_expand by # popping out the elements in nodes_to_expand into temp_list to find node i # afterwards push all the elements from temp_list back to nodes_to_expand temp_list = [] while not nodes_to_expand.empty(): next_item = nodes_to_expand.get() if next_item[1] == i: # update the node i's totalcost updated_node = (path_cost_from_starting_node_to_neighbour, i) temp_list.append(updated_node) break temp_list.append(next_item) for x in temp_list: nodes_to_expand.put(x) else: nodes_to_expand.put((path_cost_from_starting_node_to_neighbour, i)) # update generated_nodes_dictionary with neighbour node's info generated_nodes_dictionary[i] = Node(path_cost_from_starting_node_to_neighbour, current_expanded_node, energy_cost_from_starting_node_to_neighbour) shortest_path = [end_node] current_node = shortest_path[0] while True: node_to_backtrack_to = generated_nodes_dictionary[current_node].previous_node if node_to_backtrack_to == "0": break else: shortest_path.append(node_to_backtrack_to) current_node = node_to_backtrack_to print("Shortest path: ", end = "") for node_label in shortest_path[::-1]: if node_label != end_node: print(node_label + "->", end = "") else: print(node_label + ".") print() print("Shortest distance: " + str(generated_nodes_dictionary[end_node].path_cost_from_starting_node_to_current_node) + ".") print("Total energy cost: " + str(generated_nodes_dictionary[end_node].energy_cost_from_starting_node_to_current_node) + ".") def main(): convert_json_files_to_dictionaries() uniform_cost_search_2("1", "50", 287932) if __name__ == "__main__": main()
from math import * max_sols = 0 best_p = 0 # the shortest side can be no larger than 'a' where # a^2 + a^2 = req_primes^2 and a + a + req_primes = p # solving gives a = .5(2p - sqrt(2)*p) for p in range(1, 1001): max_pos_shortest = floor(.5*(2*p - sqrt(2)*p)) sols = 0 for a in range(1, max_pos_shortest + 1): #the shortest side b = p*(2*a-p)/(2*(a-p)) req_primes = -(2*pow(a,2)-2*a*p+pow(p,2))/(2*a-2*p) if pow(int(a),2) + pow(int(b),2) == pow(int(req_primes),2): sols += 1 if sols > max_sols: max_sols = sols best_p = p print(best_p) print(max_sols)
''' Function to take a integer and returns its string equivalent ''' def itos(int1): if type(int1) == str: print(f'Enter an integer, {int1} is a string.') else: if isinstance(int1, float): raise ValueError('Input an integer not a float') elif isinstance(int1, int): print(f"'{int1}'") # Example itos(78) # calling the function ''' Function to take a string of floats and return its integer equivalent ''' def stof(strg): if isinstance(strg, int) or isinstance(strg, float): print(f'Enter a string of float, {strg} is not a string') else: print(strg) # Example stof('45.67') # calling the function ''' Function to take a float and return its string equivalent ''' def ftos(input): if isinstance(input, int) or isinstance(input, str): print(f'Enter a float, {input} is not a float') else: print(f"'{input}'") # Example ftos(78.89) # calling the function ''' Function to take a string of float and return its float equivalent ''' def stof(strg): alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','u','v','w','x','y','z'] if isinstance(strg, int) or isinstance(strg, float): print(f'Enter a string of float, {strg} is not a string') else: if '.' not in strg: sum1 = 0 for i in alphabets: if i in strg: sum1 = sum1 + 1 if sum1 >= 1: print(f'Input is not a float, contains letters') else: raise ValueError('This is an integer string') else: print(strg) stof('45.67')
imiona = ['Artur', 'Barbara', 'Czesław'] print(imiona) indeks = int(input('Proszę podać indeks imienia do skasowania: ')) if indeks < len(imiona): print('Kasowane imię to:', imiona[indeks]) del imiona[indeks] else: print('Nie ma elementu o takim indeksie') print(imiona)
imiona = ['Artur', 'Barbara', 'Czesław'] print(imiona) nowe_imie = input('Proszę podać nowe imię: ') imiona.append(nowe_imie) print(imiona) imiona[0] = 'Guido' print(imiona)
from datetime import datetime poczatek = datetime.now() input('Naciśnij ENTER') pierwszy_stop = datetime.now() pierwsza_roznica = pierwszy_stop - poczatek print(f'Naciśnięto ENTER po {pierwsza_roznica} sekundach.') input('Naciśnij ENTER') drugi_stop = datetime.now() druga_roznica = drugi_stop - pierwszy_stop print(f'Naciśnięto ENTER po {druga_roznica} sekundach.') if pierwsza_roznica < druga_roznica: print('Za pierwszym razem naciśnięto szybciej!') else: print('Za drugim razem naciśnięto szybciej!')
lista = [1, 2, 'jakiś tekst', True, None, [1, 2, 3]] for element in lista: print('element:', element, ' typu:', type(element))