blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
675ab06bd6f1512e00daa95ab82697de8d3a6f08 | m-m-adams/ChallengeServer | /Solutions/ChallengeClient.py | 3,125 | 3.5625 | 4 | import socket
import time
import select
###########################################################
# Class declarations
###########################################################
###########################################################
# Challenge Interface
# This class is a wrapper for socket functions to make
# them more friendly to use in this context. Has specific
# functions select_level and submit_answer for this
# challenge, as well as implementing friendlier send and
# receives, reset, and exit for internal use in the class.
class challengeinterface(object):
#setup the socket to connect to the challenge
#This function has default arguments
def __init__(self,address,port):
sock=socket.socket()
self.address=address
self.port=port
self.sock=sock
def start(self):
self.sock.connect((self.address, self.port))
return self.receive()
#accept a level and a challenge socket as
#input, select the level and return its text
def select_level(self,level):
self.transmit(level)
ChallengeText=self.receive()
return ChallengeText
#If it's correct you get a flag
#if it's incorrect you get a new challenge
#in some challenges, on submitting a correct
#answer you immediately get a new challenge,
#which will be stored in result
def submit_answer(self,solution):
self.transmit(solution)
result=''
while result=='':
result=self.receive()
return result
#resets the socket and restarts the connection
#shouldn't be needed but implemented for robustness
def reset(self):
self.exit()
sock=socket.socket()
sock.connect((self.address,self.port))
self.sock=sock
#generic socket encode and send
def transmit(self,submission):
return self.sock.send(str(submission).encode())
# socket receive and decode
# checks that the socket has data on it, and if so reads
# repeats until the socket has no more data
# 0.15 second wait each loop accounts for latency on the
# server side - it's an AWS t2.nano instance......
# default to receiving until it receives 'END MESSAGE\n', as sent by the server's communications.py
def receive(self, terminator='END MESSAGE\n'):
do_read = False
receiveddata=''
while not receiveddata.endswith(terminator):
try:
# select.select will return true if there is data on the socket
# this prevents the recv function from blocking
r, _, _ = select.select([self.sock], [], [],0.15)
do_read = bool(r)
except socket.error:
pass
if do_read:
data = self.sock.recv(1024).decode()
receiveddata+=data
return receiveddata.replace('END MESSAGE\n','')
#generic socket close
def exit(self):
self.sock.close()
#end of challenge interface class
#############################################################
|
6739e2d0bbde7dd5b96001abf6c3e775c765acb2 | BMHArchives/ProjectEuler | /Problem_9/Problem_9.py | 605 | 3.6875 | 4 | import numpy as np
import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
def FindAnswer():
sum = 1000
numbers = []
range_a = round_up(sum/3, -2),
range_a = int(range_a[0])
range_b = int(sum/2)
for a in range(1,range_a):
for b in range(1, range_b):
c = sum - a-b
if((a*a) + (b*b) == (c*c)):
numbers.append(a)
numbers.append(b)
numbers.append(c)
return numbers
print("Answer is: {} ".format(np.prod(FindAnswer())))
|
c5db4886b9e216f7da109bcfdd190a2267d7258b | BMHArchives/ProjectEuler | /Problem_1/Problem_1.py | 1,128 | 4.21875 | 4 | # Multiples of 3 and 5
#---------------------
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
numberCount = 1000 # Use this number to find all multiples under the numberCount
total = 0 # summerize the total count of multiples under 1000
# loop between 1 and 1000
for count in range(1,numberCount):
if count != 0: # can't divide by 0
# if the % value is equal to 0 for 3 or 5, then add it to the total.
if (count % 3) == 0 or (count % 5) == 0:
total += count
#def FindAllMultiplesOfTragetNumber(TargetNumber):
# sumTotal = 0
# for a in range(1,numberCount):
# if(a % TargetNumber) == 0:
# sumTotal += a
# return sumTotal
# We're using 3, 5 and 15 here because 15 is the lowest common denominator between 3 and 5, so we will add 3 + 5 to 8 and then subtract from 15 to get the value.
#print(FindAllMultiplesOfTragetNumber(3) + FindAllMultiplesOfTragetNumber(5) - FindAllMultiplesOfTragetNumber(15))
print("Answer: {}".format(total))
|
84fa0e7c67f83e895ab25832db97d086807a4689 | luturol/learning-python | /snake-game/app.py | 5,442 | 3.546875 | 4 | import os
from msvcrt import getch
class SnakeGame(object):
screen = None
def __init__(self, rows_count, column_count):
self.screen = self.initialize_screen(rows_count, column_count)
self.collided = False
def initialize_screen(self, rows_count, column_count):
#creates the 2D list with 0 in all values
screen = [[0 for x in range(column_count)] for y in range(rows_count)]
#get the rows
for row in range(len(screen)):
if row == 0 or row == len(screen) - 1:
screen[row] = self.add_same_value_entire_list(screen[row], 1)
else:
for column in range(len(screen[row])):
if column == 0 or column == len(screen[row]) - 1:
screen[row][column] = 1
return screen
def add_same_value_entire_list(self, list, value):
populatedList = [value for i in range(len(list))]
return populatedList
def print_screen(self):
screen_text = ''
for row in self.screen:
for column in row:
screen_text = screen_text + self.translated_value(column)
screen_text = screen_text + '\n'
return screen_text
def translated_value(self, value):
if value == 1:
return '#'
elif value == 2:
return '*'
elif value == -1: #snake body
return 'O'
elif value == -2: #moving left snake head left <----
return '<'
elif value == -3: #moving right snake head right ---->
return '>'
elif value == -4: #moving down
return 'V'
elif value == -5: #moving up
return '^'
else:
return ' '
def play(self):
player = Player()
key_pressed = 9999
self.add_player_to_screen(player)
while(self.defeated() is not True and key_pressed != 27):
self.clear()
print(self.print_screen())
key_pressed = self.read_key()
player.move(self.translate_key(key_pressed))
self.add_player_to_screen(player)
def read_key(self):
return ord(getch())
def add_player_to_screen(self, player):
print(player.location_x)
print(player.location_y)
if(player.position_cordination == 'E'):
self.screen[player.location_x][player.location_y - 1] = 0
elif (player.position_cordination == 'W'):
self.screen[player.location_x][player.location_y + 1] = 0
elif (player.position_cordination == 'N'):
self.screen[player.location_x + 1][player.location_y] = 0
elif (player.position_cordination == 'S'):
self.screen[player.location_x - 1][player.location_y] = 0
if(self.screen[player.location_x][player.location_y] == 0):
self.screen[player.location_x][player.location_y] = player.body
elif(self.screen[player.location_x][player.location_y] < 0):
self.collided = True
def translate_key(self, key):
print (key)
if (key == 224):
key = ord(getch())
print(key)
if (key == 72):
return 'N'
elif (key == 80):
return 'S'
elif (key == 75):
return 'W'
elif (key == 77):
return 'E'
else:
pass
def defeated(self):
return self.collided
def clear(self):
os.system('cls' if os.name=='nt' else 'clear')
class Player(object):
def __init__(self):
self.nodes_size = 1
self.position_cordination = 'E'
self.last_cordination = 'E'
self.location_x = 4
self.location_y = 4
self.body = -3
def draw(self):
body = ''
for index in range(self.nodes_size):
if(index == 0 and self.position_cordination == 'E'):
body = '>'
elif(index == 0 and self.position_cordination == 'W'):
body = '<'
elif(index == 0 and self.position_cordination == 'N'):
body = '^'
elif(index == 0 and self.position_cordination == 'S'):
body = 'V'
else:
body += '-'
return body
def move(self, cordination):
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
if (self.position_cordination != 'S' and cordination == 'N'):
self.location_x -= 1
self.body = -5
elif (self.position_cordination != 'N' and cordination == 'S'):
self.location_x +=1
self.body = -4
elif (self.position_cordination != 'W' and cordination == 'E'):
self.location_y += 1
self.body = -3
elif (self.position_cordination != 'E' and cordination == 'W'):
self.location_y -= 1
self.body = -2
else:
pass
self.position_cordination = cordination
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
snake = SnakeGame(32, 32)
snake.play() |
c0d728b393c1b9184357b51442f0f3ee96e0db3d | edvalvitor/projetos | /python/media2.py | 1,215 | 4.15625 | 4 | #Programa para calcular a média e quanto falta para passar
#Centro Universitário Tiradentes
#Edval Vitor
#Versão 1.0.1
while True:
print("Programa para calcular média da UNIT")
print("Se você quer calcular a sua média digite 1")
print("Se quer calcular quanto precisa para passar digite 2")
opcao = int(input("Digite sua opção: "))
#Função para calcular a média final
def func1():
uni1 = float(input("Digite a nota da Primeira unidade: "))
uni2 = float(input("Digite a nota da Segunda unidade: "))
total = ((uni1 * 4) + (uni2 * 6))
if (total >= 60):
print("Você passou, sua nota é igual a: ", (total/10))
elif (total < 60):
print("Você não passou, sua nota é igual a: ", (total/10))
#Função para calcular quanto precisa para passar
def func2():
uni1 = float(input("Digite a nota da primeira unidade: "))
falta =(60 - (uni1*4))
mediaf = falta /6
print("Você precisa de", mediaf, "para passar")
if (opcao == 1):
func1()
elif (opcao == 2):
func2()
else:
print("Opção incorreta, saindo do programa!")
break
|
868fa6af1abc4794475a805bc1aba88de1c468ee | wragon/Fall_Detection_System | /user.py | 868 | 3.78125 | 4 | # About User Info
class UserInfo:
name = ""
number = ""
location = ""
def __init__(self):
self.set_user()
def set_user(self):
self.set_name()
self.set_number()
self.set_location()
def set_name(self):
self.name = input ("사용자 이름: ")
#self.name = "" # todo yourself
def set_number(self):
self.number = input ("보호자 연락처: ")
#self.number = "" # todo yourself
def set_location(self):
self.location = input ("사용자 위치: ")
#self.location = "" # todo yourself
def get_user(self):
print(self.name)
print(self.number)
print(self.location)
def get_name(self):
return self.name
def get_number(self):
return self.number
def get_location(self):
return self.location
|
7a1672a4dcf3a4b717001d7504315692b5209305 | lucasmarcao/slot_pra_python | /slot_para_python/jogodatabuada.py | 1,087 | 3.5 | 4 | import random
cont=0
try:
testandomatriz = random.sample([1,4,2],counts=[5,5,5], k=7)
print(testandomatriz)
except Exception as e:
print("famoso erro")
print("Você precisa de 10 pontos para ganhar")
while(cont<10):
prim = random.randint(1,11)
seg = random.randint(1,11)
print("a conta é : ",prim," X ",seg," = \n" )
vezes = prim * seg
resposta = int(input("O resultado desta conta é -------->"))
if(resposta==vezes):
print("você acertou!!!, o resultado realmente era: ", vezes)
cont = cont + 1
print("sua pontuação é:", cont)
else:
print("Você está errado, a resposta era: ", vezes)
print("sua pontuação é:", cont)
confirm = input("deseja continuar?")
if(confirm=="sim" or confirm=="SIM" or confirm=="s" or confirm=="S" or confirm=="claro"):
prim = 0
seg = 0
vezes = 0
else:
cont = 11
print("até a proxima")
if(cont==10):
print("Você ganhou o jogo")
|
7396455c9f1af991085a0a7954f7a75c55ea7986 | qilin-link/-algorithm015 | /Week_08/merge.py | 1,181 | 3.796875 | 4 | ###############################
# leetcode [56] 合并区间
###############################
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
n = len(intervals)
res = []
left = intervals[0][0]
right = intervals[0][1]
for i in range(1, n):
# 下一区间的左界小于等于当前区间的右界,表示有公共部分
if intervals[i][0] < right:
# intervals[i]右界大于当前区间的右界,表示intervals[i]不包含于当前区间,需要更新当前区间的右界
if intervals[i][1] > right:
right = intervals[i][1]
else:
# 没有交集
res.append([left, right])
# 更新当前区间左界和右界,指向下一区间
left = intervals[i][0]
right = intervals[i][1]
res.append([left, right])
return res
if __name__ == "__main__":
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
s = Solution()
print(s.merge(intervals))
|
f87ddea432ce38f221e1d2bd793f375b7d27a125 | martius-lab/GateL0RD-paper | /src/environments/remote_control_gym.py | 19,880 | 3.65625 | 4 | """
Simple control task where an agent can control a robot after accessing a computer.
The goal is to bring the robot to a goal location
The scenario is implemented in the OpenAi Gym interface (gym.openai.com)
"""
import gym
from gym import spaces, logger
import remote_control_gym_rendering as rendering
import numpy as np
import pyglet
import random
from pyglet.gl import *
from pyglet.image.codecs.png import PNGImageDecoder
import os
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) + '/'
class RemoteControlGym(gym.Env):
"""
Simple gym task for controlling a boy and a robot in a 2D environment
Observation (4 dimensional):
- Position of agent (x, y)
- Position of robot (x, y)
Action (2-dimensional):
- Movement of agent (x, y)
Additional information (may be used as additional observation, 9-dimensional)
- Is the robot controlled?
- Distance to wall for agent (N, E, S, W)
- Distance to wall for agent (N, E, S, W)
Reward is obtained when the robot is moved to the goal position.
The robot can be moved when the agent reaches a computer.
Agent and robot starting positions are randomly sampled for each simulation.
Goal and computer position do not change over simulations.
"""
def __init__(self, r_seed=42):
"""
:param r_seed: random seed
"""
super().__init__()
np.random.seed(r_seed)
self.agent_pos = (np.random.rand(2) - 0.5) * 2
self.robot_pos = (np.random.rand(2) - 0.5) * 2 + np.array([2.0, 0.0], dtype=np.float64)
self.computer_pos = np.array([0.5, 0.5], dtype=np.float64)
self.goal_pos = np.array([2.5, -0.5], dtype=np.float64)
self.r_seed = r_seed
self.agent_pos_upper_limits = np.array([0.95, 0.95], dtype=np.float64)
self.agent_pos_lower_limits = np.array([-0.95, -0.95], dtype=np.float64)
self.robot_pos_upper_limits = np.array([2.95, 0.95], dtype=np.float64)
self.robot_pos_lower_limits = np.array([1.05, -0.95], dtype=np.float64)
self.position_limits = np.array([0.95, 0.95, -0.95, -0.95, 2.95, 0.95, 1.05, -0.95], dtype=np.float64)
action_limits = np.array([1, 1])
obs_limits = np.array([0.95, 0.95, 0.95, 0.95])
self.action_space = spaces.Box(-1 * action_limits, action_limits, dtype=np.float64)
self.observation_space = spaces.Box(-1 * obs_limits, obs_limits, dtype=np.float64)
# VISUALIZATION
self.viewer = None
# all entities are composed of a Geom, a Transform (determining position) and a sprite
self.agent_sprite = None
self.agent_sprite_trans = None
self.robot_sprite = None
self.robot_sprite_trans = None
self.computer_sprite = None
self.computer_sprite_trans = None
self.goal_sprite = None
self.goal_sprite_trans = None
# background image is treated the same way
self.background_sprite = None
self.background_geom = None
self.background_trans = None
# Threshold for reaching the goal
self.goal_threshold = 0.1
# Scaling of action effect
self.action_factor = 0.1
# Range where the distance sensors detect walls
self.distance_range = 0.1
# Flag whether robot is currently controlled
self.robot_controlled = False
self.last_action = np.array([-0.1, 0], dtype=np.float64)
self.wall_contacts = np.zeros(8, dtype=np.float64)
self.t = 0
self.t_render = 0
def seed(self, seed):
self.r_seed = seed
random.seed(seed)
np.random.seed(seed)
# ------------- STEP -------------
def step(self, action):
"""
Performs one step of the simulation
:param action: next action to perform
:return: next information, obtained reward, end of sequence?, additional inf
"""
assert self.action_space.contains(action), "%r (%s) invalid" % (action, type(action))
# Save the action
self.last_action = action * self.action_factor
# Move agent (and robot) based on action
self.agent_pos = self.agent_pos + self.last_action
if self.robot_controlled:
self.robot_pos = self.robot_pos + self.last_action
# check boundaries of agent and patient position
self._clip_positions()
# Infrared sensor like measurement of wall distances
self.wall_contacts = np.zeros(8, dtype=np.float64)
double_pos_agent = np.append(self.agent_pos, self.agent_pos, 0)
double_pos_robot = np.append(self.robot_pos, self.robot_pos, 0)
double_pos = np.append(double_pos_agent, double_pos_robot, 0)
self.wall_contacts = 1.0 - 10* abs(double_pos - self.position_limits)
pos_diff = double_pos - self.position_limits
self.wall_contacts[abs(pos_diff) > self.distance_range] = 0
# Check if agent reached computer
distance_agent_computer = np.linalg.norm(self.computer_pos - self.agent_pos)
if distance_agent_computer < self.goal_threshold:
self.robot_controlled = True
# Check if robot reached goal
distance_robot_goal = np.linalg.norm(self.goal_pos - self.robot_pos)
done = distance_robot_goal < self.goal_threshold
reward = 0.0
if done:
reward = 1.0
# Adjust robot position such that it is in [-1, 1] for the observation
norm_robot_pos = np.copy(self.robot_pos)
norm_robot_pos[0] -= 2.0
# Create additional info vector
robot_controlled_array = np.array([0.0])
if self.robot_controlled:
robot_controlled_array[0] = 1.0
info = np.append(robot_controlled_array, self.wall_contacts)
observation = np.append(self.agent_pos.flat, norm_robot_pos.flat, 0)
return observation, reward, done, info
def _clip_positions(self):
np.clip(self.agent_pos, self.agent_pos_lower_limits, self.agent_pos_upper_limits, self.agent_pos)
np.clip(self.robot_pos, self.robot_pos_lower_limits, self.robot_pos_upper_limits, self.robot_pos)
# ------------- RESET -------------
def reset(self, with_info=False):
"""
Randomly reset the simulation.
:param with_info: include additional info (robot control, wall sensors) in output
:return: first observation, additional info
"""
self.agent_pos = (np.random.rand(2) - 0.5) * 2
self.robot_pos = (np.random.rand(2) - 0.5) * 2 + np.array([2.0, 0.0], dtype=np.float64)
self.computer_pos = np.array([0.5, 0.5], dtype=np.float64)
self.goal_pos = np.array([2.5, -0.5], dtype=np.float64)
self.robot_controlled = False
norm_robot_pos = np.copy(self.robot_pos)
norm_robot_pos[0] -= 2.0
self.wall_contacts = np.zeros(8, dtype=np.float64)
# Infrared sensor like measurement
double_pos_agent = np.append(self.agent_pos, self.agent_pos, 0)
double_pos_robot = np.append(self.robot_pos, self.robot_pos, 0)
double_pos = np.append(double_pos_agent, double_pos_robot, 0)
self.wall_contacts = 1.0 - 10 * abs(double_pos - self.position_limits)
pos_diff = double_pos - self.position_limits
self.wall_contacts[abs(pos_diff) > 0.1] = 0
o_init = np.append(self.agent_pos.flat, norm_robot_pos.flat, 0)
if with_info:
# Create additional info vector
robot_controlled_array = np.array([0.0])
if self.robot_controlled:
robot_controlled_array[0] = 1.0
info_init = np.append(robot_controlled_array, self.wall_contacts)
return o_init, info_init
return o_init
# ------------- RENDERING -------------
def _determine_robot_sprite(self, action, t):
"""
Finds the right sprite for the robot depending on the last actions
:param action: last action
:param t: time
:return: sprite number
"""
if self.robot_controlled:
return t % 4
return 0
def _determine_agent_sprite(self, action, t):
"""
Finds the right sprite for the agent depending on the last actions
:param action: last action
:param t: time
:return: sprite number
"""
if abs(action[1]) > abs(action[0]):
# Left right dimension is stronger than up/down
if action[1] < 0:
# down:
return 0 + t % 2
else:
#up
return 2 + t % 2
else:
if action[0] < 0:
# left:
return 4 + t % 2
else:
#right
return 6 + t % 2
def render(self, store_video=False, video_identifier=1, mode='human'):
"""
Renders the simulation
:param store_video: bool to save screenshots or not
:param video_identifier: number to label video of this simulation
:param mode: inherited from gym, currently not used
"""
# Constant values of window size, sprite sizes, etc...
screen_width = 1200 #pixels
screen_height = 630 #pixels
agent_sprite_width = 70 # pixels of sprite
robot_sprite_width = 70
computer_sprite_width = 70
wall_pixel_width = 12
goal_sprite_width = 16
goal_sprite_height = 16
scale = 300.0 # to compute from positions -> pixels
foreground_sprite_scale = 2 # constant scaling of foreground sprites
background_sprite_scale = 3 # constant scaling of walls, floor, etc...
self.t += 1
if self.t % 2 == 0:
self.t_render += 1
if self.viewer is None:
# we create a new viewer (window)
self.viewer = rendering.Viewer(screen_width, screen_height)
glEnable(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
# Agents sprite list [d, u, l, r] *[0, 1]
agent_sprite_list = []
robot_sprite_list = []
agent_sprite_names = ["d", "u", "l", "r"]
for i in range(4):
robot_sprite_file = SCRIPT_PATH + "RRC_Sprites/rob" + str(i+1) + ".png"
robot_image = pyglet.image.load(robot_sprite_file, decoder=PNGImageDecoder())
robot_pyglet_sprite = pyglet.sprite.Sprite(img=robot_image)
robot_sprite_list.append(robot_pyglet_sprite)
for j in range(2):
agent_sprite_file = SCRIPT_PATH + "RRC_Sprites/" + agent_sprite_names[i] + str(j+1) + ".png"
agent_image = pyglet.image.load(agent_sprite_file, decoder=PNGImageDecoder())
agent_pyglet_sprite = pyglet.sprite.Sprite(img=agent_image)
agent_sprite_list.append(agent_pyglet_sprite)
self.agent_sprite = rendering.SpriteGeom(agent_sprite_list)
self.agent_sprite_trans = rendering.Transform()
self.agent_sprite.add_attr(self.agent_sprite_trans)
self.viewer.add_geom(self.agent_sprite)
self.robot_sprite = rendering.SpriteGeom(robot_sprite_list)
self.robot_sprite_trans = rendering.Transform()
self.robot_sprite.add_attr(self.robot_sprite_trans)
self.viewer.add_geom(self.robot_sprite)
goal_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/target.png", decoder=PNGImageDecoder())
goal_pyglet_sprite = pyglet.sprite.Sprite(img=goal_image)
goal_sprite_list = [goal_pyglet_sprite]
self.goal_sprite = rendering.SpriteGeom(goal_sprite_list)
self.goal_sprite_trans = rendering.Transform()
self.goal_sprite.add_attr(self.goal_sprite_trans)
self.viewer.add_geom(self.goal_sprite)
computer_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/terminal2.png", decoder=PNGImageDecoder())
computer_pyglet_sprite = pyglet.sprite.Sprite(img=computer_image)
computer_sprite_list = [computer_pyglet_sprite]
self.computer_sprite = rendering.SpriteGeom(computer_sprite_list)
self.computer_sprite_trans = rendering.Transform()
self.computer_sprite.add_attr(self.computer_sprite_trans)
self.viewer.add_geom(self.computer_sprite)
wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder())
wall_pyglet_sprite = pyglet.sprite.Sprite(img=wall_image)
wall_sprite_list = [wall_pyglet_sprite]
wall_sprite = rendering.SpriteGeom(wall_sprite_list)
wall_sprite_trans = rendering.Transform()
wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_sprite_trans.set_translation(screen_width/2.0 - wall_pixel_width/2.0 * background_sprite_scale, 0)
wall_sprite.set_z(3)
wall_sprite.add_attr(wall_sprite_trans)
self.viewer.add_geom(wall_sprite)
wall_2image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder())
wall_2pyglet_sprite = pyglet.sprite.Sprite(img=wall_2image)
wall_2sprite_list = [wall_2pyglet_sprite]
wall_2sprite = rendering.SpriteGeom(wall_2sprite_list)
wall_2sprite_trans = rendering.Transform()
wall_2sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_2sprite_trans.set_translation(0 - wall_pixel_width / 2.0 * background_sprite_scale, 0)
wall_2sprite.set_z(3)
wall_2sprite.add_attr(wall_2sprite_trans)
self.viewer.add_geom(wall_2sprite)
wall_3image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder()) # "Sprites/wall_longest3.png"
wall_3pyglet_sprite = pyglet.sprite.Sprite(img=wall_3image)
wall_3sprite_list = [wall_3pyglet_sprite]
wall_3sprite = rendering.SpriteGeom(wall_3sprite_list)
wall_3sprite_trans = rendering.Transform()
wall_3sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_3sprite_trans.set_translation(screen_width - wall_pixel_width / 2.0 * background_sprite_scale, 0)
wall_3sprite.set_z(3)
wall_3sprite.add_attr(wall_3sprite_trans)
self.viewer.add_geom(wall_3sprite)
back_wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/back_wall.png", decoder=PNGImageDecoder())
back_wall_pyglet_sprite = pyglet.sprite.Sprite(img=back_wall_image)
back_wall_sprite_list = [back_wall_pyglet_sprite]
back_wall_sprite = rendering.SpriteGeom(back_wall_sprite_list)
back_wall_sprite_trans = rendering.Transform()
back_wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
back_wall_pixel_height = 20
back_wall_sprite_trans.set_translation(0, screen_height - back_wall_pixel_height)
back_wall_sprite.add_attr(back_wall_sprite_trans)
self.viewer.add_geom(back_wall_sprite)
front_wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/grey_line.png", decoder=PNGImageDecoder())
front_wall_pyglet_sprite = pyglet.sprite.Sprite(img=front_wall_image)
front_wall_sprite_list = [front_wall_pyglet_sprite]
front_wall_sprite = rendering.SpriteGeom(front_wall_sprite_list)
front_wall_sprite_trans = rendering.Transform()
front_wall_sprite_trans.set_translation(0, 0)
front_wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
front_wall_sprite.add_attr(front_wall_sprite_trans)
self.viewer.add_geom(front_wall_sprite)
background_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/grey_wood_background.png", decoder=PNGImageDecoder())
background_pyglet_sprite = pyglet.sprite.Sprite(img=background_image)
background_sprite_list = [background_pyglet_sprite]
background_sprite = rendering.SpriteGeom(background_sprite_list)
background_sprite_trans = rendering.Transform()
background_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
background_sprite.set_z(-1)
background_sprite.add_attr(background_sprite_trans)
self.viewer.add_geom(background_sprite)
# during video recording images of the simulation are saved
if store_video:
self.viewer.activate_video_mode("Video" + str(video_identifier) + "/")
# determine the sprite position and size for
# 1. ... agent
agent_x = (self.agent_pos[0] + 1) * scale
agent_y = (self.agent_pos[1] + 1) * scale
self.agent_sprite.set_z(1)
self.agent_sprite.alter_sprite_index(self._determine_agent_sprite(self.last_action, self.t_render))
self.agent_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
sprite_center = np.array([foreground_sprite_scale * agent_sprite_width / 2.0, 0.0])
self.agent_sprite_trans.set_translation(agent_x - sprite_center[0], agent_y - sprite_center[1])
# 2. ... the computer
computer_x = (self.computer_pos[0] + 1) * scale
computer_y = (self.computer_pos[1] + 1) * scale
self.computer_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
computer_sprite_center = np.array([foreground_sprite_scale * computer_sprite_width / 2.0, 0])
self.computer_sprite_trans.set_translation(computer_x - computer_sprite_center[0], computer_y - computer_sprite_center[1])
self.computer_sprite.set_z(0)
if agent_y > computer_y + computer_sprite_width / 4.0:
self.computer_sprite.set_z(2)
# 3. ... the goal
goal_x = (self.goal_pos[0] + 1) * scale
goal_y = (self.goal_pos[1] + 1) * scale
self.goal_sprite.set_z(0)
self.goal_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
goal_sprite_center = np.array([background_sprite_scale * goal_sprite_width / 2.0, background_sprite_scale * goal_sprite_height / 2.0])
self.goal_sprite_trans.set_translation(goal_x - goal_sprite_center[0], goal_y - goal_sprite_center[1])
# 4. ... the robot
robot_x = (self.robot_pos[0] + 1) * scale
robot_y = (self.robot_pos[1] + 1) * scale
self.robot_sprite.set_z(1)
self.robot_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
robot_sprite_center = np.array([foreground_sprite_scale * robot_sprite_width / 2.0, 0.0])
self.robot_sprite_trans.set_translation(robot_x - robot_sprite_center[0], robot_y - robot_sprite_center[1])
self.robot_sprite.alter_sprite_index(self._determine_robot_sprite(self.last_action, self.t_render))
return self.viewer.render(mode == 'rgb_array')
# ------------- CLOSE -------------
def close(self):
"""
Shut down the gym
"""
if self.viewer:
self.viewer.deactivate_video_mode()
self.viewer.close()
self.viewer = None
|
a0411df383523974ac3d9bfec5c4031066dcfe93 | Serge-Mavuba/Python-List-Comprehensions | /Lists Comprehensions.py | 3,665 | 4.34375 | 4 | # List = [1,2, "collection ", "of", "data", "surronded", "by", "brackets", "and", "the",
# "elements", "are", "separated", "by", "commas"]
# List comprehensions =
# ["is", "also", "surronded", "by", "brackets","but", "instead", "of", "a", "list", "of", "data", "inside"
# "you", "enter", "an", "expression", "followed", "by", "for", "loops", "and", "if", "clauses"]
# Here is the most basic forms for a list comprehension:
# [expr for val in collection]
# expr: the first expression generates the elements in the list
# for val in collection: followed with a for loop over some collection of data (this evaluates every item in the collection)
# [expr for val in collection if <test>]
# if <test>: adding an if clause will only evaluate the expression for certains pieces of data
# Print colored Text
import colorama
from colorama import Fore, Back, Style
colorama.init(autoreset=True)
# Using a List Comprcehension, list all the students with the name that starts with the letter "S"
#------------------------------------------------------------------------------------------------
NAMES = ['Dana Hausman', 'Corrine Haley', 'Huan Xin (Winnie) Cai', 'Greg Willits', 'Michael Lyda', 'Aidana Utepkaliyeva',
'Claudius Taylor', 'Dyian Nikolv', 'Higl Daniel', 'Mary Beth Arroyo', 'Sajini George', 'Natalia Gomez',
'Riad Mesharafa','Shafan Sugarman','Sarah Chang', 'Rashmi Venkatesh', 'Higl Daniel', 'Domineco Sacca', 'Tanzeela Chaudry',
'Nataliia Zdrok','Natnael Argaw','Nosa Okundaye', 'Sibel Gulmez', 'Serge Mavuba', 'Geethalakshmi Prasanna', 'Gwei Balantar',
'Imran Barker', 'Lesley Ndeh', 'Trevor Unaegbu', 'Abraham Musa', 'Roberto Santos']
print(Fore.WHITE + Back.RED + Style.BRIGHT +"Names = " + ", ".join(NAMES))
print(155*"-")
# Without using a List comprehension
#-----------------------------------
# Make an empty list
PerScholas =[]
# Loop over the list of names
for student in NAMES:
# We can use the startswith method to see the student names that start with the letter S
if student.startswith("S"):
# then append the results to a list
PerScholas.append(student)
# print to make sure that it worked
print(Fore.WHITE + Back.RED + Style.BRIGHT + ", ".join(PerScholas))
print(155*"-")
# Using a List Comprehension you can reduce lines of code into a single line
#---------------------------------------------------------------------------
PerScholas2=[student for student in NAMES if student.startswith('S')]
# the expression we want to appear on our list is simply the student; next loop over the names
# but also check that the name starts with the letter S then print
print(Fore.RED + Back.WHITE + Style.BRIGHT + ", ".join(PerScholas2))
print(155*"-")
# Lets get fancier: consider a List of tuples
# -------------------------------------------
NEW = [('Dana Hausman', 1996), ('Corrine Haley', 1998), ('Huan Xin (Winnie) Cai', 1997), ('Greg Willits', 2001), ('Michael Lyda', 1995), ('Aidana Utepkaliyeva', 2000),
('Claudius Taylor', 2001), ('Dyian Nikolv', 2016), ('Higl Daniel', 2009), ('Mary Beth Arroyo', 2010), ('Sajini George', 2006), ('Natalia Gomez', 2007),
('Riad Mesharafa', 1922),('Shafan Sugarman', 1980),('Sarah Chang', 1946), ('Rashmi Venkatesh', 1970), ('Higl Daniel', 1919), ('Domineco Sacca', 2000), ('Tanzeela Chaudry', 2020),
('Nataliia Zdrok', 2121),('Natnael Argaw', 2021),('Nosa Okundaye',2525), ('Sibel Gulmez', 2527), ('Serge Mavuba', 1995), ('Geethalakshmi Prasanna', 2000), ('Gwei Balantar', 3000),
('Imran Barker', 1900), ('Lesley Ndeh', 1999), ('Trevor Unaegbu', 2001), ('Abraham Musa', 2000), ('Roberto Santos', 1890)]
# Using a list comprehension list all the students born before the year 2000
#---------------------------------------------------------------------------
pre2k=[student for (student, year) in NEW if year < 2000]
# we want our list to contain the student name but this time when we write the for-loop; each element is a tuple.
# Next We select the students that were born before 2000 using an if clause
print(Fore.WHITE+ Back.GREEN + Style.BRIGHT + ", ".join(pre2k)) |
b436c92cebb0c6af8e53b211d2b85bb68374ea4b | diagram-ai/vishwakarma | /vishwakarma/pdfplot.py | 4,625 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
Build visualizations for continuous distributions
[Uniform, Gaussian, Exponential, Gamma]
Example:
from vishwakarma import pdfplot
pdfplot.gaussian(mu, sigma)
Attributes:
Todo:
'''
import requests
import tempfile
import os
import random
import shutil
import string
import datetime
from IPython.display import Image
class pdfplot:
''' This class generates visualizations for continuous distributions '''
# setup the API endpoint to be called
_url = 'http://api.diagram.ai:5000/vishwakarma/'
_endpoint = 'pdfplot/'
# default width of image to be displayed
_width = 600
@classmethod
def uniform(cls, a, b):
'''
Visualization for a Uniform distribution
Args:
a, b (int): parameters to a Uniform distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if not isinstance(a, int):
raise ValueError('For a Uniform distribution, a should always be an integer.')
if not isinstance(b, int):
raise ValueError('For a Uniform distribution, b should always be an integer.')
if b <= a:
raise ValueError('For a Uniform distribution, b should always be greater than a.')
return cls._call_post(dist='uniform', a=a, b=b)
@classmethod
def gaussian(cls, mu, sigma):
'''
Visualization for a Gaussian distribution
Args:
mu, sigma (float): parameters to a Gaussian distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if sigma <= 0:
raise ValueError('For a Gaussian distribution, sigma should be greater than zero.')
return cls._call_post(dist='gaussian', mu=mu, sigma=sigma)
@classmethod
def exponential(cls, lam, sam):
'''
Visualization for an Exponential distribution
Args:
lam (float): parameter to an Exponential distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if lam <= 0:
raise ValueError('For an Exponential distribution, lambda should be greater than zero.')
return cls._call_post(dist='exponential', lam=lam, sam=sam)
@classmethod
def gamma(cls, alpha, beta):
'''
Visualization for a Gamma distribution
Args:
alpha, beta (float): parameters to a Gamma distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if alpha <= 0:
raise ValueError('For a Gamma distribution, alpha should be greater than zero.')
if beta <= 0:
raise ValueError('For a Gamma distribution, beta should be greater than zero.')
return cls._call_post(dist='gamma', alpha=alpha, beta=beta)
@classmethod
def _call_post(cls, **kwargs):
'''
Calls the API hosted on www.diagram.ai
Args:
kwargs: Name and parameters of the distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
Note:
Internal function - not to be exposed
'''
tmp_dir_name = ''
try:
# create a temp directory & temp file
tmp_dir_name = tempfile.mkdtemp()
# generate a tmp file name (excluding file extension)
epoch = datetime.datetime.now().strftime('%s')
tmp_file_name = ''.join(
[random.choice(string.ascii_letters + string.digits) for n in range(8)])
tmp_file_name = os.path.join(
tmp_dir_name, tmp_file_name + epoch + '.png')
# make the call ...
resp = requests.post(cls._url + cls._endpoint, json=kwargs)
if(resp.ok):
# get the image file and write it to temp dir
if resp.headers.get('Content-Type') == 'image/png':
open(tmp_file_name, 'wb').write(resp.content)
# now return this image as an Image object displayable in a
# Jupyter notebook
return Image(filename=tmp_file_name, width=cls._width)
else:
raise Exception(resp.raise_for_status())
finally:
# cleanup the temp directory
shutil.rmtree(tmp_dir_name, ignore_errors=True)
|
077c33b4377263224f651ff989fd186d289d71ff | hongweifei/Fly-python | /compiler/ast.py | 2,156 | 3.546875 | 4 |
from .token import *
from enum import Enum,unique,auto
@unique
class TreeType(Enum):
NONE = auto() #
IMPORT = auto() # include,import
RETURN = auto() # return
VAR = auto() # 变量声明
FUNCTION = auto() # 函数声明
UNION = auto() # 定义联合体
STRUCT = auto() # 定义结构体
CLASS = auto() # 定义类
CALL = auto() # 调用
ASSIGN = auto() # 赋值
IF = auto() # 如果
SWITCH = auto() # 判断
WHILE = auto() # while
FOR = auto() # for
class Node(object):
"""
A node in the abstract syntax tree of the program.
"""
def __init__(self,token = None):
super().__init__()
self.token:Token = token;
self.parent = None;
self.children = [];
def add_child(self,node):
if node != None:
self.children.append(node);
node.parent = self;
def get_parent(self):
return self.parent;
def get_children(self):
return self.children;
def get_parent_num(self) -> int:
if self.parent == None:
return 0;
else:
n = 0;
parent:Node = self.parent;
while parent != None:
n += 1;
parent = parent.parent;
return n;
def print(self):
if self.parent == None:
print("--" + self.token.value + " type:" + str(self.token.ttype))
else:
print("--" + "-" * self.get_parent_num() + self.token.value + " type:" + str(self.token.ttype))
if self.parent != None and len(self.children) == 0:
if self is self.parent.children[len(self.parent.children) - 1]:
print("\n")
for child in self.children:
child.print()
class RootNode(Node):
def __init__(self, token = None):
super().__init__(token = token)
self.ttype = TreeType.NONE;
def print(self):
print("Type:" + str(self.ttype));
return super().print();
|
c219b35384dcc23574658cfcbae883f4223f8709 | LRG84/python_assignments | /average7.5.py | 538 | 4.28125 | 4 | # calculate average set of numbers
# Write a small python program that does the following:
# Calculates the average of a set of numbers.
# Ask the user how many numbers they would like to input.
# Display each number and the average of all the numbers as the output.
def calc_average ():
counter = int (input('How many numbers would you like to input?_'))
total = 0
for a in range (0, counter):
total = total + int(input('Enter number_ '))
print('The average of your input is ', total/counter)
calc_average ()
|
cfa1235528a3b32f4c93e015f89ef13b2b8053be | LRG84/python_assignments | /Celsius_5degree_increments.py | 323 | 3.984375 | 4 | #write a program that outputs a table of celsius temperatures from 1-100, in increments of 5
#in addition, the corresponding farenheit temperature should be listed.
#upload to github
for a in range (0,101,5):
cel_temp = a
far_temp = cel_temp * (9/5) + 32
print ('celsius =',cel_temp,'farenheit =',far_temp)
|
0095ae6aada5352dee242b1ec05a027fd695de99 | VishLi777/python-practice | /bonus_practice1/task6_1_1.py | 490 | 3.90625 | 4 | # Реализуйте функцию fast_mul в соответствии с алгоритмом двоичного умножения в столбик.
# Добавьте автоматическое тестирование, как в случае с naive_mul.
def fast_mul(x, y):
if x == 0 or y == 0: # add condition
return 0
r = 0 # r = 1
while y > 0:
if y % 2 == 1:
r += x
x *= 2
y //= 2
return r
|
6cbc3f38656ead6125e3c1cc360d9e0e2a1de979 | ttitus72372/GitHubTesting | /main.py | 597 | 3.546875 | 4 | '''
x = 0
while x <= 10:
x +=1
print(x)
#print(x)
list1 = [1,4,7,9,11,34,65]
for item in list1:
#print(item)
if item <= 20:
print(item)
numb1 = int(input("Please enter a number:\n"))
numb2 = int(input("Please enter another number:\n"))
numb3 = numb1 + numb2
print(numb3)
'''
list2 = []
counter = 0
while counter < 5:
var = int(input("Type a number to be added into the list:\n"))
list2.append(var)
counter +=1
print(sum(list2))
#hi tim
#looks like the Github collaboration works.
#it doesn't seem to highlight who did what changes, directly within repl.it, at this time.
|
66a863f91af4b1fb778e0b8edface323d321f370 | RasmusKnothNielsen/PicoCTF2019 | /General_Skills/whats_the_difference/whats_the_difference_solution.py | 597 | 3.546875 | 4 | # Whats-the-difference
# General skills
# PicoCTF 2019
# Author: Rasmus Knoth Nielsen
# Open the kitters.jpg file and read it into memory
with open('./kitters.jpg', 'rb') as f:
kitters = f.read()
# Open the cattos.jpg file and read it into memory
with open('./cattos.jpg', 'rb') as f:
cattos = f.read()
flag = ''
# For the length of the shortest file, do the following
for i in range(min(len(kitters), len(cattos))):
# If these differ, do the following
if kitters[i] != cattos[i]:
# Save the Decimal as the ASCII value in our flag variable
flag += chr(cattos[i])
print(flag)
|
1420c19f9f80614f5d3b6ba122ed7b1d9f51122f | shihan123a/Daily_-summary | /绘图函数/递归函数.py | 238 | 4.03125 | 4 | import sys
def Factorial(num):
if num == 1 :
return 1
else:
result = num * Factorial(num-1)
return result
if __name__ == '__main__' :
result = Factorial(5)
print('5的阶乘是:{}'.format(result)) |
833bd691452513944dabb2af51272c90c70c8eaf | lucasrwv/python-p-zumbis | /lista III/questao04.py | 273 | 4.125 | 4 | #programa fibonacci
num = int(input("digite um numero "))
anterior = 0
atual = 1
proximo = 1
cont = 0
while cont != num :
seun = proximo
proximo = atual + anterior
anterior = atual
atual = proximo
cont += 1
print("o seu numero fibonacci é %d" %seun)
|
ddfd3b2738cce2d2d41f57cd21687fa488e76f2b | lucasrwv/python-p-zumbis | /lista II/questao02.py | 259 | 3.953125 | 4 | # ano bixesto
ano = int(input("digite o ano: "))
if ano % 4 == 0 and ano % 100 != 0 :
print("o ano é bissexto")
elif ano % 4 == 0 and ano % 100 == 0 and ano % 400 == 0 :
print("o ano é bissexto")
else :
print("o ano nao é bissexto")
|
fef2ed2eaf412fa0a834c78b34b9b44a5539ad8a | vijaykumar0425/hacker_rank | /find_angle_mbc.py | 232 | 3.5625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
import sys
AB = int(sys.stdin.readline())
BC = int(sys.stdin.readline())
sys.stdout.write(str(int(round(math.degrees(math.atan2(AB,BC)))))+'°')
|
87b9e6213dcff364197171e9afeaedb337ffb85d | cloew/KaoEnum | /kao_enum/enum.py | 310 | 4 | 4 |
class Enum:
""" Represents an Enum Value """
def __init__(self, name, value):
""" Initialize the enum """
self.name = name
self.value = value
def __repr__(self):
""" Return the string representation of this code """
return self.name |
a57a741e02e04d1f68da45e92fcbf8185c338f36 | mizanur-rahman/HackerRank | /Python3/30 days of code/Day 15: Linked List/Solutions.py | 992 | 4.0625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
#Complete this method
if (head == None):
head = Node(data)
elif (head.next == None):
head.next = Node(data)
else:
self.insert(head.next, data)
return head
'''The function gets called with the whole linked list.
If the list is empty,
insert the element as the head.
Otherwise if there is no element after the head,
put the data after the head.
Otherwise,
call the function with all of the elements except for the current head'''
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
|
ef5382ae6d2ee520c0557fd3e6a391a23aaee001 | Ashokkommi0001/Python-Patterns-Numbers | /_1.py | 234 | 4.09375 | 4 | def _1():
for row in range(7):
for col in range(7):
if (col==3 or row==6) or (row<3 and row+col==2):
print("*",end="")
else:
print(end=" ")
print()
|
a0767955d16ae2f862b4a531a76a8184e8787d48 | LucasVanni/Curso_Python | /Exercícios/ex031.py | 346 | 3.703125 | 4 | viagem = float(input('Qual a distância da sua viagem? '))
if viagem <= 200:
valor = viagem * 0.5
else:
valor = viagem * 0.45
valor = viagem * 0.5 if viagem <= 200 else viagem * 0.45
print('Você está prestes a começar uma viagem de {}KM.'.format(viagem))
print('E o preço da sua passagem será de R${:.2f}'.format(valor))
|
5fdcd02074edb64c999337c33c6c19bc83969632 | LucasVanni/Curso_Python | /AulasCursoemVideo/Desafio 034.py | 246 | 3.890625 | 4 | salario = float(input('Digite o valor do salário: '))
if salario >= 1250.00:
aumento = (salario * 10/100)
else:
aumento = (salario * 15/100)
print('Com o salário de R${}, irá ter um aumento de R${}'.format(salario, aumento)) |
793d6472ec2b57d50651c22328f73ab33782cfac | LucasVanni/Curso_Python | /AulasCursoemVideo/Desafio 020 - nome dos quatro alunos ordem sorteada.py | 412 | 3.703125 | 4 | import random
n1 = str(input('Digite o nome do primeiro aluno a ser sorteado: '))
n2 = str(input('Digite o nome do segundo aluno a ser sorteado: '))
n3 = str(input('Digite o nome do terceiro aluno a ser sorteado: '))
n4 = str(input('Digite o nome do quarto aluno a ser sorteado: '))
lista = [n1, n2, n3, n4]
random.shuffle(lista)
print('A ordem da lista de apresentação será: ')
print(lista)
|
28727bb99a537272c5e73381d48e565bcf9316c3 | LucasVanni/Curso_Python | /Exercícios/ex017.py | 346 | 3.859375 | 4 | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hip = hypot(ca, co)
hi = (co ** 2 + ca ** 2) ** (1/2)# maneira matemática
print('A hipotenusa vai medir {:.2f}'.format(hip))
print('A hipotenusa no método matemático vai medir {:.2f}'.format(hi))
|
fd589aec05438820a5d63f54515ef62ea4d2f5b1 | mrerikas/Mastery_Python | /find_duplicates.py | 523 | 4.0625 | 4 | def find_duplicates(list):
duplicates = []
for item in list:
if list.count(item) > 1:
if item not in duplicates:
duplicates.append(item)
return duplicates
print(find_duplicates(['a', 'b', 'c', 'a', 'd', 'd', 'e', 'f', 'g', 'f']))
# or without function()
list = ['a', 'b', 'c', 'a', 'd', 'd', 'e', 'f', 'g', 'f']
duplicates = []
for items in list:
if list.count(items) > 1:
if items not in duplicates:
duplicates.append(items)
print(duplicates)
|
14743b046284e9c60f213351695433fd0c763a11 | jcheong0428/psy161_assignments | /sandbox20160216.py | 1,050 | 3.84375 | 4 | def size(A):
i=[]
while type(A)==list:
i.append(len(A))
A=A[0]
return tuple(i)
def slicer(lst,slicelist,i=0):
res = []
if isinstance(slicelist,slice):
return res
else:
print lst, slicelist,
for i,e in enumerate(lst[slicelist[i]]):
print i,e
res.append(slicer(e,slicelist(i),i))
def mygen2(lst,slicelist):
""" Returns a slice of your Array.
Input must be a list of tuples with length the same as dimensions.
Only supports 2 ~ 4 dimensions right now...
Examples
--------
>> a=[[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]]
>> A = Array(a)
>> A.mygen2([slice(0,2),slice(0,2),slice(0,2)])
>> [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
maybe use res.append(recursive function here)
"""
res = []
if isinstance(lst,list)&isinstance(slicelist,list):
s = slicelist[0]
for e in lst[s]:
res.append(list(slicer(e,s)))
lst = list(slicer(e,s))
slicelist.pop(0)
return res |
a085d9ff5c97264c048a0f265806c906647d90df | shyam-de/py-developer | /d2exer1.py | 1,091 | 4.1875 | 4 | # program to check wether input number is odd/even , prime ,palindrome ,armstrong.
def odd_even(num):
if num%2==0:
print("number is even")
else:
print( 'number is odd')
def is_prime(num):
if num>1:
for i in range(2,num//2):
if (num%i)==0:
print('number is not prime')
# print(i,"times",num//i,'is'num)
break
else:
print("number is prime")
else:
print("number is not prime")
def is_arm(num):
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**3
temp//=10
if num==sum:
print("number is armstrong")
else :
print("number is not armstrong")
def is_pal(num):
temp=num
rev=0
while num>0:
dig=num%10
rev=rev*10+dig
num=num//10
if temp==rev:
print("number is palindrome")
else:
print(" numer is not palindrome")
num=int(input("Enter a number "))
print(odd_even(num),is_prime(num),is_arm(num),is_pal(num))
|
c0a5c9e9dffd82f9bf748ed09963ebde4e9c8fd1 | ShimizuKo/AtCoder | /ABC/100-109/109/B.py | 233 | 3.5625 | 4 | N = int(input())
word_list = []
ans = "Yes"
for i in range(N):
word = input()
word_list.append(word)
if i != 0:
if not(word[0] == word_list[i - 1][-1] and word_list.count(word) == 1):
ans = "No"
break
print(ans) |
4d6fdfa22d2fb1555731651c32a588dde6552795 | ShimizuKo/AtCoder | /企業コン/三井住友2019/B.py | 120 | 3.609375 | 4 | N = int(input())
ans = ":("
for x in range(1, N + 1):
n = int(x * 1.08)
if n == N:
ans = x
break
print(ans) |
1a2a51b714e82ae71922c9dfb5d3b002923d53b3 | Crow07/python-learning | /python learning/循环/for.py | 390 | 3.984375 | 4 | for i in range(3):
print('loop',i)
for i in range(0,6,2):
print("loop",i)
age_of_crow = 22
count= 0
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_crow:
print("yes,all right")
break
elif guess_age > age_of_crow:
print("smaller")
else:
print("bigger")
else:
print("you have tried too many times") |
d5f5fc08d19273e530ff46658c3b67804bebf92d | tweatherford/COP1000-Homework | /Weatherford_Timothy_A9_Sort_Search_Rainfall.py | 3,810 | 3.703125 | 4 | '''
Assignment#9: Rainfall Version - Sorts data, searches array, and outputs to file.
Programmer: Timothy Weatherford
Course: COP1000 - Intro to Computer Programming
'''
#Initial Variables
rainArray = []
count = 0
file = open("rainfallData.txt","r")
sortStatus = False
outputFile = open("Weatherford_Timothy_A9_Python_Rainfall_Output.txt", "w")
#Helper Methods
#prints header
def makeHeader(text):
print("=-"*30)
print(text)
print("=-"*30)
#writes headers to file
def writeHeader(text):
global outputFile
outputFile.write("=-"*30 + "\n")
outputFile.write(text + "\n")
outputFile.write("=-"*30 + "\n")
#Appends data to array for us
def appendData(rain):
global rainArray
rainArray.append(float(rain))
#Searches the array for a a rain data of the users choice
def searchArray(outputFile):
outputFile = outputFile
count = 0
targetCount = 0
writeHeader("Rain Data Search")
searchString = input("Please enter rain data to search for:")
global rainArray
for rain in rainArray:
if float(rain) == float(searchString):
targetCount += 1
outputFile.write("Your target rain data of " + str(searchString) + " occured " + str(targetCount) + " times." + "\n")
print("-"*10)
print("Your target rain data of " + str(searchString) + " occured " + str(targetCount) + " times." + "and the output has been saved to the file.")
print("-"*10)
#Iterates array and displays each
def displayArray(sortStatus,outputFile):
outputFile = outputFile
count = 0
global rainArray
if sortStatus == True:
makeHeader("Display all rain data(sorted):")
writeHeader("Display all rain datas(sorted):")
else:
makeHeader("Display all rain data(unsorted):")
writeHeader("Display all rain data(unsorted):")
for rain in rainArray:
count += 1
outputFile.write("Rain Data#" + str(count) + " is:" + str(rainArray[count-1]) + "\n")
print("Rain Data#" + str(count) + " is:" + str(rainArray[count-1]))
print("The output has been prepared to the file. Please quit to save.")
#Sorts array
def sortArray(rainArray,targetCount):
#Bubble sort variables
flag = 0
swap = 0
while flag == 0:
flag = 1
swap = 0
while swap < (int(targetCount)-1):
if rainArray[swap] > rainArray[swap + 1]:
tempRain = rainArray[swap]
rainArray[swap] = rainArray[swap + 1]
rainArray[swap + 1] = tempRain
flag = 0
swap = swap + 1
sortStatus = True
print("-"*10)
print("The rain list has been sorted, please re-run 1 from the main menu to prepare the file for output.")
print("-"*10)
return sortStatus
#Main Menu
def mainMenu():
global targetCount, sortStatus, outputFile
makeHeader("Main Menu")
choice = int(input("Please choose 1 to display and output all rain entries to file, 2 to search rain data, 3 to sort rain data, or 4 to quit(writes file to disk):"))
if choice == 1:
displayArray(sortStatus,outputFile)
mainMenu()
elif choice == 2:
searchArray(outputFile)
mainMenu()
elif choice == 3:
sortStatus = sortArray(rainArray,targetCount)
mainMenu()
elif choice == 4:
outputFile.close()
pass
else:
print("Invalid Selection - Please choose again")
mainMenu()
#RAIN ARRAY INTIALIZATION - This handles startup more or less.
makeHeader("Program Startup - Rain Entry")
targetCount = input("How many rain data points are in the input file?(default 60):")
if targetCount == "":
targetCount = 60
while count < int(targetCount):
count +=1
rain = float(file.readline().strip())
appendData(rain)
mainMenu()
|
f179a86035e710a59300a467e2f3cd4e9f8f0b15 | tweatherford/COP1000-Homework | /Weatherford_Timothy_A3_Gross_Pay.py | 1,299 | 4.34375 | 4 | ##-----------------------------------------------------------
##Programmed by: Tim Weatherford
##Assignment 3 - Calculates a payroll report
##Created 11/10/16 - v1.0
##-----------------------------------------------------------
##Declare Variables##
grossPay = 0.00
overtimeHours = 0
overtimePay = 0
regularPay = 0
#For Presentation
print("Payroll System")
print("=-"*30)
##Input Section##
empName = str(input("Enter the Employee's Full Name:"))
hoursWorked = float(input("Enter Hours Worked:"))
payRate = float(input("Enter " + empName + "'s hourly rate of pay:$"))
print("-"*60)
##Logic Functions##
if hoursWorked > 40:
overtimeHours = hoursWorked - 40
regularPay = 40 * payRate
overtimePay = (payRate*1.5) * overtimeHours
grossPay = regularPay + overtimePay
else:
regularPay = hoursWorked * payRate
grossPay = regularPay
#Output
print("=-"*30)
print("Payroll Report for " + empName)
print("=-"*30)
print("--Hours Worked--")
print("Total Hours Worked:" + str(hoursWorked))
print("Overtime Hours:" + str(overtimeHours))
print("--Pay Information--")
print("Regular Pay:$" + str(format(regularPay, "9,.2f")))
print("Overtime Pay:$" + str(format(overtimePay, "9,.2f")))
print("Total Gross Pay:$" + str(format(grossPay, "9,.2f")))
print("=-"*30)
print("End Payroll Report")
|
f9e3d8e6a7ab0bc54e40128daf95ab132f5360f7 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia4/cwiczenia6.py | 245 | 3.65625 | 4 | a = int(input("Podaj liczbę: "))
b = 0
c = 0
while a % 2 == 0 or a % 3 == 0:
b += 1
if a % b == 0:
if a == b:
break
c = a + b
print(b)
else:
if b == a:
break
continue
|
ef8a51fe8281b47ccb7f0e64986aab70d585982a | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia6/cwiczenia2.py | 521 | 3.640625 | 4 | from statistics import median
tab = []
n = int(input("Podaj początek zakresu: "))
x = int(input("Podaj koniec zakresu zakresu: "))
while True:
if n == 0 or x == 0:
print("Podałeś gdzieś zero")
break
else:
for i in range(n, x):
i += 1
tab.append(i)
tab_2 = tab[0:6]
print("Twoja tablica liczb: ", tab_2)
print("Wartość maksymaalna: ", max(tab_2))
print("Wartość minimalna: ", min(tab_2))
print("Średnia: ", len(tab_2))
print("Mediana: ", median(tab_2))
|
6db7314e823010875b7f68d7defd4b094a144cb2 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia9/cwiczenia2.py | 857 | 3.8125 | 4 | import statistics
tel = {
"Jan": "123456789",
"Robert": "123456789",
"Andrzej": "123456789",
"Karol": "123456789",
"Romek": "123456789",
"Szymon": "123456789",
"Grzegorz": "123456789",
"Karolina": "123456789",
"Anna": "123456789",
"Maja": "123456789"
}
"""for i in range(10):
nazwisko = str(input("Podaj nazwisko: "))
numer = str(input("Podaj numer: "))
tel[nazwisko] = numer
"""
print(tel)
telf = list(tel.keys())[0]
tell = list(tel.keys())[len(tel)-1]
print(telf, tell)
tel[telf] = "b"
tel[tell] = "c"
print(tel)
telm1 = statistics.median_low(tel)
telm2 = statistics.median_high(tel)
print(telm1, telm2)
del tel[telm1]
del tel[telm2]
print(tel)
tel.clear()
tel[input("Podaj nazwisko: ")] = input("Podaj numer tel.: ")
tel[input("Podaj nazwisko: ")] = input("Podaj numer tel.: ")
print(tel)
|
5375af97c9022b28682ef915e1bad014247daf7b | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia7/cwiczenie7.py | 1,282 | 3.5 | 4 | import random
tab_r = []
tab_u = []
tab_w = []
print("Zaczynamy losowanie liczb...")
for i in range(0, 6):
a = random.randint(1, 49)
if a in tab_r:
a = random.randint(1, 49)
tab_r.append(a)
if a not in tab_r:
tab_r.append(a)
print("Wylosowałem")
print("Teraz wprowadź swoje liczby")
for i in range(6):
a = int(input("Wprowadź liczby (1-49): "))
if 1 <= a <= 49:
tab_u.append(a)
else:
a = int(input("Wprowadź jeszcze raz (1-49)"))
tab_u.append(a)
print("Wylosowane liczby to: ", tab_r)
print("Twoje liczby: ", tab_u)
print("Sprawdźmy ile trafiłeś...")
tab_u.sort()
tab_r.sort()
# print(tab_u)
# print(tab_r)
for i in range(0, 6):
if tab_r[i] in tab_u:
tab_w.append(tab_r[i])
i += 1
else:
continue
print("O to co trafiłeś: ", tab_w, ". Trafiłeś więc ", len(tab_w))
if len(tab_w) == 0:
print("Nic nie wygrałeś :(")
elif len(tab_w) == 1:
print("Wygrałeś 2 zł")
elif len(tab_w) == 2:
print("Wygrałeś 5 zł")
elif len(tab_w) == 3:
print("Wygrałeś 1000 zł")
elif len(tab_w) == 4:
print("Wygrałeś 20 000 zł")
elif len(tab_w) == 5:
print("Wygrałeś 500 000 zł")
elif len(tab_w) == 6:
print("Wygrałeś 1 000 000 zł!")
|
80c1d701bc33441af1a566dc9853b1b1a89de84b | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia4/cwiczenia2a.py | 141 | 3.640625 | 4 | x = float(-254)
while x >= -320:
while x % 2 != 0 and x % 5 == 0:
print(x)
x -= 1
else:
x -= 1
pass
|
a703c51fb4b25f59051085a1477c78f14144477d | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia5/polacz91011.py | 935 | 3.640625 | 4 | import random
tab = []
print("1 - Lotto")
print("2 - Multi Multi")
print("3 - Mini Lotto")
w = int(input("Wybierz które losowanie chcesz przeprowadzić: "))
if w == 1:
for j in range(0, 6):
i = random.randint(1, 49)
if i in tab:
i = random.randint(1, 49)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
elif w == 2:
for j in range(0, 20):
i = random.randint(1, 80)
if i in tab:
i = random.randint(1, 80)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
elif w == 3:
for j in range(0, 5):
i = random.randint(1, 42)
if i in tab:
i = random.randint(1, 42)
tab.append(i)
if i not in tab:
tab.append(i)
print("Wylosowane liczby to:", tab)
else:
print("Błąd.")
|
2cdb9ee58bed41b39c88a0e6995e8d8cf59e6684 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia7/cwiczenia2.py | 168 | 3.515625 | 4 | tab = []
for i in range(0, 10):
a = int(input("Podaj dowolną liczbę: "))
tab.append(a)
i += 1
print("Wybrane elementy: ", tab[1], tab[4], tab[7], tab[9]) |
1d9f8283d44840cf14f3177d10e95a282fae61d7 | BVGdragon1025/-wiczenia | /Semestr 1/Prace zaliczeniowe/Program7.py | 2,396 | 4 | 4 | import dateutil.easter
import datetime
def menu():
print("Witaj w programie!")
print("Co chcesz zrobić? ")
print("[1] Dowiedzieć się co było wczoraj i jutro ")
print("[2] Odkryć w jaki dzień się urodziłeś ")
print("[3] Dowiedzieć się kiedy Wielkanoc")
choice = input("Wybierz funkcję: ")
if choice == "1":
days()
elif choice == "2":
birthday()
elif choice == "3":
easter_day()
else:
print("Zły wybór!")
def days():
# Timedelta ustawiona jest, aby pokazywać dzień do przodu
# (lub dzień do tyłu, zależnie od działania)
# Dzisiejsza data
today = datetime.date.today()
print("Dzisiaj mamy: ", today.strftime("%d-%m-%Y"))
# Wyświetlenie wczorajszej daty
yesterday = today - datetime.timedelta(days=1)
print("Wczoraj mieliśmy: ", yesterday.strftime("%d-%m-%Y"))
# Wyświetlenie jutrzejszej daty
tommorrow = today + datetime.timedelta(days=1)
print("Jutro będzie: ", tommorrow.strftime("%d-%m-%Y"))
def birthday():
# Słownik użyty do tłumaczenia nazw angielskich (raczej logiczne)
day_dict = {"Monday": "Poniedziałek",
"Tuesday": "Wtorek",
"Wednesday": "Środa",
"Thursday": "Czwartek",
"Friday": "Piątek",
"Saturday": "Sobota",
"Sunday": "Niedziela"}
day = int(input("Podaj dzień (liczbowo): "))
month = int(input("Podaj miesiąc (liczbowo): "))
year = int(input("Podaj rok (liczbowo, pełny): "))
full_date = datetime.date(year, month, day)
dom = full_date.strftime("%A")
print("Urodziłeś się w: ", day_dict[dom])
def easter_day():
# Tak, skorzystałem z gotowej funkcji z biblioteki dateutil
# Wiem, powinienem napisać to sam
# Ale to było za dużo dla mnie, aby wykalkulować jeden dzień
# I to jeszcze taki losowy, zależny od pełni, innego święta i przesilenia
# Kto na to wpadł, ja sie pytam
# A na rozwiązanie wpadłem kiedy przeszukując Internety i widząc ten sam algorytm wszędzie
# w końcu ktoś na StackOverflow podał tę bibliotękę i stweirdziłem że to jest lepsze rozwiązanie
# Wartość 3 oznacza współczesną metodę, używaną w Polsce
year = int(input("Podaj rok: "))
print("Wielkanoc wypada w: ", dateutil.easter.easter(year, 3))
menu()
|
caddf242f33906c4946ff9491dd58336338c6072 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia.py | 412 | 3.59375 | 4 | x1 = input("Podaj 1 wartość: ")
x2 = input("Podaj 2 wartość: ")
dod = int(x1)+int(x2) # dodawanie wartosci x1 i x2
odj = int(x1)-int(x2) # odejmowanie wartości x1 i x2
mno = int(x1)*int(x2) # mnozenie wartości x1 i x2
dzi = int(x1)/int(x2) # dzielenie wartosci x1 i x2
print("Wynik dodawania: ", dod)
print("Wynik odejmowania: ", odj)
print("Wynik mnożenia: ", mno)
print("Wynik dzielenia: ", dzi)
|
046ecafc48914b85956a7badd6b8500232a57db4 | lathika12/PythonExampleProgrammes | /areaofcircle.py | 208 | 4.28125 | 4 | #Control Statements
#Program to calculate area of a circle.
import math
r=float(input('Enter radius: '))
area=math.pi*r**2
print('Area of circle = ', area)
print('Area of circle = {:0.2f}'.format(area)) |
362eb0297bbb144719be1c76dc4696c141b72017 | lathika12/PythonExampleProgrammes | /sumeven.py | 225 | 4.125 | 4 | #To find sum of even numbers
import sys
#Read CL args except the pgm name
args = sys.argv[1:]
print(args)
sum=0
#find sum of even args
for a in args:
x=int(a)
if x%2==0:
sum+=x
print("Sum of evens: " , sum) |
a1fe59470da2ee519283240483f8fa24917891b3 | lathika12/PythonExampleProgrammes | /ifelsestmt.py | 316 | 4.375 | 4 | #Program for if else statement
#to test if a number is even or odd
x=10
if x%2==0:
print("Even Number" ,x )
else:
print("Odd Number" , x )
#Program to test if a number is between 1 to 10
x=19
if x>=1 and x<=10:
print(x , " is in between 1 to 10. " )
else:
print(x , " is not in between 1 to 10. " ) |
5a44a5e2780e3c2db32b8dd8a46720fa2682655a | RohitGupta06/RohitPythonAssignments | /Module 2/Exercise II-A/math_eq_b.py | 164 | 4.03125 | 4 | # Evaluate using formula
# Initialization
x = 2
y = 5
# Evaluation
A = ((2 * x) + 6.22 * (x + y)) / (x + y)
# Displaying the result
print("The value of A is",A) |
8715a1bb07778f3099ca3d443663d0721ae908bf | RohitGupta06/RohitPythonAssignments | /Module 2/Exercise II-B/upper.py | 193 | 4.375 | 4 | # Taking the string input from user
user_input = input("Please enter your string: ")
# Changing in upper case
updated_string = user_input.upper()
print("The changed string is:",updated_string) |
57b0f6f47db94524924487b5a6780da8855141f9 | naflymim/vscode-python-pandas-work | /dataframe_ex_01.py | 388 | 3.890625 | 4 | import numpy as np
import pandas as pd
array_2d = np.random.rand(3, 3)
# print(array_2d[0, 1])
# print(array_2d[2, 0])
df = pd.DataFrame(array_2d)
print(df.columns)
print(df)
df.columns = ["First", "Second", "Third"]
print(df.columns)
print(df)
print(df["First"][0])
print(df["Second"][2])
print(df["Third"])
df["Third"].index = ['One', 'Two', 'Three']
print(df["Third"])
print(df)
|
070c621faf5ceb32087b3f9ce6bbc2e3b4b100f7 | carfri/D0009E-lab | /labb2-5a.py | 604 | 3.65625 | 4 | import math
def derivative(f, x, h):
k =(1.0/(2*h))*(f(x+h)-f(x-h))
return k
##print derivative(math.sin, math.pi, 0.0001)
##print derivative(math.cos, math.pi, 0.0001)
##print derivative(math.tan, math.pi, 0.0001)
def solve(f, x0, h):
lastX = x0
new = 0.0
while (abs(lastX) - abs(new) > h) or lastX==new:
new = lastX
lastX = lastX - f(lastX)/derivative(f, lastX, h)
return lastX
def function1(x):
return x**2-1
def function2(x):
return 2**x-1
def function3(x):
x-cmath.e**-x
print solve(function2, 4, 0.00001)
|
7d4b9473e8da1f4df6818bd37ec202a1c9644b32 | fitosegrera/simplePerceptron | /app.py | 662 | 3.546875 | 4 | from perceptron import Perceptron
inputs = [-1,-1,1]
weightNum = len(inputs)
weights = 0
learningRate = 0.01
desired = 1
iterate = True
iterCount = 0
ptron = Perceptron()
weights = ptron.setWeights(weightNum)
while iterate:
print "-"*70
print "Initial Weights: ", weights
sum = ptron.activate(weights, inputs)
print "Sum: ", sum
returned = ptron.updateWeights(learningRate, desired, sum)
print "New Weights: ", returned['newWeights']
if not returned['iterate']:
print "Iterations: ", iterCount
iterate = False
print "-"*70
else:
weights = returned['newWeights']
iterCount = iterCount + 1
|
1097ed658416acf59c22137682dc327629e02078 | DiegoC386/Taller-Estructura-de-Control-For | /Ejercicio_10.py | 627 | 3.75 | 4 | #10. El alcalde de Antananarivo contrato a algunos alumnos de la Universidad Ean
#para corregir el archivo de países.txt, ya que la capital de Madagascar NO es rey julien
#es Antananarivo, espero que el alcalde se vaya contento por su trabajo.
#Utilice un For para cambiar ese Dato
with open('paise.txt') as archivo:
lista=[]
for i in archivo:
lista.append(i)
a=" ".join(lista)
if(a=="Madagascar: rey julien\n"):
break
lista=[]
b=a.index(":")
tamaño=len(a)
lista2=[]
for i in range(0,tamaño):
lista2.append(a[i])
lista2.remove("b")
2==("Antananarivo")
lista2.insert(1,2)
print(lista2)
archivo.close() |
4562ef887b02ca21d7e322717c4b1c6f41b21543 | Anna-Joe/Python3-Learning | /exercise/testfunction/city_functions.py | 266 | 3.625 | 4 | def formatted_city_country(city,country,population=0):
if population!=0:
formatted_string=city.title()+','+country.title()+' - population '+str(population)
else:
formatted_string=city.title()+','+country.title()
return formatted_string
|
99ef2163869fda04dbe4f1c23b46e56c14af7a17 | TredonA/PalindromeChecker | /PalindromeChecker.py | 1,822 | 4.25 | 4 | from math import floor
# One definition program to check if an user-inputted word
# or phrase is a palindrome. Most of the program is fairly self-explanatory.
# First, check if the word/phrase in question only contains alphabetic
# characters. Then, based on if the word has an even or odd number of letters,
# begin comparing each letter near the beginning to the corresponding word
# near the end.
def palindromeChecker():
word = input("Please enter a word: ")
if not word.isalpha():
print("Word is invalid, exiting program.")
elif len(word) % 2 == 0:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != (len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
else:
leftIndex = 0
rightIndex = len(word) - 1
while leftIndex != floor(len(word) / 2):
if word[leftIndex] == word[rightIndex]:
leftIndex += 1
rightIndex -= 1
else:
print("\'" + word + "\' is not a palindrome.")
leftIndex = -1
break
if leftIndex != -1:
print("\'" + word + "\' is a palindrome!")
answer = input("Would you like to use this program again? Type in " +\
"\'Yes\' if you would or \'No\' if not: ")
if(answer == 'Yes'):
palindromeChecker()
elif(answer == 'No'):
print("Thank you for using my program. Have a great day!")
else:
print("Invalid input. Ending program...")
return
palindromeChecker()
|
d11e7f3d340926f13326a0ed63661d049452ac74 | dovelism/Kmeans_4_Recommendation | /Kmeans4MovieRec.py | 6,850 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@Author:Dovelism
@Date:2020/4/5 11:30
@Description: Kmeans'implement for recommendation,using Movielens
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse import csr_matrix
import helper
# Import the Movies dataset
movies = pd.read_csv('movies.csv')
#movies.head()
# Import the ratings dataset
ratings = pd.read_csv('ratings.csv')
#ratings.head()
print('The dataset contains: ', len(ratings), ' ratings of ', len(movies), ' movies.')
genre_ratings = helper.get_genre_ratings(ratings, movies, ['Romance', 'Sci-Fi'], ['avg_romance_rating', 'avg_scifi_rating'])
#genre_ratings.head()
biased_dataset = helper.bias_genre_rating_dataset(genre_ratings, 3.2, 2.5)
print( "Number of records: ", len(biased_dataset))
#biased_dataset.head()
helper.draw_scatterplot(biased_dataset['avg_scifi_rating'],
'Avg scifi rating', biased_dataset['avg_romance_rating'],
'Avg romance rating')
# turn our dataset into a list
X = biased_dataset[['avg_scifi_rating','avg_romance_rating']].values
# TODO: Import KMeans
from sklearn.cluster import KMeans
# TODO: Create an instance of KMeans to find two clusters
#kmeans_1 = KMeans(n_clusters=2)
# TODO: use fit_predict to cluster the dataset
#predictions = kmeans_1.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions)
# TODO: Create an instance of KMeans to find three clusters
#kmeans_2 = KMeans(n_clusters=3)
# TODO: use fit_predict to cluster the dataset
#predictions_2 = kmeans_2.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions_2)
# Create an instance of KMeans to find four clusters
kmeans_3 = KMeans(n_clusters =4)
# use fit_predict to cluster the dataset
predictions_3 = kmeans_3.fit_predict(X)
# Plot
#helper.draw_clusters(biased_dataset, predictions_3)
# Choose the range of k values to test.
# We added a stride of 5 to improve performance. We don't need to calculate the error for every k value
possible_k_values = range(2, len(X)+1, 5)
#print(possible_k_values)
# Calculate error values for all k values we're interested in
errors_per_k = [helper.clustering_errors(k, X) for k in possible_k_values]
# Look at the values of K vs the silhouette score of running K-means with that value of k
list(zip(possible_k_values, errors_per_k))
# Plot the each value of K vs. the silhouette score at that value
fig, ax = plt.subplots(figsize=(16, 6))
ax.set_xlabel('K - number of clusters')
ax.set_ylabel('Silhouette Score (higher is better)')
ax.plot(possible_k_values, errors_per_k)
# Ticks and grid
xticks = np.arange(min(possible_k_values), max(possible_k_values)+1, 5.0)
ax.set_xticks(xticks, minor=False)
ax.set_xticks(xticks, minor=True)
ax.xaxis.grid(True, which='both')
yticks = np.arange(round(min(errors_per_k), 2), max(errors_per_k), .05)
ax.set_yticks(yticks, minor=False)
ax.set_yticks(yticks, minor=True)
ax.yaxis.grid(True, which='both')
# Create an instance of KMeans to find seven clusters
kmeans_4 = KMeans(n_clusters=7)
# use fit_predict to cluster the dataset
predictions_4 = kmeans_4.fit_predict(X)
# plot
helper.draw_clusters(biased_dataset, predictions_4, cmap='Accent')
biased_dataset_3_genres = helper.get_genre_ratings(ratings, movies,
['Romance', 'Sci-Fi', 'Action'],
['avg_romance_rating', 'avg_scifi_rating', 'avg_action_rating'])
biased_dataset_3_genres = helper.bias_genre_rating_dataset(biased_dataset_3_genres, 3.2, 2.5).dropna()
print( "Number of records: ", len(biased_dataset_3_genres))
biased_dataset_3_genres.head()
X_with_action = biased_dataset_3_genres[['avg_scifi_rating',
'avg_romance_rating',
'avg_action_rating']].values
# TODO: Create an instance of KMeans to find seven clusters
kmeans_5 = KMeans(n_clusters=7)
# TODO: use fit_predict to cluster the dataset
predictions_5 = kmeans_5.fit_predict(X_with_action)
# plot
helper.draw_clusters_3d(biased_dataset_3_genres, predictions_5)
# Merge the two tables then pivot so we have Users X Movies dataframe
ratings_title = pd.merge(ratings, movies[['movieId', 'title']], on='movieId' )
user_movie_ratings = pd.pivot_table(ratings_title, index='userId', columns= 'title', values='rating')
print('dataset dimensions: ', user_movie_ratings.shape, '\n\nSubset example111:')
user_movie_ratings.iloc[:6, :10]
n_movies = 30
n_users = 18
most_rated_movies_users_selection = helper.sort_by_rating_density(user_movie_ratings, n_movies, n_users)
print('dataset dimensions: ', most_rated_movies_users_selection.shape)
most_rated_movies_users_selection.head()
helper.draw_movies_heatmap(most_rated_movies_users_selection)
user_movie_ratings = pd.pivot_table(ratings_title, index='userId', columns= 'title', values='rating')
most_rated_movies_1k = helper.get_most_rated_movies(user_movie_ratings, 1000)
sparse_ratings = csr_matrix(pd.SparseDataFrame(most_rated_movies_1k).to_coo())
# 20 clusters
predictions = KMeans(n_clusters=20, algorithm='full').fit_predict(sparse_ratings)
predictions.shape
type(most_rated_movies_1k.reset_index())
max_users = 70
max_movies = 50
clustered = pd.concat([most_rated_movies_1k.reset_index(), pd.DataFrame({'group':predictions})], axis=1)
helper.draw_movie_clusters(clustered, max_users, max_movies)
# Pick a cluster ID from the clusters above
cluster_number = 6
# filter to only see the region of the dataset with the most number of values
n_users = 75
n_movies = 300
cluster = clustered[clustered.group == cluster_number].drop(['index', 'group'], axis=1)
cluster = helper.sort_by_rating_density(cluster, n_movies, n_users)
print(cluster)
helper.draw_movies_heatmap(cluster, axis_labels=False)
cluster.fillna('').head()
# Pick a movie from the table above since we're looking at a subset
movie_name = "American Beauty (1999)"
cluster[movie_name].mean()
# The average rating of 20 movies as rated by the users in the cluster
cluster.mean().head(20)
# TODO: Pick a user ID from the dataset
# Look at the table above outputted by the command "cluster.fillna('').head()"
# and pick one of the user ids (the first column in the table)
user_id = 5
#print(cluster)
# Get all this user's ratings
user_2_ratings = cluster.loc[user_id, :]
# Which movies did they not rate? (We don't want to recommend movies they've already rated)
user_2_unrated_movies = user_2_ratings[user_2_ratings.isnull()]
print(user_2_unrated_movies.head())
# What are the ratings of these movies the user did not rate?
avg_ratings = pd.concat([user_2_unrated_movies, cluster.mean()], axis=1, join='inner').loc[:,0]
# Let's sort by rating so the highest rated movies are presented first
avg_ratings.sort_values(ascending=False)[:20]
|
bf9df75e6eb4ccf29ec267fbec0836f73ec99394 | pavan142/spellwise | /spellwise/algorithms/soundex.py | 4,076 | 3.59375 | 4 | from typing import List
from ..utils import sort_list
from .base import Base
class Soundex(Base):
"""The Soundex algorithm class for for identifying English words which are phonetically similar
Reference: https://nlp.stanford.edu/IR-book/html/htmledition/phonetic-correction-1.html
"""
def __init__(self) -> None:
"""The constructor for the class"""
super(Soundex, self).__init__()
def _pre_process(self, word: str) -> str:
"""Pre-processor for Soundex
Args:
word (str): The word to be pre-processed
Returns:
str: The pre-processed word
"""
word = word.lower()
word = "".join(_w for _w in word if _w in self._alphabet)
first_letter = word[0]
word = word[1:]
for _w in "aeiouhwy":
word = word.replace(_w, "0")
for _w in "bfpv":
word = word.replace(_w, "1")
for _w in "cgjkqsxz":
word = word.replace(_w, "2")
for _w in "dt":
word = word.replace(_w, "3")
word = word.replace("l", "4")
for _w in "mn":
word = word.replace(_w, "5")
word = word.replace("r", "6")
for _w in "0123456789":
while _w * 2 in word:
word = word.replace(_w * 2, _w)
word = word.replace("0", "")
word = first_letter + word + "0" * 3
word = word[0:4]
return word
def _replace(self, a: str, b: str) -> float:
"""Cost to replace the letter in query word with the target word
Args:
a (str): First letter
b (str): Second letter
Returns:
float: The cost to replace the letters
"""
if a == b:
return 0
return 1
def get_suggestions(self, query_word: str, max_distance: int = 0) -> List[dict]:
"""Get suggestions based on the edit-distance using dynamic-programming approach
Args:
query_word (str): The given query word for suggesting indexed words
max_distance (int, optional): The maximum distance between the words indexed and the query word. Defaults to 0
Returns:
List[dict]: The word suggestions with their corresponding distances
"""
processed_query_word = self._pre_process(query_word)
def search(dictionary_node, previous_row):
"""Search for the candidates in the given dictionary node's children
Args:
dictionary_node (Dictionary): The node in the Trie dictionary
previous_row (list): The previous row in the dynamic-programming approach
"""
for current_source_letter in dictionary_node.children:
current_row = [previous_row[0] + 1]
for i in range(1, len(processed_query_word) + 1):
value = min(
previous_row[i] + 1,
current_row[i - 1] + 1,
previous_row[i - 1]
+ self._replace(
current_source_letter, processed_query_word[i - 1]
),
)
current_row.append(value)
if (
current_row[-1] <= max_distance
and dictionary_node.children[current_source_letter].words_at_node
is not None
):
for word in dictionary_node.children[
current_source_letter
].words_at_node:
suggestions.append({"word": word, "distance": current_row[-1]})
if min(current_row) <= max_distance:
search(dictionary_node.children[current_source_letter], current_row)
suggestions = list()
first_row = range(0, len(processed_query_word) + 1)
search(self._dictionary, first_row)
suggestions = sort_list(suggestions, "distance")
return suggestions
|
88f082a0fed712513d2968e461b00eed445526ab | sss4920/python_list | /python_basic/lab7_5.py | 465 | 3.9375 | 4 | '''
학번과 점수를 dictionary 를 이용하여 5개 정도 정의한다
사용자로부터 학번과 점수를 입력받아 만약 기존에 해당 학번이 없으면 dictionary 에 추가한다
성적이 높은 순으로 출력하라.
'''
a={'201914009':10,'20000000':20,'100000000':30,'342ㅕ49':40,'24234':50}
s = input("학번:")
s1 = int(input("점수:"))
if s not in a:
a[s]=s1
li=sorted(a,key=a.__getitem__,reverse=True)
for x in li:
print(x)
|
8c657b49cd4e298ea17b2b5573e1f7438e49a680 | sss4920/python_list | /python_basic/lab5_10.py | 146 | 4.125 | 4 | """
람다함수를 이용하여 절대값을 출력하라.
l=[-3,2,1]
"""
L = (lambda x:-x if x<0 else x)
l=[-3,2,1]
for f in l:
print(L(f)) |
db36adc273138a78165f9e36a09d17835a172688 | sss4920/python_list | /python_basic/lab02_3.py | 179 | 3.890625 | 4 | """
문제: 원주율을 상수 PI로 정의하고 반지름을 입력받아 원의 넓이를 출력하라
"""
PI=3.141592
r=int(input('반지름: '))
print('넓이:'+str(PI*r*r)) |
6a6547bf2b47de116649d2a8f2465262114b1898 | sss4920/python_list | /python_basic/lab7_6.py | 565 | 3.78125 | 4 | '''
이름: 전화번호를 가지는 딕셔너리를 생성하여 5개의 원소로 초기화하고
이름을 입력하면 해당 전화번호를 출력하고
해당이름이 없다면 전화번호가 없습니다를 출력
마지막에 전체의 이름과 전화번호를 출력
'''
dic = {"김수현":"1111","ㅇㅇ":"2222","ㄱㄱ":"3333","ㄴㄴ":"4444","ㄷㄷ":"5555"}
name = input("이름:")
if name in dic.keys():
print("%s 전화번호는 %s"%(name,dic[name]))
else:
print("해당 전화번호가 없습니다.")
for x in dic:
print(x,dic[x])
|
92b81af21b824c8ce3bf88d939f61f697ba3994f | sss4920/python_list | /python_basic/lab4_7.py | 239 | 3.765625 | 4 | """
팩토리얼 계산과정과 값을 출력하라.
"""
a = int(input("양의 정수:"))
b = " "
sum = 1
for x in range(a,0,-1):
sum *= x
if x != 1:
b+=str(x)+"*"
else:
b+=str(x)
print("%d! ="%a,b,"= %d"%sum)
|
4f4a148d6e3745e74a0c2c4bded6f284cf54a992 | sss4920/python_list | /python_basic/lab5_8.py | 581 | 4.09375 | 4 | """
매개변수로 넘어온 리스트에서 최소값과 최대값을 반환하는 함수 min_max를 정의한다
프로그램에서
ㅣ=[3,5,-2,20,9]를 정의한 후 , min_max를 호출하여 최소값은 m1최대값은 m2에 저장하고 이를 출력하라
"""
def min_max(l):
"""
:param l: 리스트
:return: 최소값,최대값
"""
min1=l[0]
max1=l[0]
for x in l:
if min1>x:
min1=x
if max1<x:
max1=x
return min1,max1
l=[3,5,-2,20,9]
m1,m2=min_max(l)
print("최소값:%d"%m1)
print("최대값:%d"%m2)
|
66f78d22a851951ee3d7a66ade4e75d6e2dbc4e7 | sss4920/python_list | /python_basic/lab2_8.py | 250 | 3.796875 | 4 | """
사용자로부터 x좌표와 y좌표를 입력받아, 원점으로부터의 거리를 출력한다.
"""
from math import *
a = int(input("x좌표:"))
b = int(input("y좌표:"))
distance = sqrt(a*a + b*b)
print("원점까지의 거리",distance)
|
fd35e801070b1beb3e12a927293fd2ec5d16314e | sss4920/python_list | /python_basic/ㅇㅇ.py | 140 | 3.546875 | 4 | test=int(input())
for x in range(test):
a,b=input().split()
a=int(a)
temp=''
for y in b:
temp+=y*a
print(temp)
|
39929223fd0fa0624313263ef16cee26b11cbb50 | sss4920/python_list | /cruscal/1922.py | 809 | 3.6875 | 4 | import sys
input = sys.stdin.readline
def union(array,a,b):
left = find(array, a)
right = find(array, b)
if left>right:
array[left]=right
else:
array[right]=left
def find(array, a):
if a==array[a]:
return a
return find(array,array[a])
def cycle(array, a, b):
if find(array, a)==find(array, b):
return True
return False
computer = int(input())
line = int(input())
array = [] #이거는 그냥 케이스의 배열이고
family = [ i for i in range(computer+1)]
for x in range(line):
temp = list(map(int,input().split()))
array.append(temp)
array.sort(key = lambda x : x[2])
sum=0
for temp in array:
if not cycle(family, temp[0],temp[1]):
union(family,temp[0],temp[1])
sum+=temp[2]
print(sum) |
c0bbb76252f023738872456fb82bfd0e23eb3a50 | kdserSH/Training-Python-SHMCC | /OOP/OOP-CS.py | 970 | 3.984375 | 4 | #实例可以修改实例变量,不能修改类变量,程序调用时优先寻找实例变量,其次再找类变量。
class role(object): #定义类
n = 123 #类变量
def __init__(self,name,role,weapon,life_value=100,money=15000):#构造函数,init是传参数用的,用于调用方法时传参数。
self.name=name #实例变量
self.role=role
self.weapon=weapon
self.life_value=life_value
self.money=money
def get_shot(self): #类的方法、功能
print('Oh no,%s got shot'%self.name)
def shot(self):
print('%s Shooting'%self.name)
def buygun(self,gun_name):
print('%s got %s'%(self.name,gun_name))
r1=role('gsj','police','m4a')#类的实例化(aka初始化一个类)
r2=role('ddd','terroist','ak47')
r1.buygun('ak47')
r2.get_shot()
print(role.n)
r1.name='ak47'
r2.name='m4a'
r1.bulletproof=True
print(r1.bulletproof)
print(r1.n,r1.name)
print(r2.n,r2.name)
|
6e82dc8d6d525baa5c9bd4e27cadc1827cfc9d65 | ravenclaw-10/Python_basics | /lists_prog/avg_of_2lists.py | 355 | 3.90625 | 4 | '''Write a Python program to compute average of two given lists.
Original list:
[1, 1, 3, 4, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 4, 5, 7, 8]
Average of two lists:
3.823529411764706
'''
list1=[1,1,3,4,4,5,6,7]
list2=[0,1,2,3,4,4,5,7,8]
sum=0
for i in list1:
sum+=i
for i in list2:
sum+=i
avg=sum/(len(list1)+len(list2))
print(avg) |
a113879ec0112ff4c269fb2173ed845c29a3b5e5 | ravenclaw-10/Python_basics | /lists_prog/max_occur_elem.py | 708 | 4.25 | 4 | # Element with maximum occurence in a list=[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2] .
#Python program to check if the elements of a given list are unique or not.
n=int(input("Enter the no. of element in the list(size):"))
list1=[]
count=0
max=0
print("Enter the elements of the lists:")
for i in range(0,n):
elem=input()
list1.append(elem)
max_elem=list1[0]
for i in range(0,n):
count=0
for j in range(0,n):
if list1[i]==list1[j]:
count+=1
if max<=count:
max=count
max_elem=list1[i]
if max==1:
print("The given list have unique elements")
else:
print("Maximum occered element:",max_elem) |
44dd23671d3c68a9356024dcf69785c0c520033e | ravenclaw-10/Python_basics | /lists_prog/string_first_last_same.py | 409 | 3.953125 | 4 | '''Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
'''
list1=['abc','xyz','aba','1221']
list2=[]
for i in range(0,len(list1)):
if list1[i][0]==list1[i][-1]:
list2.append(list[i])
print(len(list2)) |
bea7e17c53d59d9b6f9047eeef0bb63995cc5669 | jennywei1995/sc-projects | /StanCode-Projects/break_out_game/breakoutgraphics_extension.py | 17,526 | 3.671875 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
-------------------------
File: Breakoutgraphics_extension.py
Name: Jenny Wei
-------------------------
This program creates a breakout game.
This file is the coder side, which build the important components of the game.
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
import random
# constants
BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing.
BRICK_WIDTH = 40 # Height of a brick (in pixels).
BRICK_HEIGHT = 15 # Height of a brick (in pixels).
BRICK_ROWS = 10 # Number of rows of bricks.
BRICK_COLS = 10 # Number of columns of bricks.
BRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels).
BALL_RADIUS = 10 # Radius of the ball (in pixels).
PADDLE_WIDTH = 75 # Width of the paddle (in pixels).
PADDLE_HEIGHT = 15 # Height of the paddle (in pixels).
PADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels).
INITIAL_Y_SPEED = 7.0 # Initial vertical speed for the ball.
MAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball.
class BreakoutGraphicsExtension:
"""
This class will build the components of the game.
"""
def __init__(self, ball_radius=BALL_RADIUS, paddle_width=PADDLE_WIDTH,
paddle_height=PADDLE_HEIGHT, paddle_offset=PADDLE_OFFSET,
brick_rows=BRICK_ROWS, brick_cols=BRICK_COLS,
brick_width=BRICK_WIDTH, brick_height=BRICK_HEIGHT,
brick_offset=BRICK_OFFSET, brick_spacing=BRICK_SPACING,
title="Jenny Wei's Breakout"):
# Create a graphical window, with some extra space.
self.window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing
self.window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)
self.window = GWindow(width=self.window_width, height=self.window_height, title=title)
# Create a paddle.
self.paddle = GRect(paddle_width, paddle_height, x=(self.window.width - paddle_width) / 2,
y=self.window.height - paddle_offset)
self.paddle.filled = True
self.paddle.fill_color = 'black'
self.window.add(self.paddle)
# Center a filled ball in the graphical window.
self.ball_radius = ball_radius
self.original_x = self.window.width / 2 - self.ball_radius
self.original_y = self.window.height / 2 - self.ball_radius
self.ball = GOval(2 * self.ball_radius, 2 * self.ball_radius,
x=self.original_x, y=self.original_y)
self.ball.filled = True
self.window.add(self.ball)
# Default initial velocity for the ball.
self.__dx = 0
self.__dy = 0
self.original_dx = self.__dx
self.original_dy = self.__dy
# to make sure the ball will go up when it hits the paddle
self.up_initial_y_speed = -INITIAL_Y_SPEED # to make sure the ball will go up when it hits the paddle
# Draw bricks.
for i in range(brick_rows):
for j in range(brick_cols):
self.brick_offset = brick_offset
self.brick_spacing = brick_spacing
self.brick = GRect(brick_width, brick_height, x=0 + i * (brick_width + brick_spacing),
y=self.brick_offset + j * (brick_height + brick_spacing))
self.brick.filled = True
if j // 2 == 0:
self.brick.fill_color = 'tan'
self.brick.color = 'tan'
elif j // 2 == 1:
self.brick.fill_color = 'dark_salmon'
self.brick.color = 'dark_salmon'
elif j // 2 == 2:
self.brick.fill_color = 'indian_red'
self.brick.color = 'indian_red'
elif j // 2 == 3:
self.brick.fill_color = 'slate_gray'
self.brick.color = 'slate_gray'
elif j // 2 == 4:
self.brick.fill_color = 'cadet_blue'
self.brick.color = 'cadet_blue'
self.window.add(self.brick)
self.brick_num = brick_cols * brick_rows
# Initialize our mouse listeners.
onmouseclicked(self.check_game_start)
# to draw the score label
self.score = 0
self.score_label=GLabel(f'Score:{self.score}')
self.score_label.font = '-20'
self.score_label.color = 'black'
self.window.add(self.score_label,x=10, y=self.window.height-10)
# to draw the life label
self.life_label = GLabel(f'Life: ')
self.life_label.font = '-20'
self.life_label.color = 'black'
self.window.add(self.life_label, x=self.window.width-self.life_label.width-20, y=self.window.height - 10)
# to draw the start label
self.start_label = GLabel('Please click the mouse to start!')
self.start_label.font = '-20'
self.start_label.color = 'black'
self.window.add(self.start_label,x=self.window.width / 2 - self.start_label.width / 2,
y=self.window.height / 2 - self.start_label.height / 2 -20)
# to draw the win label
self.win_label=GLabel(f'You win! You got: {self.score}')
self.win_label.font = '-20'
self.win_label.color = 'black'
# to draw the lose label
self.lose_label = GLabel(f'Game over! You got: {self.score}')
self.lose_label.font = '-20'
self.lose_label.color = 'black'
def paddle_move(self, mouse):
"""
The paddle will move while the user move the mouse.
The user's mouse will be at the middle of the paddle
"""
self.paddle.x = mouse.x - self.paddle.width / 2
if self.paddle.x+self.paddle.width>self.window.width:
self.paddle.x = self.window.width - self.paddle.width
if self.paddle.x <= 0:
self.paddle.x = 0
def check_game_start(self, mouse):
"""
once the user click the mouse, the game will start that the function
will give the ball velocity to move.
once the ball is out of the window, the user have to click the mouse again
to drop the ball.
"""
if self.ball.x == self.original_x and self.ball.y == self.original_y:
onmousemoved(self.paddle_move)
self.window.remove(self.start_label)
# give the ball velocity
if self.__dx == 0:
self.__dy = INITIAL_Y_SPEED
self.__dx = random.randint(1, MAX_X_SPEED)
if random.random() > 0.5:
self.__dx = -self.__dx
print(f'{self.__dy}')
def bounce_back(self):
"""
once the ball bump into the wall,
it will bounce back.
"""
if self.ball.x <= 0 or self.ball.x + self.ball.width >= self.window.width:
self.__dx = -self.__dx
if self.ball.y <= 0:
self.__dy = -self.__dy
def check_paddle(self):
"""
To check whether the ball bump into any object, including the brick and the paddle.
If the ball hit the brick, the brick will be cleared,
and it will bounce back if it doesn't hit anything anymore.
once the ball hit the paddle, the ball will bounce back.
"""
left_up = self.window.get_object_at(self.ball.x, self.ball.y)
right_up = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y)
left_down = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height)
right_down = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height)
# when ball hits the paddle
if left_up is self.paddle or right_up is self.paddle:
pass
elif left_down is self.paddle and right_down is None:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle and left_down is self.paddle:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle and left_down is None:
self.__dy = self.up_initial_y_speed
if self.ball.y + self.__dy >= self.paddle.y:
if self.ball.y + self.__dy <= self.paddle.y+self.paddle.height:
if left_down is self.paddle:
self.__dy = self.up_initial_y_speed
elif right_down is self.paddle:
self.__dy = self.up_initial_y_speed
# to make the ball faster while the user reach certain scores
if self.score >= 150:
if self.__dy < 0:
self.__dy = -9
elif self.__dy > 0:
self.__dy = 9
if self.score >= 600:
if self.__dy < 0:
self.__dy = -10.5
elif self.__dy > 0:
self.__dy = 10.5
def check_brick(self):
"""
To check whether the ball hits the brick.
If the ball hit the brick, the brick will be cleared,
and it will bounce back if it doesn't hit things anymore.
"""
left_up = self.window.get_object_at(self.ball.x, self.ball.y)
right_up = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y)
left_down = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height)
right_down = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height)
# if the ball's left_up corner hit the brick
if left_up is not None:
if left_up is not self.score_label:
if left_up is not self.life_label and left_up is not self.paddle:
if left_up is not self.paddle:
self.window.remove(left_up)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if left_up.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif left_up.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif left_up.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif left_up.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if left_up.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's right_up corner hit the brick
elif right_up is not None:
if right_up is not self.score_label:
if right_up is not self.life_label:
if right_up is not self.paddle:
self.window.remove(right_up)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if right_up.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif right_up.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif right_up.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif right_up.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if right_up.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's left_down corner hit the brick
elif left_down is not None:
if left_down is not self.score_label:
if left_down is not self.life_label:
if left_down is not self.paddle:
self.window.remove(left_down)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if left_down.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif left_down.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif left_down.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif left_down.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if left_down.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
# if the ball's right_down corner hit the brick
elif right_down is not None:
if right_down is not self.score_label:
if right_down is not self.life_label:
if right_down is not self.paddle:
self.window.remove(right_down)
self.__dy = -self.__dy
self.brick_num -= 1
# when the ball hits different color's brick, it will get different scores
if right_down.y >= self.brick_offset + 8 * (self.brick.height + self.brick_spacing):
self.score += 5
elif right_down.y >= self.brick_offset + 6 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 7 * (self.brick.height + self.brick_spacing):
self.score += 10
elif right_down.y >= self.brick_offset + 4 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 5 * (self.brick.height + self.brick_spacing):
self.score += 15
elif right_down.y >= self.brick_offset + 2 * (self.brick.height + self.brick_spacing):
if right_down.y <= self.brick_offset + 3 * (self.brick.height + self.brick_spacing):
self.score += 20
else:
self.score += 25
self.score_label.text = 'Score: ' + str(self.score)
self.win_label.text = 'You win! You got: ' + str(self.score)
self.lose_label.text = 'Game over! You got: ' + str(self.score)
def get_dx(self):
"""
to return the value of the dx to the user side
"""
return self.__dx
def get_dy(self):
"""
to return the value of the dy to the user side
"""
return self.__dy
def re_set_ball(self):
"""
once the ball is out of the window, its position will be reset.
It's velocity will be set to 0 again. And the user will have to
click the mouse to continue the game.
"""
self.__dy = 0
self.__dx = 0
self.ball.x = self.original_x
self.ball.y = self.original_y
onmouseclicked(self.check_game_start)
|
7e3d68562bfb27ebe0dec9fd95a2a1e8b488ad60 | LevinWeinstein/attendance_formatter | /attendance.py | 4,733 | 3.625 | 4 | #! /usr/bin/env python3
"""
Filename : attendance.py
Author : Levin Weinstein
Organization : USF CS212 Spring 2021
Purpose : Convert a directory full of attendance lists to a single, aggregated attendance sheet
Usage : ./attendance.py --directory="DIRECTORY" --event=[lecture|lab] > ${OUTPUT_FILE}
"""
import os
import sys
import argparse
class Attendee:
""" A class for an individual Attendee, with a name and an email"""
def __init__(self, name, email):
""" constructor for the Attendee class
:param name: the name of the attendee
:param email: the email of the attendee
"""
self.name = name
self.email = email
def __eq__(self, other):
""" Equals operator for the Attendee class
We're just using email to determine equivalency for the sake of simplicity.
:param other: the other Attendee to which to compare
"""
return self.email == other.email
def __hash__(self):
""" Hash code """
return hash(self.email)
def __str__(self):
""" convert an Attendee to string """
return self.name + ',' + self.email
class Attendance:
""" A class to take the attendance.
Contains methods to:
- add an attendee
- add a whole file
- add a whole directory of files
- a getter for an unmodifiable set of the attendees
- merge another Attendance set
"""
def __init__(self, event_type=""):
""" An initializer for the Attendance """
self._attendees = set()
self.event_type = event_type
def add_attendee(self, line):
""" Method to add an attendee
:param line: the line from which to parse and add an attendee
"""
fields = line.split(',')
if len(fields) == 4:
name, email, _, _ = fields
else:
name, email, _ = fields
new_attendee = Attendee(name, email)
self._attendees.add(new_attendee)
def add_file(self, filename):
""" Method to add all attendees from a file
:param filename: the name of the file
"""
local_attendance = Attendance(self.event_type)
try:
with open(filename) as f:
# Skip the lines above the whitespace, since they are not names
next(f) # skip the top part header line
_, topic, _, _, _, _, _, _ = next(f).split(',')
print(topic, file=sys.stderr)
if self.event_type == "lab" and "code review" in topic.lower():
pass
elif self.event_type not in topic.lower():
print(f"Wrong event type. Skipping {filename}", file=sys.stderr)
return
next(f) # Skip the blank line
next(f) # Skip the header line with the title "Name", "Email", etc
for line in f:
local_attendance.add_attendee(line)
self.merge(local_attendance)
except Exception as e:
print(f"Error parsing file: {filename}: {e}", file=sys.stderr)
def add_all_files(self, root_directory):
"""Adds all files from the given directory
:param root_directory: the directory within which to search for attendance files
"""
for (root, dirs, files) in os.walk(root_directory):
for f in files:
self.add_file(os.path.join(root, f))
def attendees(self):
"""A getter for the _attendees set
:return: an immutable frozenset with the contents of the _attendees set
"""
return frozenset(self._attendees)
def merge(self, other):
"""Merge another Attendance sheet into this one
:param other: the other Attendance sheet with which to merge
"""
self._attendees |= other.attendees()
def __str__(self):
""" convert the Attendance to string """
attendees = sorted(self._attendees, key=lambda person: person.email)
return "\n".join([str(person) for person in attendees])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Convert a directory full of attendance lists to a single, aggregated attendance sheet")
parser.add_argument("-e", "--event", help="The event type. Can be either lecture or lab", required=True)
parser.add_argument("-d", "--directory", help="The directory within which to parse.", required=True)
arguments = parser.parse_args()
attendance = Attendance(arguments.event)
attendance.add_all_files(arguments.directory)
print(attendance)
|
6094c69f6d4fa7a0bb59fc8da0eb7fb379832514 | Boukos/AlgorithmPractice | /recursion/rec_len.py | 328 | 4.1875 | 4 | def rec_len(L):
"""(nested list) -> int
Return the total number of non-list elements within nested list L.
For example, rec_len([1,'two',[[],[[3]]]]) == 3
"""
if not L:
return 0
elif isinstance(L[0],list):
return rec_len(L[0]) + rec_len(L[1:])
else:
return 1 + rec_len(L[1:])
print rec_len([1,'two',[[],[[3]]]]) |
609f6c607a6f8d3f363cd4c983c9c552fc58a6b1 | NIKHILDUGAR/codewars4kyuSolutions | /Snail.py | 352 | 3.59375 | 4 | # https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
def snail(array):
res = []
while len(array) > 1:
res = res + array.pop(0)
res = res + [row.pop(-1) for row in array]
res = res + list(reversed(array.pop(-1)))
res = res + [row.pop(0) for row in array[::-1]]
return res if not array else res + array[0]
|
7788a1f6524ed2aff9aa7b3368ff41b13418a4c4 | Uvernes/DSRI_2021 | /utility/nearest_rotation_matrix.py | 1,761 | 3.515625 | 4 | import numpy as np
import math
import sys
"""
Input
-----
R - 3 by 3 matrix we want to find nearest rotation matrix for
Output
------
Nearest rotation matrix
"""
def exact_nearest_rotation_matrix(R):
A = np.dot(R.transpose(), R)
m = np.trace(A) / 3
Q = A - m * np.identity(3)
q = np.linalg.det(Q) / 2
p = np.sum(np.power(Q, 2)) / 6
sp = math.sqrt(p)
theta = math.atan2(math.sqrt(abs(p**3 - q**2)), q) / 3
ctheta = math.cos(theta)
stheta = math.sin(theta)
l1 = abs(m + 2*sp*ctheta)
l2 = abs(m - sp*(ctheta+math.sqrt(3)*stheta))
l3 = abs(m - sp*(ctheta-math.sqrt(3)*stheta))
a0 = math.sqrt(l1*l2*l3)
a1 = math.sqrt(l1*l2)+math.sqrt(l1*l3)+math.sqrt(l3*l2)
a2 = math.sqrt(l1)+math.sqrt(l2)+math.sqrt(l3)
dem = a0*(a2*a1-a0)
b0 = (a2*(a1**2) - a0 * ((a2**2) + a1))/dem
b1 = (a0+a2*((a2**2) - 2*a1))/dem
b2 = a2/dem
U = np.dot(np.dot(b2, A), A) - np.dot(b1, A) + np.dot(b0, np.eye(3))
return np.dot(R, U)
# --------------- Testing -----------------------#
# tMatrix = np.array([[0.74359, -0.66199, 0.08425],
# [0.21169, 0.35517, 0.91015],
# [-0.63251, -0.65879, 0.40446]])
#
# closest = exact_nearest_rotation_matrix(tMatrix)
# print("Matrix: ")
# print(tMatrix)
# print("Nearest rotation matrix: ")
# print(closest)
# # Matrix multiplication below is eye(3), as expected
# print("Matrix multiplication:")
# np.savetxt(sys.stdout, np.dot(closest, closest.transpose()), '%.5f')
# print("---------------")
# matrix = np.array([[1, 2, 3], [4, 5, 6]])
# print(matrix)
# print(np.sum(matrix))
# print(np.power(matrix, 2))
# print(np.sum(np.power(matrix, 2)))
|
cb227b2f3eb1500e66e84c4461846205e4c4ab63 | eyeCube/Softly-Into-the-Night-OLD | /levels.py | 3,835 | 3.578125 | 4 | '''
levels.py
level design algorithms
'''
import libtcodpy as libtcod
import random
from const import *
import tilemap
# generate
# main procedural level generator
# Parameters:
# Map : TileMap object (pointer)
# level : current dungeon level that we're creating
# nRooms : maximum number of "rooms" to generate on this floor
def generate(Map, level, nRooms=50):
if level == 0:
# create base
Map.cellular_automata(
FUNGUS,FLOOR,8, (-1, -1,-1,-1,0, 1,1,1,1,), simultaneous=True )
# create rooms
elif level == 1:
#unfinished code...
floor = tilemap.TileMap(ROOMW,ROOMH)
hyper = tilemap.TileMap(ROOMW,ROOMH)
for rr in range(nRooms):
build_random_room(hyper)
#try to put this room on the floor
# algorithm assumes a blank TileMap object is passed in
def build_random_room(Map):
#pick a type of room to place on the map
choices = ("cave","box","cross","circle","cavern",)
roomType = random.choice(choices)
if roomType == "cave": #small cave-like room
drunkardWalk(Map, 3, 10, 0.5, (1,1,1,1,1,1,1,1,))
elif roomType == "box": #rectangle
pass
elif roomType == "cross": #two rectangles overlaid
pass
elif roomType == "circle":
pass
elif roomType == "cavern": #large cave
pass
print("New room created of type {}".format(roomType))
#
# drunken walk algorithm
# Parameters:
# walks number of walks to go on
# length length of each walk
# bounciness tendency to remain around origin rather than branch out
# weights iterable w/ directional weights in 8 directions
# - index 0 is 0 degrees, 1 is 45 deg, etc.
def drunkardWalk(Map, walks, length, bounciness, weights):
xp = 15
yp = 15
for i in range(10): # clearing where you start
for j in range(10):
self.tile_change(xp-5+i,yp-5+j,T_FLOOR)
self.tile_change(xp,yp,T_FLOOR)
for i in range(6000):
xp+=int(random.random()*3)-1
yp+=int(random.random()*3)-1
xp=maths.restrict(xp, 0,w-1)
yp=maths.restrict(yp, 0,h-1)
self.tile_change(xp,yp,T_FLOOR)
for x in range(1,4):
for y in range(1,2):
xx=maths.restrict(x+xp-1, 0,w-1)
yy=maths.restrict(y+yp-1, 0,h-1)
self.tile_change(xx,yy,T_FLOOR)
self.tile_change(xp,yp,T_STAIRDOWN)
#
#UNFINISHED...
# file == .lvl file to load from when creating the cells
'''def make_celledRoom(cols,rows,Map,file):
# read from the file
if file[:-4] != ".lvl":
print("ERROR: File '{}' wrong file type (must be '.lvl'). Aborting...".format(file))
raise
mode=0
try:
with open(file, "r") as f:
numCells = f.readline().strip()
cellw = f.readline().strip()
cellh = f.readline().strip()
cy=0
for line in f:
if mode==0:
if line.strip().lower() == "center":
mode=1 #begin reading in the cell data
elif mode==1:
cx=0
for char in line.strip():
if char=='#':
Map.tile_change(cx,cy,)
cx+=1
cy+=1
#
except FileNotFoundError:
print("ERROR: File '{}' not found. Aborting...".format(file))
raise
'''
'''# for each cell in the room
for cc in range(cols):
for rr in range(rows):
# for each tile in each cell
for xx in range(cellw):
for yy in range(cellh):
Map.tile_change(x,y,T_FLOOR)'''
#make_celledRoom(16,12,5,5,)
|
15f68fe0b019bb466d2d7bcfbd83c6baabf2efc4 | eyeCube/Softly-Into-the-Night-OLD | /searchFiles.py | 925 | 4.125 | 4 | #search a directory's files looking for a particular string
import os
#get str and directory
print('''Welcome. This script allows you to search a directory's
readable files for a particular string.''')
while(True):
print("Current directory:\n\n", os.path.dirname(__file__), sep="")
searchdir=input("\nEnter directory to search in.\n>>")
find=input("Enter string to search for.\n>>")
#search each (readable) file in directory for string
for filename in os.listdir(searchdir):
try:
with open( os.path.join(searchdir,filename)) as file:
lineNum = 1
for line in file.readlines():
if find in line:
print(filename, "| Line", lineNum)
lineNum +=1
except Exception as err:
pass
print("End of report.\n------------------------------------------")
|
9b1bc8b4678f0961b00ed39cb8f3f62a1cbab015 | sahilchutani91/facial_keypoints | /models.py | 4,312 | 3.59375 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
# input WXH 96X96, after convolution (96-4)/1 + 1 = 93X93; pooling -> 46X46
# input WXH 46X46, after convolution (46-3)/1 + 1 = 44X44; pooling -> 22X22
# input WXH 22X22, after convolution (22-2)/1 + 1 = 21X21; pooling -> 10X10
# input WXH 10X10, after convolution (10-1)/1 + 1 = 10X10; pooling -> 5X5
# input WXH 224X224, after convolution (224 - 4)/1 + 1; pooling -> 110x110
# input WXH 110X110, after convolution (110 - 3)/1 + 1; pooling -> 54x54
# input WXH 224X224, after convolution (54 - 2)/1 + 1; pooling -> 26x26
# input WXH 224X224, after convolution (26 - 1)/1 + 1; pooling -> 13x13
# Convlution layers
self.conv1 = nn.Conv2d(1, 32, 4)
self.conv2 = nn.Conv2d(32, 64, 3)
self.conv3 = nn.Conv2d(64, 128, 2)
self.conv4 = nn.Conv2d(128, 256, 1)
# Maxpool
self.pool = nn.MaxPool2d(2,2)
# fully connected layers
self.fc1 = nn.Linear(256*13*13,1000 )
self.fc2 = nn.Linear(1000, 1000)
self.fc3 = nn.Linear(1000, 136)
# dropouts
self.drop1 = nn.Dropout(p=0.1)
self.drop2 = nn.Dropout(p=0.2)
self.drop3 = nn.Dropout(p=0.3)
self.drop4 = nn.Dropout(p=0.4)
self.drop5 = nn.Dropout(p=0.5)
self.drop6 = nn.Dropout(p=0.6)
# initializing weights
# initialize convolutional layers to random weight from uniform distribution
for conv in [self.conv1, self.conv2, self.conv3, self.conv4]:
I.uniform_(conv.weight)
# initialize fully connected layers weight using Glorot uniform initialization
for fc in [self.fc1, self.fc2, self.fc3]:
I.xavier_uniform_(fc.weight, gain=I.calculate_gain('relu'))
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
# normalize
self.norm = nn.BatchNorm1d(136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## Full Network
## Input -> conv1 -> Activation1 -> pool -> drop1 -> conv2 -> Activation2 -> pool -> drop2
## -> conv3 -> Activation3 -> pool -> drop3 -> conv4 -> Activation4 -> pool -> drop4 ->
## flatten -> fc1 -> Activation5 -> drop5 -> fc2 -> Activation6 -> drop6 -> fc3
## Activation1 to Activation5 are Exponential Linear Units
## Activation6 is Linear Activation Function
x = self.pool(F.elu(self.conv1(x)))
x = self.drop1(x)
x = self.pool(F.elu(self.conv2(x)))
x = self.drop2(x)
x = self.pool(F.elu(self.conv3(x)))
x = self.drop3(x)
x = self.pool(F.elu(self.conv4(x)))
x = self.drop4(x)
x = x.view(x.size()[0], -1)
x = F.elu(self.fc1(x))
x = self.drop5(x)
x = F.relu(self.fc2(x))
x = self.drop6(x)
x = self.fc3(x)
x = self.norm(x)
return x
|
00573e96c1c60760e541eb3c56859594e59eecc9 | ministry78/pythonStudy | /HeadFirstPython/test.py | 785 | 3.71875 | 4 | # -*- coding: UTF-8 -*-
__author__ = 'drudy'
import random
secret = random.randint(1,100)
guess = 0
tries = 0
print "你好,我是电脑机器人,接下来我们开始一个猜数字的游戏!"
print "游戏规则是:我会随机给1至100的数字,你来猜我给的数字,猜对了有奖品哦!机会只有6次哦!"
while guess != secret and tries < 6:
guess = input("你猜的数字是多少,请输出来?")
if guess < secret:
print "小了哦!还有机会哦"
elif guess > secret:
print "大了哦!还有机会哦"
# tries = tries + 1
if guess == secret:
print "真棒,你猜对了,快去领奖吧!"
else:
print "真抱歉,机会已经用完了哦,祝你下次好运!"
print "真实的数字是", secret
|
551d3fc22b4c95da30104a073383c1e463bd7f5a | mnjey/RSA | /seventh_frame_wordlist_attack.py | 1,667 | 3.609375 | 4 | #By now,we have found that the structure of plaintext frame.
#In this program,we give the prefix of the fourth plaintext frame.And we already have get the sixth plaintext frame which ends with "." and the eighth plaintext frame is " "Logic",we just construct a wordlist of the words which looks meaningful.
import os
import os.path
import sys
import copy
import binascii
import math
os.chdir("./fujian2")
list_dir=os.listdir('.')
frame_list=[]
E_attemp=3
plain_pre="9876543210abcdef000000060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
#The seventh plaintext frame starts with the string,plain_pre.
potential_ending=[' It says',' It said',' That is',' He says',' He said'] #This is our wordlist.The seventh plaintext frame probably ends with these words with length 8.
for frame_file in list_dir:
with open(frame_file) as fd:
code_str=fd.readline()
N=int(code_str[0:256],16) #extract N in the frame
e=int(code_str[256:512],16) #extract e in the frame
c=code_str[512:768].lower() #extract c in the frame
frame_list.append((frame_file,e,N,c))
for item_0 in frame_list: #We just try all the items in the wordlist to see which is the plaintext message.
for item in potential_ending:
plain_num=int(plain_pre+binascii.b2a_hex(item),16)
if(item_0[3].lstrip('0') in hex(pow(plain_num,item_0[1],item_0[2]))):
print "Decoding "+item_0[0]+"......"
print "The plaintext message is "+item
|
dc58c81a1ae7e98ab3f20f62ff3067b576e0f4f9 | sasuketttiit/Hacker-Rank | /hurdle_race.py | 138 | 3.53125 | 4 | def hurdleRace(k, height):
potion = 0
max_jump = max(height)
if k < max_jump:
potion = max_jump - k
return potion
|
bfa76a889d6e60cc8e1cbd408f90217e07da3284 | NagarajuSaripally/PythonCourse | /Methods/nestedStatementsAndScope.py | 727 | 3.75 | 4 | '''
Scope is LEGB rule:
Local: Names assigmned in any way with in a function
E: Enclosing function locals : Names in the local scope of any and all enclosing function
Global : Names assigned at the tope-level of a module file or declared ina def with in the file:
B : Built-in - Names preassigned in the built in names module: open, range, syntax error
'''
name = 'This is a global String'
def greet():
name = "Sammy"
def hello():
print("hello " + name)
hello()
greet()
print(name)
'''
if we use global keyword, if we change any local scope that impacts the global scope:
'''
x = 50
def func():
global x
print(f'X is {x}')
x = 200
print(f'Hey I am locally changed {x}')
func()
print(f'Global X is {x}') |
8774264a6b3b9972dcda87929f0943e96d3906e6 | NagarajuSaripally/PythonCourse | /ObjectAndDataStructureTypes/someFunMethods.py | 8,191 | 4.21875 | 4 | """
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True
"""
def sleep_in(weekday, vacation):
if not weekday or vacation:
return True
else:
return False
"""
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
monkey_trouble(True, True) → True
monkey_trouble(False, False) → True
monkey_trouble(True, False) → False
"""
def monkey_trouble(a_smile, b_smile):
if (a_smile and b_smile) or (not a_smile and not b_smile):
return True
return False
"""
Given two int values, return their sum. Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
"""
def sum_double(a, b):
if a == b:
return (a + b) * 2
else:
return a + b
"""
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
"""
def diff21(n):
subtractedValue = abs(n - 21)
if n > 21:
return 2 * subtractedValue
return subtractedValue
"""
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.
parrot_trouble(True, 6) → True
parrot_trouble(True, 7) → False
parrot_trouble(False, 6) → False
"""
def parrot_trouble(talking, hour):
if talking and ( hour < 7 or hour > 20):
return True
else:
return False
"""
Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.
makes10(9, 10) → True
makes10(9, 9) → False
makes10(1, 9) → True
"""
def makes10(a, b):
if a == 10 or b == 10 or a + b == 10:
return True
else:
return False
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) → True
near_hundred(90) → True
near_hundred(89) → False
"""
def near_hundred(n):
if n in range(90, 111) or n in range(190, 211):
return True
else:
return False
"""
Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.
pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True
"""
def pos_neg(a, b, negative):
if negative:
return (a < 0 and b < 0)
else:
return (a < 0 and b > 0) or (a > 0 and b < 0)
"""
Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged.
not_string('candy') → 'not candy'
not_string('x') → 'not x'
not_string('not bad') → 'not bad'
"""
def not_string(str):
if len(str) >= 3 and str[0] == 'n' and str[1] == 'o' and str[2] == 't':
return str
else:
return 'not ' + str
"""
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).
missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'
"""
def missing_char(str, n):
myString = ''
for index, character in enumerate(str):
if index != n:
myString += character
return myString
"""
Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'
"""
def front_back(str):
if len(str) <= 1:
return str
else:
first = str[-1]
last = str[0]
return first + str[1:len(str)-1] + last
"""
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.
front3('Java') → 'JavJavJav'
front3('Chocolate') → 'ChoChoCho'
front3('abc') → 'abcabcabc'
"""
def front3(str):
if len(str) < 3:
return '' + (str * 3)
else:
return '' + (str[:3] * 3)
"""
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'
"""
def string_times(str, n):
return ''+ str * n
"""
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;
front_times('Chocolate', 2) → 'ChoCho'
front_times('Chocolate', 3) → 'ChoChoCho'
front_times('Abc', 3) → 'AbcAbcAbc'
"""
def front_times(str, n):
if len(str) >= 3:
myString = str[0:3]
return '' + myString * n
else:
return '' + str * n
"""
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
string_bits('Hello') → 'Hlo'
string_bits('Hi') → 'H'
string_bits('Heeololeo') → 'Hello'
"""
def string_bits(str):
return str[::2]
"""
Given a non-empty string like "Code" return a string like "CCoCodCode".
string_splosion('Code') → 'CCoCodCode'
string_splosion('abc') → 'aababc'
string_splosion('ab') → 'aab'
"""
def string_splosion(str):
count = 0
resultString = ""
while count < len(str):
for index, character in enumerate(str):
if(count >= index):
resultString += character
count += 1
return resultString
"""
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') → 1
last2('xaxxaxaxx') → 1
last2('axxxaaxx') → 2
"""
def last2(str):
# Screen out too-short string case.
if len(str) < 2:
return 0
# last 2 chars, can be written as str[-2:]
last2 = str[len(str)-2:]
count = 0
# Check each substring length 2 starting at i
for i in range(len(str)-2):
sub = str[i:i+2]
if sub == last2:
count = count + 1
return count
"""
Given an array of ints, return the number of 9's in the array.
array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3
"""
def array_count9(nums):
count = 0
for num in nums:
if num == 9:
count += 1
return count
"""
Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.
array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False
"""
def array_front9(nums):
return (9 in nums[0:4])
"""
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
"""
def array123(nums):
if len(nums) >= 3:
for ind, lst in enumerate(nums):
if(ind+2) <= len(nums)-1:
if nums[ind] == 1 and nums[ind+1] == 2 and nums[ind+2] ==3:
return True
return False
"""
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0
"""
def string_match(a, b):
count = 0
for ind, character in enumerate(a):
for i, char in enumerate(b):
if (a[ind:ind+2] == b[i:i+2]) and (len(a[ind:ind+2]) > 1) and (len(b[i:i+2])>1) and (ind == i):
count += 1
return count |
8097283ba70a2e1ee33c31217e4b9170a45f2dd1 | NagarajuSaripally/PythonCourse | /StatementsAndLoops/loops.py | 2,014 | 4.75 | 5 | '''
Loops: iterate through the dataypes that are iterable, iterable datatypes in python or in any language
string, lists, tuples, dictionaries
keywords to iterate through these iterables:
#for
syntax
for list_item in list_items:
print(list_item)
'''
# lists:
my_list_items = [1,2,3,4,5,6]
for my_list_item in my_list_items:
print(my_list_item)
# strings
mystring = 'Hello World!'
for eachChar in mystring:
print(eachChar)
#without assigning varibles
for variable in 'Good Morning':
print(variable)
# here instead of each character, we can print what ever the string that we want many times as string length
# so instead of putting a variable name we can use _ there
for _ in 'Hello World!':
print('cool!')
# tuples:
tup = (1,2,3)
for eachTup in tup:
print(eachTup)
# Tuple unpacking, sequence contain another tuples itself then for will upack them
my_tuples = [(1,2),(3,4),(5,6),(7,8),(9,0)]
print("length of my_tuples: {}".format(len(my_tuples)))
for item in my_tuples:
print(item)
# this is called tuple unpacking. techincally we don't need paranthesis like (a,b) it can be just like a,b
for (a,b) in my_tuples:
print(a)
print(b)
#dictionaries:
d = {'k1': 1, 'K2': 2, 'K3': 3}
for item in d:
print(item)
for value in d.values():
print(value)
'''
While loop, it continues to iterate till the condition satisfy
syntax:
while conition:
# do something
while condition:
# do something:
else:
# do something else:
'''
x = 0
while x < 5:
print(f'The current value of x is {x}')
x += 1
while x < 10:
print(f'The current value of x is {x}')
x += 1
else:
print('X is not should not greater than 10')
'''
useful keywords in loops
break, continue, pass
pass: do nothing at all
'''
p = [1,2,3]
for item in p:
#comment
pass # it just passes, in pythong for loops we need at least on statement in loop
print("Passed");
letter = 'something here'
for let in letter:
if let == 'e':
continue
print(let)
for let in letter:
if let == 'e':
break
print(let) |
30cf7566ca858b10b86bf6ffc72826de02134db2 | NagarajuSaripally/PythonCourse | /Methods/lambdaExpressionFiltersandMaps.py | 1,141 | 4.5 | 4 | '''
Lambda expressions are quick way of creating the anonymous functions:
'''
#function without lamda expression:
def square(num):
return num ** 2
print(square(5))
#converting it into lambda expression:
lambda num : num ** 2
#if we want we can assign this to variable like
square2 = lambda num : num ** 2. # we are not going to use this very often, cause lamda function are anonymous
print(square2(5))
print(list(map(lambda num : num **2, [1,2,3,4])))
'''
Map: map() --> map(func, *iterables) --> map object
'''
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
#if I wanna get sqaure for all the list items, we can use map function, instead of for loop, for loop is costly
#Method 1:
for item in map(square, my_nums):
print(item)
#method 2:
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'''
Filter: iterate function that returns either true or false
'''
def check_even(num):
return num % 2 == 0
my_numbers = [1,2,3,4,5,6]
print(list(filter(check_even, my_numbers))) |
06d57c0fd60d591256825eb4992e2eded1d6b70a | GabrieLima-dev/udacity_exercises | /teste.py | 190 | 3.625 | 4 | idade_inteiro = int(input())
idade = idade_inteiro
if idade < 12:
print('crianca')
elif idade < 18:
print('Adolecente')
elif idade < 60:
print('Adulto')
else:
print('Idoso')
|
3f947479dbb78664c2f12fc93b926e26d16d2c34 | ankurkhetan2015/CS50-IntroToCS | /Week6/Python/mario.py | 832 | 4.15625 | 4 | from cs50 import get_int
def main():
while True:
print("Enter a positive number between 1 and 8 only.")
height = get_int("Height: ")
# checks for correct input condition
if height >= 1 and height <= 8:
break
# call the function to implement the pyramid structure
pyramid(height)
def pyramid(n):
for i in range(n):
# the loop that controls the blank spaces
for j in range(n - 1 - i):
print(" ", end="")
# the loop that controls and prints the bricks
for k in range(i + 1):
print("#", end="")
print(" ", end="")
for l in range(i + 1):
# the loop that control the second provided pyramid
print("#", end="")
# goes to the next pyramid level
print()
main()
|
27dc314ba44397a66b2f0916dc25df92d1d8535b | Zeriuno/adventofcode | /2016/d4.py | 1,381 | 3.515625 | 4 | def get_ID_tot(param):
"""
Opens the param file, looks for the real rooms and returns the sum of their sector IDs
"""
tot_ID = 0
list = open(param, "r")
for r in list:
r = Room(r)
if (r.is_real):
tot_ID += room.ID
return tot_ID
class Room:
"""
Room object.
"""
def __init__(self):
"""
Creation of a Room.
room1 = Room(aaaaa-bbb-z-y-x-123[abxyz])
self.checksum contains only the checksum, without the brackets: "abxyz"
self.ID contains only the ID number: 123
self.string contains only the letters of the room, without dashes: "aaaaabbbzyx"
self.is_real is set to True if the name follows the rules of a real room
"""
self.checksum = self.split('[')[-1][:-1]
self.ID = int(self.split('-')[-1].split('[')[0])
self.string = ''
for bit in self.split('-')[:-1]:
self.string += bit
occurrencesletters = []
occurrences = []
for letter in self.string:
if(letter in occurrencesletters):
occurrences[occurrencesletters.index(letter)] += 1
else:
occurrencesletters.append(letter)
occurrences.append(1)
# now occurrences is an unordered list of the occurrences
self.occurrences = collection.Counter(self.string)
if():
self.is_real = True
else:
self.is_real = False
2.b Order the ties alphabetically
3. Check the 5 most frequent letters appear in alphabetical order: self.is_real
1. Take a room name.
|
e10a267a92be6ae4eb564140f7fc1d9fdd80b53e | Everton42/video-youtube-rsa | /criptografia-cifra-de-cesar/criptografia.py | 391 | 3.578125 | 4 | def cripto_cesar(texto,p):
cifra = ''
for i in range(len(texto)):
char = texto[i]
if(char.isupper()):
cifra += chr((ord(char) + p - 65) % 26 + 65)
else:
cifra += chr((ord(char) + p - 97) % 26 + 97)
return cifra
texto = 'Nininini'
p = 28
print('texto: ',texto)
print('padrao: ' + str(p))
print('cifra: ' + cripto_cesar(texto,p))
|
86589672dfb4163954b2b7454a0f7d275bad8938 | nedstarksbastard/LeetCode_Py | /leetcode.py | 3,480 | 3.75 | 4 |
def twoSum( nums, target):
"""
https://leetcode.com/problems/two-sum/description/
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for index, num in enumerate(nums):
if target - num in d.keys():
return [d[target-num], index]
d[num] = index
# nums = [2, 7, 11, 15]
# target = 18
# print(twoSum(nums, target))
def reverse(num):
"""
:type x: int
:rtype: int
"""
#return int(''.join(list(str(x))[::-1]))
if num < -2147483648 or num > 2147483647:
return 0
negativeFlag = False
if (num < 0):
negativeFlag = True
num = -num
prev_rev_num, rev_num = 0,0
while (num != 0):
curr_digit = num % 10
rev_num = (rev_num * 10) + curr_digit
if (rev_num - curr_digit) // 10 != prev_rev_num:
print("WARNING OVERFLOWED!!!\n")
return 0
prev_rev_num = rev_num
num = num // 10
return -rev_num if negativeFlag else rev_num
#print(reverse(1534236469))
def lengthOfLongestSubstring( s):
"""
:type s: str
:rtype: int
"""
i, ans = 0, 0
d = dict()
for j, char in enumerate(s):
if char in d:
i = max(d[char], i)
ans = max(ans, j-i+1) #sliding window
d[char] = j+1
return ans
#lengthOfLongestSubstring("abcabcbb")
def hammingDistance(x, y):
"""
https://leetcode.com/problems/hamming-distance/description/
:type x: int
:type y: int
:rtype: int
"""
def getBinary(num):
import collections
deq = collections.deque()
while (num > 0):
deq.appendleft(num % 2)
num = num // 2
return deq
x, y = getBinary(x), getBinary(y)
length = abs(len(x) - len(y))
if len(x) > len(y):
y.extendleft([0] * length)
else:
x.extendleft([0] * length)
distance = 0
for i, j in zip(x,y):
if i != j:
distance +=1
return distance
#print(hammingDistance(3,5))
def singleNumber(nums):
"""
https://leetcode.com/problems/single-number/description/
:type nums: List[int]
:rtype: int
"""
#return filter(lambda x: nums.count(x)==1, nums).__next__()
#return 2*sum(set(nums)) - sum(nums)
a = 0
for i in nums:
a ^= i
return a
#print(singleNumber([5,2,2]))
def is_one_away(first: str, other: str) -> bool:
"""Given two strings, check if they are one edit away. An edit can be any one of the following.
1) Inserting a character
2) Removing a character
3) Replacing a character"""
skip_difference = {
-1: lambda i: (i, i+1), # Delete
1: lambda i: (i+1, i), # Add
0: lambda i: (i+1, i+1), # Modify
}
try:
skip = skip_difference[len(first) - len(other)]
except KeyError:
return False # More than 2 letters of difference
for i, (l1, l2) in enumerate(zip(first, other)):
if l1 != l2:
i -= 1 # Go back to the previous couple of identical letters
break
# At this point, either there was no differences and we exhausted one word
# and `i` indicates the last common letter or we found a difference and
# got back to the last common letter. Skip that common letter and handle
# the difference properly.
remain_first, remain_other = skip(i + 1)
return first[remain_first:] == other[remain_other:]
print(is_one_away('pale', 'ale')) |
f82577df1e996d7a18832b14f029d767235ee714 | tckl91/02-Pig-Latin | /pig_latin.py | 1,855 | 3.78125 | 4 | def is_vowel(ch):
if ch in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:
return True
else:
return False
def cut(word):
if len(word) == 1:
return (word, '')
else:
for n in range(0, len(word)):
if is_vowel(word[n]):
return (word[:n], word[n:])
def piggify_word(word):
if len(word) == 1:
if is_vowel(word[0]):
return word + 'hay'
else:
return word + 'ay'
else:
if is_vowel(word[0]):
return word + 'hay'
else:
return cut(word)[1] + cut(word)[0] + 'ay'
def clean_word(raw_word):
if len(raw_word) == 0:
return ('')
else:
for n in range (0, len(raw_word)):
if not raw_word[n].isalpha():
return (raw_word[:n], raw_word[n:])
return (raw_word, '')
def get_raw_words (sentence):
return sentence.split()
def piggify_pairs(pair_list):
new_list = []
for n in range (0, len(pair_list)):
pig_word = piggify_word(pair_list[n][0])
add_punctuation = (pig_word, pair_list[n][1])
new_list.append(add_punctuation)
return new_list
def reassemble(pair_list):
sentence = ''
for n in range(0, len(pair_list)):
if n == (len(pair_list) - 1):
sentence += pair_list[n][0] + pair_list[n][1]
else:
sentence += pair_list[n][0] + pair_list[n][1] + ' '
return sentence
def piggify_sentence(sentence):
clean_list = []
for n in get_raw_words(sentence):
clean_list.append(clean_word(n))
return reassemble(piggify_pairs(clean_list))
def main():
sentence = input('Please enter your sentence to be translated into Pig Latin: ')
print (piggify_sentence(sentence))
if __name__ == "__main__":
main()
|
b9233a3d426c1e037e23ca892c7426b8acdaf153 | kenglishhi/kenglish-ics699 | /sandbox/whitespace_test.py | 526 | 3.609375 | 4 | #!/usr/bin/python
from string import *
dna = """
aaattcctga gccctgggtg caaagtctca gttctctgaa atcctgacct aattcacaag
ggttactgaa gatttttctt gtttccagga cctctacagt ggattaattg gccccctgat
tgtttgtcga agaccttact tgaaagtatt caatcccaga aggaagctgg aatttgccct
tctgtttcta gtttttgatg agaatgaatc ttggtactta gatgacaaca tcaaaacata
ctctgatcac cccgagaaag taaacaaaga tgatgaggaa ttcatagaaa gcaataaaat
gcatggtatg tcacattatt ctaaaacaa """
print "BEFORE:"
print dna
for s in whitespace:
dna = replace(dna, s, "")
print "AFTER:"
print dna
|
eeecf3d2b4bf2cee7e59ba996215d4c85d6cd944 | scienceacademy/python_examples | /conditional_examples.py | 274 | 4.09375 | 4 | print("Enter two numbers")
x = int(input("x: "))
y = int(input("y: "))
if x > y:
print("x is bigger")
elif y > x:
print("y is bigger")
else:
print("they're the same")
age = int(input("How old are you? "))
if age > 12 and age < 20:
print("You're a teenage") |
be5f73e2e74a92d9d0c94eef14c6771a6c642a27 | rameym/UW-IT-FDN-100 | /hw5.py | 3,319 | 4.4375 | 4 | #!/usr/bin/env python3
''' Assignment 5
1. Create a text file called Todo.txt using the following data, one line per row:
Clean House,low
Pay Bills,high
2. When the program starts, load each row of data from the ToDo.txt text file
into a Python list. You can use the readlines() method to import all lines as a list.
3. After you load the data into a list, loop through the list and add each item
as a "key,value" pair a new dictionary. Look back through the lecture notes
at "split" and "indexing".
4. After you have added existing data to the dictionary, use the menu structure
included in the template to allow the user to Add or Remove tasks from the
dictionary using numbered choices.
5. Create your menu by adding a print statement that tells the user which
option to select. Something similar to this:
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
6. Save the data from the table into the Todo.txt file when the program exits.
7. For two points, let us know what you would like feedback on and/or have questions about '''
infile = "todo.txt"
# read in ToDo.txt here using readlines
with open(infile, 'r') as todo_file:
lines = todo_file.readlines()
task_dict = {}
# create empty dictionar to store data as we loop
for line in lines:
task = line.split(",")[0].strip()
priority = line.split(",")[1].strip()
task_dict[task] = priority
# add line to add new key to a dictionary here using task ask key and priority as value
while(True):
print ("""
Menu of Options
1) Show current data
2) Add a new item.
3) Remove an existing item.
4) Save Data to File
5) Exit Program
""")
strChoice = str(input("Which option would you like to perform? [1 to 5] - "))
print() #adding a new line
# Choice 1 -Show the current items in the table
if (strChoice.strip() == '1'):
for key, val in task_dict.items():
print(key, val)
# loop through the dictionary here and print items
# Choice 2 - Add a new item to the list/Table
elif (strChoice.strip() == '2'):
new_key = input("Enter the additional task: ")
new_value = input("Rank the priority from low to high: ")
task_dict[new_key] = new_value
# add a new key, value pair to the dictionary
# Choice 3 - Remove a new item to the list/Table
elif (strChoice == '3'):
remove_key = input("Enter the task name to remove: ")
if remove_key in task_dict.keys():
del task_dict[remove_key]
else:
input("Your task is not in the dictionary, please check spelling and try again: ")
# locate key and delete it using del function
# Choice 4 - Save tasks to the ToDo.txt file
elif (strChoice == '4'):
with open(infile, 'w') as fh:
# fh.writelines(task_dict)
for key, value in task_dict.items():
fh.write('{},{}\n'.format(key, value))
# open a file handle
# loop through key, value and write to file
# Chocie 5- end the program
elif (strChoice == '5'):
print("Goodbye!")
break #and Exit the program
|
fda998e4ecca4119973210c287411f612af6bc0f | saffiya/quiz_game | /quiz/quiz.py | 1,463 | 4.0625 | 4 | def show_menu():
print("1. Ask questions")
print("2. Add a question")
print("3. Exit game")
option = input("Enter option: ")
return option
def ask_questions():
questions = []
answers = []
with open("questions.txt", "r") as file:
lines = file.read().splitlines()
for i, text in enumerate(lines):
if i%2 == 0:
questions.append(text)
else:
answers.append(text)
number_of_questions = len(questions)
questions_and_answers = zip(questions, answers)
score = 0
for question, answer in questions_and_answers:
guess = input(question + "> ")
if guess == answer:
score += 1
print("right!")
print(score)
else:
print("wrong!")
print("You got {0} correct out of {1}".format(score, number_of_questions))
def add_question():
print("")
question = input("Enter a question\n> ")
print("")
print("OK then, tell me the answer")
answer = input("{0}\n> ".format(question))
file = open("questions.txt","a")
file.write(question + "\n")
file.write(answer + "\n")
file.close()
def game_loop():
while True:
option = show_menu()
if option == "1":
ask_questions()
elif option == "2":
add_question()
elif option == "3":
break
else:
print("Invalid option")
print("")
game_loop() |
75189396066ec93f1ed51015039fa29011aeb5a5 | odayibas/astair | /controller-logic/pmvModel.py | 4,834 | 3.5625 | 4 | import math
import sys
from datetime import datetime
"""
--- Input Parameters ---
Air Temperature (Celsius) -> ta
Mean Radiant Temperature (Celsius) -> tr
Relative Air Velocity (m/s) -> vel
Relative Humidity (%) -> rh
Metabolic Rate (met) -> met (1.2)
Clothing (clo) -> clo (0.3)
External Work (Generally 0) -> work
"""
# This function calls all necessary functions.
def pmv(ta, tr, vel, rh, met, clo, work = 0):
pa = calculatePA(rh, ta)
icl = calculateICL(clo)
mw = calculateMW(met, work)
fcl = calculateFCL(icl)
hcf = calculateHCF(vel)
taa = convertKelvin(ta)
tra = convertKelvin(tr)
tcla = calculateTCLA(taa, ta, icl)
tcl, xn, hc = calculateTCL(icl, fcl, taa, tra, mw, tcla, hcf)
totalLost = calculationTotalLost(mw, pa, met, ta, fcl, xn, tra, tcl, hc)
ts = calculationTS(met)
pmv = calculatePVM(ts, mw, totalLost)
ppd = calculatePPD(pmv)
return pmv, ppd
# This function displays pmv and ppd in screen.
def display(pmv, ppd, cel):
print(f"PMV Value: {pmv}")
print(f"PPD Value: {ppd}")
degree = round(pmv, 0)
print(f'New A/C Degree: {cel + degree}')
# This function calculates pressure.
# Unit -> Pa
def calculatePA(rh, ta):
return rh * 10.0 * math.exp(16.6536 - 4030.183 / (ta + 235.0))
# This function calculates thermal insulation of the clothing.
# Unit -> m^2 * K/W
def calculateICL(clo):
return 0.155 * clo
# This function calculates internal heat production in the human body,
# Using metabolic rate and external work.
# met&work unit -> met
# Unit -> W/m^2
def calculateMW(met, work):
m = met * 58.15 # Convert W/m^2
w = work * 58.15 # Convert W/m^2
return m + w
# This function calculates clothing area factor
def calculateFCL(icl):
if(icl < 0.078):
fcl = 1.0 + 1.29 * icl
else:
fcl = 1.05 + 0.645 * icl
return fcl
# This function calculates heat transfer coefficient by forced convection.
# Unit -> W/(m^2*K)
def calculateHCF(vel):
return 12.1 * (vel**0.5)
# This function converts celsius to kelvin,
# for air temp. and mean radiant temp.
def convertKelvin(temp):
return temp + 273
# -----
# This functions calculate clothing surface temperature.
# Unit -> Celsius (C)
def calculateTCLA(taa, ta, icl):
return taa + (35.5 - ta) / (3.5 * icl + 0.1)
def calculateTCL(icl, fcl, taa, tra, mw, tcla, hcf):
p1 = icl * fcl
p2 = p1 * 3.96
p3 = p1 * 100.0
p4 = p1 * taa
p5 = 308.7 - 0.028 * mw + p2 * (tra/100) ** 4
xn = tcla / 100.0
xf = xn / 50.0
n = 0
eps = 0.00015
hc = 1.0
while(abs(xn-xf) > eps):
xf = (xf + xn) / 2.0
hcn = 2.38 * abs(100.0 * xf - taa)**0.25
if(hcf > hcn):
hc = hcf
else:
hc = hcn
xn = (p5 + p4 * hc - p2 * xf**4.0) / (100.0 + p3 * hc)
n = n + 1
if(n>150):
print("Error")
exit()
tcl = 100.0 * xn - 273.0
return tcl, xn, hc
# -----
# This function calculates total lost.
def calculationTotalLost(mw, pa, m, ta, fcl, xn, tra, tcl, hc):
m = m * 58.15 # Convert met to W/m^2
hl1 = 3.05 * 0.001 * (5733.0 - 6.99 * mw - pa) # heat loss diff. through skin
if(mw > 58.15): # heat loss by sweating
hl2 = 0.42 * (mw - 58.15)
else:
hl2 = 0.0
hl3 = 1.7 * 0.00001 * m * (5867.0 - pa) # latent respiration heat loss
hl4 = 0.0014 * m * (34.0 - ta) # dry respiration heat loss
hl5 = 3.96 * fcl * (xn**4.0 - (tra/100.0)**4.0) # heat loss by radiation
hl6 = fcl * hc * (tcl - ta)
return hl1 + hl2 + hl3 + hl4 + hl5 + hl6 # Sum of loss
# This function calculates thermal sensation transfer coeefficient.
def calculationTS(m):
return 0.303 * math.exp(-0.036 * (m * 58.15)) + 0.028
# This function calculates predicted percentage dissat (PPD).
def calculatePPD(pmv):
return 100 - 95 * math.exp(-0.03353 * (pmv**4) - 0.2179 * (pmv**2))
# This function calculates predicted mean vote (PVM).
def calculatePVM(ts, mw, totalLost):
return ts * (mw - totalLost)
def writeFile(pmv, ppd, tr):
myFile = open('PMVModel.txt', 'a')
myFile.write('\nAccessed on ' + str(datetime.now()) + " PMV: " + str(pmv) + " PPD: " + str(ppd) + " New A/C Degree: " + str(round(pmv, 0) + tr))
# Main Function
if __name__ == "__main__":
if(len(sys.argv) != 7):
print("Error")
sys.exit(1)
tr = float(sys.argv[1]) #25
ta = float(sys.argv[2]) #23.5
vel = float(sys.argv[3]) #0.2
rh = float(sys.argv[4]) #60
met = float(sys.argv[5]) #1.2
clo = float(sys.argv[6]) #0.3
pmv, ppd = pmv(tr, ta, vel, rh, met, clo)
#writeFile(pmv, ppd, tr) |
8e72f93ab40369d2bfcad78fced401e3f3d072ac | rounakbanik/stanford_algorithms | /week6/median.py | 3,203 | 3.53125 | 4 | def find_parent(ele_num):
if ele_num% 2 == 1:
return ele_num/2
return ele_num/2 - 1
def find_children(ele_num):
return 2*ele_num + 1, 2*ele_num + 2
def insertmax(hlow, num):
hlow.append(num)
ele_num = len(hlow) - 1
while ele_num > 0:
if num > hlow[find_parent(ele_num)]:
hlow[ele_num], hlow[find_parent(ele_num)] = hlow[find_parent(ele_num)], hlow[ele_num]
ele_num = find_parent(ele_num)
else:
return hlow
return hlow
def insertmin(hhigh, num):
hhigh.append(num)
ele_num = len(hhigh) - 1
while ele_num > 0:
if num < hhigh[find_parent(ele_num)]:
hhigh[ele_num], hhigh[find_parent(ele_num)] = hhigh[find_parent(ele_num)], hhigh[ele_num]
ele_num = find_parent(ele_num)
else:
return hhigh
return hhigh
def deletemax(hlow):
index = len(hlow) - 1
hlow[index], hlow[0] = hlow[0], hlow[index]
hlow.pop()
ele_num = 0
while 2*ele_num +1 < index:
c = find_children(ele_num)
if c[1] > index-1:
hlow.append(-1* float("inf"))
if hlow[ele_num] < hlow[c[0]] or hlow[ele_num] < hlow[c[1]]:
maxi_index = hlow.index(max(hlow[c[0]], hlow[c[1]]))
hlow[ele_num], hlow[maxi_index] = hlow[maxi_index], hlow[ele_num]
ele_num = maxi_index
else:
if hlow[-1] == -1*float("inf"):
hlow.pop()
return hlow
if hlow[-1] == -1*float("inf"):
hlow.pop()
return hlow
def deletemin(hhigh):
index = len(hhigh) - 1
hhigh[index], hhigh[0] = hhigh[0], hhigh[index]
hhigh.pop()
ele_num = 0
while 2*ele_num + 1 < index:
c = find_children(ele_num)
if c[1] > index-1:
hhigh.append(float("inf"))
if hhigh[ele_num] > hhigh[c[0]] or hhigh[ele_num] > hhigh[c[1]]:
mini_index = hhigh.index(min(hhigh[c[0]], hhigh[c[1]]))
hhigh[ele_num], hhigh[mini_index] = hhigh[mini_index], hhigh[ele_num]
ele_num = mini_index
else:
if hlow[-1] == float("inf"):
hhigh.pop()
return hhigh
if hhigh[-1] == float("inf"):
hhigh.pop()
return hhigh
median_sum = 0
hlow = []
hhigh = []
median_arr = []
vertices = []
with open("Median.txt") as f:
for line in f:
num = int(line)
vertices.append(num)
if len(hlow) == 0 and len(hhigh) == 0:
hlow.append(num)
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
else:
if len(hlow) > 0:
maxi = hlow[0]
else:
maxi = -1*float("inf")
if len(hhigh) > 0:
mini = hhigh[0]
else:
mini = float("inf")
if num < maxi:
hlow = insertmax(hlow, num)
elif num > mini:
hhigh = insertmin(hhigh, num)
else:
hlow = insertmax(hlow, num)
if len(hlow) > len(hhigh) + 1:
ele = hlow[0]
hlow = deletemax(hlow)
if -1*float("inf") in hlow:
hlow.remove(-1*float("inf"))
hhigh = insertmin(hhigh, ele)
elif len(hhigh) > len(hlow) + 1:
ele = hhigh[0]
hhigh = deletemin(hhigh)
if float("inf") in hhigh:
hhigh.remove(float("inf"))
hlow = insertmax(hlow, ele)
if len(hlow)> len(hhigh):
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
elif len(hhigh) > len(hlow):
median_sum = median_sum + hhigh[0]
median_arr.append(median_sum)
else:
median_sum = median_sum + hlow[0]
median_arr.append(median_sum)
print median_sum%10000
|
b91c80ad878426912f994ee6f2112d62416acf0e | SagarikaNagpal/Python-Practice | /QuesOnOops/PythonTuples.py | 154 | 4.09375 | 4 | tuple = ('abcd',786,2.23,'john',70.2)
tinyTuple = (123,'john')
print(tuple)
print(tinyTuple)
print(tuple[1:3])
print(tinyTuple+tuple)
print(tinyTuple*3)
|
18d9399b5e6fe4e0c089b392e7fd436dcb0cc790 | SagarikaNagpal/Python-Practice | /QuesOnOops/D-15.py | 263 | 4.0625 | 4 | # Question D15: WAP to input 10 values in a float array and display all the values more than 75.
floatArray=[34.9,65.3,56.3,50.7,54.7,87.9,76.8]
for val in floatArray:
if(val>75):
print("The numbers which are greater than 75 are : ",val)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.