blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c5dfcc04363ad648a1c53eb8223afa1d7f63f41d
111110100/my-leetcode-codewars-hackerrank-submissions
/leetcode/minStack.py
4,021
4.03125
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] def push(self, val: int) -> None: self.stack.append(val) return def pop(self) -> None: self.stack.pop() return def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return min(self.stack) class MinStack2: def __init__(self): """ initialize your data structure here. """ self.stack = [] def push(self, val: int) -> None: if self.stack: m = min(val, self.stack[-1][0]) self.stack.append((m, val)) else: self.stack.append((val, val)) return def pop(self) -> None: self.stack.pop()[1] return def top(self) -> int: return self.stack[-1][1] def getMin(self) -> int: return self.stack[-1][0] class MinStack3(object): def __init__(self): """ initialize your data structure here. """ self.lst = [] self.min = float("inf") def push(self, val): """ :type val: int :rtype: None """ if (not self.lst): self.lst.append(val) self.min = val else: if (val < self.min): self.min = val self.lst.append(val) def pop(self): """ :rtype: None """ result = self.lst[-1] self.lst = self.lst[:-1] if (result == self.min and self.lst): self.min = min(self.lst) return result def top(self): """ :rtype: int """ return self.lst[-1] def getMin(self): """ :rtype: int """ return self.min class MinStack4: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minStack = [] def push(self, val: int) -> None: self.stack.append(val) if not self.minStack or val < self.minStack[-1]: self.minStack.append(val) def pop(self) -> None: if self.minStack[-1] == self.stack[-1]: self.minStack.pop() self.stack.pop() def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.minStack[-1] """ MinStack() initializes the stack object. void push(val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. """ # 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() answer = MinStack4() answer.push(-2) answer.push(0) answer.push(-1) answer.getMin() # return -3 answer.pop() answer.top() # return 0 answer.getMin() # return -2 print(answer.stack) """ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. Example 1: Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 Constraints: -2^31 <= val <= 2^31 - 1 Methods pop, top and getMin operations will always be called on non-empty stacks. At most 3 * 104 calls will be made to push, pop, top, and getMin. """
b7e344a06d52f9269e126bd7791eba38c59e7807
nathanhoang5/fractals
/koch.py
556
3.71875
4
from turtle import Turtle t = Turtle() t.color('red', 'yellow') def Recursive_Koch(length, depth): if depth == 0: t.forward(length) else: Recursive_Koch(length, depth-1) t.right(60) Recursive_Koch(length, depth-1) t.left(120) Recursive_Koch(length, depth-1) t.right(60) Recursive_Koch(length, depth-1) # ---------- t.penup() t.penup() t.setpos(-150,-150) t.pendown() print(t.pos()) LENGTH=10 LEVEL=3 for i in range(6): Recursive_Koch(LENGTH, LEVEL) t.left(60) c = input()
4dc1318c935d1a01ebfa7776855132e63676acb1
AndreyIh/Solved_from_chekio
/Mine/best_stock.py
936
3.75
4
#!/usr/bin/env checkio --domain=py run best-stock # You are given the current stock prices. You have to find out which stocks cost more. # # Input:The dictionary where the market identifier code is a key and the value is a stock price. # # Output:The market identifier code (ticker symbol) as a string. # # Preconditions:All the prices are unique. # # # END_DESC def best_stock(dic): max0, imax = 0, '' for i in dic: if dic.get(i)>max0: max0 = dic.get(i) imax = i return imax if __name__ == '__main__': print("Example:") print(best_stock({"CAC": 10.0, "ATX": 390.2, "WIG": 1.2})) # These "asserts" are used for self-checking and not for an auto-testing assert best_stock({"CAC": 10.0, "ATX": 390.2, "WIG": 1.2}) == "ATX" assert best_stock({"CAC": 91.1, "ATX": 1.01, "TASI": 120.9}) == "TASI" print("Coding complete? Click 'Check' to earn cool rewards!")
d7030a0c34426c8a48b88c51adfa66f63e210fbd
QuentinDevPython/McGyver2.0
/mcgyver/game.py
8,414
3.6875
4
""" Import the time Import the module 'pygame' for writing video games Import the other classes 'Maze' and 'Player' to manage the all game Import the file 'config' for the constants. """ import time import pygame from mcgyver.maze import Maze from mcgyver.player import Player import config class Game: """class that initiates the game of the maze, updates it according to each action of the player and graphically displays the game. """ def __init__(self): """function that instantiates the class "Game" by loading and resizing the images of the game, defines the width and height of the maze and initializes the grid and the player. """ self.maze = Maze() self.player = Player(self) self.width = config.GAME_WIDTH self.length = config.GAME_HEIGHT self.dimension = config.GAME_SQUARE_DIMENSION self.wall_image = pygame.image.load( 'mcgyver/assets/background/wall.png') self.wall_image = pygame.transform.scale( self.wall_image, (self.dimension, self.dimension)) self.floor_image = pygame.image.load( 'mcgyver/assets/background/floor.png') self.floor_image = pygame.transform.scale( self.floor_image, (self.dimension, self.dimension)) self.player_image = pygame.image.load( 'mcgyver/assets/characters/mac_gyver.png') self.player_image = pygame.transform.scale( self.player_image, (self.dimension-3, self.dimension-3)) self.end_image = pygame.image.load( 'mcgyver/assets/background/end.png') self.end_image = pygame.transform.scale( self.end_image, (self.dimension, self.dimension)) self.guardian_image = pygame.image.load( 'mcgyver/assets/characters/guardian.png') self.guardian_image = pygame.transform.scale( self.guardian_image, (self.dimension-2, self.dimension-2)) self.ether_image = pygame.image.load('mcgyver/assets/items/ether.png') self.needle_image = pygame.image.load( 'mcgyver/assets/items/needle.png') self.plastic_tube_image = pygame.image.load( 'mcgyver/assets/items/plastic_tube.png') self.syringe_image = pygame.image.load( 'mcgyver/assets/items/syringe.png') self.win = pygame.image.load( 'mcgyver/assets/finish_game/win.png') self.win = pygame.transform.scale(self.win, (200, 200)) self.defeat = pygame.image.load( 'mcgyver/assets/finish_game/defeat.png') self.defeat = pygame.transform.scale(self.defeat, (200, 200)) def run_game(self): """function that launches the game window and follows the player’s actions.""" pygame.init() # define the dimensions of the game window number_squares = self.width size_squares = self.dimension screen_size = (number_squares * size_squares, number_squares * size_squares) # generate the game window screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('Escape from the maze') pygame.font.init() myfont = pygame.font.Font(None, 24) self.maze.create_maze(self.width, self.length) self.maze.define_item_square(self.length) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT and self.player.can_move_right(): self.player.move_right() elif event.key == pygame.K_LEFT and self.player.can_move_left(): self.player.move_left() elif event.key == pygame.K_UP and self.player.can_move_up(): self.player.move_up() elif event.key == pygame.K_DOWN and self.player.can_move_down(): self.player.move_down() self.player.take_item() text_items_taken = ( 'You have taken {}/4 items'.format(self.player.number_items_taken)) text = myfont.render(text_items_taken, 1, (255, 255, 255)) self.__update_map(screen, text) running = self.player.is_victorious()[0] if not running: time.sleep(3) def __update_map(self, screen, text): """function that graphically displays the elements of the maze and that updates it with each action of the player. """ map_printed = '' map_in_window = self.maze.create_maze_map( map_printed, self.width, self.length) map_in_window = map_in_window.split(' ') index = 0 for line_maze in range(self.width): for column_maze in range(self.length): if (line_maze, column_maze) != (0, 0): index += 1 if map_in_window[index] == '#': screen.blit(self.wall_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'x': screen.blit(self.floor_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(self.player_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'a': screen.blit(self.end_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(self.guardian_image, (column_maze * self.dimension, line_maze * self.dimension)) else: screen.blit(self.floor_image, (column_maze * self.dimension, line_maze * self.dimension)) if map_in_window[index] == 'e': screen.blit(self.ether_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'n': screen.blit(self.needle_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 'p': screen.blit(self.plastic_tube_image, (column_maze * self.dimension, line_maze * self.dimension)) elif map_in_window[index] == 's': screen.blit(self.syringe_image, (column_maze * self.dimension, line_maze * self.dimension)) screen.blit(text, (20, 10)) if self.player.is_victorious()[1] == 1: screen.blit(self.win, ((self.width * self.dimension) / 3, (self.length * self.dimension)/3)) elif self.player.is_victorious()[1] == 0: screen.blit(self.defeat, ((self.width * self.dimension) / 3, (self.length * self.dimension)/3)) pygame.display.flip() """ # for console game while running: map_printed = '' self.maze.create_maze_map(map_printed, self.width, self.length) bool_direction = False while not bool_direction: direction = input( 'Where do you want to go ? (Q,Z,D,S)') if direction == 'Q' and self.player.can_move_left(): self.player.move_left() bool_direction = True elif direction == 'D' and self.player.can_move_right(): self.player.move_right() bool_direction = True elif direction == 'Z' and self.player.can_move_up(): self.player.move_up() bool_direction = True elif direction == 'S' and self.player.can_move_down(): self.player.move_down() bool_direction = True """
f91d741c29d6b6e332cdb86732ec6bb9665a14fb
SimonZhang04/Small-Projects
/Hangman.py
1,094
3.828125
4
import random import re life = 5 word_bank = ["apple", "banana", "cherry", "figs", "grapes", "honeydew", "jackfruit", "kiwi", "lemon", "mango", "nectarine", "orange", "peach", "raspberry", "strawberry", "watermelon"] hidden_word = word_bank[random.randint(0, len(word_bank)-1)] incorrect_guesses = [] blanks = "_ " * len(hidden_word) while life > 0: print(blanks) print(f"Incorrect guesses: {incorrect_guesses}") guess = input("What is your guess? ") if guess in hidden_word: character_indexes = ([m.start() for m in re.finditer(guess, hidden_word)]) print(f"There are {len(character_indexes)} '{guess}'(s)") for x in range(len(character_indexes)): character_indexes[x] = character_indexes[x] * 2 for x in range(len(character_indexes)): blanks = blanks[:character_indexes[x]] + guess + blanks[character_indexes[x] + 1:] if "_" not in blanks: print("You win!") break else: print("Incorrect guess") incorrect_guesses.append(guess) life -= 1 print(f"You have {life} live(s) left") print(f"The word was {hidden_word}")
b6902c9c35453d1847b0af1614b5426d3242dd5a
Madhu2244/Leetcode-ProgrammingPrep
/0. Non-Leetcode Problems/Boba Code But Better/Spider Pig/solution.py
1,232
3.828125
4
def main(): params = list(map(int,input().split())) maxJump = params[1] arr = list(map(int,input().split())) cur_index = 0 #which building we are currently on total_climbs = 0 #output while cur_index < len(arr) - 1: #if we are out of bounds we are done #print('new loop') localMax = 0 best_index = 0 #index that is less than arr[cur_index] and the largest from (cur_index to cur_index+jump] for i in range (1,maxJump + 1): #check from jump range 1 to max range if cur_index + i > len(arr) - 1: #if we are out of bounds then we are done break if arr[cur_index + i] >= arr[cur_index]: break if arr[cur_index + i] >= localMax: #if the next building has a height greater than the local max but is also less than cur_index, then we adjust the localMax. localMax = arr[cur_index + i] best_index = cur_index + i #print(arr[cur_index + i], localMax, cur_index+i) if localMax == 0: cur_index += 1 total_climbs += 1 else: cur_index = best_index print(total_climbs) if __name__ == '__main__': main()
e7447d5423c935601f81e8e42e3f63d17c3523d0
p-lots/codewars
/7-kyu/multiples!/python/solution.py
153
3.578125
4
def multiple(x): ret = '' if x % 3 == 0: ret += 'Bang' if x % 5 == 0: ret += 'Boom' return ret if ret else 'Miss'
8bcf54c5c30ffa8d17fb176cb00d17a83aa9b894
vim-vdebug/vdebug
/python3/vdebug/ui/interface.py
1,173
3.53125
4
class Ui: """Abstract for the UI, used by the debugger """ watchwin = None stackwin = None statuswin = None logwin = None sourcewin = None tracewin = None def __init__(self): self.is_open = False def __del__(self): self.close() def open(self): pass def say(self, string): pass def close(self): pass def log(self): pass class Window: """Abstract for UI windows """ name = "WINDOW" is_open = False def __del__(self): self.destroy() def on_create(self): """ Callback for after the window is created """ pass def on_destroy(self): """ Callback for after the window is destroyed """ pass def create(self): """ Create the window """ pass def write(self, msg): """ Write string in the window """ pass def insert(self, msg, position=None): """ Insert a string somewhere in the window """ pass def destroy(self): """ Close window """ pass def clean(self): """ clean all data in buffer """ pass
0c25d9a02a4186a950d03f1a8f5db4c91e02a56d
syllamacedo/exercicios_python
/curso_em_video/ex094_cadastro_grupo.py
1,468
4.0625
4
# Exercício Python 094: Crie um programa que leia nome, sexo e idade de várias pessoas, # guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. # No final, mostre: # A) Quantas pessoas foram cadastradas # B) A média de idade # C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média dados = dict() dadosfinal = [] media = 0 while True: dados['nome'] = str(input('Nome: ')).upper() while True: dados['sexo'] = str(input('Sexo: [M/F] ')).upper()[0] if dados['sexo'] in 'MF': break print('ERRO! Por favor digite M ou F.') dados['idade'] = int(input('Idade: ')) dadosfinal.append(dados.copy()) media = (media + dados['idade']) / len(dadosfinal) while True: resp = str(input('Deseja continuar? [S/N] ')).upper()[0] if resp in 'SN': break print('ERRO! Por favor digite S ou N.') if resp == 'N': break print() print('-='*30) print(f'- O grupo tem {len(dadosfinal)} pessoas\n' f'- A média de idade é de {media:.1f}\n' f'- As mulheres cadastradas foram: ', end='') for n in dadosfinal: if n['sexo'] == 'F': print(f'{n["nome"]};', end=' ') print(f'\n- Lista das pessoas que estão acima da média:\n') for n in dadosfinal: if n['idade'] > media: print(f'Nome = {n["nome"]}; Sexo = {n["idade"]}; Idade = {n["idade"]};') print() print('<< ENCERRADO >>')
cb515e02f70717274cfdf6e7cf88ec8da1b76191
alisatsar/itstep
/Python/Tkinter/grid2.py
791
3.578125
4
from tkinter import * root = Tk() # окно root.title("Вставка строки") f_1 = Frame(root,width = 50, height = 50,bg = 'green') f_2 = Frame(root,width = 50, height = 50, bg = 'blue') f_3 = Frame(root,width = 50, height = 50, bg = 'red') f_4 = Frame(root,width = 50, height = 50, bg = 'yellow') f_5 = Frame(root,width = 50, height = 50, bg = 'gray') f_6 = Frame(root,width = 50, height = 50, bg = 'orange') f_7 = Frame(root,width = 50, height = 50, bg = 'black') f_8 = Frame(root,width = 50, height = 50, bg = 'white') f_1.grid(row=0,column=0,columnspan=2) f_2.grid(row=1,column=0) f_3.grid(row=2,column=0) f_4.grid(row=2,column=1) f_5.grid(row=2,column=2) f_6.grid(row=0,column=1,columnspan=1) f_7.grid(row=0,column=2,columnspan=2) f_8.grid(row=1,column=2) root.mainloop()
ac4fdcb5dfdf4cbcf90c6a756a132bddf9c43edf
Jeff-28/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
87
3.5
4
#!/usr/bin/python3 def uniq_add(my_list=[]): return sum(x for x in set(my_list))
9e81e3f0e6c1c5d83f71655e40acf436a79240e8
dhull33/python_exercises
/string_exercises.py
1,791
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 6 14:55:34 2018 @author: davidhull """ # Uppercase a string x = 'p' print(x.upper()) # Capitalize a string x = "david" print(x.capitalize()) # Reverse a string rev = x[::-1] print(rev) # Leetspeak def leet(): x = input("What's your giant string? ") k = list(x.lower()) final = [] for i in range(len(k)): if k[i] == "a": k[i]= '4' elif k[i] == 'e': k[i] = '3' elif k[i] == 'g': k[i] = '6' elif k[i] == 'i': k[i] = '1' elif k[i] == 'o': k[i] = '0' elif k[i] == 's': k[i] = '5' elif k[i] == 't': k[i] = '7' final += k[i] fin = ''.join(map(str, final)) return fin # Long-Long Vowels def add_vowels(): x = input("Give me your word: ") vowels = ['aa', 'ee', 'ii', 'oo', 'uu', 'AA', 'EE', 'II', 'OO', 'UU'] fin = '' for i in range(len(x)): if x[i:i+2] in vowels: fin += x[i] * 4 else: fin += x[i] return fin # Caesar Cipher def ceasar_cipher(): init = input("What shall I encrypt for you good? ") unencr = init.lower() encr = '' for i in range(len(unencr)): if ord(unencr[i]) <= 109: num = ord(unencr[i]) n_num = num + 13 encr += chr(n_num) elif ord(unencr[i]) >= 110: num = ord(unencr[i]) n_num = num - 13 encr += chr(n_num) else: encr += unencr[i] return encr
677aaa7b534dbce2b4ba41df1e5787377017e9b1
lmurtinho/smartcab_planner
/planner_world.py
7,543
3.8125
4
# -*- coding: utf-8 -*- import pandas as pd import random class PlannerWorld(): """ The world (a toroidal grid) in which the planners operate. """ def __init__(self, grid_size=(8, 6), trials=1000, deadline=100): self.grid_size = grid_size self.trials = trials self.deadline = deadline def get_delta(self, location, destination): """ get the horizontal and vertical distance between location and destination. """ delta = [0, 0] for i in range(2): # 1st option: destination to the east/south of location if destination[i] > location[i]: # two possible distances, going east/south or # going west/north possible_delta = [destination[i] - location[i], location[i] + self.grid_size[i] - \ destination[i]] # if the first distance is the smallest, pick it if min(possible_delta) == possible_delta[0]: delta[i] = possible_delta[0] # if seconde distance is the smallest, pick minus it # (the agent will have to go west/north to get to a point # to the east/south) else: delta[i] = -possible_delta[1] # 2nd option: destination to the west/north of location else: # two possible distances, going west/north or # going east/south possible_delta = [location[i] - destination[i], destination[i] + self.grid_size[i] - \ location[i]] # if the first distance is the smallest, pick minus it # (the agent will have to go west/north) if min(possible_delta) == possible_delta[0]: delta[i] = -possible_delta[0] # if second distance is smallest, pick it else: delta[i] = possible_delta[1] # return a tuple return tuple(delta) def get_distance(self, delta): """ Returns the overall distance. """ return sum([abs(i) for i in delta]) def get_reward(self, steps_left): """ Returns a negative reward proportional to distance if the agent has not reached its destination, and a negative reward proportional to the time left if the agent has reached its destination. """ delta = self.get_delta(self.planner.location, self.planner.destination) distance = self.get_distance(delta) reward = -distance if distance else steps_left return reward def move_agent(self, action): """ Modifies the position and heading of the agent. """ location = self.planner.location heading = self.planner.heading next_point = list(location) # to be modified below next_heading = list(heading) # to be modified below if action == 'forward': # just move according to the heading next_point = [(next_point[i] + next_heading[i]) % \ self.grid_size[i] for i in range(2)] elif action == 'right': if heading[0]: #turned to EW axis next_point[1] = (next_point[1] + heading[0]) % \ self.grid_size[1] next_heading = [heading[1], heading[0]] else: # turned to NS axis next_point[0] = (next_point[0] - heading[1]) % \ self.grid_size[0] next_heading = [-heading[1], heading[0]] elif action == 'left': if heading[0]: # turned to EW axis next_point[1] = (next_point[1] - heading[0]) % \ self.grid_size[1] next_heading = [heading[1], -heading[0]] else: # turned to NS axis next_point[0] = (next_point[0] + heading[1]) % \ self.grid_size[0] next_heading = [heading[1], heading[0]] else: raise ValueError('Invalid action.') # check if agent has gone to the other side of the world next_point = [self.grid_size[i] if next_point[i] == 0 \ else next_point[i] for i in range(2)] # change agent's position and heading self.planner.location = tuple(next_point) self.planner.heading = tuple(next_heading) def get_random_position(self): """ Returns a random position in a grid-like world. """ return tuple([random.choice(range(number)) + 1 for number in self.grid_size]) def simulate(self, planner): self.planner = planner trial_results = [] # to be populated t = 0 # to keep track of the number of actions taken by the agent for i in range(self.trials): # define the agent's location, destination and heading self.planner.location = self.get_random_position() self.planner.destination = self.get_random_position() while self.planner.destination == self.planner.location: self.planner.destination = self.get_random_position() axis = random.choice(range(2)) self.planner.heading = tuple(0 if i != axis else \ random.choice([-1, 1]) for i in range(2)) # initialize the sum of rewards reward_sum = 0 # for each step in the trial for i in range(self.deadline): t += 1 # count the time # get the delta between location and destination delta = self.get_delta(self.planner.location, self.planner.destination) # set up the agent's state state = (delta, self.planner.heading) # use the planner to come up with an action action = self.planner.policy(state) # update the agent's location and heading self.move_agent(action) # get the next state and the reward associated to it next_delta = self.get_delta(self.planner.location, self.planner.destination) next_state = (next_delta, self.planner.heading) reward = self.get_reward(self.deadline - i) # use the qval function to update the state's Q-value experience = (state, action, reward, next_state) self.planner.update_qval(experience, t) # update the sum of rewards reward_sum += reward # check if the agent has reached its destination if self.planner.location == self.planner.destination: break # store the results of the trial trial_results.append((i+1, reward_sum)) # return a dataframe with the trial results and # the dict with Q-values df = pd.DataFrame(trial_results) df.columns = ['n_steps', 'reward_sum'] return df, self.planner.qvals
d1b4aaea9b8c0646fab56a418756c1d08039fdfd
shamsyousafzai/Maths
/Maths-Formulas-master/school-level-formulas/surface_area_of_cube.py
199
4.15625
4
from math import pow s = int(raw_input("Enter the side value :")) def surface_area_of_cube(s): area = 6 * (pow(s, 2)) return "Surface area of cube is %s" % (area) print surface_area_of_cube(s)
402df0b13a8ddfa2de08866b6fc6bcd1a4ba5efd
gdesjonqueres/py-complete-course
/files/json_context_manager.py
452
3.75
4
import json with open('friends.json', 'r') as file: file_contents = json.load(file) # reads file and turn it into a dictionnary print(file_contents['friends'][0]) cars = [ {'make': 'Ford', 'model': 'Fiesta'}, {'make': 'Ford', 'model': 'Focus'} ] with open('cars.json', 'w') as file: json.dump(cars, file) my_json_string = '[{"name": "Alpha Romeo", "released": 1950}]' my_car = json.loads(my_json_string) print(my_car[0]['name'])
4add6d46900cd2eff0b1df7246913816b07a536d
SusanQu/ProcessingSketches
/parametric_equation_sketch_3/ellipse_variation2.py
859
3.5625
4
######################################### # ellipse - circle to square ######################################### t = 0 DELAY = 5 * 100 def setup(): background(242, 242, 242) size(700, 700) def draw(): background(242, 242, 242) global t ellipseMode(CENTER) stroke(121, 102, 72) fill(255, 193, 7) strokeWeight(1) ellipse(width/2, height / 2, 200, 200) translate(width / 2, height / 2) for i in range(80): stroke(121, 102, 72, i*10) fill(255, 193, 7, i) #noFill() strokeWeight(1) ellipse(x2(t + i), y2(t + i), x3(t + i), y3(t + i)) t = t + 0.075 def mousePressed(): pauseFrame() def pauseFrame(): delay(DELAY) def x2(t): return sin(t/10) def y2(t): return cos(t/10) def x3(t): return sin(t/10) * 200 def y3(t): return cos(t/10) * 200
8cb39416287c5ceaea564d5416e9516c3702bae8
jeganrajrajan/python_basics
/pythonre.py
1,169
4.03125
4
import re # Program to extract numbers from a string # Output: ['12', '89', '34'] string = 'hello 12 hi 89. Howdy 34' pattern = '\d+' result = re.findall(pattern, string) print(result) #re.split() # Output: ['Twelve:', ' Eighty nine:', '.'] string = 'Twelve:12 Eighty nine:89.' pattern = '\d+' result = re.split(pattern, string) print(result) # sub() # Program to remove all whitespaces # multiline string # Output: abc12de23f456 string = 'abc 12\ de 23 \n f45 6' # matches all whitespace characters pattern = '\s+' # empty string replace = '' new_string = re.sub(pattern, replace, string) print(new_string) # subn() new_str = re.subn(pattern, replace, string) print(new_str) string = '39801 356, 2102 1111' # Three digit number followed by space followed by two digit number pattern = '(\d{3}) (\d{2})' # match variable contains a Match object. match = re.search(pattern, string) if match: print(match.group()) else: print("pattern not found") # Output: 801 35 string = '\n and \r are escape sequences.' result = re.findall(r'[\n\r]', string) print(result) # Output: ['\n', '\r']
f0530161b3d80e7ccc9f071c8d7adaa1a53019d2
Leoyuseu/python
/Codeskulptor/Guess the number.py
1,986
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui, random num_range = 100 player_num =0 player_guess_times = 0 # helper function to start and restart the game def new_game(): global num_range, player_num, player_guess_times if (num_range==100): player_guess_times = 7 else: player_guess_times = 10 player_num = random.randrange(0,num_range) print '' print 'New game, Range is from 0 to ', num_range print 'You have ', player_guess_times, ' chances to guess.' # remove this when you add your code # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global num_range #print num_range num_range = 100 # remove this when you add your code new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global num_range num_range =1000 new_game() def input_guess(guess): # main game logic goes here global player_guess_times guess_num = int(guess) player_guess_times -= 1 print '' print 'You guessed: ', guess_num, '. ' print 'You have ', player_guess_times, ' chances to guess.' if (int(guess) == player_num): print 'You are correct!' new_game() elif (int(guess) < player_num): print 'Higher!' else: print 'Lower!' # create frame frame = simplegui.create_frame('Guess the number', 200, 200) # register event handlers for control elements and start frame frame.add_button('Range is [0,100)', range100, 200) frame.add_button('Range is [0,1000)', range1000, 200) frame.add_input('Enter a guess', input_guess, 200) # call new_game new_game() frame.start() # always remember to check your completed program against the grading rubric
8739f4e60ccba7ac382dea3f55801914d00971b4
ashk0821/StatisticsCalculator
/StatsCalculator.py
1,142
3.859375
4
import math def read_numbers(): nums = [] lines = input("Enter your numbers.") r while lines != "": line_lists = lines.split() for s in line_lists: nums.append(float(s)) lines = input() return nums def get_mean(my_list): total = 0 for n in my_list: total += n return total / len(my_list) def get_range(my_list): return max(my_list) - min(my_list) def get_median(my_list): my_list.sort() if len(my_list) % 2 == 0: pos = len(my_list) // 2 return (my_list[pos] + my_list[pos - 1]) / 2 else: pos = len(my_list) // 2 return my_list[pos] def get_std_dev (my_list): total = 0 for x in range (len(my_list)): total += (get_mean(my_list) - my_list[x]) ** 2 return math.sqrt(total/len(my_list)) def main (): my_list = read_numbers() print ("Mean: %.2f" % get_mean(my_list)) print ("Std Dev: %.2f" % get_std_dev(my_list)) print ("Median: ", get_median(my_list)) print ("Min: ", min(my_list)) print ("Max: ", max(my_list)) print ("Range: ", get_range(my_list)) main()
e043dfe14199af29897122698e7c4b442d6abd5f
TestowanieAutomatyczneUG/laboratorium-6-maciejSzcz
/src/zad1.py
1,547
3.921875
4
class FizzBuzz: def game(self, num): """Takes integer and produces the result based on divisibility of the number >>> c = FizzBuzz() >>> c.game(5) 'Buzz' >>> c.game(3) 'Fizz' >>> c.game(15) 'FizzBuzz' >>> c.game("12") Traceback (most recent call last): File "/usr/lib/python3.8/doctest.py", line 1336, in __run exec(compile(example.source, filename, "single", File "<doctest __main__.FizzBuzz.game[4]>", line 1, in <module> c.game("12") File "zad1.py", line 15, in game raise Exception("Not a valid number") Exception: Not a valid number >>> c.game(2) Traceback (most recent call last): File "/usr/lib/python3.8/doctest.py", line 1336, in __run exec(compile(example.source, filename, "single", File "<doctest __main__.FizzBuzz.game[5]>", line 1, in <module> c.game(2) File "zad1.py", line 32, in game raise Exception("Error in FizzBuzz") Exception: Error in FizzBuzz """ if type(num) != int: raise Exception("Not a valid number") if ((num % 15) == 0): return "FizzBuzz" elif ((num % 3) == 0): return "Fizz" elif ((num % 5) == 0): return "Buzz" else: raise Exception("Error in FizzBuzz") if __name__ == "__main__": import doctest doctest.testmod()
3d48ad782fbb53f79db3421ce8bd63852cd6387b
paoladuran0618/PythonPractices
/platzi/string.py
366
3.84375
4
string = 'paola' for letter in string: print(letter) mi_string = 'Leonardo Medina' print(len(mi_string)) string_2 = 'Eso es otro string super largo' print(string_2.upper()) print(string_2.lower()) print(string_2.find('s')) print(string_2[1:]) print(string[1:3]) print(string_2[1:6:2]) print(string_2[::-1]) #Lee al reves la palabra #print(string_2[start:ends:stepts])
b1d7bdc45036293ad9ede4892cf4d0c521d95017
AnvarM/python-101
/exceptions_handling.py
1,474
4
4
# Exceptions handling 1 / 0 Traceback (most recent call last): File "<string>", line 1, in <fragment> ZeroDivisionError: integer division or modulo by zero try: 1 / 0 except ZeroDivisionError: print("You cannot divide by zero!") # output will be: You cannot divide by zero! my_dict = {"a":1, "b":2, "c":3} try: value = my_dict["d"] except KeyError: print("That key does not exist!") # output will be: That key does not exist! my_list = [1, 2, 3, 4, 5] try: my_list[6] except IndexError: print("That index is not in the list!") # output will be: That index is not in the list! my_dict = {"a":1, "b":2, "c":3} try: value = my_dict["d"] except IndexError: print("This index does not exist!") except KeyError: print("This key is not in the dictionary!") except: print("Some other error occurred!") try: value = my_dict["d"] except (IndexError, KeyError): print("An IndexError or KeyError occurred!") #The "finally" Statement my_dict = {"a":1, "b":2, "c":3} try: value = my_dict["d"] except KeyError: print("A KeyError occurred!") finally: print("The finally statement has executed!") #will return: #A KeyError occurred! #The finally statement has executed! #Finally statement always executes #try, except, or else my_dict = {"a":1, "b":2, "c":3} try: value = my_dict["a"] except KeyError: print("A KeyError occurred!") else: print("No error occurred!")
419cbe9023bb2742ab5f1a76a136b1b88de106f3
padma67/guvi
/looping/Multiplication_table.py
148
4.15625
4
#To print the multiplication table #get number from the user a=int(input(" enter the value")) for i in range(1,11,1): print(a,"*",i,"=",a*i)
ac3bce80594fcff788827a37455b309c7f17882e
anuragbisht12/Daily-Coding-Problems
/solutions/problem_228.py
1,684
3.640625
4
def get_largest(nums, prefix=""): num_dict = dict() for num in nums: str_num = str(num) fdig = str_num[0] if fdig not in num_dict: num_dict[fdig] = list() num_dict[fdig].append(str_num) sorted_arrs = sorted(num_dict.values(), key=lambda x: x[0], reverse=True) combined = list() for arr in sorted_arrs: if len(arr) == 1: combined.extend(arr) continue split_dict = dict() for num in arr: len_num = len(num) if len_num not in split_dict: split_dict[len_num] = list() split_dict[len_num].append(num) sorted_val_arrs = sorted( split_dict.values(), key=lambda x: len(x[0])) for val_arr in sorted_val_arrs: combined.extend(sorted(val_arr, reverse=True)) return int(prefix.join(combined)) # Tests assert get_largest([10, 7, 76, 415]) == 77641510 """ Another way """ def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ numstr = sorted([str(num) for num in nums]) # go through the list to rearrage the order curr = [numstr[0]] for i in range(1, len(nums)): if curr[-1] +numstr[i] > numstr[i]+curr[-1]: numstr[i-len(curr)] = numstr[i] numstr[i] = curr[-1] elif curr[-1] +numstr[i] == numstr[i]+curr[-1]: curr.append(numstr[i]) else: curr = [numstr[i]] result = ''.join(reversed(numstr)) if int(result)>0: return result else: return '0'
55ba5db4058bd45561c197e03a9955cde1fd0120
fazalgujjar/Python
/CGPA Calculator basic.py
5,096
3.90625
4
subject_1 = input('please enter 1st subject name:') subject_2 = input('please enter 2nd subject name:') subject_3 = input('please enter 3rd subject name:') subject_4 = input('please enter 4th subject name:') subject_5 = input('please enter 5th subject name:') subject1_marks = int(input(f" Please enter {subject_1} total Marks:")) subject2_marks = int(input(f" Please enter {subject_2} total Marks:")) subject3_marks = int(input(f" Please enter {subject_3} total Marks:")) subject4_marks = int(input(f" Please enter {subject_4} total Marks:")) subject5_marks = int(input(f" Please enter {subject_5} total Marks:")) subject1_omarks = int(input(f" Please enter {subject_1} obtained Marks:")) subject2_omarks = int(input(f" Please enter {subject_2} obtained Marks:")) subject3_omarks = int(input(f" Please enter {subject_3} obtained Marks:")) subject4_omarks = int(input(f" Please enter {subject_4} obtained Marks:")) subject5_omarks = int(input(f" Please enter {subject_5} obtained Marks:")) subject1_C_Hour = int(input(f" Please enter {subject_1} Total Credit Hours:")) subject2_C_Hour = int(input(f" Please enter {subject_2} Total Credit Hours:")) subject3_C_Hour = int(input(f" Please enter {subject_3} Total Credit Hours:")) subject4_C_Hour = int(input(f" Please enter {subject_4} Total Credit Hours:")) subject5_C_Hour = int(input(f" Please enter {subject_5} Total Credit Hours:")) subject1_Average = (subject1_omarks/subject1_marks) * 100 subject2_Average = (subject2_omarks/subject2_marks) * 100 subject3_Average = (subject3_omarks/subject3_marks) * 100 subject4_Average = (subject4_omarks/subject4_marks) * 100 subject5_Average = (subject5_omarks/subject5_marks) * 100 if subject1_Average >= 80 and subject1_Average <= 100: sgpa1 = 4 print(f'SGPA of Subject {subject_1} is {sgpa1}') elif subject1_Average >= 70 and subject1_Average <= 79: sgpa1 = 3 print(f'SGPA of Subject {subject_1} is {sgpa1}') elif subject1_Average >= 60 and subject1_Average <= 69: sgpa1 = 2 print(f'SGPA of Subject {subject_1} is {sgpa1}') elif subject1_Average >= 50 and subject1_Average <= 59: sgpa1 = 1 print(f'SGPA of Subject {subject_1} is {sgpa1}') else: sgpa1 = 0 print(f'SGPA of Subject {subject_1} is {sgpa1}') if subject2_Average >= 80 and subject2_Average <= 100: sgpa2 = 4 print(f'SGPA of Subject {subject_2} is {sgpa2}') elif subject2_Average >= 70 and subject2_Average <= 79: sgpa2 = 3 print(f'SGPA of Subject {subject_2} is {sgpa2}') elif subject2_Average >= 60 and subject2_Average <= 69: sgpa2 = 2 print(f'SGPA of Subject {subject_2} is {sgpa2}') elif subject2_Average >= 50 and subject2_Average <= 59: sgpa2 = 1 print(f'SGPA of Subject {subject_2} is {sgpa2}') else: sgpa2 = 0 print(f'SGPA of Subject {subject_2} is {sgpa2}') if subject3_Average >= 80 and subject3_Average <= 100: sgpa3 = 4 print(f'SGPA of Subject {subject_3} is {sgpa3}') elif subject3_Average >= 70 and subject3_Average <= 79: sgpa3 = 3 print(f'SGPA of Subject {subject_3} is {sgpa3}') elif subject3_Average >= 60 and subject3_Average <= 69: sgpa3 = 2 print(f'SGPA of Subject {subject_3} is {sgpa3}') elif subject3_Average >= 50 and subject3_Average <= 59: sgpa3 = 1 print(f'SGPA of Subject {subject_3} is {sgpa3}') else: sgpa3 = 0 print(f'SGPA of Subject {subject_3} is {sgpa3}') if subject4_Average >= 80 and subject4_Average <= 100: sgpa4 = 4 print(f'SGPA of Subject {subject_4} is {sgpa4}') elif subject4_Average >= 70 and subject4_Average <= 79: sgpa4 = 3 print(f'SGPA of Subject {subject_4} is {sgpa4}') elif subject4_Average >= 60 and subject4_Average <= 69: sgpa4 = 2 print(f'SGPA of Subject {subject_4} is {sgpa4}') elif subject4_Average >= 50 and subject4_Average <= 59: sgpa4 = 1 print(f'SGPA of Subject {subject_4} is {sgpa4}') else: sgpa4 = 0 print(f'SGPA of Subject {subject_4} is {sgpa4}') if subject5_Average >= 80 and subject5_Average <= 100: sgpa5 = 4 print(f'SGPA of Subject {subject_5} is {sgpa4}') elif subject5_Average >= 70 and subject5_Average <= 79: sgpa5 = 3 print(f'SGPA of Subject {subject_5} is {sgpa4}') elif subject5_Average >= 60 and subject5_Average <= 69: sgpa5 = 2 print(f'SGPA of Subject {subject_5} is {sgpa4}') elif subject5_Average >= 50 and subject5_Average <= 59: sgpa5 = 1 print(f'SGPA of Subject {subject_5} is {sgpa4}') else: sgpa5 = 0 print(f'SGPA of Subject {subject_5} is {sgpa4}') quality_point1 = subject1_C_Hour * sgpa1 quality_point2 = subject2_C_Hour * sgpa2 quality_point3 = subject3_C_Hour * sgpa3 quality_point4 = subject4_C_Hour * sgpa4 quality_point5 = subject5_C_Hour * sgpa5 print(f"Quality point of {subject_1} ,{subject_2}, {subject_3} ,{subject_4} ,{subject_5} is respectevely {quality_point1}, {quality_point2}, {quality_point3},{quality_point4}, {quality_point5}") sum_qp = quality_point1 + quality_point2 + quality_point3 + quality_point4 + quality_point5 sum_credit_hour = subject1_C_Hour + subject2_C_Hour + subject3_C_Hour + subject4_C_Hour + subject5_C_Hour CGPA = (sum_qp/sum_credit_hour) print(f"CGPA is {CGPA}")
9e55bc5c2b13e7d2bfe6ddb9bc418d038a1355ff
internetsadboy/math
/numerical-analysis/as4/eulers-modified/eulers-modified.py
990
3.53125
4
# Euler's Modified Method # http://en.wikipedia.org/wiki/Euler_method#Modifications_and_extensions # user input: n, d, x, and poly # poly: dx/dt == f(t,x) # n: # of steps # d: domain a <= t <= b # x: initial value # h: step size # t: the delta of current steps taken from math import * n = 10.0 d = [0.0,2.0] h = (d[1]-d[0])/n # f(t,x) + f(t+h,x+hf(t,x)) def poly(h,x,t): return 4*h*x - 2*h*t - 4*x + 2*t + h # euler stuff def EulersModfied(log): x = 1.0 t = 0.0 for k in range(int(n)): t = k*h # bread if log: print "k ", k print "h ", h print "t ", t print "x(k) ", x print "h/2f(h,t(k),x(k)) ", h/2*poly(h,x,t) x = x+h/2*poly(h,x,t) # butter if log: print "x(k+1) ", x print "" return x z =EulersModfied(True) l = len(str(z))+9 for i in range(l): import sys sys.stdout.write("=") print "" print "x(",int(n)-1,") =", z
a3f1844686bda0cc3745122159c678d24f9515ff
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/Aula05/exemploRecursividade.py
252
3.734375
4
def ImprimeSequencia(a,b) : for x in range(a,b+1) : print(x,end=" ") ImprimeSequencia(14,22) def imprimeSequencia(a,b) : if a==b: print(b) else: print(a,end=" ") imprimeSequencia(a+1,b) imprimeSequencia(14,22)
61cfeaac3a6b20a28f06e9a3a3055efc3a4ae2aa
lance-lh/Data-Structures-and-Algorithms
/DSA/stack/trap.py
1,645
3.8125
4
''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! Example: Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 ''' # 单调栈应用(单减栈) # 接雨水需要满足一个U形,维护一个单减栈,纪录index class Solution: def trap(self, height): ''' :param height: List[int] :return: int ''' res = 0 # stack to store index stack = [] i = 0 # for-loop is not ok # for i in range(len(height)): while i < len(height): # if not stack or height[i] <= height[stack[-1]]: stack.append(i) i += 1 # if height[i] > stack[-1] # 当读取到高度值大于栈顶index对应height,说明当前位置满足U形,可以计算面积 else: # 取出U形谷底,弹出 valley = stack[-1] stack.pop() # 弹出后如果stack中为空,跳转到下次判断 if not stack: continue # width calculation w = i - stack[-1] - 1 # height calculation h = min(height[stack[-1]],height[i]) - height[valley] res += w * h return res height = [0,1,0,2,1,0,1,3,2,1,2,1] print(Solution().trap(height))
a48cf4a7e2f714dc2647334027661d9d5a1586fd
alejandro-mosso/language-service
/app/define/services.py
826
3.59375
4
from PyDictionary import PyDictionary import json class DefineService: dictionary = PyDictionary() def __init__(self): return def meaning(self, word): definition = self.dictionary.meaning(word) """ Changes key names to lower case """ if (definition is None): print('DEFINITION NOT FOUND') definition = {} else: if 'Adjective' in definition: definition['adjective'] = definition.pop('Adjective') if 'Adverb' in definition: definition['adverb'] = definition.pop('Adverb') if 'Noun' in definition: definition['noun'] = definition.pop('Noun') if 'Verb' in definition: definition['verb'] = definition.pop('Verb') return definition
be5684b3fc2921f7daeeb8e7135fca33f530bb1d
Paxton0222/Python-AI-class
/第九章 Pandas套件/Ch9_4_4.py
567
3.625
4
import pandas as pd import numpy as np df = pd.read_csv("dists.csv", encoding="utf8") ordinals =["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eigth", "ninth", "tenth", "eleventh", "twelvth", "thirteenth"] df.index = ordinals columns =["city","name", "population"] # 建立空的DataFrame物件 df_empty = pd.DataFrame(np.nan, index=ordinals, columns=columns) #建立空的資料 並且設定 index and colums print(df_empty) # 複製DataFrame物件 df_copy = df.copy() # copy 顧名思義 print(df_copy)
b62c2ae9f6ebfc2fdb870087d8d6c1ff5967da39
2CinnamonToast17/untitled1
/Expenses.py
842
3.90625
4
import matplotlib.pyplot as plt def createBarChart(data, labels): # Number of Bars num_bars = len(data) #This list is the point on the y-axis where each Bar is centered. Here it will be [1, 2, 3...] positions = range(1, num_bars+1) plt.barh(positions, data, align='center') # Set Label of each bar plt.yticks(positions, labels) plt.xlabel('Amount') plt.ylabel('Categories') plt.title('Total Expenditures') plt.grid() plt.show() if __name__ == '__main__': # Number of MONEY I SPENT amount = [] # Corresponding categories categories = [] c = int(input('How many categories would you like?')) for i in range(1, c+1): a = input('Enter Category: ') b = int(input('Enter Expenditure: ')) categories.append(a) amount.append(b) createBarChart(amount, categories)
1a2994707d3b344b3353cb160bf8cebc295618a6
estebanyque/udemy
/python/myprogram.py
384
3.65625
4
#greeting2 = input("Write a greeting: ") #print(greeting2) #a = 2 #b = 3.5 #print(a + b) #print(type(a)) age = input("Enter your age: ") new_age = int(age) + 50 print(new_age) #a = 20 - 10/5 * 3**2 #b = (20 - 10) / 5 * 3**2 #c = (20 - 10) / (5 * 3)**2 #print(a) #print(b) #print(c) c = "Here" print(c.replace("e", "i")) # List methods print(dir(c)) #Help print(help("".replace))
6344395d1888cb6b115ed4d93c2d789bc61f1533
Ham4690/AtCoder
/abc165/b.py
163
3.546875
4
def calc(x): return int(x * 1.01) X = int(input()) val = 100 y = 0 while True: if val >= X: print(y) break val = calc(val) y += 1
03a55f8ae3977923861fb17f67f2d3c4fa4a5aee
allyshoww/python-examples
/exemplos/operadores-aritmeticos.py
391
3.96875
4
#! /usr/bin/python3 num1 = 4; num2 = 5; # Soma num1 + num2; # Subtração num1 - num2; #Divisão num1 / num2; # Setar a variavel number = 1; # Utilizar o módulo & num1 % num2; # Somamos 2 a variável number += 2; #Subtraimos 2 a variavel number -= 2; # Multiplicando a variavel por 2 number *= 2; # Dividindo a variavel por 2 number /= 2; # Resto da divisão por 2 number %= 2;
f5f616ba5502b75a45e1eb382472f83b69674cc9
ledbagholberton/holbertonschool-machine_learning
/math/0x07-bayesian_prob/3-posterior.py
2,864
3.640625
4
#!/usr/bin/env python3 """ calculates the posterior probability for the various hypothetical probabilities of developing severe side effects given the data: x is the number of patients that develop severe side effects n is the total number of patients observed P is a 1D numpy.ndarray containing the various hypothetical probabilities of developing severe side effects Pr is a 1D numpy.ndarray containing the prior beliefs of P If n is not a positive integer, raise a ValueError with the message n must be a positive integer If x is not an integer that is greater than or equal to 0, raise a ValueError with the message x must be an integer that is greater than or equal to 0 If x is greater than n, raise a ValueError with the message x cannot be greater than n If P is not a 1D numpy.ndarray, raise a TypeError with the message P must be a 1D numpy.ndarray If Pr is not a numpy.ndarray with the same shape as P, raise a TypeError with the message Pr must be a numpy.ndarray with the same shape as P If any value in P or Pr is not in the range [0, 1], raise a ValueError with the message All values in {P} must be in the range [0, 1] where {P} is the incorrect variable If Pr does not sum to 1, raise a ValueError with the message Pr must sum to 1 All exceptions should be raised in the above order Returns: the posterior probability of each probability in P given x and n """ import numpy as np def factorial(n): """Function factorial""" factorial = 1 for i in range(1, int(n)+1): factorial = factorial * i return factorial def posterior(x, n, P, Pr): """Function posterior""" if type(n) is not int or n <= 0: raise ValueError("n must be a positive integer") if type(x) is not int or x < 0: msg1 = "x must be an integer that is greater than or equal to 0" raise ValueError(msg1) if x > n: raise ValueError("x cannot be greater than n") if not isinstance(P, np.ndarray): raise TypeError("P must be a 1D numpy.ndarray") if len(P.shape) is not 1: raise TypeError("P must be a 1D numpy.ndarray") if not isinstance(Pr, np.ndarray): raise TypeError("Pr must be a numpy.ndarray with the same shape as P") if P.shape != Pr.shape: raise TypeError("Pr must be a numpy.ndarray with the same shape as P") if np.amax(P) > 1 or np.amin(P) < 0: raise ValueError("All values in P must be in the range [0, 1]") if np.amax(Pr) > 1 or np.amin(Pr) < 0: raise ValueError("All values in Pr must be in the range [0, 1]") sum_p = np.sum(Pr) if np.allclose([sum_p], [1], atol=0) is False: raise ValueError("Pr must sum to 1") comb = factorial(n)/(factorial(x)*factorial(n-x)) likelihood = comb * np.power(P, x) * np.power((1-P), n-x) inter = likelihood * Pr margin = np.sum(inter) return(inter/margin)
abf4cdb5b47f74eb5dddcdd0b079d99e12a9368b
MaxMeiY/code_practice
/tiles_place.py
550
3.90625
4
''' page78 Given an empty plot of size 2*n. we want to place tiles such that the entire plot is coverd. Each tile is of size 2*1 and can be placed either horizontally or vertically. see page78<Dynamic Programming for Coding Interviews> ''' def solution(n): if n == 0 or n == 1: return 1 return solution(n-1) + solution(n-2) def f(n): if n < 2: return 0 elif n == 2: return 1 return f(n-2) + 2 * g(n-1) def g(n): if n < 1: return 0 elif n == 1: return 1 return f(n-1) + g(n-2)
0a902ef254fb471e7b2eace022d7c03d894569ce
driftgeek/Learning-Python
/VerifyPNT.py
2,337
4.03125
4
def VerifyPNT(N): if (N < 2): #The number 2 is considered as the first prime number. So 0 and 1 have to be excluded from the range. return False if (N == 2) or (N == 3): # N has to be prime numbers. 2 and 3 are prime numbers. return True if (N == 5) or (N == 7): # 5 and 7 are prime numbers. return True if (N % 2) == 0 or (N % 3) == 0: # N cannot be multiples of 2 and 3. If it is, it will be considered as a composite number. return False if (N% 5) == 0 or (N % 7) == 0:# N cannot be multiples or 5 or 7 in order for this to work. The output will be considered False. return False for i in range (2, int(N**(0.5))+1): if (N%i) == 0: #N cannot be divisible by i. return False return True piN = 0 #This is my pi(N) N1= 10 # This is same as 10**1 N2= 100 # This is the same as 10**2 N3= 1000 # This is the same as 10**3 N4= 10000 # This is the same as 10**4 N5= 100000 # This is the same as 10**5 for i in range (1,N1): if VerifyPNT(i) == True: ## print(i), ##I wanted to verify the prime numbers in the range from 1-10. piN += 1 tempN1 = piN/(math.log(N1)) print [N1, piN, tempN1] for i in range (11,N2): # I excluded the previous range 1-10 from finding out the range from (1,100). Previously, I noticed I was getting an added number of prime numbers. It is suppose to be 25 but I was getting 29 instead. if VerifyPNT(i) == True: ## print (i),# I wanted to verify the prime numbers in the range from 1-100. piN += 1 tempN2 = piN/(math.log(N2)) print [N2, piN, tempN2] for i in range (101,N3): if VerifyPNT(i) == True: #### print(i), # Just verifying the prime numbers in the range. piN += 1 tempN3 = piN/(math.log(N3)) print [N3, piN, tempN3] for i in range (1001, N4): if VerifyPNT(i) == True: ## print(i), # Just verifying the prime numbers in the range. piN += 1 tempN4 = piN/(math.log(N4)) print [N4, piN, tempN4] for i in range (10001, N5): if VerifyPNT(i) == True: ## print(i), # Just verifying the prime numbers in the range. piN += 1 tempN5 = piN/(math.log(N5)) print [N5, piN, tempN5]
f48c11628be0ce87c1eb8fbb2fb9d1fa5632f6df
chivalry/algorithm_design_manual
/light_more_light.py
1,456
4.3125
4
"""" There is man named ”mabu” for switching on-off light in our University. He switches on-off the lights in a corridor. Every bulb has its own toggle switch. That is, if it is pressed then the bulb turns on. Another press will turn it off. To save power consumption (or may be he is mad or something else) he does a peculiar thing. If in a corridor there is n bulbs, he walks along the corridor back and forth n times and in i-th walk he toggles only the switches whose serial is divisable by i. He does not press any switch when coming back to his initial position. A i-th walk is defined as going down the corridor (while doing the peculiar thing) and coming back again. Now you have to determine what is the final condition of the last bulb. Is it on or off? Input The input will be an integer indicating the n’th bulb in a corridor. Which is less then or equals 232 − 1. A zero indicates the end of input. You should not process this input. Output Output ‘yes’ if the light is on otherwise ‘no’, in a single line. Sample Input 3 6241 8191 0 Sample Output no yes no """ def walk(n): lights = [False] * n for i in range(n): for j in range(n): denom = i + 1 numer = j + 1 toggle = numer % denom == 0 if toggle: lights[j] = not lights[j] return lights[-1] if __name__ == '__main__': print(walk(3)) print(walk(6241)) print(walk(8191))
4b36b126b383eca6e7236ed36527883bf2e45d17
Elias-Giannakidis/Deep_Q_learning_avoid_enemies
/car.py
1,165
3.546875
4
import pygame import math import Colors as c class Car: def __init__(self, start_position): self.x = start_position[0] self.y = start_position[1] self.width = 25 self.hight = 25 self.speed = 7.5 self.angle = 0 self.dth = math.pi * (1 / 6) self.line = 200 def move(self): self.y -= self.speed * math.cos(self.angle) self.x += self.speed * math.sin(self.angle) def turn_right(self): self.angle += self.dth if self.angle > 2 * math.pi: self.angle -= 2*math.pi def turn_left(self): self.angle -= self.dth if self.angle < -2 * math.pi: self.angle += 2*math.pi def draw(self, win): pygame.draw.rect(win, c.BLACK, (self.x, self.y, self.width, self.hight), 0) pygame.draw.line(win, c.WHITE, (self.x + self.width/2, self.y + self.hight/2), (self.x + self.width/2 + self.line * math.cos(self.angle - math.pi/2), self.y + self.hight/2 + self.line * math.sin(self.angle - math.pi/2)))
f022da5068eb13500a08b829a235335bff448f34
giselaortt/numerical_analyses
/second_homework.py
1,846
3.515625
4
# -*- coding: utf-8 -*- ''' ALUNA: GISELA MOREIRA ORTT NUSP: 8937761 ''' import matplotlib.pyplot as plt import numpy as np import math def method_euler_modified( dy_dx, t_final, t_initial = 0, number_of_iterations = None, delta_t = None, y_initial = 0 ): y = [y_initial] if(delta_t is None): delta_t = float(t_final)/float(number_of_iterations) time = np.arange( t_initial, t_final, delta_t ) for t in time : k1 = dy_dx(t, y[-1]) k2 = dy_dx(t + delta_t, y[-1] + delta_t * k1 ) y.append( y[-1] + (delta_t / 2.0) * ( k1 + k2 )) return y def integral( t ): return math.exp( t )*( math.sin( 2.0 * t ) ) + 1 def dy_dx( t, x ): return math.exp(t)*( math.sin( 2.0 * t ) + 2.0*math.cos( 2.0 * t ) ) def question_three(): deltas = [ 0.1/pow( 2.0, m ) for m in range(0, 6) ] for delta_t in deltas: teste = method_euler_modified( dy_dx, 1, delta_t = delta_t, y_initial = 1 ) #stop + step se faz necessario uma vez que a biblioteca numpy faz um intervalo aberto plt.plot( np.arange( 0, 1 + delta_t, delta_t ), teste ) plt.show() time = np.arange( 0,1+delta_t, delta_t ) plt.plot( time, [ integral( t ) for t in time ], linewidth = 2, label = 'Sol. Exata' ) plt.show() def question_two( time_final = 1 ): deltas_t = [ 0.1/pow( 2.0, m ) for m in range(0, 6) ] colors = [ 'b', 'r', 'c', 'y', 'k', 'm' ] for i in range(6): x = [1] delta_t = deltas_t[i] #stop + step se faz necessario uma vez que a biblioteca numpy faz um intervalo aberto time = np.arange( 0, time_final + delta_t, delta_t ) for t in time[:-1] : x.append( x[-1] + delta_t * ( -100*x[-1] ) ) plt.plot( time, x, color = colors[i] ) time = np.arange( 0, time_final, 0.000001 ) plt.plot( time, [ math.exp( -100*t ) for t in time ], linewidth = 2, label = 'Sol. Exata' ) plt.show() #question_three() #question_two( )
c155b678fe5c2dabb71173279a25e3a15c9c5631
feladie/info-206
/hw9/hw9.1.anna.cho.py
1,160
4.5625
5
# (1) A reversi number is a number that reads the same forwards and backwards, such as 303. # The largest reversi number that is a product of two 2-digit numbers is 9009 = 91 x 99. # Write a Python program to find the largest reversi number that is a product of two 3-digit numbers. # Your output format should be "abc x def = ghiihg" (where the letters are replaced by digits). # Traditional Method def find_reversi(): # Creates a list of the products of two 3-digit numbers. Returns the largest reversi within list. products = {} # products of 3-digit numbers for number in range(100, 1000): for other_number in range(100, 1000): product = number * other_number if is_reversi(product): products[product] = str(number) + " x " + str(other_number) max_reversi = max(products.keys()) print(products[max_reversi] + " = " + str(max_reversi)) def is_reversi(product): # Checks whether a number is a reversi. str_product = str(product) return str_product == str_product[::-1] ########################################################################################## # Main def main(): find_reversi() if __name__ == '__main__': main()
35d49f6c3250553c7a4070003b0c08468ddf06bb
rammie/advent-of-code-2020
/day3.py
585
3.765625
4
import os from functools import reduce from operator import mul slope = [list(l) for l in open("day3.input").read().split(os.linesep)] def find_trees(slope, sx=3, sy=1, x=0, y=0, trees=0): h, w = len(slope), len(slope[0]) if y >= h: return trees has_tree = slope[y][x] == "#" return find_trees(slope, sx, sy, (x + sx) % w, y + sy, trees + int(has_tree)) # Part 1 answer print(find_trees(slope)) # Part 2 answer trees = [find_trees(slope, sx, sy) for sx, sy in [ [1, 1], [3, 1], [5, 1], [7, 1], [1, 2], ]] print(reduce(mul, trees, 1))
b010533c168622028e0f67a3ebea2b9257176eac
SuperMartinYang/learning_algorithm
/leetcode/medium/The_Maze_II.py
1,276
3.5
4
class Solution(object): def the_maze_ii(self, grid, i, j, x, y): """ DFS, when deeper, count when roll, memo to memoize result of path passed, return minimum :param grid: 2D list, maze :return: shortest path to there """ m = len(grid) n = len(grid[0]) if m else 0 memo = [[1e9] * n for _ in range(m)] memo[i][j] = 0 d = ((1, 0), (0, 1), (0, -1), (-1, 0)) def dfs(ni, nj): if ni == x and nj == y: return # no need to memo whether we visited it before. because we may from a shorter path to a certain point for p in d: ti, tj, cnt = ni, nj, memo[ni][nj] while 0 <= ti + p[0] < m and 0 <= tj + p[1] < n and grid[ti + p[0]][tj + p[1]] != 1: ti += p[0] tj += p[1] cnt += 1 if memo[ti][tj] > cnt: memo[ti][tj] = cnt dfs(ti, tj) dfs(i, j) return memo[x][y] if memo[x][y] != 1e9 else -1 grid = [[0,0,1,0,0], [0,0,0,0,0], [0,0,0,1,0], [1,1,0,1,1], [0,0,0,0,0]] si = 0 sj = 4 ex = 3 ey = 2 ex1 = 4 ey1 = 4 print(Solution().the_maze_ii(grid, si, sj, ex1, ey1))
86780ea69ccc3aa118b4439370dfc9dea468e461
prabhathkota/MLPractise
/jumpStartScikitLearn/8_ensembles/7_gradient_boosting_classification.py
772
3.546875
4
# Gradient Boosting Classification # Gradient Boosting is an ensemble method that uses boosted decision trees like AdaBoost, # but is generalized to allow an arbitrary differentiable loss function (i.e. how model error is calculated). from sklearn import datasets from sklearn import metrics from sklearn.ensemble import GradientBoostingClassifier # load the iris datasets dataset = datasets.load_iris() # fit a Gradient Boosting model to the data model = GradientBoostingClassifier() model.fit(dataset.data, dataset.target) print(model) # make predictions expected = dataset.target predicted = model.predict(dataset.data) # summarize the fit of the model print(metrics.classification_report(expected, predicted)) print(metrics.confusion_matrix(expected, predicted))
1ffde4bafb513e8d136bf0c746c5eb990ffb0929
KarolinaStepien/WDI
/3 Animacje/.idea/węże_na_sawannie.py
798
3.8125
4
import random size = int(input('Podaj rozmiar sawanny: ')) #poczatkowa tablica weza snake = [] a = random.randint(0,size-1) snake.insert(0, a) snake.insert(0, a) snake.insert(0, a) while(len(snake)<size): a = random.randint(0,size-1) while a==snake[0]: a = random.randint(0, size-1) snake.insert(0, a) snake.insert(0, a) snake.insert(0, a) for k in range(2): a = random.randint(0, size-1) while a==snake[0]: a = random.randint(0, size-1) for i in range(3): snake.insert(0, a) for i in range(size): for j in range(size): if snake[i] == j: print('o', end=' ') else: print('.', end=' ') print() print() snake.pop(size-1)
03e90d7dd93bc4ea026b4efaa19116d1009bbd57
lamelameo/Algorithms-Udacity-Misc
/Algorithms/AVLTree.py
15,632
3.796875
4
""" Implementation of an AVL Tree using python dicts for pointer like connections. Supports duplicate values and the following operations: - Insert in O(logn) - Delete in O(logn) - Rank in O(logn) - Search in O(logn) - Successor in O(logn) """ class AVLTree: """ AVL tree data structure supporting O(logn) search, insert, and delete queries in O(n) space Takes one optional parameter: array - a List object which will be converted to a tree Each node in the tree is a list containing 7 items: (key, parent, left, right, height, children, size) Using the children attribute we can determine the rank of item in sorted list The size attribute stores the number of this key that are present in the set """ def __init__(self, array=None): # TODO: use dict for pointer like functionality? This also means we have O(1) search not O(logn)?? # are there losses for dict for add/del - preprocess dict with array item with empty tuples? # Can change dict syntax to something nicer? # self.tree = [] self.tree = dict() self.root = None self.size = 0 # we have been given an array to convert to a tree if array: for item in array: self.insert(item) # return a string representation of the tree, successive line representing successive heights # TODO: implement this def __str__(self): tree = "" queue = [self.root] while queue: tree += str(queue.pop()) while True: break return "not implemented" # find the parent node to which the item should be attached, or the item's node if it already exists # return a tuple, tuple[0] is the node key and tuple[1] is 1 or 0 representing item node or parent node def search(self, item): node = self.tree.get(item) if node: return node, 1 else: current = self.tree.get(self.root) # tree is empty if not current: return None, 0 # traverse tree while True: if item < current[0]: # item less than node - go left if current[2]: current = self.tree[current[2]] else: return current, 0 else: # go right if current[3]: current = self.tree[current[3]] else: return current, 0 # insert item to tree def insert(self, item): self.size += 1 node, found = self.search(item) # inserting into empty tree if not node: self.root = item self.tree[item] = [item, None, None, None, 0, 0, 1] return # item already in tree, increment size, update #children attribute for O(logn) parents if found: node[6] += 1 self.rebalance(self.tree.get(node[1])) else: # have to add item as a child of given parent node self.tree[item] = [item, node[0], None, None, 0, 0, 1] if item < node[0]: # update parent's left child pointer node[2] = item else: # update parent's right child pointer node[3] = item # check if we need to balance the tree self.rebalance(node) # convenient function to call to deal with height of a node taking into account node=None def height(self, node): if not node: return -1 else: return node[4] # update height and children attributes of a given node def update_height(self, node): left = self.tree.get(node[2]) right = self.tree.get(node[3]) node[5] = 0 # update children attribute if right: node[5] += right[6] + right[5] if left: node[5] += left[6] + left[5] # update height attribute node[4] = 1 + max(self.height(left), self.height(right)) # def rebalance(self, node): while node: # update height first self.update_height(node) # left = self.tree.get(node[2]) right = self.tree.get(node[3]) # left unbalanced if self.height(left) >= 2 + self.height(right): # left.left >= left.right if self.height(self.tree.get(left[2])) >= self.height(self.tree.get(left[3])): self.right_rotate(node) # left.left < left.right, must rotate left child first before node else: self.left_rotate(left) self.right_rotate(node) # right unbalanced elif self.height(right) >= 2 + self.height(left): # right.right >= right.left if self.height(self.tree.get(right[3])) >= self.height(self.tree.get(right[2])): self.left_rotate(node) # right.right < right.left else: self.right_rotate(right) self.left_rotate(node) node = self.tree.get(node[1]) # def left_rotate(self, a): b = self.tree.get(a[3]) beta = self.tree.get(b[2]) parent = self.tree.get(a[1]) # if A has a parent, change its left/right child from A to B and update parent of B if parent: if parent[0] > a[0]: parent[2] = b[0] else: parent[3] = b[0] b[1] = parent[0] else: b[1] = None self.root = b[0] # switch beta to be child of A and then switch A to be left child of B if beta: a[3] = beta[0] beta[1] = a[0] else: a[3] = None # update A to B links a[1] = b[0] b[2] = a[0] # update heights of A then B (A is child) self.update_height(a) self.update_height(b) # def right_rotate(self, b): a = self.tree.get(b[2]) beta = self.tree.get(a[3]) parent = self.tree.get(b[1]) # if B has a parent, change its left/right child from and update parent of A if parent: if parent[0] > b[0]: parent[2] = a[0] else: parent[3] = a[0] a[1] = parent[0] else: a[1] = None self.root = a[0] # switch beta to be child of B and then switch B to be right child of A if beta: b[2] = beta[0] beta[1] = b[0] else: b[2] = None # update A to B links b[1] = a[0] a[3] = b[0] # update heights of B then A (B is child) self.update_height(b) self.update_height(a) # remove a node from the tree and rebalance # 4 possible cases: # - Node has duplicate values, so decrement size attribute, no deletion # (No Duplicate values) # - 2 children; find the successor of the node and use this as its replacement before deleting # - 1 child; use this child as the node's replacement before deleting # - 0 children; delete the node def remove(self, item): # TODO: simplify code, probably can amalgamate lots of the branches node = self.tree.get(item) if not node: print("Item not found.") return self.size -= 1 # handle updating links between parent and replacement for deleted node def modify_parent(self_, child): # update deleted nodes parent link if parent: # node is a left child if parent[2] == node[0]: parent[2] = child[0] else: parent[3] = child[0] # update left parent link child[1] = parent[0] else: # deleted node was the root self_.root = child[0] child[1] = None # if duplicates only have to change item size attribute and update parent children attribute if node[6] > 1: node[6] -= 1 else: # handle node with 0,1,2 children parent = self.tree.get(node[1]) # node has left child if node[2]: left = self.tree[node[2]] # 2 children - get successor and replace if node[3]: succ = self.successor(node) succ_par = self.tree.get(succ[1]) succ_child = self.tree.get(succ[3]) # successor has a right child if succ_child: # replace successor with its child - 2 cases # successor is deleted nodes right child if succ_par == node: succ_par[3] = succ_child[0] succ_child[1] = succ_par[0] # successor is a left child of some node in the right sub tree of deleted node else: succ_par[2] = succ_child[0] succ_child[1] = succ_par[0] # replace node to be deleted with successor succ[3] = node[3] self.tree[node[3]][1] = succ[0] succ[2] = left[0] left[1] = succ[0] # update deleted nodes parent link modify_parent(self, succ) node = succ_child # successor has no child else: # update left child link succ[2] = left[0] left[1] = succ[0] # update deleted nodes parent link modify_parent(self, succ) # if successor was right child of deleted node, we are done, otherwise must update right child # and parent of the successor if succ_par != node: succ[3] = node[3] self.tree[node[3]][1] = succ[0] succ_par[2] = None node = succ_par else: node = succ # one (left) child else: # update deleted node's parent's link modify_parent(self, left) else: # only one (right) child if node[3]: right = self.tree[node[3]] # update deleted nodes parent link modify_parent(self, right) # 0 children else: # update deleted nodes parent link modify_parent(self, [None, None]) node = parent # delete item from dict or set to None # del self.tree[item] self.tree[item] = None # rebalance the tree starting from lowest node that has been affected self.rebalance(node) # return the index the given item would be placed in a sorted array of the items in the tree def rank(self, item): # find items place in tree, then climb up tree to root counting number of nodes smaller than item by # looking at parent size + left child at each step up we moved to a parent with a smaller value count = 0 node, _ = self.search(item) # found item or item larger than insert parent node, count then start loop while node: # only count if we move up to a parent that is less than node (will be less than item too) if node[0] <= item: count += node[6] left = self.tree.get(node[2]) if left: count += left[5] + left[6] # update node and parent node = self.tree.get(node[1]) return count # TODO: what if we return None, ie no successor? # get the next highest item in sorted list def successor(self, node): # if we have a right subtree, find minimum in that tree right = self.tree.get(node[3]) if right: current = right # succ = self.search(node[0] + 1) # shortcut left = self.tree.get(right[2]) while left: current = left left = self.tree.get(current[2]) return current else: current = node # if no right subtree, must move up to parents until root or until a parent is greater than current node # to get the next highest node parent = self.tree.get(node[1]) if not parent: return None while parent[3] == current[0]: current = parent parent = self.tree.get(current[1]) # node was largest in the tree if not parent: break return parent def max(self): node = self.tree.get(self.root) if not node: return None while True: child = self.tree.get(node[3]) if not child: return node[0] else: node = child def test(): # Check different conditions for rotations, successor, rank, insert, remove # insert test_array = [8, 3, 13, 2, 6, 11, 14, 1, 5, 7, 9, 12, 15, 4, 10] tree = AVLTree(test_array) print(tree.tree) print('max', tree.max()) tree2 = AVLTree() for x in test_array: tree2.insert(x) print("same tree?", tree.tree == tree2.tree) # rotation # right unbalanced - right child right rotate then node left rotate array = [4, 2, 9, 1, 3, 7, 10, 6, 8, 11, 5] tree2 = AVLTree(array) print("tree2:", tree2.tree) # successor for x in [1,3,6,7,8,13,15]: print(x) print(tree.successor(tree.tree.get(x))) # rank print("\nrank") for x in [0,1,4,6,8,10,15,16]: print(tree.rank(x)) # add duplicates for x in [1,1,4,6,10,10,15,15]: tree.insert(x) print("duplicates:") for x in [0,1,4,6,8,10,15,16]: print(tree.rank(x)) print("test!!") array = [6,1,10,10,5,5,9] t = AVLTree(array) for x in [0, 0.5, 1, 1.9, 4, 6, 10, 11]: print(t.rank(x)) quit() # remove array = [8, 3, 13, 2, 6, 11, 16, 1, 5, 7, 9, 12, 15, 18, 4, 10, 14, 17, 19, 20] tree3 = AVLTree(array) print(tree3.tree) print() tree3.remove(8) print(tree3.tree) print() tree3.remove(20) print(tree3.tree) array += [20,20,10,10,10,13] tree3 = AVLTree(array) tree3.remove(20) tree3.remove(8) print(tree3.tree) # extra tests for all conditions of remove array = [8, 3, 13, 2, 6, 11, 14, 1, 5, 7, 9, 12, 15, 4, 10] print('remove') tree3 = AVLTree(array) print("size", tree3.size) tree3.remove(13) print(tree3.tree) print("size", tree3.size) tree3 = AVLTree(array) tree3.remove(6) print(tree3.tree) tree3 = AVLTree(array) tree3.remove(3) print(tree3.tree) tree3 = AVLTree(array) tree3.remove(9) print(tree3.tree) tree3.remove(2) print(tree3.tree) # test()
ea4ffcb2cf452b88f68b490def113765638bb3bb
bennyk53/python
/Unit 2 Selective Process and Types of Variables/Change.py
1,476
4.15625
4
# Name: Ben Koczwara # Date: Sept.5,2013 # Purpose: this program will find the combination of change print "Change Maker" print "------------" print print "This progaram will determine the combination for values under a dollar" print again = "y" while again == "y": money = int(raw_input("Enter the amount of money in cents under 100: ")) print print money,"cents requires:", quarters = money // 25 if quarters > 1: q = "quarters" else: q = "quarter" money = money % 25 dimes = money // 10 if dimes > 1: d = "dimes" else: d = "dime" money = money % 10 nickels = money // 5 if nickels > 1: n = "nickels" else: n = "nickel" money = money % 5 pennies = money if pennies >1: p = "pennies" else: p = "penny" if quarters > 0: print quarters,q, if dimes > 0: print dimes,d, if nickels > 0: print nickels,n, if pennies > 0: print pennies,p, print print answer = False while not answer: again = raw_input("Would you like to find another change combination? (y/n): ").lower() print if again != "" and (again[0] == "n" or again[0] == "y"): answer = True else: print "You must enter yes or no" print again = again[0]
3740064041ad4e68a5e981b0fc6824df5fb24800
vibhor-shri/Python-Basics
/basics/ArithmeticOperators.py
497
4.5
4
# Arithmetic operators in python separator = "============================" print("Basic Arithmetic") print(separator) # + Addition print("Addition") print(3+2) # - Subtraction print("Subtraction") print(3-2) # * Multiplication print("Multiplication") print(3*2) # / fraction division print("fraction division") print(3/2) # // Integer division print("Integer division") print(3//2) # ** exponentiation print("exponentiation") print(3**2) # % remainder print("remainder") print(3%2)
0b83a95ce3e686f9c0da5b9980bd28de463a7afa
schmit/perl
/perl/distributions.py
843
3.59375
4
from collections import namedtuple import random class Normal: def __init__(self, mu, sigma): self.mu = mu self.sigma = sigma def sample(self): return random.gauss(self.mu, self.sigma) @property def mean(self): return self.mu def __repr__(self): return "Normal({:.2f}, {:.2f})".format(self.mu, self.sigma) class Bernoulli: def __init__(self, p): self.p = p def sample(self): return 1 if random.random() < self.p else 0 @property def mean(self): return self.p def __repr__(self): return "Bernoulli({:.2f})".format(self.p) class Rademacher: def sample(self): return 1 if random.random() < 0.5 else -1 @property def mean(self): return 0 def __repr__(self): return "Rademacher"
45703a7fad1d5391c6c981af7c1c7ea27eee2a4a
AndreyAAleksandrov/GBPython
/Algorythm/Lesson3_Task5.py
879
3.9375
4
# 5. В массиве найти максимальный отрицательный элемент. Вывести на # экран его значение и позицию в массиве. import random size = 10 list = [random.randint(-99, 99) for _ in range(size)] print(f"Array : {list}") min_index = 0 min_item = list[0] for index in range(1,size): if list[index] < min_item: min_index = index min_item = list[index] if min_item >= 0: print(f"В массиве нет отрицательных элементов") else: wildcard = ["" for _ in range(size)] for i in range(size): if min_item == list[i]: wildcard[i] = min_item print(f"Wildcard : {wildcard}") print(f"Максимальный отрицательный элемент: {min_item} находится на позиции {min_index}")
da5c455e8be1f7e25a8527ae71b3075fc5a4c27e
ConstantineChe/prog1
/3_6.py
584
4.125
4
from math_util import is_natural_number def power(x, n): return x if n == 1 else power(x, n - 1) * x while True: try: x = float(input("Введіть основу: ")) n = int(input("Введіть ступінь: ")) if is_natural_number(n): break else: print("Ступінь має бути натуральним числом.") except ValueError: print("Основа має бути дійсним числом, а ступінь - натуральним.") print("%f^%f = %f" % (x, n, power(x, n)))
94e572b6620e751f4dfd80e2a7061f05051e6fc3
JunkaiCheng/Game-of-Gomoku
/agent.py
2,577
3.5625
4
import board from minimax import Minimax from alphabeta import AlphaBeta class MinimaxAgent: def __init__(self, firstPlayer): self.board = board.Board() if firstPlayer: self.me = "x" else: self.me = "o" if firstPlayer: self.oppo = "o" else: self.oppo = "x" # self.me = firstPlayer ? "x" : "o" # self.oppo = firstPlayer ? "o" : "x" self.firstPlayer = firstPlayer # get opponent's turn and place move def receiveTurn(self, coor): self.board.placeMove(coor, self.oppo) return coor def firstMove(self): # use default first move - the center of the board self.board.placeMove((3, 3), self.me) return (3, 3) def pickMove(self): minimax = Minimax(self.board) if self.me == "x": return minimax.playMinimax(self.board, 3, True) elif self.me == "o": return minimax.playMinimax(self.board, 3, False) def takeTurn(self): move = self.pickMove() print("Picked move - ", move) self.board.placeMove(move, self.me) return move # winner 1 -> me win # winner 2 -> oppo win # 0 -> tie def getWinner(self): return self.board.winner() class AlphaBetaAgent: def __init__(self, firstPlayer): self.board = board.Board() if firstPlayer: self.me = "x" else: self.me = "o" if firstPlayer: self.oppo = "o" else: self.oppo = "x" # self.me = firstPlayer ? "x" : "o" # self.oppo = firstPlayer ? "o" : "x" self.firstPlayer = firstPlayer # get opponent's turn and place move def receiveTurn(self, coor): self.board.placeMove(coor, self.oppo) return coor def firstMove(self): # use default first move - the center of the board self.board.placeMove((3, 3), self.me) return (3, 3) def pickMove(self): alphabeta = AlphaBeta(self.board) if self.me == "x": return alphabeta.playAlphabeta(self.board, 3, -100000, 100000, True) elif self.me == "o": return alphabeta.playAlphabeta(self.board, 3, -100000, 100000, False) def takeTurn(self): move = self.pickMove() print("Picked move - ", move) self.board.placeMove(move, self.me) return move # winner 1 -> me win # winner 2 -> oppo win # 0 -> tie def getWinner(self): return self.board.winner()
25ec4bd9b3a52d647b12e23c3cef32d89bc58368
sovietspy2/dataCleaner
/script.py
1,543
3.609375
4
from sys import argv import sys import re #regex import os import csv import pandas as pd def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] new_file_name = "clean_data.csv" if (len(argv))==1: print("Error! No params! Usage: script.py <filename> <filename> <filename> ") sys.exit() sentences = [] languages = [] for argument in argv: try: if (argument==argv[0]): print("Cleaning started . . . ") continue try: file = open(argument+".txt", "r", encoding="utf-8") except FileNotFoundError: print("Error! No file with the name: "+argument +" (Provide filename without extenstion eg: german instead of german.txt) ") sys.exit() file.seek(0) lines = file.readlines() #new file #new_file = open(new_file_name, "a+", encoding="utf8") for line in lines: new_line = re.split(r'\t+', line)[1] new_line = new_line[0:len(new_line)-1] sentences.append(new_line) languages.append(argument) #new_file.write(new_line) file.close() except EnvironmentError: print("Error! file in wrong format!") sys.exit() df = pd.DataFrame(data={"sentence":sentences, "language":languages}) df.to_csv(new_file_name , sep=";", index=False, columns=["sentence", "language"], encoding="utf8") print("Cleaning completed successfully. New file created: "+os.getcwd()+"\\"+new_file_name)
8d319df95f389a66d074da245cb01a95b1f1e5a1
Sanlook/guvi
/task/looping/even.py
188
3.921875
4
n=int(input("enter the starting range:")) m=int(input("enter the ending range:")) sum=0 for num in range(n, m + 1): if num % 2 == 0: sum=sum+num print(sum)
7a4d0d25148ff612f808bd53c14da4048bb6c252
ccrownhill/NewtonMethod
/newton_method.py
2,345
3.78125
4
#!/usr/bin/python3 import argparse def newton_root(xn, f, f_prime, margin, verbose=False): i = 0 while f(xn) > margin or f(xn) < -margin: i += 1 try: xn = xn - f(xn)/f_prime(xn) except ZeroDivisionError: print(f"Bad x-value: Derivative will become 0. You can't divide by zero.") return if verbose: print(f"xn in Iteration {i} = {xn}") if i > 1e5: return return xn def calculate_roots(start_values, f, f_prime, margin=1e-12, verbose=False): roots = list() for start_x in start_values: print(f"Starting with x value: {start_x} ...") root = newton_root(start_x, f, f_prime, margin=margin, verbose=verbose) print(f"\t--> Calculated root value: {root}\n") if root: roots.append(root) return roots def remove_duplicates(roots): for i in range(len(roots)-1, -1, -1): # iterate backwards to prevent element skipping after deletion if roots.index(roots[i]) != i: del roots[i] return roots def generate_root_output(roots, precision): if not roots: return "No roots found" root_output = "Roots:\n" for i in range(len(roots)): root_output += f"x{i+1} = {roots[i]:.{precision}f}\n" return root_output if __name__=="__main__": parser = argparse.ArgumentParser() parser.add_argument('-f', '--function', type=str, required=True) parser.add_argument('-d', '--derivative', type=str, required=True) parser.add_argument('-m', '--margin', type=float, default=1e-12, required=False) parser.add_argument('-p', '--precision', type=int, default=10, required=False) parser.add_argument('start_values', type=float, nargs='*', default=[-2.0, -0.2, 0.2, 2.0]) args = parser.parse_args() f = lambda x: eval(args.function) f_prime = lambda x: eval(args.derivative) print(f"Setting precision to {args.precision} decimals (use -p or --precision to change this)\n") roots = calculate_roots(args.start_values, f, f_prime, margin=args.margin, verbose=False) roots = list(map(lambda x: round(x, args.precision), roots)) roots = remove_duplicates(roots) root_output = generate_root_output(roots, args.precision) print(root_output, end='') # don't put another newline at the end
8d41d4595308683fbc0f7be0d94e0ac099b412e7
jasminekaurmann/first-project
/coinflip.py
861
4.09375
4
import random money = 100 def coin_flip(guess, bet): global money #Bet should be greater than 0 if bet <= 0: print("Your bet needs to exceed 0 to play.") return 0 result=random.choice(['heads', 'tails']) is_correct = (guess == result) if is_correct : money = money + bet print(f"You guessed {guess} and the coin landed on {result}. You won ${bet}, now you have ${money}.") else: money = money - bet print(f"You guessed {guess} and the coin landed on {result}. You lost ${bet}, now you have ${money} loser:p.") while True: user_guess = input("Heads or Tails?") user_guess = user_guess.lower() user_guess = user_guess.strip() user_bet = input(f"You have ${money}. How much are you willing to bet?") user_bet = int(user_bet) coin_flip(user_guess, user_bet)
bdcf42fadac8449f956ca49de1bfb58f3d65337a
fatukunda/python-intro
/battleship.py
1,243
4.21875
4
"""Battleship game""" from random import randint board = [] for row in range(5): board.append(["O"] * 5) def print_board(board_in): for row in board_in: print(" ".join(row)) print_board(board) def random_row(board): return randint(0, len(board) -1) def random_col(board): return randint(0, len(board) -1) # Get a random row and column where the ship is hidden ship_row = random_row(board) ship_col = random_col(board) for turn in range(4): print('Turn ' + str(turn + 1)) #Get the user's guess of the row and column where the ship is hidden guess_row = int(input('Guess Row: ')) guess_col = int(input('Guess Col: ')) if guess_row == ship_row and guess_col == ship_col: print('Congratulations! You sank my battleship') break else: if guess_row not in range(5) or guess_col not in range(5): print("Oops, that's not even in the ocean.") elif board[guess_row][guess_col] == 'x': print('You guessed that one already') else: print('You missed my battleship!') board[guess_row][guess_col] = "x" print_board(board) if (turn == 3): print('Game over') print_board(board)
852df89644d1b150aedac37e862d15696ed3c6bb
zhinan18/Python3
/code/base/lesson9/9-4.py
276
4.03125
4
def calculate_tax(price, tax_rate): total = price + (price * tax_rate) my_price = 1 print(my_price) return total my_price = float(input("Enter a price: ")) totalPrice = calculate_tax(my_price, 0.06) print("price = ", my_price, " Total price = ", totalPrice)
691653b49812842dda4b642c225e6d29aef96968
sagar87/Wichtel
/wichtel.py
3,310
3.515625
4
import random import smtplib ### Specify the eMail address of the organizer and set the username and password of the outgoing SMTP server. fromaddr = '' username = '' password = '' def sendMail(fromaddr, toaddrs, msg): """ sendMail sends a Mail to person (toaddr) with a message defined in (msg). """ FROM = fromaddr TO = toaddrs SUBJECT = "Secret Santa Gift Exchange" TEXT = msg # Prepare actual message message = "\From: %s\nTo: %s\nSubject: %s\n\n%s" % (FROM, TO, SUBJECT, TEXT) # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, message) server.quit() def createNameList(text): """ Takes a tabs top separated txt-file as input and returns a list which contains all persons participating in secret santa. In order to process the txt-file correctly, the txt-file should have this format: forename surname*TABSTOP*eMail address """ fopen = open(text, 'r') names = [] for line in fopen: fields = line.split('\t') names.append(fields[0]) #eMail.append(fields[1]) return names def createEmailDic(text): """ Takes a tabs top separated txt-file as input and returns a dictionary which contains all persons and their eMail adresses. In order to process the txt-file correctly, the txt-file should have this format: forename surname*TABSTOP*eMail address """ fopen = open(text, 'r') eMail = {} for line in fopen: fields = line.split('\t') eMail[fields[0]] = fields[1][0:-1] #print fields[1] return eMail def findWichtelPartner(names): """ Takes a list of names and assigns to each name another name. FindWichtelPartner returns a dictionary with all randomly chosen names. """ copy1 = list(names) copy2 = list(names) partner = {} while len(copy1) != 0: #for i in range(0, len(names)): name1 = random.choice(copy1) name2 = random.choice(copy2) #print name1, name2 if name1 == name2: pass else: partner[name1] = name2 copy1.remove(name1) copy2.remove(name2) return partner def createTextAndSendMail(text): """ This function finally sends the mails to all guests. """ eMail = createEmailDic(text) names = createNameList(text) partner = findWichtelPartner(names) for name in partner.keys(): msg = """Dear %s,\n\nthe Secret Santa Script has (randomly) chosen %s as your partner. We (the people attending the X-ray crystallography course) spontaneously decided to make a christmas dinner next week (further informations will be posted on fb). To spice things up a bit we want to organize a Secret Santa Gift Exchange, therefore, your have to get a present for %s (max. 5 Euro). This Email was sent automatically to: %s. If you want to organize your own Secret Santa Gift Exchange you may want to use pieces of paper, otherwise check: https://github.com/sagar87/Wichtel/ ;). \n""" % (name.split(' ')[0], partner[name], partner[name].split(' ')[0], eMail[name]) #print msg sendMail(fromaddr, eMail[name], msg)
27ecd096287ab68d9a23de0e62bc78824b5c56c7
Deep455/Python-programs-ITW1
/End Semester Assignment/1.py
760
4.0625
4
def quick_sort(lst,start,end): temp1,temp2=start,end if(start>=end): # terminating condition for quick_sort return 0 pivot=lst[start] while(start<end): while(lst[start]<pivot): start+=1 while(lst[end]>pivot): end-=1 if(start<end): lst[start],lst[end]=lst[end],lst[start] else: break pivot,lst[end]=lst[end],pivot quick_sort(lst,temp1,end-1) # left side sort quick_sort(lst,end+1,temp2) # right side sort n=int(input("Enter number of elements : ")) lst=[] print("Enter {} numbers".format(n)) for i in range(n): x=int(input()) lst.append(x) print("Given Data : ") print(lst) quick_sort(lst,0,n-1) print("Sorted Data : ") print(lst)
48bb8a510ac3a1db33982b712fdcace59dd14047
RaulRC/machine-learning-use-cases
/courses/deep-learning/src/neuron.py
415
3.71875
4
# coding: utf-8 import numpy as np ## En este caso estamos suponiendo que el vector de pesos es 1d ## Y el bias es un número class Neuron: def __init__(self, pesos, bias, function): self.w = pesos self.b = bias self.function = function def forward(self, entradas): logit = np.dot(entradas, self.w) + self.b salida = self.function(logit) return output
7c68005390ceb5ff1f44b4527b3d2fbc91b8363c
max180643/Pre-Programming-61
/Onsite/Week-3/Tuesday/Past Tense 2.0.py
263
4.03125
4
"""Past Tense""" def main(): """Main Function""" text = input() text = text.replace(" is", " was") text = text.replace(" are", " were") text = text.replace("Is", "Was") text = text.replace("Are", "Were") print(text) main()
8e6e4dd3f14ca3dd36a2c3b9da1cb52e4819e817
explodes/euler-python
/euler/problems/euler17.py
3,036
3.5625
4
#!/usr/bin/env python from euler.problems.registry import register LIMIT = 1000 DIGITS = { 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", } PREFIXED = ( (90, "ninety"), (80, "eighty"), (70, "seventy"), (60, "sixty"), (50, "fifty"), (40, "forty"), (30, "thirty"), (20, "twenty"), ) POSTFIXED = ( (1000, "thousand"), (100, "hundred"), ) def as_words(n): # this very much reminds me of the roman numeral kata.. if n == 0: return "" parts = [] for val, name in POSTFIXED: if n >= val: d = n / val parts.append(as_words(d)) parts.append(name) n -= (d * val) for val, name in PREFIXED: if n >= val: d = n - val s = name if d > 0: s += "-" + as_words(d) if parts: parts.append("and") parts.append(s) break else: if n in DIGITS: if parts: parts.append("and") parts.append(DIGITS[n]) return " ".join(parts) def count_letters(n): words = as_words(n) return len(words.replace("-", "").replace(" ", "")) def count_letters_of_range(n): return sum(count_letters(i) for i in xrange(1, n + 1)) @register class Euler: """ If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. """ NUMBER = 17 NAME = "Number letter counts" ANSWER = 21124 def run(self): return count_letters_of_range(LIMIT) def test(self): def check(val, name): words = as_words(val) print val, "->", words assert words == name check(1, "one") check(9, "nine") check(10, "ten") check(11, "eleven") check(20, "twenty") check(25, "twenty-five") check(99, "ninety-nine") check(100, "one hundred") check(101, "one hundred and one") check(115, "one hundred and fifteen") check(563, "five hundred and sixty-three") check(1000, "one thousand") check(2798, "two thousand seven hundred and ninety-eight") assert count_letters_of_range(5) == 19 if __name__ == '__main__': euler = Euler() euler.test() print euler.run()
a9f23a2a2b5f41e219612dc1ff6ca306b04ac79c
idellang/Python_Learning_Corey
/loopsAndIterations.py
646
4.09375
4
nums = [1, 2, 3, 4, 5] for num in nums: print(num) # break : break out of the loop for num in nums: print(num) if num == 3: print("We found the number three") break # continue: move onto the next iteration for num in nums: print(num) if num == 3: print("Found the number three") continue # loop within a loop for num in nums: for letter in "abc": print(num, letter) # loop within a certain number of time for i in range(1, 11): print(i) # while loops : will keep going until certain condition is met x = 0 while x < 10: if x == 5: break print(x) x += 1
252a3611ac591f418038ba03ceaac6cdf20c11eb
chenxu0602/LeetCode
/2210.count-hills-and-valleys-in-an-array.py
960
3.53125
4
# # @lc app=leetcode id=2210 lang=python3 # # [2210] Count Hills and Valleys in an Array # # @lc code=start class Solution: def countHillValley(self, nums: List[int]) -> int: # hillValley = 0 # for i in range(1, len(nums) - 1): # if nums[i] == nums[i + 1]: # nums[i] = nums[i - 1] # if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]: # hillValley += 1 # if nums[i] < nums[i - 1] and nums[i] < nums[i + 1]: # hillValley += 1 # return hillValley res = 0 candidate = last = None for i in range(1, len(nums)): if nums[i] != nums[i - 1]: if candidate and ((candidate > last and candidate > nums[i]) or (candidate < last and candidate < nums[i])): res += 1 candidate = nums[i] last = nums[i - 1] return res # @lc code=end
deef4e71c15cb7df3661a017d7d334a7260643e6
jennyChing/leetCode
/75_sortColors.py
908
4.15625
4
''' 75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. ''' class Solution(object): def sortColors(self, nums): # need 3 pointers for 3 colors!! One starting from the end of the list a, b, c = 0, 0, len(nums) - 1 while b <= c: print(nums, a, b, c) if nums[a] == 0: nums[b], nums[a] = nums[a], nums[b] a += 1 b += 1 elif nums[b] == 1: b += 1 else: nums[b], nums[c] = nums[c], nums[b] c -= 1 return(nums) if __name__ == "__main__": res = Solution().sortColors([0,1,2,0,1,1,2]) print(res)
eb7a14f4d26fadfda756c5a2a0474dd1f778fec4
CrMatt9/InitCodeProblems
/IntCodeNave202.py
9,212
3.75
4
class IntCode (): #This program translates a standard spaceship IntCode def __init__ (self, input, emergencyCode = 0000, desiredValue = None): self.sumCte = 1 self.multCte = 2 self.endCte = 99 self.emergencyCode = emergencyCode self.desiredValue = desiredValue self.value = 0 self.noun = self.emergencyCode//100 self.verb = self.emergencyCode-self.noun*100 self.errors = 0 dataFrame = open(input, "r") self.rawData = dataFrame.read().split(',') dataFrame.close() self.groupedData = [] #Data grouped in intructions in this case 4 ints so it is a list of ?x4 self.groupedDataCopy = [] self.errorMessage = "" #Store all the errors while running the intcode def Parse(self): self.rawData = [int(x) for x in self.rawData] #convert everything into int #splint the int f.e 2562 into 25 , 62 and assing it to posc 1 and 2 respectively #We consider that 0000 means that there is no emergencyCode if(self.emergencyCode != 0000): self.rawData[1] = self.noun self.rawData[2] = self.verb #separe data into groups of 4 to ease the search, it should be the standard format groupPosc = 0; while groupPosc <= len(self.rawData): diff = len(self.rawData) - groupPosc if diff <= 4 : self.groupedData.append(self.rawData[len(self.rawData)-diff-1 : len(self.rawData)-1]) break else: self.groupedData.append(self.rawData[groupPosc:groupPosc+4]) groupPosc += 4 self.groupedDataCopy = self.groupedData def RunIntCode(self): self.errorMessage = '' groups = len(self.groupedData) # print(self.groupedData) for instr in range(groups): instruction = self.groupedData[instr] opCode = instruction[0] firstOper = instruction[1] secondOper = instruction[2] storeRes = instruction[3] # print("Ejecutando instr {instructions} de {groups} \n".format(instructions=instr, groups=groups)) # print("Ejecutando OPCode %i" % opCode) if opCode == self.sumCte: #We make a sum ; elem 1* + elem 2* and we store it in elem3* sum1 = self.groupedData[firstOper//4][firstOper%4] sum2 = self.groupedData[secondOper//4][secondOper%4] #we store it self.groupedData[storeRes//4][storeRes%4] = sum1 + sum2 elif opCode == self.multCte: #We make a multiplication ; elem 1* · elem 2* and we store it in elem3* mult1 = self.groupedData[firstOper//4][firstOper%4] mult2 = self.groupedData[secondOper//4][secondOper%4] #we store it self.groupedData[storeRes//4][storeRes%4] = mult1 * mult2 elif opCode == self.endCte: #End self.value = self.groupedData[0][0] break else: error = "There was an Error on instruction {instruction} with noun {noun} and verb {verb} \n ".format(instruction=instr, noun=self.noun, verb=self.verb) print(error) self.errors += 1 #We keep the errors messages to write out on the output.txt self.errorMessage += error """Find noun and verb to get a desired value. This solution is trying to use a solver that make steps depending on the difference of the value gotten and the disired one. At the end of the day it cant get the solution. """ def FindVar(self): self.RunNoSave() lastStep = None lastDifference = None while(self.desiredValue != self.value): #Create the Solver solver = Solver(self.desiredValue, self.value, self.noun, self.verb, maxLen=len(self.rawData), lastStep=lastStep, lastDifference=lastDifference, errors = self.errors) #Runs it self.noun, self.verb, lastStep, lastDifference = solver.Run() #We are forced to use the try except due to the error out of range in certain verbs and noun combinations try: self.RunNoSave() print("On the int code we found %i Value" % self.value) except: pass return self.noun, self.verb """ Second way to solve this problem is the "dirtiest one, I am just trying all the possible combinations inside the possible values (0 to the len(rawData)) """ def FindVar2(self): results = [] for noun in range(len(self.rawData)-1): self.noun = noun for verb in range(len(self.rawData)-1): self.verb = verb try: self.RunNoSave() print(self.value) if self.value == self.desiredValue: #in case the value is gotten we add it to a list of lists results.append[self.noun,self.verb,self.errors] except: pass #In this for loop we choose the best solution (the one with less errors) for i in range(len(results)): if i == 0: result = results[0] elif result[2]>results[i][2]: result = results[i] return result def StoreResults(self): outputFrame = open("output.txt", "w") #we generate a flat list to write it easily respecing the input format outputList = [item for instr in self.groupedData for item in instr] outputFrame.writelines(', '.join([str(elem) for elem in outputList])) outputFrame.writelines('\n' + self.errorMessage) outputFrame.close() def Run(self): self.Parse() self.RunIntCode() self.StoreResults() def RunNoSave(self): self.Parse() self.RunIntCode() class Solver(): def __init__(self, desiredValue, actualValue, noun, verb, maxLen, lastStep=None, lastDifference=None, errors=0): self.desiredValue = desiredValue self.actualValue = actualValue self.noun = noun self.verb = verb self.maxLen = maxLen self.errors = errors self.step = 1 self.lastStep = lastStep self.lastDifference = lastDifference self.distance = self.desiredValue - self.actualValue self.suma = [1, self.maxLen//100, self.maxLen//50, self.maxLen//20, self.maxLen//10, self.maxLen//7, self.maxLen//5, self.maxLen//4, self.maxLen//3, self.maxLen//2] #Set values on first iteration def FirstIteration(self): if self.distance>10000000: self.step = 9 elif self.distance>1000000: self.step = 8 elif self.distance>500000: self.step = 7 elif self.distance>100000: self.step = 6 elif self.distance>50000: self.step = 5 elif self.distance>10000: self.step = 4 elif self.distance>1000: self.step = 3 elif self.distance>100: self.step = 2 elif self.distance>10: self.step = 1 else: self.step = 0 self.lastStep = self.step self.lastDifference = self.distance #Manage the differences (positive or negative), manages the step and calls the executer to apply it def GetNewValues(self): if abs(self.distance) > abs(self.lastDifference): if step > 0 : self.step -= 1 else : self.step += 7 if self.distance > 0 : self.ApplyStep() elif self.disance < 0: self.ApplyStep(positive=False) def ApplyStep(self, positive=True): if positive == True: self.noun = self.noun + self.suma[self.step] self.verb = self.verb + self.suma[self.step] else: self.noun = self.noun - self.suma[self.step] self.verb = self.verb - self.suma[self.step] if self.noun > self.maxLen: self.noun = self.maxLen//2 if self.verb > self.maxLen: self.verb = self.maxLen//2 def Run(self): if self.lastDifference==None or self.lastStep==None: self.FirstIteration() if self.distance != 0 and self.errors != 0: self.GetNewValues() if self.distance == 0 and self.errors != 0: self.step += 1 print("The error was {error} and last error was {last}".format(error=self.distance, last=self.lastDifference)) return self.noun, self.verb, self.step, self.distance testIntCode1 = IntCode("Input.txt", emergencyCode = 1202) testIntCode1.Run() testIntCode2 = IntCode("Input.txt", desiredValue = 19690720) try: result = testIntCode2.FindVar2() print(result) except: print("No solution found") #we could use a timer here to just dont let it search for infinite time. noun, verb = testIntCode2.FindVar() print(noun, verb)
dab98b56d9a3edcbcc73df19c7adf6a2a57c0866
suruomo/PyQT5
/db/sqlite_demo.py
425
3.765625
4
# -*- coding: utf-8 -*- __author__ = 'suruomo' __date__ = '2020/10/9 13:03' import sqlite3 # 连接数据库,创建表和加入数据 conn = sqlite3.connect("student.db") cursor = conn.cursor() sql="create table student(name Text,phone Text,address Text)" cursor.execute(sql) sql="insert into student values('zhangsan','1231231242','beijing'),"\ "('lisi','1231242412','shanghai')" cursor.execute(sql) conn.commit()
a0d871ac76ceb05b1fa5a2fc23b2d46863ed09e6
avinandan029/Python_Files
/main.py
979
3.65625
4
import sqlite3 class DataBaseOperations: def connect(self): self.db = sqlite3.connect('SBIDB') return self.db def disconnect(self): self.db.close() def createTbl(self): sql_smt=''' create table Accounts (AccountNo int PRIMARY KEY,NAME text not null, Type text not null, Balance real not null) ''' res=self.db.execute(sql_smt) self.db.commit() return res def insertTbl(self,id_val): sql_smt='''insert into Accounts values(%s, 'Avinandan','Saving',20000.00)'''%(id_val) res = self.db.execute(sql_smt) self.db.commit() return res def readTbl(self): sql_smt=''' select * from Accounts ''' res = self.db.execute(sql_smt) self.db.commit() return res db_obj1= DataBaseOperations() db_obj1.connect() #db_obj1.createTbl() db_obj1.insertTbl("112") output=db_obj1.readTbl() for i in output: print(i) db_obj1.disconnect()
f048e52613c92e994259d7aa09586ffa41ffe5ac
zeastion/hardway
/test29.py
656
3.625
4
class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): return "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg) def drive_car(self): self.condition = "used" class ElectricCar(Car): def __init__(self, model, color, mpg, battery_type): super(ElectricCar, self).__init__(model, color, mpg) self.battery_type = battery_type def drive_car(self): self.condition = condition = "like new" return condition my_car = ElectricCar("DeLorean", "Black", 90, "molten salt") print my_car.condition print my_car.drive_car()
ecc5eefcb4d5f979e19bdd1065f2210b8241a255
UCD-pbio-rclub/Pithon_MinYao.J
/hw6/hw6-3_web_fasta_count.py
594
3.703125
4
# Problem 3 # Modify one of your functions from problem 1 or 2 to work with a file stored on the internet import string import urllib.request def webFastaCount(): filename = input('Enter URL: ') try: with urllib.request.urlopen(filename) as f: count = 0 line = f.readline().decode() while line != '': if line.startswith('>'): count += 1 line = f.readline().decode() print('There are', count, 'fasta records in this file') except: print('URL could not be reached')
2bd2738e4c0020d6605362042af9b0ef31deb6ea
abhijeet9706772771/test---S107-R
/1st.py
224
4.09375
4
maximum = int(input("Please Enter any Maximum Value : ")) if (maximum==1): print("1") else: for number in range(0, (maximum*2)+2): if(number % 2 != 0 and number % 5 != 0): print(number, end=',')
95df7f045bf2c4a54302482574405a8628c95f88
ShekhRaselMasrurAhmmadNissan/URI-Online-Judge
/Beginner/__pycache__/.wolf11752ubkuFtsaJPJV.py
285
3.796875
4
# Reading the Data... numbers = list() for serial_number in range(0, 5): numbers.append(float(input())) # Checking the conditions... even_number_count = 0 for number in numbers: if (number % 2 == 0): even_number_count += 1 print(f'{even_number_count} valores pares')
65e751035c6c8ca60092c4e81be8f2e78fe878bf
bellyfat/Python_Cryptographic_Signatures
/Python_Base64_Encryption_Base64.py
1,218
3.734375
4
# Python Base64 Encryption # base64 Base16, Base32, Base64, Base85 Data Encodings # This module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. # It provides encoding and decoding functions for the encodings specified in RFC 3548, which defines the Base16, Base32, and Base64 algorithms, and for the # de-facto standard Ascii85 and Base85 encodings. # The RFC 3548 encodings are suitable for encoding binary data so that it can safely sent by email, used as parts of URLs, or included as part of an HTTP # POST request. # The encoding algorithm is not the same as the uuencode program. # # base64.encodebytes(s) # Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') # inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME). # # # An example usage of the module: # import base64 encoded = base64.b64encode(b'data to be encoded') encoded # OUTPUT: 'b'ZGF0YSB0byBiZSBlbmNvZGVk'' data = base64.b64decode(encoded) data # OUTPUT: 'b'data to be encoded''
485d1f96e43b4309cd5ddd4ef7506aef33407f0e
xutkarshjain/HackerRank-Solution
/Problem Solving/DataStructure/Arrays/Left Rotation.py
157
3.53125
4
d=input().split() t=int(d[-1]) lists=input().split() for i in range(t): temp=lists[0] lists.pop(0) lists.append(temp) s=" ".join(lists) print(s)
5cde09b41db3f91641f83cd09649434c44efcb6d
shonihei/road-to-mastery
/data-structures/MinHeap.py
1,304
3.828125
4
class MinHeap: def __init__(self): # this heap is implemented using one-indexing # for faster child and parent index calculation self.heap = [0] self.count = 0 def __repr__(self): return str(a.heap[1:]) def insert(self, v): self.heap.append(v) self.count += 1 self.heapify_up(self.count) def heapify_up(self, i): while i // 2 > 0: if self.heap[i] < self.heap[i // 2]: self.heap[i], self.heap[i // 2] = self.heap[i // 2], self.heap[i] i //= 2 def heapify_down(self, i): while i * 2 <= self.count: m = i * 2 # default min child to left child if m + 1 < self.count and self.heap[m+1] < self.heap[m]: m += 1 if self.heap[i] < self.heap[m]: break self.heap[i], self.heap[m] = self.heap[m], self.heap[i] i = m def del_min(self): if self.count == 0: raise IndexError("cannot delete from empty heap") self.heap[1], self.heap[-1] = self.heap[-1], self.heap[1] del self.heap[-1] self.count -= 1 self.heapify_down(1) def get_min(self): r = self.heap[1] self.del_min() return r
84309dfe18acf11f94301577ac9dc2d40f8462f4
Naateri/Compiladores
/Labs/3/lab_1.py
406
3.765625
4
#Alumno: Renato Luis Postigo Avalos #Primer ejercicio regex import re ip_num = '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])' #Primer caso: 0-9 #Segundo caso: 10-99 #Tercer caso: 100-199 #Cuarto caso: 200-249 #Quinto caso: 250-255 ip_regex = '(' + ip_num + '\.){3}' + ip_num + "$" print(ip_regex) p = re.compile(ip_regex) ip = "192.16.255.5" if p.match(ip): print("Es una IP") else: print("No es una IP")
779aea4f0937e27ad3e88711f664eef469ce14c4
sudhirshahu51/my_leetcode_solutions
/array/Happy_Number.py
273
3.5
4
#Happy_Number class Solution: def isHappy(self, n: int) -> bool: results = [] while True: n = sum([int(i)**2 for i in str(n)]) if n == 1: return True elif n in results: return False else: results.append(n)
9c03ac98cb23efd9f925707a4fd44b57434a6bd3
Rodin2333/Algorithm
/剑指offer/08跳台阶.py
616
3.734375
4
#!/usr/bin/env python # encoding: utf-8 """ 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 """ class Solution: def jumpFloor(self, number): """ :param number: 台阶数 :return: 跳法 """ if number == 0: return 0 if number == 1: return 1 if number == 2: return 2 prepre, pre = 1, 2 for k in range(3, number + 1): prepre, pre = pre, prepre + pre return pre
e08b4d7f12cd878feb8d630162d203265c042bf3
khinthandarkyaw98/Python_Practice
/rayleigh_distribution.py
736
4.1875
4
# rayleigh_distribution # used in signal processing # It has two parameters. # scale - standard deviation, decides how flat the distribution will be default 1.0 # size - the shape of the returned array # draw out a sample for rayleigh distribution with scale of 2 with size 2x3 from numpy import random x = random.rayleigh(scale = 2, size = (2, 3)) print(x) # visualization of rayleigh distribution # from numpy import random import matplotlib.pyplot as plt import seaborn as sns sns.distplot(random.rayleigh(size = 1000), hist = False) plt.show() # similarity between rayleigh and chi square distribution # at unit stddev the???? and 2 df rayleigh and chi square represent the same distribution.
01ffe8617a4f52887882f85f8fc661e79b0d56d7
unswit/COMP9021_2
/Final_exam/2019T3_Sample_exam/exercise_5.py
937
3.953125
4
# You might find the ord() function useful. def longest_leftmost_sequence_of_consecutive_letters(word): ''' You can assume that "word" is a string of nothing but lowercase letters. >>> longest_leftmost_sequence_of_consecutive_letters('') '' >>> longest_leftmost_sequence_of_consecutive_letters('a') 'a' >>> longest_leftmost_sequence_of_consecutive_letters('zuba') 'z' >>> longest_leftmost_sequence_of_consecutive_letters('ab') 'ab' >>> longest_leftmost_sequence_of_consecutive_letters('bcab') 'bc' >>> longest_leftmost_sequence_of_consecutive_letters('aabbccddee') 'ab' >>> longest_leftmost_sequence_of_consecutive_letters('aefbxyzcrsdt') 'xyz' >>> longest_leftmost_sequence_of_consecutive_letters('efghuvwijlrstuvabcde') 'rstuv' ''' # REPLACE THE PREVIOUS LINE WITH YOUR CODE if __name__ == '__main__': import doctest doctest.testmod()
a1fb12f592717961642de5b11d1b380aed842fe4
SudPY/Profit-or-Loss
/Profit or Loss.py
631
3.875
4
def Profit(costPrice, sellingPrice) : profit = (sellingPrice - costPrice) return profit def Loss(costPrice, sellingPrice) : loss = (costPrice - sellingPrice) return loss if __name__ == "__main__": costPrice = int(input("Please enter the cost price : ")) sellingPrice = int(input("Please enter the selling price : ")) if sellingPrice == costPrice: print("Neither profit nor loss.") elif sellingPrice > costPrice: print("Rs.", Profit(costPrice, sellingPrice), "profit.") else: print("Rs.", Loss(costPrice, sellingPrice), "loss.")
5d6d03e31ef96f61d1c4c531b50ac0265409adba
soundaraj/practicepython.org
/element search.py
294
3.921875
4
import random def search(num,element): # print num for i in num: if i == element: print True break else: print False num = list(input("enter the list")) element = input("enter the search element") search(num,element)
3667abcaa566e8bf231267326b3de6db83c1d68f
aobrien89/cti110
/M6HW1_O'Brien (1).py
1,435
4
4
# Takes input of test scores and displays letter grades. # 11/12/2017 # CTI-110 M6HW1 - Test Average and Grade # Anthony O'Brien # def main(): score1, score2, score3, score4, score5 = ask_Scores() print() print_results(score1, score2, score3, score4, score5) def ask_Scores(): score1 = float(input("Enter first score: ")) score2 = float(input("Enter second score: ")) score3 = float(input("Enter third score: ")) score4 = float(input("Enter fourth score: ")) score5 = float(input("Enter fifth score: ")) return score1, score2, score3, score4, score5 def print_results(score1, score2, score3, score4, score5): print("Score\tLetter Grade") print(str(score1) + "\t\t" + determine_grade(score1), \ str(score2) + "\t\t" + determine_grade(score2), \ str(score3) + "\t\t" + determine_grade(score3), \ str(score4) + "\t\t" + determine_grade(score4), \ str(score5) + "\t\t" + determine_grade(score5), sep = "\n") def calc_average(score1, score2, score3, score4, score5): average = score1 + score2 + score3 + score4 + score5 / 5 return average def determine_grade(userscore): if userscore < 60: return "F" elif userscore < 70: return "D" elif userscore < 80: return "C" elif userscore < 90: return "B" elif userscore < 101: return "A" main()
a58ce21cf30410095b9240c18eaa976c74e04c86
dvanderk/wellesley_trivia
/wellesleytriviagamefinal.py
19,035
3.9375
4
# Dee van der Knaap and Molly Hoch # CS 111 Final Project # Wellesley Trivia Adventure import Tkinter as tk import os import random import animation WIDTH, HEIGHT = 1200,800 SPEED = 4 # makes it possible for the character to stop at all TOLERANCE = 5000 # list of places places = ["ScienceCenter", "StoneDavis", "HoughtonChapel", "AcademicQuad", "ClappLib", "Davis Museum", "LuluWang", "LastPosition"] # list of coordinates # these are for laptops coords = [(395, 150), (395, 285), (290, 175), (230, 125), (245, 265), (115, 170), (215, 85), (0,0)] # these are for desktops coords2 = [(790, 300), (790, 570), (580, 350), (460, 250), (495, 530), (230, 340), (430, 170), (0,0)] class OpeningScreen(tk.Frame): def __init__(self, root): tk.Frame.__init__(self) self.awaitingToClick = True self.root=root root.title('The Wellesley Trivia Adventure') self.grid() self.createWidgets() def createWidgets(self): # set the opening photo on the screen titleLabel = tk.Label(self, text = 'Welcome to the Wellesley Trivia Adventure!', fg = 'red', font = 'Helvetica 16 bold italic') titleLabel.grid(row = 0, columnspan = 2) pic = tk.PhotoImage(file = "WellesleyOpeningPic.gif") imageLabel = tk.Label(self, image=pic, borderwidth = 0) imageLabel.pic = pic imageLabel.grid(row = 1, columnspan = 2) titleLabel = tk.Label(self, text='Wellesley Trivia!', bg='white', font='Helvetica 24') # create a button to move into the game from the opening screen # sets the game up for a laptop user # with proportions roughly half that of the desktop user self.enterButton = tk.Button(self, text = 'Enter the Game Laptop Version', command=self.onEnterButtonClick) self.enterButton.grid(row = 1, column = 1, sticky = tk.S + tk.W) # creates a button to move into the game from the opening screen # sets the game up for a desktop user self.enterButton2 = tk.Button(self, text = 'Enter the Game Desktop Version', command = self.onEnter2ButtonClick) self.enterButton2.grid(row=1,column=2, sticky=tk.S+tk.W) self.quitButton = tk.Button(self, text = 'Quit', command = self.onQuitButtonClick) self.quitButton.grid(row=1, column =3, sticky=tk.S+ tk.E) # creates a frame with the pick your character screen, set up for a laptop def onEnterButtonClick(self): newThing = PickYourCharacter(self.root,'laptop') newThing.pack() self.destroy() # creates a frame with the pick your character screen, set up for a desktop def onEnter2ButtonClick(self): newThing = PickYourCharacter(self.root,'desktop') newThing.pack() self.destroy() def onQuitButtonClick(self): root.destroy() class PickYourCharacter(tk.Frame): '''Creates a GUI where a player can select a character''' def __init__(self, root,compType): tk.Frame.__init__(self) self.root=root self.compType =compType root.title('You\'re ready to pick your character!') self.grid() # a list of pictures corresponding to each potential character self.pictures = ['','rhys.gif','wanda.gif','wendy.gif'] # a list of pictures corresponding to each potential character, made smaller for laptops self.smallPictures=['','rhys_small.gif','wanda_small.gif','wendy_small.gif'] # a list of captions corresponding to each potential character self.captions = ['welcome','Rhys!','Wanda!','Wendy!'] # variable that will be used to get the player's choice self.picChoice = tk.IntVar() self.createWidgets() def createWidgets(self): # Image and Title pic = tk.PhotoImage(file='') # left blacnk until character is selected self.iLabel = tk.Label(self,image=pic,borderwidth=3) self.iLabel.pic = pic self.iLabel.grid(row=1,column=1,columnspan=3,rowspan=3,sticky=tk.N+tk.E+tk.S+tk.W) titleLabel = tk.Label(self, text='Pick your character:', fg='red',bg='white', font='Helvetica 26 bold italic') titleLabel.grid(row=0,column=2,sticky=tk.N+tk.E+tk.S+tk.W) leftLabel = tk.Label(self, text=' ', bg='white')# adding some space on left side leftLabel.grid(row=0,column=0,sticky=tk.N+tk.E+tk.S+tk.W) # Status Label # left blank until character is picked, then appears below the photo self.results = tk.StringVar() self.resultsLabel = tk.Label(self, fg='blue', font='Verdana 14 italic', textvariable=self.results) self.resultsLabel.grid(row=4,column=2) self.results.set('') # Choose Again # left blank until character is picked self.chooseAgain = tk.StringVar() self.chooseAgainLabel = tk.Label(self, fg='blue', font='Helvetica 14', textvariable=self.chooseAgain) self.chooseAgainLabel.grid(row=5,column=2) self.chooseAgain.set('') # Radio buttons # player uses these to select a character rhys = tk.Radiobutton(self, text='Rhys',value=1, variable=self.picChoice) rhys.grid(row=6,column=1) wanda = tk.Radiobutton(self,text='Wanda',value=2, variable=self.picChoice) wanda.grid(row=6,column=2) wendy = tk.Radiobutton(self, text='Wendy',value=3, variable=self.picChoice) wendy.grid(row=6,column=3) # Change picture button changeButton = tk.Button(self, text = 'Pick Character',command=self.onChangeButtonClick) changeButton.grid(row=7,column=2) # Quit Button quitButton = tk.Button(self, text='Quit', command=self.onQuitButtonClick) quitButton.grid(row=7,column=5) # Add any more functions that you need here def onQuitButtonClick(self): root.destroy() def onChangeButtonClick(self): self.choice = self.picChoice.get() if self.compType == 'desktop': self.character = self.pictures[self.choice] else: self.character = self.smallPictures[self.choice] newpic=tk.PhotoImage(file=self.character) # Create Move On Button moveOnButton = tk.Button(self, text='Start Game', command=self.onMoveButtonClick) moveOnButton.grid(row=7, column=3) self.iLabel.configure(image=newpic) self.iLabel.image = newpic self.results.set('You chose ' + self.captions[self.choice]) self.chooseAgain.set('Pick another character or press "Start Game".') def onMoveButtonClick(self): if self.compType == 'laptop': newThing2 = WellesleyGameApp(self.root,self.character,'laptop') else: newThing2 = WellesleyGameApp(self.root,self.character,'desktop') newThing2.pack() self.destroy() class QuestionsAndChoices: def __init__(self, filename): self.questionsAndChoices = [] in_file = open(filename, 'r') lines = in_file.readlines() for line in lines: newLine = line.strip('\n').split('\t') answerList=[] for i in range(2,5): answerList.append(newLine[i]) # remove trailing newline self.questionsAndChoices.append((newLine[0],newLine[1],answerList)) in_file.close() def getTitle(self,questionNumber): return self.questionsAndChoices[questionNumber-1][0] def getQuestion(self, questionNumber): return self.questionsAndChoices[questionNumber-1][1] def getChoices(self, questionNumber): return self.questionsAndChoices[questionNumber-1][2] class Icon(animation.AnimatedObject): # create the animated object over the map def __init__(self,canvas,character,currentIndex,isMoving,compType): self.CurrentIndex = currentIndex self.character = character self.compType = compType if self.compType=='laptop': self.coords=coords else: self.coords=coords2 self.NextPosition = self.coords[self.CurrentIndex+1] self.CurrentPosition = self.coords[self.CurrentIndex] self.x = self.CurrentPosition[0] self.y = self.CurrentPosition[1] self.canvas = canvas self.character = tk.PhotoImage(file = self.character) # image variable is newpic from pickYourCharacter file self.displayCharacter = self.character.subsample(2,2) self.id = self.canvas.create_image(self.CurrentPosition[0], self.CurrentPosition[1], image = self.displayCharacter) #self.moving = True self.moving = isMoving def move(self): #print str((self.x - self.NextPosition[0])*(self.x - self.NextPosition[0])+(self.y - self.NextPosition[1])*(self.y - self.NextPosition[1])) if (self.x - self.NextPosition[0])*(self.x - self.NextPosition[0])+(self.y - self.NextPosition[1])*(self.y - self.NextPosition[1]) < TOLERANCE: self.moving = False if self.moving: self.canvas.move(self.id, ((self.NextPosition[0] - self.CurrentPosition[0])/100), ((self.NextPosition[1] - self.CurrentPosition[1])/100)) self.x +=((self.NextPosition[0] - self.CurrentPosition[0])/100) self.y += ((self.NextPosition[1] - self.CurrentPosition[1])/100) if self.CurrentIndex >= len(self.coords): return "The Game is Over" else: self.CurrentIndex += 1 # update index of the list # class WellesleyGameApp(tk.Frame): def __init__(self, root,character, compType): tk.Frame.__init__(self, root) self.root = root self.character = character self.root.title("Are You A True Wendy Wellesley?") self.QA = QuestionsAndChoices('questions.txt') self.pack() self.compType = compType if self.compType == 'laptop': self.width=WIDTH/2 self.height=HEIGHT/2 self.photo = 'wesleyan.gif' else: self.width =WIDTH self.height=HEIGHT self.photo='wellesley_map.gif' self.totalNumberOfQuestions = 7 self.numberOfAnswers = 3 self.currentQuestionNumber = 1 self.numberAnsweredCorrectly = 0 #self.indexOfCurrentQuestion = self.currentQuestionNumber-1 self.awaitingUserToSubmitAnswer = True self.createWidgets() def createWidgets(self): self.canvas = animation.AnimationCanvas(self,width=self.width,height=self.height) self.im = tk.PhotoImage(file=self.photo) self.canvas.create_image(self.width/2,self.height/2,image=self.im) #this is the center self.canvas.pack() self.iconOne = Icon(self.canvas,self.character,self.currentQuestionNumber-1,False,self.compType) self.canvas.addItem(self.iconOne) self.canvas.start() # Question self.question = tk.StringVar() questionLabel = tk.Label(self, fg='blue', font='Times 14', textvariable=self.question) questionLabel.pack() self.setQuestion() # Set text of question # Answers self.answerIndex = tk.IntVar() # Index of selected radiobutton # List of StringVars, one for each radiobutton. # Each list element allows getting/setting the text of a radiobutton. self.answerTexts = [] for i in range(0,3): self.answerTexts.append(tk.StringVar()) self.rbs = [] for i in range(len(self.answerTexts)): # Create radiobuttons rb = tk.Radiobutton(self, fg='red', textvariable=self.answerTexts[i],\ variable=self.answerIndex,value=i) rb.pack() self.rbs.append(rb) self.setAnswers() # Set text of radiobuttons # Status Label self.results = tk.StringVar() self.resultsLabel = tk.Label(self, fg='brown', font='Times 14 italic', \ textvariable=self.results) self.resultsLabel.pack() # Submit Button self.submitButton = tk.Button(self, text='Submit', command=self.onSubmitButtonClick) self.submitButton.pack() # Quit Button quitButton = tk.Button(self, text='Quit', command=self.onQuitButtonClick) quitButton.pack() self.canvas.start() def setQuestion(self): self.question.set('Stop ' + str(self.currentQuestionNumber) + ' out of ' \ + str(self.totalNumberOfQuestions) +'--'+\ str(self.QA.getTitle(self.currentQuestionNumber))+ '.\n' + \ self.QA.getQuestion(self.currentQuestionNumber)) def setAnswers(self): '''Populates the answer radiobuttons in a random order with the correct answer as well as random answers.''' answers = [] # List of possible answers choices = self.QA.getChoices(self.currentQuestionNumber) answers.append(choices[0]) # Add correct answer to list answers.append(choices[1]) answers.append(choices[2]) random.shuffle(answers) # Randomly shuffle answer list for i in range(0, len(answers)): # Populate text of radiobuttons self.answerTexts[i].set(answers[i]) self.rbs[i].deselect() # deselect the radiobuttons def onSubmitButtonClick(self): '''dictates what is executed when player clicks the submit button''' # Invariant: self.awaitingUserToSubmitAnswer is True when button has # label 'Submit' and is False when button has label 'Next' if self.awaitingUserToSubmitAnswer: # the correct answer is always the first in the list correctAnswer = self.QA.getChoices(self.currentQuestionNumber)[0] # this gets which answer the player picked userAnswer = self.answerTexts[self.answerIndex.get()].get() # if the answer is correct, gives player positive feedback if correctAnswer == userAnswer: self.results.set("Correct!") self.numberAnsweredCorrectly += 1 # Increment correct score # if incorrect, provides player with the correct answer else: self.results.set("Incorrect: the correct answer is " + correctAnswer) # if there are more questions, changes 'Submit' to 'Next' if self.currentQuestionNumber<self.totalNumberOfQuestions: self.submitButton.config(text="Next") # Change "Submit" button to "Next" # if there are no more questions, changes 'Submit' to 'Finish Game' else: self.submitButton.config(text='Finish Game') self.awaitingUserToSubmitAnswer = False elif self.currentQuestionNumber < self.totalNumberOfQuestions: # User has pressed Next button when game not over # removes previous icon if possible try: self.canvas.removeItem(self.iconTwo) except AttributeError: pass # adds a moving icon so character can go from place to place self.iconTwo = Icon(self.canvas,self.character,self.currentQuestionNumber-1,True,self.compType) self.canvas.addItem(self.iconTwo) self.currentQuestionNumber += 1 # Increment question number self.setQuestion() # Populate text of question self.setAnswers() # Populate text of answer radiobuttons self.results.set('') # Clear status label self.submitButton.config(text="Submit") # Change "Next" button to "Submit" self.awaitingUserToSubmitAnswer = True else: # if the user did well, they will see a picture of ice cream! if self.numberAnsweredCorrectly>3: finalScreen = Screen(self.root,True,self.width,self.height) finalScreen.pack() self.destroy() # if the user did poorly, they go in the lake :( else: finalScreen = Screen(self.root, False,self.width,self.height) finalScreen.pack() self.destroy() def onQuitButtonClick(self): root.destroy() class Screen(tk.Frame): '''Creates the final game screen''' def __init__(self, root, win,width,height): tk.Frame.__init__(self, root) # sets whether or not user won self.win=win # gets the width and height depending on user's screen size self.width = width self.height= height self.root = root root.title('Game Over') self.pack() self.createWidgets() def createWidgets(self): # the user gets ice cream if she wins - Yay! if self.win: self.picName = 'dinoCrunch.gif' self.titleLabel = tk.Label(self, text = 'You did very well! You get '+\ 'a big scoop of ice cream in Lulu!', fg = 'red', font = 'Helvetica 16 bold italic') # the user has to go for a swim in the chemically-infested Lake Waban # if she loses--not yay else: self.picName = 'lakeWaban.gif' self.titleLabel = tk.Label(self, text = 'This did not go well for you.' +\ ' You must take a dip in Lake Waban.', fg = 'red', font = 'Helvetica 16 bold italic') self.canvas = tk.Canvas(self, width=self.width, height=self.height) self.im = tk.PhotoImage(file = self.picName) self.canvas.create_image(self.width/2,self.height/2, image = self.im) self.canvas.pack() self.titleLabel.pack() root = tk.Tk() app = OpeningScreen(root) # For Macs only: Bring root window to the front os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') app.mainloop()
54f2c280f9a4d582c78f38a58729b82d2aa5bfb5
Ebenezer997/https-github.com-2020-Spring-CSC-226-t13-keep-it-classy-ayisie-t13
/nim_class.py
3,358
4.0625
4
###################################################################### import random import turtle class Nim: # class variables def __int__(self, init_balls = 0, user_re = 0, comp_rem = 0, remainder = 0): self.init_ball = init_balls self.user_removed = user_re self.com_remove = comp_rem self.remainder = remainder self.wn = None self.write_text = None def begin_game(self): self.init_ball = int(input("How many balls would you like to begin with? Remember it should be 15 or higher.\n")) while self.init_ball < 15: # checks if number of balls is required self.init_ball = int(input("Number must be 15 or higher.\n")) print("let's begin the game. Remember you should start first.\n") self.remainder = self.init_ball self.wn = turtle.Screen() return self.init_ball def user_remove(self): """ It checks the number of balls user has taken. which supposed to be between 1 to 4. Deduct the user selction from the total balls :return: Balls remaining after user selection""" # print("How many balls would you like to take?", end='') self.user_removed = self.wn.numinput("WELCOME TO NIM GAME", "How many balls do you want to select?",0, minval=1, maxval=4) while self.user_removed < 1 or self.user_removed > 4: print("\nNumber must be between 1 and 4.\n") self.user_removed = self.wn.numint(input()) # User removed balls print("Window removed",self.wn.numinput()) self.remainder = self.remainder - self.user_removed print('You take', self.user_removed,'balls') # calculating remaining balls def comp_removed(self): """ Functions makes computer select random number of balls between 1 to 4. subtract from the remaining balls Checks is the remaining balls after computer selection is zero""" self.com_remove = self.remainder % 5 if self.com_remove == 0: self.com_remove = random.randint(1,4) self.remainder= self.remainder - self.com_remove print('Computer takes',self.com_remove, 'balls.') print(self.remainder, 'balls remaining. \n') if self.remainder == 0: # checks the winner when balls are zero print("Computer won") return self.remainder def end_game(self): # self.init_ball = begin_game() while self.remainder > 0: choice = self.remainder # user_balls_remove() if choice < 1: print("You win the Game.Congratulations!!!") break if self.remainder <1: print("The computer wins!!! Better luck next time.") break def main(): """ :return: """ g = Nim() g.begin_game() g.user_remove() g.comp_removed() while g.remainder >0: print("The remainder is", g.remainder) g.user_remove() if g.remainder > 0: g.comp_removed() if __name__ == "__main__": main()
204b84e2f619f4fb9b2b13f6455d4396ab8ab896
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/3573.py
2,523
3.5
4
# -*- coding: utf-8 -*- f = open("B-small-attempt24.in") #f = open("test.txt") testCaseNumber = int(f.readline()) final_text = "" def buy_n_time(C, F, X, time): # C mean how many cookies can buy a farm. # F mean after buy a farm, extra F cookies per second. # X mean cookies number goal. cookies_rate = 2 # how many cookies per second if time == 0: return X / cookies_rate total_buy_time = 0 for t in list(range(0, time)): buy_time = C / cookies_rate cookies_rate = cookies_rate + F total_buy_time = total_buy_time + buy_time wait_time = X / cookies_rate result = wait_time + total_buy_time return result for case_number in list(range(1, testCaseNumber+1)): one_case = f.readline() one_case_list = one_case.split() C = float(one_case_list[0]) F = float(one_case_list[1]) X = float(one_case_list[2]) # C mean how many cookies can buy a farm. # F mean after buy a farm, extra F cookies per second. # X mean cookies number goal. l = [] #print("C:" + str(C) + " F: " + str(F) + " X: " + str(X) ) #print(str(type(C))) #break ####################################### # # 3个数字我们现在拿到了, 现在开始计算~ # ####################################### # 买不同次数的 farm 后会如何? # 我只买1次farm, 然后干等到goal呢? 我只买2次farm, 然后干等到goal呢? 我只买3............. time_list = [] ''' for time in list(range(0,999)): t = buy_n_time(C, F, X, time) #t = buy_n_time(500.0, 4.0, 2000.0, time) if len(time_list) > 1 and float(t) > float(time_list[-1]): break time_list.append(t) ''' timeaaaa = 0 while True: t = buy_n_time(C, F, X, timeaaaa) if len(time_list) > 1 and float(t) > float(time_list[-1]): break else: time_list.append(t) timeaaaa = timeaaaa + 1 r = min(time_list) r = round(r, 7) r = "{:.7f}".format(r) # 输出最终结果 case = "Case #" + str(case_number) + ": " + str(r) final_text = final_text + case + "\n" print(final_text) # 输出到文件里 with open('new_B_out.txt', 'w') as file: file.write(final_text)
5fe1f774307d29f09449d3a9adeacd6b73350393
junghanss/UCEMA-PythonLab
/Exercises/random_walk.py
481
3.84375
4
import matplotlib.pyplot as plt from random import choice plt.rc('figure',figsize=(12,6)) #plt.xlim(0,1.0) #plt.ylim(0,50) plt.title('Random Walk') plt.xlabel('Number of steps') plt.ylabel('Distance from origin') step_option= [-1,1] step_choice= choice(step_option) step_choice walk=[] walk.append(step_choice) for step in range(1,1000): next_step=walk[step-1] + choice(step_option) walk.append(next_step) print(walk) plt.plot(walk) plt.show()
9336fe1d56dfe9247fe990e0c3f76c1ceb15b90e
sunabove/lec_1911_rasp
/led/blink_2.py
635
3.640625
4
# coding: utf-8 import time import RPi.GPIO as GPIO # Pin definitions led_pin = 17 # Suppress warnings GPIO.setwarnings(False) # Use "GPIO" pin numbering GPIO.setmode(GPIO.BCM) # Set LED pin as output GPIO.setup(led_pin, GPIO.OUT) print( "Press Ctrl + C to quit! ") # Blink forever while True: print("+", end = '', flush=True ) GPIO.output(led_pin, GPIO.HIGH) # Turn LED on time.sleep(1) # Delay for 1 second print("\b-", end = '', flush=True) GPIO.output(led_pin, GPIO.LOW) # Turn LED off time.sleep(1) # Delay for 1 second print("\b", end = '', flush=True) pass
a4a453ffc55e6d59b3334919699ea6be97ef927c
rojarfranklin/guvi
/loop/sum natural.py
138
3.828125
4
num=int(input()) sum=0 if (num<=0): print("invalid") else: while (num>0): sum+=num num-=1 print(sum)
bf06a29bc61372a0e1e5f34ca2a830b1e1daee87
mcmyers12/social-media-analytics
/projects/relational-algebra/extract-social-network.py
2,318
3.953125
4
'''Extract a structured data set from a social media of your choice. For example, you might have user_ID associated with forum_ID. Use relational algebra to extract a social network (or forum network) from your structured data. Create a visualization of your extracted network. What observations do you have in regards to the network structure of your data? Create a network using authors of comments from subreddits''' import praw from igraph import * def getCommentAuthors(r, authors, subreddits, authorCount): for subredditName in subreddits: subreddit = r.subreddit(subredditName) for post in subreddit.comments(limit=authorCount): if post.author and post.author.name: author = post.author.name if author in authors: if subreddit.display_name not in authors[author]['subreddits']: authors[author]['subreddits'].append(subreddit.display_name) else: authors[author] = {'subreddits': [subreddit.display_name]} def formatGraph(g, authors, subreddits): authorList = list(authors.keys()) labels = subreddits + ['' for x in range(len(authorList))] g.vs['label'] = labels colors = ['teal' for x in range(len(subreddits))] + ['purple' for x in range(len(authors.keys()))] g.vs['color'] = colors addEdges(g, authorList, authors, subreddits) def addEdges(g, authorList, authors, subreddits): for i in range(len(authorList)): author = authorList[i] authorSubreddits = authors[author]['subreddits'] vertexNumber = i + len(subreddits) subredditNumbers = [subreddits.index(s) for s in authorSubreddits] for subredditNumber in subredditNumbers: g.add_edge(vertexNumber, subredditNumber) def createGraph(authors, subreddits): g = Graph() g.add_vertices(len(authors) + len(subreddits)) formatGraph(g, authors, subreddits) plot(g) def main(): r = praw.Reddit(client_id='1RmB7ChqHgjuZw', client_secret='xl04Tf2edeM6k_0hmnQrWFdmvrs', user_agent='me') authors = {} authorCount = 50 subreddits = ['dance', 'ballet', 'dancemoms', 'dancingwiththestars', 'worldofdance', 'thebachelor'] getCommentAuthors(r, authors, subreddits, authorCount) createGraph(authors, subreddits) main()
9adb694fd0b3771b3de8bd04e95b93b3051e4692
apepkuss/Cracking-Leetcode-in-Python
/src/amazon/leetcode98_ValidateBinarySearchTree.py
2,438
4.1875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): """ @ Amazon, Microsoft, Bloomberg, Facebook Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false. """ # Method 1: make use of in-order traversal of a BST, as the result of in-order traversal should be a sequence in # increasing order def isValidBST_inorderTraversal(self, root): """ :type root: TreeNode :rtype: bool """ if root== None: return True vals = self.inorderTraversal(root) # case1: the result from inorder traversal is not a increasing sequence # case2: the result from inorder traversal contains duplicates # for the two cases above, return false if (len(vals) > 1 and (vals != sorted(vals))) or (len(vals) > len(list(set(vals)))): return False return True def inorderTraversal(self, root): vals = [] if root: stack = [] while stack != [] or root: if root: # traverse left subtree stack.append(root) root = root.left else: # traverse root and right subtree root = stack.pop() vals.append(root.val) root = root.right return vals # Method 2: recursive method def isValidBST_recursive(self, root): """ :type root: TreeNode :rtype: bool """ import sys return self.validBST(root, -sys.maxint - 1, sys.maxint) def validBST(self, root, lower, upper): if root is None: return True return lower < root.val < upper and self.validBST(root.left, lower, root.val) and self.validBST( root.right, root.val, upper)
c90067e3e977df20cfc2ee2a67481f409da50a2b
camiloaromero23/computacionParalela
/tercerCorte/clase2/first/gravity.py
922
3.859375
4
from math import sqrt class Planet(object): def __init__(self): # Some position and initial velocity self.x = 1.0 self.y = 0.0 self.z = 0.0 self.vx = 0.0 self.vy = 0.5 self.vz = 0.0 # Mass self.m = 1.0 def single_step(planet, dt): """Next step on time""" # Force calculation distance = sqrt(planet.x**2 + planet.y**2 + planet.z**2) Fx = -planet.x/distance**3 Fy = -planet.y/distance**3 Fz = -planet.z/distance**3 # Time step of position by velocity planet.x += dt*planet.vx planet.y += dt*planet.vy planet.z += dt*planet.vz # Time step of speed by force and mass planet.vx += dt*Fx/planet.m planet.vy += dt*Fy/planet.m planet.vz += dt*Fz/planet.m def step_time(planet, time_span, n_steps): dt = time_span / n_steps for _ in range(n_steps): single_step(planet, dt)
79567f8955ccc289882de1515392e6f204dccccf
hsyao/algorithm
/模拟训练/day03/队列.py
670
4.0625
4
""" """ class Queue(object): """队列""" def __init__(self): self.items = [] def is_empty(self): """判断是否为空""" return self.items == [] def enqueue(self, item): """进队列""" self.items.append(item) def dequeue(self): """出队列""" return self.items.pop(0) def size(self): """返回大小""" return len(self.items) if __name__ == '__main__': queue = Queue() queue.enqueue("hello") queue.enqueue("world") queue.enqueue("itcast") print(queue.size()) print(queue.dequeue()) print(queue.dequeue()) print(queue.dequeue())
b537cde7618ef007414e50b480810f45911e7d9d
suhasreddy123/python_learning
/Hacker rank/Python/lists.py
361
3.9375
4
"""insert i e: Insert integer at position . print: Print the list. remove e: Delete the first occurrence of integer . append e: Insert integer at the end of the list. sort: Sort the list. pop: Pop the last element from the list. reverse: Reverse the list.""" n = int(input()) ar = list(input().strip().split(' ')) print(ar) list1=[] list1.ar[0](ar[1],ar[2])
e229a3c8e1ae925ce04f51fa78a7bdd9771fcd91
EchoLLLiu/OtherCodes
/剑指offer/GetLeastNumbers.py
1,307
3.578125
4
# coding=utf-8 __author__ = 'LY' __time__ = '2018/6/17' # 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4. # 堆排序(小根堆) class Solution: def GetLeastNumbers_Solution(self, tinput, k): if tinput == [] or len(tinput) < k or k == 0: return [] '''堆排序,只排前k个最小''' self.Build_Min_Heap(tinput) i = len(tinput)-1 count = 1 while count <= k and i >= 0: tinput[0], tinput[i] = tinput[i], tinput[0] self.Min_Heapify(tinput, i, 0) count += 1 i -= 1 res = tinput[-k:] return res[::-1] def Min_Heapify(self, heap, heapSize, root): '''小根堆调整函数''' left = 2 * root + 1 right = left + 1 larger = root if left < heapSize and heap[larger] > heap[left]: larger = left if right < heapSize and heap[larger] > heap[right]: larger = right if larger != root: heap[larger], heap[root] = heap[root], heap[larger] self.Min_Heapify(heap, heapSize, larger) else: return def Build_Min_Heap(self, heap): '''构建初始小根堆''' heapSize = len(heap) for i in range((heapSize-2)//2, -1, -1): self.Min_Heapify(heap, heapSize, i) if __name__ == '__main__': heap = [4,5,1,6,2,7,3,8] s = Solution() print(s.GetLeastNumbers_Solution(heap, 0))
ef0f458eaad991021b86c1b89fa5900c12b7ba14
derek-nguyen123/AdventOfCode
/Challenge 6/ch6.py
907
3.859375
4
def countYes(groups): """ :type groups = [str] :rtype: (int, int) """ # Start counting for parts 1 and 2 of question part1, part2 = 0, 0 # Check every set of applications for group in groups: # Find all distinct letters in the set of applications letters = set(''.join(group.split('\n'))) part1 += len(letters) # For every letter, check if they exist in the rest of applications per group for letter in letters: # Check each person for person in group.split('\n'): # If one person is missing the letter, don't increase if (letter not in person) and (person != ''): break else: part2 += 1 return(part1, part2) file = open("input.txt", "r") groups = file.read() file.close() groups = groups.split("\n\n") print(countYes(groups))
2de4ba7b0f58d99aaf86f8be8351b8b371d75baa
crispimneto/wppp
/wpppp1.py
402
3.953125
4
#1º) Escreva um programa que pergunte a velocidade do carro de um usuário. #Caso utrapasse 80km/h, exiba uma mensagem dizendo que o usuário foi multado. #Nessa caso, exiba o valor da multa, cobrando R$5,00 por km acima de 80. vel = int(input('Digite a Velocidade do seu Veículo: ')) if vel > 80: print(f'Você foi Multado em R$ {((vel-80)*5):.2f}') else: print('Velocidade Correta')
8cf01970df9b4a9985834711a84d162e8cc034c5
Xinhe998/leetcode-python
/09_palindromeNumber.py
251
3.53125
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False return int(str(x)[::-1]) == x solution = Solution() print solution.isPalindrome(1234321)
0790775c7435aa44ee2c8e3e834aa1dc24df4f10
M3hrdadR/Implementation-of-LIF-NLIF-AELIF
/AELIF/AELIF.py
3,846
3.625
4
import matplotlib.pyplot as plt import numpy as np import random import math from MyPlot import my_plot e = math.e # A class for Adaptive-ELIF Model. class AELIF: # this function will initialize model. # no_fig will be used in my_plot function. def __init__(self, no_fig, dt, u_rest=-70, R=10, I=0, tau_m=8, thresh=-50, delta=2, a=0.5, b=0.5, tau_w=100, duration=20): self.fig = no_fig self.dt = 1 self.u_rest = u_rest self.R = R self.Current = I self.tau_m = tau_m self.thresh = thresh self.delta = delta self.a = a self.b = b self.tau_w = tau_w self.duration = duration self.u_spike = -40 self.w = [] self.spike = [] self.time = [] self.current_lst = [] self.u = [] for i in range(0, int(duration/dt), 1): self.time.append(i * dt) self.u.append(0) self.w.append(0) self.current() self.potential() return # this function will be used for making a list of currents # if self.Current is -1 , it means that the user wants random currents in all times. # otherwise the currents will be fixed. def current(self): if self.Current != -1: for i in range(len(self.time)): if i < len(self.time) // 10: self.current_lst.append(0) else: self.current_lst.append(self.Current) else: for i in range(len(self.time)): if i < len(self.time) // 10: self.current_lst.append(0) else: self.current_lst.append(random.randrange(-20, 100, 1) / 10) return # this function will calculate w which will be used in calculation of potential. # consider that values of w or any other continuous parameter will be stored in list # so it will become discrete. def calc_w(self, i): t_fire = -1 if len(self.spike) >= 1: t_fire = self.spike[-1] diff = self.a * (self.u[i - 1] - self.u_rest) - self.w[i - 1] + self.b * self.tau_w * int(1 - np.sign(self.time[i - 1] - t_fire)) tmp = diff / self.tau_w * self.dt self.w[i] = self.w[i-1] + tmp return # this function calculates potential and stores them in a list. # each time that neuron spikes, its time will be stored in a list named spike list. def potential(self): self.u[0] = self.u_rest self.w[0] = 0 for i in range(1, len(self.time)): self.calc_w(i) diff = -1 * (self.u[i - 1] - self.u_rest) + np.exp((self.u[i - 1] - self.thresh) / self.delta) * self.delta\ + self.R * self.current_lst[i] - self.R * self.w[i] tmp = diff / self.tau_m * self.dt + self.u[i - 1] if tmp >= self.thresh: self.u[i-1] = self.u_spike self.u[i] = self.u_rest self.spike.append(self.time[i]) else: self.u[i] = tmp return # this function just is used for plotting. # my_plot is a function that will use matplotlib and is written by me. def plot(self): my_plot(False, self.fig, self.time, self.u, 'U - T', 'Time', 'Potential', 2, self.time, self.current_lst, 'I - T', 'Time', 'Current') return a = AELIF(1, 0.1, R=10, I=5, tau_m=8, a=0.5, b=0.5, tau_w=100) b = AELIF(2, 0.1, R=5, I=10, tau_m=8, a=0.5, b=0.5, tau_w=100) c = AELIF(3, 0.1, R=10, I=10, tau_m=8, a=0.5, b=2, tau_w=100) d = AELIF(4, 0.1, R=10, I=5, tau_m=8, a=2, b=3, tau_w=100) e = AELIF(5, 0.1, R=10, I=5, tau_m=8, a=0.5, b=0.5, tau_w=400) f = AELIF(6, 0.1, I=-1) a.plot() b.plot() c.plot() d.plot() e.plot() f.plot() plt.show()