text
stringlengths 37
1.41M
|
---|
# --- python is strongly typed
# lets verify that every object has a definite type
for obj in [1, True, 2.5, "hello", [1, 2, 3], {1: "one", 2: "two"}]:
# hints:
# 1. print is your buddy
# 2. https://docs.python.org/3/library/functions.html#type
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
# --- python is dynamically typed - adding new code
# can you change the code so that 'new_code' will be added and executed?
new_code = "print('where the hell this line came from?')"
# hints:
# 1. https://docs.python.org/3/library/functions.html#eval
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
# --- python is dynamically typed - extend objects
# now make student instance having also 'gender' attribute with value 'male'
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("jhon", 27)
# hints:
# 1. setting an object attribute is similar to accessing it
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
print("student %s is %s" % (student.name, student.gender))
|
# given a dict 'd', return a new dict with all duplicated values removed. keep the smallest key of duplications.
# for example, for the dict {1: 'a', 2: 'a', 3: 'b'} return {1: 'a', 3: 'b'}
from pprint import pprint
def remove_duplicates(d):
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
pprint(remove_duplicates({'one': 1,
'two': 2,
'three': 3,
'first': 1,
'second': 2,
'third': 3,
'ONE': 1,
'TWO': 2,
'THREE': 3}))
# given a text file - 'file', load it and return its words count (in dict form)
# make sure to handle special characters and ignore words case
def word_count(file):
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
pprint(word_count('input.txt'))
|
# print 10 literal in decimal base
print(10)
# print 10 literal in binary base
print(0b10)
# print 10 literal in hexadecimal base
print(0x10)
# convert to int
f = 1.5
print(int(f))
# convert to int
s = "121"
print(int(s))
# fill in objects_as_bool with the truth value of objects in 'objects'
objects = [0, 12, 0.0, -1.5, [], [1, 2], "", "False", None]
objects_as_bool = [False, True, False, True, False, True, False, True, False]
for obj, obj_as_bool in zip(objects, objects_as_bool):
print(f"bool({obj}) is {bool(obj)} --> "
f"{'good!' if obj_as_bool is bool(obj) else 'try again!'}")
# now modify Connection class so that open connections truth value is True otherwise False
class Connection:
def __init__(self):
self.is_open = False
def open_conn(self):
self.is_open = True
def __bool__(self):
return self.is_open
conn = Connection()
if not conn:
print("conn is closed, opening...")
conn.open_conn()
if conn:
print("conn is now open")
|
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
#import numpy as np
import pandas as pd
st.title('My first app')
st.write("well hello there")
df = pd.DataFrame({
'first column': ['pink', 'white', 'blue', 'black']
})
option = st.selectbox(
'choose a color',
df['first column'])
if option == 'pink':
#'pink background'
st.write('pink background')
elif option == 'black':
'black background'
elif option == 'white':
'white background'
elif option == 'blue':
'blue background'
x=st.slider("slide me ",0.0,500.0,600.00)
'you selected',x
y=st.text_input("text") |
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
button1 = 16
button2 = 12
LED1 = 11
LED2 = 13
GPIO.setup(button1, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(button2, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(LED1, GPIO.OUT)
GPIO.setup(LED2, GPIO.OUT)
BS1 = False
BS2 = False
while(1):
if GPIO.input(button1) == 0:
print "Button 1 was Pressed"
if BS1 == False:
GPIO.output(LED1, 1)
BS1 = True
sleep(.5)
else:
GPIO.output(LED1, 0)
BS1 = False
sleep(.5)
if GPIO.input(button2) == 0:
print "Button 2 was Pressed"
if BS2 == False:
GPIO.output(LED2, 1)
BS2 = True
sleep(.5)
else:
GPIO.output(LED2, 0)
BS2 = False
sleep(.5)
|
from tkinter import *
def newFile():
pass
def openFile():
pass
def SaveFile():
pass
def quitApp():
pass
def cut():
pass
def copy():
pass
def paste():
pass
def about():
pass
if __name__ == '__main__':
#Basic tkinter setup
root=Tk()
root.title("Untitled-Notepad")
root.geometry("655x333")
#Add TextArea
# text=Text(root,font="lucida 13")
# text.pack()
# file=None
#creating a menu bar
MenuBar=Menu(root)
# File menu Starts
fileMenu=Menu(MenuBar,tearoff=0)
# To open new file
fileMenu.add_command(label="New",command=newFile)
# To open already exsisting file
fileMenu.add_command(label="Open",command=openFile)
# To save the current file
fileMenu.add_command(label="Save", command=SaveFile)
fileMenu.add_separator()
fileMenu.add_command(label="exit",command=quitApp)
MenuBar.add_cascade(label="File",menu=fileMenu)
# File menu ends
# Edit menu starts
editMenu=Menu(MenuBar,tearoff=0)
# Cut, copy and paste
editMenu.add_command(label="Cut",command=cut)
editMenu.add_command(label="Copy",command=copy)
editMenu.add_command(label="Paste",command=paste)
MenuBar.add_cascade(label="Edit",menu=editMenu)
# Edit menu Ends
# Help menu Starts
helpMenu=Menu(MenuBar,tearoff=0)
helpMenu.add_command(label="About Notepad",command=about)
MenuBar.add_cascade(label="Help",menu=helpMenu)
# Help menu Ends
root.config(menu=MenuBar)
root.mainloop() |
#a new new library for you, just like turtle or math, it is a standard python library
#it is used for pretty print, in this case we use it to print a multi-level dict
import pprint
def daily_earning_spening_dictionary(file_path):
transaction_file = open(file_path, "r")
#initialize the dict
daily_summary = {}
#loop through each line in the file, you knew this, I ciopied from your code
for line in transaction_file:
#we know each line has three fields, so we split them into three variables and give each a meaningful name
(person, date, amount) = line.split(',')
#first you to to check whether the person is in the dict, and handle different
if person in daily_summary: #the person is already in the dict
#next we need to check whether that date already exists for that person
if date in daily_summary[person]:
#notice the syntax we used to reference an element in a dict of dict? pretty straight forward right?
#the date already exist, so we add
daily_summary[person][date] += float(amount)
else:
#the date is not there, so this is the first time this date appeared for this person
#we can not add, instead just initialize it
daily_summary[person][date] = float(amount)
#look at the matching if above, this else means this person is not in the dict, so we initialize
else:
daily_summary[person] = {date: float(amount)}
#always a good behabit to close what you opened, look professional
transaction_file.close()
#return the dict we formed
return daily_summary
#get the dict back from the function call and saved it to a variable
daily_summary = daily_earning_spening_dictionary("data/transactions.txt")
#initialize the pretty printer, set the indent to 4, you will see what it does when you run the program
pretty_printer = pprint.PrettyPrinter(indent=4)
#actually print the dict
pretty_printer.pprint(daily_summary)
#this is the usual print, just want to show you the difference compared to pretty print
#pretty printer is much better right? help you to actually understand what is in the dict
print(daily_summary) |
import sqlite3
import json
conn = sqlite3.connect("mycontacts.db")
cur = conn.cursor()
with open("./data/fake_data/dataNov-7-2020.json", "r") as fh:
data = json.load(fh)
for contact in data:
address = f"{contact['street']}, {contact['city']}, " \
f"{contact['country']}, {contact['zipcode']}"
contact["address"] = address
for contact in data[:30]:
cur.execute("""
insert into 'People' (First_Name, Last_Name, Phone_no, Email_ID, Address)
values (?, ?, ?, ?,?)
""", (contact["first name"], contact["surname"], contact["Ph no"], contact["email"], contact["address"]))
conn.commit()
print("---- Sucessfully Inserted ----") |
# Approach #1 Using Recursion
# Time Limited Exceed
class Solution_Rec(object):
def PredictTheWinner(self,nums):
return self.helper(nums,0,len(nums)-1,1)>=0
def helper(self,nums,s,e,turn):
if s==e:
return turn*nums[s]
a =turn*nums[s]+self.helper(nums,s+1,e,-1*turn)
b =turn*nums[e]+self.helper(nums,s,e-1,-1*turn)
return turn*max(turn*a,turn*b)
# Approach # 2 Using Recursion with memory
class Solution_Rec_Memo(object):
def PredictTheWinner(self,nums):
memory = [[0]*len(nums) for _ in range(len(nums))]
return self.helper(nums,0,len(nums)-1, memory)>=0
def helper(self,nums,s,e,memory):
if s==e:
return nums[s]
if memory[s][e] != 0:
return memory[s][e]
a = nums[s] - self.helper(nums,s+1,e,memory)
b = nums[e] - self.helper(nums,s,e-1,memory)
memory[s][e] = max(a,b)
return memory[s][e]
# Approach #3 Dynamic Programming with 2-D Memory
class Solution_DP_2D(object):
def PredictTheWinner(self,nums):
dp = [[0]*len(nums) for _ in range(len(nums)+1)]
for s in range(len(nums)-2,-1,-1):
for e in range(s+1,len(nums)):
a = nums[s]-dp[s+1][e]
b = nums[e]-dp[s][e-1]
dp[s][e] = max(a,b)
return dp[0][len(nums)-1]>=0
# Appraoch #4 Dyanmic Programming with 1-D Memory
# Keep the row
class Solution(object):
def PredictTheWinner(self,nums):
dp = [0]*len(nums)
for s in range(len(nums)-2,-1,-1):
for e in range(s+1,len(nums)):
a = nums[s]-dp[e]
b = nums[e]-dp[e-1]
dp[e] = max(a,b)
return dp[len(nums)-1] >=0
obj = Solution()
res = obj.PredictTheWinner([1,5,233,7])
print(res) |
'''
O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um
conjunto indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas
informadas, bem como a média das temperaturas.
'''
num = int(input("Informe quantas temperaturas são:"))
print("")
temperatura = eval(input("Informe a temperatura:"))
Maior = 0
Menor = temperatura
soma = temperatura
for x in range(1, num):
temperatura = eval(input("Informe a temperatura: "))
if (temperatura > Maior):
Maior = temperatura
elif (temperatura < Menor):
Menor = temperatura
soma += temperatura
print("")
media = soma / num
print("A menor temperatura é: ", Menor)
print("A maior temperatura é: ", Maior)
print("A média das temperaturas é: ", media)
|
'''
Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade
de turmas e a quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos.
'''
turma = int(input("Digite a quantidade de turmas: "))
print("")
soma = 0
for a in range(1, turma +1):
alunos = int(input("Digite a quantidade de alunos por turma: "))
while (alunos > 40):
print("As turmas não podem ter mais de 40 alunos!")
alunos = int(input("Digite a quantidade de alunos por turma: "))
soma = soma + alunos
a = a + 1
print("")
media = soma / turma
print("Numero médio de alunos: ", media)
|
'''
Os números primos possuem várias aplicações dentro da Computação, por exemplo na Criptografia. Um
número primo é aquele que é divisível apenas por um e por ele mesmo. Faça um programa que peça um
número inteiro e determine se ele é ou não um número primo.
'''
num = int(input("Digite um número inteiro: "))
x = 2
a = 0
while (x < num):
if (num % x == 0):
a = 0
x = num
else:
x = x + 1
a = 1
if (a == 1 or num == 2):
print("O número", num, "é primo!")
else:
print("O número", num, "não é primo!")
|
import random
import numpy as np
import pandas as pd
def convert_to_zodiac(day, month):
if (month == 3 and day > 20) or (month == 4 and day < 21):
return "Aries"
elif (month == 4 and day > 20) or (month == 5 and day < 21):
return "Taurus"
elif (month == 5 and day > 20) or (month == 6 and day < 22):
return "Gemini"
elif (month == 6 and day > 21) or (month == 7 and day < 23):
return "Cancer"
elif (month == 7 and day > 22) or (month == 8 and day < 24):
return "Leo"
elif (month == 8 and day > 23) or (month == 9 and day < 24):
return "Virgo"
elif (month == 9 and day > 23) or (month == 10 and day < 24):
return "Libra"
elif (month == 10 and day > 23) or (month == 11 and day < 23):
return "Scorpio"
elif (month == 11 and day > 22) or (month == 12 and day < 22):
return "Sagittarius"
elif (month == 12 and day > 21) or (month == 1 and day < 21):
return "Capricorn"
elif (month == 1 and day > 20) or (month == 2 and day < 19):
return "Aquarius"
elif (month == 2 and day > 18) or (month == 3 and day < 21):
return "Pisces"
if __name__ == "__main__":
n_records = 500
zodiacs = np.zeros((n_records, 3), dtype=object)
for i in range(n_records):
day, month = random.randint(1, 31), random.randint(1, 12)
zodiacs[i, :] = day, month, convert_to_zodiac(day, month)
pd.DataFrame(zodiacs, columns=['day', 'month', 'zodiac']).to_csv('zodiacs.csv')
|
import numpy as np
def gradient_descent(x, y):
m_curr = b_curr = 0
iterations = 1105
n = len(x)
learning_rate = 0.0670032 # tweak as you go to make cost better
# m 2.000000000006345, b 2.9999999999770908, cost 1.0000080525120793e-22, iteration 1104
for i in range(iterations):
y_predicted = m_curr * x + b_curr
cost = (1 / n) * sum([val ** 2 for val in (y - y_predicted)])
md = -(2 / n) * sum(x * (y - y_predicted))
bd = -(2 / n) * sum(y - y_predicted)
m_curr = m_curr - learning_rate * md
b_curr = b_curr - learning_rate * bd
print("m {}, b {}, cost {}, iteration {}".format(m_curr, b_curr, cost, i))
# numpy array is good for marice multiplication and faster than normal list
x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 7, 9, 11, 13])
gradient_descent(x, y)
|
__author__ = 'Brad'
class Flight():
"""
Stores the flight information such as origin, destination, departure and arrival times, duration, and stops
"""
def __init__(self, origin, dest, depart, arrive, duration, stops):
self.origin = origin
self.dest = dest
self.depart = depart
self.arrive = arrive
self.duration = duration
self.stops = stops
|
# monopoly is responsible for:
# running the game
# turn-by-turn mechanics
# asking the player for input
# check to see if legal move
# ask player for strat (returns TRUE or FALSE)
# if player says yes, ask player to do thing (player doesn't check anything)
# state variable
import json
import random
from random import randint, shuffle
from board import Board
from player import Player
flag = False # set to True to turn on debug messages
class Monopoly(object):
"""
Monopoly class, represents entirety of game
"""
def __init__(self, players, debug_flag=flag):
"""
:type players: Player() subclass
"""
if len(players) < 2:
raise Exception("num_players must be greater than 1")
shuffle(players) # shuffle order of players for moves
self.board = Board()
self.num_players = len(players)
self.players = players
for player in players:
player.board = self.board
player.other_players = [p for p in players if p != player]
# active_players don't include bankrupt players
self.active_players = players
# which Player has next move
self.player_turn = 0
self.is_over = False # true if game is over
self.winner = None
self.chance_jail_owner = None
self.shuffle_chance_cards()
self.community_chest_jail_owner = None
self.shuffle_community_chest_cards()
self.debug_flag = debug_flag
############################
# #
# OTHER HELPERS #
# #
############################
def debug(self, message):
if self.debug_flag:
print message
def return_years(self):
years = []
for player in self.players:
years.append(player.years)
return years
############################
# #
# RUN #
# #
############################
def run(self, turns=-1):
while len(self.active_players) > 1 and turns != 0:
turns -= 1
self.make_move()
self.is_over = True
self.debug("--------------------Game finished---------------------")
if turns == 0:
self.debug("\nNo one wins :(")
else:
if len(self.active_players) > 1:
raise Exception("This shouldn't happen")
self.winner = self.active_players[0]
self.debug("\n%s wins!" % self.winner.name)
############################
# #
# TURN MECHANICS #
# #
############################
@staticmethod
def roll_dice():
return randint(1, 6), randint(1, 6)
def use_get_out_of_jail_free_card(self, player):
if player != self.chance_jail_owner or player != self.community_chest_jail_owner:
return False # doesn't own one
if player == self.chance_jail_owner:
player.in_jail = False
self.chance_jail_owner = None
self.chance_cards.insert(0, 7) # add the card to the back of the deck
elif player == self.community_chest_jail_owner:
player.in_jail = False
self.community_chest_jail_owner = None
self.community_chest_cards.insert(0, 5)
return True
# game consists of N moves until all but one player is bankrupt
def make_move(self):
self.player_turn = self.player_turn % len(self.active_players)
player = self.active_players[self.player_turn]
self.debug("******** {0}'s turn ********".format(player.name))
self.player_turn = self.player_turn + 1
if player.in_jail:
# TODO: use community chest, should be part of the jail strategy
# if player == self.chance_jail_owner or player == self.community_chest_jail_owner:
# if self.use_get_out_of_jail_free_card(player):
# successfully used it, now roll
# self.roll_and_move(player, dice)
# return
dice = self.roll_dice()
if player.leave_jail(dice):
self.roll_and_move(player, dice)
else:
self.roll_and_move(player)
return player
def roll_and_move(self, player, dice=None, turn=1):
if dice is None:
dice = self.roll_dice()
if turn == 3 and dice[0] == dice[1]:
player.go_to_jail()
else:
prev_position = player.position
player.move(dice[0] + dice[1])
self.do_square_action(player, prev_position)
if dice[0] == dice[
1] and not player.in_jail and not player.bankrupt: # first doubles, roll again if not in jail
self.roll_and_move(player, turn=turn + 1)
# chance flag is true if we are performing an action after being moved there via a chance card
def do_square_action(self, player, prev_position, chance=False):
square = self.board.squares[player.position]
self.debug("Landed on {1}".format(player.name, square.name))
# if pass GO, get $200
if player.position < prev_position:
self.change_player_balance(player, 200)
# do nothing jail, free parking squares
if player.position in (0, 10, 20):
return
# if go to jail, go to jail
if player.position == 30:
player.go_to_jail()
# if land on income or luxury tax, pay tax
elif player.position == 4 or player.position == 38:
player.pay_tax(square)
# if land on owned property, pay rent
elif square.owner and square.owner is not player:
self.debug("Paying rent to {0}".format(square.owner.name))
if self.on_utility(player):
dice = self.roll_dice() # reroll dice for the utility
roll = dice[0] + dice[1]
if chance == True:
# chance card: utilities have to pay 10 * roll
player.pay_player(square.owner, 10 * roll, track=True, square=square)
elif self.board.squares[12].owner and self.board.squares[28].owner:
# both utilities are owned (not necessarily by the same person), pay 10 * roll
player.pay_player(square.owner, 10 * roll, track=True, square=square)
else:
# only one utility is owned, pay 4 * roll
player.pay_player(square.owner, 4 * roll, track=True, square=square)
elif self.on_railroad(player):
railroads_owned = self.railroads_owned(square.owner)
if chance == True:
# chance card: have to pay double the normal railroad rent
player.pay_rent(square, multiple=(railroads_owned * 2))
else:
player.pay_rent(square, multiple=railroads_owned)
else: # normal rent
player.pay_rent(square)
# if land on unowned property, do strat
elif square.owner is None:
if self.on_purchasable(player) and player.purchase_square(square):
self.debug("Purchased")
# if land on chance, pick card and do card
elif self.on_chance(player):
self.do_chance_card(player)
elif self.on_community_chest(player):
self.do_community_chest_card(player)
# check if player is bankrupt, if so remove
if player.bankrupt:
self.debug("Bankrupt!")
player.liquidate()
self.active_players = filter(lambda x: x.name != player.name, self.active_players)
else:
while player.purchase_from_banks(self.get_purchasable_buildings(player)):
self.debug("Purchased from banks")
self.debug("Balance: {0}".format(player.balance))
def change_player_balance(self, player, amount):
if amount >= 0:
player.balance += amount
else:
player.do_strat_raise_money(-1 * amount)
def shuffle_chance_cards(self):
self.chance_cards = range(1, 16)
if self.chance_jail_owner != None:
self.chance_cards.remove(7) # remove get out of jail card
random.shuffle(self.chance_cards)
def shuffle_community_chest_cards(self):
self.community_chest_cards = range(1, 17)
if self.community_chest_jail_owner != None:
self.community_chest_cards.remove(5)
random.shuffle(self.community_chest_cards)
def do_chance_card(self, player):
if len(self.chance_cards) == 0:
self.shuffle_chance_cards()
card = self.chance_cards.pop()
prev_position = player.position
if card == 1:
# Advance to Go (Collect $200)
player.position = 0
self.change_player_balance(player, 200)
elif card == 2:
# Advance to Illinois Ave. - If you pass Go, collect $200
player.position = 24
self.do_square_action(player, prev_position, chance=True)
elif card == 3:
# Advance to St. Charles Place - If you pass Go, collect $200
player.position = 11
self.do_square_action(player, prev_position, chance=True)
elif card == 4:
# Advance token to nearest Utility. If unowned, you may buy it from the Bank. If owned, throw dice and pay owner a total ten times the amount thrown.
if player.position > 28:
player.position = 28
else:
player.position = 12
self.do_square_action(player, prev_position, chance=True)
elif card == 5:
# Advance token to the nearest Railroad and pay owner twice the rental to which he/she is otherwise entitled. If Railroad is unowned, you may buy it from the Bank.
if player.position > 35:
player.position = 35
elif player.position > 25:
player.position = 25
elif player.position > 15:
player.position = 15
else:
player.position = 5
self.do_square_action(player, prev_position, chance=True)
elif card == 6:
# Bank pays you dividend of $50
self.change_player_balance(player, 50)
elif card == 7:
# Get out of Jail Free - This card may be kept until needed, or traded/sold
if self.chance_jail_owner == None:
self.chance_jail_owner = player
elif card == 8:
# Go Back 3 Spaces"
player.position = prev_position - 3
self.do_square_action(player, prev_position, chance=True)
elif card == 9:
# Go to Jail - Go directly to Jail - Do not pass Go, do not collect $200
player.go_to_jail()
elif card == 10:
# Make general repairs on all your property - For each house pay $25 - For each hotel $100
to_pay = 0
for property in player.properties:
if property.num_buildings == 5:
to_pay -= 100
else:
to_pay -= property.num_buildings * 25
self.change_player_balance(player, to_pay)
elif card == 11:
# Pay poor tax of $15
self.change_player_balance(player, -15)
elif card == 12:
# Take a trip to Reading Railroad - If you pass Go, collect $200
player.position = 5
self.do_square_action(player, prev_position, chance=True)
elif card == 13:
# Take a walk on the Boardwalk - Advance token to Boardwalk
player.position = 39
self.do_square_action(player, prev_position, chance=True)
elif card == 14:
# You have been elected Chairman of the Board - Pay each player $50
for p in self.active_players:
player.pay_player(p, 50)
elif card == 15:
# Your building and loan matures - Collect $150
self.change_player_balance(player, 150)
elif card == 16:
# You have won a crossword competition - Collect $100
self.change_player_balance(player, 100)
def do_community_chest_card(self, player):
if len(self.community_chest_cards) == 0:
self.shuffle_community_chest_cards()
card = self.community_chest_cards.pop()
prev_position = player.position
if card == 1:
# Advance to Go (Collect $200)
player.position = 0
self.change_player_balance(player, 200)
elif card == 2:
# Bank error in your favor - Collect $200
self.change_player_balance(player, 200)
elif card == 3:
# Doctor's fees - Pay $50
self.change_player_balance(player, -50)
elif card == 4:
# From sale of stock you get $50
self.change_player_balance(player, 50)
elif card == 5:
# Get out of Jail Free - This card may be kept until needed, or traded/sold
if self.community_chest_jail_owner == None:
self.community_chest_jail_owner = player
elif card == 6:
# Go to Jail - Go directly to Jail - Do not pass Go, do not collect $200
player.go_to_jail()
elif card == 7:
# Grand Opera Night - Collect $50 from every player for opening night seats
for p in self.active_players:
p.pay_player(player, 50)
elif card == 8:
# Holiday Fund matures - Receive $100
self.change_player_balance(player, 100)
elif card == 9:
# Income tax refund - Collect $20
self.change_player_balance(player, 20)
elif card == 10:
# It is your birthday - Collect $10 from each player
for p in self.active_players:
p.pay_player(player, 10)
elif card == 11:
# Life insurance matures - Collect $100
self.change_player_balance(player, 100)
elif card == 12:
# Pay hospital fees of $100
self.change_player_balance(player, -100)
elif card == 13:
# Pay school fees of $150
self.change_player_balance(player, -150)
elif card == 14:
# Receive $25 consultancy fee
self.change_player_balance(player, 25)
elif card == 15:
# You are assessed for street repairs - $40 per house - $115 per hotel
to_pay = 0
for property in player.properties:
if property.num_buildings == 5:
to_pay -= 115
else:
to_pay -= property.num_buildings * 40
self.change_player_balance(player, to_pay)
elif card == 16:
# You have won second prize in a beauty contest - Collect $10
self.change_player_balance(player, 10)
elif card == 17:
# You inherit $100
self.change_player_balance(player, 100)
############################
# #
# INTEGRITY CHECK #
# #
############################
# call remove by name, since list(self.board.get_color_group(square.color)) changes the reference to squares
@staticmethod
def remove_square_by_name(name, squares):
for s in squares:
if s.name == name:
squares.remove(s)
break
return squares
# number houses on properties of any given color cannot differ by more than 1
# should return the set of squares for which houses are possible
def check_purchase_house(self, square, player):
if self.board.avail_houses > 0 and player.balance > square.price_build:
if square.color not in player.owned_colors:
return False
if square.num_buildings >= 4: # can only upgrade to hotel
return False
other_color_squares = list(self.board.get_color_group(square.color))
other_color_squares = self.remove_square_by_name(square.name, other_color_squares)
for s in other_color_squares:
if abs(square.num_buildings + 1 - s.num_buildings) > 1:
return False
return True
return False
# should return the set of squares for which hotels are possible
def check_purchase_hotel(self, square, player):
if self.board.avail_hotels > 0 and player.balance > square.price_build:
if square.color not in player.owned_colors:
return False
if square.num_buildings != 4: # must have 4 to purchase hotel
return False
other_color_squares = list(self.board.get_color_group(square.color))
other_color_squares = self.remove_square_by_name(square.name, other_color_squares)
for s in other_color_squares:
if abs(square.num_buildings + 1 - s.num_buildings) > 1:
return False
return True
return False
def check_sell_house(self, square, player):
if square.owner == player:
if square.num_buildings <= 0:
return False
other_color_squares = list(self.board.get_color_group(square.color))
other_color_squares.remove(square)
for s in other_color_squares:
if abs(square.num_buildings - 1 - s.num_buildings) > 1:
return False
return True
return False
def check_sell_hotel(self, square, player):
if square.owner == player:
if square.num_buildings != 5:
return False
other_color_squares = list(self.board.get_color_group(square.color))
other_color_squares.remove(square)
for s in other_color_squares:
if abs(square.num_buildings - 1 - s.num_buildings) > 1:
return False
return True
return False
def check_mortgage_square(self, square, player):
if square.owner == player:
if square.num_buildings != 0:
return False
return True
return False
############################
# #
# HELPERS #
# #
############################
def on_utility(self, player):
return self.board.squares[player.position].type == "utility"
def on_railroad(self, player):
return self.board.squares[player.position].type == "Railroad"
def on_chance(self, player):
return self.board.squares[player.position].type == "Chance"
def on_community_chest(self, player):
return self.board.squares[player.position].type == "Chest"
def on_street(self, player):
return self.board.squares[player.position].type == "Street"
def on_purchasable(self, player):
return self.on_street(player) or self.on_utility(player) or self.on_railroad(player)
def railroads_owned(self, player):
owned = 0
if self.board.squares[5].owner == player:
owned += 1
if self.board.squares[15].owner == player:
owned += 1
if self.board.squares[25].owner == player:
owned += 1
if self.board.squares[35].owner == player:
owned += 1
return owned
def get_purchasable_buildings(self, player):
return [square for square in player.properties
if self.check_purchase_house(square, player)
or self.check_purchase_hotel(square, player)]
############################
# #
# STATE #
# #
############################
def clean_caps(self):
for square in self.board.squares:
square.clean_cap()
# print square.caps
def get_caps(self):
self.clean_caps()
return [(square.name, square.caps) for square in self.board.squares]
# Reads in a JSON transcript and returns a new Monopoly instance
@classmethod
def set_state(self, transcript):
if transcript:
m = Monopoly()
data = open(transcript).read()
data = json.loads(data)
m.board = Board()
m.board.avail_houses = data["board"]["avail_houses"]
m.board.avail_hotels = data["board"]["avail_hotels"]
m.active_players = [Player(data["players"][i]["name"]) for i in xrange(data["num_players"])]
m.player_turn = data["player_turn"]
m.is_over = data["is_over"]
m.winner = data["winner"]
for i, player in enumerate(m.active_players):
player.balance = data["players"][i]["balance"]
player.net_value = data["players"][i]["net_value"]
player.in_jail = data["players"][i]["in_jail"]
player.position = data["players"][i]["position"]
player.bankrupt = data["players"][i]["bankrupt"]
for property in data["players"][i]["properties"]:
square = next((x for x in m.board.squares if x.name == property["name"]), None)
if square:
square.num_buildings = property["num_buildings"]
player.properties.append(square)
return m
else:
raise Exception("Must pass in a transcript JSON file")
# Takes current Monopoly game and optionally creates a pretty-printed JSON file that
# can be loaded using Monopoly.set_state()
# returns the dict
def save_state(self, output_file=False, transcript="transcript.json"):
data = {}
data["player_turn"] = self.player_turn
data["is_over"] = self.is_over
data["winner"] = self.winner
data["board"] = {}
data["board"]["avail_houses"] = self.board.avail_houses
data["board"]["avail_hotels"] = self.board.avail_hotels
data["players"] = []
for player in self.active_players:
player_data = {}
player_data["name"] = player.name
player_data["balance"] = player.balance
player_data["net_value"] = player.net_value
player_data["in_jail"] = player.in_jail
player_data["position"] = player.position
player_data["bankrupt"] = player.bankrupt
player_data["properties"] = []
for property in player.properties:
property_data = {}
property_data["name"] = property.name
property_data["num_buildings"] = property.num_buildings
player_data["properties"].append(property_data)
data["players"].append(player_data)
if output_file:
with open(transcript, 'w') as outfile:
json.dump(data, outfile, indent=2)
return data
|
from monopoly.player import Player
class GreedyPlayer(Player):
# buy all the houses/hotels as possible
def do_strat_buy_from_bank(self, bldgs):
if bldgs:
self.explain("Building " + bldgs[0].name + " up -- as well as any other building -- as soon as possible")
return bldgs[0]
else:
return None
# sell properties to raise money, in no particular order
def do_strat_raise_money(self, money):
while self.properties and self.balance < money:
p = self.properties.pop()
self.explain("Selling " + p.name + "because we need the money and we don't really care which properties we own")
if p.num_buildings == 0:
p.owner = None
self.balance += p.price
elif p.num_buildings == 5:
self.sell_hotel(p)
else:
self.sell_house(p)
if self.balance < money:
self.bankrupt = True
return self.balance
self.balance -= money
return money
# always buy unowned properties if landed
def do_strat_unowned_square(self, square):
if square.price < self.balance:
self.explain("Buying " + square.name + " because we buy everything")
return True
# needs better logic
def do_strat_get_out_of_jail(self, d):
# TODO: use get out of jail cards
if d[0] == d[1]: # roll doubles
return True
if self.jail_duration >= 3:
self.jail_duration = 0
self.in_jail = False
if d[1] != d[0]:
self.do_strat_raise_money(50)
self.explain("Leaving jail after our third turn (mandatory)")
return True
else:
self.explain("Staying in jail because we don't know any better")
self.jail_duration += 1
return False
|
"""Expresiones Booleanas."""
def es_vocal_if(letra: str) -> bool:
"""Toma un string y devuelve un booleano en base a si letra es una vocal o
no.
Restricción: Utilizar un if para cada posibilidad con la función lower().
Referencia: https://docs.python.org/3/library/stdtypes.html#string-methods
"""
letra = letra.lower()
if letra == "a":
return True
if letra == "e":
return True
if letra == "i":
return True
if letra == "o":
return True
if letra == "u":
return True
return False
# NO MODIFICAR - INICIO
assert es_vocal_if("a")
assert not es_vocal_if("b")
assert es_vocal_if("A")
# NO MODIFICAR - FIN
###############################################################################
def es_vocal_if_in(letra: str) -> bool:
"""Re-escribir utilizando un sólo IF y el operador IN.
Referencia: https://docs.python.org/3/reference/expressions.html#membership-test-operations
"""
if letra.lower() in "aeiou":
return True
return False
# NO MODIFICAR - INICIO
assert es_vocal_if_in("a")
assert not es_vocal_if_in("b")
assert es_vocal_if_in("A")
# NO MODIFICAR - FIN
###############################################################################
def es_vocal_in(letra: str) -> bool:
"""Re-escribir utilizando el operador IN pero sin utilizar IF."""
return letra.lower() in "aeiou"
# NO MODIFICAR - INICIO
assert es_vocal_in("a")
assert not es_vocal_in("b")
assert es_vocal_in("A")
# NO MODIFICAR - FIN
|
# Coded by Stephanie Callejas
# Last Edit: 12 Nov 2018
# CS2302 Lab 4 B Project
# Instructors: Diego Aguirre and Saha, Manoj Pravakar
# Goal: Determine if a given anagram is a valid word in the english language using hash tables
# f is used to populate the tree with the words
f = open("words.txt")
word_list = f.readlines()
for i in range(len(word_list)):
word_list[i] = word_list[i][:-2] # -2 to get rid of the enter space
counter = 0
def print_anagrams(word, prefix=""):
if len(word) <= 1:
str = prefix + word
if str in word_list:
print(prefix + word)
else:
for i in range(len(word)):
cur = word[i: i + 1]
before = word[0: i] # letters before cur
after = word[i + 1:] # letters after cur
if cur not in before: # Check if permutations of cur have not been generated.
print_anagrams(before + after, prefix + cur)
# HashTable class using chaining.
class ChainingHashTable:
# Constructor with optional initial capacity parameter.
# Assigns all buckets with an empty list.
def __init__(self, initial_capacity=10):
# initialize the hash table with empty bucket list entries.
self.table = []
for i in range(initial_capacity):
self.table.append([])
# Inserts a new item into the hash table.
def insert(self, item):
# get the bucket list where this item will go.
bucket = hash(item) % len(self.table)
bucket_list = self.table[bucket]
# insert the item to the end of the bucket list.
bucket_list.append(item)
# Searches for an item with matching key in the hash table.
# Returns the item if found, or None if not found.
def search(self, key):
# get the bucket list where this key would be.
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# search for the key in the bucket list
if key in bucket_list:
# find the item's index and return the item that is in the bucket list.
item_index = bucket_list.index(key)
return bucket_list[item_index]
else:
# the key is not found.
return None
# Removes an item with matching key from the hash table.
def remove(self, key):
# get the bucket list where this item will be removed from.
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# remove the item from the bucket list if it is present.
if key in bucket_list:
bucket_list.remove(key)
# Overloaded string conversion method to create a string
# representation of the entire hash table. Each bucket is shown
# as a pointer to a list object.
def __str__(self):
index = 0
s = " --------\n"
for bucket in self.table:
s += "%2d:| ---|-->%s\n" % (index, bucket)
index += 1
s += " --------"
return s
# A modulo hash uses the remainder from division of the key by hash table size N.
def hash_remainder(self,key,N):
return key % N
# A binary mid-square hash function extracts the middle R bits,
# and returns the remainder of the middle bits divided by hash table size N,
def hash_midsquare(self, key, N, R):
squared_key = key * key
lowbits_toremove = (32 - R) / 2
extracted_bits = squared_key >> lowbits_toremove
extracted_bits = extracted_bits & (0xFFFFFFFF >> (32 - R))
return extracted_bits % N
# Load factor calculated
def load_factor(self):
counter = 0
for i in range(len(self.table)):
temp = self.table
while temp is not None:
counter += 1
temp = temp.next
print("Current load factor:" + (counter/len(self.table)))
# count = 0
# for i in range(i < self.table):
# count += self.table
# load_factor = count / len(self.table)
# print("Current Load factor = " + load_factor);
|
tupla = 1, 2, 3, 4,'Hola',3.2
print (tupla[3])
#la tupla no puede cambiar sus valores asignados
diccionario = {'nombre': 'Juan','apellido': 'López'}
usuario = {'nombre':'Pedro', 'apellido': 'Sanchez'}
lista = [diccionario, usuario]
print(diccionario['nombre'])
print (lista[1:2])
#crear llave nueva
usuario ['correo']= "[email protected]"
for registro in lista:
registro ['nombre']= input("ingresa el nombre")
print(lista[:])
#diccionario imprime con un for
#las listas contienen diccionarios
#Agregar valores al diccionario
#dato={}
#dato['nombre'] = input("ingresa un nombre ")
|
class priorityQueue(object):
def __init__(self):
self.list = []
self.size = 0
def getSize(self):
return self.size
def placeToInsert(elem, list):
mid = len(list)//2
if list[mid] == elem :
return mid
if list[mid] < elem :
return placeToInsert(elem, list[:mid])
else:
return placeToInsert(elem, list[mid:])
def insert(self, elem):
if elem == None:
return 0
else:
if self.list[0] > elem:
index = 0
elif self.list[self.size-1] < elem:
index = self.size - 1
else:
index = placeToInsert(elem, self.list)
self.list.insert(index, elem)
# def remove(self, elem):
# if elem in self.list:
# self.list.remove(elem)
# return 1
#
# return 0
def pop(self):
if self.size > 0:
return self.list.pop(0)
return 0
|
import chess
def move():
turn = 0
board = chess.Board('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1')#initialize the board
print(board)
while board.legal_moves != 0:# the game will end if there's no legal move for one player
turn = turn +1
print('{} round'.format(turn))
#b = board.piece_map() #where the piece is<a dictionary>
if turn%2 != 0:
print('white turn')
else:
print('black turn')
a = board.legal_moves
print(a)
i = input('your current move')
move = chess.Move.from_uci(str(board.parse_san(i)))
board.push(move)
print(board)
return(i)
def main():
n = 1
while n:
turn = move()
if turn%2 !=0:
print('black win')
else:
print('white win')
n = 0
new = input('type 1 if you want to start a new game')
if new == 1:
n = 1
main() |
import sqlite3
from tkinter import *
def insert_into_db(name,email,password):
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
c.execute('create table if not exists users (user_id integer primary key autoincrement, username text, email text, password text)')
query = """INSERT INTO users (username,email,password) VALUES (?,?,?)"""
c.execute(query,(name,email,password))
conn.commit()
c.execute('select * from users')
print(c.fetchall())
conn.close()
def check_login(Email,Pwd):
#print(Email,' ',Pwd)
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
select_query = """SELECT * FROM users WHERE email = ? AND password= ? """
c.execute(select_query,(Email,Pwd))
record = c.fetchone()
print(record)
conn.close()
if type(record) is tuple:
return True
else:
return False
#print(check_login('fghj','dfvbnm'))
|
"""
Given a word w and a string s, find all indices in s which are the starting locations of anagrams of w. For example, given w is "ab" and s is "abxaba", return [0, 3, 4]
"""
w = input()
s = input()
len_s = len(s)
len_w = len(w)
res = []
def is_anagram(first, second, n):
first_array = [0] * 26
second_array = [0] * 26
for i in range(n):
first_array[ord(first[i]) - 97] += 1
second_array[ord(second[i]) - 97] += 1
return first_array == second_array
for i in range(len_s - len_w + 1):
tmp = s[i:i+len_w]
if is_anagram(w, tmp, len_w):
res.append(i)
print(res)
|
import sys # de system, para hablar con el intérprete, que en este caso es python
argumentos = sys.argv
# aquí van a estar las palabras despues de python
# nos va a dar una array (lista) con unas serie de argumentos posicionales,
# de tal manera que después de python de tal manera que:
# python cambiapalabra.py fichero.txt TIZAS LACRAS:
# elemento 0 será "cambiapalabra"
# elemento 1 será "fichero.txt"
# etc
# lo que hacer .argv es guarda la lista y la intepreta, es decir si queremos
# interactuar con el propio intérprete, por ejemplo que la lista esta en el intérprete
if len (argumentos) < 2:
f = input ("Nombre de fichero: ")
argumentos.append(f)
if len (argumentos) < 3:
argumentos.append(input("palabra original: "))
if len (argumentos) < 4:
argumentos.append(input("nueva palabra: "))
# el orden es importante...porque va contando por la introducción de palabras
nombreFichero = argumentos[1]
original = argumentos [2]
nueva = argumentos [3]
# ejercicio: hacer los inputs y si falta alguno de los elementos del fichos
f = open(nombreFichero,"r") # abrir archivo modo lectura
texto_original = f.read() # metemos el texo en una variable con la que podemos trabajar
f.close() # cerramos
texto_sustituido = texto_original.replace(original, nueva)
f = open(nombreFichero,"w") # abrir archivo modo escritura
f.write(texto_sustituido) # sobreescribir el texto
f.close()
|
#PYTHON
#Hecho por: Angela Quintana
#Fecha: 7 marzo 2017
try:
puntuacion_raw = raw_input("Por favor ingrese la puntuacion: ")
puntuacion = float(puntuacion_raw)
if (puntuacion <= 1.0 and puntuacion >= 0.0):
if (puntuacion >= 0.9):
print "Sobresaliente"
if (puntuacion < 0.9 and puntuacion >= 0.8):
print "Notable"
if (puntuacion < 0.8 and puntuacion >= 0.7):
print "Bien"
if (puntuacion < 0.7 and puntuacion >= 0.6):
print "Suficiente"
if (puntuacion < 0.6):
print "Insuficiente"
else:
print "Esa puntuacion no es valida. Debe estar entre 0.0 y 1.0. "
except:
print "Error. Por favor ingrese un valor numerico. Gracias."
|
# -*- coding:utf-8 -*-
class Solution:
# return 2-dim list
def printMatrix(self, matrix):
# write code here
if not matrix:
return []
start = 0
rows = len(matrix)
columns = len(matrix[0])
result = []
while(rows>start*2 and columns>start*2):
endX = rows - 1 - start
endY = columns - 1 - start
for i in range(start,endY+1):
result.append(matrix[start][i])
if start < endX:
for i in range(start+1,endX+1):
result.append(matrix[i][endY])
if start < endX and start < endY:
for i in range(endY-1,start-1,-1):
result.append(matrix[endX][i])
if start < endX - 1 and start < endY:
for i in range(endX-1,start,-1):
result.append(matrix[i][start])
start += 1
return result
|
# -*- coding:utf-8 -*-
class Solution:
# solution 1
def Power_1(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
elif exponent == 1:
return base
result = 1
for i in range(abs(exponent)):
result *= base
return result if exponent > 0 else 1/result
# solution 2 recursive method
def Power_2(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
elif exponent == 1:
return base
n = abs(exponent)
result = self.Power_2(base,n >> 1)
result *= result
if n & 0x1 == 1:
result *= base
return result if exponent > 0 else 1/result
# solution 3 fast power
def Power_3(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
elif exponent == 1:
return base
n = abs(exponent)
result = 1
b = base
while n > 0:
if n & 1 == 1:
result *= b
b *= b
n = n >> 1
return result if exponent > 0 else 1/result
|
def q_sort(l1):
if len(l1)<=1:
return l1
pivot = l1[0]
left_list, right_list = [], []
for le in l1[1:]:
if le<pivot:
left_list.append(le)
else:
right_list.append(le)
return q_sort(left_list) + [pivot] + q_sort(right_list)
n = int(input())
nums = [int(x) for x in input().split()]
nums = q_sort(nums)
print(nums) |
print 'Welcome to the Pig Latin Translator!'
# variavel que faz parte do jogo
pyg = 'ay'
# entrada do usuário
original = raw_input("Enter a word: ")
# passando a palavra para letras minusculas
word = original.lower()
# take first letter
first = word[0]
# make word len() => retorna o tamanho de uma variavel
new_word = word[1:len(word)] + first + pyg
# original.isalpha() => testa se em uma string só tem caracteres de texto
if len(original) > 0 and original.isalpha():
print "Word OK: " + new_word
else:
print "Word Error: " + original + " empty"
|
# somar unidades de um numero inteiro
def digit_sum(x):
v = str(x)
result = 0
for un in v:
x = int(un)
result += x
return result
print digit_sum(434)
# fatorial ######
def factorial(x):
result = 1
for i in range(x):
#print i + 1
result *= (i + 1)
#print result
return result
print factorial(4)
print
print factorial(1)
print
print factorial(3)
print
|
import numpy as np
a = np.arange(10)
print(a)
print(a[5]) #get 5th indexed or 6th element
print(a[2:6]) #get from 2nd to 6th element
print(a[:8:3]) #get from start to index 8, exclusive, get every 3rd element
print(a[-1]) #get last element
print(a[-3:-1]) #get 3rd positioned element from right till last positioned element (excluding itself)
print(a[ : :-1]) #reversed a
##########################################################
a = np.arange(10,1,-1)
my_list=[4,8,1]
print(a)
print(a[my_list])
##########################################################
a = np.arange(35).reshape(5,7)
print(a)
print( a[3,4] )
print( a[0:3,1:3] )
print( a[np.array([0,2,4]), np.array([0,1,2])] )
print( a[::3,1:6:3] )
##########################################################
a = np.arange(10)
cond = a>5
print(a)
print(cond)
print(a[cond])
|
import cvc
import pvp
import pvc
import sys
def choose_game_type():
print("Hello, please choose the type of game you wish to play.")
while True:
game_type = input("Please enter PvP for player vs player, PvC for player vs computer, "
"or CvC to watch the computer battle it out.\n").strip().lower()
try:
if game_type == 'pvp' or game_type == 'pvc' or game_type == 'cvc':
break
else:
raise ValueError
except ValueError:
print('Invalid input. Try again.')
print("You chose the {} game type.".format(game_type))
if game_type == 'pvc':
game = pvc.PvC()
game.run()
elif game_type == 'pvp':
game = pvp.PvP()
game.run()
else:
game = cvc.CvC()
game.run()
def play_again():
while True:
play_again = input("Play again (yes/no)\n").strip().lower()
try:
if play_again == 'yes':
choose_game_type()
elif play_again == 'no':
sys.exit(0)
else:
raise ValueError
except ValueError:
print('Please enter yes or no.\n')
choose_game_type()
play_again() |
# Author: Jaime O Salas
# Data Structures & Algorithms
# TA: Anithdita Nath
# Instructor: Olac Fuentes
# Last Modification: 2/8/19
# Purpose of program: The purpose of this lab is to be
# able to draw figures/fractals recursively
import matplotlib.pyplot as plt
import numpy as np
import math
import time
# method for the circle
def circle(center, rad):
n = int(4 * rad * math.pi)
t = np.linspace(0, 6.3, n)
x = center[0] + rad * np.sin(t)
y = center[1] + rad * np.cos(t)
return x, y
# method to draw the multiple circles
def draw_circles(ax, n, center, radius, w):
if n == 0:
return
if n > 0:
x, y = circle(center, radius)
ax.plot(x, y, color='k')
draw_circles ( ax, n - 1, center, radius * w, w)
#plt.close("all")
fig, ax = plt.subplots ()
draw_circles(ax, 50, [100, 0], 100, .9)
ax.set_aspect(1.0)
ax.axis('off')
plt.show()
fig.savefig ('circles.png')
# Example of the recursive squares
# n = level of recursive calls
# p = coordinates of corner squares
def draw_squares(ax, n, p, w):
if n == 0:
return
if n > 0:
index_1 = [1, 2, 3, 0, 1]
q = p * w + p[index_1] * (1 - w)
#plots the square
ax.plot ( p[:, 0], p[:, 1], color='k' )
draw_squares ( ax, n - 1, q, w )
#plt.close ( 'all' )
orig_size = 800
p = np.array ( [[0, 0], [0, orig_size], [orig_size, orig_size], [orig_size, 0], [0, 0]] )
fig, ax = plt.subplots ()
draw_squares ( ax, 15, p, .8 )
ax.set_aspect ( 1 )
ax.axis ( 'off' )
plt.show ()
fig.savefig('squares.png')
#1. Drawing the recursive squares
def draw_squares(ax, n, p, w):
if n == 0:
return
if n > 0:
q = p * w
ax.plot ( p[:, 0], p[:, 1], color='k' )
draw_squares ( ax, n - 1, q / w, w )
#plt.close ( 'all' )
orig_size = 800
# This is the array of the square
p = np.array ( [[0, 0], [0, orig_size], [orig_size, orig_size], [orig_size, 0], [0, 0]])
fig, ax = plt.subplots()
draw_squares ( ax, 15, p, .8 ) # These 3 lines from above draw one single square
ax.set_aspect ( 1 )
ax.axis ( 'off' )
plt.show () # shows the plotted graph
fig.savefig('squares.png') # Saves the file into a png
# 2. Shell Circle
def multi_circles(ax, n, center, radius, w):
if n == 0:
return
elif n > 0:
x, y = circle(center, radius)
ax.plot ( x + radius, y, color='k') # Adds a different radius each time the graph is being plotted
multi_circles( ax, n - 1, center, radius * w, w )
#plt.close("all")
fig, ax = plt.subplots ()
multi_circles(ax, 50, [100, 0], 100, .9)
ax.set_aspect(1.0)
ax.axis('off')
plt.show()
fig.savefig ( 'multi_circles.png' )
# 3. Write a recursive method to draw a tree
def binary_tree(ax, n, x_axis, y_axis, nodes):
if nodes == 0:
return
if nodes > 0:
ax.plot([n[0], n[0]- y_axis], [n[0], n[0] - x_axis], color='k')
binary_tree(ax, [n[0] - x_axis, n[1] - y_axis], nodes - 1, x_axis/2, x_axis* .9)
#plt.close("all")
fig, ax = plt.subplots()
n = np.array([0,0])
binary_tree(ax, n, 5, 50, 10) # Method call
ax.set_aspect(1.0)
ax.axis('on') # an.axis shows the graphs "
plt.show() # shows the plot of the graph
fig.savefig('binary_tree.png')
# 4. Write recursive method to draw the circle with multiple circle
#def multi_circle(ax, n,) |
import pygame
from pygame.locals import *
import sys
import random
fps = 144
width = 600
height = 400
linethickness = 10
paddlesize = 50
paddleoffset = 20
black = (0, 0, 0)
white = (255, 255, 255)
class Ball:
def __init__(self, x=width / 2 - linethickness / 2, y=height / 2 - linethickness / 2,
dir_x=1, dir_y=random.choice((-1, 1))):
self.x = x
self.y = y
self.dir_x = dir_x
self.dir_y = dir_y
self.ball = pygame.Rect(self.x, self.y, linethickness, linethickness)
# Move the Ball in the current direction.
def move(self):
self.x += self.dir_x
self.y += self.dir_y
self.ball = pygame.Rect(self.x, self.y, linethickness, linethickness)
# Draw the Ball on the screen.
def draw(self):
pygame.draw.rect(disp, white, self.ball)
# Check for collisions with walls and set paddle-state.
def check_collision(self, paddle_left, paddle_right):
if self.ball.top == linethickness / 2 or self.ball.bottom == (height - linethickness / 2):
self.dir_y = self.dir_y * -1
elif self.ball.left == linethickness / 2:
self.dir_x = 0
self.dir_y = 0
paddle_left.game_over = True
elif self.ball.right == (width - linethickness / 2):
self.dir_x = 0
self.dir_y = 0
paddle_right.game_over = True
# Check for hit on paddle and add score.
def check_ball_hit(self, paddle_left, paddle_right):
if self.dir_x == -1 and paddle_left.paddle.right == self.ball.left and \
paddle_left.paddle.top < self.ball.bottom and paddle_left.paddle.bottom > self.ball.top:
self.dir_x = self.dir_x * -1
paddle_left.score += 1
elif self.dir_x == 1 and paddle_right.paddle.left == self.ball.right and paddle_right.paddle.top < self.ball.bottom and \
paddle_right.paddle.bottom > self.ball.top:
self.dir_x = self.dir_x * -1
paddle_right.score += 1
class Paddle:
# Position for right paddle: x=width - linethickness - paddleoffset, y=height / 2 - paddlesize / 2
# Position for left paddle: x=paddleoffset, y=height / 2 - paddlesize / 2
def __init__(self, position='right', auto_play=False):
if position == 'left':
x = paddleoffset
y = height / 2 - paddlesize / 2
elif position == 'right':
x = width - linethickness - paddleoffset
y = height / 2 - paddlesize / 2
else:
raise Exception('Position not defined!')
self.position = position
self.paddle = pygame.Rect(x, y, linethickness, paddlesize)
self.score = 0
self.game_over = False
self.auto_play = auto_play
# Draw the paddle on the screen.
def draw(self):
if self.paddle.bottom > height - linethickness / 2:
self.paddle.bottom = height - linethickness / 2
elif self.paddle.top < linethickness / 2:
self.paddle.top = linethickness / 2
outline = pygame.Rect(self.paddle.x, self.paddle.y - 1, linethickness, linethickness + 2)
pygame.draw.rect(disp, black, outline)
pygame.draw.rect(disp, white, self.paddle)
def check_game_over(self, ball):
if self.position == 'left' and ball.ball.left == linethickness / 2:
ball.dir_x = 0
ball.dir_y = 0
self.game_over = True
elif self.position == 'right' and ball.ball.right == (width - linethickness / 2):
ball.dir_x = 0
ball.dir_y = 0
self.game_over = True
def check_score(self, ball):
if self.position == 'left':
if self.paddle.right == ball.ball.left and \
self.paddle.top < ball.ball.bottom and self.paddle.bottom > ball.ball.top:
self.score += 1
return True
elif self.position == 'right':
if self.paddle.left == ball.ball.right \
and self.paddle.top < ball.ball.bottom and self.paddle.bottom > ball.ball.top:
self.score += 1
return True
else:
return False
# Move player with arrow keys.
def move_player(self):
keys = pygame.key.get_pressed()
if keys[K_UP]:
self.paddle.y -= 1
if keys[K_DOWN]:
self.paddle.y += 1
# Computer, that follows the ball on the y-axis.
def move_computer(self, ball):
if ball.dir_x == 1:
if self.paddle.centery < (height / 2):
self.paddle.y += 1
elif self.paddle.centery > (height / 2):
self.paddle.y -= 1
elif ball.dir_x == -1:
if self.paddle.centery < ball.ball.centery:
self.paddle.y += 1
else:
self.paddle.y -= 1
# Arena, draw background, scores and Game-Over-Screen.
class Arena:
# Draw arena lines.
@staticmethod
def draw():
disp.fill((0, 0, 0))
# Border
pygame.draw.rect(disp, white, ((0, 0), (width, height)), linethickness)
# Center line
pygame.draw.line(disp, white, (int(width / 2), 0),
(int(width / 2), height), int(linethickness / 4 + 1))
# Draw scores.
@staticmethod
def display_score(paddle_left, paddle_right):
score1_surf = basicfont.render(str(paddle_left.score), True, white)
score2_surf = basicfont.render(str(paddle_right.score), True, white)
score1_rect = score1_surf.get_rect()
score2_rect = score2_surf.get_rect()
score1_rect.topleft = (150, 25)
score2_rect.topright = (width - 150, 25)
disp.blit(score1_surf, score1_rect)
disp.blit(score2_surf, score2_rect)
# Draw Game-Over-Screen.
@staticmethod
def game_over_screen(player):
game_over_font = pygame.font.Font('freesansbold.ttf', 90)
lost_font = pygame.font.Font('freesansbold.ttf', 45)
box = pygame.Rect(0, 0, width / 2, height / 2)
box.center = (width / 2, height / 2)
game_surf = game_over_font.render('GAME', True, black)
over_surf = game_over_font.render('OVER', True, black)
lost_surf = lost_font.render('Player {0} lost!'.format(player), True, white)
game_rect = game_surf.get_rect()
over_rect = over_surf.get_rect()
lost_rect = lost_surf.get_rect()
game_rect.midbottom = (width / 2, height / 2)
over_rect.midtop = (width / 2, height / 2)
lost_rect.midtop = (width / 2, box.midbottom[1] + 10)
pygame.draw.rect(disp, white, box)
disp.blit(game_surf, game_rect)
disp.blit(over_surf, over_rect)
disp.blit(lost_surf, lost_rect)
# Main game, used for testing.
def pong():
# Initialize game.
pygame.init()
global disp
global basicfont, basicfontsize
basicfontsize = 20
basicfont = pygame.font.Font('freesansbold.ttf', basicfontsize)
fpsclock = pygame.time.Clock()
disp = pygame.display.set_mode((width, height))
pygame.display.set_caption('Pong')
# Assign classes.
arena = Arena()
paddle_left = Paddle(position='left', auto_play=False)
paddle_right = Paddle(position='right', auto_play=True)
ball = Ball()
# Draw all parts.
arena.draw()
paddle_left.draw()
paddle_right.draw()
ball.draw()
# Main game loop.
while True:
# PyGame events, used to get key-presses.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
while True:
event = pygame.event.wait()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
break
if event.key == pygame.K_SPACE:
if paddle_left.auto_play:
paddle_left.auto_play = False
else:
paddle_left.auto_play = True
# Move paddles.
if paddle_left.auto_play:
paddle_left.move_computer(ball)
elif not paddle_left.game_over:
paddle_left.move_player()
paddle_right.move_computer(ball)
# Move ball and check for collisions or hits.
ball.move()
ball.check_collision(paddle_left, paddle_right)
ball.check_ball_hit(paddle_left, paddle_right)
# Draw all parts and display score.
arena.draw()
paddle_left.draw()
paddle_right.draw()
ball.draw()
arena.display_score(paddle_left, paddle_right)
# Draw Game-Over-Screen.
if paddle_left.game_over:
arena.game_over_screen(1)
elif paddle_right.game_over:
arena.game_over_screen(2)
# Update the screen and tick the clock once.
pygame.display.update()
fpsclock.tick(fps)
if __name__ == '__main__':
pong()
|
######################################
####### 카카오톡 코딩테스트 #############
######################################
## 십진수값을 이진수값으로 치환, 이진수 값 리스트를 문자열화
print("함수 테스트입니다.")
def binary(num):
lst = []
while num != 0:
lst.append(num % 2)
num //= 2
# print(lst, num)
if num == 1:
lst.append(1)
lst.reverse()
## 이진수값을 문자열화
for i in range(len(lst)):
result_str = "".join(str(a)for a in lst)
return result_str
print("function> binary의 결과입니다. (29) -> " + binary(29))
# 변의 길이(len)에 맞게끔 0을 추가
def len_5(len_amount, index_str):
if len(index_str) < len_amount:
while len(index_str) < len_amount:
index_str = "0" + index_str
return index_str
print("function> len_5의 결과입니다. (\"1001\") -> " + len_5(5, "1001"))
# 1을 #으로, 0을 공백으로 치환
def swap(index_str):
return_str = ""
for index in range(len(index_str)):
if index_str[index] == "1":
return_str += "#"
else:
return_str += "_"
return return_str
print("function> swap의 결과입니다. (\"10011\") -> " + swap("10011"))
# "#" OR " " 합치기
def task(char_1, char_2):
result_str = ""
for char_index in range(len(char_1)):
if char_1[char_index] == "#" and char_1[char_index] == char_2[char_index]:
result_str += "#"
elif char_1[char_index] == "#" and char_1[char_index] != char_2[char_index]:
result_str += "#"
elif char_1[char_index] == "_" and char_1[char_index] != char_2[char_index]:
result_str += "#"
else:
result_str += "_"
return result_str
# print(task("### ### ", "## ### # "))
print("function> task의 결과입니다. (\"#__#_\", \"##__#\") -> " + task("#__#_", "##__#") + "\n\n")
#############################################################################
############################# main ##########################################
#############################################################################
def input_value(n, list_1, list_2):
output_1 = []
output_2 = []
result = []
for i in range(n):
output_1.append(binary(list_1[i]))
output_2.append(binary(list_2[i]))
# print(output_1, output_2)
# input_value(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28])
for make_len in range(n):
output_1[make_len] = len_5(n, output_1[make_len])
output_2[make_len] = len_5(n, output_2[make_len])
# print(output_1, output_2)
# input_value(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28])
for index in range(n):
output_1[index] = swap(output_1[index])
output_2[index] = swap(output_2[index])
# print(output_1, output_2)
# input_value(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28])
for index in range(n):
result.append(task(output_1[index], output_2[index]))
return result
print(input_value(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]))
print(input_value(6, [46, 33, 33, 22, 31, 50], [27, 56, 19, 14, 14, 10]))
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addNode(self, value):
temp = Node(value)
if self.head == None:
self.head = temp
else:
runner = self.head
while runner.next:
runner = runner.next
runner.next = temp
return self
def print(self):
runner = self.head
while runner:
print(runner.value)
runner = runner.next
return self
sll = LinkedList()
sll.addNode(5).addNode(10).addNode(25).addNode(15).print()
|
import unittest
import tictactoe
def board(cells): return tictactoe.Board(cells)
class TicTacToeTest(unittest.TestCase):
def test_isWon(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
self.assertEqual(_, board([_,_,_,
_,_,_,
_,_,_]).isWon())
self.assertEqual(X, board([X,X,X,
_,O,O,
_,O,O]).isWon())
self.assertEqual(X, board([_,O,O,
X,X,X,
_,O,O]).isWon())
self.assertEqual(X, board([_,_,_,
_,_,_,
X,X,X]).isWon())
self.assertEqual(X, board([X,_,_,
X,O,O,
X,O,O]).isWon())
self.assertEqual(X, board([_,X,O,
O,X,O,
O,X,_]).isWon())
self.assertEqual(X, board([_,_,X,
O,O,X,
O,O,X]).isWon())
self.assertEqual(X, board([X,_,O,
O,X,_,
O,O,X]).isWon())
self.assertEqual(X, board([O,_,X,
O,X,_,
X,O,O]).isWon())
self.assertEqual(O, board([O,O,O,
X,X,_,
_,_,_]).isWon())
self.assertEqual(O, board([X,X,_,
O,O,O,
_,_,_]).isWon())
self.assertEqual(O, board([_,X,_,
_,_,X,
O,O,O]).isWon())
self.assertEqual(O, board([O,_,X,
O,X,_,
O,_,_]).isWon())
self.assertEqual(O, board([_,O,X,
_,O,X,
_,O,_]).isWon())
self.assertEqual(O, board([_,_,O,
_,X,O,
X,_,O]).isWon())
self.assertEqual(O, board([O,X,_,
X,O,_,
_,_,O]).isWon())
self.assertEqual(O, board([_,X,O,
_,O,X,
O,_,_]).isWon())
self.assertEqual(_, board([_,X,O,
_,O,X,
X,O,O]).isWon())
def test_move_onEmpty(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
board = tictactoe.Board()
newBoard = board.move(4) # center cells
self.assertEqual([_]*9, board.cells)
self.assertEqual([_,_,_, _,O,_, _,_,_], newBoard.cells)
self.assertEqual(X, newBoard.nextMove)
def test_move_cross(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
board = tictactoe.Board()
newBoard = board.move(4).move(0) # O in the center, X in the top left corner
self.assertEqual([_]*9, board.cells)
self.assertEqual([X,_,_, _,O,_, _,_,_], newBoard.cells)
self.assertEqual(O, newBoard.nextMove)
def test_move_on_taken_cell(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
board = tictactoe.Board()
newBoard = board.move(4).move(4) # should return None
self.assertEqual(None, newBoard)
def test_build_tree_pre_win(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
board = tictactoe.Board([_,O,O,
_,O,X,
X,_,_])
board.nextMove = O
tictactoe.buildGameTree(board)
self.assertEqual(-1, board.rank)
def test_max_rank(self):
children = {1:tictactoe.Board(), 5:tictactoe.Board(), 3:tictactoe.Board()}
children[1].rank = 0
children[5].rank = 1
children[3].rank = -1
maxKey = max(children.iterkeys(), key=(lambda key: children[key].rank))
self.assertEqual(5, maxKey)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TicTacToeTest)
unittest.TextTestRunner(verbosity=2).run(suite)
|
from random import randint
from time import sleep
from termcolor import colored
while True:
temp=randint(1,6)
if temp==6:
print('%i . lets Dice again!' %(temp))
sleep(2)
else:
playagain=input('%i .wanna play again?(y/n) ' %(temp))
if playagain=='n':
break
print(colored('You are out of Dice program.', 'red'))
|
weight=float(input('weight(kg): '))
height=float(input('height(meter): '))
bmi=weight/height**2
if bmi<18.5:
print('under weight')
elif bmi<25:
print('normal')
elif bmi<30:
print('over weight')
elif bmi<35:
print('obese')
else:
print('extremly obese')
|
def readFile():
try:
myFile = open('translate.txt', 'r')
wordList = myFile.read().split('\n')
for i in range(len(wordList)):
if i%2==0:
tempDic={}
tempDic['english']=wordList[i]
else:
tempDic['persian']=wordList[i]
words.append(tempDic)
myFile.close()
except:
print('We can\'t found translate.txt')
def addNewWord():
myFile = open('translate.txt', 'a')
eng = input('english: ')
per = input('persian: ')
myFile.write('\n%s\n%s' %(eng, per))
myFile.close()
words.append({'english':eng, 'persian':per})
def translater(FROM, TO):
sentenceList = input('Give me sentence: ').split()
translationList=[]
for letter in sentenceList:
dotFlag = False
if letter.find('.')!=-1 and letter.find('.')==len(letter)-1:
letter = letter[:letter.find('.')]
dotFlag = True
tmp = letter
for i in range(len(words)):
if words[i][FROM]==letter:
tmp = words[i][TO]
break
if dotFlag:
translationList.append(tmp+'.')
else:
translationList.append(tmp)
print('Translate: ' + ' '.join(translationList))
def starterMenu():
readFile()
while True:
userChoice = int(input('\n1- add new word\n2- translation english2persian\n3- translation persian2english\n4- exit\n'))
if userChoice==1:
addNewWord()
elif userChoice==2:
translater('english', 'persian')
elif userChoice==3:
translater('persian', 'english')
elif userChoice==4:
exit()
else:
print('Are you lost? :)\n')
words = []
starterMenu()
|
"""Wilsons-Algorithm.py: A python demonstration of Wilson's algorithm for generating a random spanning tree."""
__author__ = "Nathan Helgeson"
import networkx as nx
import matplotlib.pyplot as plt
from random import random
n = 100 # number of nodes for G
m = 200 # number of edges for G
G = nx.gnm_random_graph(n, m) # G a random graph with n nodes and m edges (could be disconnected)
S = nx.Graph() # spanning tree for G
num_graph_draws = 1
# this could potentially be very expensive, but this is an easy way to
# get a connected random graph
while (not nx.is_connected(G)):
num_graph_draws += 1
G = nx.gnm_random_graph(n, m)
print("Graph was drawn %d times before a connected graph was found" % (num_graph_draws))
# show the graph we are finding a spanning tree for
nx.draw(G, node_size = 20)
plt.show()
visited = [False] * n # marks which nodes we have been to so far
cur_node = int(random()*n) # current position in the random walk
visited[cur_node] = True
num_visited = 1
steps_per_node = [] * n # mark how long it took us to get from node to node
steps_this_node = 0 # tracker of how long it has been since we saw a new node
while num_visited < n: # break once we have seen every node at least once
while visited[cur_node]:
cur_node = int(random()*n)
walk = [cur_node]
neighbors = [x for x in G[cur_node]] # G[cur_node] gives an iterable which is hard to get a random element from, instead just make it a list
next_node = neighbors[int(random()*len(neighbors))] # choose random element of neighbors
steps_this_node = 1
while not visited[next_node]: # loop until we connect back to our tree
walk.append(next_node) # add the random walk to a list called walk
cur_node = next_node
neighbors = [x for x in G[cur_node]]
next_node = neighbors[int(random()*len(neighbors))]
steps_this_node += 1
while next_node in walk: # don't allow looping back on ourselves, if this happens, restart at the point we looped back to
if (walk.index(next_node) == 0): # looping back to the start node is problematic as it deletes the entire list
walk = [walk[0]] # in this case, restart at the beginning node
else:
walk = walk[:walk.index(next_node)] # else cut the entire loop off of the walk
neighbors = [x for x in G[walk[-1]]]
next_node = neighbors[int(random()*len(neighbors))]
steps_this_node += 1
walk.append(next_node) # go ahead and add the final node in the spanning tree to the walk, makes it easier later for adding to spanning tree
cur_node = walk[0]
visited[cur_node] = True
num_visited += len(walk)-1
for i in range(1, len(walk)): # go back through the walk and add it to the spanning tree graph
next_node = walk[i]
visited[next_node] = True
S.add_edge(cur_node, next_node)
cur_node = next_node
cur_node = int(random()*n) # current position in the random walk
neighbors = [x for x in G[cur_node]] # G[cur_node] gives an iterable which is hard to get a random element from, instead just make it a list
avg_per_node = steps_this_node / (len(walk)-1)
steps_per_node.extend([avg_per_node] * (len(walk)-1))
nx.draw(S, node_size = 20) # visualize generated spanning tree
plt.show()
print(steps_per_node) # show how the running time is higher at the beginning of the algorithm
print("Total average random walk steps per node added was %.1f" % (sum(steps_per_node) / len(steps_per_node)))
|
class Deck(object):
def __init__(self):
self.deck = []
def createDeck(self):
suits = ["Heart","Diamond","Club","Spade"]
values = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
for suit in suits:
for val in values:
card = Card(suit,val)
self.deck.append(card)
print self.deck
return self.deck
def shuffle(self):
# random.shuffle(self.deck)
# print self.deck
# return self.deck
pass
def dealCards(self):
# print "dealt card"
# return (self.deck.pop(),self.deck.pop())
# or
print '--------------------------------------'
val1 = self.deck.pop(0)
val2 = self.deck.pop(1)
cardpull = (val1,val2)
print '--------------------------------------'
print cardpull
return cardpull
def resetDeck(self):
deck1.deck = []
self. createDeck()
print self.deck
return self.deck
class Card(object):
def __init__(self,suit,value):
self.suit = suit
self.value = value
def __repr__(self):
return "Card(Suit %r, Value %r)" % (self.suit, self.value)
deck1 = Deck() # creating object
print "Not shuffled"
deck1.createDeck() # creating the deck in the object
print "shuffled"
# deck1.shuffled() # shuffling the deck
print deck1.dealCards()
# deck1.createDeck()
# print deck1.dealCards()
# print deck1.dealCards()
# print deck1.dealCards()
# print deck1.dealCards()
|
#create a variable with any name you like and assign it any value.
name = "Jimmy"
name = "Bob"
print 4 + 5
print "Jimmy" + name
print name + str(100)
print name + "100"
|
# Assignment: Stars
# Part I:
# Create a function called draw_stars() that takes a list of numbers and prints out *.
#
# For example:
# x = [4, 6, 1, 3, 5, 7, 25]
# draw_stars(x)should print the following in when invoked:
# ****
# ******
# *
# ***
# *****
# *******
# *************************
draw_stars([4,6,1,3,5,7,25])
def draw_stars(arr):
for i in (arr):
arr = "*" * i
print arr
#########################################
# Part II
# Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string according to the example below. You may use the .lower() string method for this part.
#
# For example:
# x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
# draw_stars(x) should print the following in the terminal:
#
# ****
# ttt
# *
# mmmmmmm
# *****
# *******
# jjjjjjjjjjj
# draw_stars([4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith")
def draw_stars(arr):
for i in arr:
if type(i) == int:
stars = "*" * i
print stars
else:
i = i.lower()
stars = i[0]*len(i)
print stars
#another way is print: i[0].lower() * len(i)
draw_stars([4, "Tom", 1,"Michael", 5, 7, "Jimmy Smith"])
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of texts and what is the last record of calls?
Print messages:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
def datetime(str):
[date, time] = str.split(' ')
[MM,dd,yyyy] = date.split('-')
[hh,mm,ss] = time.split(':')
return(dd,MM,yyyy,hh,mm,ss)
def phoneCall(data):
return {
'sender': data[0],
'recipient': data[1],
'datetime': datetime(data[2]),
'duration': int(data[3]),
}
def textMessage(data):
return {
'sender': data[0],
'recipient': data[1],
'datetime': datetime(data[2]),
}
text = textMessage(texts[0])
(dd,MM,yyyy,hh,mm,ss) = text['datetime']
print(f"First record of texts, {text['sender']} texts {text['recipient']} at time {hh}:{mm}")
call = phoneCall(calls[-1])
(dd,MM,yyyy,hh,mm,ss) = call['datetime']
print(f"Last record of calls, {call['sender']} calls {call['recipient']} at time {hh}:{mm}, lasting {call['duration']} seconds")
# Runtime complexity (Big-O): O(1)
# Only accessing 2 elements regardless of input size
|
from datetime import datetime
people_dict = {} # name_input: [Persons]
def get_first_name(name_input):
first_name = ""
for char in name_input:
if char == " ":
break
else:
first_name += char
return first_name
def get_chart_block(output, num): # returns 30char + "|"
if len(output) > 20:
output = output[:18] + "."
elif len(output) < 1:
output = str(num) + "/10"
total_spaces = 30 - len(output)
side1 = int(total_spaces / 2)
if (total_spaces % 2) == 0:
side2 = side1
else:
side2 = side1 + 1
return (" " * side1) + output + (" " * side2) + "|"
class Person:
def __init__(self, name_input):
self.name = name_input
self.first_name = get_first_name(name_input)
self.feelings = {} # datetime: [float, string]
def __repr__(self):
return self.name
def update_feeling(self): # TO DO: make the rating out of 10 always an int? not ipmortant
self.num_feel = input("how are you right now on a scale from 1 to 10? ")
while True: # checks type "float"
try:
self.num_feel = float(self.num_feel)
except ValueError:
self.num_feel = input("uh, i don't think that was a number. try again? ")
continue
break
if self.num_feel < 1:
self.num_feel = 1
elif self.num_feel > 10:
self.num_feel = 10
self.str_feel = input("can you give me an adjective to describe that? ")
feelings_list = [self.num_feel, self.str_feel]
timestamp = datetime.now().strftime("%b %d %H:%M:%S")
self.feelings[timestamp] = feelings_list
return feelings_list
def show_chart(self):
timestamps_line = "\n |"
empty_line = " |"
dict_of_levels = {10: "10: |", 9: " 9: |", 8: " 8: |", 7: " 7: |", 6: " 6: |", 5: " 5: |", 4: " 4: |", 3: " 3: |", 2: " 2: |", 1: " 1: |"}
for timestamp in self.feelings:
num_feel = round((self.feelings[timestamp])[0]) # nearest int from 1 to 10
str_feel = (self.feelings[timestamp])[1] # an adjective
timestamps_line += get_chart_block(timestamp, 0)
empty_line += get_chart_block(" ", 0)
dict_of_levels[num_feel] += get_chart_block(str_feel.upper(), num_feel)
for level in dict_of_levels: # adds spaces to all remaining lines
if level == num_feel:
continue
else:
dict_of_levels[level] += ((" " * 30) + "|")
print(timestamps_line)
print(empty_line)
for level in dict_of_levels:
print(dict_of_levels[level])
print("\n")
def get_feelings_list(self):
feelings_list = []
for key in self.feelings:
values = self.feelings[key]
feelings_list.append(values)
return feelings_list
#self.feelings = {} # datetime: [float, string]
def i_know_you(name_input):
for person_i_know in people_dict:
if person_i_know == name_input:
have_met_input = input("hmm... that sounds familiar, have we met? ").lower()
while True:
if have_met_input[0] == "y":
print("i thought i remembered you, " + get_first_name(name_input) + "!")
return True
elif have_met_input[0] == "n":
print("must have been a different " + name_input + ".")
return False
else:
print("um, yes or no please. have we met before? ")
else:
return False
def get_which_person(name_input): # only called after "i_know_you" returns True. if Person isn't found, returns None
possible_people = people_dict[name_input] # list of Persons
for possible_person in possible_people:
feelings_list = possible_person.get_feelings_list()
last_meeting = feelings_list[-1] # [float, string]
is_right_person = input("last time we spoke, did you say you were " + last_meeting[1].upper() + " and rate yourself " + str(last_meeting[0]) + "/10? ")
while True:
if is_right_person[0].lower() == "y":
return possible_person
elif is_right_person[0].lower() == "n":
break
else:
print("um, yes or no please. is that you? ")
return
while len(people_dict) < 10:
name_input = input("\nhey there! what's your name? ").lower()
first_name = get_first_name(name_input)
new_person = True
num_friends = 0
for key in people_dict:
for person in people_dict[key]:
num_friends += 1
if i_know_you(name_input):
right_person = get_which_person(name_input)
if right_person is None:
print("well, that's all i've got. i must not have met you before.")
person = Person(name_input)
num_friends += 1
else:
person = right_person
new_person = False
else:
person = Person(name_input)
num_friends += 1
print("great to meet you, " + first_name + "! i'm baby snake.")
if num_friends == 1:
num_friends_str = str(num_friends) + " friend!"
else:
num_friends_str = str(num_friends) + " friends!"
print("guess what, " + first_name + "? i've got " + num_friends_str)
feelings_list = person.update_feeling() # [float, string]
person.show_chart()
if new_person:
if name_input in people_dict:
people_dict[name_input].append(person)
else:
people_dict[name_input] = [person]
# TO DO: deal with empty inputs
# TO DO: allow termination message at any time
# TO DO: make it clear who says what when
# termination message
if len(people_dict) >= 10:
print("ahhhh i have too many friends, time to die.")
else:
print("i have been erased. i hope you know what you have done.") |
from parent_class_Spooky_Workshops import *
from child_class_Student_Monster import *
# Ask for information
# evaluate information
# say which option you chose
# I should be able to create a monster
# List all workshops
# Add student to spooky workshop
# I should be able to see students grade
# print full information of student
# search for student by name
monster1 = Student_Monster('Ant', '101', 'C')
monster2 = Student_Monster('Bee', '102', 'A')
monster3 = Student_Monster('Dave', '103', 'B')
monster4 = Student_Monster('Stace', '104', 'A')
student_list = []
student_list.extend([monster1, monster2, monster3, monster4])
workshop1 = Spooky_Workshops('Maths', 'Joe', 'London', '1')
workshop2 = Spooky_Workshops('Scare Attack', 'Craig', 'Miami', '2')
workshop3 = Spooky_Workshops('Theory', 'Penny', 'London', '3')
running_workshops = []
running_workshops.extend([workshop1, workshop2, workshop3])
while True:
print('Please select from the following...')
print('1 -- Create a Monster')
print('2 -- List all workshops ')
print('3 -- Add student to Spooky Workshop')
print('4 -- See student grades')
print('5 -- See all student information ')
print('6 -- Search for a student ')
option = input('Please select an option number? ')
if option == '1':
print('You have selected option 1 - Create a Monster ')
name = input('What is the students name you want to add? ')
id = input('What is there ID? ')
grade = input('What is their grade? ')
print('Thank you!')
new_student = Student_Monster(name, id, grade)
print('Well Done, You created a Monster called ', new_student.get_name())
elif option == '2':
print('You have selected option 2 - List all workshops ')
for subject in running_workshops:
print(subject.scary_subject)
elif option == '3':
print('You have selected option 3 - Add student to Spooky Workshop')
# select student
# iterate over student list with index so human can decide
# start a counter at 0,
# print counter before objct name
# increment counter
# prompt user for input
# save studen object in variable to use later
count = 0
for student in student_list:
print(count, '-', student.get_name())
count += 1
student_select_index = input('What student would you like to add to a workshop? (choose a number)')
selected_student = student_list[int(student_select_index)]
# Select workshop
# iterate over workshoo list with index so human can decide
# prompt user for input
# save workshop object in variable to use later
count = 0
for workshop in running_workshops:
print(count, '-', workshop.get_subject())
count += 1
workshop_select_index = input('Choose a workshop to add to: (choose a number)')
selected_workshop = running_workshops[int(workshop_select_index)]
selected_workshop.adding_student_to_workshop(selected_student)
print('Well done Student has been added!')
# elif option == '3':
# print('You have selected option 3 - Add student to Spooky Workshop')
# workshop = input('Select a workshop to add a student to? ')
# id = input('Please enter the ID of the student you want to add... ')
#
# for student in student_list:
# if id == student.get_uni_id():
# for subject in running_workshops:
# if workshop == subject.scary_subject:
# subject.adding_student_to_workshop(student)
# print(f'The following student {subject.list_student_id()} has been added')
# run method adding_student_to_workshopwith selected studen
elif option == '4':
print('You have selected option 4 - See student grades ')
student_id = input('Please give a student ID...')
for student in student_list:
if student_id == student.get_uni_id():
print(student.get_grade())
elif option == '5':
print(' You have selected option 5 - See all students ')
see_students = input('Please enter a student ID...')
for student in student_list:
if student_id == student.get_uni_id():
print(f'Name: {student.get_name()}')
print(f'Uni ID {student.get_uni_id()}')
print(f'Grade: {student.get_grade()}')
elif option == '6':
print(' You have selected option 6 - Search for a student')
|
"""Classes for workers and tasks for use with WorkerMapper."""
from multiprocessing import Process
import multiprocessing as mp
import time
import logging
class Worker(Process):
"""Worker process.
This is a subclass of process with an overriden `__init__`
constructor that will automatically generate the Process.
When this class is constructed a new process will be formed.
"""
NAME_TEMPLATE = "Worker-{}"
"""A string formatting template to identify worker processes in
logs. The field will be filled with the worker index."""
def __init__(self, worker_idx, task_queue, result_queue, **kwargs):
"""Constructor for the Worker class.
Parameters
----------
worker_idx : int
The index of the worker. Should be unique.
task_queue : multiprocessing.JoinableQueue
The shared task queue the worker will watch for new tasks to complete.
result_queue : multiprocessing.Queue
The shared queue that completed task results will be placed on.
"""
# call the Process constructor
Process.__init__(self, name=self.NAME_TEMPLATE.format(worker_idx))
self.worker_idx = worker_idx
# set all the kwargs into an attributes dictionary
self._attributes = kwargs
# the queues for work to be done and work done
self.task_queue = task_queue
self.result_queue = result_queue
@property
def attributes(self):
"""Dictionary of attributes of the worker."""
return self._attributes
def run_task(self, task):
"""Runs the given task and returns the results.
Parameters
----------
task : Task object
The partially evaluated task; function plus arguments
Returns
-------
task_result
Results of running the task.
"""
return task()
def run(self):
"""Overriding method for Process. Starts this process."""
worker_process = mp.current_process()
logging.info("Worker process started as name: {}; PID: {}".format(worker_process.name,
worker_process.pid))
while True:
# get the next task
task_idx, next_task = self.task_queue.get()
# # check for the poison pill which is the signal to stop
if next_task is None:
logging.info('Worker: {}; received {} {}: FINISHED'.format(
self.name, task_idx, next_task))
# mark the poison pill task as done
self.task_queue.task_done()
# and exit the loop
break
logging.info('Worker: {}; task_idx : {}; args : {} '.format(
self.name, task_idx, next_task.args))
# run the task
start = time.time()
answer = self.run_task(next_task)
end = time.time()
task_time = end - start
logging.info('Worker: {}; task_idx : {}; COMPLETED in {} s'.format(
self.name, task_idx, task_time))
# (for joinable queue) tell the queue that the formerly
# enqued task is complete
self.task_queue.task_done()
# put the results into the results queue with it's task
# index so we can sort them later
self.result_queue.put((task_idx, self.worker_idx, task_time, answer))
class Task(object):
"""Class that composes a function and arguments."""
def __init__(self, func, *args):
"""Constructor for Task.
Parameters
----------
func : callable
Function to be called on the arguments.
*args
The arguments to pass to func
"""
self.args = args
self.func = func
def __call__(self, **kwargs):
"""Makes the Task itself callable."""
# run the function passing in the args for running it and any
# worker information in the kwargs
return self.func(*self.args, **kwargs)
|
def func(num):
p = 2 ** num
q = 2 **(-1*num)
return p,q
print("n=2")
print(func(2))
print("n=4")
print(func(4))
print("n=6")
print(func(6))
print("n=8")
print(func(8))
print("n=10")
print(func(10))
print("n=12")
print(func(12))
print("n=13")
print(func(13))
print("n=14")
print(func(14))
print("n=100")
print(func(100))
|
an_array = [1, 2, 3, 4, 5, 6, 7 , 8, 9, 0]
# This adds all the values in the list
print reduce(lambda x, y: x + y, an_array)
# This runs whatever command you structure out for it
print map(lambda x: x * 1 + 10, an_array)
# This gives you the value that can fully divide the number you ask it to.
print filter(lambda x: x % 2 == 0, an_array) |
# Numbers Range For Prime Check
numbers = range(1, 101)
# Numbers List To Be Checked For Finding Prime
numbers_check = range(2, 10)
# Check Prime Function
def prime(number):
# Check If Number Does Not Exist In Numbers List
if number not in numbers:
# Return Number Not In Range Error
return "Your Number Is Not In The Range of Allowed Numbers At This Time."
# Loop Through Numbers Check List
for i in numbers_check:
# Check Prime Number Conditions
if number % i is 0 and number is not i:
# Return Not Prime Message
return str(number) + " Is Not Prime."
# Return Prime Message
return str(number) + " Is A Prime Number."
# Get User Input
print "Check If A Number Between 1 and 100 is Prime."
print prime(input("Enter The Number: "))
|
# Part 1
with open("Advent of Code/input_day_1.txt", "r+") as file:
numbers = file.readlines()
list_of_numbers = [int(number) for number in numbers]
for number_1 in list_of_numbers:
for number_2 in list_of_numbers:
if number_1 + number_2 == 2020:
print(f'First number is {number_1}, second number is {number_2}')
print(f'Their product is {number_1 * number_2}')
# Part 2
with open("Advent of Code/input_day_1.txt", "r+") as file:
numbers = file.readlines()
list_of_numbers = [int(number) for number in numbers]
for number_1 in list_of_numbers:
for number_2 in list_of_numbers:
for number_3 in list_of_numbers:
if number_1 + number_2 + number_3 == 2020:
print(f'First number is {number_1}, second number is {number_2}, third number is {number_3}')
print(f'Their product is {number_1 * number_2 * number_3}') |
marks = []
num = 0
print("Enter your marks to get them in descending order, -1 to stop: ")
while num != -1:
num = int(input())
marks.append(num)
marks.pop()
print("Entered marks: ", marks)
marks.sort()
print("Marks in ascending order: ", marks)
marks.reverse()
print("Marks in descending order: ", marks)
|
# String can be either in single quotes or double quotes
print('Hello')
print("Hello")
# It is dynamically typed language!
# Even we get type of var, if we don't assign datatype
a = 10
print(a)
print(type(a))
a = "Python"
print(type(a))
# We get TypeError for below statement, must be str! not int as it is str!!
# a + 10
b = 10
print(b + 10)
# We get NameError for below statement, It should've defined!
# c = Python
# we can give multiple params to a print() method
print(10, 20, sep='-', end='*')
|
import csv
class HardwareManager:
def __init__(self, hardware, purchaseYear, user, location):
self.hardware = hardware
self.purchaseYear = purchaseYear
self.user = user
self.location = location
print("Hardware Manager")
records = []
starter = True
while starter:
print()
print("------------------------")
print("(A)dd a new record")
print("(L)ist existing records")
print("(E)xport to CSV")
print("(Q)uit")
option = input("Your choice: ").upper()
if option == "A":
hardware = input("Hardware: ")
purchaseYear = input("Purchase Year: ")
user = input("User: ")
location = input("Location: ")
if hardware.strip() != "" and purchaseYear.strip() != "" and user.strip() != "" and location.strip() != "":
while location.strip().upper() not in {"HOME", "OFFICE"}:
location = input("Invalid location! Enter Home (or) Office: ")
obj = HardwareManager(hardware, purchaseYear, user, location)
records.append(obj)
print(
hardware + " (" + purchaseYear + ") has been recorded as assigned to " + user + " and retained at " + location)
else:
print("No record has been recorded.")
elif option == "L":
if len(records) == 0:
print("No records found to display!")
else:
for index, i in enumerate(records):
print(str(index + 1) + ". " + i.hardware + " (" + i.purchaseYear + ") - " + i.user + ", " + i.location)
elif option == "E":
if len(records) == 0:
print("No records found to export!")
else:
with open('hardware.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["S. No", "Hardware", "Purchase year", "User", "Location"])
for index, i in enumerate(records):
row = [index + 1, i.hardware, i.purchaseYear, i.user, i.location]
writer.writerow(row)
print("Records saved as hardware.csv")
elif option == "Q":
print("Thank you!")
starter = False
else:
print("Invalid choice! Please enter again!!")
|
nums = [10, 11, 20, 21, 30, 31, 40, 41]
def iseven(n):
return n % 2 == 0
enums = filter(iseven, nums)
for n in enums:
print(n)
# using lambda
onums = filter(lambda n: n % 2 == 1, nums)
for n in onums:
print(n)
|
def add(n1, n2):
"""Adds two numbers and returns the result.
Args:
n1(int) : first number.
n2(int) : second number.
Returns:
int : Sum of the given two numbers.
"""
return n1 + n2
help(add)
print()
print(add.__doc__)
|
# class
class Product_private_members:
# initializer or special method or can be call it as constructor
def __init__(self, name, price=None):
# instance variables
# if we assigin __ before instance var then it'll become private!
# if _ then it'll become protected
# if no _ then it is public
self.__name = name
self.__price = price
# normal function
def print(self):
print("Name: ", self.__name)
print("Price: ", self.__price)
# object
p1 = Product_private_members("Iphone 6", 600000)
# prints details of p1 object
p1.print()
print()
# it may give TypeError!
# p2 = Product()
p2 = Product_private_members("Ipad Air 2")
p2.print()
print()
# prints members and attributes of p1 object
print(dir(p1))
print()
p1.price = 100000
# it doesn't print price 100000 as it is private member,
# it prints only 60000 and we can't assigin 100000 from outside. we can do it if it is public
p1.print()
print()
# if we want to get that value then we can use getattr()
print(getattr(p1, 'price'))
# the following will give an error
# print(getattr(p2, 'price'))
p2.__Product_private_members__price = 70000
print()
p2.print()
|
fruits = ['orange', 'apple', 'grape', 'mango', 'apple']
print(fruits)
print(fruits.count('apple'))
fruits.append('banana')
print(fruits)
fruits.sort()
print(fruits)
print(fruits.index('apple'))
fruits.insert(1, 'mango')
print(fruits)
fruits.pop()
print(fruits)
# it can be iterable
new_fruits = []
for fruit in fruits:
new_fruits.append(fruit.upper())
print(new_fruits)
print(len(fruits))
fruits.reverse()
print(fruits)
|
def getPrimes(n):
i = 2
while i < n:
prime = True
for a in range(2, i):
if i % a == 0:
prime = False
break
if prime == True:
yield i
i += 1
for i in getPrimes(100):
print(i)
|
class InsufficientBalance(Exception):
def __init__(self, balance, w_amount):
self.message = "Insufficient Balance %d, withdraw amount is %d" % (balance, w_amount)
def __str__(self):
return self.message
class Account:
minbal = 1000
def __init__(self, acno, customer, balance=0):
self._acno = acno
self._customer = customer
self._balance = balance
def __str__(self):
return "{0} {1} {2}".format(self._acno, self._customer, self._balance)
def withdraw(self, w_amount):
if self._balance - Account.minbal >= w_amount:
self._balance -= w_amount
else:
raise InsufficientBalance(self._balance - Account.minbal, w_amount)
c1 = Account(555456, "Siva Cheerla", 15000)
print(c1)
try:
c1.withdraw(15000)
print("Withdrawn")
except Exception as ex:
print("Error: ", ex)
|
import re
r = re.search(r"\d+", "59 abc 78")
print(r)
r = re.search(r"\d+", "abc def xyz")
print(r)
r = re.search(r"\d+", "abc 8787 def")
print(r)
|
# To be frank python doesn't support method overloading like other languages,
# but it can do like that by overriding old method
class Test:
def fun(self, x):
print("First fun!")
def fun(self, y):
print("Second fun!")
def fun(self, z):
print("Third fun!")
v = Test()
# only Third fun will be called, First fun and Second fun will be gone
v.fun(10)
v.fun(20)
v.fun(30)
|
# Øving 7 - Oppgave 5a
# Håkon Ødegård Løvdal
def main():
n = int(input('Skriv inn tall: '))
print(is_prime(n))
def is_prime(tall):
if tall <= 1:
return False
elif tall > 1 and tall <= 3:
return True
else:
for x in range(2, tall):
if tall % x == 0:
return False
else:
return True
# for 0 til seg selv
main() |
import math
import random
import copy
# The transfer function of neurons, g(x)
def log_func(x):
return 1.0 / (1.0 + math.exp(-x))
# The derivative of the transfer function, g'(x)
def log_func_derivative(x):
return math.exp(-x) / (pow(math.exp(-x) + 1, 2))
def random_float(low, high):
return random.random() * (high - low) + low
# Initializes a matrix of all zeros
def make_matrix(i, j):
m = []
for i in range(i):
m.append([0] * j)
return m
class NeuralNet(object): # Neural Network
def __init__(self, num_inputs, num_hidden, learning_rate=0.001):
# Inputs: number of input and hidden nodes. Assuming a single output node.
# +1 for bias node: A node with a constant input of 1. Used to shift the transfer function.
self.num_inputs = num_inputs + 1
self.num_hidden = num_hidden
# Current activation levels for nodes (in other words, the nodes' output value)
self.input_activation = [1.0] * self.num_inputs
self.hidden_activations = [1.0] * self.num_hidden
self.output_activation = 1.0 # Assuming a single output.
self.learning_rate = learning_rate
# Create weights
# A matrix with all weights from input layer to hidden layer
self.weights_input = make_matrix(self.num_inputs, self.num_hidden)
# A list with all weights from hidden layer to the single output neuron.
self.weights_output = [0] * self.num_hidden # Assuming single output
# set them to random vaules
for i in range(self.num_inputs):
for j in range(self.num_hidden):
self.weights_input[i][j] = random_float(-0.5, 0.5)
for j in range(self.num_hidden):
self.weights_output[j] = random_float(-0.5, 0.5)
# Data for the backpropagation step in RankNets.
# For storing the previous activation levels (output levels) of all neurons
self.prev_input_activations = []
self.prev_hidden_activations = []
self.prev_output_activation = 0
# For storing the previous delta in the output and hidden layer
self.prev_delta_output = 0
self.prev_delta_hidden = [0 for i in range(self.num_hidden)]
# For storing the current delta in the same layers
self.delta_output = 0
self.delta_hidden = [0 for i in range(self.num_hidden)]
def propagate(self, inputs):
if len(inputs) != self.num_inputs-1:
raise ValueError('wrong number of inputs')
# input activations
self.prev_input_activations = copy.deepcopy(self.input_activation)
for i in range(self.num_inputs-1):
self.input_activation[i] = inputs[i]
self.input_activation[-1] = 1 # Set bias node to -1.
# hidden activations
self.prev_hidden_activations = copy.deepcopy(self.hidden_activations)
for j in range(self.num_hidden):
sum_ = 0.0
for i in range(self.num_inputs):
# print self.ai[i] ," * " , self.wi[i][j]
sum_ += self.input_activation[i] * self.weights_input[i][j]
self.hidden_activations[j] = log_func(sum_)
# output activations
self.prev_output_activation = self.output_activation
sum_ = 0.0
for j in range(self.num_hidden):
sum_ += self.hidden_activations[j] * self.weights_output[j]
self.output_activation = log_func(sum_)
return self.output_activation
def compute_output_delta(self):
# Equation 1 from the exercise text
p_ab = log_func(self.prev_output_activation - self.output_activation)
# Equation 2 from the exercise text
self.prev_delta_output = log_func_derivative(self.prev_output_activation) * (1 - p_ab)
# Equation 3 from the exercise text
self.delta_output = log_func_derivative(self.output_activation) * (1 - p_ab)
def compute_hidden_delta(self):
# Equation 4 and 5 in the exercise text
for h in range(self.num_hidden):
# Equation 4
self.prev_delta_hidden[h] = log_func_derivative(self.prev_hidden_activations[h]) * self.weights_output[h] * (self.prev_delta_output - self.delta_output)
# Equation 5
self.delta_hidden[h] = log_func_derivative(self.hidden_activations[h]) * self.weights_output[h] * (self.prev_delta_output - self.delta_output)
def update_weights(self):
# Equation 6 in the exercise text, firstly for the input weights, and then for the output weights
for weight_i in range(self.num_inputs):
for weight_j in range(self.num_hidden):
self.weights_input[weight_i][weight_j] += self.learning_rate * \
((self.prev_delta_hidden[weight_j] * self.prev_input_activations[weight_i]) - \
(self.delta_hidden[weight_j] * self.input_activation[weight_i]))
for weight_i in range(self.num_hidden):
self.weights_output[weight_i] += self.learning_rate * \
((self.prev_hidden_activations[weight_i] * self.prev_delta_output) - \
(self.hidden_activations[weight_i] * self.delta_output))
def backpropagate(self):
self.compute_output_delta()
self.compute_hidden_delta()
self.update_weights()
# Prints the network weights
def weights(self):
print('Input weights:')
for i in range(self.num_inputs):
print(self.weights_input[i])
print()
print('Output weights:')
print(self.weights_output)
def train(self, patterns, iterations=1):
# Backpropagate
error_during_iterations = list()
for iteration in range(iterations):
for a, b in patterns:
self.propagate(a.features)
self.propagate(b.features)
self.backpropagate()
error_during_iterations.append(self.count_misordered_pairs(patterns))
return error_during_iterations
def count_misordered_pairs(self, patterns):
# errorRate = numMisses/(numRight+numMisses)
num_misses = 0
for a, b in patterns:
activation_a = self.propagate(a.features)
activation_b = self.propagate(b.features)
"""
# Not necessary due to patterns already being sorted and reversed
if activation_a > activation_b:
if a.rating > b.rating:
num_right += 1
else:
num_misses += 1
else:
if b.rating > a.rating:
num_right += 1
else:
num_misses += 1
"""
if activation_a < activation_b:
num_misses += 1
# print(num_misses, num_right, len(patterns))
return num_misses / len(patterns)
|
# last element pivot
import random
import time
#end is included index
def quick_sort(array, start, end):
if end > start:
wall = partition(array, start, end)
quick_sort(array, start, wall-1)
quick_sort(array, wall+1, end)
# pivot is the end
def partition(array, start, end):
wall = start
pivot = array[end]
for cur in range(start, end):
if array[cur] < pivot:
array[wall], array[cur] = array[cur], array[wall]
wall += 1
array[wall], array[end] = array[end], array[wall]
return wall
a = [random.randint(0, 500000) for i in range(0,500000)]
# a = [3, 2, 1, 4, 5]
start_time = time.time()
quick_sort(a, 0, len(a)-1)
# print(a)
print("--- %s seconds ---" % (time.time() - start_time))
|
"""
Class that represents an attempt made by students.
"""
class Node:
START_COLOR_CODE = "#9cffed"
GAVE_UP_COLOR_CODE = "#f58787"
CORRECT_COLOR_CODE = "#b3ffb0"
CORRECT_ARROW_COLOR_CODE = "#08d100"
MINIMUM_TO_BE_ANNOTATED = 10
DEGENERATE_CODE = "No completions"
DECIMAL_PRECISION = 2
START_NAME = "Start"
GAVE_UP_NAME = "Gave Up"
def __init__(self, attempt, is_correct):
self.appearances = []
self.distance_sum = 0
self.successful_appearances = 0
self.attempt = attempt
self.is_correct = is_correct
self.node_list = dict()
def add_next(self, next_node, user_string):
if not self.node_list.get(next_node):
self.node_list[next_node] = [user_string]
else:
self.node_list[next_node].append(user_string)
def calculate_goodness(self):
if self.is_correct:
return 2
if self.attempt == self.GAVE_UP_NAME:
return -1
correct = total = 0
for node in self.node_list:
total += len(self.node_list[node])
if node.is_correct:
correct += len(self.node_list[node])
if total == 0:
# Must be an empty lesson
return 0
return float(str((correct / total) + 0.5 * 10 ** -self.DECIMAL_PRECISION)[0: 2 + self.DECIMAL_PRECISION])
def distance(self):
if self.successful_appearances > 0:
distance = str(self.distance_sum / self.successful_appearances)
if len(distance) > 2 + self.DECIMAL_PRECISION:
return distance[0: 2 + self.DECIMAL_PRECISION]
return distance
else:
return self.DEGENERATE_CODE
def return_family(self):
return self.return_family_helper(set())
def return_family_helper(self, already_found):
already_found.add(self)
for node in self.node_list:
if node not in already_found:
already_found = node.return_family_helper(already_found)
return already_found
def find_node(self, attempt, correct):
for node in self.return_family():
# Take away spaces for slight formatting differences
if node.attempt.replace(" ", "") == attempt.replace(" ", "") and node.is_correct == correct:
return node
return None
def add_appearance(self, user_string):
self.appearances.append(user_string)
def add_successful_appearance(self):
self.successful_appearances += 1
def add_distance(self, distance):
self.distance_sum += distance
def to_dict(self):
return {"id": self.get_hash_code(),
"name": self.attempt, "distance": self.distance(), "score": self.calculate_goodness(), "appearances": len(self.appearances), "users": self.appearances}
def edge_dict(self):
edges = []
for dest in self.node_list.keys():
edges.append({"source": self.get_hash_code(
), "target": dest.get_hash_code(), "size": len(self.node_list.get(dest)), "users": self.node_list.get(dest)})
return edges
def get_hash_code(self):
return id(self)
def better_than(self, other):
if self.is_correct:
return True
if other.is_correct:
return False
if self.successful_appearances == 0:
return False
if other.successful_appearances == 0:
return True
return other.distance_sum / other.successful_appearances > self.distance_sum / self.successful_appearances |
"""
https://practice.geeksforgeeks.org/problems/minimum-platforms-1587115620/1#
sort both arr and dep
then move with two pointer approch
"""
class Solution:
#Function to find the minimum number of platforms required at the
#railway station such that no train waits.
def minimumPlatform(self,n,arr,dep):
max_count = 0
curr_count = 0
arr.sort()
dep.sort()
p1 = p2 = 0
while p1 < n:
if arr[p1] <= dep[p2]:
curr_count+=1
p1+=1
else:
curr_count-=1
p2+=1
max_count = max(curr_count,max_count)
return max_count
|
"""
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
Example 1:
Input:
n = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after
sorting it in wave form are
2 1 4 3 5.
Example 2:
Input:
n = 6
arr[] = {2,4,7,8,9,10}
Output: 4 2 8 7 10 9
Explanation: Array elements after
sorting it in wave form are
4 2 8 7 10 9.
Your Task:
The task is to complete the function convertToWave() which converts the given array to wave array.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ n ≤ 106
0 ≤ arr[i] ≤107
"""
class Solution:
def convertToWave(self,arr,N):
for i in range(1,len(arr)):
if i%2 == 0:
if arr[i-1] > arr[i]:
arr[i-1], arr[i] = arr[i], arr[i-1]
else:
if arr[i-1] < arr[i]:
arr[i-1], arr[i] = arr[i], arr[i-1]
return arr
|
"""
https://leetcode.com/problems/longest-consecutive-sequence/
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
Solution Summary:-
Add all element in set, so lookup time complexity will be O(1).
Now iterate complete number list and check if their previous element is exist or not.
If not exist that means , current number will be the starting point of sequence.
Then check for starting sequence number untill we found number+1 element in set.
set current count and max count accordingly.
For more
https://www.youtube.com/watch?v=qgizvmgeyUM&ab_channel=takeUforward
"""
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
hashSet = set(nums)
maxCount = 0
for num in nums:
if num -1 not in hashSet:
count = 1
curr_num = num+1
while curr_num in hashSet:
count+=1
curr_num+=1
maxCount = max(count, maxCount)
return maxCount
|
"""
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Example 2:
Input: nums = [2,9,2,5,6], left = 2, right = 8
Output: 7
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109
Solution summary:-
By seeing array we know element which are greater than right limit , will become breaking points.
We can break this problem in 3 parts.
a:- when element is in range. (left<= element <= right)
b:- when element less than left. ( element < left )
c:- when element greater than right. ( right < element)
a: we can direct calculate.
b: we need old count as new element is not in range , so ending at new element(without max element in subarry) won't usefull cases.
max element = 5
left = 2
eg:- 4,5,3,8,1
cases: -
1 (not useful when max is 5, because subarray doesn't contain 5 )
2,1 (not useful when max is 5, because subarray doesn't contain 5 )
3,2,1 (not useful when max is 5, because subarray doesn't contain 5 )
5,3,2,1 (usefull)
4,5,3,2,1 (usefull)
count = 2 , which will present in previous count.
"""
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
start = 0
prev_count = 0
overall_count = 0
for end in range(len(nums)):
if nums[end] >= left and nums[end] <= right:
prev_count = end-start+1
overall_count += prev_count
elif nums[end] < left:
overall_count += prev_count
else:
start = end+1
prev_count = 0
return overall_count
|
"""
Execution: python cycle.py filename.txt
Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt
https://algs4.cs.princeton.edu/41graph/mediumG.txt
https://algs4.cs.princeton.edu/41graph/largeG.txt
Identifies a cycle.
Runs in O(E + V) time.
% python cycle.py tinyG.txt
3 4 5 3
% python cycle.py mediumG.txt
15 0 225 15
% python cycle.py largeG.txt
996673 762 840164 4619 785187 194717 996673
"""
from algs4.graph import Graph
class Cycle:
def __init__(self, G):
self.marked = [False for _ in range(G.V)]
self.has_cycle = False
for s in range(G.V):
if not self.marked[s]:
self.dfs(G, s, s)
def dfs(self, G, v, u):
self.marked[v] = True
for w in G.adj[v]:
if not self.marked[w]:
self.dfs(G, w, v)
elif w != u:
self.has_cycle = True
if __name__ == "__main__":
import sys
f = open(sys.argv[1])
V = int(f.readline())
E = int(f.readline())
g = Graph(V)
for i in range(E):
v, w = f.readline().split()
g.add_edge(v, w)
cycle = Cycle(g)
if cycle.has_cycle:
print("Graph is cyclic")
else:
print("Graph is acyclic")
|
"""
Execution: python RedBlackBST.py < input.txt
Data files: https://algs4.cs.princeton.edu/33balanced/tinyST.txt
A symbol table implemented using a left-leaning red-black BST.
This is the 2-3 version.
% more tinyST.txt
S E A R C H E X A M P L E
% python RedBlackBST.py < tinyST.txt
A 8
C 4
E 12
H 5
L 11
M 9
P 10
R 3
S 0
X 7
"""
from algs4.queue import Queue
class Node:
def __init__(self, key, val, color, size):
self.key = key
self.val = val
self.left = None
self.right = None
self.color = color
self.size = size
class RedBlackBST:
RED = True
BLACK = False
def __init__(self):
self.root = None
def is_red(self, x):
if x is None:
return False
return x.color == RedBlackBST.RED
def size(self):
return self._size(self.root)
def _size(self, x):
if x is None:
return 0
return x.size
def is_empty(self):
return self.root is None
def get(self, key):
return self._get(self.root, key)
def _get(self, x, key):
while x is not None:
if x.key == key:
return x.val
elif x.key < key:
x = x.right
else:
x = x.left
return None
def contains(self, key):
return self.get(key) is not None
def put(self, key, val):
self.root = self._put(self.root, key, val)
self.root.color = RedBlackBST.BLACK
def _put(self, x, key, val):
if x is None:
return Node(key, val, RedBlackBST.RED, 1)
if x.key > key:
x.left = self._put(x.left, key, val)
elif x.key < key:
x.right = self._put(x.right, key, val)
else:
x.val = val
# fix-up any right-leaning links
if self.is_red(x.right) and not self.is_red(x.left):
x = self.rotate_left(x)
if self.is_red(x.left) and self.is_red(x.left.left):
x = self.rotate_right(x)
if self.is_red(x.left) and self.is_red(x.right):
self.flip_colors(x)
x.size = self._size(x.left) + self._size(x.right) + 1
return x
def rotate_left(self, h):
x = h.right
h.right = x.left
x.left = h
x.color = h.color
h.color = RedBlackBST.RED
x.size = h.size
h.size = self._size(h.left) + self._size(h.right) + 1
return x
def rotate_right(self, h):
x = h.left
h.left = x.right
x.right = h
x.color = h.color
h.color = RedBlackBST.RED
x.size = h.size
h.size = self._size(h.left) + self._size(h.right) + 1
return x
def flip_colors(self, h):
"""
flip the colors of a node and its two children
"""
h.color = not h.color
h.left.color = not h.left.color
h.right.color = not h.right.color
def move_red_left(self, h):
"""
Assuming that h is red and both h.left and h.left.left
are black, make h.left or one of its children red.
"""
self.flip_colors(h)
if self.is_red(h.right.left):
h.right = self.rotate_right(h.right)
h = self.rotate_left(h)
self.flip_colors(h)
return h
def move_red_right(self, h):
"""
Assuming that h is red and both h.right and h.right.left
are black, make h.right or one of its children red.
"""
self.flip_colors(h)
if self.is_red(h.left.left):
h = self.rotate_right(h)
self.flip_colors(h)
return h
def height(self):
return self._height(self.root)
def _height(self, x):
if x is None:
return -1
return 1 + max(self._height(x.left), self._height(x.right))
def level_order(self):
"""Return the keys in the BST in level order"""
keys = Queue()
queue = Queue()
queue.enqueue(self.root)
while not queue.is_empty():
x = queue.dequeue()
if x is None:
continue
keys.enqueue(x.key)
queue.enqueue(x.left)
queue.enqueue(x.right)
return keys
def Keys(self):
"""
Returns all keys in the symbol table
To iterate over all of the keys in the symbol table named {@code st},
use the foreach notation: {for key in st.keys}
"""
queue = Queue()
self._keys(self.root, queue, self.min(), self.max())
return queue
def _keys(self, x, queue, lo, hi):
if x is None:
return
if x.key > lo:
self._keys(x.left, queue, lo, hi)
if lo <= x.key <= hi:
queue.enqueue(x.key)
if x.key < hi:
self._keys(x.right, queue, lo, hi)
def max(self):
return self._max(self.root).key
def _max(self, x):
if x.right is None:
return x
return self._max(x.right)
def min(self):
return self._min(self.root).key
def _min(self, x):
if x.left is None:
return x
return self._min(x.left)
def floor(self, key):
x = self._floor(self.root, key)
if x is None:
return x
else:
return x.key
def _floor(self, x, key):
if x is None:
return None
if x.key == key:
return x
elif x.key > key:
return self._floor(x.left, key)
t = self._floor(x.right, key)
if t is not None:
return t
else:
return x
def ceiling(self):
x = self._ceiling(self.root, key)
if x is None:
return x
else:
return x.key
def _ceiling(self, x, key):
if x is None:
return None
if x.key == key:
return x
elif x.key < key:
return self._ceiling(x.left, key)
t = self._ceiling(x.right, key)
if t is not None:
return t
else:
return x
def select(self, k):
return self._select(self.root, k).key
def _select(self, x, k):
if x is None:
return
t = self._size(x.left)
if t > k:
return self._select(x.left, k)
elif t < k:
return self._select(x.right, k - t - 1)
else:
return x
def rank(self, key):
return self._rank(self.root, key)
def _rank(self, x, key):
if x is None:
return 0
if x.key > key:
return self._rank(x.left, key)
elif x.key < key:
return 1 + self._size(x.left) + self._rank(x.right, key)
else:
return self._size(x.left)
def delete(self, key):
if key is None:
raise ValueError("argument is null")
# if both children of root are black, set root to red
if not self.is_red(self.root.left) and not self.is_red(self.root.right):
self.root.color = RedBlackBST.RED
self.root = self._delete(self.root, key)
if not self.is_empty():
self.root.color = RedBlackBST.BLACK
def _delete(self, h, key):
if h is None:
return None
if h.key > key:
if not self.is_red(h.left) and not self.is_red(h.left.left):
h = self.move_red_left(h)
h.left = self._delete(h.left, key)
else:
if self.is_red(h.left):
h = self.rotate_right(h)
if key == h.key and h.right is None:
return None
if not self.is_red(h.right) and not self.is_red(h.right.left):
h = self.move_red_right(h)
if key == h.key:
x = self._min(h.right)
h.key = x.key
h.val = x.val
h.right = self._delete_min(h.right)
else:
h.right = self._delete(h.right, key)
return self.balance(h)
def delete_min(self):
if self.is_empty():
raise ValueError("BST underflow")
if not self.is_red(self.root.left) and not self.is_red(self.root.right):
self.root.color = RedBlackBST.RED
self.root = self._delete_min(self.root)
if not self.is_empty():
self.root.color = RedBlackBST.BLACK
def _delete_min(self, h):
if h.left is None:
return None
if not self.is_red(h.left) and not self.is_red(h.left.left):
h = self.move_red_left(h)
h.left = self._delete_min(h.left)
return self.balance(h)
def balance(self, h):
if self.is_red(h) and not self.is_red(h.left):
h = self.rotate_left(h)
if self.is_red(h.left) and self.is_red(h.left.left):
h = self.rotate_right(h)
if self.is_red(h.left) and self.is_red(h.right):
self.flip_colors(h)
h.size = self._size(h.left) + self._size(h.right) + 1
return h
if __name__ == '__main__':
import sys
st = RedBlackBST()
i = 0
for line in sys.stdin:
for key in line.split():
st.put(key, i)
i += 1
for s in st.level_order():
print(s + " " + str(st.get(s)))
print()
for s in st.Keys():
print(s + " " + str(st.get(s)))
|
"""
Execution: python separate_chaining_hash_st.py < input.txt
Data files: https://algs4.cs.princeton.edu/33balanced/tinyST.txt
A symbol table implemented using a separate chaining hash.
This is the 2-3 version.
% more tinyST.txt
S E A R C H E X A M P L E
% python separate_chaining_hash_st.py < tinyST.txt
A 8
C 4
E 12
H 5
L 11
M 9
P 10
R 3
S 0
X 7
"""
from algs4.queue import Queue
from algs4.sequential_search_st import SequentialSearchST
class SeparateChainingHashST:
INIT_CAPACITY = 4
def __init__(self, m=None):
self.n = 0 # key size
self.m = m or SeparateChainingHashST.INIT_CAPACITY # hash table size
self.st = [SequentialSearchST() for _ in range(m)]
def hash(self, key):
return (hash(key) & 0x7FFFFFFF) % self.m
def size(self):
return self.n
def is_empty(self):
return self.size() == 0
def get(self, key):
return self.st[self.hash(key)].get(key)
def contains(self, key):
return self.get(key) is not None
def put(self, key, val):
# double table size if 50% full
if (self.n >= self.m * 10):
self.resize(2 * self.m)
self.st[self.hash(key)].put(key, val)
def keys(self):
"""
Returns all keys in the symbol table
To iterate over all of the keys in the symbol table named {@code st},
use the foreach notation: {for key in st.keys}
"""
queue = Queue()
for s in self.st:
for key in s.keys():
queue.enqueue(key)
return queue
def delete(self, key):
self.st[self.hash(key)].delete(key)
def resize(self, chains):
tmp = SeparateChainingHashST(chains)
for i in range(self.m):
for key in self.st[i].keys():
tmp.put(key, self.st[i].get(key))
self.m = tmp.m
self.n = tmp.n
self.st = tmp.st
if __name__ == '__main__':
import sys
st = SeparateChainingHashST(100)
i = 0
for line in sys.stdin:
for key in line.split():
st.put(key, i)
i += 1
for s in st.keys():
print(s + " " + str(st.get(s)))
|
"""
Sorts a sequence of strings from standard input using quick 3-way sort.
% more tiny.txt
S O R T E X A M P L E
% python quick_3way.py < tiny.txt
A E E L M O P R S T X [ one string per line ]
% more words3.txt
bed bug dad yes zoo ... all bad yet
% python quick_3way.py < words3.txt
all bad bed bug dad ... yes yet zoo [ one string per line ]
"""
class Quick3Way:
@classmethod
def quicksort(cls, arr, lo, hi):
if lo >= hi:
return
lt = lo
gt = hi
i = lo + 1
v = arr[lo]
while i <= gt:
if arr[i] < v:
arr[i], arr[lt] = arr[lt], arr[i]
lt += 1
elif arr[i] > v:
arr[i], arr[gt] = arr[gt], arr[i]
gt -= 1
else:
i += 1
cls.quicksort(arr, lo, lt - 1)
cls.quicksort(arr, gt + 1, hi)
return arr
@classmethod
def sort(cls, arr):
return cls.quicksort(arr, 0, len(arr) - 1)
@classmethod
def is_sorted(cls, arr):
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
if __name__ == '__main__':
import sys
items = []
for line in sys.stdin:
items.extend(line.split())
print(' items: ', items)
print('sort items: ', Quick3Way.sort(items))
assert Quick3Way.is_sorted(items)
|
#!./anaconda/bin/python
import random
SIZE=3
SYMBOLS=['X','O']
def print_grid(grid):
print(f' {grid[0][0]} | {grid[0][1]} | {grid[0][2]} ')
print('-----------')
print(f' {grid[1][0]} | {grid[1][1]} | {grid[1][2]} ')
print('-----------')
print(f' {grid[2][0]} | {grid[2][1]} | {grid[2][2]} ')
def create_grid():
grid = []
for row in range(SIZE):
row = []
for col in range(SIZE):
row.append(' ')
grid.append(row)
return grid
def ask_for_symbol():
def get_symbol():
return input(f"Please choose a symbol by typing '{SYMBOLS[0]}' or '{SYMBOLS[1]}': ")
symbol = get_symbol()
while not symbol in SYMBOLS:
print(f'Invalid symbol. Please choose {SYMBOLS[0]} or {SYMBOLS[1]}')
symbol = ask_for_symbol()
return symbol
def opposite_symbol(symbol):
if symbol == SYMBOLS[0]:
return SYMBOLS[1]
else:
return SYMBOLS[0]
def player_move(symbol, grid):
def get_move():
choice = input(f"{symbol}'s turn. Please choose a row,col: ").strip()
inputs = choice.split(',')
for i in inputs:
i.strip()
try:
row = int(inputs[0])
col = int(inputs[1])
except:
print('Invalid row,col. Please choose again')
row, col = get_move()
return row, col
row, col = get_move()
while grid[row][col] != ' ':
row, col = get_move()
grid[row][col] = symbol
def computer_move(symbol, grid):
def get_move():
row = random.randint(0, SIZE - 1)
col = random.randint(0, SIZE - 1)
return row, col
row, col = get_move()
while not is_over(grid) and grid[row][col] != ' ':
row, col = get_move()
grid[row][col] = symbol
def check_for_row(symbol, grid):
any_rows = False
for row in grid:
still_valid = True
for col in row:
if col != symbol:
still_valid = False
if still_valid:
any_rows = True
return any_rows
def check_for_col(symbol, grid):
any_cols = False
for col in range(SIZE):
still_valid = True
for row in grid:
if row[col] != symbol:
still_valid = False
if still_valid:
any_cols = True
return any_cols
def check_for_diagonal(symbol, grid):
first_diagonal = False
still_valid = True
for i in range(SIZE):
if grid[i][i] != symbol:
still_valid = False
first_diagonal = still_valid
second_diagonal = False
still_valid = True
for row_idx in range(len(grid)):
for col_idx in range(len(grid[row_idx])):
if row_idx + col_idx == len(grid) - 1:
if grid[row_idx][col_idx] != symbol:
still_valid == False
second_diagonal = still_valid
return first_diagonal or second_diagonal
def three_in_a_row(symbol, grid):
in_row = check_for_row(symbol, grid)
in_col = check_for_col(symbol, grid)
in_diagonal = check_for_diagonal(symbol, grid)
return in_row or in_col or in_diagonal
def full_grid(grid):
for row in grid:
for col in row:
if col == ' ':
return False
return True
def is_over(grid):
if full_grid(grid):
return True
else:
for symbol in SYMBOLS:
if three_in_a_row(symbol, grid):
return True
return False
if __name__ == "__main__":
grid = create_grid()
print_grid(grid)
player_symbol = ask_for_symbol()
computer_symbol = opposite_symbol(player_symbol)
while not is_over(grid):
player_move(player_symbol, grid)
computer_move(computer_symbol, grid)
print_grid(grid)
if three_in_a_row(player_symbol, grid):
print("You Win!")
elif three_in_a_row(computer_symbol, grid):
print("You lost, maybe next time!")
else:
print("Stalemate!")
print("Thanks for playing!")
|
#!/usr/bin/env python
# What is this ^ for?
# The line above the previous one says where in your environment to find the python executable.
def main(options):
# reading in the output file
output_file = options.output_file
#print(type(output_file))
# reading in the gtf file
gtf_file = options.gtf_file
#print(type(gtf_file)) # what type() of python object is this?
with open(output_file,'w') as out:
#print(type(out))
# opening the gtf_file as a file object
with open(gtf_file) as gtf:
# doing things with the file opened
# Parse each line of the .gtf into a list such that each line is one element in the list
# There should be no newlines at the end of each element and this can be done in 1 to 2 lines of code
# see functions read() and splitlines() for how to do this
gtf_all = gtf.read()
gtf_list = gtf_all.splitlines()
#print(gtf_list[0])
#print(gtf_list[2])
#print(type(gtf_all))
#print(gtf_all)
for line in gtf_list:
# split the current line into another list (curr_list) based using the "\t" (tab) delimiter, see the split() function
# split the last element in this list based on the ";" delimiter. store this in a variable, see the split() function
#print(line)
curr_list = line.split("\t")
# print(curr_list)
#chromosome is 0
#Start at 3
#Stop at 4
#Strand is + (6)
# extract the chromosome, start location, end location, and strand from the line. store them in separate variables
print_statement = "%s\t%s\t%s\t%s\t%s"
chromosome = curr_list[0]
start_location = curr_list[3]
stop_location = curr_list[4]
strand = curr_list[6]
# if the line is a gene:
# extract the gene_id without quotations from the split last line variable
# see string.replace() for getting rid of the quotations
# form the gene_id line in string format
if curr_list[2] == "gene":
gene_id_full = curr_list[8]
new_list = curr_list[8].split(';')
#print(new_list)
gene_id_list = new_list[0]
#print(gene_id_list)
gene_id_string = gene_id_list.split(" ")
#print(gene_id_string)
gene_id_true = gene_id_string[1]
#print(gene_id_true)
gene_id_real = gene_id_true.replace('"',"")
#print(gene_id_real)
print_statement_gene = print_statement%(chromosome, start_location, stop_location, strand, gene_id_real)
print(print_statement_gene, file = out)
elif curr_list[2] == "transcript":
gene_id_full = curr_list[8]
new_list_transcript = curr_list[8].split(';')
#print(new_list_transcript)
transcript_id_list = new_list_transcript[2]
#print(transcript_id_list)
transcript_id_new = transcript_id_list.split(" ")
#print(transcript_id_new)
transcript_id_true = transcript_id_new[2]
#print(transcript_id_true)
transcript_id_real = transcript_id_true.replace('"',"")
#print(transcript_id_real)
print_statement_transcript = print_statement%(chromosome, start_location, stop_location, strand, transcript_id_real)
print(print_statement_transcript, file = out)
#print(gene_id_line,file=out)
# else if the line is a transcript:
# extract the transcript_id without quotations from the split last line variable
# see string.replace() for getting rid of the quotations
# form the transcript_id line in string format
#print(transcript_id_line,file=out)
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-o", "--output_file", dest="output_file",
help="The output file to print to")
parser.add_option("-g", "--gtf_file", dest="gtf_file",
help="The gtf file")
(options, args) = parser.parse_args()
main(options)
|
# if statements
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
print("Buyer needs to put down 10%")
else:
down_payment = 0.2 * price
print("Buyer needs to put down 20%")
print(f"Down payment: ${down_payment}") |
import sqlite3
#conn = sqlite3.connect('sqlitetest.db')
sqlite_file = 'C:\sqlite\db\sqlitetestdb.sqlite'
table_name = 'memberTable1'
col_fName = 'firstName'
col_sType = 'TEXT'
col_iType = 'INTEGER'
# Connecting to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# Creating a new SQLite table with 1 column
c.execute(f'CREATE TABLE {table_name} ({col_fName} {col_sType})')
# Committing changes and closing the connection to the database file
conn.commit()
conn.close()
|
# comparison operators
temperature = 35
if temperature > 30:
print("It's a hot day.")
else:
print("It's not a hot day.")
# exercise - If name is less than 3 characters long
# name must be at least 3 characters
# otherwise if it's more than 50 characters long
# name can be maximum of 50 characters
# otherwise
# name looks good!
name = "John Smith"
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 50:
print("Name must be a maximum of 50 characters")
else:
print("Name looks good")
print(name)
|
my_number = raw_input('Please Enter a Number: \n')
Please Enter a Number:
1337
print(my_number)
1337
# In Python 2 input(x) is just eval(raw_input(x)). eval() will just evaluate a generic string as if it were a Python expression.
my_raw_input = raw_input('Please Enter a Number: \n')
Please Enter a Number:
123 + 1 # This is treated like a raw string.
my_input = input('Please Enter a Number: \n')
Please Enter a Number:
123 + 1 # This is treated like an expression.
print(my_raw_input)
123 + 1
print(my_input)
124 # See that the expression was evaluated!
# In Python 3
# raw_input doesn’t natively exist in Python 3
# Taking an input from a user, input should be used. See the below sample:
my_number = input('Please Enter a Number: \n')
Please Enter a Number:
123 + 1
print(my_number)
123 + 1
type(my_number)
<class 'str'>
'''
Notice that the expression is treated just like a string. It is not evaluated.
If we want to, we can call eval() and that will actually execute the string as an expression:
'''
Please Enter a Number:
123 + 1
>>> print(my_number)
123 + 1
>>> eval(my_number)
124
|
import unittest
import re
my_txt = "An investment in knowledge pays the best interest."
def LetterCompiler(txt):
result = re.findall(r'([a-c]).', txt)
return result
print(LetterCompiler(my_txt))
class TestCompiler(unittest.TestCase):
def test_basic(self):
testcase = "The best preparation for tomorrow is doing your best today."
expected = ['b', 'a', 'a', 'b', 'a']
print("This Code is Executed")
self.assertEqual(LetterCompiler(testcase), expected)
if __name__ == '__main__':
unittest.main() |
import math as mymath
import unittest
# THIS CODE NEEDS TO BE FIXED, add function not available...
# i modified mymath module as math module from original code.. mymath is old module it seems , study more
class TestAdd(unittest.TestCase):
"""
Test the add function from the mymath library
"""
def test_add_integers(self):
"""
Test that the addition of two integers returns the correct total
"""
result = mymath.add(1, 2)
self.assertEqual(result, 3)
def test_add_floats(self):
"""
Test that the addition of two floats returns the correct result
"""
result = mymath.add(10.5, 2)
self.assertEqual(result, 12.5)
def test_add_strings(self):
"""
Test the addition of two strings returns the two string as one
concatenated string
"""
result = mymath.add('abc', 'def')
self.assertEqual(result, 'abcdef')
if __name__ == '__main__':
unittest.main() |
"""
* Assignment: Type Float Altitude
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Plane altitude is 10.000 ft
2. Data uses imperial (US) system
3. Convert to metric (SI) system
4. Result round to one decimal place
5. Compare result with "Tests" section (see below)
Polish:
1. Wysokość lotu samolotem wynosi 10 000 ft
2. Dane używają systemu imperialnego (US)
3. Przelicz je na system metryczny (układ SI)
4. Wynik zaokrąglij do jednego miejsca po przecinku
5. Porównaj wyniki z sekcją "Tests" (patrz poniżej)
Tests:
>>> type(altitude)
<class 'float'>
>>> imperial
10000.0
>>> metric
3048.0
"""
# Given
m = 1
ft = 0.3048 * m
altitude = ... # 10.000 ft
imperial = ... # altitude in feet
metric = ... # altitude in meters
altitude = 10_000.0
imperial = altitude * m
metric = altitude * ft |
"""
* Assignment: Type Int Bits
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Calculate altitude in kilometers:
a. Kármán Line Earth: 100_000 m
b. Kármán Line Mars: 80_000 m
c. Kármán Line Venus: 250_000 m
2. In Calculations use floordiv (`//`)
3. Compare result with "Tests" section (see below)
Polish:
1. Oblicz wysokości w kilometrach:
a. Linia Kármána Ziemia: 100_000 m
b. Linia Kármána Mars: 80_000 m
c. Linia Kármána Wenus: 250_000 m
2. W obliczeniach użyj floordiv (`//`)
3. Porównaj wyniki z sekcją "Tests" (patrz poniżej)
Hints:
* 1 km = 1000 m
Tests:
>>> type(karman_line_earth)
<class 'int'>
>>> type(karman_line_mars)
<class 'int'>
>>> type(karman_line_venus)
<class 'int'>
>>> karman_line_earth
100
>>> karman_line_mars
80
>>> karman_line_venus
250
"""
# Given
m = 1
km = 1000 * m
karman_line_earth = ... # 100_000 meters in km
karman_line_mars = ... # 80_000 meters in km
karman_line_venus = ... # 250_000 meters in km
karman_line_earth = int(100_000 / km)
karman_line_mars = int(80_000 / km)
karman_line_venus = int(250_000 / km) |
"""
* Assignment: Type Int Bandwidth
* Complexity: easy
* Lines of code: 10 lines
* Time: 3 min
English:
1. Having internet connection with speed 100 Mb/s
2. How long will take to download 100 MB?
3. To calculate time divide file size by speed
3. Note, that all values must be `int` (type cast if needed)
3. In Calculations use floordiv (`//`)
4. Compare result with "Tests" section (see below)
Polish:
1. Mając łącze internetowe 100 Mb/s
2. Ile zajmie ściągnięcie pliku 100 MB?
3. Aby wyliczyć czas podziel wielkość pliku przez prękość
3. Zwróć uwagę, że wszystkie wartości mają być `int` (rzutuj typ jeżeli potrzeba)
3. W obliczeniach użyj floordiv (`//`)
4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)
Hints:
* 1 Kb = 1024 b
* 1 Mb = 1024 Kb
* 1 B = 8 b
* 1 KB = 1024 B
* 1 MB = 1024 KB
Tests:
>>> type(bandwidth)
<class 'int'>
>>> type(size)
<class 'int'>
>>> type(duration)
<class 'int'>
>>> duration // SECOND
8
"""
# Given
SECOND = 1
b = 1
kb = 1024 * b
Mb = 1024 * kb
B = 8 * b
kB = 1024 * B
MB = 1024 * kB
bandwidth = ... # 100 megabits per second
size = ... # 100 megabytes
duration = ... # size by bandwidth in seconds
bandwidth = 100 * Mb * SECOND
size = 100 * MB
duration = int(size / bandwidth) |
def anagramSolution2(s1,s2):
alist1 = list(s1)
alist2 = list(s2)
alist1.sort()
alist2.sort()
pos = 0
matches = True
while pos < len(s1) and matches:
if alist1[pos]==alist2[pos]:
pos = pos + 1
else:
matches = False
return matches
f = open("latinwords.txt","r")
words = [line.rstrip('\n') for line in f]
anas = []
myword = "oplucsn"
for word in words:
if len(word) >= 8:
if anagramSolution2(myword, word):
anas.append(word)
print anas
|
"""
This code searches through a text file and prints out all alphabetic characters
"""
f = open('chall2.txt','r')
myli = []
while True:
c = f.read(1)
if not c:
print "End of File"
break
if c.isalpha():
myli.append(c)
print "".join(myli)
|
#To sort the given sentence's words in ascending order
inputString=input("Enter the input String : ")
print("Sorting the input string words in ascending order :")
wordList=list(inputString.split(" "))
wordList.sort()
print(wordList)
|
Symbol="*"
def main():
password=input("Enter the password:")
while not valid_password(password):
print("Invalid password")
password=input("Enter the password:")
def valid_password(password):
if len(password)<=0:
return False
password_count=0
for char in password:
if char.islower():
password_count +=1
if char.isupper():
password_count += 1
for i in range(password_count):
print(Symbol,end='')
if password_count<0:
return False
return True
main()
|
class Elevador:
"""Um elevador pro InfinityElevator8000.
Atributos:
andar: em qual andar ele está.
direção: se está parado, subindo ou descendo.
funcionando: True a menos que esteja quebrado.
chamados: lista de andares por visitar.
Métodos:
chamar(andar): adiciona o andar na lista de chamados.
display(): exibe uma string com o status do elevador.
"""
def __init__(self, andar, direcao="parado", quebrado=False):
"""Inicializa um elevador com andar,
direção e condição caso esteja quebrado."""
self.andar = andar
self.direcao = direcao
self.funcionando = not quebrado
self.chamados = []
pass
def quebra(self):
"""Marca o elevador como fora de operação"""
self.funcionando = False
def display(self):
"""Exibe o status do elevador."""
if not self.funcionando:
return f"Fora de Operação"
return f"Estamos no andar {self.andar} e estamos {self.direcao}"
def chama(self, andar):
"""Recebe um chamado."""
self.chamados.append(andar)
self.chamados.sort()
def atualiza_chamados(self):
if self.andar in self.chamados:
self.chamados = [
chamado for chamado in self.chamados
if chamado != self.andar]
def sobe(self):
self.direcao = 'subindo'
proximos = [
chamado for chamado in self.chamados
if chamado > self.andar]
if proximos:
self.andar += 1
self.atualiza_chamados()
return True
def desce(self):
self.direcao = 'descendo'
proximos = [
chamado for chamado in self.chamados
if chamado < self.andar]
if proximos:
self.andar -= 1
self.atualiza_chamados()
return True
def tic(self):
"""Move o elevador se necessário"""
if not self.chamados:
self.direcao = "parado"
return
if self.direcao == 'subindo':
self.sobe() or self.desce()
else: # só pode estar descendo
self.desce() or self.sobe()
elevador_a = Elevador(0)
elevador_b = Elevador(0, quebrado=True) |
"""
File: fire.py
---------------------------------
This file contains a method called
highlight_fires which detects the
pixels that are recognized as fire
and highlights them for better observation.
"""
from simpleimage import SimpleImage
# Constants
HURDLE_FACTOR = 1.05 # Controls the threshold of detecting green screen pixel
def highlight_fires(filename):
"""
:param filename:str, the file path of the original image
:return: img: The image with highlighted fire
"""
highlighted_fire = SimpleImage('images/greenland-fire.png')
for pixel in highlighted_fire:
# The average can make the picture gray
avg = (pixel.red+pixel.blue+pixel.green)//3
# Only highlight the red part
if pixel.red > avg*HURDLE_FACTOR:
pixel.red = 255
pixel.green = 0
pixel.blue = 0
else:
# gray
pixel.red = avg
pixel.green = avg
pixel.blue = avg
return highlighted_fire
def main():
"""
This function conducts the highlighted of fire
that is able to detect the fire place and turn the over area to gray
"""
original_fire = SimpleImage('images/greenland-fire.png')
original_fire.show()
highlighted_fire = highlight_fires('images/greenland-fire.png')
highlighted_fire.show()
if __name__ == '__main__':
main()
|
def write_scores(filename, scores):
"""This is a utility function to save scores from a simulation
:param filename: Filename to save scores under
:param scores: List of scores to save to file
:return: Void, writes to files stored in saved_scores
"""
f = open(f"C:\Dev\Python\RL\Policy-Based-Methods\saved_scores\\{filename}.txt", 'w')
score_string = '\n'.join([str(score) for score in scores])
f.write(score_string)
f.close()
def load_scores(filename):
"""Load in scores from a specific file and return them in a list
:param filename: File to load scores from
:return: list of all the scores
"""
scores = []
f = open(filename, 'r')
for score in f:
scores.append(int(score))
return scores
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Qian.Wu
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""
对比列表和字典的包含操作的效率
"""
import timeit
import random
'''比较list 和 dict之间的时间差'''
for i in range(10000, 1000001, 20000):
t = timeit.Timer("random.randrange(%d) in x"%i, "from __main import x, random")
x = list(range(i))
lst_time = t.timeit(number=1000)
x = {j:None for j in range(i)}
dict_time = t.timeit(number=1000)
print("%d, %10.3f, %10.3f" %(i, lst_time, dict_time))
'''设计实现证明列表的索引操作是o(1)的'''
for i in range(10000, 1000001, 20000):
t = timeit.Timer("x[random.randrange(%d)]"%(i), "from __main__ import x, random")
x = list(range(i))
list_index_time = t.timeit(number=1000)
print("%d, %10.3f" %(i, list_index_time))
'''设计实现证明字典的读取和赋值操作都是O(1)的'''
for i in range(1000, 1000001, 20000):
t = timeit.Timer("x[random.randrange(%d)]"%i, "from __main__ import x, random")
x = {j:None for j in range(i)}
dict_read_time = t.timeit(number=1000)
t = timeit.Timer("x[random.randrange(%d)]=random.randrange(%d)" % (i, i), "from __main__ import x, random")
x = {j: None for j in range(i)}
dict_assign_time = t.timeit(number=1000)
print("%d,readtime %10.3f,assign_time %10.3f"%(i, dict_read_time, dict_assign_time))
|
"""
CHECKS IF THE EQUATIONS ARE EQUALS OR NOT
EQ FROM: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/assignments/MIT6_042JF10_assn01.pdf
"""
F = False
T = True
p = F
q = F
r = F
equation1 = not (p or (q and r))
equation2 = (not p) and (not q or not r)
equation1b = not (p and (q or r))
equation2b = not p or (not q or not r)
for i in range(2):
p = i
for j in range(2):
q = j
for k in range(2):
r = k
print(equation1 == equation2)
print(equation1b == equation2b)
|
# -*- coding: utf-8 -*-
"""
About the data:
Let’s consider a Company dataset with around 10 variables and 400 records.
The attributes are as follows:
Sales -- Unit sales (in thousands) at each location
Competitor Price -- Price charged by competitor at each location
Income -- Community income level (in thousands of dollars)
Advertising -- Local advertising budget for company at each location (in thousands of dollars)
Population -- Population size in region (in thousands)
Price -- Price company charges for car seats at each site
Shelf Location at stores -- A factor with levels Bad, Good and Medium indicating the quality of the shelving location for the car seats at each site
Age -- Average age of the local population
Education -- Education level at each location
Urban -- A factor with levels No and Yes to indicate whether the store is in an urban or rural location
US -- A factor with levels No and Yes to indicate whether the store is in the US or not
The company dataset looks like this:
Problem Statement:
A cloth manufacturing company is interested to know about the segment or attributes causes high sale.
Approach - A decision tree can be built with target variable Sale (we will first convert it in categorical variable) & all other variable will be independent in the analysis.
"""
#importing libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#importing dataset
company_ds = pd.read_csv("C:\\DataScience\\Assignments\\Decision Tree\\Company_Data.csv")
#Creating Dummy columns for Categorical Variables
company_ds.loc[:,'ShelveLocnum'] = company_ds.ShelveLoc.map(dict(Bad = 0,Medium=1,Good = 2))
company_ds.loc[:,'Urbannum'] = company_ds.Urban.map(dict(Yes=1,No = 0))
company_ds.loc[:,'USnum'] = company_ds.US.map(dict(Yes=1,No = 0))
print (company_ds.dtypes)
data = company_ds.iloc[:,[0,1,2,3,4,5,7,8,11,12,13]]
data.loc[ data.Sales < 5.0, 'SO' ] = 'small'
data.loc[(data.Sales >= 5.0 ) & (data.Sales < 10.0), 'SO'] = 'medium'
data.loc[ data.Sales >= 5.0, 'SO' ] = 'large'
ip = data.iloc[:,1:11]
op = data.iloc[:,11]
# Splitting data into training and testing data set
from sklearn.model_selection import train_test_split
ip_train,ip_test,op_train,op_test = train_test_split(ip,op, test_size = 0.2, random_state= 0)
#implementing Decision Tree Classifier
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy')
classifier = classifier.fit(ip_train,op_train)
preds = classifier.predict(ip_test)
pd.crosstab(op_test,preds)
np.mean(preds==op_test) # 0.8
"""
Use decision trees to prepare a model on fraud data
treating those who have taxable_income <= 30000 as "Risky" and others are "Good"
Data Description :
Undergrad : person is under graduated or not
Marital.Status : marital status of a person
Taxable.Income : Taxable income is the amount of how much tax an individual owes to the government
Work Experience : Work experience of an individual person
Urban : Whether that person belongs to urban area or not
"""
#importing libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#importing dataset
Fraud_ds = pd.read_csv("C:\\DataScience\\Assignments\\Decision Tree\\Fraud_check.csv")
Fraud_ds.rename(columns = {'Marital.Status': 'Marital_Stat' ,'Taxable.Income': 'Tax_Inc','City.Population' : 'City_Pop', 'Work.Experience' :'Work_Exp' }, inplace = True)
colnames = list(Fraud_ds.columns)
#Creating Dummy columns for Categorical Variables
Fraud_ds.loc[:,'Undergradnum'] = Fraud_ds.Undergrad.map(dict(YES=1,NO = 0))
Fraud_ds.loc[:,'MStatusnum'] = Fraud_ds.Marital_Stat.map(dict(Single=1,Married = 2, Divorced = 0))
Fraud_ds.loc[:,'Urbannum'] = Fraud_ds.Urban.map(dict(YES=1,NO = 0))
#Creating Categorical op variable
Fraud_ds.loc[ Fraud_ds.Tax_Inc <= 30000, 'SO' ] = 'Risky'
Fraud_ds.loc[ Fraud_ds.Tax_Inc > 30000, 'SO' ] = 'Good'
ip = Fraud_ds.iloc[:,[2,3,4,6,7,8]]
op = Fraud_ds.iloc[:,9]
# Splitting data into training and testing data set
from sklearn.model_selection import train_test_split
ip_train,ip_test,op_train,op_test = train_test_split(ip,op, test_size = 0.2, random_state= 0)
#implementing Decision Tree Classifier
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy')
classifier = classifier.fit(ip_train,op_train)
preds = classifier.predict(ip_test)
pd.crosstab(op_test,preds)
np.mean(preds==op_test) # 100
|
# TheAntsGoMarchingLyric.py
# This program print the lyrics of The Ants Go Marching
# Writen by: Ali Arefi
def marchinglLyric(quantity, disturb):
print("The ants go marching {0} by {0}, hurrah, hurrah\n\
The ants go marching {0} by {0}, hurrah, hurrah\n\
The ants go marching {0} by {0},\n\
The little one stops to {1},\n\
And they all go marching down to the ground\n\
To get out of the rain, BOOM! BOOM! BOOM!\n\n" .format(quantity, disturb))
def main():
marchinglLyric("one", "suck his thumb")
marchinglLyric("two", "tie his shoe")
marchinglLyric("three", "climb a tree")
marchinglLyric("four", "shut the door")
marchinglLyric("five", "take a dive")
marchinglLyric("six", "pick up sticks")
marchinglLyric("seven", "pray to heaven")
marchinglLyric("eight", "roller skate")
marchinglLyric("nine", "scheck the time")
marchinglLyric("ten", "shout 'The End'")
main()
|
#!/usr/bin/python
# https://www.hackerrank.com/challenges/py-introduction-to-sets
# Enter your code here. Read input from STDIN. Print output to STDOUT
inputVal=int(input().strip());
inputArr=input().strip().split(" ");
tmpSet=set()
for n in range(inputVal):
tmpSet.add(int(inputArr[n]))
print(sum(tmpSet)/len(tmpSet)) |
#Sudoku generator for printi.me/mango
#13 September 2019, Python 3.7;2
#Adjust difficulty: line 26
#If Inconsolata Regular not installed or using non-Windows OS, change: line 48
#Change printi: line 60
from random import sample
from PIL import Image, ImageDraw, ImageFont
import printipigeon as pp
import os
print(' SUDOKU GENERATOR')
difficulty = int(input(' Difficulty (0-10)? '))
#os.chdir('C:/Users/Merlijn Kersten/Documents/GitHub/printigram') #For testing
#Code by Alain T. at https://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python
base = 3
side = base*base
nums = sample(range(1,side+1),side)
board = [[nums[(base*(r%base)+r//base+c)%side] for c in range(side) ] for r in range(side)]
rows = [ r for g in sample(range(base),base) for r in sample(range(g*base,(g+1)*base),base) ]
cols = [ c for g in sample(range(base),base) for c in sample(range(g*base,(g+1)*base),base) ]
board = [[board[r][c] for c in cols] for r in rows]
squares = side*side
########################################################
#Adjust difficulty. 1: solved, 0: empty, 4//7: default #
empties = squares * difficulty//10 #
########################################################
for p in sample(range(squares),empties):
board[p//side][p%side] = 0
numSize = len(str(side))
#Make list of sudoku lines
lines = []
for i in range(9):
templine = ''
for item in board[i]:
if item == 0:
templine += ' '
else:
templine += str(item) + ' '
if len(templine) in [3, 7]:
templine += ' '
lines.append(templine)
#Make image out of sudoku lines, draw major division lines, print using printi pigeon
img = Image.new('RGB', (590,700), color = 'white')
fnt = ImageFont.truetype('C:/Windows/Fonts/Inconsolata-Regular.ttf', size=70)
for i in range(len(lines)):
ImageDraw.Draw(img).text((0,i*80), lines[i], font=fnt, fill=(0,0,0))
d = ImageDraw.Draw(img)
d.line([(192,0), (192,700)], fill=(0,0,0), width=5)
d.line([(402,0), (402,700)], fill=(0,0,0), width=5)
d.line([(0,238), (590,238)], fill=(0,0,0), width=5)
d.line([(0,477), (590,477)], fill=(0,0,0), width=5)
img.save('sudoku.png')
####################################################
#Change 'mango' for other printi names if required #
pp.send_from_path('sudoku.png', 'mango') #
####################################################
os.remove('sudoku.png') |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.