text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# Created by: Haokai Li
# Created on: Sept 2021
# This Program calculate weight and volume of package
def main():
# This function calculate weight and volume of package
# input
string_weight = input("Please enter weight of the package(kg): ")
string_length = input("Please enter length of the package(cm): ")
string_width = input("Please enter width of the package(cm): ")
string_height = input("Please enter height of the package(cm): ")
print("")
# process
try:
number_weight = int(string_weight)
number_length = int(string_length)
number_width = int(string_width)
number_height = int(string_height)
cubic_volume = number_length * number_width * number_height
if number_weight <= 27 or cubic_volume <= 10000:
if number_weight <= 27:
if cubic_volume <= 10000:
# output
print("OK, we will accept the package.")
else:
# output
print("Your package is too large.")
else:
# output
print("Your package is too heavy.")
else:
# output
print("Your package is too heavy and too large.")
except Exception:
# output
print("Your input is not a valid input.")
print("\nDone.")
if __name__ == "__main__":
main()
|
#
# CSE 3521 - Programming Assignment 01 (Part1)
#
# Input - one text file containing a single integer in each line and several
# such lines; this text files is expected to contain the ranks of the ojects
# coming down the Conveyer Belt in this environment. The assumption is that the
# file is well formatted. Occurrence of two '-1' ranks in this text file
# will denote that we have reached the end of the belt
#
# Output - a sequence of text printed to stdout that explains the values input
# to this agent, the state of the agent and the action taken by the agent
#
# by Haribabu, Karpaka Vellaya (Hari)
# email karpakavellaya.1@osu.edu
#
# Execution - this program requires the 'sys' and 'string' python modules
# execution syntax :
# 'python part2.py [Belt_file]'
# if the input file 'Belt_file' is not specified by the user, then the
# default file "inp" that is provided with this code is used as input.
# An alternate method of providing custom input to the program would be
# to edit the contents of the file "inp".
#
# For the last element in the belt, this agent always decides to PICKUP the item;
# This is so that this program behaves in the same way as the example shown in
# the Question
#
import sys
import string
class ConveyerBelt:
def __init__(self, BeltFileName):
self.RankSet = [] # Ranks are stored in a set
self.EOB = 0 # EOB denotes the end of belt; ie., the
# end farthest from this Agent's sensors
self.pos = 0 # pos denotes the location on the belt
# closest to the agent's sensors
BeltFile = open(BeltFileName, "r")
while True:
val = string.rstrip(BeltFile.readline(), "\n")
if val == "":
break
self.RankSet = self.RankSet + [int(val)]
# all ranks are read and stored in the
# set RankSet
self.EOB+=1
def GetRanks(self):
Ranks = self.RankSet[self.pos : self.pos+2]
return Ranks
def Advance(self):
self.pos+=1
def Pickup(self):
self.RankSet[self.pos] = 0
class Agent:
def ReflexAgent(self, percept1, percept2):
# percept1 is Rank of EOB and percept2 is Rank of EOB+1
# this agent has no set variables and so, no member variables
# in this implementation of this class Agent
if percept1 == 0 and percept2 == -1:
return "ADVANCE"
elif percept1 == -1:
return "STOP"
elif percept1 > percept2:
return "PICKUP"
else:
return "ADVANCE"
def main(argv):
if argv == []:
belt_filename = "inp"
else:
belt_filename = argv[0]
CB = ConveyerBelt(belt_filename)
RA = Agent()
ranks = CB.GetRanks()
while True:
print "INPUT PERCEPTION:", ranks[0], ranks[1]
action = RA.ReflexAgent(ranks[0], ranks[1])
print "OUTPUT ACTION:", action
if action == "PICKUP":
CB.Pickup()
elif action == "ADVANCE":
CB.Advance()
elif action == "STOP":
return
ranks = CB.GetRanks()
if __name__ == "__main__":
main(sys.argv[1:])
|
import sqlite3
conn = sqlite3.connect('UsuariosApp.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS Usuarios (
Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
Nome TEXT NOT NULL,
Email TEXT NOT NULL,
Senha TEXT NOT NULL
);
""")
print('Conectando ao Banco de Dados') |
# --- Day 14: Docking Data ---
# As your ferry approaches the sea port, the captain asks for your help again. The computer system that runs this port isn't compatible with the docking program on the ferry, so the docking parameters aren't being correctly initialized in the docking program's memory.
# After a brief inspection, you discover that the sea port's computer system uses a strange bitmask system in its initialization program. Although you don't have the correct decoder chip handy, you can emulate it in software!
# The initialization program (your puzzle input) can either update the bitmask or write a value to memory. Values and memory addresses are both 36-bit unsigned integers. For example, ignoring bitmasks for a moment, a line like mem[8] = 11 would write the value 11 to memory address 8.
# The bitmask is always given as a string of 36 bits, written with the most significant bit (representing 2^35) on the left and the least significant bit (2^0, that is, the 1s bit) on the right. The current bitmask is applied to values immediately before they are written to memory: a 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged.
# For example, consider the following program:
# mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# mem[8] = 11
# mem[7] = 101
# mem[8] = 0
# This program starts by specifying a bitmask (mask = ....). The mask it specifies will overwrite two bits in every written value: the 2s bit is overwritten with 0, and the 64s bit is overwritten with 1.
# The program then attempts to write the value 11 to memory address 8. By expanding everything out to individual bits, the mask is applied as follows:
# value: 000000000000000000000000000000001011 (decimal 11)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001001001 (decimal 73)
# So, because of the mask, the value 73 is written to memory address 8 instead. Then, the program tries to write 101 to address 7:
# value: 000000000000000000000000000001100101 (decimal 101)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001100101 (decimal 101)
# This time, the mask has no effect, as the bits it overwrote were already the values the mask tried to set. Finally, the program tries to write 0 to address 8:
# value: 000000000000000000000000000000000000 (decimal 0)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001000000 (decimal 64)
# 64 is written to address 8 instead, overwriting the value that was there previously.
# To initialize your ferry's docking program, you need the sum of all values left in memory after the initialization program completes. (The entire 36-bit address space begins initialized to the value 0 at every address.) In the above example, only two values in memory are not zero - 101 (at address 7) and 64 (at address 8) - producing a sum of 165.
# Execute the initialization program. What is the sum of all values left in memory after it completes?
# --- Part Two ---
# For some reason, the sea port's computer system still can't communicate with your ferry's docking program. It must be using version 2 of the decoder chip!
# A version 2 decoder chip doesn't modify the values being written at all. Instead, it acts as a memory address decoder. Immediately before a value is written to memory, each bit in the bitmask modifies the corresponding bit of the destination memory address in the following way:
# If the bitmask bit is 0, the corresponding memory address bit is unchanged.
# If the bitmask bit is 1, the corresponding memory address bit is overwritten with 1.
# If the bitmask bit is X, the corresponding memory address bit is floating.
# A floating bit is not connected to anything and instead fluctuates unpredictably. In practice, this means the floating bits will take on all possible values, potentially causing many memory addresses to be written all at once!
# For example, consider the following program:
# mask = 000000000000000000000000000000X1001X
# mem[42] = 100
# mask = 00000000000000000000000000000000X0XX
# mem[26] = 1
# When this program goes to write to memory address 42, it first applies the bitmask:
# address: 000000000000000000000000000000101010 (decimal 42)
# mask: 000000000000000000000000000000X1001X
# result: 000000000000000000000000000000X1101X
# After applying the mask, four bits are overwritten, three of which are different, and two of which are floating. Floating bits take on every possible combination of values; with two floating bits, four actual memory addresses are written:
# 000000000000000000000000000000011010 (decimal 26)
# 000000000000000000000000000000011011 (decimal 27)
# 000000000000000000000000000000111010 (decimal 58)
# 000000000000000000000000000000111011 (decimal 59)
# Next, the program is about to write to memory address 26 with a different bitmask:
# address: 000000000000000000000000000000011010 (decimal 26)
# mask: 00000000000000000000000000000000X0XX
# result: 00000000000000000000000000000001X0XX
# This results in an address with three floating bits, causing writes to eight memory addresses:
# 000000000000000000000000000000010000 (decimal 16)
# 000000000000000000000000000000010001 (decimal 17)
# 000000000000000000000000000000010010 (decimal 18)
# 000000000000000000000000000000010011 (decimal 19)
# 000000000000000000000000000000011000 (decimal 24)
# 000000000000000000000000000000011001 (decimal 25)
# 000000000000000000000000000000011010 (decimal 26)
# 000000000000000000000000000000011011 (decimal 27)
# The entire 36-bit address space still begins initialized to the value 0 at every address, and you still need the sum of all values left in memory at the end of the program. In this example, the sum is 208.
# Execute the initialization program using an emulator for a version 2 decoder chip. What is the sum of all values left in memory after it completes?
import copy
import re
import sys
# we're working with 36-bit binary
BIT_OFFSET = 35
def main():
input_file = sys.argv[1]
try:
with open(input_file) as file_reader:
raw_instructions = file_reader.readlines()
# part 1: sum all values written to memory after the instructions are processed applying bitmasks to values
print(
sum_values_in_memory(
process_instructions_masking_value(raw_instructions)
)
)
# part 2: sum all values written to memory after the instructions are processed applying bitmasks to memory addresses
print(
sum_values_in_memory(
process_instructions_masking_address(raw_instructions)
)
)
except Exception as error:
print(error)
raise
# build a memory map given a set of instructions in the format
# mask = <string>
# mem[<int>] = <int>
# bitmasks alter the VALUE being written to memory in this version
def process_instructions_masking_value(instructions):
bitmask = []
memory = {}
for line in instructions:
line_parts = line.rstrip().split("= ")
if line_parts[0].startswith("mask"):
bitmask = []
for index, char in enumerate(line_parts[1]):
# when masking values, we ignore any "X" in the bitmask
if char != "X":
bitmask.append((index, char))
elif line_parts[0].startswith("mem"):
memory_address, binary_value = parse_memory_address_and_value(line_parts)
memory[memory_address] = apply_mask_to_value(bitmask, binary_value)
return memory
# build a memory map given a set of instructions in the format
# mask = <string>
# mem[<int>] = <int>
# bitmasks alter the MEMORY ADDRESS being written to in this version
# when an address is masked, it may contain "unstable" bits, represented by "X"
# these bits can be either 1 or 0 - write values to all possible permutations of the address
def process_instructions_masking_address(instructions):
bitmask_stable_bits = []
bitmask_unstable_bits = []
memory = {}
for line in instructions:
line_parts = line.rstrip().split("= ")
if line_parts[0].startswith("mask"):
bitmask_stable_bits = []
bitmask_unstable_bits = []
for index, char in enumerate(line_parts[1]):
# separate our "unstable" bits; store just their 'index' in the binary string (0 is the far right)
if char == "X":
bitmask_unstable_bits.append(BIT_OFFSET - index)
# in this bit mask, 1's can flip 0's; 0's do nothing
elif char == "1":
bitmask_stable_bits.append((index, char))
elif line_parts[0].startswith("mem"):
memory_address, binary_value = parse_memory_address_and_value(line_parts)
possible_memory_addresses = apply_mask_to_address(
bitmask_stable_bits, bitmask_unstable_bits, memory_address
)
for address in possible_memory_addresses:
memory[address] = binary_value
return memory
def parse_memory_address_and_value(raw_memory_instruction):
memory_address = int(re.findall(r"\d+", raw_memory_instruction[0])[0])
binary_value = int_to_binary_string(raw_memory_instruction[1])
return (memory_address, binary_value)
def int_to_binary_string(int_to_convert):
return "{0:b}".format(int(int_to_convert)).zfill(36)
def apply_mask_to_value(bitmask, binary_value):
transformed_value = list(copy.copy(binary_value))
for index, value in bitmask:
transformed_value[index] = value
return "".join(transformed_value)
def apply_mask_to_address(bitmask_stable_bits, bitmask_unstable_bits, memory_address):
possible_addresses = []
# convert the address to binary string
transformed_address = int_to_binary_string(memory_address)
# transform the address with the stable bits (convert to list so we can continue to mess w/ chars)
transformed_address = list(
apply_mask_to_value(bitmask_stable_bits, transformed_address)
)
# find all possible address permutations created by the unstable bits
# first, switch all unstable bits to one (max possible address value)
for unstable_bit in bitmask_unstable_bits:
transformed_address[BIT_OFFSET - unstable_bit] = "1"
# these are our seed addresses: all unstable bits switched to 1, max unstable bit flipped to 0
# (convert to ints so the they work with our problem)
max_bit_index = BIT_OFFSET - bitmask_unstable_bits[0]
seed_address_string = "".join(transformed_address)
seed_address_1 = int(seed_address_string, 2)
seed_address_2 = int(
"".join(
seed_address_string[0:max_bit_index]
+ "0"
+ seed_address_string[max_bit_index + 1 :]
),
2,
)
# append the seed addresses to the list - they are also possibilities
possible_addresses += [seed_address_1, seed_address_2]
# calculate all possible addresses that can originate from the seed addresses
possible_addresses += calculate_possible_addresses_from_seed(
bitmask_unstable_bits[1:], seed_address_1
) + calculate_possible_addresses_from_seed(
bitmask_unstable_bits[1:], seed_address_2
)
print(possible_addresses)
return possible_addresses
# recursive sliding subtraction -> continually subtract (2^m + 2^n + ...) where m and n are the locations
# in the binary string of the unstable bits in the bit mask - we'll do this for every value in in the
# unstable bitmask, reducing the size of the list by one for each iteration
def calculate_possible_addresses_from_seed(bitmask_unstable_bits, seed_address):
possible_addresses = []
for list_index, unstable_bit_location in enumerate(bitmask_unstable_bits):
# subtract 2^(current unstable bit) and add to the possible addresses
next_seed_address = seed_address - (2 ** unstable_bit_location)
possible_addresses.append(next_seed_address)
# subtract the rest of the 2^n from this seed
possible_addresses += calculate_possible_addresses_from_seed(
bitmask_unstable_bits[list_index + 1 :], next_seed_address
)
return possible_addresses
def sum_values_in_memory(memory):
memory_sum = 0
for value in memory.values():
memory_sum += int(value, 2)
return memory_sum
if __name__ == "__main__":
main()
|
def nextPrime(primes, cur):
for p in primes:
if (cur % p == 0):
return nextPrime(primes, cur+1)
return cur
def getNthPrime(n):
p = 2
primes = [2]
for i in xrange(n):
p = nextPrime(primes, p)
primes.append(p)
print(p)
print(len(primes))
getNthPrime(10000)
|
from tkinter import *
#Zona de clases
#Zona de funciones
#Ejemplo
def Hello():
det=Tk()
frame = Frame(det)
lan = ["Python", "C++", "iOS", "Swift"]
d = 1;
list = Listbox(frame)
for i in lan:
list.insert(d, i)
d += 1
frame.pack()
list.pack()
det.mainloop()
#Ventana
root = Tk()
#Declaracion de variables
ment = StringVar()
#Metadatos
root.title("Diccionario")
root.geometry("400x300+50+50")
# Declaración de Marcos
topFrame = Frame(root)
topFrame.pack(fill=BOTH) # Primer Frame
middleFrame = Frame(root)
middleFrame.pack(fill=BOTH) # Marco del centro
bottonFrame = Frame(root)
bottonFrame.pack(side=BOTTOM, fill=BOTH) # Marco del final
# Labels
label1 = Label(topFrame,text="Primer proyecto de Estructura de Datos y Algoritmos II\nOscar Gutiérrez Castillo\nCarlos Arrileta")
# Inputs
input = Entry(middleFrame, textvariable=ment).pack()
# Botones
buscar = Button(middleFrame, text="Buscar", fg="red", command=Hello)
agregar = Button(middleFrame, text="Agregar", fg="blue")
eliminar = Button(middleFrame, text="Eliminar", fg="green")
cargar = Button(bottonFrame, text="Cargar", fg="purple")
guardar = Button(bottonFrame, text="Guardar")
salir = Button(bottonFrame, text="Salir", command=sys.exit)
# Paquetes
label1.pack()
buscar.pack()
agregar.pack(side=LEFT)
eliminar.pack(side=RIGHT)
cargar.pack()
guardar.pack()
salir.pack(side=BOTTOM)
#Lanzador
root.mainloop()
|
#!/usr/bin/env python3
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class YourBorg(Borg):
def __init__(self, state=None):
# Share __dict__ between all instances
super().__init__()
if state:
self.state = state
else:
if not hasattr(self, "state"):
self.state = "Init"
def __str__(self):
return self.state
def main():
'''
>>> What is this pattern about?
a way to implement singleton behavior, but instead of
having only one instance of a class, there are multiple
instances that share the same state.
In other words, the focus is on sharing state
instead of sharing instance identity.
>>> What does this example do?
In Python, instance attributes are stored in a
attribute dictionary called __dict__.
Usually, each instance will have its own dictionary,
but the Borg pattern modifies this so that all
instances have the same dictionary.
The __shared_state attribute will be the dictionary
shared between all instances, and this is ensured by assigining
__shared_state to the __dict__ variable when initializing a new
instance (i.e., in the __init__ method).
Other attributes are usually added to the instance's attribute
dictionary, but, since the attribute dictionary itself is
shared (which is __shared_state), all other attributes will also be shared.
'''
b1 = YourBorg()
print(f"b1: {b1}")
b2 = YourBorg()
b1.state = 'Idle'
b2.state = 'Running'
print(f"b1: {b1}, b2: {b2}")
b2.state = 'Zombie'
print(f"b1: {b1}, b2: {b2}")
print(f"b1 is b2: {b1 is b2}")
b3 = YourBorg()
print(f"b1: {b1}, b2: {b2}, b3: {b3}")
b4 = YourBorg('Running')
print(f"b1: {b1}, b2: {b2}, b3: {b3}, b4: {b4}")
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
import time
import numpy as np
import tkinter as tk
UNIT = 80
H, W = 5, 5
class Maze(tk.Tk, object):
def __init__(self):
super(Maze, self).__init__()
self.action_space = ['E', 'W', 'S', 'N']
self.n_state = 2
self.n_action = len(self.action_space)
self.title('maze')
self.geometry("{}x{}".format(UNIT*H, UNIT*W))
self._build_maze()
def _build_maze(self):
self.canvas = tk.Canvas(self,
bg='white',
height=UNIT*H,
width=UNIT*W)
for h in range(1, H):
x0, y0, x1, y1 = UNIT*h, 0, UNIT*h, UNIT*H
self.canvas.create_line(x0, y0, x1, y1)
for w in range(1, W):
x0, y0, x1, y1 = 0, UNIT*w, UNIT*W, UNIT*w
self.canvas.create_line(x0, y0, x1, y1)
origin = np.array([UNIT//2, UNIT//2])
h1_c = origin + np.array([UNIT*2, UNIT*1])
self.h1 = self.canvas.create_rectangle(
h1_c[0] - (UNIT*3//8), h1_c[1] - (UNIT*3//8),
h1_c[0] + (UNIT*3//8), h1_c[1] + (UNIT*3//8),
fill='black')
h2_c = origin + np.array([UNIT*1, UNIT*2])
self.h2 = self.canvas.create_rectangle(
h2_c[0] - (UNIT*3//8), h2_c[1] - (UNIT*3//8),
h2_c[0] + (UNIT*3//8), h2_c[1] + (UNIT*3//8),
fill='black')
oval_c = origin + np.array([UNIT*2, UNIT*2])
self.oval = self.canvas.create_oval(
oval_c[0] - (UNIT*3//8), oval_c[1] - (UNIT*3//8),
oval_c[0] + (UNIT*3//8), oval_c[1] + (UNIT*3//8),
fill='yellow')
rect_c = origin
self.rect = self.canvas.create_rectangle(
rect_c[0] - (UNIT*3//8), rect_c[1] - (UNIT*3//8),
rect_c[0] + (UNIT*3//8), rect_c[1] + (UNIT*3//8),
fill='red')
self.canvas.pack()
def reset(self):
self.update()
time.sleep(0.1)
self.canvas.delete(self.rect)
origin = np.array([UNIT//2, UNIT//2])
rect_c = origin
self.rect = self.canvas.create_rectangle(
rect_c[0] - (UNIT*3//8), rect_c[1] - (UNIT*3//8),
rect_c[0] + (UNIT*3//8), rect_c[1] + (UNIT*3//8),
fill='red')
# return self.canvas.coords(self.rect)
# maybe normalize the state?
return np.array(self.canvas.coords(self.rect)[:2]) / (UNIT*H)
def step(self, action):
s = self.canvas.coords(self.rect)
base_action = np.array([0,0])
if action == 0: # east
if s[0] < (W-1)*UNIT:
base_action[0] += UNIT
elif action == 1: # west
if s[0] > UNIT:
base_action[0] -= UNIT
elif action == 2: # south
if s[1] < (H-1)*UNIT:
base_action[1] += UNIT
elif action == 3: # north
if s[1] > UNIT:
base_action[1] -= UNIT
else:
assert False, 'invalid action'
self.canvas.move(self.rect, base_action[0], base_action[1])
s_ = self.canvas.coords(self.rect)
if s_ == self.canvas.coords(self.oval):
reward = 1
done = True
s_ = 'terminal'
elif s_ in [self.canvas.coords(self.h1), self.canvas.coords(self.h2)]:
reward = -1
done = True
s_ = 'terminal'
else:
reward = 0
done = False
# maybe normalize the state?
s_ = np.array(self.canvas.coords(self.rect)[:2]) / (UNIT*H)
return s_, reward, done
def render(self):
# time.sleep(0.05)
self.update()
def main():
env = Maze()
env.mainloop()
if __name__ == "__main__":
main()
|
import random
def place_marker(board, marker, position):
board[position] = marker
def display_board(board: list):
print('\n' * 5)
print(board[7] + '|' + board[8] + '|' + board[9])
print('-' * 6)
print(board[4] + '|' + board[5] + '|' + board[6])
print('-' * 6)
print(board[1] + '|' + board[2] + '|' + board[3])
return board
def player_input():
marker = ''
while marker != 'X' and marker != 'O':
marker = input('Which marker would you like to use? X or O: ')
player1 = marker
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
return player1, player2
def win_check(board, marker):
markers_in_a_row = list(marker * 3)
# different way of calculating it
if board[7:10] == markers_in_a_row:
won = True
print('You\'ve won horizontally in the first row')
elif board[4:7] == markers_in_a_row:
won = True
print('You\'ve won horizontally in the second row')
elif board[1:4] == markers_in_a_row:
won = True
print('You\'ve won horizontally in the last row')
elif board[1::3] == markers_in_a_row:
won = True
print('You\'ve won vertically in the first column')
# bunch checking each board item
elif board[2] == board[5] == board[8] == marker:
won = True
print('You\'ve won vertically in the second column')
elif board[3] == board[6] == board[9] == marker:
won = True
print('You\'ve won vertically in the last column')
elif board[1] == board[5] == board[9] == marker:
won = True
print('You\'ve won digonally upwards')
elif board[7] == board[5] == board[3] == marker:
won = True
print('You\'ve won digonally downwards')
elif full_board_check(board):
won = False
print('Tie')
else:
won = False
return won
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
return ' ' not in board
def player_choice(board):
num_chosen = 0
while num_chosen not in range(1, 10) or not space_check(board, num_chosen):
num_chosen = int(input('Choose a position (1-9): '))
return num_chosen
def choose_first():
number = random.randint(0, 1)
if number == 0:
return 'Player 1'
else:
return 'Player 2'
def replay():
will_replay = input('Do you want to replay the game. Y or N: ')
return 'y'.lower() in will_replay
def play_game():
print('Welcome to Tic Tac Toe')
# TUPLE UNPACKING - SIMILAR TO DESTRUCTURING
player1_marker, player2_marker = player_input()
playing = False
current_board = [' '] * 10
current_player_marker = player1_marker
player_did_win = False
if current_player_marker is not None:
print(f'Player 1 is {player1_marker}\nPlayer 2 is {player2_marker}')
print('Started playing')
playing = True
display_board(current_board)
while playing:
position = player_choice(current_board)
place_marker(current_board, current_player_marker, position)
display_board(current_board)
# check for winner
if win_check(current_board, current_player_marker):
if current_player_marker == player1_marker:
print('Player 1 wins')
player_did_win = True
else:
print('Player 2 wins')
player_did_win = True
# make sure the players alternate every turn
if not player_did_win:
if current_player_marker == player1_marker:
current_player_marker = player2_marker
print('Player 2\'s turn')
else:
current_player_marker = player1_marker
print('Player 1\'s turn')
if player_did_win:
will_replay = replay()
if will_replay:
play_game()
else:
quit()
play_game()
|
# creating a caesar cipher
def encrypt(string, shift_by):
"""
Encrypt the string into a new string
"""
numList = [(ord(s) - shift_by) for s in string]
encrypted_string = ''
for i in numList:
encrypted_string += chr(i)
return encrypted_string
encryptedSentence = encrypt('This is a sentence for my people and It Has Weird CapitalS EvErywhere', 23)
print(encryptedSentence)
|
'''
Password Management
'''
import string
from random import choice, shuffle
def generate(length = 15, caps = 2, nums = 2, chars = 2, restricted = "", isExactly = False):
###BELOW ARE CONSTANTS
LOWERCASE = removeRestricted(string.ascii_lowercase, restricted)
UPPERCASE = removeRestricted(string.ascii_uppercase, restricted)
DIGITS = removeRestricted(string.digits, restricted)
CHARS = removeRestricted(" " + string.punctuation, restricted)
ALL = LOWERCASE + UPPERCASE + DIGITS + CHARS
password = [choice(UPPERCASE) for i in range(caps)] + [choice(DIGITS) for i in range(nums)] + [choice(CHARS) for i in range(chars)]
if isExactly:
password += [choice(LOWERCASE) for i in range(length - len(password))]
else:
password += [choice(ALL) for i in range(length - len(password))]
shuffle(password)
password = "".join(password)
return password
def removeRestricted(word, notAllowed): ###DELETES RESTRICTED LETTERS, NUMBERS, AND CAPITALS FROM CONSTANDS DEFINED ABOVE
for c in notAllowed:
word = word.replace(c, "")
return word
|
bonacci(signature, n):
if(n==0):
return []
if(n==1):
return signature[:1]
if(n==2):
return signature[:2]
if(n==3):
return signature[:3]
tribonacciSequence = signature.copy()
while len(tribonacciSequence) < n:
tribonacciSequence.append(tribonacciSequence[-1] + tribonacciSequence[-2] + tribonacciSequence[-3])
return tribonacciSequence
|
import sys
import data
import index
import utils
def main() -> None:
"""
Driver method
"""
# Read arguments
filename = sys.argv[1]
products = sys.argv[2:]
# Load data and create index
items = data.read_data(filename)
item_index, shop_index = index.build_index(items)
# Find relevant shops
shops = utils.find_shops(item_index, products)
# Calculate price for each of them and store in list of tuples format
# with first index as shop ID and second as final price -
# [
# (shop1, total1),
# (shop2, total2),
# ...
# ]
price_list = [(i, utils.calculate_price(shop_index, products, i))
for i in shops]
if price_list:
best_price = min(price_list, key=lambda x: x[1]) # Find the best price
else: # No relevant shop found
best_price = None
print(best_price)
if __name__ == '__main__':
main()
|
def calculate_bisiesto(año):
if(año%400==0)or(año%100!=0)and(año%4==0):
return ('True')
else:
return ('False')
def main():
#escribe tu código abajo de esta línea
año = int(input())
print(calculate_bisiesto(año))
pass
if __name__=='__main__':
main()
|
from collections import namedtuple
import datetime
Book = namedtuple('Book', ['title', 'author', 'year_published', 'subject', 'section']) #title(str), author(str), year_published(int), subject(str), section(str)
Checkout = namedtuple('Checkout', ['book', 'student', 'due_date']) #book(Book), student(Student), due_date(datetime.date)
Student = namedtuple('Student', ['student_name', 'house', 'checked_out_books']) #student_name(str), house(str), checked_out_books(list=[])
Penalty = namedtuple('Penalty', ['curse', 'point_deduction']) #curse(str), point_deduction(int)
no_penalty = Penalty("None", 0)
one_day_penalty = Penalty("Ear-Shrivelling", 10)
two_day_penalty = Penalty("Hair Loss", 20)
three_day_penalty = Penalty("Curse of the Bogies", 30)
four_day_penalty = Penalty("Slug-Vomiting", 50)
five_day_penalty = Penalty("Book Return", 80)
# Define Container of the total outstanding point balance of every house
house_penalties = {"Gryffindor": 0, "Hufflepuff": 0, "Ravenclaw": 0, "Slytherin": 0}
# Define Library Data Structures
book_collection = {} #book_title:Book
library_members = {} #student_name:Student
checkouts = {} #book_title:Checkout
reservations = {} #book_title:[(student_name, start_date,end_date)]
penalties = [no_penalty, one_day_penalty, two_day_penalty, three_day_penalty, four_day_penalty, five_day_penalty]
library_passcodes = ["Accio", "Protego"]
start_date = None
# Print Format Strings. NOTE: Most output uses width 60-characters.
due_today_format_string = "{title:<35}{name:>25}"
due_report_format_string = "{title:<35}{name:>25}"
checkout_report_format_string = "{title:<30}{name:^20}{due_date:>10}"
user_report_format_string = "{title:<35}{due_date:>25}"
hold_report_format_string = "{name:<33}{number_of_days:^27}"
# See below for example namedtuple instances
if __name__ == "__main__":
# Define Container of the total outstanding point balance of every house
house_balance = {"Gryffindor": 0, "Hufflepuff": 0, "Ravenclaw": 0, "Slytherin": 0}
#Books
curses = Book("Curses and Counter-Curses", "Vindictus Viridian", 1703, "Curses", "Restricted")
# Define Members
harry_potter = Student("Harry Potter", "Gryffindor", [curses])
# Define checkouts
curse_checkout = Checkout(curses, harry_potter, datetime.date(year=1991, month=9, day=3)) |
# File: nums.py
# Started: by Dr. Gibson
# Author: Sanaa Mironov
# Date: Oct 24, 2016
# Section: 04
# Description:
# This file contains python code that uses functions to
# allow a user to get basic information about a number
# they've entered.
MIN_VAL = -1000000
MAX_VAL = 1000000
def evenOrOdd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
def posNegZero(num):
if num < 0 :
return "negative"
elif num == 0:
return "zero"
else:
return "postive"
def getValidInt(minn, maxx):
message = "Please enter a number between " + str(minn) + " and " + \
str(maxx) + " (inclusive): "
newInt = int(input(message))
while newInt <= minn or newInt >= maxx:
newInt = int(input(message))
return newInt
def main():
print("Welcome to the number program!")
userNum = getValidInt(MIN_VAL,MAX_VAL)
sign = posNegZero(userNum)
print("The number", userNum, "is", sign)
result = evenOrOdd(userNum)
print("The number", userNum, "is", result)
print("Thank you for using the number program! Come again!")
main() |
def topological_sort(graph):
def dfs(graph, used, order, u):
used[u] = True
for v in graph[u]:
if not used[v]:
dfs(graph, used, order, v)
order.append(u)
n = len(graph)
used = [False] * n
order = []
for i in range(n):
if not used[i]:
dfs(graph, used, order, i)
return order[::-1]
def test():
g = [[] for _ in range(3)]
g[2].append(0)
g[2].append(1)
g[0].append(1)
assert topological_sort(g) == [2, 0, 1]
test()
|
string = input()
character_count = {}
for i in string:
if i not in character_count:
character_count[i] = string.count(i)
odd_counts = 0
for i in character_count:
if character_count[i] % 2 == 1:
odd_counts += 1
if odd_counts > 1:
print("NO")
else:
print("YES")
|
from Tkinter import Tk, Canvas, BOTH
from math import sin, cos, radians
from random import choice, randint
WIDTH=1000
HEIGHT=600
global text1
def quit_to_exit():
w=Tk()
w.after(3000, lambda:w.destroy())
w.mainloop()
def call():
# f = open("score_data.txt", "r+")
class Breakout(Tk):
def __init__(self):
Tk.__init__(self)
#self.canvas.delete('all')
self.geometry('790x600')
self.resizable(0,0) #set both parameters to false and to check whether window is resizable in x and y directions
self.func()
# game screen
def func(self):
self.canvas = Canvas(self, bg='skyblue', width=990, height=600,highlightcolor='green')
self.canvas.pack(expand=1, fill=BOTH) #when it is true and widget expands to fill any space
# ball
self._initiate_new_ball()
#self.level=choice([1])
# paddle
self.canvas.create_rectangle(375,975,525,585, fill='red', tags='paddle')
self.bind('<Key>', self._move_paddle)
# bricks
self.bricks = {}
brick_coords = [15,12,60,45]
for i in range(56):
self.canvas.create_rectangle(brick_coords, outline='green',fill=('yellow'),tags='brick' + str(i))
self.bricks['brick' + str(i)] = None
brick_coords[0] += 55; brick_coords[2] += 55
if brick_coords[2] > 790:
brick_coords[0] = 15; brick_coords[2] = 60
brick_coords[1] += 55; brick_coords[3] += 55
def _initiate_new_ball(self):
if self.canvas.find_withtag('ball'):
self.canvas.delete('ball')
self.x = 300; self.y = 350
self.angle = 240; self.speed = 10; self.level=0; self.score=0
self.canvas.create_oval(self.x,self.y,self.x+10,self.y+10,
fill='orange', outline='red', tags='ball')
self.after(2000, self._move_ball)
def _move_paddle(self, event):
if event.keysym == 'Left':
if self.canvas.coords('paddle')[0] > 0:
self.canvas.move('paddle', -20, 0)
elif event.keysym == 'Right':
if self.canvas.coords('paddle')[2] < 990:
self.canvas.move('paddle', +20, 0)
#def _move_ball1(self):
# call1()
#self._initiate_new_ball1()
def _move_ball(self):
# variables to determine where ball is in relation to other objects
ball = self.canvas.find_withtag('ball')[0]
bounds = self.canvas.find_overlapping(0,0,790,600)
paddle = self.canvas.find_overlapping(*self.canvas.coords('paddle'))
for brick in self.bricks.iterkeys():
self.bricks[brick] = self.canvas.find_overlapping(*self.canvas.bbox(brick))
# calculate change in x,y values of ball
angle = self.angle - 120 # correct for quadrant IV
increment_x = cos(radians(angle)) * self.speed
increment_y = sin(radians(angle)) * self.speed
#self.level += choice([1])
#score=self.score
#score=0
# finite state machine to set ball state
if ball in bounds:
self.ball_state = 'moving'
for brick, hit in self.bricks.iteritems():
if ball in hit:
self.ball_state = 'hit_brick'
delete_brick = brick
elif ball in paddle:
self.ball_state = 'hit_wall'
elif (self.score)//3 == 56:
self.canvas.create_text(WIDTH/4,HEIGHT/2.3,text="CONGRATS!! GAME COMPLETED!",font=("Helvetica",20),fill="orange")
self.canvas.create_text(WIDTH/4,HEIGHT/2,text=(self.score//3),font=("Helvetica",20),fill="red")
self.canvas.create_text(WIDTH/4,HEIGHT/1.7,text="YOUR SCORE ",font=("Helvetica",20),fill="darkorange")
#image()
quit_to_exit()
call()
elif ball not in bounds:
if self.canvas.coords('ball')[1] < 600:
self.ball_state = 'hit_wall'
else:
self.ball_state = 'out_of_bounds'
#self.level += choice([1])
self.canvas.create_text(WIDTH/2.5,HEIGHT/2.3,text="GAME OVER !!PLEASE CLOSE THE WINDOW TO RESTART!",tag="cr2",font=("Helvetica",20),fill="orange")
self.canvas.create_text(WIDTH/4,HEIGHT/2,text="YOUR SCORE IS",tag="cr1",font=("Helvetica",20),fill="orange")
self.canvas.create_text(WIDTH/4,HEIGHT/1.7,text=(self.score//3)+1,tag="cr",font=("Helvetica",20),fill="red")
quit_to_exit()
call()
self._initiate_new_ball()
#self.bind('<key>',self.game_over)
#game = Breakout()
#game.mainloop()
# handler for ball state
if self.ball_state is 'moving':
self.canvas.move('ball', increment_x, increment_y)
self.after(35, self._move_ball)
# self.level +=choice([1])
elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall':
if self.ball_state == 'hit_brick':
self.canvas.delete(delete_brick)
del self.bricks[delete_brick]
self.canvas.move('ball', -increment_x, -increment_y)
# self.level += choice([1])
self.score += choice([1])
self.angle += choice([135])
self.canvas.delete("cr")
self.canvas.delete("cr1")
self.canvas.delete("cr2")
#canvas.create_text(WIDTH/4,HEIGHT/5,text="GAME OVER!")
self._move_ball()
# f.write(str(text1)+",")
# f.close()
paddlebreakballgame = Breakout()
paddlebreakballgame.mainloop()
call()
|
from matplotlib import pyplot as plt
plt.ion()
plt.plot([1,2,3])
# h = plt.ylabel('y')
# h.set_rotation(0)
plt.ylabel(-0.1, 0.5, 'Y label', rotation=90,
verticalalignment='center', horizontalalignment='right',
transform=plt.ylabel.transAxes)
plt.draw() |
nombre = input("Por favor ingrese su nombre: ")
print(nombre)
prueba = str(20)
print(type(prueba))
print(prueba)
numero = int(input("Por favor ingrse un número: "))
flotante = float(input("Por favor ingruese un número decimal: "))
titulo = input("Proporciona el titulo: ")
autor = input("Proporciona el autor")
print(titulo + " fue escrito por " + autor) |
class Caja:
def __init__(self, alto, ancho, largo):
self.__alto = alto
self.__ancho = ancho
self.__largo = largo
def calcularVolumnen(self):
return self.__alto * self.__ancho * self.__largo
alto = int(input("Por favor inrese el alto de la caja: "))
ancho = int(input("Por favor ingrese el ancho de la caja: "))
largo = int(input("Por favor ingrese el largo de la caja: "))
caja1 = Caja(alto, ancho, largo)
print(caja1.calcularVolumnen(), "M^3")
|
a = int(input("Ingrese un valor: "))
min = 0
max = 5
dentroRango = a >= min and a <= max
print(dentroRango)
if dentroRango:
print("Dentro del rango")
else:
print("Fuera de rango")
descanso = False
vacaciones = True
if descanso or vacaciones:
print("Puedo ir a donde quiera")
else:
print("Tengo deberes")
if not (descanso or vacaciones):
print("Tengo deberes")
else:
print("Puedo ir a donde quiera")
alto = int(input("Por favor ingrese el alto"))
ancho = int(input("Por favor ingrese el ancho"))
area = alto * ancho
perimetro = (alto + ancho) * 2
print(f"Area: {area}")
print(f"Perimetro: {perimetro}")
numero1 = int(input("Por favor ingrese el primer número"))
numero2 = int(input("Por favor ingrese el segundo número"))
if numero1 > numero2:
print(f"El número mayor es {numero1}")
else:
print(f"El número mayor es {numero2}")
|
import turtle
import time
import sys
from collections import deque
from tkinter import *
window = Tk()
window.title("BFS Maze Solving Program")
wn = '' # window declared
# this is the class for the Maze
class Maze(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
turtle.setup( width = 0, height = 0, startx = None, starty = None)
self.shape("square") # the turtle shape
self.color("white") # colour of the turtle
self.penup() # lift up the pen so it do not leave a trail
self.speed(0)
# this is the class for the finish line - green square in the maze
class Green(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
turtle.setup( width = 0, height = 0, startx = None, starty = None)
self.shape("square")
self.color("green")
self.penup()
self.speed(0) #delay in speed..set it to more than 0 for seeing the generating bfs path
class Blue(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
turtle.setup( width = 0, height = 0, startx = None, starty = None)
self.shape("circle")
self.color("blue")
self.penup()
self.speed(2)
# this is the class for the yellow or turtle
class Red(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
turtle.setup( width = 0, height = 0, startx = None, starty = None)
self.shape("circle")
self.color("red")
self.penup()
self.speed(0)
class Yellow(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
turtle.setup( width = 0, height = 0, startx = None, starty = None)
self.shape("square")
self.color("yellow")
self.penup()
self.speed(1)
grid1 = [
"+++++++++++++++",
"+s+ + +e+",
"+ +++++ +++ + +",
"+ + + + +",
"+ + +++ + + +",
"+ + + + + + +",
"+ + + + + +",
"+++++ + + + +",
"+ + + +",
"+++++++++++++++",
]
grid2 = [
"+++++++++",
"+ ++s++++",
"+ ++ ++++",
"+ ++ ++++",
"+ ++++",
"++++ ++++",
"++++ ++++",
"+ e+",
"+++++++++",
]
grid3 = [
"+++++++++++++++",
"+ +",
"+ +",
"+ +",
"+ e +",
"+ +",
"+ +",
"+ +",
"+ s +",
"+++++++++++++++",
]
grid4 = [
"+++++++++++++++++++++++++++++++++++++++++++++++++++",
"+ + +",
"+ ++++++++++ +++++++++++++ +++++++ ++++++++++++",
"+s + + ++ +",
"+ +++++++ +++++++++++++ +++++++++++++++++++++ +",
"+ + + + + + +++ +",
"+ + + + + + ++++ + + +++++++++++++ +++ +",
"+ + + + + + + + + + + +",
"+ + ++++ + ++++++++++ + + ++++ + + ++ +",
"+ + + + + + + + ++ ++",
"+ ++++ + +++++++ ++++++++ +++++++++++++ ++ ++",
"+ + + + + ++ +",
"++++ + ++++++++++ +++++++++++ ++++++++++ +++ +",
"+ + + + + + + +++ +",
"+ + ++++ +++++++++++++ + ++++ + + + ++ +",
"+ + + + + + + + + + ++ ++",
"+ + + +++++++ ++++ + + + ++++++++++ ++ ++",
"+ + + + ++ ++",
"+ ++++++ + + + + +++ +++ ++",
"+ ++++++ ++++++ +++++++++ ++e ++ ++++++++++ ++",
"+ + + +++ + +++++++++ ++ +++++++ + ++",
"+ ++++ ++++ +++ + +++ +++ ++ ++ ++ ++ + ++",
"+ ++++ + + +++ +++ ++ ++++++++ ++ ++ ++ ++",
"+ ++ ++++++++++ ++ ++ +++++++",
"+++++++++++++++++++++++++++++++++++++++++++++++++++",
]
def setup_maze(grid): # define a function called setup_maze
global start_x, start_y, end_x, end_y # set up global variables for start and end locations
for y in range(len(grid)): # read in the grid line by line
for x in range(len(grid[y])): # read each cell in the line
character = grid[y][x] # assign the varaible "character" the the x and y location od the grid
screen_x = -588 + (x * 24) # move to the x location on the screen staring at -588
screen_y = 288 - (y * 24) # move to the y location of the screen starting at 288
if character == "+":
maze.goto(screen_x, screen_y) # move pen to the x and y location and
maze.stamp() # stamp a copy of the turtle on the screen
walls.append((screen_x, screen_y)) # add coordinate to walls list
if character == " " or character == "e":
path.append((screen_x, screen_y)) # add " " and e to path list
if character == "e":
green.color("purple")
green.goto(screen_x, screen_y) # send green sprite to screen location
end_x, end_y = screen_x,screen_y # assign end locations variables to end_x and end_y
green.stamp()
green.color("green")
if character == "s":
start_x, start_y = screen_x, screen_y # assign start locations variables to start_x and start_y
red.goto(screen_x, screen_y)
def endProgram():
wn.exitonclick()
sys.exit()
def search(x,y):
frontier.append((x, y))
solution[x,y] = x,y
while len(frontier) > 0: # exit while loop when frontier queue equals zero
time.sleep(0)
x, y = frontier.popleft() # pop next entry in the frontier queue an assign to x and y location
if(x - 24, y) in path and (x - 24, y) not in visited: # check the cell on the left
cell = (x - 24, y)
solution[cell] = x, y # backtracking routine [cell] is the previous cell. x, y is the current cell
#blue.goto(cell) # identify frontier cells
#blue.stamp()
frontier.append(cell) # add cell to frontier list
visited.add((x-24, y)) # add cell to visited list
if (x, y - 24) in path and (x, y - 24) not in visited: # check the cell down
cell = (x, y - 24)
solution[cell] = x, y
#blue.goto(cell)
#blue.stamp()
frontier.append(cell)
visited.add((x, y - 24))
print(solution," ")
if(x + 24, y) in path and (x + 24, y) not in visited: # check the cell on the right
cell = (x + 24, y)
solution[cell] = x, y
#blue.goto(cell)
#blue.stamp()
frontier.append(cell)
visited.add((x +24, y))
if(x, y + 24) in path and (x, y + 24) not in visited: # check the cell up
cell = (x, y + 24)
solution[cell] = x, y
#blue.goto(cell)
#blue.stamp()
frontier.append(cell)
visited.add((x, y + 24))
green.goto(x,y)
green.stamp()
blue.goto(start_x,start_y)
blue.stamp()
blue.goto(end_x,end_y)
blue.stamp()
def backRoute(x, y):
final.append((x,y))
yellow.goto(x, y)
yellow.stamp()
while (x, y) != (start_x, start_y): # stop loop when current cells == start cell
yellow.goto(solution[x, y]) # move the yellow sprite to the key value of solution ()
yellow.stamp()
print(x,y)
final.append((x,y))
x, y = solution[x, y] # "key value" now becomes the new key
# set up classes
maze = Maze()
red = Red()
green = Green()
yellow = Yellow()
blue = Blue()
# setup lists
walls = []
path = []
final=[]
visited = set()
frontier = deque()
solution = {} # solution dictionary
def reverse_list(list): #reversing the list and moving the turtle in selected bfs path
print('old list',list)
list.reverse()
print('new list',list)
red.goto(start_x,start_y)
red.stamp()
for i in list:
red.goto(i)
red.stamp()
def setGrid(wrapperValue):
def wrapper_setGrid(gridNumber = wrapperValue):
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("BFS Maze Solving Program")
wn.setup(1300,700)
if(gridNumber == 1):
grid = grid1 #selecting small maze
elif(gridNumber == 2):
grid = grid2 #selecting medium maze
elif(gridNumber == 3):
grid = grid3 #selecting large maze
elif(gridNumber == 4):
grid = grid4 #selecting xl maze
window.destroy() #closing the tkinter window
setup_maze(grid)
search(start_x,start_y)
backRoute(end_x, end_y)
reverse_list(final)
wn.exitonclick()
return wrapper_setGrid
# GUI code
heading = Label(window, text="Welcome to BFS maze solving\nsimulator", font=("Arial", 15))
heading.grid(column=0, row=0, padx = 50)
instruction1 = Label(window, text="Select grid size", font=("Arial", 12))
instruction1.grid(column=0, row=2, pady = 10)
btn1 = Button(window, text="Small maze", command=setGrid(1))
btn1.grid(column=0, row=3, pady = 10)
btn2 = Button(window, text="Medium maze", command=setGrid(2))
btn2.grid(column=0, row=4, pady = 10)
btn3 = Button(window, text="Large maze", command=setGrid(3))
btn3.grid(column=0, row=5, pady = 10)
btn3 = Button(window, text="XL maze", command=setGrid(4))
btn3.grid(column=0, row=6, pady = 10)
window.geometry('350x300')
window.mainloop()
|
from random import choice
def open_and_read_file(file_path):
"""Takes file path as string; returns text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
file_obj = open(file_path)
file_text = file_obj.read()
file_obj.close()
return file_text
def make_chains(text_string, n):
"""Takes input text as string and number for n-gram;
returns a dictionary of markov chains.
A chain will be a key that consists of a tuple of n-gram
(word_1, word_2 ... word_n) and the value would be a list
of the word(s) that follow those words in the input text.
For example:
>>> make_chains("Hi hi my friend how are you", 5)
{("Hi", "hi", "my", "friend", "how"): ['are'],
("hi", "my", "friend", "how", "are"): ['you']}
"""
words = text_string.split()
chains_dict = {}
for i in range(len(words) - n):
key_tuple_list = []
for j in range(n):
key_tuple_list.append(words[i + j])
key_tuple = tuple(key_tuple_list)
if key_tuple not in chains_dict:
chains_dict[key_tuple] = [words[i+n]]
else:
chains_dict[key_tuple].append(words[i+n])
return chains_dict
def make_text(chains):
"""Takes dictionary of markov chains; returns random text."""
all_key_tuples = chains.keys()
upper_case_key_tuples = []
n = len(all_key_tuples[0])
# n counts the number of items in the key tuple
# for making n-gram
for word_set in all_key_tuples:
if word_set[0][0].isupper():
upper_case_key_tuples.append(word_set)
random_key = choice(upper_case_key_tuples)
final_output = []
for i in range(n):
final_output.append(random_key[i])
# populate the final_output list with the items of
# the initial random_key
while random_key in chains:
random_key_position_last = choice(chains[random_key])
# get the last item for the *NEW* random_key
random_key_list = []
for i in range(n-1):
random_key_list.append(random_key[i+1])
# populate the *NEW* random_key list with items
# from the current random_key[1] -- [n-1]
# essentially drop random_key[0]
random_key_list.append(random_key_position_last)
# add the newly pulled value hashed to the key
# to the last position to form a *NEW* random_key
random_key = tuple(random_key_list)
final_output.append(random_key_position_last)
# the newly pulled value also forms part of the
# random text
text = (" ").join(final_output)
return text
input_path = "gettysburg.txt"
input_text = open_and_read_file(input_path)
chains = make_chains(input_text, 4)
random_text = make_text(chains)
print random_text
|
############################################################################
## Python sample code to create a new pdf file with different formats ##
## Author: Gunther Bacellar ##
## Email: gcbacel@hotmail.com ##
############################################################################
# Steps to run the script:
# 1) install PyPDF3 (python3 -m pip install PyPDF3)
# 2) verify instalation: python3 -m pip show PyPDF3
from PyPDF3 import PdfFileWriter, PdfFileReader
pdf_path = r'C:\Users\gunther\'
input_pdf_name = 'input.pdf'
output_pdf_name = 'output.pdf'
watermark_pdf = 'watermark.pdf'
new_pdf = PdfFileWriter()
with PdfFileReader(open(pdf_path + input_pdf_name, "rb")) as pdf
# print pdf number of pages
print("pdf has %d pages." % pdf.getNumPages())
# add page 1 from pdf readed to the new document, unchanged
new_pdf .addPage(pdf.getPage(0))
# add page 2 from pdf readed, but rotated clockwise 90 degrees
new_pdf .addPage(pdf.getPage(1).rotateClockwise(90))
# add page 3 from pdf readed, rotated the other way:
new_pdf.addPage(pdf.getPage(2).rotateCounterClockwise(90))
# add page 4 from pdf readed, but first add a watermark from another PDF:
page4 = pdf.getPage(3)
watermark = PdfFileReader(open(pdf_path + watermark_pdf, "rb"))
page4.mergePage(watermark.getPage(0))
new_pdf.addPage(page4)
# add page 5 from pdf readed, but crop it to half size:
page5 = pdf.getPage(4)
page5.mediaBox.upperRight = (
page5.mediaBox.getUpperRight_x() / 2,
page5.mediaBox.getUpperRight_y() / 2
)
new_pdf.addPage(page5)
# encrypt your new PDF and add a password
password = "Brazil"
new_pdf.encrypt(password)
# finally, write "output" to document-output.pdf
outputStream = open(pdf_path + output_pdf_name, "wb")
new_pdf.write(outputStream) |
from typing import Any,Sequence
def bin_search(a:Sequence, key:Any)-> int:
pl=0
pr=len(a)-1
while True:
pc=(pl+pr)//2
if a[pc]== key:
return pc
elif a[pc]<key:
pl=pc+1
else:
pr=pc-1
if pl>pr:
break
return -1
if __name__ == '__main__':
num = int(input('원소 수를 입력하세요.:'))
x = [None] * num
print("배열 데이터를 오름차순으로 입력하세요.")
x[0]=int(input('x[0]: '))
for i in range(1,num):
while True:
x[i]=int(input(f'x[{i}]: '))
if x[i]>=x[i-1]:
break
ky=int(input('검색할 값을 입력하세요.::'))
idx=bin_search(x,ky)
if idx==-1:
print('검색값을 갖는 원소가 존재하지 않습니다.')
else:
print(f'검색값은 x[{idx}]에 있습니다. ') |
# a부터 b까지 정수의 합을 구하자 (for문 이용)
import time
import os
print("a부터 b까지 정수의 합을 구하는 프로그램을 시동합니다....")
print("로딩중...")
time.sleep(1)
print("30% 완료")
time.sleep(4)
print("72% 완료")
time.sleep(2)
print("97% 완료")
time.sleep(2)
print("잠시만 기다려 주세요...")
time.sleep(5)
print("정수 a와 b의 값을 입력해 주세요")
a=int(input("정수 a를 입력해주세요:"))
b=int(input("정수 b를 입력해주세요:"))
if a>b:
a,b=b,a
sum=0
for i in range(a,b+1):
sum+=i
print(a,'부터',b,'까지 정수의 합은',sum,'입니다.')
|
"""
" draw the scatter with log plot of both
" X and Y axis
" accept two lists as input
" range, x/y labels, title and Ticks
"""
import matplotlib.pyplot as plt
import math
class plotLog():
def __init__(self, xData, yData,):
self.xData = [math.log10(x) for x in xData]
self.yData = [math.log10(y) for y in yData]
self.plt = plt
def setLabel(self, xLabel=None, yLabel=None, fontsize=20):
self.plt.xlabel(xLabel, fontsize=fontsize)
self.plt.ylabel(yLabel, fontsize=fontsize)
def setTitle(self, title, fontsize=30):
self.plt.title(title, fontsize=fontsize)
def setTicks(self, axis, realData, labelData):
if axis.lower() == "x":
realDataLog = [math.log10(rData) for rData in realData]
self.plt.xticks(realDataLog, labelData)
elif axis.lower() == "y":
realDataLog = [math.log10(rData) for rData in realData]
self.plt.yticks(realDataLog, labelData)
def doPaint(self, label):
self.plt.plot(self.xData, self.yData, label=label, color="black", marker="x")
self.plt.legend(loc="best", fontsize=15)
self.plt.show()
if __name__ == '__main__':
x = [1,10, 100, 1000]
y = [1, 200, 3000, 40000]
xy = plotLog(x, y)
xy.setLabel(xLabel="X", yLabel="Y")
xy.doPaint("x-y") |
# Created by Viktoria
# (▰˘◡˘▰)
# 21/10/2020
# Student number: R00180598
import math
def powerV1():
num1=int(input("please enter the base number: "))
num2=int(input("please enter the power number: "))
print("The value {} raised to the power of {} is :{} ".format(num1,num2,pow(num1,num2)))
def powerV2():
num1=int(input("please enter the power number: "))
result=int(input("please enter the result number: "))
print("The logarithm of {} with base {} is : {}".format(result,num1,math.log(result,num1)))
def main():
powerV1()
powerV2()
main()
|
# Created by Viktoria
# (▰˘◡˘▰)
# 21/10/2020
# Student number: R00180598
options=["Addition","Subtraction","Multiplication","Division"]
symbols=['+','-','*','/']
def menu():
print("What would you like to perform?")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division")
def calculate(num1, num2, choice):
if (choice == 1):
final = num1 + num2
return final
elif (choice == 2):
final = num1 - num2
return final
elif (choice == 3):
final = num1 * num2
return final
else:
final = num1 / num2
return final
def smallcalc(num1,num2,choice):
if(choice>=1 and choice<=4):
total = num1 + symbols[choice - 1] + num2
return eval(total)
def main():
num1 = int(input("Please enter a numerical value: "))
num2 = int(input("Please enter another numerical value: "))
menu()
choice = int(input("> "))
final = calculate(num1, num2, choice)
print("{} of {} and {} is {} ".format(options[choice-1],num1, num2, final))
print("{:-^40}".format(""))
final2 = smallcalc(str(num1), str(num2), choice)
print("{} of {} and {} is {} ".format(options[choice - 1], num1, num2, final2))
main()
|
# Created by Viktoria
# (▰˘◡˘▰)
# 21/10/2020
# Student number: R00180598
fibonacci=[0,1]
def sequence():
for i in range(40+1):
fibonacci.append(fibonacci[i]+fibonacci[i+1])
print(fibonacci)
def getNum(index):
return fibonacci[index-1]
sequence()
print(getNum(13))
|
print(bool("Hello"))
print(bool(15))
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj)) |
#!/usr/bin/python
#
# Sums all the values from a certain predicate from the database.
import sys
from lib_db import read_db
if len(sys.argv) < 3:
print "usage: count_db_total.py <predicate> <argument position (1..N)>"
sys.exit(1)
predicate = sys.argv[1]
position = int(sys.argv[2])
db = read_db(sys.stdin.readlines())
total = 0
for node, data in db.iteritems():
for d in data:
name = d['name']
if name == 'count':
total = total + int(d['args'][position-1])
print total
|
"""
Class Block :
- block_ids: a list of blocks (We give each block an id) eg. [Block A, Block B]
- id_quantity: a dictionary consist of id and its corresponding quantity eg. {id: quantity, id:quantity}
- size: block size, a list of [L,W,H] eg. [100, 40, 100]
- orientation:
- fitness:
"""
class Block:
def __init__(self, id_quantity, simple_block=False):
#self.id = block_id
self.id_quantity = id_quantity
self.real_volume = 0
self.absolute_volume = 0
self.size = 0
self.fitness = 0
self.is_simple_block = simple_block
def get_unique_id(self):
return self.unique_id
def get_block_uids(self):
return self.block_uids
def get_id_quantity(self):
return self.id_quantity
def get_is_simple_block(self):
return self.is_simple_block
def get_upper_face(self):
return self.upper_face
def get_added_direction(self):
return self.added_direction
def get_dr_quantity(self):
return self.dr_quantity
def get_item_quantity(self):
return self.quantity
def get_size(self):
return self.size
def get_real_volume(self):
return self.real_volume
def get_absolute_volume(self):
return self.absolute_volume
def get_volume_loss(self):
return (self.absolute_volume - self.real_volume)
def get_fitness(self):
return self.fitness
def set_block_uids(self, block_uids):
self.block_uids = block_uids
def set_unique_id(self, unique_id):
self.unique_id = unique_id
def set_upper_face(self,upper_face):
self.upper_face = upper_face
def set_added_direction(self,added_direction):
self.added_direction = added_direction
def set_id_quantity(self, id_quantity):
self.id_quantity = id_quantity
def set_dr_quantity(self, dr_quantity):
self.dr_quantity = dr_quantity
def set_size(self, size):
self.size = size
def set_absolute_volume(self, absolute_volume):
self.absolute_volume = absolute_volume
def set_real_volume(self, real_volume):
self.real_volume = real_volume
def set_fitness(self, fitness):
self.fitness = fitness
def __repr__(self):
return "{id_quantity: %s\n, absolute_volume: %s\n, real_volume: %s\n, size: %s\n, fitness:%s\n, volumeloss:%s" \
% (self.id_quantity, self.absolute_volume, self. real_volume, self.size,self.fitness, self.get_volume_loss()) + "}\n"
|
"""Utility functions for storing and loading json data.
Attributes:
basepath (str): Basepath for object files.
basepath_json (str): Basepath for json files.
basepath_pick (str): Basepath for pickle files.
"""
import json
# import pickle
from os import makedirs, path
import shutil
# import traceback
# Version 1.6
basepath_json = "./jobj/"
basepath_pick = "./obj/"
# def load(filename):
# """Args:
# filename (string): Identifier for object
# Returns:
# Object
# """
# return json_load(filename)
# def save(object, filename):
# """Args:
# object (object): Object to store
# filename (string): Identifier for object
# """
# return json_save(object, filename)
def get_json_path(basepath, filename):
return path.relpath(path.join(basepath, filename + ".json"))
def json_load(filename, basepath=basepath_json, default=None):
"""Args:
filename (string): Identifier for object
Returns:
Object
"""
json_path = get_json_path(basepath, filename)
try:
with open(json_path, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.decoder.JSONDecodeError) as e:
# raise
print("Error with file", json_path)
# traceback.print_exc()
if default is not None:
# print("Load failed for file", filename, "; defaulting.")
return default
else:
# print("Load failed for file", filename, "with no default provided")
raise
def json_save(object, filepath, basepath=basepath_json):
"""Args:
object (object)
filename (string): Identifier for object
"""
filepath = get_json_path(basepath, filepath)
(fdirs, fname) = path.split(filepath)
makedirs(fdirs, exist_ok=True)
# Displace
if path.isfile(filepath):
shutil.move(filepath, filepath + ".bak")
with open(filepath, 'w') as file:
json.dump(object, file, indent=4)
load = json_load
save = json_save
class Handler():
def __init__(self, name, default=None, basepath=basepath_json, readonly=False):
self.name = name
self.default = default
self.readonly = readonly
self.basepath = basepath
self.obj = None
def load(self):
return load(self.name, basepath=self.basepath, default=self.default)
def __enter__(self):
self.obj = self.load()
return self.obj
def __exit__(self, type, value, traceback):
if not self.readonly:
self.flush()
def flush(self):
if self.readonly:
raise NotImplemented("Cannot save if readonly is True.")
else:
# print("Flushing", self.name)
save(self.obj, self.name, basepath=self.basepath)
class RotatingHandler(Handler):
def load(self):
try:
self.obj = load(self.name, basepath=self.basepath) # Don't handle failure; no default
# File is good, so:
self.backup()
return self.obj
except (json.JSONDecodeError, FileNotFoundError) as e:
print("Warning: data file '{}' corrupted. ".format(self.name))
if shutil.os.path.isfile(get_json_path(self.basepath, self.name)):
# If the file exists, but is corrupted
print("Deleting corrupted data")
shutil.os.remove(get_json_path(self.basepath, self.name))
if path.exists(get_json_path(self.basepath, self.name) + ".bak"):
# If backup exists
print("Restoring backup")
shutil.copy2(
get_json_path(self.basepath, self.name) + ".bak",
get_json_path(self.basepath, self.name)
)
self.obj = load(self.name, basepath=self.basepath)
return self.obj
elif self.default is not None:
self.obj = load(self.name, basepath=self.basepath, default=self.default)
return self.obj
else:
raise
def backup(self):
# print("Backing up", self.name)
if path.exists(get_json_path(self.basepath, self.name)):
shutil.copy2(
get_json_path(self.basepath, self.name),
get_json_path(self.basepath, self.name) + ".bak"
)
# def flush(self):
# super().flush()
# self.backup()
|
"""
and ---- ve
or ---- veya
not ----- değil
"""
sayi = int(input("Sayi Gir: "))
sayi2 = int(input("Sayi2 Gir: "))
if sayi > 5:
if sayi % 2 == 0:
print("Doğru")
//kolay yolu
if sayi > 5 and sayi % 2 == 0: //and (ve demek)
print("doğru")
if sayi > 5 or sayi2 == 5: // veya demek
print("doğru")
else:
print("En az girisin 5 olması lazım!")
if not bool(isim):
print("Doğru!") // değer giresen doğru yazar ama girmezsen retrun yapar
|
# list that saves the names of the subjects and the grades of those subjects
last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
# lists that saves other subjects and grades
subjects = ["physics", "calculus", "poetry", "history"]
grades = [98, 97, 85, 88]
# this adds computer science to subjects and 100 to grades
subjects.append("computer science")
grades.append(100)
# the zip() function combines subjects and grades and it saves this zip object
# as a list into a variable called gradebook.
gradebook = list(zip(grades, subjects))
# this append adds ("visual arts", 93) to the variable gradebook.
gradebook.append(("visual arts", 93))
# the items from both gradebook and last_semester_gradebook are stored into the
#variable full_gradebook
full_gradebook = last_semester_gradebook + gradebook
print(list(gradebook))
|
import utils
import sorts
bookshelf = utils.load_books('books_small.csv')
bookshelf_v1 = bookshelf.copy()
bookshelf_v2 = bookshelf.copy()
long_bookshelf = bookshelf.copy()
def by_title_ascending(book_a,book_b):
if book_a['title_lower'] > book_b['title_lower']:
return True
return False
def by_author_ascending(book_a,book_b):
return book_a['author_lower'] > book_b['author_lower']
def by_total_length(book_a,book_b):
return len(book_a['author_lower'])+len(book_a['title_lower']) > len(book_b['author_lower'])+len(book_b['title_lower'])
print('\nPerforming Quicksort\n')
sort1 = sorts.bubble_sort(bookshelf,by_title_ascending)
sort2 =sorts.bubble_sort(bookshelf_v1,by_author_ascending)
sort3 = sorts.bubble_sort(long_bookshelf,by_total_length)
sorts.quicksort(long_bookshelf,0,len(long_bookshelf)-1,by_total_length)
sorts.quicksort(bookshelf_v2,0,len(bookshelf_v2)-1,by_author_ascending)
print('\n Sorting the Bookshelf based on Title : Bubble Sort\n')
for book in sort1:
print(book['title'])clear
print('\n Sorting the Bookshelf based on Author : Bubble Sort\n')
for book in sort2:
print(book['author'])
print('\n Sorting the Bookshelf based on sum of characters in author and title : Bubble Sort\n')
for book in sort3:
print(book['author_lower'],book['title_lower'])
print('\n Sorting the Bookshelf based on sum of characters in author and title : Quick Sort\n')
for book in long_bookshelf:
print(book['author_lower'],book['title_lower'])
print('\n Sorting the Bookshelf based on Author : Quick Sort\n')
for book in bookshelf_v2:
print(book['author'])
|
###
# Code by Olzhas Kurenov
# Implementation of Quick Sort
# Average running time: O(nlog)
###
from random import randint
print '\n~~~~~~~~~Quick Sort Algorithm~~~~~~~~~\n'
print 'Reading input file\n'
with open('quickSort.txt') as f:
lines = f.readlines()
numbers = [];
for line in lines:
numbers.append(int(line))
def swap(a,i,j):
temp = a[i]
a[i] = a[j]
a[j] = temp
def getPivot(start, end, random):
if random and start < end:
return randint(start, end - 1)
return start;
def partitionAroundPivot(a, start, end, p):
for i in range(start, end):
if (p == i):
continue;
if a[i] < a[p] and i > p:
if (abs(i - p) == 1):
swap(a,i,p);
p=i;
else:
swap(a,i,p + 1);
swap(a,p,p + 1);
p+=1;
elif a[i] > a[p] and i < p:
swap(a,i,p);
p=i;
return p;
def QuickSort(a, start, end):
if abs(end - start) <= 1:
return;
pivot = getPivot(start, end, True);
pivot = partitionAroundPivot(a, start, end, pivot);
QuickSort(a, start, pivot);
QuickSort(a, pivot + 1, end);
print numbers;
QuickSort(numbers, 0, len(numbers));
print numbers;
|
#Importin tweepy to access twitter
import tweepy
#importing json to write to ajson file
import json
#importing pandas to create graph
import pandas as pd
#importing matplotlib to plot graph
import matplotlib.pyplot as plt
#impotrting tweepy to access twitter
from tweepy import OAuthHandler
#storing keys in public variables
consumer_key = '4lEMOO4PDthOqTXDdbm01RgtI'
consumer_secret = 'ggqfFEZ7nVHFbJgBQKm8TlF3uG58HUfdMwHzn3cEfts0XjiIuC'
access_token = '1267691766028939264-gbsyEyBgkpsRvb56o0jKMVdNfRENbS'
access_secret = 'ADtavjckOMJhd6ZDswaMG6GORYhNwYjcX9qlStKOfy9hm'
#accessing twitter account through api
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
#getting user input on what to search for
hashtag = "BLM"
tweetamount=100
#search input through api
tweets = tweepy.Cursor(api.search,q=hashtag,lang="en",until="").items(tweetamount)
alltweets = [[tweet.user.screen_name, tweet.user.location, tweet.user.created_at] for tweet in tweets]
#exporting results to a json folder
with open('twitter.json', 'w') as f:
for tweet in tweepy.Cursor(api.search,q=hashtag,lang="en",until="").items(tweetamount):
f.write(json.dumps(tweet._json)+"\n")
print("Written to Json file")
tweet_graph = pd.DataFrame(data=alltweets)
#displaying results on graph
tweet_graph.plot()
plt.xlabel('Amount of tweets about topic')
plt.ylabel('Date topic was tweeted about')
plt.title('Graph of tweets over time')
|
def verify_password(line: str, version: int = 1) -> bool:
policy, password = [item.strip() for item in line.split(':')]
bounds = policy[:-2]
letter = policy[-1]
low, high = [int(item) for item in bounds.split('-')]
if version == 1:
letter_count = password.count(letter)
if low <= letter_count <= high:
return True
elif version == 2:
letters = [password[low-1], password[high-1]]
if letters.count(letter) == 1:
return True
return False
def count_good_passwords(data: list, version: int = 1) -> int:
good_passwords = 0
for line in data:
if verify_password(line, version):
good_passwords += 1
print(f'Number of good password: {good_passwords}')
return good_passwords
if __name__ == "__main__":
data = []
with open('passwords.txt') as f:
for line in f:
data.append(line.strip())
count_good_passwords(data, version=2) |
import sys
def collatz_terms(A, limit):
num_terms = 0
while A != 1 and A <= limit:
if A % 2 == 0:
A /= 2
else:
A = 3 * A + 1
num_terms += 1
if A == 1:
num_terms += 1
return num_terms
case = 1
for line in sys.stdin:
A, limit = [int(n) for n in line.split()]
if A < 0 and limit < 0:
break
print("Case {}: A = {}, limit = {}, number of terms = "
"{}".format(case,A,limit,collatz_terms(A,limit)))
case += 1
|
import pygame
from pygame import gfxdraw
from .color import Color
class Draw:
game_display = None
screen_width = 0
screen_height = 0
@classmethod
def set_game_display(cls, screen, screen_width, screen_height):
"""
set the screen reference
:param screen: the pygame's screen object
:param screen_width:
:param screen_height:
"""
cls.game_display = screen
cls.screen_width = screen_width
cls.screen_height = screen_height
@classmethod
def update_background(cls):
"""
fill all screen with black at the begging of each frame
"""
cls.game_display.fill(Color.black)
@classmethod
def circle(cls, position, radius, color, alpha):
"""
Draw a circle
:param position: circle's position
:param radius: circle's radius
:param color: circle's color
:param alpha: the opacity of the draw
"""
if alpha < 0:
alpha = 0
pygame.gfxdraw.filled_circle(cls.game_display, int(position.x), int(position.y), int(radius), (color[0], color[1], color[2], alpha))
@classmethod
def polygon(cls, color, point_list, alpha):
"""
Draw a polygon
:param color: the color of the polygon
:param point_list: the list of points that defines the polygon
:param alpha: the opacity of the draw
"""
if alpha < 0:
alpha = 0
pygame.gfxdraw.filled_polygon(cls.game_display, point_list, (color[0], color[1], color[2], alpha))
@classmethod
def text(cls, position_x, position_y, label, alpha=255):
"""
Draws text
:param position_x: text's x position
:param position_y: text's y position
:param label: its the pygame label necessary to draw the text
:param alpha: the opacity of the draw
"""
if alpha != 255:
if alpha < 0:
alpha = 0
alpha_img = pygame.Surface(label.get_rect().size, pygame.SRCALPHA)
alpha_img.fill((255, 255, 255, alpha))
label.blit(alpha_img, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
cls.game_display.blit(label, (position_x, position_y))
|
# -*- coding: utf-8 -*-
"""
Fig. 3.4. beta prior y posterior
@author: COTP
"""
#librerias a usar
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
#fijando la semilla
np.random.seed(0)
#función de probabilidad (beta)
def fun1(n,a,b):
X=ss.beta(a,b)
X1=X.pdf(n)
return X1
#parametros
n=np.array([5,100])
Sy=np.array([1,20])
#valores del eje x
x=np.linspace(0,1,1000)
#distribuciones
plt.figure(figsize=(12,10))
plt.subplot(2,2,1)
plt.plot(x, fun1(x,1,1), x,fun1(x,1+Sy[0],1+n[0]-Sy[0]))
plt.ylabel(r'$p(\theta|y)$')
plt.xlabel(r'$\theta$')
plt.title('beta(1,1) prior, '+r'$n=5,\sum y_i=1$')
plt.legend(["prior","posterior"])
plt.subplot(2,2,2)
plt.plot(x, fun1(x,3,2),x,fun1(x,1+Sy[0],1+n[0]-Sy[0]))
plt.ylabel(r'$p(\theta|y)$')
plt.xlabel(r'$\theta$')
plt.title('beta(3,2) prior, '+r'$n=5,\sum y_i=1$')
plt.legend(["prior","posterior"])
plt.subplot(2,2,3)
plt.plot(x, fun1(x,1,1),x,fun1(x,1+Sy[1],1+n[1]-Sy[1]))
plt.ylabel(r'$p(\theta|y)$')
plt.xlabel(r'$\theta$')
plt.title('beta(1,1) prior, '+r'$n=100,\sum y_i=20$')
plt.legend(["prior","posterior"])
plt.subplot(2,2,4)
plt.plot(x, fun1(x,3,2),x,fun1(x,1+Sy[1],1+n[1]-Sy[1]))
plt.ylabel(r'$p(\theta|y)$')
plt.xlabel(r'$\theta$')
plt.title('beta(1,1) prior, '+r'$n=100,\sum y_i=20$')
plt.legend(["prior","posterior"])
plt.show()
|
import pygame
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
WHITE = (255,255,255)
class Button:
def __init__(self,screen,x,y,w,h,wm,hm,name):
self.screen = screen
self.color = [YELLOW,RED]
self.toggle = 0
self.name = name
self.x,self.y,self.w,self.h,self.wm,self.hm = x,y,w,h,wm,hm
self.Toggle()
def Toggle(self):
self.draw_button(self.color[self.toggle])
self.toggle=1-self.toggle
def UnToggle(self):
self.draw_button(YELLOW)
self.toggle=1
def draw_button(self,color):
x,y,w,h,wm,hm = self.x,self.y,self.w,self.h,self.wm,self.hm
pygame.draw.rect(self.screen, BLACK, (x,y,wm,hm), 5)
k = 1
pygame.draw.rect(self.screen, color, (x+k,y+k,wm-k,hm-k))
aName = self.name
Text.headline(aName,x+5,y+10,25,self.screen)
def isClicked(self,event):
posx = event.pos[0]
posy = event.pos[1]
x,y,wm,hm = self.x,self.y,self.wm,self.hm
if(x<=posx and posx<=x+wm):
if(y<=posy and posy<=y+hm):
print(x,posx,x+wm,y,posy,y+hm)
print(x)
return 1
return 0
class Text:
@staticmethod
def headline(headline,x,y,size,Screen):
def getFont(size):
return pygame.font.SysFont("monospace", size)
label = getFont(size).render(headline, 1 , BLACK)
Screen.blit(label, (x, y))
pygame.display.update()
|
#!/bin/python3.6
import re
f = open('./madlibs.txt').read()
for word in f.split():
if "ADJECTIVE" in word:
print("Enter a new adjective: ")
newAdj = input()
f = f.replace("ADJECTIVE", newAdj)
if "NOUN" in word:
print("Enter a new noun: ")
newNoun = input()
f = f.replace("NOUN", newNoun, 1)
if "VERB" in word:
print("Enter a new verb: ")
newVerb = input()
f = f.replace("VERB", newVerb)
fileObj = open('./madlibs.txt', 'w')
fileObj.write(f)
fileObj.close()
fileObj = open('./madlibs.txt')
fileContent = fileObj.read()
print(fileContent)
|
'''
This python program solves the given non linear equation by various methods
'''
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import *
def f(x):# the function
return np.sin(np.cos(np.exp(x)))
'''
Root finding by bisection method in the range (-1.0,1.0).
'''
root = bisect(f,-1.0,1.0)
print("root of the function sin(cos(exp(x))) = 0 is : ",root)
print("Value f(x) = ",f(root))#We an readily observe that it is not completely zero but evaluated to some toleran
'''
This function calculatesthe root the function usng newton rapson method by using the information about it's derivative.
'''
def func(x):# the derivative of the function
return -np.exp(x)*np.cos(np.cos(np.exp(x)))*np.sin(np.exp(x))
root2= newton(f,-1.0,fprime = func)# evaluated with initial guess at x = -1.0
root3= newton(f,-0.1,fprime = func)# evaluated with initial guess at x = -0.1
root4= newton(f,-1.0)# this one find's the root using secant method
print("root with initial guess at -1.0= ",root2)
print("Value f(x) = ",f(root2))
print("root with initial guess at -0.1 = ",root3)
print("Value f(x) = ",f(root3))
print("root using secant method with initial guess at -1.0= ",root4)
print("Value f(x) = ",f(root4))
'''
The answer for each of the initial guesses changes because the newton Raphson method for different values of initial conditions, the roots might fall at different places.
'''
x = np.linspace(-2.5,10,200)
y = f(x)
l1 = func(-1.0)*x+f(-1.0)
plt.plot(x,y)
plt.plot(x,l1)
plt.grid()
plt.show() |
INF = int(1e9)
# graph = [[] for i in range(n + 1)]
graph = [
[],
[(2, 2), (3, 5), (4, 1)],
[(3, 3), (4, 2)],
[(2, 3), (6, 5)],
[(3, 3), (5, 1)],
[(3, 1), (6, 2)],
[]
]
visited = [False] * (len(graph))
distance = [INF] * (len(graph))
def get_small_node():
min_val = INF
index = 0
for i in range(1, len(graph)):
if distance[i] < min_val and not visited[i]:
index = i
min_value = distance[i]
return index
def dijkstra(next):
distance[next] = 0
for _ in range(len(graph) - 1):
next = get_small_node()
visited[next] = True
for node in graph[next]:
distance[node[0]] = min(distance[next] + node[1], distance[node[0]])
dijkstra(1)
print(distance[1:])
|
from collections import deque
queue = deque()
queue.append(8)
queue.append(1)
queue.append(4)
queue.append(2)
print("팝 :", queue.popleft())
queue.append(0)
queue.append(3)
print("팝 :", queue.popleft())
print(queue)
queue.reverse()
print(queue) |
s = list(input())
s.sort()
sum = 0
for c in s:
if '0'<= c <= '9':
sum += int(c)
else:
print(c, end='')
print(sum) |
n = int(input())
array = []
for _ in range(n):
data = input().split()
array.append((data[0], int(data[1])))
array = sorted(array, key = lambda student: student[1])
for i in array:
print(i[0], end = ' ')
# print([x[0] for x in d])
|
def bubblesort(myList):
for item in range(len(myList)):
for i in range(len(myList)-1):
if myList[i] > myList[i+1]:
myList[i], myList[i+1] = myList[i+1], myList[i]
numList = [1, 5, 6, 7, 8, 2, 3, 4, 5, 6, 1, 8,
9, 4, 243, 23, 12, 19, 54, 43]
bubblesort(numList)
print(numList) |
import matplotlib.pyplot as plt
import pandas as pd
# setting to display max 85 columns because default is 10
pd.set_option('display.max_columns', 85)
# loading data
df_data_schema = pd.read_csv('survey_results_schema.csv', header=0)
# loading next column but this time respondent number is row id too
df_data_public = pd.read_csv(
'survey_results_public.csv',
header=0,
usecols=['Respondent', 'WorkWeekHrs', 'Age'],
index_col=['Respondent'])
# delete rows where is Nan
df_data_public.dropna(inplace=True)
df_data_public.dtypes
df_data_public.info()
# check unique values
column_values = df_data_public[['Age']].values.ravel()
unique_values = pd.unique(column_values)
print(unique_values)
# round and check values
df_data_public['Age'].round(0)
column_values = df_data_public['Age'].values.ravel()
unique_values = pd.unique(column_values)
print(unique_values)
df_data_public['WorkWeekHrs'].round(0)
column_values = df_data_public['WorkWeekHrs'].values.ravel().astype('int64')
unique_values = pd.unique(column_values)
print(unique_values)
# choose employes who work 160 hours per week because some people said
# that they worked more than 160 but this is impossible
df_data_public = df_data_public[df_data_public.WorkWeekHrs < 161]
# change type
df_data_public = df_data_public.astype('int64', copy=False)
plt.plot(df_data_public['Age'],
df_data_public['WorkWeekHrs'],
'ro',
markersize=0.3)
df_data_public_gender = pd.read_csv(
'survey_results_public.csv',
header=0,
usecols=[
'Respondent', 'WorkWeekHrs', 'Age', 'Gender'],
index_col=['Respondent'])
plt.xlabel('Age')
plt.ylabel('WorkWeekHrs')
plt.show()
# drop nulls
df_data_public_gender.dropna(inplace=True)
# check number of genders
column_values = df_data_public_gender['Gender'].values.ravel()
unique_values = pd.unique(column_values)
print(unique_values)
df_data_public_gender['Gender'] = df_data_public_gender['Gender'].astype(str)
df_data_public_gender.info()
# select only man and woman
df_data_public_gender = df_data_public_gender.loc[
(df_data_public_gender['Gender'] == 'Man') |
(df_data_public_gender['Gender'] == 'Woman')]
column_values = df_data_public_gender['Gender'].values.ravel()
unique_values = pd.unique(column_values)
print(unique_values)
column_values = df_data_public_gender[['Age']].values.ravel()
unique_values = pd.unique(column_values)
print(unique_values)
df_data_public_gender['WorkWeekHrs'].round(0)
column_values = df_data_public_gender[
'WorkWeekHrs'].values.ravel().astype('int64')
unique_values = pd.unique(column_values)
print(unique_values)
df_data_public_gender = df_data_public_gender[
df_data_public_gender.WorkWeekHrs < 161]
grouped = df_data_public_gender.groupby('Gender')
fig, axes = plt.subplots(grouped.ngroups, sharex=True, figsize=(8, 6))
for i, (Gender, d) in enumerate(grouped):
ax = d.plot.scatter(x='Age', y='WorkWeekHrs', ax=axes[i], label=Gender)
ax.set_xlabel('AGE OF THE EMPLOYEE')
ax.set_ylabel('HOURS COUNT WORKED PER WEEK')
fig.tight_layout()
plt.show()
|
sentence = input("Write a sentence: ")
print()
long = len(sentence)
reverse=""
for i in range(long):
reverse = reverse + sentence[long-1]
long = long-1
print("Your sentence in reverse order is: " + str(reverse)) |
frase=str(input("Write a sentence and I'll give you back the letters that are in even positions."))
i=0
frase=frase.replace(' ','')
leng=len(frase)
while (i<=leng):
if (i%2!=0):
print(frase[i])
i+=1 |
def Bsearch(LIST, ITEM, n): # n is the number of elements in list
''' Main Function for the Binary Search '''
beg = 0 # starting element
last = n - 1 # end element
while (beg<=last):
mid = (beg + last)//2
if (ITEM == LIST[mid]):
return mid
elif (ITEM > LIST[mid]):
beg = mid + 1
else:
last = mid - 1
else:
return False
#__main__
if __name__ == "__main__":
# Taking the length of list from user
n = int(input("Enter the Number of elements you want in list: "))
lst = [0]* n
# Taking the elements of list from user
print("Please Enter The elements\n*please enter the list in sorted form*:")
for i in range(n):
lst[i] = int(input("Element" + str(i) + ": "))
# Taking the item from the user to search
item = int(input("Enter the element you want to search: "))
# Searching The Item
pos = Bsearch(lst, item, n)
if pos: # If item found
print(f"\nElement found at index: {pos}, Position: {pos+1}")
else: # If item not found
print(f"\n Element Not Exist in the below list!!\n{lst}") |
iteration = 0
state = 'A'
position = 0
data = ['0','1','1','1','1','1','']
#output of first data
print(f"Input data: ", data)
#algorithm
print(f"⋙State: ",state, f"⋙Position: ", position, f"⋙Data state: ", data)
def stateA():
global position
global state
if data[position] == '1' or data[position] == '0':
# same state
position += 1 # move right
elif data[position] == '':
state = 'B' # change state to B
position -= 1 # move left
print(f"⋙State: ",state, f"⋙Position: ", position, f"⋙Data state: ", data)
def stateB():
global position
global state
if data[position] == '1':
# same state
data[position] = '0' # change data to 0
position -= 1 # move left
elif data[position] == '0' or data[position] == '':
state = 'C' # change state to C
data[position] = '1' # change data to 1
position -= 1 # move
print(f"⋙State: ",state, f"⋙Position: ", position, f"⋙Data state: ", data)
def stateC():
print(f"Done! ⋙Output: " , data)
while True:
if state == 'A':
stateA()
elif state == 'B':
stateB()
else:
stateC()
break
|
fruits = ["Bananas", "Oranges", "Mangoes", "passion fruits"]
for x in fruits:
print(x)
if x == "Mangoes":
break
# BREAKING BEFORE THE LOOP
fruits = ["Bananas", "Oranges", "Mangoes", "passion fruits"]
for x in fruits:
if x == "Mangoes":
break
print(x)
#CONTINUE USE, STOPS THE MENTION ELEMENT IN THE LIST
fruits = ["Bananas", "Oranges", "Mangoes", "passion fruits"]
for x in fruits:
if x == "Mangoes":
continue
print(x)
|
class person:
def __init__(self, age, name):
self.age = age
self.name = name
def myfunction(self):
print("Hello my name is " + self.name + " and am", self.age)
p1 = person(30, "John")
p1.myfunction()
|
def ordinal( x ):
suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
if x < 0:
x *= -1
x = int(x)
if x % 100 in (11,12,13):
p = 'th'
else:
p = suffix[x % 10]
return str(x) + p
print[ordinal(n) for n in range(1,10)]
|
##Screen asking you to input yourname
print("Enter your name:")
x = input()
print("Hello", x) |
class Myfirstclass:
def __init__(self, name, age):
self.age = age
self.name = name
p1 = Myfirstclass("James", 30)
#print("My name is", p1.name, "and am " , p1.age,".")
print(p1.age)
print(p1.name) |
#Data
Belanja1 = input("Masukkan daftar belanja 1:")
Belanja2 = input("Masukkan daftar belanja 2:")
Belanjatambah1 = input("Tambahkan data ke daftar belanja 1:")
Belanjatambah2 = input("Tambahkan data ke daftar belanja 2:")
#Progres
print("Daftar belanja 1 adalah", Belanja1 +","+Belanjatambah1)
print("Daftar belanja 2 adalah", Belanja2 +","+Belanjatambah2)
#Data
Belanja1 = input("Masukkan daftar belanja 1:")
Belanja2 = input("Masukkan daftar belanja 2:")
Belanjatambah1 = input("Tambahkan data ke daftar belanja 1:")
Belanjatambah2 = input("Tambahkan data ke daftar belanja 2:")
#progres
print("Daftar belanja 1 adalah", Belanja1 +","+Belanjatambah1)
print("Daftar belanja 2 adalah", Belanja2 +","+Belanjatambah2)
|
print('-' * 75)
import json
# Dictionary
emp = {
1: {
'name': 'justin',
'loc': 'kochin'
},
2: {
'name': 'tris',
'loc': 'hyderabad'
},
3: {
'name': 'davies',
'loc': 'noida'
}
}
print(emp, '-', type(emp))
print('-' * 75)
# Convert dictionary to JSON object
json_obj = json.dumps(emp)
print(json_obj, '-', type(json_obj))
print('-' * 75)
# Convert JSON object to Python Native Datatype
json_dict = json.loads(json_obj)
print(json_dict, '-', type(json_dict))
# Parse the content
print('Only 3rd Record -', json_dict['3'])
print('Name from 3rd Record -', json_dict['3']['name'])
print('-' * 75)
# Write the dictionary to JSON file
with open(r'files\data.json', 'w') as json_write:
json.dump(emp, json_write, indent=4)
print('JSON File Written')
print('-' * 75)
# Read the content of JSON in the form of Python Datatype
with open(r'files\data.json') as json_read:
json_dict = json.load(json_read)
print(json_dict, '-', type(json_dict))
print('-' * 75)
emp = {
"count": 1,
"alerts": [
{
"nsxtManager": "10.79.65.233",
"eventTags": [
"NSX-T"
],
"displayName": "Routing Advertisement disabled",
"name": "NSXTRoutingAdvertisementEvent",
"eventSeverity": "Warning",
"eventType": "Problem",
"intentName": "",
"manager": "10.79.65.233",
"anchorEntities": [
"oc-cl1-kube-public"
],
"recommendations": [
"Enable route advertisement on Tier-1 logical router."
],
"reason": "",
"message": "Routing advertisement for Tier-1 logical router oc-cl1-kube-public is disabled",
"definedBy": "System",
"description": [
"Routing advertisement is disabled for NSX-T Tier-1 logical router. Networks under this router are not reachable from outside."
]
}
]
}
res_json = json.dumps(emp) #default=lambda o: o.__dict__)
print(res_json)
print('-' * 75)
|
proceed = 1
try :
dictFile = open(input("Enter the file path to create Keys : "), encoding="utf8")
except Exception :
print (" FILE OPEN ERROR FROM CODE")
proceed = 0
if proceed==1 :
# trigger an empty dictionary
wordDict = dict()
count = 0
for line in dictFile :
wordKeys = line.split()
for word in wordKeys :
#wordDict.update({word : count}) # flavor #1
wordDict.update(dict([(word , count)])) # flavor #2
count = count+1
display = input ("Display Keys and values (0/1) ")
if display == str(1) :
print (wordDict)
print (wordDict.keys())
print (wordDict.values())
while True :
inputStr = input("Enter the key to search : ")
if inputStr == "exit" :
break
else :
if inputStr in wordDict :
print ("key is present in dictionary at position : {} ".format(wordDict[inputStr]))
else :
print ("Key NOT present in dictionary. Try Again !")
# to count how many times each letter appears in the keys above.
letterCount = 0
display = input ("Display letter count map : ")
if display == str(1) :
countMe = dict()
for keyStr in wordDict.keys() :
for c in keyStr :
if c not in countMe:
countMe[c] = 1
else:
countMe[c] = countMe[c] + 1
print(countMe)
else :
print ("ERROR IN OPENING FILE, END PROGRAM")
|
'''
itertools.islice()
perfrom lazy slicing of any iterator
'''
from itertools import islice, count
one_million_numbers = (x for x in range(1, 1000000))
first_ten = islice(one_million_numbers, 10)
for x in first_ten:
print(x)
def is_even(num):
"""
Predicate Function
:param num:
:return:
"""
if num % 2 == 0:
return True
else:
return False
# first thousand evens isslice and count
first_thousand_even = islice((x for x in count() if is_even(x)), 1000)
print(first_thousand_even)
list_it = list(first_thousand_even)[-10:]
print(list_it)
for x in first_thousand_even:
print(x) |
import threading
from time import sleep
def do_work(item):
print("Processing !! --> {} by --> {} ".format(item, threading.current_thread().name))
sleep(1)
def worker():
while True:
# get processing item from queue when available
item = q.get()
if item is None:
break
do_work(item)
q.task_done()
def source():
return [1, 2, 3, 4, 5, 6]
if __name__ == "__main__":
num_worker_threads = 3
q = queue.Queue()
threads = []
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for item in source():
q.put(item)
sleep(1)
print("{} added".format(item))
# block until all tasks are done
q.join()
# stop workers
for i in range(num_worker_threads):
q.put(None)
for t in threads:
t.join()
|
'''
Syntax: Generators are type of comprehension that generates generator object.
Syntax is similar to list comprehension, instead of square brackets [], parenthesis are used ()
(expr(item) for item in iterable)
where needed : where you need,
- lazy evaluation of generators
and
- declarative way of writing comprehensions
Note:
- Generator are single use objects. Everytime we call generator function, a new generator object is created.
- To re-create a generator-object from a generator-expression, you must execute the expression again
- once it is used, it will not yield in the next call. See below &&&
'''
from LearningPy.concepts import util
'''
Task: to generate squares of 1 million numbers.
No memory is consumed, as no list of numbers is created yet, lazy evaluation, just a generator
object is created.
once we call upon a list() on this, then the generator will yield
'''
'''generator expression called and generator object is created'''
million_number_square = (x * x for x in range(1, 1000001))
print(million_number_square)
'''yielded or we can say it is consumed'''
list_of_first_ten = list(million_number_square)[:10]
print(list_of_first_ten)
'''&&& once it is yielded/consumed in someway, it will not yield in the next call. Below will print []'''
list_of_first_ten = list(million_number_square)[:10]
print(list_of_first_ten)
'''call again the generator-expression to get new generator object
generator expression called and generator object is created'''
million_number_square_02 = (x * x for x in range(1, 1000001))
print(million_number_square is million_number_square_02)
'''new generator object consumed'''
list_of_last_ten = list(million_number_square_02)[-10:]
print(list_of_last_ten)
''' Sum of squares if first 1 million numbers.'''
print(sum(x * x for x in range(1, 10000001)))
''' Sum of even numbers in first 1000 numbers '''
print(sum(x for x in range(1000) if util.is_even(x)))
|
import turtle
from random import randint
from turtle import Turtle, Screen
class DrawShapes() :
def __init__(self, turtleShape = "Arrow", turtleColor = "red"):
self.xLoc = 0
self.yLoc = 0
self.my_turtle = turtle.Turtle()
self.color = "red"
self.screen = Screen()
self.width = self.my_turtle.width(3)
# set color mode
self.screen.colormode(255)
def draw_shapes(self):
self.draw_shape(self.xLoc, self.yLoc, 3)
self.draw_shape(self.xLoc, self.yLoc, 4)
self.draw_shape(self.xLoc, self.yLoc, 5)
self.draw_shape(self.xLoc, self.yLoc, 6)
self.draw_shape(self.xLoc, self.yLoc, 7)
self.draw_shape(self.xLoc, self.yLoc, 8)
self.draw_shape(self.xLoc, self.yLoc, 9)
screen = Screen()
screen.exitonclick()
def get_rand_color(self):
self.my_turtle.pencolor(randint(0, 255),
randint(0, 255),
randint(0, 255))
def draw_shape(self, xLoc, yLoc, sides, sideLen = 100):
if sides == 0:
return
angle = 360 / sides
self.get_rand_color()
"""
- start, forward x side
while:
- turn by angle
- draw side
if reach xLoc, yLoc
break
"""
while True:
print("-->",self.my_turtle.pos(), abs(self.my_turtle.pos()))
self.my_turtle.forward(sideLen)
self.my_turtle.right(angle)
# if reach to start position
if abs(self.my_turtle.pos()) < 1:
break
if __name__ == '__main__':
printer = DrawShapes()
printer.draw_shapes() |
print('-' * 75)
# Functions
# Re-usable piece of code
def validate_mobile_number(mobile):
status = 'invalid'
'''
Should be 10 Digits
First digit should be between 6 and 9
'''
if len(mobile) == 10 and mobile.isdigit() and int(mobile[0]) in range(6, 10):
status = 'valid'
return status, len(mobile), [mobile, mobile.isdigit()]
print(validate_mobile_number, '-', type(validate_mobile_number))
ret_status = validate_mobile_number('8876543210')
if ret_status is not None:
print('Returns -', ret_status, '-', type(ret_status))
else:
print("Function Returns Nothing")
print('-' * 75)
name = 'justin'
loc = 'bangalore'
sal = 9000.508776
print('Concat -', name + ' from ' + loc + ' earns Rs.' + str(sal))
print('Format 1 -', '{} from {} earns Rs.{}'.format(name, loc, sal))
print('Format 2 -', '{} from {} and {} earns Rs.{}'.format(name, loc, name, sal))
print('Format 3 -', '{0} from {1} and {0} earns Rs.{2}'.format(name, loc, sal))
print('Format 4 -', '{nm} from {lc} earns Rs.{sl}'.format(nm=name,
lc=loc,
sl=sal))
print('Format 5 -', f'{name.upper()} from {loc.title()} earns Rs.{sal + 25000}')
print('Format 6 -', '%s from %s earns Rs.%.02f' % (name, loc, sal))
print('Using Padding 1 -', '{:10} from Bangalore'.format(name))
print('Using Padding 2 -', '{:>10} from Bangalore'.format(name))
print('-' * 75)
|
"""
Model to aircraft flights
"""
from pprint import pprint as pp
class Flight:
'''
instance method for initializing new objects
it is an initializer not a constructor
self ~ this in java
_number ? why
- to avoid name clash with number()
- by convention, implementation details start with underscore
'''
def __init__(self, number, aircraft):
if not number[:2].isalpha():
raise ValueError(f"No Airline code in Flight '{number}'")
if not number[:2].isupper():
raise ValueError(f"Invalid Airline code in Flight '{number}'")
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError(f"Invalid route number in Flight '{number}'")
self._number = number
self._aircraft = aircraft
# seat booking data structure will be list of dictionaries
# list : number of rows
# dict : mapping of seat to passenger
rows, seats = self._aircraft.seating_plan()
'''
say xxx ---> {seat_letter: None for seat_letter in seats} is dictionary comprehension
[ xxx for _ in rows ] list comprehension
so, it is list of dictionaries
[None,
{'A': None, 'B': None, 'C': None, 'D': None, 'E': None, 'F': None},
{'A': None, 'B': None, 'C': None, 'D': None, 'E': None, 'F': None},
.
.
{'A': None, 'B': None, 'C': None, 'D': None, 'E': None, 'F': None}]
'''
self._seating = [None] + [{seat_letter: None for seat_letter in seats} for _ in rows]
def allocate_seat(self, seat, passenger_name):
row, letter = self._parse_seat(seat)
if self._seating[row][letter] is not None:
raise ValueError(f"Seat Occupied {seat}")
self._seating[row][letter] = passenger_name
def reallocate_passenger(self, from_seat, to_seat):
row_from, letter_from = self._parse_seat(from_seat)
if self._seating[row_from][letter_from] is None:
raise ValueError (f"No Passenger to relocate from seat {from_seat}")
if self._seating[row_from][letter_from] is not None:
raise ValueError (f"Already occupied Passenger seat {from_seat}")
row_to, letter_to = self._parse_seat(from_seat)
self._seating[row_to][letter_to] = self._seating[row_from][letter_from]
self._seating[row_from][letter_from] = None
def num_available_seats(self):
return sum(sum (1 for s in row.values if s is None) # seat per row
for row in self._seating if row is not None) # each row
def _parse_seat(self, seat):
rows, seat_letters = self._aircraft.seating_plan()
# get last character as seat letter
letter = seat[-1]
if letter not in seat_letters:
raise ValueError(f"Invalid seat letter {seat}")
row_text = seat[:-1]
try:
row = int(row_text)
except ValueError:
raise ValueError(f"Invalid seat row {seat}")
if row not in rows:
raise ValueError(f"Out of range row in seat {seat}")
return row, letter
def aircraft_model(self):
return self._aircraft.model()
# self basically holds the reference of the instance on which the method is called.
def number(self):
return self._number
def airline(self):
return self._number[:2]
def current_seating(self):
return self._seating
def make_boarding_cards(self, card_printer):
for passenger, seat in sorted(self._passenger_seat()):
card_printer(passenger, seat, self._number, self.aircraft_model())
def _passenger_seat(self):
rows, seat_letters = self._aircraft.seating_plan()
for r in rows:
for sl in seat_letters:
passenger = self._seating[r][sl]
if passenger is not None:
yield passenger, f"{r} {sl}" #tuple
# class Aircraft:
#
# def __init__(self, registration, model, num_rows, num_seats_per_row):
# self._registration = registration
# self._model = model
# self._num_rows = num_rows
# self.num_seats_pre_row = num_seats_per_row
#
# def model(self):
# return self._model
#
# def registration(self):
# return self._registration
#
# def seating_plan(self):
# return (range(1, self._num_rows+1),
# "ABCDEFJHIJK"[:self.num_seats_pre_row])
"""
Polymorphism is achieved using duck-typing. Also, called Late binding.
Duck Typing Context:
if a bird, swims like a duck, walks like duck and quacks like a duck, then i will call it a duck
concept:
- object's fitness for use is only determined at use (in ontrast to statically typed compiled languages, where compiler
decides if the object can be used)
- in duck typing, suitability is not determined by inheritance or interfaces except the attributes the object has
at the time of use.
"""
class A380:
def __init__(self, registration):
self._registration = registration
self._model = "A380"
self._num_rows = 10
self.num_seats_pre_row = 9
def model(self):
return self._model
def registration(self):
return self._registration
def seating_plan(self):
return (range(1, self._num_rows+1),
"ABCDEFJHIJK"[:self.num_seats_pre_row])
class Boeing777:
def __init__(self, registration):
self._registration = registration
self._model = "Boeing777"
self._num_rows = 4
self.num_seats_pre_row = 6
def model(self):
return self._model
def registration(self):
return self._registration
def seating_plan(self):
return (range(1, self._num_rows+1),
"ABCDEFJHIJK"[:self.num_seats_pre_row])
def console_card_printer(passenger, seat, flight, aircraft):
output = f"| Name : {passenger} " \
f" Seat : {seat}" \
f" Flight : {flight}" \
f" Aircraft: {aircraft} |"
banner = "+" + "-" * (len(output) - 2) + "+"
border = "|" + " " * (len(output) - 2) + "|"
lines = [banner, border, output, border, banner]
card = "\n".join(lines)
print(card)
print()
'''
class invariants:
Truths about an object that endure for its lifetime
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.
It should follow two conditions to become class invariant:-
The condition should hold at the end of every constructor.
The condition should hold at the end of every mutator (non-const) operation
-----------
Class invariant is a property of a class which always fulfills or satisfies some condition even after going through transformations by using public methods.
A class invariant is simply a property that holds for all instances of a class, always, no matter what other code does.
------------
class invariant
The collection of meanings and constraints on the fields and properties of a class that describe the valid states of all instances of the class before and after each method is called. The class invariant should appear as comments on the declarations of the fields. A constructor should truthify the class invariant. Each method body and property can assume that the class invariant is true
and should terminate with the class invariant true, for all objects.
'''
if __name__ == "__main__":
f = Flight("AI3344", A380("D-WIVEDI"))
f.allocate_seat("1A", "Chirag Nayak")
f.allocate_seat("1B", "Saanvi Nayak")
f.allocate_seat("1C", "Yamini Dwivedi")
f.allocate_seat("2A", "SJV")
pp(f.current_seating())
f.make_boarding_cards(console_card_printer)
g = Flight("SD1234", Boeing777("N-AYAK"))
g.allocate_seat("1A", "Chirag Nayak")
g.allocate_seat("1B", "Saanvi Nayak")
g.allocate_seat("1C", "Yamini Dwivedi")
g.allocate_seat("2A", "SJV")
pp(g.current_seating())
g.make_boarding_cards(console_card_printer)
|
import random
import turtle
from random import randint
from turtle import Turtle, Screen
class RandomWalk():
def __init__(self, screen_size=500, step_size=20, steps_to_take=500, use_heading = False ):
self.xLoc = 0
self.yLoc = 0
self.my_turtle = turtle.Turtle()
self.color = "red"
self.screen = Screen()
self.width = self.my_turtle.width(7)
# set screen size
self.screen_size = screen_size
self.screen.setup(self.screen_size, self.screen_size)
self.limit = self.screen_size / 2
self.step_size = step_size
self.steps_to_take = steps_to_take
self.use_heading = use_heading
# set color mode
self.screen.colormode(255)
def get_rand_color(self):
self.my_turtle.pencolor(randint(0, 255),
randint(0, 255),
randint(0, 255))
def take_random_direction_and_step(self, stepSize):
self.get_rand_color()
if self.use_heading:
self.my_turtle.setheading(random.choice([0, 90, 180, 270]))
self.my_turtle.forward(stepSize)
else:
dir = random.randint(0, 3)
if self.check_if_hitting_wall(dir):
return
if dir == 0:
self.my_turtle.right(90)
self.my_turtle.forward(stepSize)
elif dir == 1:
self.my_turtle.left(90)
self.my_turtle.forward(stepSize)
elif dir == 2:
self.my_turtle.backward(stepSize)
else:
self.my_turtle.forward(stepSize)
def take_steps(self, xLoc=0, yLoc=0):
step = 0
self.my_turtle.setposition(xLoc, yLoc)
while step < self.steps_to_take:
self.take_random_direction_and_step(self.step_size)
step += 1
screen = Screen()
screen.exitonclick()
def check_if_hitting_wall(self, dir):
"""
right limit = x = 250
top limit = y = 250
bottom limit = y = -250
left limit = x = -250
"""
(xPos, yPos) = self.my_turtle.position()
if xPos >= self.limit or xPos <= -self.limit or yPos >= self.limit or yPos <= -self.limit:
# go backwards
self.my_turtle.right(180)
self.my_turtle.forward(self.step_size * 3)
return True
else:
return False
if __name__ == '__main__':
rWalk = RandomWalk(screen_size=500, step_size=20, steps_to_take=200, use_heading=False)
rWalk.take_steps()
|
'''
Exercise 4.6 - Successor:
Write an algorithm to find the "next" node of a given node in a binary seach tree.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.parent = None
def minNode(node):
while root.left:
root = root.left
return root.val
def successorNode(node):
if node.right:
return minNode(node.right)
parent = node.parent
while parent and parent.right == node:
node = parent
parent = parent.parent
return node
|
'''
Exercise 10.4 - Sorted Search, No Size:
You are given an array-like data structure Listy which lacks
a size method. It does, however, have an elementAt(i) method
that returns the element at index i in O(1) time. If i is beyond
the bounds of the data structure, it returns -1. (For this reason,
the data structure only supports positive integers.) Given a Listy
which contains sorted, positive integers, find the index at which an
element x occurs. If x occurs multiple times, you may return any index.
'''
def findLength(myList,target):
index = 1
while myList[index-1] != -1 and myList[index-1] <= target:
index *= 2
return index-1
def tweakBS(myList,target,start,end):
while start <= end:
middle = (start + end)//2
if myList[middle] == target:
return middle
if target < myList[middle] or myList[middle] == -1:
end = middle-1
else:
start = middle+1
return -1
def sortedSearch_noSize(myList,target):
length = findLength(myList,target)
return tweakBS(myList,target,0,length)
if __name__ == "__main__":
myList = [1,2,4,5,6,10,23,25,100,200,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
print(sortedSearch_noSize(myList,100)) |
'''
Exercise 1.2 - Check Permutation:
Given two strings, write a method to decide if one is a permutation of the other.
O(n) solution
'''
def stringToDict(s):
character_dict = dict()
for character in s:
if character not in character_dict:
character_dict[character] = 1
else:
character_dict[character] += 1
return character_dict
def checkPermutation(s1, s2):
if len(s1) != len(s2):
return False
s1_dict = stringToDict(s1)
s2_dict = stringToDict(s2)
if len(s1_dict) != len(s2_dict):
return False
for character in s1_dict:
if not (character in s2_dict and s1_dict[character] == s2_dict[character]):
return False
return True
if __name__ == "__main__":
# True
print(checkPermutation('hello world','world hello'))
print(checkPermutation('dogandcat','catanddog'))
# False
print(checkPermutation('hello world','world hell'))
print(checkPermutation('dogandcat','doganddog')) |
"""
Bellman-Ford algorithm
Time Complexity: O(EV)
"""
def shortestPath(graph, start):
# Initialize distances.
distance = {}
for k in graph:
distance[k] = float('inf')
distance[start] = 0
# Rellax all edges V -1 Times.
for _ in range(len(graph)):
for node in graph:
for neighbour in graph[node]:
if distance[neighbour] > (distance[node] + graph[node][neighbour]):
distance[neighbour] = (distance[node] + graph[node][neighbour])
return distance
# Check for negative-weight cycles.
for node in graph:
for neighbour in graph[node]:
if distance[neighbour] > (distance[node] + graph[node][neighbour]):
raise NameError('Negative weight cycle!')
if __name__ == "__main__":
graph = {
'A': { 'B': -1, 'C': 4 },
'B': { 'C': 3, 'D': 2, 'E': 2 },
'C': { },
'D': { 'C': 5, 'B': 1 },
'E': { 'D': -3 }
}
distance = shortestPath(graph,'A')
for k in graph:
print("Distance from [ A ] to [",k,"] -> ",distance[k]) |
'''
Exercise 8.5 - Recursive Multiply:
Write a recursive function to multiply two positive integers without
using the * operator or / operator. You can use addition, substraction,
and bit shifting, but you should minimize the number of those operations.
'''
def recursiveMultiply(a,b):
def multiply(a,b):
if a == 1:
return b
return b + multiply(a-1,b)
smaller = a if a < b else b
bigger = b if a < b else a
half = multiply(smaller//2,bigger)
if smaller%2 == 0:
return half + half
else:
return half + half + bigger
if __name__ == '__main__':
print(recursiveMultiply(17,23)) |
'''
Exercise 2.6 – Palindrome:
Implement a function to check if a linked list is a palindrome.
'''
from LinkedList import LinkedList
from collections import deque
def isPalindrome(myList):
current = runner = myList.head
stack = deque()
while runner != None:
stack.append(current.value)
current = current.next
runner = runner.next
if runner:
runner = runner.next
else:
# In the case the list is even we need to pop the middle element
stack.pop()
while current != None:
if current.value != stack.pop():
return False
current = current.next
return True
if __name__ == "__main__":
myList = LinkedList()
myList.addMultiple([1,2,3,4,3,2,1])
print(isPalindrome(myList))
|
def partition(myList, start, end):
pivot = myList[(start + end)//2]
while start <= end:
while myList[start] < pivot:
start += 1
while myList[end] > pivot:
end -= 1
if start <= end:
myList[start], myList[end] = myList[end], myList[start]
start += 1
end -= 1
return start
def quickSort(myList, start, end):
index = partition(myList,start,end)
if start < index -1:
quickSort(myList,start,index-1)
if index < end:
quickSort(myList,index,end)
a = [3,2,6,5,7,8,1,10,100,69]
quickSort(a,0,9)
print(a) |
'''
Exercise 2.2 – Return Kth to Last:
Implement an algorithm to find the Kth to last element
of a singly linked list.
'''
from LinkedList import LinkedList
# Revursive
def recursiveKth(node,k):
if node == None:
return 1, None
position, kvalue = recursiveKth(node.next,k)
if position == k:
return position+1, node.value
return position+1,kvalue
def returnKthR(myList,k):
position, kvalue = recursiveKth(myList.head,k)
return kvalue
# Iterative
def returnKthI(myList,k):
current = runner = myList.head
for _ in range(k):
if runner == None:
return None
runner = runner.next
while runner != None:
runner = runner.next
current = current.next
return current.value
if __name__ == "__main__":
myList = LinkedList()
myList.addRandom(1,100,10)
print(myList)
print(returnKthI(myList,3))
|
'''
Priority Queue for Dijkstra Algorithm
Time Complexity:
* add = O(1) // We do not heapify
* pop = O(log(n))
* decrease = O(log(n))
'''
class PriorityQueue:
def __init__(self):
self.nodes = []
self.total_nodes = 0
self.indexs = {}
def add(self, priority, node):
self.nodes.append((priority,node))
self.indexs[node] = self.total_nodes
self.total_nodes += 1
def pop(self):
def popHeapify(index):
left = (index * 2) + 1
right = (index * 2) + 2
min_val = index
if left < self.total_nodes and self.nodes[left] < self.nodes[min_val]:
min_val = left
if right < self.total_nodes and self.nodes[right] < self.nodes[min_val]:
min_val = right
if min_val != index:
minIndex, currentIndex = self.nodes[min_val][1], self.nodes[index][1]
self.indexs[minIndex], self.indexs[currentIndex ] = self.indexs[currentIndex], self.indexs[minIndex]
self.nodes[min_val], self.nodes[index] = self.nodes[index], self.nodes[min_val]
popHeapify(min_val)
if self.empty():
return
node = self.nodes[0]
firstIndex, lastIndex = self.nodes[0][1], self.nodes[self.total_nodes-1][1]
self.indexs[lastIndex] = self.indexs[firstIndex]
self.nodes[0], self.nodes[self.total_nodes-1] = self.nodes[self.total_nodes-1], self.nodes[0]
self.nodes.pop()
del self.indexs[firstIndex]
self.total_nodes -= 1
popHeapify(0)
return node
def decrease(self, node, priority):
def decreaseHeapify(index):
if self.nodes[index//2] > self.nodes[index]:
parentIndex, childIndex = self.nodes[index//2][1], self.nodes[index][1]
self.indexs[parentIndex], self.indexs[childIndex ] = self.indexs[childIndex], self.indexs[parentIndex]
self.nodes[index//2], self.nodes[index] = self.nodes[index], self.nodes[index//2]
decreaseHeapify(index//2)
index = self.indexs[node]
self.nodes[index] = (priority,node)
decreaseHeapify(index)
def empty(self):
return self.total_nodes < 1
def getPriority(self,node):
return self.nodes[self.indexs.get(node)][0]
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 11:42:27 2020
@author: Parvish
"""
# Finds sum with equal partition of the list
def equalPartitionSums(l):
listLength=len(l)
l1=[]
l2=[]
for i in range(listLength,0,-1):
for j in range(0,listLength-1):
l1.append(l[j])
for k in range(listLength-1,len(l)):
l2.append(l[k])
if sum(l1) == sum(l2):
print('List 1: ', l1, '\nList 2: ',l2,'\nSum: ', sum(l1))
break;
elif sum(l2)<sum(l1):
l1=[]
l2=[]
listLength-=1
else:
print('No such partition possible')
break;
# Main Function
def main():
n=int(input('Enter the length of your list: '))
ls=[]
l=[]
for i in range(0,n):
l=int(input())
ls.append(int(l))
ls.sort()
equalPartitionSums(ls)
# While loop, in order to ask user for retry
while 1:
main()
ta=input('Try again? (Y/N)')
if(ta.lower() == 'n'):
break
"""
Example:
#1 Enter the length of the list: 6
1
1
2
3
3
10
#Output will come as,
List 1: [1,1,2,3,3]
List 2: [10]
Sum: 10
#2 Enter the length of list: 5
1
2
3
4
5
# Output will come as,
No such partitions possible
""" |
pw = "Kaddan"
intentos = 3
clave = input("BIENVENIDO AL SISTEMA. POR FAVOR, INSERTAR LA CLAVE DE ACCESO:")
while intentos>0:
if pw.lower() == clave.lower():
print("\nLA CONTRASEÑA ES CORRECTA. BIENVENIDO AL SISTEMA.")
intentos = 0
else:
intentos -=1
if intentos==0:
print("SE HAN ACABADO TUS INTENTOS. POR FAVOR, NO VUELVA HASTA SABER LA CLAVE DE ACCESO.")
else:
print(f"\nLA CONTRASEÑA ES INCORRECTA. TE QUEDAN {intentos} INTENTOS.")
clave = input("POR FAVOR, INSERTAR LA CLAVE DE ACCESO:") |
# 1. Realiza una función que imprima 'Hola Mundo'
def holamundo():
print('Hola Mundo!')
# 2. Realiza una función que sume dos números pasados por parámetros
def sumador(a,b):
return a+b
# 3. Realiza una función que indique si un número pasado por parámetro es par o impar.
def espar(a):
return (a%2 == 0)
# 4. Hacer una función que nos genere un número aleatorio entre dos parámetros pasados.
from random import * # Importa de una librería llamada random, ya existe
def azar(a,b):
if a > b:
c = a
a = b
b = c
return randint(a,b) # randint es una función de la librería random
# 5. Crea una función que calcule el factorial de un número pasado por parámetro.
def factorial(a):
resultado = a
for i in range(a-1,1,-1):
resultado = resultado * i
return resultado
# 6. Crea una función que dados dos números mostrará todos los números que hay entre ellos.
def contador(a,b):
for i in range(a+1,b):
print(i)
i+=1 |
### Scope ###
## Age ##
# Find the average age, for all and gender
## Charges ##
# Average charge, for all and gender
## Smoking ##
# Find ratio of smokers in genders
# Find ratio of smokers with low, normal and high BMI
# Find ratio of smokers for people with and without kids
# Average price increanse for smokers vs non-smokers
## Regions ##
# Find ratio between regions
# Find price difference between regions
# Possible reason for higher, lower price in certain region
## Children ##
# Ratio of having kids vs not
# Average price increase of 1 child
# Average amount of kids in segment 'having kids'
## BMI ##
# Average BMI
# Average price increase for high BMI
# Ratio of BMI low, normal, high
import pandas as pd
insurance_data = pd.read_csv('insurance.csv')
## Age ##
#Average age, for all and gender
avg_age = insurance_data['age'].mean()
#prints 39.2
sum_f_age = 0
num_of_females = 0
if insurance_data['sex'] == 'female':
sum_f_age += int(insurance_data['age'])
num_of_females += 1
avg_age_female = sum_f_age / num_of_females
print(avg_age_female)
## Charges ##
# Average charge, for all and gender
avg_charge = insurance_data['charges'].mean()
## Smoking ##
# Find ratio of smokers in genders
# Find ratio of smokers with low, normal and high BMI
# Find ratio of smokers for people with and without kids
# Average price increanse for smokers vs non-smokers
## Regions ##
# Find ratio between regions
# Find price difference between regions
# Possible reason for higher, lower price in certain region
## Children ##
# Ratio of having kids vs not
# Average price increase of 1 child
# Average amount of kids in segment 'having kids'
## BMI ##
# Average BMI
# Average price increase for high BMI
# Ratio of BMI low, normal, high
|
r = float(input())
area = 3.1416 * r * r
print(area) |
'''
494. Target Sum [Medium]
You are given a list of non-negative integers,
a1, a2, ..., an, and a target, S.
Now you have 2 symbols + and -.
For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
[Method 1]: DP
该问题可以转换为 416.Partition Equal Subset Sum 问题,从而使用 0-1 背包的方法来求解。
可以将这组数看成两部分,P 和 N,其中 P 使用正号,N 使用负号,有以下推导:
sum(P) - sum(N) = target
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
2 * sum(P) = target + sum(nums)
因此只要找到一个子集,令它们都取正号,并且和等于 (target + sum(nums))//2,就证明存在解。
[Time]: O(n + n*cap) = O(n*cap), N为nums的元素个数,cap为(S+Sum) // 2;
[Space]: O(cap+1)
Runtime: 76 ms, faster than 98.69% of Python3 online submissions for Target Sum.
Memory Usage: 13.8 MB, less than 58.33% of Python3 online submissions for Target Sum.
'''
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
Sum = sum(nums)
if S > Sum or (S+Sum) % 2: return 0
cap = (S+Sum) // 2
dp = [0] * (cap+1)
dp[0] = 1
for num in nums:
for j in range(cap, num-1, -1):
dp[j] = dp[j] + dp[j-num]
return dp[cap]
'''
[Metho 2]: DFS
利用dfs深度优先搜索
设置一个哈希表(字典),键是一个元祖,元祖第一位是目前的和,第二位是目前的位数。
值是这个元祖推导到最后能有多少个解。
例如d[(4,5)] = 1 代表已经读了前4位的时,正好有一个解符合条件(那么在这个例子中符合条件的S就是5),
然后倒导d([3,5]) = 2 ......(在这种情况下,第4位是0,总共就4位)
初始化节点为(0,0),代表已经读了0位,现在和为0。
开始深度优先搜索,i为0时表示还未开始读,当i比len(nums)小,说明可以深入。
为了避免重复运算,要看当前节点是否在d里已经出现过。
每次深入的结果,就是d[(i, cur)] = dfs(cur + nums[i], i + 1, d) + dfs(cur - nums[i], i + 1, d)。
意思就是当前节点推导到最后有多少个可能性呢?
这个节点再读取一位,要么是加上这一位,要么是减掉这一位,所以这个节点的可能性就是对加上下一位的可能性与减掉下一位的可能性之和。
当深入到最后一位时,再深入就超了位数限制了,此时可以直接判断这个节点的和(即元祖的第二位)是否等于需要的S。
The get() method is used to avoid such situations.
This method returns the value for the given key, if present in the dictionary.
If not, then it will return None (if get() is used with only one argument).
d.get((i, cur), int(cur == S),若满足cur == S则返回1,否则返回0。
因为dfs可能遍历到重复节点,所以return一行写作d.get((i, cur), int(cur == S))。
如果是重复节点直接返回字典里对应值就完事儿
[Time]: O(2^n + 2^(n-1) + ... + 2^0) = O(2^n). Size of recursion tree will be 2^n, n refers to the size of nums array.
[Space]:O(n). The depth of the recursion tree can go upto n.
Runtime: 560 ms, faster than 15.16% of Python3 online submissions for Target Sum.
Memory Usage: 14.6 MB, less than 50.00% of Python3 online submissions for Target Sum.
'''
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
d = {}
def dfs(cur, i, d):
if i < len(nums) and (cur, i) not in d: # 搜索周围节点
d[(cur, i)] = dfs(cur + nums[i], i + 1, d) + dfs(cur - nums[i],i + 1, d)
return d.get((cur, i), int(cur == S))
return dfs(0, 0, d)
'''
#or:
dfs遍历所有可能结果,以当前位置 i 和当前总和 cur 为根节点,以下一位数字的加减为邻域扩散搜索
利用 d 构造记忆,以便剪枝(搜索过程中遇到相同位置和相同cur值时返回值应该相同)
dfs中 d 参数传的是引用,所以只有第一次会采用默认值 {}
'''
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
def dfs(cur, i, d = {}):
if i < len(nums) and (i, cur) not in d: # 搜索周围节点
d[(i, cur)] = dfs(cur + nums[i], i + 1) + dfs(cur - nums[i], i + 1)
return d.get((i, cur), int(cur == S))
return dfs(0, 0)
|
'''
面试题26. 树的子结构
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
例如:
给定的树 A:
3
/ \
4 5
/ \
1 2
给定的树 B:
4
/
1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1]
输出:false
示例 2:
输入:A = [3,4,5,1,2], B = [4,1]
输出:true
限制:
0 <= 节点个数 <= 10000
[前序遍历+递归]
首先要遍历A找出与B根节点一样值的节点R,即找到入口
然后递归判断树A中以R为根节点的子树是否包含和B一样的结构
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
res = False
if A and B:
if A.val == B.val:
res = self.isSubTree(A, B)
if not res:
res = self.isSubStructure(A.left, B)
if not res:
res = self.isSubStructure(A.right, B)
return res
def isSubTree(self, A, B):
if not B: return True
if not A or A.val != B.val: return False
return self.isSubTree(A.left, B.left) and self.isSubTree(A.right, B.right)
|
'''
地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。
一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 k 的格子。
请问该机器人能够达到多少个格子?
样例1
输入:k=7, m=4, n=5
输出:20
样例2
输入:k=18, m=40, n=40
输出:1484
解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
注意:
0<=m<=50
0<=n<=50
0<=k<=100
[Method 1]: Backtracking
从[0,0]开始,先向右递归再向下递归,
用一个一维数组visited来标记已经走过了的格子。
最终走完全部格子后返回count。
'''
class Solution(object):
def movingCount(self, threshold, rows, cols):
"""
:type threshold: int
:type rows: int
:type cols: int
:rtype: int
"""
if not threshold:
return 1
if not rows or not cols:
return 0
self.visited = [0]*rows*cols
self.count = 0
def helper(i,j):
if i%10 + i//10 + j%10 + j//10 <= threshold and not self.visited[i*cols + j]:
self.visited[i*cols + j] = 1
self.count += 1
if 0 <= i < rows and 0 <= j + 1 < cols:
helper(i,j+1)
if 0 <= i+1 < rows and 0 <= j < cols:
helper(i+1,j)
helper(0,0)
return self.count
#Or:
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if threshold < 0 or rows <= 0 or cols <= 0: return 0
visited = [[0 for _ in range(cols)] for _ in range(rows)]
return self.count(threshold, cols, rows, 0 ,0 ,visited)
def count(self,threshold, cols, rows, i , j ,visited):
if i >= rows or j >= cols or visited[i][j] == 1 or threshold < sum(map(int,str(i)+str(j))): return 0
visited[i][j] = 0
return 1 + self.count(threshold, cols, rows, i + 1 , j ,visited) + self.count(threshold, cols, rows, i , j + 1,visited)
|
'''
【剑指offer】
在一个长度为n的数组里的所有数字都在0到n-1的范围内。
数组中某些数字是重复的,但不知道有几个数字是重复的。
也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
[Method 1]: 抽屉原理(桶排序)
因为原数组包含的是从0到n-1的数,为了处理0,先把原数组每个数+1,
然后遍历每个数,把每个数(其绝对值-1)看成是一个index,把该index的数取反,
表示该index的数是存在的,
因为只需要输出第一个重复的数字,
则当我们遇到该index的数为负时,就可以直接输出其idx,即为重复的数字,并返回True。
否则遍历完后返回False。
'''
# python 2.7.3
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
for i in xrange(len(numbers)):
numbers[i] += 1
for i in xrange(len(numbers)):
idx = abs(numbers[i]) - 1
if numbers[idx] < 0:
duplication[0] = idx
return True
numbers[idx] = - numbers[idx]
return False
if __name__ == '__main__':
sol = Solution()
duplication = [False]
s = sol.duplicate([2,3,1,0,2,5,3],duplication)
print(s)
print(duplication)
'''
拓展:如果要求输出所有重复的数组成的list,
和未出现的数字list:
仍然是把数字先加1避免处理0不好取反的情况,
然后把每个数(绝对值-1)看成是数组下标,
把对应的数取反,
遍历时当当前数为负,则说明当前idx重复出现了,加入duplication这个set中,
最后再遍历一次,把不在duplication的为正的数的index加入到missing中。
'''
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到所有重复的一个值加入到duplication
# 并且找到missing numbers加入到missing
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
for i in range(len(numbers)):
numbers[i] += 1
print(numbers)
for i in range(len(numbers)):
idx = abs(numbers[i]) - 1
if numbers[idx] < 0:
duplication.add(idx)
numbers[idx] = - numbers[idx]
missing = [idx for idx in range(len(numbers)) if numbers[idx] > 0 and idx not in duplication]
print('missing numbers: ',missing)
return missing != None
if __name__ == '__main__':
sol = Solution()
duplication = set()
s = sol.duplicate([2,3,1,0,2,5,3],duplication)
print(s)
print('Repeated numbers: ',duplication)
'''
[3, 4, 2, 1, 3, 6, 4]
missing numbers: [4, 6]
True
Repeated numbers: {2, 3}
'''
'''
[Method 2]: 交换排序
利用元素数字都在0到n-1的范围内的特点,若不存在重复数字,
则排序后的数字就在与其相同的索引值的位置,即数字i在第i个位置。
遍历的过程中寻找位置和元素不相同的值,并进行交换排序,
在此过程中如果有 numbers[i] == numbers[numbers[i]], 则找到重复数字,输出返回。
时间复杂度O(n),空间复杂度O(1)。
'''
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
for i in range(len(numbers)):
while i != numbers[i]:
idx = numbers[i]
if numbers[i] == numbers[idx]:
duplication[0] = numbers[i]
return True
numbers[i], numbers[idx] = numbers[idx], numbers[i]
return False
if __name__ == '__main__':
sol = Solution()
duplication = [False]
s = sol.duplicate([2,3,1,0,2,5,3],duplication)
print(s)
print(duplication)
'''
要求不mutate原数组,则和leetcode的本题思路相同,
即用二分法(种方法无法保证找出所有的重复数字,需要在解决前了解需求。)或者快慢指针
[Method 3]: 二分法(分治,抽屉原理) O(nlogn)
这道题目主要应用了抽屉原理和分治的思想。
抽屉原理:n+1 个苹果放在 n 个抽屉里,那么至少有一个抽屉中会放两个苹果。
用在这个题目中就是,一共有 n+1 个数,每个数的取值范围是1到n,所以至少会有一个数出现两次。
然后我们采用分治的思想,将每个数的取值的区间[1, n]划分成[1, n/2]和[n/2+1, n]两个子区间,
然后分别统计两个区间中数的个数。
注意这里的区间是指 数的取值范围,而不是 数组下标。
划分之后,左右两个区间里一定至少存在一个区间,区间中数的个数大于区间长度。
这个可以用反证法来说明:如果两个区间中数的个数都小于等于区间长度,
那么整个区间中数的个数就小于等于n,和有n+1个数矛盾。
因此我们可以把问题划归到左右两个子区间中的一个,而且由于区间中数的个数大于区间长度,
根据抽屉原理,在这个子区间中一定存在某个数出现了两次。
依次类推,每次我们可以把区间长度缩小一半,直到区间长度为1时,我们就找到了答案。
复杂度分析
时间复杂度:每次会将区间长度缩小一半,一共会缩小 O(logn) 次。
每次统计两个子区间中的数时需要遍历整个数组,时间复杂度是 O(n)。
所以总时间复杂度是 O(nlogn)。
空间复杂度:代码中没有用到额外的数组,所以额外的空间复杂度是 O(1)。
'''
|
'''
Passing Parameters In URLs
'''
import requests
# http get request
payload = {'key1': 'value1 ', 'key2': 'value2 '}
r1 = requests.get('https://httpbin.org/get', params=payload)
print(r1.url) # https://httpbin.org/get?key1=value1+&key2=value2+
# http post request:
payload = {'key1': 'value1 ', 'key2': ['value2', 'value3']}
r2 = requests.post('https://httpbin.org/post', params=payload)
print(r2.url) # https://httpbin.org/post?key1=value1+&key2=value2&key2=value3
'''
If we want to send some form-encoded data — much like an HTML form.
To do this, simply pass a dictionary to the data argument.
Our dictionary of data will automatically be form-encoded when the request is made:
'''
payload = {'key1': 'value1 ', 'key2': ['value2', 'value3']}
r = requests.post("https://httpbin.org/post", data=payload)
print(r.text)
'''
"form": {
"key1": "value1 ",
"key2": [
"value2",
"value3"
]
}, ...
The data argument can also have multiple values for each key.
This can be done by making data either a list of tuples or a dictionary with lists as values.
This is particularly useful when the form has multiple elements that use the same key:
'''
payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
payload_dict = {'key1': ['value1', 'value2']}
r2 = requests.post('https://httpbin.org/post', data=payload_dict)
print(r1.text)
'''
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
'''
print(r1.text == r2.text) # True
'''
https://requests.readthedocs.io/en/master/user/quickstart/#passing-parameters-in-urls
'''
|
'''
字节跳动面试题,
同样的条件,给出一个target,看在数组里面小于等于k的元素个数有多少个。
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
k = 16,
Output: 16
[解析]
因为每行每列都是排好序的,所以对于一个位于非边界的元素,比它小的有向上向左两种方向,
比它大的有向右向下两种方向,比较起来比较麻烦。但是对于边界元素,如最后一行的第一个元素,
要找比它小的元素只有往上遍历,找比它大的只能往右遍历,所以这样下来worst case的时间复杂度也就(m + n),
即最多需要遍历 m + n 个元素。
'''
def searchMatrix(matrix, target):
if not matrix or not matrix[0]: return None
rows = len(matrix)
cols = len(matrix[0])
row, col = rows-1, 0
count = 0
while row >= 0 and col < cols:
if target >= matrix[row][col]:
count += row + 1
col += 1
else:
row -= 1
return count
if __name__ == '__main__':
matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
print(searchMatrix(matrix,16)) #16
matrix = [[1,2,3,3,4],[2,2,3,4,5],[3,3,3,5,8]]
print(searchMatrix(matrix,3)) #10
|
'''
543. Diameter of Binary Tree [Easy]
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
[Method 1]: Recursion
实际上有可能并不包含根节点,所以还是需要通过设置一个全局变量来记录最大路径长度,
每次递归都要通过比较来更新这个全局变量,最终返回它。
时间复杂度:O(N),每个节点只访问一次。
空间复杂度:O(N),深度优先搜索的栈开销。
Runtime: 48 ms, faster than 71.95% of Python3 online submissions for Diameter of Binary Tree.
Memory Usage: 14.4 MB, less than 100.00% of Python3 online submissions for Diameter of Binary Tree.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
#全局变量,记录最长路径的节点个数
self.Max = 1
if not root or (not root.left and not root.right): return 0
self.max_depth(root)
#减1是因为返回的值是按edge计算的
return self.Max - 1
#返回的是该节点的最大深度,按路径中的节点个数算
def max_depth(self, root):
if not root:
return 0
L = self.max_depth(root.left)
R = self.max_depth(root.right)
self.Max = max(self.Max,L+R+1)
return 1 + max(L,R)
#Or:
class Solution(object):
def diameterOfBinaryTree(self, root):
self.ans = 1
def depth(node):
if not node: return 0
L = depth(node.left)
R = depth(node.right)
self.ans = max(self.ans, L+R+1)
return max(L, R) + 1
depth(root)
return self.ans - 1
|
'''
Method 1: Bit operation #O(1)
If n is the power of two:
n = 2 ^ 0 = 1 = 0b0000...00000001, and (n - 1) = 0 = 0b0000...0000.
n = 2 ^ 1 = 2 = 0b0000...00000010, and (n - 1) = 1 = 0b0000...0001.
n = 2 ^ 2 = 4 = 0b0000...00000100, and (n - 1) = 3 = 0b0000...0011.
n = 2 ^ 3 = 8 = 0b0000...00001000, and (n - 1) = 7 = 0b0000...0111.
we have n & (n-1) == 0b0000...0000 == 0
Otherwise, n & (n-1) != 0.
For example, n =14 = 0b0000...1110, and (n - 1) = 13 = 0b0000...1101.
'''
def isPowerOfTwo(n):
return n > 0 and (n & (n-1)) == 0
'''
Method 2: Iteration #O(lgn)
Runtime: 12 ms, faster than 95.63% of Python online submissions for Power of Two.
Memory Usage: 11.7 MB, less than 100.00% of Python online submissions for Power of Two.
'''
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
if n == 1:
return True
while n%2 == 0:
n >>= 1
if n == 1:
return True
return False
#Or:
def isPowerOfTwo(n):
if (n == 0):
return False
while (n%2 == 0):
n/=2
return n == 1
'''
Method 3: Recursion
O(lgn)
'''
def isPowerOfTwo(n):
return n > 0 and (n == 1 or (n%2 == 0 and isPowerOfTwo(n//2)))
'''
Method 4: Math derivation O(1)
Because the range of an integer = -2147483648 (-2^31) ~ 2147483647 (2^31-1),
the max possible power of two = 2^30 = 1073741824.
(1) If n is the power of two, let n = 2^k, where k is an integer.
We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0.
(2) If n is not the power of two, let n = j*(2^k), where k is an integer and j is an odd number.
We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.
return n > 0 && (1073741824 % n == 0);
Method 5: Bit count O(1)
Very intuitive. If n is the power of 2, the bit count of n is 1.
Note that 0b1000...000 is -2147483648, which is not the power of two, but the bit count is 1.
return n > 0 && Integer.bitCount(n) == 1;
The time complexity of bitCount() can be done by a fixed number of operations.
More info in https://stackoverflow.com/questions/109023.
Method 6: Look-up table
There are only 31 numbers in total for an 32-bit integer.
return new HashSet<>(Arrays.asList(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824)).contains(n);
'''
|
'''
100. Same Tree
> 类型:DFSF分制
> Time Complexity O(N)
> Space Complexity O(h)
Runtime: 32 ms, faster than 92.27% of Python3 online submissions for Same Tree.
Memory Usage: 13.9 MB, less than 5.72% of Python3 online submissions for Same Tree.
'''
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return False
#Or:
def isSameTree(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
#Return True only if p and q are both None else return False(because it's reference comparison)
return p is q
# 前序遍历DFS with stack
def isSameTree2(self, p, q):
stack = [(p, q)]
while stack:
node1, node2 = stack.pop()
if not node1 and not node2:
continue
elif None in [node1, node2]:
return False
else:
if node1.val != node2.val:
return False
stack.append((node1.right, node2.right))
stack.append((node1.left, node2.left))
return True
#BFS with queue
from collections import deque
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
queue = deque()
queue.append((p,q))
while queue:
node1,node2 = queue.popleft()
if not node1 and not node2:
continue
elif None in (node1,node2):
return False
else:
if node1.val != node2.val:
return False
queue.append((node1.left,node2.left))
queue.append((node1.right,node2.right))
return True
|
#0-1 背包问题
def knapsack1(weight, value, capacity):
'''
>>> knapsack1([], [], 10)
0
>>> knapsack1([3], [10], 0)
0
>>> knapsack1([4], [15], 4)
15
>>> knapsack1([4], [15], 10)
15
>>> knapsack1([4], [15], 3)
0
>>> weight = [1, 2, 3, 8, 7, 4]
>>> value = [20, 5, 10, 40, 15, 25]
>>> capacity = 10
>>> knapsack1(weight, value, capacity)
60
>>> weight = [10, 20, 30]
>>> value = [60, 100, 120]
>>> capacity = 50
>>> knapsack1(weight, value, capacity)
220
'''
#winpty python -m doctest knapsack_problem_0_1.py
n = len(weight)
if n < 1 or capacity < 1: return 0
dp = [0]*(capacity + 1)
for item in range(n):
for j in range(capacity, weight[item]-1, -1):
dp[j] = max(dp[j], dp[j - weight[item]] + value[item])
#print(dp)
return dp[capacity]
#0-1 硬币找零问题
def coinChange1(coins, amount):
'''
>>> coinChange1([2], 1)
-1
>>> coins = [2, 3, 5]
>>> coinChange1(coins, 10)
3
>>> coinChange1(coins, 11)
-1
>>> coinChange1(coins, 0)
-1
>>> coins = [2, 1, 2, 3, 5]
>>> coinChange1(coins, 10)
3
>>> coinChange1(coins, 11)
4
>>> coinChange1(coins, 5)
1
>>> coinChange1(coins, 6)
2
'''
n = len(coins)
if n < 1 or amount < 1: return -1
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for j in range(amount, coin-1, -1):
dp[j] = min(dp[j], dp[j-coin] + 1)
print(dp)
return dp[amount] if dp[amount] != float('inf') else -1
|
'''
---------------------------------------------
70.Climbing Stairs [Easy]
---------------------------------------------
DP (Bottom Up)
Time: O(n), Space: O(n)
'''
class Solution:
def climbStairs(self, n: int) -> int:
if n < 2: return n
dp = [0]*n
dp[0], dp[1] = 1, 2
for i in range(2, n):
dp[i] = dp[i-1] + dp[i-2]
return dp[n-1]
'''
爬楼梯变形:给定n,找到不同将n写成1,3,4相加的问题(顺序matters)
或理解为:仍然是爬楼梯,一次可以爬1步,3步或者4步
[分析]
关键还是找到公式dp[i] = dp[i-1] + dp[i-3] + dp[i-4],
其实可以想成第一步是1有多少种选择,加上第一步是3的选择数,再加第一步是4的可能组合。
'''
def climb_stairs(n):
dp = [1, 1, 2, 4]
if n > 4:
dp += [0]*(n-4)
for i in range(4, n):
dp[i] = dp[i-1] + dp[i-3] + dp[i-4]
return dp[n-1]
'''
|
'''
26. Remove Duplicates from Sorted Array [Easy]
Given a sorted array nums, remove the duplicates in-place
such that each element appear only once and return the new length.
Do not allocate extra space for another array,
you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.(也就是说,修改后的nums的前returned length的值都为排好序的不重复的数字。)
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5,
with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference,
which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
'''
'''
O(n^2)
Runtime: 104 ms, faster than 40.72% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.4 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
'''
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if nums == []:
return 0
count = 1
i = len(nums) - 1
while i > 0:
if nums[i] == nums[i-1]:
#worst case: O(n)
nums.pop(i)
else:
count += 1
i -= 1
return count
'''
Two Pointers
O(n)
[Analysis]
in-place mutation of the first non-duplicate elements
Since the array is already sorted, we can keep two pointers i and j, where j is the slow-runner while i is the fast-runner.
As long as nums[i] = nums[j], we increment i to skip the duplicate.
When we encounter nums[i] != nums[j], the duplicate run has ended so we must copy its value to nums[j + 1].
j is then incremented and we repeat the same process again until i reaches the end of array.
Runtime: 96 ms, faster than 76.89% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.5 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
[思路]
非末端pop的删除操作会导致O(n)的时间复杂度,又要求O(1的)空间,
所以我们可以把每种数字的第一个数的index(初始为0)记下来,为newTail,然后从数组的第二个数开始与这个数(即A[newTail])比较,
看是否相等。如果不等,我们更新这个index的下一位(即1),并使其值为第二种数字,如此for循环到最后一个元素。
最终返回最后一个不重复数字的index加上1,即为整个数组里不重复数字的总数。
e.g.
[1,1,1,2,3,3,4,5,5,6,6,6,7,7,7] ==>
[1, 2, 3, 4, 5, 6, 7, 5, 5, 6, 6, 6, 7, 7, 7]
'''
class Solution:
def removeDuplicates(self, A):
if not A:
return 0
#记录了每个不同数字的第一个数的index,最后加1就为不重复数字的总数
newTail = 0
for i in range(1, len(A)):
if A[i] != A[newTail]:
newTail += 1
A[newTail] = A[i]
return newTail + 1
'''
O(n)
Runtime: 88 ms, faster than 97.92% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.9 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted Array.
'''
from collections import OrderedDict
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums[:] = OrderedDict.fromkeys(nums)
'''
[Note]
1.Using nums[:] will not allocate new memory, it's in-place mutation,
so it will change the values already used by nums
rather than just reassigning the name nums to the newly created list.
nums[:]只是以in-place的方式修改其元素,但是nums = nums[:]则是重新赋值
Test this in python interpreter:
***nums = nums[:]是重新赋值***
>>> a = [1,2,3,4,5]
>>> b = a
>>> b
[1, 2, 3, 4, 5]
>>> a = a[:]
>>> a.pop()
5
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4, 5]
>>>
***nums[:]只是以in-place的方式修改其元素***
>>> b
[1, 2, 3, 4, 5]
>>> c = b
>>> c
[1, 2, 3, 4, 5]
>>> b[:] = [1,2,3]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>>
2.OrderedDict will maintain the sorted order of nums while set() wouldn't
'''
|
import unittest
from circles import circle_area
from math import pi
'''
test command:
winpty python -m unittest test_circles
or:
winpty python -m unittest # it will search for tests and run them
'''
class TestCircleArea(unittest.TestCase):
def setUp(self):
self._f = circle_area
def test_area(self):
# Test areas with radius >= 0
'''
For the self.assertAlmostEqual method(difference within 10e-7)
or the self.assertEqual,
the first argument should be the output of the function
while the second should be the correct answer
'''
r = self._f(1)
self.assertAlmostEqual(r, pi)
r = self._f(0)
self.assertAlmostEqual(r, 0)
r = self._f(2.1)
self.assertAlmostEqual(r, pi * 2.1**2)
def test_values(self):
# Make sure value errors are raised when necessary(check improper input values)
'''
For the self.assertRaises method,
the first argument should be the type of error that should be raised;
the second should be the function and
the third is the argument to the function
'''
self.assertRaises(ValueError, self._f, -2)
def test_types(self):
# Make sure type errors are raised when the input is not real number
self.assertRaises(TypeError, self._f, True)
self.assertRaises(TypeError, self._f, 3+5j)
self.assertRaises(TypeError, self._f, 'radius')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.