text
stringlengths 37
1.41M
|
---|
import pygame
import math
import random
from helper_code import scale
class Pong:
GAME_WIDTH = 500
GAME_HEIGHT = 500
FPS = 120
PLAYER_WIDTH = 10
PLAYER_HEIGHT = 40
PLAYER_VEL = 4
MAX_BOUNCE_ANGLE = 1 # ~60 degrees
BALL_SIZE = 10
BALL_SPEED = 3
def __init__(self, win):
""" This is the top-level code for pong. We are passed a window to
draw into and do so continually until the user exits.
"""
self.p1_pos = 250
self.p2_pos = 250
self.p1_score = 0
self.p2_score = 0
self.ball_pos = (250, 250)
self.ball_vx = random.choice([1, -1]) * Pong.BALL_SPEED / 2
self.ball_vy = 0
pygame.init()
pygame.display.set_caption("Pong")
game_surface = pygame.Surface((self.GAME_WIDTH, self.GAME_HEIGHT))
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.Font(pygame.font.get_default_font(), 60)
run = True
while run:
# pygame.time.delay(10) # pause for 10ms (~100fps)
clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
win = pygame.display.set_mode(
(event.w, event.h), pygame.RESIZABLE)
self.window_width = event.w
self.window_height = event.h
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and (self.p1_pos > 0):
self.p1_pos -= self.PLAYER_VEL
if keys[pygame.K_s] and (self.p1_pos < 499 - Pong.PLAYER_HEIGHT):
self.p1_pos += self.PLAYER_VEL
if keys[pygame.K_UP] and(self.p2_pos > 0):
self.p2_pos -= self.PLAYER_VEL
if keys[pygame.K_DOWN] and (self.p2_pos < 499 - Pong.PLAYER_HEIGHT):
self.p2_pos += self.PLAYER_VEL
self.ball_pos = (
self.ball_pos[0] + self.ball_vx,
self.ball_pos[1] + self.ball_vy)
# ball bounces off top or bottom of screen
if (self.ball_pos[1] <= 0) or (self.ball_pos[1] >= 499):
self.ball_vy = -self.ball_vy
# ball bounces off players
if ((30 <= self.ball_pos[0] <= 40)
and (self.p1_pos <= self.ball_pos[1] <= self.p1_pos + Pong.PLAYER_HEIGHT)):
relative_intersect = (
self.p1_pos + Pong.PLAYER_HEIGHT/2) - self.ball_pos[1]
normalised_relative_intersect = relative_intersect / \
(Pong.PLAYER_HEIGHT / 2)
bounce_angle = normalised_relative_intersect * Pong.MAX_BOUNCE_ANGLE
self.ball_vx = Pong.BALL_SPEED * math.cos(bounce_angle)
self.ball_vy = - Pong.BALL_SPEED * math.sin(bounce_angle)
elif (460 <= self.ball_pos[0] <= 470
and (self.p2_pos <= self.ball_pos[1] <= self.p2_pos + Pong.PLAYER_HEIGHT)):
relative_intersect = (
self.p2_pos + Pong.PLAYER_HEIGHT/2) - self.ball_pos[1]
normalised_relative_intersect = relative_intersect / \
(Pong.PLAYER_HEIGHT / 2)
bounce_angle = normalised_relative_intersect * Pong.MAX_BOUNCE_ANGLE
self.ball_vx = - Pong.BALL_SPEED * math.cos(bounce_angle)
self.ball_vy = - Pong.BALL_SPEED * math.sin(bounce_angle)
# if ball off screen reset and update score
if (self.ball_pos[0] <= 0):
self.ball_pos = (250, 250)
self.ball_vx = self.BALL_SPEED / 2
self.ball_vy = 0
self.p2_score += 1
elif (self.ball_pos[0] >= 499):
self.ball_pos = (250, 250)
self.ball_vx = -self.BALL_SPEED / 2
self.ball_vy = 0
self.p1_score += 1
# draw screen
game_surface.fill((0, 0, 0))
dashes = 25
dash_length = (500//dashes)
for i in range(dashes):
pygame.draw.line(
game_surface,
(255, 255, 255),
(250, i*(dash_length) + 10),
(250, i*(dash_length) + dash_length//2 + 10),
2)
pygame.draw.rect(
game_surface,
(255, 255, 255),
(int(self.ball_pos[0] - Pong.BALL_SIZE/2),
int(self.ball_pos[1] - Pong.BALL_SIZE/2),
Pong.BALL_SIZE,
Pong.BALL_SIZE)
)
pygame.draw.rect(
game_surface,
(255, 255, 255),
(30, self.p1_pos, Pong.PLAYER_WIDTH, Pong.PLAYER_HEIGHT))
pygame.draw.rect(
game_surface,
(255, 255, 255),
(460, self.p2_pos, Pong.PLAYER_WIDTH, Pong.PLAYER_HEIGHT))
p1_text = font.render(str(self.p1_score), True, (255, 255, 255))
p2_text = font.render(str(self.p2_score), True, (255, 255, 255))
game_surface.blit(p1_text, (int(200 - p1_text.get_rect().width/2), 20))
game_surface.blit(p2_text, (int(300 - p2_text.get_rect().width/2), 20))
scale(
win,
game_surface,
(self.GAME_WIDTH, self.GAME_HEIGHT),
(self.window_width, self.window_height))
pygame.display.update()
pygame.font.quit()
pygame.quit()
|
import pygame
from space_invaders.projectile import Projectile
# from living_entity import LivingEntity
class Player:
WIDTH = 30
HEIGHT = 30
VELOCITY = 3
LIVES = 3
COLOR = (63, 68, 16)
DELAY_BETWEEN_SHOTS = 40
PROJ_VELOCITY = 4
def __init__(self, pos_x, pos_y):
""" Players are entities with three lives """
self.alive = True
self.pos_x = pos_x
self.pos_y = pos_y
self.lives = Player.LIVES
self.count = 0
self.img = pygame.image.load('space_invaders\images\player.png')
def draw(self, win):
""" Add an image onto win, centred on its position and scaled to
the size of the player
"""
if self.alive:
win.blit(pygame.transform.scale(
self.img,
(Player.WIDTH, Player.HEIGHT)),
(int(self.pos_x - Player.WIDTH/2),
int(self.pos_y - Player.HEIGHT/2)))
def check_if_hit(self, projectiles):
""" Player can only be hit by a Projectile object travelling downwards.
If the player is hit by a projectile(s), the projectile(s) is/are
removed.
"""
hit = False
if self.alive: # only check for collisions if entity is still alive
for projectile in projectiles:
if ((self.pos_x - Player.WIDTH/2 <= projectile.pos_x <= self.pos_x + Player.WIDTH/2)
and (self.pos_y - Player.HEIGHT/2 <= projectile.pos_y <= self.pos_y + Player.HEIGHT/2)
and (projectile.direction == False)):
projectiles.remove(projectile)
hit = True
if hit:
self.lives -= 1
if self.lives <= 0:
self.alive = False
def update(self, keys, window_width, projectiles):
""" Defines what the player entity does every frame """
if self.alive:
if ((keys[pygame.K_a] or keys[pygame.K_LEFT])
and (self.pos_x > Player.WIDTH)):
self.pos_x -= Player.VELOCITY
if ((keys[pygame.K_d] or keys[pygame.K_RIGHT])
and (self.pos_x < window_width - Player.WIDTH)):
self.pos_x += Player.VELOCITY
self.check_if_hit(projectiles)
if self.count == 0:
if (keys[pygame.K_SPACE]):
self.count = Player.DELAY_BETWEEN_SHOTS
# fire a projectile firing upwards
projectiles.append(Projectile(
self.pos_x, self.pos_y, True, Player.PROJ_VELOCITY))
else:
self.count -= 1
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
#n 횟수 s 배열
height = 0
heightrecord = []
valleycount = 0
for i in range(len(s)):
if s[i] == "U":
height += 1
else:
height -= 1
heightrecord.append(height)
#-1->0으로 높이가 변하는 경우를 count
j = 1
for j in range(len(s)):
if heightrecord[j-1] == -1 and heightrecord[j] == 0:
valleycount += 1
return valleycount
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close() |
import itertools
import random
#set up the deck
def getDeck():
deck=list(itertools.product(range(3),range(3),range(3),range(3),[False]));
idx=['col','shape','fill','num','dealt'];
deck=[dict(zip(idx,x)) for x in deck];
return deck
def deal(deck):
not_dealt=[x for x in range(len(deck)) if not(deck[x]['dealt'])];
idx=random.sample(not_dealt,12);
in_play=list([]);
print idx
for i in idx:
# print deck[i]['dealt']
deck[i]['dealt']=True;
in_play.append(deck[i]);
return in_play,deck
# print deck;
deck=getDeck();
in_play,deck=deal(deck);
picked=[0,1,2];
picked=[in_play[i] for i in picked];
keys_all=picked[0].keys();
picked=[ len(set([one_dict.get(key) for one_dict in picked])) for key in picked[0].keys() if not(key=='dealt')];
print picked
print picked.count(2)==0
picked=[1,3,1,3]
print picked.count(2)==0
print picked
# picked=zip(*picked);
# print picked
# print a
# a.update(in_play[picked[1]]);
# print a
# print deck |
"""Vanessa wants:
to be more adventurous by going to more activities
about Music,festivals, art, animals, food, languages, sunsets, photography
"""
import json
import urllib2
def take_in_keyword():
# takes in user's interest via raw_input
# return string
pass
def take_in_date_user_wants_to_go_out():
# takes in month by raw_input
# takes in date by raw_input
# takes in year by raw_input
# return date_tuple
pass
def take_in_time_user_wants_to_go_out():
# takes in hour of day
# takes in am/pm
pass
def make_keyword_request_to_ticket_master_api(user_keyword='Shakira'):
# user_keyword = "Madonna" #raw_input("what event to you want to search for")
api_key = "<add key here"
api_url = "http://app.ticketmaster.com/discovery/v1/events.json?keyword="+ user_keyword+"&apikey="+api_key+"&callback=myFunction"
response = urllib2.urlopen(api_url)
json_obj = json.load(response)
return json_obj
def parse_json_obj_for_useful_info(json_obj):
#navigate dictionary to get what you want:
for key in json_obj:
print key
pass
# def make_recommendations_about_other_artists():
# # maybe compare artist_name with other playlists
# # would need to find another api like spotifiy or soundcloud??
# pass
# def
def main():
user_keyword = raw_input("What event do you want to search for?: ")
json_obj = make_keyword_request_to_ticket_master_api(user_keyword)
parse_json_obj_for_useful_info(json_obj)
if __name__ == '__main__':
main()
|
class MovieInfo(object):
def __init__(self, director, release_year, title, actor_1, actor_2, location):
self.director= director
self.release_year = release_year
self.title = title
self.actor_1 = actor_1
self.actor_2 = actor_2
self.location = location
|
print "Welcome to the survey!"
name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
hobby = raw_input("What is your favorite hobby? ")
movie = raw_input("What is your favorite movie? ")
pets = raw_input("Do you prefer dogs or cats? ")
siblings = raw_input("How many siblings do you have? ")
print name + "'s favorite color is " + color + "."
print "%s's favorite hobby is %s." % (name, hobby)
print name + "'s favorite movie is " + movie + "."
print name, "has", siblings, "siblings!"
print "%s prefers %s." % (name, pets) |
from json_class import JsonClass
from dungeonsheets.item import Item
class Shield(Item):
"""A shield that can be worn on one hand."""
id = ""
name = "Shield"
cost = "10 gp"
base_armor_class = 2
type = "shield"
json_attributes = Item.json_attributes + (
"base_armor_class",
)
def __str__(self):
return self.id
def __repr__(self):
# return "\"{:s}\"".format(self.name)
return "\"{:s}\"".format(self.id)
@staticmethod
def related_db():
from db.tables import DB_Armor
return DB_Armor
@classmethod
def improved_version(cls, bonus):
bonus = int(bonus)
class NewShield(cls):
name = f'+{bonus} ' + cls.name
base_armor_class = cls.base_armor_class + bonus
return NewShield
@classmethod
def to_base_dict(cls):
retVal = cls().save_dict()
use_id = cls.id
if use_id == "":
use_id = "Basic" + cls.__name__
retVal['id'] = use_id
retVal['base_class'] = cls.__name__
retVal['improved'] = 0
return retVal
class WoodenShield(Shield):
name = 'Wooden shield'
class ShieldOfFaces(Shield):
name = "Shield +1"
base_armor_class = 3
class NoShield(Shield):
"""If a character is carrying no shield."""
name = "No shield"
cost = "0"
base_armor_class = 0
# def __str__(self):
# return self.name
all_shields = (Shield, WoodenShield, ShieldOfFaces, NoShield)
class Armor(Item):
"""A piece of armor that can be worn.
Attributes
----------
name : str
Human-readable name for this armor.
cost : str
Cost and currency for this armor.
base_armor_class : int
Armor class granted before modifiers.
dexterity_mod_max : int
How much dexterity can the user contribute. ``0`` for no
dexterity modifier, ``None`` for unlimited dexterity modifier.
strength_required : int
Minimum strength needed to use this armor properly.
stealth_disadvantage : bool
If true, the armor causes disadvantage on stealth rolls.
weight_class : str
light, medium, or heavy
weight : int
In lbs.
"""
json_attributes = Item.json_attributes + (
"base_class",
"base_armor_class",
"dexterity_mod_max",
"stealth_disadvantage",
"strength_required",
)
id = ""
base_class = ""
name = "Unknown Armor"
cost = "0 gp"
type = "armor"
base_armor_class = 10
dexterity_mod_max = None
strength_required = None
stealth_disadvantage = False
weight = 0 # In lbs
def __str__(self):
return self.id
def __repr__(self):
return "\"{:s}\"".format(self.id)
@staticmethod
def related_db():
from db.tables import DB_Shield
return DB_Shield
@classmethod
def improved_version(cls, bonus):
bonus = int(bonus)
class NewArmor(cls):
name = f'+{bonus} ' + cls.name
base_armor_class = cls.base_armor_class + bonus
return NewArmor
@classmethod
def to_base_dict(cls):
retVal = cls().save_dict()
use_id = cls.id
if use_id == "":
use_id = "Basic" + cls.__name__
retVal['id'] = use_id
retVal['base_class'] = cls.__name__
retVal['improved'] = 0
return retVal
class NoArmor(Armor):
name = "No Armor"
class LightArmor(Armor):
name = "Light Armor"
class MediumArmor(Armor):
name = "Medium Armor"
class HeavyArmor(Armor):
name = "Heavy Armor"
class PaddedArmor(LightArmor):
name = "Padded Armor"
cost = "5 gp"
base_armor_class = 11
weight = 8
stealth_disadvantage = True
class LeatherArmor(LightArmor):
name = "Leather Armor"
cost = "10 gp"
base_armor_class = 11
weight = 10
class StuddedLeatherArmor(LightArmor):
name = "Studded Leather Armor"
cost = "45 gp"
base_armor_class = 12
weight = 13
class HideArmor(MediumArmor):
name = "Hide Armor"
cost = "10 gp"
base_armor_class = 12
dexterity_mod_max = 2
weight = 12
class ChainShirt(MediumArmor):
name = "Chain Shirt"
cost = "50 gp"
base_armor_class = 13
dexterity_mod_max = 2
weight = 20
class ScaleMail(MediumArmor):
name = "Scale Mail"
cost = "50 gp"
base_armor_class = 14
dexterity_mod_max = 2
stealth_disadvantage = True
weight = 45
class Breastplate(MediumArmor):
name = "Breastplate"
cost = "400 gp"
base_armor_class = 14
dexterity_mod_max = 2
weight = 20
class HalfPlate(MediumArmor):
name = "Half Plate"
cost = "750 gp"
base_armor_class = 15
dexterity_mod_max = 2
stealth_disadvantage = True
weight = 40
class RingMail(HeavyArmor):
name = "Ring Mail"
cost = "30 gp"
base_armor_class = 14
dexterity_mod_max = 0
stealth_disadvantage = True
weight = 40
class ChainMail(HeavyArmor):
name = "Chain Mail"
cost = "75 gp"
base_armor_class = 16
dexterity_mod_max = 0
strength_required = 13
stealth_disadvantage = True
weight = 55
class SplintArmor(HeavyArmor):
name = "Splint Armor"
cost = "200 gp"
base_armor_class = 17
dexterity_mod_max = 0
strength_required = 15
stealth_disadvantage = True
weight = 60
class PlateMail(HeavyArmor):
name = "Plate Mail"
cost = "1,500 gp"
base_armor_class = 18
dexterity_mod_max = 0
strength_required = 15
stealth_disadvantage = True
weight = 65
# Custom Armor
class ElvenChain(MediumArmor):
name = 'Elven Chain'
cost = '5,000 gp'
base_armor_class = 14
dexerity_mod_max = 2
weight = 20
armor_types = [LightArmor, MediumArmor, HeavyArmor]
light_armors = [PaddedArmor, LeatherArmor, StuddedLeatherArmor]
medium_armors = [HideArmor, ChainShirt, ScaleMail, Breastplate, HalfPlate, ElvenChain]
heavy_armors = [RingMail, ChainMail, SplintArmor, PlateMail]
all_armors = light_armors + medium_armors + heavy_armors
|
'''age = 10
if age >= 18:
print("可以去看电影了!")
else:
print("还未成年")
'''
i = 0
while i < 3:
score = int(input("请输入本次考试分数:"))
if score <= 100 and score >90:
print("优秀")
elif score <= 90 and score > 80:
print("良好")
elif score <= 80 and score >=60:
print("及格")
elif score < 60 and score >= 0:
print("不及格")
else:
print("输入非法")
i = i + 1 |
'''
登陆系统:
业务:
输入用户名和密码
从db.txt文件中匹配是否存在该用户以及
密码是否正确,若正确则登陆成功!
否则弹出友好提示信息!(用户名或密码错误!)
'''
#1.将所有数据行提取,存储到字典里(字典:缓冲区,便于快速的修改)
db = {}
#开始读取db.txt文件
f = open("db.txt","r+",encoding="utf-8")
data = f.readlines() #["张三:zhangsan","李思:lisi"]
for i in data:
line = i.split(":") #["张三","zhangsan"]#通过 :号将前后进行切割
db[line[0]] = line[1].replace("\n","") #替代所有密码后面的\n改成""(空字符)
#2.开发
name = input("请输入您的用户名:")
password = input("请输入您的密码:")
'''
1.先判断是否存在该用户名;
若存在,继续匹配密码是否正确
若密码正确:登陆成功
若密码错误:打印友好提示信息
若不存在,该用户不存在
'''
if name in db:
if password == db[name]:
print("登陆成功!")
else:
print("密码错误!")
else:
print("该用户不存在!") |
'''
方法:函数
好处:一本万利,一次书写,处处使用。
def 【方法名】(参数列表):
方法体
[return]
方法名: 多个单词组成,第二个单词开始,首字母就要大写。 totalStudentNumber : 驼峰式命名法
参数列表:
1.单值传输
2.*args:元组:能不定数量的接受参数
3.**kwargs:字典
4.注意:3个参数列表的位置是禁止调换的。
'''
#就用方法来打印1-100以内的数据,(方法的递归调用)
'''i = 1
def printNum(i):
if i <= 100:
print(i)
i = i + 1
printNum(i)
printNum(i)
'''
#求和
'''a = 5
b = 3
c = 1
d = 8
def getSum(a,b,c,d):
s = getSum1(a,b) + getSum1(c,d)
return s
def getSum1(a,b):
return a + b
print(getSum(a,b,c,d))
def showInfo(name,age,*args,**kwargs):
print(name,"------",age)
print(args)
for i in args:
print(i)
print(kwargs["password"],"-----------",kwargs["address"])
showInfo("张佳伟",89,"男",176,password=12233,address="北京市昌平区")
'''
a = 6
b = 7
def getSum(a,b):
c = a + b
return c
print(getSum(a,b)) |
#计算机
'''class Calculator:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self): # 两数相加
return self.a + self.b
def sub(self): # 两数相减
return self.a - self.b
def mul(self): # 两数相乘
return self.a * self.b
def dev(self): # 两数相除
return self.a / self.b
class Test(Calculator):
pass
a = float(input("请输入一个数:"))
x = input("请输入需要进行的运算符号(+,-,*,/):")
b = float(input("请输入另一个数:"))
if x == "+":
result = Calculator(a,b).add()
print(result)
if x == "-":
result = Calculator(a,b).sub()
print(result)
if x == "*":
result = Calculator(a,b).mul()
print(result)
if x == "/":
try:
result = Calculator(a,b).dev()
except ZeroDivisionError:
print("输入错误,除数不能为0!")
else:
print(result)
'''
class OldPhone:
__brand = None
__phoneNumber = None
def __init__(self,brand,phonenumber):
self.__brand = brand
self.__phoneNumber = phonenumber
def setBrand(self,brand):
self.__brand = brand
def getBrand(self):
return self.__brand
def setPhoneNumber(self,phonenumber):
self.__phoneNumber = phonenumber
def getPhoneNumber(self):
return self.__phoneNumber
def call(self,number):
print(self.__phoneNumber,"正在给",number,"打电话......")
class NewPhone(OldPhone):
def call(self,number):
super().call(number)
print("语音拨号中......")
def introduce(self):
print("品牌为:",self.getBrand(),"的手机很好用...")
phone = NewPhone("华为")
phone.phonenumber = "16709823333"
phone.call("17860982222")
phone.introduce() |
def find_person(dict_users, strU):
if strU in dict_users:
return dict_users[strU]
else:
return 'Not Found'
if __name__ == "__main__":
names = ['xiaoyun','xiaohong','xiaoteng','xiaoyi','xiaoyang']
QQ = ['88888','5555555','11111','12341234','1212121']
dict_users = dict(zip(names, QQ))
strU = input()
print(find_person(dict_users, strU)) |
#game_class_version.py
import random
print("Rock, Paper, Scissors, Shoot!")
# CAPTURE INPUTS
user_choice = input("Please choose one of the following options: 'rock', 'paper', or 'scissors': ")
print("-----------")
print("USER CHOICE: ",user_choice)
# VALIDATE INPUTS
options = ["rock", "paper", "scissors"]
if user_choice not in options:
print("INVALID SELECTION, PLEASE TRY AGAIN...")
exit()
# GENERATE CONPUTER SELECTION
computer_choice = random.choice(options)
print("-----------")
print("GENERATING...")
print("COMPUTER CHOICE: ", computer_choice)
# DETERMINE WINNER
#rock beats scissors
#paper beats rock
#scissors beats paper
#same selection is a tie
if user_choice == computer_choice:
print("TIE")
elif user_choice == "rock" and computer_choice == "paper":
print("WINNER: paper")
print("COMPUTER WINS")
elif user_choice =="rock" and computer_choice == "scissors":
print("WINNER: rock")
print("YOU WIN")
elif user_choice == "paper" and computer_choice == "rock":
print("WINNER: paper")
print("YOU WIN")
elif user_choice =="paper" and computer_choice == "scissors":
print("WINNER: scissors")
print("COMPUTER WINS")
elif user_choice == "scissors" and computer_choice == "paper":
print("WINNER: scissors")
print("YOU WIN")
elif user_choice =="scissors" and computer_choice == "rock":
print("WINNER: rock")
print("COMPUTER WINS")
print("-----------")
# DISPLAY FINAL OUTPUTS / OUTCOMES |
Total_amount = float(input("Enter total amount"))
tip_percantage_amount = float(input("Enter the tip percentage amount"))
tip_amount= (tip_percantage_amount/100) * Total_amount
print(tip_amount)
|
TEXT = 'We choose to go to the Moon. We choose to go to the Moon in this decade and do the other things. Not because they are easy, but because they are hard. Because that goal will serve to organize and measure the best of our energies and skills. Because that challenge is one that we are willing to accept. One we are unwilling to postpone. And one we intend to win'
total_sentences = 0
total_words = 0
total_chars = 0
total_letters = 0
total_commas = 0
total_adverbs = 0
for sentence in TEXT.split('.'):
sentence = sentence.strip()
words = sentence.split()
characters = sentence.replace(',', '')
letters = characters.replace(' ', '')
total_sentences += 1
total_words += len(words)
total_chars += len(characters)
total_letters += len(letters)
total_commas += sentence.count(',')
for word in words:
if word.endswith('ly'):
total_adverbs += 1
print(f'Sentences: {total_sentences}')
print(f'Words: {total_words}')
print(f'Characters: {total_chars}')
print(f'Letters: {total_letters}')
print(f'Commas: {total_commas}')
print(f'Adverbs: {total_adverbs}')
|
print'''
'''
# defines the function name and its arguments, then what it does
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
# provides values right from the command line
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
# uses variables to assign values
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# gives values by having python do some math
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
# gives values by having python retrieve the values of the variables
# and then doing math
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese - 5, amount_of_crackers + 1000)
print '''
''' |
year = int(input())
result = 1
if year%400 != 0:
if year%4 == 0:
if year%100 == 0:
result=0
else:
result=0
print(result)
'''
#짧은 코드
if x%4==0 and (x%100!=0 or x%400==0):
print(1)
else:
print(0)
'''
|
#-*- coding: utf-8 -*-
#python3
a = input().split() #python3는 input()
print(float(a[0]) / float(a[1])) #나눗셈 결과. 소수점까지 출력
print(int(a[0]) // int(a[1])) # 나눗셈 몫
'''
python3에서는 input() 함수로 사용자로 부터 입력을 받는다.
입력받은 값을 split( ) 함수를 이용해 space를 구분자로 하여 a 배열의 각 인덱스에 값을 저장한다.
첫번째 입력값 a[0]을 float 형으로 변환하고, 두번째 입력값 a[1]을 float 형으로 변환하여 나눈 값을 출력하면 된다.
'''
|
#-*- coding:utf-8 -*-
'''
각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력
print에 바로 출력하려고 하면 띄어쓰기 출력형식이 맞지 않아서, 문자열로 결합 후 출력
output print format
python3에서 %operator을 지원하지만 권장하지 않음
str.format 함수 사용
'''
import sys
n = int(sys.stdin.readline().rstrip())
for i in range(1,n+1):
x,y = map(int, sys.stdin.readline().rstrip().split())
# case 1
#case = "Case #"+str(i)+": " + str(x) +" + "+str(y)+" = "+str(x+y)
#print(case)
# case 2
# print("Case #%d: %d + %d =" %(i,a,b), a+b)
# case 3
result = 'Case #{}: {} + {} = {}'.format(i,x,y,x+y)
print(result)
|
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f:
f = open("dictionary.txt","r")
print("Can your password survive a dictionary attack?")
#Take input from the keyboard, storing in the variable test_password
#NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords
testpw = input("Type in a trial password: ")
#Write logic to see if the password is in the dictionary file below here:
wordfound = False
for passcode in f:
if (testpw.strip() == passcode.strip()):
print("yikes, your password is in the dictionary!! that's not too great! try again!")
wordfound = True
break
if wordfound == False:
#do not print until it indexes the whole dict
print("what can i say. nice job crafting your passcode! we couldn't figure it out.")
|
'''
CHECK if the string is palindrome
eg = "civic" , "Level"
'''
#!/usr/bin/python
from argparse import ArgumentParser
class palindrome():
def is_palindrome(self, s1):
list1=list(s1)
list1.reverse()
s2=''.join(list1)
if s1==s2:
return True
else:
return False
def main():
parser = ArgumentParser()
parser.add_argument("-s", "--string",dest="string1",
help="please provide string to check palindrome")
args = parser.parse_args()
m1 = palindrome()
print m1.is_palindrome(args.string1)
if __name__=='__main__':
main()
|
flower = "lily"
def print_flower():
global flower # overrides the global variable
flower = "hibiscus"
print(f"Inside the function the flower is {flower}")
print_flower()
print(f"Outside the function the flower is {flower}") |
for n in range(10):
# 0 to 9 inclusive
print(",,", n)
for n in range(3, 10):
# 3 to 9 inclusive
print("}}", n)
for n in range(2, 10, 3):
# 2 5 8 increase in 3s from 2 to 9 inclusive
print("qq", n)
colors = ["blue", "red", "yellow", "orange"]
for n in range(len(colors)):
print(n, colors[n])
for n in range(len(colors) - 1, -1, -1):
print(n, colors[n])
|
num = int(input("Give me a number: "))
if num % 2 == 0:
print("The number is even")
elif num % 2 == 1:
print("the number is odd")
if num % 4 == 0:
print("the number is even and divisible by 4")
divisor = int(input("Give me a second number: "))
if num % divisor == 0:
print("Divisor divides evenly into number.")
else:
print("Divisor does not divide evenly into number.") |
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numbers = []
for number in a:
if number < 5:
numbers.append(number)
print(numbers)
maximum = int(input("Give me a number: "))
print("Your number is " + str(maximum))
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numbers = []
for number in a:
if number < maximum:
numbers.append(number)
print(numbers) |
# Basic setup for Exercise 43's adventure game.
# Generating all my room setups first,
# then hacking on the engine and mapping....
from sys import exit
from random import randint
import inspect
class MainHub(object):
# Eventually I'd like the codeword to be randomly selected; not there yet
def room_setup(self):
room_desc = """
This is the main hub of the space station. There is a
guide here. He tells you to go north to the Diplomatic Office
and give the Chief Diplomat the codeword 'cookie.'"
"""
print room_desc
move = raw_input("> ")
if "north" in move and "do not" not in move:
print "The guide smiles and you head north."
return 'DiplomatRoom'
else:
print "The guide looks at you and gestures north again."
return 'MainHub'
class DiplomatRoom(object):
def room_setup(self):
room_desc = """
This is the office of the station's chief diplomat.
She smiles and asks you for the codeword.
"""
print room_desc
codeguess = raw_input("> ")
if "cookie" in codeguess:
print "She hands you an envelope and points you to the door to the right."
return 'AlienRoom'
else:
print 'She looks appalled and pushes a button on her desk. "Intruder!" she yells,'
print "and you are sucked into a tube and vented into space, where you die."
return 'Death'
class AlienRoom(object):
def room_setup(self):
room_desc = """
This room is hot, and a little damp, and contains the biggest,
leafiest alien you've ever seen. It extends a tendril towards you inquiringly.
"""
print room_desc
offer_item = raw_input("> ")
if "give" in offer_item and "envelope" in offer_item and "do not" not in offer_item:
print "You think the alien looks pleased; it takes the envelope and"
print "promptly digests it. One of its vines points you back to the diplomat's office.\n"
print "(You think you hear a noise in there...)"
return 'DiplomatRoom2'
else:
print "The alien shrugs and eats you, the faster to obtain the envelope."
print "You might be pooped out in 500 years."
return 'Death'
class DiplomatRoom2(object):
def room_setup(self):
room_desc = """
Back in the diplomat's office, you find that she's been replaced with a robot.
The robot levels a blaster at you and fires.
"""
print room_desc
evade = raw_input("> ")
if ("dodge" or "move") and not ("don't" or "do not") in evade:
print "You dodge expertly. You spot a shiny plaque on the wall near your head."
print "What are you going to do now? The robot prepares to fire again."
grab = raw_input("> ")
if "plaque" in grab:
print "You grab the plaque and hold it in front of you as the robot fires."
print "The blast strikes the plaque, bounces off, and hits the robot."
print "The robot explodes, leaving a chip behind. You pocket the chip and go"
print "back to the main hub."
return 'MainHub2'
else:
print "The robot shoots you dead. Station security finds"
print "your corpse and assumes you killed the diplomat,"
print "making you a posthumous assassin. Way to go, pal."
return 'Death'
else:
print "You fail to dodge. The robot blows a hole in your head."
print "Everyone assumes you killed the diplomat. Alien relations"
print "are set back a billion years because you didn't move. You suck."
return 'Death'
class MainHub2(object):
def room_setup(self):
room_desc = """
You return to the main hub to find the guide there, a robot, and the
diplomat. All three of them hold out their hand for the chip. Whom do you give it to?
"""
print room_desc
give_chip = raw_input("> ")
if "guide" in give_chip:
print "The guide hands the chip to the diplomat, then motions you to"
print "follow them out the side door as he shoot down the robot with"
print "a hidden blaster."
return 'SideDoor'
elif "robot" in give_chip:
print "The robot takes the chip, shoots you, kidnaps the diplomat,"
print "and runs for the door, covered by the traitorous guide!"
print "Way to go, idiot-- didn't that other robot try to kill you?"
return 'Death'
elif "diplomat" in give_chip:
print "The diplomat takes the chip, then turns around and disables"
print "the robot with a tiny blaster hidden in her sleeve. She"
print "motions to you and the guide to escape through a side door."
return 'SideDoor'
class SideDoor(object):
def room_setup(self):
room_desc = """
You pile out the side door with the guide and the diplomat. There is a four-man escape
pod here. As you arrive, the alien opens the pod's hatch and gestures at you.
"""
print room_desc
pod_enter = raw_input("> ")
if "enter" and "pod" in pod_enter:
print "You pile into the pod and shut the hatch. The diplomat puts the chip"
print "into the navigation computer and presses a button."
print "You soar into space, leaving the station and its murderous robots"
print "behind. Next stop, the alien homeworld!"
return 'Victory'
elif "do not" or "don't" in pod_enter:
print "You hesitate as the others enter the pod."
print "As they beckon you towards the hatch, robots enter the room"
print "and shoot you dead. The others, at least, manage to escape."
return 'Death'
else:
print "The alien gestures again, more intently."
return 'SideDoor'
class Death(object):
def room_setup(self):
self.quips = [
"Well, you picked a bad day to stop sniffing space glue.",
"You came, you saw, you messed up and died.",
"Buzz Lightyear you're not.",
"Not a space ninja, you."
]
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
class Victory(object):
def room_setup(self):
self.quips = [
"Well, looks like you've got this down.",
"Way to go! You probably wrote this game.",
"Who's the big bad space hero today?",
"Whose house? Your house."
]
print self.quips[randint(0,len(self.quips)-1)]
exit(1)
|
# you can optimize your code a bit this way
# it's syntactic sugar, really
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input ("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
|
my_name = "Zed A. Shaw"
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
my_height_cm = my_height * 2.54
my_weight_kg = my_weight * .4536 # that's avoirdupois, thx
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
# %r is "print exactly what you have, Python"
# %f is floating-point and introduces a bit of rounding
print "In metric, he's %r cm tall and %r kg heavy." % (my_height_cm, my_weight_kg)
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right:
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
|
# ord() => ASCII olarak değeri verme chr() içerisinde ki değere göre karakter üretiyor
#metin = input("şifrelenecek metni giriniz")
metin = "Python"
sifre = ""
for k in metin:
print(ord(k)) # ASCII kodlarını verir decimal olarak
print(k, "=>", chr(ord(k) + 5))
sifre = sifre + chr(ord(k) + 5)
print(sifre)
print(metin, " = >", sifre) |
#!/usr/bin/env python
from random import randint
from time import sleep
import unicornhat as unicorn
print("""Snow
Draws random white pixels to look like a snowstorm.
If you're using a Unicorn HAT and only half the screen lights up,
edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below.
""")
unicorn.set_layout(unicorn.AUTO)
unicorn.rotation(0)
unicorn.brightness(0.3)
width,height=unicorn.get_shape()
rows = []
screen_choice = 1
WHITE = (150,150,150)
RED = (200,0,0)
OFF = (0,0,0)
def init():
# create a buffer of <height> blank rows
for i in range(height):
rows.append(get_blank_row())
def get_jo_screen():
scr = []
for i in range(height):
scr.append(get_blank_row())
scr[2][0] = WHITE
scr[3][1] = WHITE
scr[0][1] = WHITE
scr[0][2] = WHITE
scr[0][3] = WHITE
scr[1][2] = WHITE
scr[2][2] = WHITE
scr[0][5] = WHITE
scr[0][6] = WHITE
scr[1][4] = WHITE
scr[1][7] = WHITE
scr[2][4] = WHITE
scr[2][7] = WHITE
scr[3][5] = WHITE
scr[3][6] = WHITE
return(scr)
'''
Make a screen for the I + heart
'''
def get_heart_screen():
scr = []
for i in range(height):
scr.append(get_blank_row())
scr[0][0] = WHITE
scr[0][1] = WHITE
scr[0][2] = WHITE
scr[1][1] = WHITE
scr[2][1] = WHITE
scr[3][0] = WHITE
scr[3][1] = WHITE
scr[3][2] = WHITE
scr[0][4] = RED
scr[0][6] = RED
scr[1][3] = RED
scr[1][4] = OFF
scr[1][5] = RED
scr[1][6] = OFF
scr[1][7] = RED
scr[2][4] = RED
scr[2][5] = OFF
scr[2][6] = RED
scr[3][5] = RED
return(scr)
def get_blank_row():
# generate a blank row
return [OFF] * width
def update_display():
global rows
# keep track of the row we are updating
for h in range(height):
for w in range(width):
# val is between 50 and 255
val = rows[h][w]
#print(rows)
print str(h) + " " + str(w) + " " + str(val)
# invert coordinates
#unicorn.set_pixel((width - 1) - w, (height - 1) - h, val, val, val)
#unicorn.set_pixel(w, h, val, val, val)
(r,g,b) = val
unicorn.set_pixel(w, h, r, g, b)
print ""
unicorn.show()
def step():
global rows
global screen_choice
scr = 1
if screen_choice == 1:
scr = get_heart_screen()
screen_choice = 2
elif screen_choice == 2:
scr = get_jo_screen()
screen_choice = 1
rows = scr
update_display()
#** Begin code here **#
init()
while True:
step()
sleep(0.9)
|
####################################################################################
################ program which compute pi from the first 20 ########################
################### terms of the Madhava series ########################
####################################################################################
from math import sqrt
#initial value of sum
som=0
for n in range(20):
som=som+((-1)**n)/((2*n+1)*(3**n))
#value of the sum given by Madhava series
P=sqrt(12)*som
print("the value of pi compute from the first 20 terms Madhava series is:pi=",P)
|
class Student:
school_name = "Springifeld Elementary"
id = 1
def __init__(self, name, lastname):
self.name = name
self.lastname = lastname
self.id = 1
def __str__(self):
return "Student"
def get_name_capitalized(self):
return self.name.capitalize()
|
import numpy as np
np.random.seed(0)
# Training data set
X = [[1, 2, 3, 2.5],
[2.0, 5.0, -1.0, 2.0],
[-1.5, 2.7, 3.3, -0.8]]
class Layer_Dense:
def __init__(self, n_inputs, n_neurons):
self.weights = 0.1 * np.random.randn(n_inputs, n_neurons) # Creating random weight per neuron
self.biases = np.zeros((1, n_neurons)) # Creating random bias per neuron
def forward(self, inputs):
self.output = np.dot(inputs, self.weights) + self.biases # Dot product of the layer
layer1 = Layer_Dense(4, 5) # Shape of each layer, index0 = input of the layer, index1 = the amount of neurons on that layer
layer2 = Layer_Dense(5, 2)
layer1.forward(X) # passing the data through the layer the parameter being the input layer
# print(layer1.output)
layer2.forward(layer1.output)
print(layer2.output)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 13:25:41 2020
@author: Apa
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#Initialize parameters ======================
Nlayers = 5 # not counting the input layer & the output layer
LayerSize = 50
input_size = 2
output_size = 1
# weight and biases RANGES for each layer
w_low_first = -1.0
w_hi_first = 1.0
w_low = -5
w_hi = 5
w_low_final = -1.0
w_hi_final = 1.0
b_low_first = -1.0
b_hi_first = 1.0
b_low = -1.0
b_hi = 1.0
b_low_final = -1.0
b_hi_final = 1.0
# for the first hidden layer (coming in from the input layer)
WeightsFirst = np.random.uniform(low = w_low_first,high = w_hi_first,size=[input_size,LayerSize])
BiasesFirst = np.random.uniform(low = b_low_first,high = b_hi_first,size=LayerSize)
# Middle layers
Weights = np.random.uniform(low = w_low,high = w_hi,size=[Nlayers,LayerSize,LayerSize])
Biases = np.random.uniform(low = b_low,high = b_hi,size=[Nlayers,LayerSize])
# for the final layer (i.e. the output neuron)
WeightsFinal = np.random.uniform(low = w_low_final, high = w_hi_final,size=[LayerSize,output_size])
BiasesFinal = np.random.uniform(low = b_low_final,high = b_hi_final ,size=output_size)
def activation(z):
return(1/(1+np.exp(-z)))
# return z*(z>0)
# return z
# a function that applies a layer to of BATCH of inputs takes a vextor y_in of dimmension (n_samples x n_in), a matrix w (n_in x n_out),vector b (n_out)
# returns a MATRIX of size (n_samples, n_out)
def apply_layer_new(y_in,w,b):
z=np.dot(y_in,w)+b # note different order in matrix product!
return activation(z)
# apply neural net to y_in of dimmension (n_samples x n_in). Neural net represented by an array of matrixes of weights and vector of biases.
def apply_multi_net(y_in, Weights, Biases, WeightsFinal, BiasesFinal, Nlayers):
# global Weights, Biases, WeightsFinal, BiasesFinal, Nlayers
y=apply_layer_new(y_in,WeightsFirst,BiasesFirst)
for j in range(Nlayers):
y=apply_layer_new(y,Weights[j,:,:],Biases[j,:])
output=apply_layer_new(y,WeightsFinal,BiasesFinal)
return(output)
# Generate a 'mesh grid', i.e. x,y values in an image
M=200 # image of dimension MxM
v0,v1=np.meshgrid(np.linspace(-0.5,0.5,M),np.linspace(-0.5,0.5,M))
batchsize=M**2 # number of samples = number of pixels = M^2
y_in = np.zeros([batchsize,2])
y_in[:,0]=v0.flatten() # fill first component (index 0)
y_in[:,1]=v1.flatten() # fill second component
print (y_in.shape)
# use the MxM input grid that we generated above
y_out = apply_multi_net(y_in,Weights, Biases, WeightsFinal, BiasesFinal, Nlayers) # apply net to all these samples!
print (y_out.shape)
#y_in_2D = np.reshape(y_in[:,0],[M,M])
y_2D = np.reshape(y_out[:,0],[M,M]) # back to 2D image
print(y_2D.shape)
#plt.figure(1)
#plt.subplot(211)
#plt.imshow(y_in_2D,origin='lower',extent=[-0.5,0.5,-0.5,0.5],interpolation='nearest',cmap='RdBu')
#plt.colorbar()
#
#plt.subplot(212)
#plt.imshow(y_2D,origin='lower',extent=[-0.5,0.5,-0.5,0.5],interpolation='nearest',cmap='RdBu')
#plt.colorbar()
#plt.show()
fig=plt.figure(figsize=(5,5)) # prepare figure
ax=plt.axes([0,0,1,1]) # fill everything with image (no border)
img=plt.imshow(y_2D,interpolation='nearest') # plot image
plt.axis('off') # no axes
t=0.0
dt=0.01
def update_wave(frame_number):
global t, img
global y_in, M
global Weights, Biases, WeightsFinal, BiasesFinal, Nlayers
Weights[1,1,1]=t
y_out=apply_multi_net(y_in,Weights, Biases, WeightsFinal, BiasesFinal, Nlayers) # apply net to all these samples!
y_2D=np.reshape(y_out[:,0],[M,M]) # back to 2D image
img.set_data( y_2D )
t+=dt
return img
anim = FuncAnimation(fig, update_wave, interval=200)
plt.show()
|
from abc import ABC
from typing import List
from main.components.button import Button
class Keyboard(ABC):
"""Клавиатура для вьюхи."""
def __init__(self, *buttons: Button) -> None:
self.buttons: List[Button] = sorted(buttons, reverse=True)
def append(self, button: Button) -> None:
"""Добавляет кнопку к клавиатуре."""
self.buttons.append(button)
def __eq__(self, other: "Keyboard") -> bool:
"""Правила сравнения двух клавиатур."""
if len(self.buttons) != len(other.buttons):
return False
return all(this == them for this, them in zip(self.buttons, other.buttons))
def __repr__(self):
return " | ".join(map(repr, self.buttons))
|
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
print("Returned None!@")
return None
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def create_burger(conn, burger):
"""
Create a new burger within the table
:param conn:
:param burger:
:return burger_id:
"""
sql_cmd = ''' INSERT INTO burgers(name, availability)
VALUES(?,?) '''
cursor = conn.cursor()
cursor.execute(sql_cmd, burger)
return cursor.lastrowid
def main():
database = "sqldemo.db"
conn = create_connection(database)
with conn:
# Create burger table
burger_table_cmd = """ CREATE TABLE IF NOT EXISTS burgers (
name text NOT NULL,
availability integer
); """
create_table(conn, burger_table_cmd)
# Create new burgers
bur1 = ("Classic Juicy Beef Burgs", 0)
bur2 = ("Southern Fried Chicken Burger", 0)
bur3 = ("Summer Sunset", 0)
bur4 = ("Baa-Baa Burger", 0)
bur5 = ("Premium Wagyu Burger", 0)
create_burger(conn, bur1)
create_burger(conn, bur2)
create_burger(conn, bur3)
create_burger(conn, bur4)
create_burger(conn, bur5)
conn.commit()
conn.close()
if __name__ == "__main__":
main() |
import numpy as np
import pylab as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
from sklearn import cross_validation, metrics, grid_search
def load_data():
boston = datasets.load_boston()
return boston
def explore_city_data(city_data):
"""Calculate the Boston housing statistics."""
housing_prices = city_data.target
housing_features = city_data.data
size_of_data = housing_prices.size
number_of_features = housing_features.shape[1]
minimum_price = housing_prices.min()
maximum_price = housing_prices.max()
mean_price = housing_prices.mean()
median_price = np.median(housing_prices)
standard_deviation = housing_prices.std()
def split_data(city_data):
"""Randomly shuffle the sample set. Divide it into 70 percent training and 30 percent testing data."""
X, y = city_data.data, city_data.target
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.3, random_state=0)
return X_train, y_train, X_test, y_test
def performance_metric(label, prediction):
return metrics.mean_squared_error(label, prediction)
def learning_curve(depth, X_train, y_train, X_test, y_test):
"""Calculate the performance of the model after a set of training data."""
# We will vary the training set size so that we have 50 different sizes
sizes = np.round(np.linspace(1, len(X_train), 50))
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))
print "Decision Tree with Max Depth: "
print depth
for i, s in enumerate(sizes):
regressor = DecisionTreeRegressor(max_depth=depth)
regressor.fit(X_train[:s], y_train[:s])
train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
learning_curve_graph(sizes, train_err, test_err)
def learning_curve_graph(sizes, train_err, test_err):
"""Plot training and test error as a function of the training size."""
pl.figure()
pl.title('Decision Trees: Performance vs Training Size')
pl.plot(sizes, test_err, lw=2, label = 'test error')
pl.plot(sizes, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Training Size')
pl.ylabel('Error')
pl.show()
def model_complexity(X_train, y_train, X_test, y_test):
"""Calculate the performance of the model as model complexity increases."""
print "Model Complexity: "
# We will vary the depth of decision trees from 2 to 25
max_depth = np.arange(1, 25)
train_err = np.zeros(len(max_depth))
test_err = np.zeros(len(max_depth))
for i, d in enumerate(max_depth):
regressor = DecisionTreeRegressor(max_depth=d)
regressor.fit(X_train, y_train)
train_err[i] = performance_metric(y_train, regressor.predict(X_train))
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
model_complexity_graph(max_depth, train_err, test_err)
def model_complexity_graph(max_depth, train_err, test_err):
"""Plot training and test error as a function of the depth of the decision tree learn."""
pl.figure()
pl.title('Decision Trees: Performance vs Max Depth')
pl.plot(max_depth, test_err, lw=2, label = 'test error')
pl.plot(max_depth, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Max Depth')
pl.ylabel('Error')
pl.show()
def fit_predict_model(city_data):
"""Find and tune the optimal model. Make a prediction on housing data."""
X, y = city_data.data, city_data.target
regressor = DecisionTreeRegressor()
parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}
scorer = metrics.make_scorer(performance_metric, greater_is_better=False)
reg = grid_search.GridSearchCV(regressor, parameters, scorer)
print "Final Model: "
print reg.fit(X, y)
x = [11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385, 24, 680.0, 20.20, 332.09, 12.13]
y = reg.predict(x)
print "House: " + str(x)
print "Prediction: " + str(y)
print "Best parameters: "
print reg.best_params_
def main():
"""Analyze the Boston housing data. Evaluate and validate the
performanance of a Decision Tree regressor on the housing data.
Fine tune the model to make prediction on unseen data."""
city_data = load_data()
explore_city_data(city_data)
X_train, y_train, X_test, y_test = split_data(city_data)
max_depths = [1,2,3,4,5,6,7,8,9,10]
for max_depth in max_depths:
learning_curve(max_depth, X_train, y_train, X_test, y_test)
model_complexity(X_train, y_train, X_test, y_test)
fit_predict_model(city_data)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
'''
SVM and KNearest digit recognition.
Sample loads a dataset of handwritten digits from 'digits.png'.
Then it trains a SVM and KNearest classifiers on it and evaluates
their accuracy.
Following preprocessing is applied to the dataset:
- Moment-based image deskew (see deskew())
- Digit images are split into 4 10x10 cells and 16-bin
histogram of oriented gradients is computed for each
cell
- Transform histograms to space with Hellinger metric (see [1] (RootSIFT))
[1] R. Arandjelovic, A. Zisserman
"Three things everyone should know to improve object retrieval"
http://www.robots.ox.ac.uk/~vgg/publications/2012/Arandjelovic12/arandjelovic12.pdf
Usage:
digits.py
'''
# built-in modules
from multiprocessing.pool import ThreadPool
import cv2
import numpy as np
from numpy.linalg import norm
# local modules
from common import clock, mosaic
import os
SZ = 20 # size of each digit is SZ x SZ
CLASS_N = 10
DIGITS_FN = 'digits.png'
def split2d(img, cell_size, flatten=True):
h, w = img.shape[:2]
sx, sy = cell_size
cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)]
cells = np.array(cells)
if flatten:
cells = cells.reshape(-1, sy, sx)
return cells
def load_digits(fn):
digits_img = cv2.imread(fn, 0)
digits = split2d(digits_img, (SZ, SZ))
labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
return digits, labels
def deskew(img):
m = cv2.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
return img
class StatModel(object):
def load(self, data_file):
this_dir = os.path.dirname(__file__)
data_file = os.path.join(this_dir, data_file)
if os.path.isfile(data_file):
self.model.load(data_file)
return True
return False
def save(self, fn):
self.model.save(fn)
class SVM(StatModel):
def __init__(self, data_file = None, C = 2.67, gamma = 5.383):
self.params = dict( kernel_type = cv2.SVM_RBF,
svm_type = cv2.SVM_C_SVC,
C = C,
gamma = gamma )
self.model = cv2.SVM()
def train(self, samples, labels):
self.model = cv2.SVM()
self.model.train(samples, labels, params = self.params)
def predict(self, samples):
return self.model.predict_all(samples).ravel()
def preprocess_hog(digits):
samples = []
for img in digits:
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy)
bin_n = 16
bin = np.int32(bin_n*ang/(2*np.pi))
bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists)
# transform to Hellinger kernel
eps = 1e-7
hist /= hist.sum() + eps
hist = np.sqrt(hist)
hist /= norm(hist) + eps
samples.append(hist)
return np.float32(samples)
|
#Data for the pokemon game
import time
import random as r
#import pygame as py
#Pokemon Class
class Pokemon():
"""Performs the tasks involving the player's information and the first
pokemonin the player list"""
def __init__(self,playerName,playerList):
self.playerName = playerName
self.playerList = playerList
#Get the various values for the first pokemon in the list
self.pokemonName = playerList[0][0]
self.health = playerList[0][1]
self.attack = playerList[0][2]
self.defence = playerList[0][3]
self.speed = playerList[0][4]
self.move1 = playerList[0][5]
self.move2 = playerList[0][6]
self.move3 = playerList[0][7]
self.move4 = playerList[0][8]
def __str__(self):
string = ("\nName:" + str(self.playerName)
+ "\nYour current Pokemon is:"
+ str(self.pokemonName) + "\nWith the following hp:"
+ str(self.health)+ "\nYour moves are:"
+ "\n1:" + str(self.move1) + "\n2:"
+ str(self.move2) + "\n3:" + str(self.move3)
+ "\n4:" + str(self.move4))
time.sleep(1)
return string
def getTeam(self):
"""Prints the initial list of each player with the three pokemon."""
print ("\n"+ str(self.playerName)+ ", Your pokemon are: ")
time.sleep(2)
for i in range (len(self.playerList)-1):
print (str(self.playerList[i][0])+", ")
print ("and "+ str(self.playerList[-1][0]))
def getPokemonName(self):
return self.pokemonName
def getHp(self):
return self.health
def selectMove(self,userInput):
while True:
try:
output = int(input(userInput))
if output == 1:
selectedMove = self.move1
elif output == 2:
selectedMove = self.move2
elif output == 3:
selectedMove = self.move3
elif output == 4:
selectedMove = self.move4
return selectedMove
except:
pass
def takeDamage(self, damageAmount=int, defendValue=int):
time.sleep(1)
dmg = damageAmount
if damageAmount >= defendValue:
dmg -= defendValue
elif damageAmount < defendValue:
dmg = 0
print(str(self.pokemonName)+ " takes "+
str(dmg)+ " damage.")
self.health -= dmg
def heal(self, healValue):
print("\n"+ str(self.pokemonName) +" healed for "
+str(healValue) + "HP.")
self.health += healValue
def atk(self,attackValue, accuracy=100):
time.sleep(1)
hitchance = r.randrange(0,100)
#Determine whether the move hits or misses
if hitchance <= accuracy:
print ("\n"+str(self.pokemonName)+ "'s move hit!")
damageAmount = attackValue
damageAmount += self.attack
elif hitchance > accuracy:
print (str(self.pokemonName)+ "'s move missed!")
#No damage if the move misses
damageAmount = 0
return damageAmount
def fainted(self):
#Determine whether the pokemon fainted
if self.health > 0:
state = False
if self.health <= 0:
state = True
return state
#End of pokemon class
#Sprite Class
class Sprite():
def __init__(self,sprite):
self.image = sprite
def draw(self,position,scr):
self.image.set_colorkey(BLACK)
scr.blit(self.image, [position[0],position[1]])
#Moveset = "Move":[[minValue,maxValue],"string",accuracy,True (if a healing move)
moveset = {"Earthquake":[[95,105],"95-105",100],
"MegaPunch": [[110,120],"110-120",85],
"Thunder": [[115,135],"115-135",75],
"MegaKick": [[115,125],"115-125",80],
"Recover": [[90,120],"(Heal) 90-125",100,True],
"Return": [[100,100],"100",100],
"Magnitude": [[40,180],"40-180",100],
"SoftBoiled": [[70,140],"(Heal) 75-140",100,True],
"BlastBurn": [[145,155],"145,155",50],
"HydroPump": [[120,120],"120",80],
"Blizzard": [[105,125],"105-125",85],
"JumpKick": [[100,110],"100-110",95],
"Psychic": [[95,115],"95-115",95],
"GunkShot": [[120,130],"120-130",75],
"BlazeKick": [[110,110],"110",90],
"StoneEdge": [[110,130],"110-130",80],
"HydroCannon": [[150,150],"150",100],
"HiddenPower": [[90,110], "90-110", 100],
"FocusBlast":[[120,140],"120-140",70],
"ShadowBall": [[105,105],"105",95],
"FrenzyPlant": [[140,160],"140-160",50]}
#End of moveset
#Set up the sprites
#List of pokemon
pokemonList = [ #[PokemonName, HP, Attackvalue, DefenseValue, Speed,Move1,Move2,Move3,Move4]
["Feraligatr", 270, 33, 27, 26,"HydroPump","HydroCannon","FocusBlast","Return"],
["Blaziken", 260, 35, 21, 27,"BlastBurn", "Earthquake", "BlazeKick", "JumpKick"],
["Venusaur", 260, 30, 29, 27,"FrenzyPlant","Recover","GunkShot","HiddenPower"],
["Snorlax", 420, 34, 27, 19, "Return", "MegaPunch","MegaKick","Recover"],
["Mew", 300, 32, 28, 32,"Psychic", "FocusBlast", "SoftBoiled", "HiddenPower"],
["Jolteon", 230, 33, 25, 38,"Thunder","HiddenPower","Return","FocusBlast"],
["Shuckle", 200, 20 , 50, 18,"StoneEdge","Earthquake","Recover","HiddenPower"],
["Blissey", 610,20 , 25, 20,"SoftBoiled","ShadowBall","Psychic","HiddenPower"],
["Pikachu", 200, 50, 16, 30,"Thunder", "MegaPunch", "MegaKick", "Return"],
["Hitmonlee", 200, 36, 26, 28,"JumpKick","StoneEdge","Earthquake","BlazeKick"],
["Aggron", 240, 34, 34, 20,"Earthquake","StoneEdge","MegaPunch","MegaKick"],
["Dragonite", 282, 37, 27, 27,"Blizzard","Earthquake","Thunder","StoneEdge"],
["Golemn", 260, 36, 28, 20,"Earthquake","StoneEdge","Magnitude","MegaKick"],
["Gengar", 220, 38, 19, 34,"ShadowBall","GunkShot","FocusBlast","Psychic"],
["Starmie", 259, 32, 25, 35,"Blizzard","Recover","HydroPump","Psychic"]]
#End of Pokemon List
|
primeiro = int(input('Primeiro numero: '))
segundo = int(input('Segundo numero : '))
terceiro = int(input('Terceiro numero: '))
# Achando o menor número
menor = primeiro
if (segundo < menor):
menor = segundo
if (terceiro < menor):
menor = terceiro
print('Menor: ', menor)
|
from Analysis import Evaluation
class SentimentLexicon(Evaluation):
def __init__(self):
"""
read in lexicon database and store in self.lexicon
"""
# if multiple entries take last entry by default
self.lexicon=dict([[l.split()[2].split("=")[1],l.split()] for l in open("data/sent_lexicon","r")])
self.predictions=[]
def classify(self,reviews,threshold,magnitude):
"""
classify movie reviews using self.lexicon.
self.lexicon is a dictionary of word: [polarity_info, magnitude_info], e.g. "bad": ["priorpolarity=negative","type=strongsubj"].
explore data/sent_lexicon to get a better understanding of the sentiment lexicon.
store the predictions in self.predictions as a list of strings where "+" and "-" are correct/incorrect classifications respectively e.g. ["+","-","+",...]
@param reviews: movie reviews
@type reviews: list of (string, list) tuples corresponding to (label, content)
@param threshold: threshold to center decisions on. instead of using 0, there may be a bias in the reviews themselves which could be accounted for.
experiment for good threshold values.
@type threshold: integer
@type magnitude: use magnitude information from self.lexicon?
@param magnitude: boolean
"""
# reset predictions
self.predictions=[]
# TODO Q0
for label, review in reviews:
positive = 0
negative = 0
if magnitude == True:
for word in review:
if word in self.lexicon:
if self.lexicon[word][5] == "priorpolarity=positive":
positive += 2
if self.lexicon[word][0] == "type=strongsubj":
positive += 1
elif self.lexicon[word][0] == "type=weaksubj":
positive -= 1
elif self.lexicon[word][5] == "priorpolarity=negative":
negative += 2
if self.lexicon[word][0] == "type=strongsubj":
negative += 1
elif self.lexicon[word][0] == "type=weaksubj":
negative -= 1
else:
for word in review:
if word in self.lexicon:
if self.lexicon[word][5] == "priorpolarity=positive":
positive += 1
elif self.lexicon[word][5] == "priorpolarity=negative":
negative += 1
if positive - negative > threshold:
result = "POS"
else:
result = "NEG"
if label == result:
#print "review prediction index", reviews_index
self.predictions.append("+")
else:
self.predictions.append("-")
#print "review prediction index", reviews_index
|
# Name: Kennedy Anukam
# Date: 2/29/20
# Class: CS 457
# Purpose: Handle insert query
import os
start_directory = os.getcwd()
def insert_table(command):
"""
function is used to insert to a table(file) from the in use database
Parameters:
command (string): Input of the query
Returns:
None
"""
# Get query in list format
temp = command[:-1].split()
if os.getcwd() == start_directory:
print("To select a table, use a database first")
elif len(temp) >= 4 and temp[0].lower() == "insert" and temp[1].lower() == "into" and "values" in temp[3].lower():
# Parse string to get data, getting file name before parsing
file_name = temp[2].upper() + ".txt"
temp = temp[3:]
temp[0] = temp[0][7:]
if len(temp) == 1:
#User put in no seperations
seperate = temp[0].split(",")
for i in range(len(seperate)):
seperate[i] = seperate[i].replace(',', '')
seperate[i] = seperate[i].replace(' ', '')
seperate[i] = seperate[i].replace("'", '')
seperate[i] = seperate[i].replace(")", '')
with open(file_name, "a") as f:
# Writing to file with string of data
f.write("\n" + ' '.join(seperate))
print("1 new record inserted.")
else:
# Loop to iterate through list and replace all occurences of ',' to '' and spaces to ''
for i in range(len(temp)):
temp[i] = temp[i].replace(',', '')
temp[i] = temp[i].replace(' ', '')
temp[i] = temp[i].replace("'", '')
temp[i] = temp[i].replace(")", '')
try:
with open(file_name, "a") as f:
# Writing to file with string of data
f.write("\n" + ' '.join(temp))
print("1 new record inserted.")
# Error thrown if the 'table' does not exist
except OSError:
print("File does not exist")
else:
print("Invalid syntax used to insert to the table, try again")
|
#!/usr/bin/python3
""" test user model """
import unittest
from models.base_model import BaseModel
from models.user import User
class TestUser(unittest.TestCase):
""" test user model"""
@classmethod
def setUp(cls):
"""steup class """
cls.user = User()
cls.user.first_name = "toor"
cls.user.last_name = "Holberton"
cls.user.email = "[email protected]"
cls.user.password = "rooty1"
cls.user.save()
def test_field_first_name(self):
""" test first name field"""
dummy_instance = User()
self.assertEqual(self.user.first_name, "toor")
self.assertIsInstance(self.user.first_name, str)
self.assertEqual(dummy_instance.first_name, "")
def test_field_last_name(self):
""" test last name field"""
dummy_instance = User()
self.assertEqual(self.user.password, "rooty1")
self.assertIsInstance(self.user.password, str)
self.assertEqual(dummy_instance.password, "")
def test_field_email(self):
"""test email field"""
dummy_instance = User()
self.assertTrue(self.user.email, "[email protected]")
self.assertIsInstance(self.user.email, str)
self.assertEqual(dummy_instance.email, "")
def test_field_password(self):
""" test password field """
dummy_instance = User()
self.assertEqual(self.user.last_name, "Holberton")
self.assertIsInstance(self.user.last_name, str)
self.assertEqual(dummy_instance.last_name, "")
def test_save_method(self):
"""test save method"""
dummy_instance = User()
dummy_instance.save()
self.assertNotEqual(
dummy_instance.created_at, dummy_instance.updated_at)
def test_class_user(self):
""" instance should be User; user should be subclass of BaseModel """
self.assertTrue(issubclass(User, BaseModel))
self.assertIsInstance(self.user, User)
@classmethod
def tearDownClass(cls):
"""clear everything"""
del cls.user.first_name
del cls.user.last_name
del cls.user.email
del cls.user.password
del cls.user
if __name__ == '__main__':
unittest.main()
|
#author: Pedro Goecking
#!-*- coding: utf8 -*-
pesca = input("Pesca (kg): ")
if calendar.isleap(ano) == True:
print 'É ano bissexto.'
else:
print 'Não é ano bissexto' |
import matplotlib.pyplot as plt
import numpy as np
# Generating simple data
t = np.linspace(0,4*np.math.pi,64)
y = np.sin(t)
z = np.cos(t)
w = np.tan(t)
# first, starting a figure
plt.figure(figsize=[6,6])
# first subplot
plt.subplot(221)
plt.plot(t, y, 'b-')
plt.title('Sine function')
plt.ylabel('sin(t)')
plt.xlabel('Angle t (radian)')
plt.axis([0,13,-1.1,1.1])
# second subplot
plt.subplot(222)
plt.plot(t, z, 'b-')
plt.title('Cosine function')
plt.ylabel('cos(t)')
plt.xlabel('Angle t (radian)')
plt.axis([0,13,-1.1,1.1])
# third subplot
plt.subplot(223)
plt.plot(t, w, 'b-')
plt.title('Tangent function')
plt.ylabel('tan(t)')
plt.xlabel('Angle t (radian)')
plt.axis([0,13,-1.1,1.1])
plt.show()
|
def depunct(inText, punctChars=',.?!;:/'):
outText = inText
for iChar in punctChars:
outText = outText.replace(iChar,'')
return outText
sampleText = '''This is a multi-line text.
This includes multiple sentences on multiple lines.
Some lines may be short.
However, other lines may be longer, containing a larger number of words.
You can split this text, line by line, using the split() method.
'''
print(depunct(sampleText))
|
age = 19
hand = 'left'
if (age<20) & (hand=='right'):
print('Meeting all the requirements.')
else:
if age<20:
print('Age requirement is met')
else:
print('None of the requirements is met')
# With if...elif...else statement
age = 19
hand = 'left'
if (age<20) & (hand=='right'):
print('Meeting all the requirements.')
elif age<20:
print('Age requirement is met')
else:
print('None of the requirements is met')
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
# loadin the data
pTraitData = pd.read_csv('personality0.txt', sep=' ')
featureNames = pTraitData.columns # list of features
# K-means clustering with 3 clusters
nClus = 3
km = KMeans(n_clusters=nClus)
km.fit(pTraitData) # fitting the principal components
y_clus = km.labels_ # clustering info resulting from K-means
# transforming the original features to 2-dimensional space
# applying PCA
pca = PCA(n_components=2) # creating a PCA transformation with 2 PCs
PC = pca.fit_transform(pTraitData) # fit the data, get 2 PCs
### plotting the clusters
# plotting PCs with clusters indicated
plt.scatter(PC[:,0], PC[:,1],c=y_clus,marker='+')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.title('Dimension reduced data with clusters')
plt.show()
|
weight = float(input('Please enter your weight (pounds): '))
height = float(input('Please enter your height (inches): '))
if (weight<=300) and (height<=78):
print('Requirements met!')
elif weight<=300:
print('Weight requirement met!')
elif height<=78:
print('Height requirement met!')
else:
print('Neither requirement met!')
|
import matplotlib.pyplot as plt
import numpy as np
# Generating simple data
t = np.linspace(0,4*np.math.pi,64)
y = np.sin(t)
# plot with title and axis labels
plt.plot(t, y, 'b-')
plt.title('Sine function')
plt.ylabel('sin(t)')
plt.xlabel('Angle t (radian)')
plt.show()
# The range of the axes are controlled now
plt.plot(t, y, 'b-')
plt.title('Sine function')
plt.ylabel('sin(t)')
plt.xlabel('Angle t (radian)')
plt.axis([0,13,-2,2])
plt.show()
|
age = 23
hand = 'right'
# evaluating the age requirement
if age>=18:
print('The age requirement is met')
# evaluating the handedness requirement
if hand=='right':
print('The handedness requirement is met')
|
from math import *
from Settings import *
def distance(x1, y1, x2, y2):
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
class point:
def __init__(self, x, y):
self.x = x
self.y = y
# rotates point around another point
def rotate(self, degrees, center):
angle = degrees * pi / 180
new_x = cos(angle) * (self.x - center.x) - sin(angle) * (self.y - center.y)
new_y = sin(angle) * (self.x - center.x) + cos(angle) * (self.y - center.y)
self.x = new_x + center.x
self.y = new_y + center.y
class movable:
def __init__(self, x, y, x_size, y_size, vx = 0, vy = 0):
self.x = x
self.y = y
self.x_size = x_size
self.y_size = y_size
self.vx = vx
self.vy = vy
def move(self):
self.x += self.vx
self.y += self.vy
def off_map(self):
if self.x + self.x_size < 0 or res_x + 150 < self.x - self.x_size:
return True
if self.y + self.y_size < 0 or res_y < self.y - self.y_size:
return True
return False
# shows text on screen
class text_window:
def __init__(self, x, y, width = 200, height = 150, text_list = [], timer = 240):
self.x = x
self.y = y
self.width = width
self.height = height
self.text_list = text_list
self.timer = timer
# adds text to queue
def add_text(self, text):
self.text_list.append( [font.render(str(text), False, (255,255,255)), self.timer, text] )
# shows texts on screen
def show_text(self, window):
position_y = self.y
for text in self.text_list:
position_x = self.x + self.width - len(text[2]) * 10 - 20
window.blit(text[0], (position_x, position_y))
position_y += font_size + 5
text[1] -= 1
if text[1] <= 0:
self.text_list.remove(text) |
#!/usr/bin/python
import sys
# Version using system arguments
#for word in sys.argv[1:]:
# print (word[::-1] == word)
# Words to test
words = [
"Oxo", "OXO", "123454321",
"ROTATOR", "12345 54321"
]
# Tests each word
for word in words:
print (word[::-1] == word) |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 16:24:48 2018
@author: Max Marder
"""
import random as rand
import math
def bucket(n, i_range):
# count number of succeses
count = 0
for i in range(i_range):
# frequerncy list of size n
freq = [0] * n
for j in range(n):
freq[math.floor(rand.uniform(0.0, 1.0) * n)] += 1
if all(p == 1 for p in freq):
count += 1
print("percent:", count/i_range * 100)
bucket(3, 10000) |
while True:
num1 = input("Ingrese Un Numero:")
num2 = input("Ingrese Otro Numero:")
res = float(num1) + float(num2)
print("La Suma Es:", res)
print("!Gracias!")
|
i = 0
while i < 5:
print('it\'s less than 5')
i += 1
else:
print('and now it\'s 5') # Print this message when the condition is no longer True
for i in range(1, 5):
if i == 3:
break
print(i)
else:
print("for loop is done")
print("Outside the for loop")
|
def contains_even_number(lst):
for i in lst:
if i % 2 == 0:
print(f"List {lst} contains an even number.")
break
else:
print(f"List {lst} does not contain an even number.")
contains_even_number([1, 9, 8])
contains_even_number([1, 3, 5]) |
number = 9
print(type(number)) # Print type of variable "number"
float_number = 9.0
print(type(float_number)) # Print type of variable "float_number"
print(float_number) # Print its value
converted_float_number = int(float_number)
print(type(converted_float_number)) # Print type of variable "converted_float_number"
print(converted_float_number) # Print its value
|
hello_world = "Hello, World!"
for character in hello_world: # Print each character from hello_world
print(character)
length = 0 # Initialize length variable
for character in hello_world:
length += 1 # Add 1 to the length on each iteration to count the characters
print(len(hello_world) == length)
|
import unittest
try:
from str_and_repr import Cat
class TestCase(unittest.TestCase):
def test_hasattr_repr(self):
cat = Cat('sphynx', 'Kitty')
actual_repr = repr(cat)
self.assertFalse('Cat object at' in actual_repr, msg='Method __repr__() is not defined for class Cat. If you copied the solution, please check the indentation.')
def test_hasattr_str(self):
cat = Cat('sphynx', 'Kitty')
actual_str = str(cat)
self.assertFalse('Cat object at' in actual_str, msg='Method __str__() is not defined for class Cat. If you copied the solution, please check the indentation.')
def test_str(self):
cat = Cat('sphynx', 'Kitty')
expected, actual = "My sphynx cat's name is Kitty", str(cat)
self.assertEqual(expected, actual, msg='Check your __str__() method.')
def test_repr(self):
cat = Cat('sphynx', 'Kitty')
expected, actual = "Cat, breed: sphynx, name: Kitty", repr(cat)
self.assertEqual(expected, actual, msg='Check your __repr__() method.')
except ImportError:
class TestFailCase(unittest.TestCase):
def test_fail(self):
self.assertTrue(False, msg='Please do not change class names.')
|
def multiply_by(a, b=2, c=1):
return a * b + c
print(multiply_by(3, 47, 0)) # Call function using custom values for all parameters
print(multiply_by(3, 47)) # Call function using default value for c parameter
print(multiply_by(3, c=47)) # Call function using default value for b parameter
print(multiply_by(3)) # Call function using default values for parameters b and c
print(multiply_by(a=7)) # Call function using default values for parameters b and c
def hello(subject, name="John"):
print(f"Hello {subject}! My name is {name}")
hello("PyCharm", "Jane") # Call "hello" function with "PyCharm as a subject parameter and "Jane" as a name
hello("PyCharm") # Call "hello" function with "PyCharm as a subject parameter and default value for the name
|
class City:
all_cities = []
def __init__(self, name, population, country):
self.name = name
self.population = population
self.country = country
self.add_city()
def add_city(self):
self.all_cities.append(self.name)
if __name__ == '__main__':
malaga = City('Malaga', 569005, 'Spain')
boston = City('Boston', 689326, 'USA')
beijing = City('Beijing', 21540000, 'China')
print(malaga.all_cities) # This should print "['Malaga', 'Boston', 'Beijing']".
|
texto = "String"
numero = 1
nulo = None
booleano = True or False
lista = ["a", "b", "c"]
dicionario = {
'chave_1': 'valor_1',
'chave_2': 'valor_2'
}
print texto
print numero
print nulo
print booleano
print lista
print dicionario
for i in range(10):
print 'ola'
|
txt = "hello,a." #1
x= txt.capitalize()
print (x)
txt = "hello,b" #2
x = txt.casefold()
print(x)
x = txt.center(20) #3
print(x)
x = txt.count("python") #4
print(x)
txt = "My name is Harsimran" #5
x = txt.encode()
print()
x = txt.endswith(".") #6
print(x)
txt = "H\ta\tr\tlrts" #7
x = txt.expandtabs(2)
print(x)
txt = "Hello, welcome to my world." #8
print(x)
x = txt.index("welcome") #9
print(x)
x = txt.isalpha() #10
print(x)
x = txt.lower() #11
print(x)
myTuple = ("har", "sim", "ran")
x = "#".join(myTuple)
print(x)
txt = "apple" #12
x = txt.ljust(20)
print(x, "is my favorite fruit.") #13
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
txt = "Hello my FRIENDS" #14
x = txt.lower()
print(x)
txt = "hi harsimran, how are u." #15
x = txt.rfind("casa")
print(x)
txt = "never, ever." #16
x = txt.rindex("casa")
print(x)
txt = "welcome to my world" #17
x = txt.split()
print(x)
x = txt.title() #18
print(x)
txt = "Hello my friends" #19
x = txt.upper()
print(x)
xt = "50" #20
x = txt.zfill(10)
print(x)
|
# DAS E Exam 15.04.2021
# Function
def counter(file, letter):
count = 0
for line in file:
#lower to catch all
line.lower()
for char in line:
if char == letter:
count += 1
return count
# Open file
file = open("RandomText.txt", "r")
print(counter(file,"p"))
|
# # rick_dict = {
# # 'first name':'Rick',
# # 'last name':'Sanchez'
# # }
# # print("The last name of rick is:", rick_dict['last name'])
#
# # my_list = [ 1,2,3,"rick", 5]
# #
# # obj=" "
# # i=0
# #
# # while obj != "rick":
# # obj= my_list[i]
# # print(obj)
# # i+=1
# # if obj=="rick":
# # break
# # DICTIONARY EXAMPLES
#
# my_animals = {
# "firstpet": "Fish",
# "secondpet": "dog",
# "thirdpet": "horse",
# }
#
# rose = {
# "height": 50,
# "petals":20,
# "color":"pink",
# "thorns": True
# }
#
# rose = {
# "height": 50,
# "petals":20,
# "color":"pink",
# "thorns": True
# }
#
# # print(rose["height"])
#
# print(f"{rose['height']} is the height and {rose['petals']} number of petals")
#
# pets_flowers = [my_animals,rose]
# print(f"{pets_flowers}")
#
# #modify data
#
# rose["color"] = "yellow"
# rose['shape'] = "vertical" # if you use a key that doesnt exist it will create it
# print(f"My favorite pet was my second pet which was my {my_animals['secondpet']} and my fave flower was rose because it was {rose['color']}")
# print(f"My favorite pet was my second pet which was my {my_animals['thirdpet']} and my fave flower was rose because it was {rose['color']}")
#
# i=1
# print("my fave flowers are:")
# for flower in pets_flowers
# print(f"My favorite pet was my second pet which was my {i['thirdpet']} and my fave flower was rose because it was {rose['color']}") ")
# i+=1
# SCREENSHOT TO CLARIFY
# for item in rose.keys(): #will always see the keys
# print(item, "-->", rose[item]) #to print keys next to values
#
# #UNPACKING
# # unpacking a container means splitting in to variables
#
#
# products={
# "computer":1000,
# "iphone": 2000,
# "Apple wheels":5000,
# "P55": 600
# }
# #ask the user how much money does he want to spend
# # #print every item that he can affort
# #
# # user_money =int(input(" how much money do you want to spend?"))
# # print("you can affort:")
# #
# # for product, price in products.items():
# # if price<=user_money:
# # print(f"{product}(£[price])")
#
# #make a dictionary called contact and add three of your friends with their phone number
#
# contacts = {
# "rick": "059768635",
# "morty": "058978676",
# "summer":"058976534"
# }
# # add another person manually
#
# contacts['emma']= '059873657'
# # print(contacts)
#
# #write a loop that print every conntact with his number
#
# for name, phone_nb in contacts.items():
# print(f"{name}:\t {phone_nb}")
#
# #write a code that searches if a given name exists in the contacts
# searched_name ="rick"
#
# for name in contacts.keys():
# if name.lower == searched_name.lower():
# print(f"{ We have had that that{name} before, this the same user?")
# if searched_name in contacts.keys():
# print()
#write a code that searches if a given number exists in contact, if it exists then print his name
# searched_number = '059873657'
# for name, phone_nb in contacts.items():
# if phone_nb == searched_number:
# print(f"{searched_number} We already have this number saved {phone_nb}it belongs to {name}")
#given another dictionary of contacts, add it to your dictionary
# rick_contacts = {
# "Hannah" : "-587876369",
# "jessica": " 0787654354"
# }
# for name, phone_nb in rick_contacts.items():
# contacts[name] =phone_nb
#
# # count how many contacts are in your dictionary
# nb_of_contacts =len(contacts.keys())
# print(f" There are {nb_of_contacts} contacts")
#
# # contacts.update(rick_contacts) #a fuction to do this for you
#
# #print the contacts in alphabetic order with their number
#
# sorted_contacts = sorted(contacts.keys())
# for contact in sorted_contacts:
# print(f"{contact} \t -> {contacts[contact]}")
# given two dicts
products_wallmart = {
"Computer": 1000,
"Iphone": 2000,
"Apple Wheels": 5000,
"PS5": 600
}
products_amazon = {
"Samsung Galaxy": 800,
"Computer": 1500,
"Apple Wheels": 3000,
"XBox": 600,
}
# print only the products that exist in both dictionaries, and the lowest price
# output should be:
# compuer(1000)
# Apple Wheela (3000)
for product in products_wallmart.keys():
if product in products_amazon.keys():
lowest_price = min(products_wallmart[product], products_amazon[product])
print(f"{product}(${lowest_price}") |
try:
month = str(input("Введите месяц (словом): "))
num = int(input("Введите число (числом): "))
except:
print("Невозможно обработать данные! Пожалуйста, введите данные, удовлетворяющие условиям!")
else:
if month == "март":
if (num >= 21) and (num <= 31):
print("Овен")
elif (num >= 1) and (num < 21):
print("Рыбы")
elif month == "апрель":
if (num >= 1) and (num < 21):
print("Овен")
elif (num >= 21) and (num <= 30):
print("Телец")
elif month == "май":
if (num >= 1) and (num < 22):
print("Телец")
elif (num >= 22) and (num <= 31):
print("Близнецы")
elif month == "июнь":
if (num >= 1) and (num < 22):
print("Близнецы")
elif (num >= 22) and (num <= 30):
print("Рак")
elif month == "июль":
if (num >= 1) and (num < 23):
print("Рак")
elif (num >= 23) and (num <= 31):
print("Лев")
elif month == "август":
if (num >= 1) and (num < 24):
print("Лев")
elif (num >= 24) and (num <= 31):
print("Дева")
elif month == "сентябрь":
if (num >= 1) and (num < 23):
print("Дева")
elif (num >= 23) and (num <= 30):
print("Весы")
elif month == "октябрь":
if (num >= 1) and (num < 23):
print("Весы")
elif (num >= 23) and (num <= 31):
print("Скорпион")
elif month == "ноябрь":
if (num >= 1) and (num < 23):
print("Скорпион")
elif (num >= 23) and (num <= 30):
print("Стрелец")
elif month == "декабрь":
if (num >= 1) and (num < 22):
print("Стрелец")
elif (num >= 22) and (num <= 31):
print("Козерог")
elif month == "январь":
if (num >= 1) and (num < 21):
print("Козерог")
elif (num >= 21) and (num <= 31):
print("Водолей")
elif month == "февраль":
if (num >= 1) and (num < 20):
print("Водолей")
elif (num >= 20) and (num <= 29):
print("Рыбы")
else:
print("Введены некорректные данные!") |
print("Введите четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, "
"потом для второй клетки: ", sep="\n")
try:
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
except:
print("Невозможно обработать данные! Пожалуйста, введите данные, удовлетворяющие условиям!")
else:
if (1 <= x1 <= 8) and (1 <= y1 <= 8) and (1 <= x2 <= 8) and (1 <= y2 <= 8):
if x2 != x1 and y2 != y1 and (x2 - y2 == x1 - y1 or x2 + y2 == x1 + y1):
print("YES")
else:
print("NO")
else:
print("Введены некорректные данные!") |
#!/usr/bin/env python3
import sys
input = " ".join(sys.argv[1:])
evaluated = eval(input)
decStr = evaluated
hexStr = hex(evaluated)
binStr = bin(evaluated)
print(decStr, hexStr, binStr, sep="\n", end="")
|
from random import choice
from random import randint
def rand_timesheet():
content = []
for _ in range(randint(1, 10)):
line = []
time = 0
for _ in range(randint(1, 3)):
a = rand_time(time, time + 3)
b = rand_time(time + 4, time + 7)
line.append(f"{a}-{b}")
time += 8
content.append(", ".join(line))
return "\n".join(content)
def rand_time(start, end):
time = f"{randint(start, end)}"
if randint(0, 1):
time += f":{choice(['00', '15', '30', '45'])}"
return time
#print rand_time(11:30,1)
|
passport_list = []
valid_passports = 0
with open('input.txt') as f:
passport_list = f.read().split('\n\n')
def check_valid(s):
rf = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
parts = s.split()
data = []
for part in parts:
p = part.split(':')
data.append(p)
for i in rf:
if i not in s:
return False
for field in data:
if field[0] == 'byr':
year = int(field[1])
if year < 1920 or year > 2002:
return False
elif field[0] == 'iyr':
year = int(field[1])
if year < 2010 or year > 2020:
return False
elif field[0] == 'eyr':
year = int(field[1])
if year < 2020 or year > 2030:
return False
elif field[0] == 'hgt':
if 'cm' in field[1] or 'in' in field[1]:
num = int(field[1][:-2])
else:
return False
if 'cm' in field[1]:
if num < 150 or num > 193:
return False
elif 'in' in field[1]:
if num < 59 or num > 76:
return False
else:
return False
elif field[0] == 'hcl':
color = field[1]
if color[0] != '#':
return False
elif len(color) != 7:
return False
allowed_chars = '1234567890abcdef'
color = color[1:6]
for c in color:
if c not in allowed_chars:
return False
elif field[0] == 'ecl':
allowed_colors = 'amb blu brn gry grn hzl oth'
if field[1] not in allowed_colors:
return False
elif field[0] == 'pid':
if len(field[1]) != 9:
return False
return True
for item in passport_list:
if check_valid(item):
valid_passports += 1
print(valid_passports)
|
# Using The Formula to Calculate Fibonacci Numbers
# Fn = {[(√5 + 1)/2] ^ n} / √5
# Reference: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html
# Time Complexity: O(1)
import math
def solution(n):
phi = (math.sqrt(5) + 1) / 2
fibonacci = math.pow(phi, n) / math.sqrt(5)
return round(fibonacci)
print(solution(23)) |
#####################################################
########## Advent of Code 2019 Day 01 ##############
#####################################################
import math
total_fuel = 0
file = open('C:\\Users\\ryan.jackson\\Desktop\\input.txt', 'r')
for module in file.readlines():
total_fuel += math.floor(int(module)/3) -2
print int(total_fuel)
|
# an Anylist is one of,
# - None
# - Pair (value, Anylist)
class Pair:
def __init__(self, first, rest):
self.first = first
self.rest = rest
def __eq__(self, other):
return ((type(other) == Pair)
and self.first == other.first
and self.rest == other.rest
)
def __repr__(self):
return ("Pair({!r}, {!r})".format(self.first, self.rest))
# None -> AnyList
# taking no arguments returns an empty list
def empty_list():
return None
# AnyList int val-> Anylist
# adds a value to a list for the given integer given index or return IndexError if index is < 0 or > len(list)
def add(al, idx, val):
if al is None:
if idx == 0:
return Pair(val, None)
else:
raise IndexError()
else:
if idx == 0:
return Pair(val, Pair(al.first, al.rest))
else:
return Pair(al.first, add(al.rest, idx - 1, val))
# AnyList -> int
# returns the number of elements in a linked list
def length(al):
if al is None:
return 0
else:
return 1 + length(al.rest)
# AnyList int -> val
# returns the value of the list at the given index
def get(al, idx):
if al is None:
raise IndexError()
else:
if idx == 0:
return al.first
else:
return get(al.rest, idx - 1)
# Anylist int val -> AnyList
# replaces the element at the specified index with the specified value
def set(al, idx, val):
if al is None:
raise IndexError()
else:
if idx == 0:
return Pair(val, al.rest)
else:
return Pair(al.first, set(al.rest, idx - 1, val))
# AnyList int -> val AnyList
# returns a tuple of the value removed at the specified index and the remaining list
def remove(al, idx, ret_val = "ret"):
if al is None:
raise IndexError()
else:
if idx == 0:
if ret_val == "list":
return al.rest
elif ret_val == "removed":
return al.first
elif ret_val == "ret":
return al.first, al.rest
else:
ret_list = Pair(al.first, remove(al.rest, idx -1, "list"))
removed_val = remove(al.rest, idx -1, "removed")
if ret_val == "ret":
return removed_val, ret_list
elif ret_val == "list":
return ret_list
elif ret_val == "removed":
return removed_val
def main(al, idx):
print(remove(al, idx))
|
#!/usr/bin/env python
# coding=utf-8
cars = 100
space_in_car = 4.0
drivers = 30
passenger = 90
cars_not_driven = cars - drivers
cars_driver = drivers
carpool_capacity = cars_driver * space_in_car
average_passengers_per_car = passenger / cars_driver
print ("There are",cars,"cars available")
print ("There are only ",drivers,"drivers available.")
print ("There will be ",cars_not_driven,"empty cars today.")
print ("We can transport",carpool_capacity,"people today.")
print ("We have",passenger,"to carpool today.")
print ("We need to put about",average_passengers_per_car,"in each car.")
|
# from turtle import*
# color("red")
# begin_fill()
# for i in range (4):
# forward(20)
# left(90)
# end_fill()
# mainloop()
# print (*range(1,21))
# print (*range (0,20,2))
# print(*range(100,1,-1))
# for i in range(1,21):
# print(i)
for i in range (1,10):
for j in range(1,10):
if i*j >9:
print(i*j, end = " ")
else:
print(i*j, end =" ")
print()
# for i in range (1,20,2):
# print(i, end=" ")
# circle(20)
# left(180)
# circle(20)
# left(60)
# circle(20)
# right(180)
# circle(20)
# right(120)
# circle(20)
# left(180)
# circle(20)
# mainloop() |
from turtle import*
forward (5)
backward(2)
left (90)
forward (2)
circle (50)
penup
forward (20)
pendown
circle(20)
mainloop()
# add at the end
print ('aaa')
print("hi",'3')
|
# Borno Kendley
# [email protected]
# instagram: @kendleyone
import random
print("Welcome to Rock-Paper-Scissors game\n")
print("Possibility: Rock-Paper-Scissors")
userScore = 0
computerScore = 0
Possibility = ["Rock", "Paper", "Scissor"]
def Play():
global userScore
global computerScore
if userChoice == "Rock" and computerChoice == "Paper":
print(f"Comuter choice: {computerChoice}")
print("Computer won")
computerScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
elif userChoice == "Rock" and computerChoice == "Scissor":
print(f"Comuter choice: {computerChoice}")
print("You won")
userScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
elif userChoice == "Paper" and computerChoice == "Rock":
print(f"Comuter choice: {computerChoice}")
print("You won")
userScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
elif userChoice == "Paper" and computerChoice == "Scissor":
print(f"Comuter choice: {computerChoice}")
print("Computer won")
computerScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
elif userChoice == "Scissor" and computerChoice == "Rock":
print(f"Comuter choice: {computerChoice}")
print("Computer won")
computerScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
elif userChoice == "Scissor" and computerChoice == "Paper":
print(f"Comuter choice: {computerChoice}")
print("You won")
userScore += 1
print(f"Score : You {userScore}-{computerScore} Computer\n")
else:
print(f"Comuter choice: {computerChoice}")
print("Same")
print(f"Score : You {userScore}-{computerScore} Computer\n")
while (userScore or computerScore) != 3:
userChoice = input("Make your choice: ")
computerChoice = random.choice(Possibility)
Play()
if(userScore == 2 and computerScore == 0) :
print("You are the winner")
break
elif computerScore == 2 and userScore == 0 :
print("Computer is the winner")
break
if (userScore or computerScore) == 3:
if (userScore > computerScore) :
print("You are the winner")
else :
print("Computer is the winner") |
# assigning variables time and day
time = '2:00a.m'
day = 'saturday'
#using the string.format method tocall thevariables
print("It is {} on a {}.".format(time,day)) |
#!/usr/bin/env python3
##
## EPITECH PROJECT, 2018
## Sans titre(Espace de travail)
## File description:
## data
##
"""
Data class
hold datas
"""
class Data:
"""Class that holds different data"""
def __init__(self):
self.avg = {
'crypto': -1,
'forex': -1,
'stock_exchange': -1,
'raw_material': -1
}
self.current = {
'crypto': -1,
'forex': -1,
'stock_exchange': -1,
'raw_material': -1
}
self.history = {
'crypto': [],
'forex': [],
'stock_exchange': [],
'raw_material': []
}
self.bought_price = {
'crypto': -1,
'forex': -1,
'stock_exchange': -1,
'raw_material': -1
}
def parse_data(self, data):
"""Store data in variables of the class"""
for elem in data:
for key in self.current:
if elem.split(':')[0] == key:
string = elem.split(':')[1].replace(',', '.')
value = float(string)
self.current[key] = value
self.history[key].append(value)
def get_bought_price(self, market):
"""
get_bought_price [summary]
Returns the price of the last market's share price bought
:param market: market's name
:type market: str
"""
return self.bought_price[market]
def get_prev_day(self, market):
"""
get_prev_day
Return previous day
:param market: market's name
:type market: str
:return: price of stock of previous day
:rtype: float
"""
try:
return self.history[market][-2]
except IndexError:
return -1
def get_current_day(self, market):
"""
get_current_day
Return current day
:param market: market's name
:type market: str
:return: price of current day's stock
:rtype: float
"""
return self.current[market]
def calc_avg(self):
"""
calc_avg
"""
for key in self.avg:
self.avg[key] = sum(self.history[key]) / len(self.history[key])
def __str__(self):
return 'crypto : {}\nforex : {}\n\
stock : {}\nraw : {}\n'.format(self.current['crypto'],
self.current['forex'],
self.current['stock_exchange'],
self.current['raw_material'])
|
import random as r # module
import time as t
guesstimes = 0
while True:
number = r.randint(0, 100)
time1 = int(t.time())
while True:
guess = int(input("Enter a number between 0 and 100: "))
if guess == number:
print("You guessed right!")
guesstimes += 1
break
elif guess > number:
print("Your guess was too high. Guess again!")
guesstimes += 1
elif guess < number:
print("Your guess was too low. Guess again!")
guesstimes += 1
else:
print("Invalid input, guess again.")
guesstimes += 1
time2 = int(t.time())
time3 = time2 - time1
print("It took you", guesstimes, "guesses.")
print("The number was", number, ".")
print("It took you", time3, "seconds.")
break
|
#!/usr/bin/python
length=5
breadth=2
area=length*breadth
print 'Areais',area
print 'Perimeter is',2*(length+breadth)
|
import re
def eval_plus(x):
while m := re.search("\d+ \+ \d+", x):
x = x.replace(m.group(), str(eval(m.group())), 1)
return x
def eval_all(x):
while m := re.search("\d+ [\+\-\*\/] \d+", x):
x = x.replace(m.group(), str(eval(m.group())), 1)
return x
def eval_expr(x, evaluate):
while m := re.search("\([^\(\)]+\)", x):
m = m.group(0)
x = x.replace(m, eval_expr(m[1:-1], evaluate), 1)
return evaluate(x)
def part1(input):
total = 0
for x in input:
x = eval_expr(x, lambda x: eval_all(x))
total += int(x)
return total
def part2(input):
total = 0
for x in input:
x = eval_expr(x, lambda x: eval_all(eval_plus(x)))
total += int(x)
return total
def main():
with open("18.in") as f:
input = [l.strip() for l in f.readlines()]
print(part1(input))
print(part2(input))
if __name__ == "__main__":
main()
|
# Chapter 4 Homework 4-7
odd_numbers = list(range(3, 30, 3))
for odd_number in odd_numbers:
print(odd_number) |
# Chapter 3 Homework 3-4
names = [ "Hezz", "Eli", "Jay"]
message = f" {names[0]}, you are invited to dinner today at 6:00."
print(message)
message = f" {names[1]}, you are invited to dinner today at 6:00."
print(message)
message = f" {names[2]}, you are invited to dinner today at 6:00."
print(message)
|
# Chapter 4 Homework 4-1
pizzas = [ "pepperoni pizza", "cheese pizza", "garlic pizza"]
for pizza in pizzas:
print(f"I like {pizza.title()}")
print("I love Pizza") |
# Chapter 2 homework 2-4
name = "jackson the gamer"
print(name.upper())
print(name.lower())
print(name.title()) |
# Chapter 5 Homework 5-4
alien_color = ["green", "yellow", "red"]
if "green" in alien_color:
print("\nYou get 5 points")
else: "red" in alien_color
print("\nYou get 10 points")
print("*****************************************")
if "yellow" in alien_color:
print("you get 15 points")
if "blue" in alien_color:
print("\nYou get -5 points")
if "red" in alien_color:
print("\nYou get 10 points")
print("*****************************************")
if "pruple" in alien_color:
print("You get -10 points")
elif "blue" in alien_color:
print("\nYou get -5 points")
else: "green" in alien_color
print("\nYou get 5 points") |
"""
Functions for preprocessing the data, before classification
"""
from numpy import bincount, array, min, zeros, nonzero, where, sum
from settings import NCLASSES
def obtain_class_weights(true_classes, weight_calc = "inverted"):
"""
Given the true classes of some samples, gives a vector of sample weights.
The sample weight is a function of the prior probabity of the class the sample belongs to
By default, the weight is set to inverted, which means the weight is 1 over the prior probability
This ensures that every class has the same total weight. For now, this is also the only possibility,
but more can be added
:param true_classes: the true classes of some samples
"""
def inverted(priorprob):
return 1.0 / priorprob
funcDict = {"inverted" : inverted}
weightFunc = funcDict[weight_calc]
priorprobs = bincount(true_classes, minlength = NCLASSES)
priorprobs = priorprobs / sum(priorprobs).astype(float)
newprobs = array([weightFunc(priorprobs[true_classes[i]]) for i in range(len(true_classes))])
factor = sum(newprobs) / len(newprobs)
return newprobs / factor
def equalize_class_sizes(data, classes):
"""
Equalize classes by removing samples to make them all the same size.
:param min_size: The number of samples to use for each class.
:return: trimmmed data and classes.
"""
classsizes = bincount(classes)
print(classsizes)
min_size = min(classsizes[nonzero(classsizes)]) #ignore classes with 0 entries
print(min_size)
filter = zeros(classes.shape, dtype = bool)
for cls in range(1, NCLASSES + 1):
this_cls = where(classes == cls)[0][:min_size]
filter[this_cls] = True
return data[filter], classes[filter]
if __name__ == '__main__':
#print undersample(array([[1,2],[2,3],[4,5],[3,2],[3,1],[2,9],[4,6]]), array([1,2,2,1,2,3,4]))
print "tests later pls" |
on# This file generates the BinarySearch pattern and puts it in the ../Patterns folder.
import math
import Helper
# 100, 0 --> 50
# 100, 1 --> 25, 50, 75
# 100, 2 --> 12, 25, 37, 50, 62, 75, 87
def binary_search_points(length, depth):
return binary_search_aux(floor(length / 2), floor(length / 4),
def binary_search_aux(pivot, amount, min_amount):
if amount <= min_amount:
return []
points = [pivot + amount, pivot - amount]
return points + binary_search_aux(pivout + amount, floor(amount / 2)) + binary_search_aux(pivot - amount, floor(amount / 2))
def generate_pattern():
"""
output = ""
on_lights = []
frequency = 75
for i in range(0,math.ceil(math.log(150,2))):
output += Helper.instruction_for_pixels(on_lights)
Helper.write_pattern("BinarySearch",output)
"""
print "Binary search was not generated"
if __name__ == '__main__':
print "Generating BinarySearch..."
generate_pattern()
|
#need to make it so it returns the whole file, not just the line, into a list.
#creating function to read file, split it at the end of a line, and close file
def f():
try:
fin = open('CustomerList.txt')
contents = fin.read()
lines = contents.split('\n')
fin.close()
return lines
except:
print'An error occured while opening file'
#setting file to list
z = f()
data = list(z)
print data
#creating color class
class color:
BLUE = '\033[34m'
RED = '\033[91m'
BOLD = '\033[1m'
END = '\033[0m'
menu_choice = 0
#creating def for selection 1
def choice_one(data):
try:
y = 'Y'
n = 'N'
id = raw_input('Please Enter User ID: ')
for item in data:
userid, first, last, street, city, state, code, phone = item.split(',')
if id == userid:
print 'Customer ID: ' + userid
print 'Customer Name: ' + first, last
print 'Address: ' + street, city, state, code
print 'Phone Number: ' + phone
confirm = raw_input('Confirm (Y/N)')
if confirm == y:
quit()
elif confirm == n:
quit()
break
except:
print 'Customer could not be found. Goodbye.'
#creating def for selection 2
def choice_two(data):
#get first name
fn = raw_input("Please enter first name: ")
first_name = fn.title()
while len(first_name) < 1 or not str.isalpha(first_name):
first_name = raw_input(color.BOLD + color.RED + "First name is required, please re-enter." + color.END)
#get their last name
ln = raw_input("Please enter last name: ")
last_name = ln.title()
while len(ln) < 1 or not str.isalpha(ln):
ln = raw_input(color.BOLD + color.RED + "Last name is required, please re-enter." + color.END)
#get street address
street = raw_input('Please enter street address: ')
st = street.title()
while len(street) < 1:
street = raw_input('Invalid entry. Please re-enter: ')
#get city
city = raw_input('Please enter city: ')
c = city.title()
while city < 1:
city = raw_input('Invalid entry. Please re-enter: ')
#get state abbreviation
state = (raw_input('Please enter state abbreviation: '))
s = state.upper()
while len(state) < 1 and len(state) > 2:
state = raw_input('Invalid. Enter state abbreviation ')
#get zip code
zc = raw_input('Plese enter zip code: ')
while len(zc) <5 and len(zc) > 5:
zc = raw_input('Invalid entry. Enter a 5 digit zip code: ')
#get phone number
ph = raw_input('Please enter phone number; digits only: ')
while len(ph) < 10 or len(ph)> 10:
ph = raw_input('Please enter a vilid 10 digit number: ')
#create user id
newid = (data[-2:-1][0]).split(',')
new = str(newid[:1]).strip("[']")
l = list(new)
l[-4:] = ""
customer = "".join(l)
n = int(customer) + 1
cph = str(n) + (ph[-4:])
info = cph+ first_name+ last_name+ st + c + s + zc, ph
info = list(''.join(info))
customer_info = list(info)
customer_info = ''.join(customer_info)
print customer_info
#creating user output
print 'Customer Information: '
print (first_name), last_name
print st
print c + ', ' + s + ', ' + zc
print ph
print color.BLUE + 'You have been added to our system. Your customer ID is: ' + cph + color.END
return (customer_info)
#creating def for selection 3
def choice_three():
print color.BLUE + "Welcome! Please create a new User to use this kiosk." + color.END + "\n"
#creating selection screen function for when user inputs an invalid option
def menu_2():
menu_choice = 0
while menu_choice >= 0:
print "==========================="
print " 1. " + color.RED + "Existing User" + color.END
print " 2. " + color.RED + "Add new User" + color.END
print " 3. " + color.RED + "Continue as Guest" + color.END
print "==========================="
choice =raw_input(color.BOLD + color.RED + 'Choose from the available options: ' + color.END + '\n')
if choice.strip() not in ['1', '2', '3']: #testing for good values as strings
print(color.BOLD + color.RED + 'Invalid selection, re-enter' + color.END)
menu_choice = 0 #reset to invalid value
else:
menu_choice = int(choice) #if its good convert to int
if menu_choice == 1:
choice_one(data)
quit()
elif menu_choice == 2:
info = [(choice_two(data))]
customer = ''.join(data + info)
with open('CustomerList.txt', 'wb') as fin:
for line in customer:
fin.write(line)
fin.write("\n")
fin.close()
quit()
elif menu_choice == 3:
choice_three()
quit()
#creating initial main selection screen
while menu_choice >= 0:
print ("\n" + color.BOLD+ 'Self Service Customer Kiosk' + color.END + "\n")
print color.BLUE + "==========================="
print " 1. " + color.END + "Existing User" + color.BLUE
print " 2. " + color.END + "Add new User" + color.BLUE
print " 3. " + color.END+ "Continue as Guest" + color.BLUE
print "===========================" + color.END
choice =raw_input('Please choose from the above options: ' + '\n')
if choice.strip() not in ['1', '2', '3']: #testing for good values as strings
print color.BOLD + color.RED + 'Invalid selection, re-enter: ' + color.END
menu_2()
else:
menu_choice = int(choice) #if its good convert to int
if menu_choice == 1:
choice_one(data)
menu_choice = -1
elif menu_choice == 2:
info = [(choice_two(data))]
customer = ''.join(data + info)
with open('CustomerList.txt', 'wb') as fin:
for line in customer:
fin.write(line)
fin.write("\n")
fin.close()
quit()
menu_choice = -1
elif menu_choice == 3:
choice_three()
menu_choice = -1
|
#construtor and destructor are optional.
#The constructor is typically to set up the varibales.
class Partyanimal:
x = 0
name = ''
#constructor with addition parameters z
def __init__(self,z):
self.name = z
print('I am constructed', self.name) # called when object created
#method
def party(self):
self.x = self.x +1
print('%s so far %d :'% (self.name,self.x))
#destructor
def __del__(self):
print(self.name,' am destructed ',self.x)
cn = Partyanimal('cn') #create a object and set up instance varible
an = Partyanimal('an') #create a object and set up instance varible
an.party() #call method
an.party()
cn.party()
an = 42 #destruct the object and reassign 42 into an variable
print('an contains ', an)
print(type(cn))
|
'''
Task
You are given a string .
Your task is to print all possible size replacement combinations of the string in lexicographic sorted order.
Input Format
A single line containing the string and integer value separated by a space.
Constraints
The string contains only UPPERCASE characters.
Output Format
Print the combinations with their replacements of string on separate lines.
Sample Input
HACK 2
Sample Output
AA
AC
AH
AK
CC
CH
CK
HH
HK
KK
'''
from itertools import combinations_with_replacement
word, r = input().split()
to_p = tuple(combinations_with_replacement(sorted(word), int(r)))
for word in to_p: print(''.join(word))
|
'''
https://www.hackerrank.com/challenges/countingsort4/problem
'''
import math
import os
import random
import re
import sys
def countSort(arr):
first_half = arr[:len(arr)//2]
first_half_val = set([b for a,b in first_half])
result = ['' for x in range(100)]
for i, item in enumerate(arr):
it, val = item
if (val in first_half_val) and (i<len(arr)//2):
result[int(it)] = result[int(it)]+' -'
else:
result[int(it)] = result[int(it)]+' '+val
result = [x.strip() for x in result if len(x)>0]
print(' '.join(result))
if __name__ == '__main__':
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(input().rstrip().split())
countSort(arr)
|
'''
https://www.hackerrank.com/challenges/picking-numbers/problem
'''
import math
import os
import random
import re
import sys
def pickingNumbers(a):
kl = []
j = []
a.sort()
for val in a:
if len(j)==0:
j.append(val)
continue
elif abs(min(j)-val)<=1:
j.append(val)
else:
kl.append(j)
j=[val,]
kl.append(j)
return max(map(len, kl))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
result = pickingNumbers(a)
fptr.write(str(result) + '\n')
fptr.close()
|
'''
https://www.hackerrank.com/challenges/s10-interquartile-range/problem
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
_ = int(input())
v1 = list(map(int, input().split()))
v2 = list(map(int, input().split()))
vals = []
for it, v in enumerate(v1):
vals.extend([v]*v2[it])
vals = sorted(vals)
n = len(vals)
def odd(values):
return values[(len(values)-1)//2]
def even(values):
return (values[len(values)//2]+ values[((len(values))//2)-1])/2
if n%2==1:
if (n//2)%2==1:
q1 = odd(vals[:(n//2)])
q3 = odd(vals[n//2+1:])
else:
q1 = even(vals[:(n-1)//2])
q3 = even(vals[((n-1)//2)+1:])
else:
if (n//2)%2==1:
q1 = odd(vals[:(n//2)])
q3 = odd(vals[(n//2):])
else:
q1 = even(vals[:(n)//2])
q3 = even(vals[((n)//2):])
print(float(q3-q1))
|
'''
https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
'''
import math
import os
import random
import re
import sys
import string
alph = string.ascii_lowercase
dicty = dict(zip(alph, range(26)))
# Complete the designerPdfViewer function below.
def designerPdfViewer(h, word):
k = []
for val in set(word):
k.append(h[dicty[val]])
return (len(word)*max(k))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
h = list(map(int, input().rstrip().split()))
word = input()
result = designerPdfViewer(h, word)
fptr.write(str(result) + '\n')
fptr.close()
|
'''
You are given a set and number of other sets. These number of sets have to perform some specific mutation operations on set .
Your task is to execute those operations and print the sum of elements from set .
Input Format
The first line contains the number of elements in set .
The second line contains the space separated list of elements in set .
The third line contains integer , the number of other sets.
The next lines are divided into parts containing two lines each.
The first line of each part contains the space separated entries of the operation name and the length of the other set.
The second line of each part contains space separated list of elements in the other set.
len(set(A))
len(otherSets)
Output Format
Output the sum of elements in set .
Sample Input
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52
4
intersection_update 10
2 3 5 6 8 9 1 4 7 11
update 2
55 66
symmetric_difference_update 5
22 7 35 62 58
difference_update 7
11 22 35 55 58 62 66
Sample Output
38
'''
_=input()
setA = set(map(int, input().split()))
for val in range(int(input())):
operation = input().split()[0]
setB = set(map(int, input().split()))
if operation=='intersection_update':
setA = setA & setB
elif operation=='update':
setA = setA | setB
elif operation=='symmetric_difference_update':
setA = setA ^ setB
else:
setA = setA - setB
print(sum(setA))
|
'''
https://www.hackerrank.com/challenges/repeated-string/problem
'''
import math
import os
import random
import re
import sys
def repeatedString(s, n):
length = len(s)
if n<=length:
return s[:n].count('a')
elif n%length==0:
return s.count('a')*(n//len(s))
else:
first = s.count('a')*(n//len(s))
second = s[:n%len(s)].count('a')
return (first+second)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
n = int(input())
result = repeatedString(s, n)
fptr.write(str(result) + '\n')
fptr.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.