text stringlengths 37 1.41M |
|---|
import unittest
from temp_converter import convert_celsius_to_fahrenheit
class TempConverterTest(unittest.TestCase):
# convert temperature from celsius to F
# test data type input
def test_celsius_is_converted_to_fahrenheit(self):
"""
F = C * 9/5 +32
"""
actual = convert_celsius_to_fahrenheit(10)
expected = 50
self.assertEqual(actual, expected, 'Celsius should convert to crrect Fahrenheit value')
self.assertEqual(convert_celsius_to_fahrenheit(20), 68, 'Celsius should convert to crrect Fahrenheit value') |
from Prac08.taxi import Taxi, UnreliableCar, SilverServiceTaxi
def main():
# Prius = Taxi("Prius", 100)
# print(Prius)
# Prius.drive(40)
# Prius.current_fare_distance = 100
# print(Prius)
#
# dodge = UnreliableCar('dodge', 100)
# print(dodge)
# if dodge.drive(130):
# print('It worked')
# else:
# print("It failed")
# print(dodge)
#
# taxi = SilverServiceTaxi('taxi',200,4)
# taxi.drive(10)
# print(taxi)
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2),
SilverServiceTaxi("Hummer", 200, 4)]
bill = 0
menu_choice = get_menu()
while menu_choice != "q":
if menu_choice == "c":
taxi_choice = run_taxi_choice(taxis)
print("Bill to date: ${:.2f}".format(bill))
menu_choice = get_menu()
elif menu_choice == "d":
bill = run_drive(bill, taxi_choice)
menu_choice = get_menu()
print("Total trip cost: ${:.2f}".format(bill))
print("Taxis are now:")
counter = 0
for taxi in taxis:
print(counter, "-", taxis[counter])
counter += 1
def get_menu():
menuOptions = ['q', 'c', 'd']
print("Let's drive!")
menu_choice = input("q)uit, c)hoose taxi, d)rive")
while menu_choice not in menuOptions:
print("incorrect answer try again")
menu_choice = input("q)uit, c)hoose taxi, d)rive")
return menu_choice
def run_taxi_choice(taxis):
counter = 0
print("Taxis available: ")
for taxi in taxis:
print(counter, "-", taxis[counter])
counter += 1
choose_taxi = int(input("Choose taxi:"))
taxi_choice = taxis[choose_taxi]
return taxi_choice
def run_drive(bill, taxi_choice):
distance = int(input("Drive how far? "))
taxi_choice.drive(distance)
fare = taxi_choice.get_fare()
bill += fare
print(
"Your {} trip cost you ${:.2f}".format(taxi_choice.name, fare))
print("Bill to date: ${:.2f}".format(bill))
return bill
main()
|
import turtle
t = turtle.Turtle()
# screen
s = turtle.Screen()
s.bgcolor("black")
t.pencolor("white")
t.speed(0)
for n in range(73):
for i in range(4):
t.forward(80)
t.left(90)
t.left(5)
t.hideturtle()
turtle.done()
|
initial_money = 2000
initial_price = 100
age = 20
hungry = (age / 100) * 100
price = initial_price
while hungry < (85/100) * 100:
print("Buy an ice cream")
print("Ice price:", price)
print ("Hungry is:", hungry)
price = price * (1 + 20/100)
hungry = hungry + age
print("Actual hungry:", hungry)
if hungry >= (85/100) * 100:
print("I don´t need to eat more") |
def aptitude():
age = int(input("How old are you?: "))
experience = int(input("How long were you at your previous job, in months?: "))
score = int(input("What did you score in the competency test?: "))
competence = (age + experience) * score
if competence > 200:
print("Candidate is competent enough")
if competence < 200:
print("Candidate is not competent")
aptitude()
|
"""
修改图片后缀名
"""
import os
base_path = "G:\\FaceImg\image\\{}"
filename = "G:\\FaceImg\\"
file = os.listdir(filename)
count = 0
for i in file:
count +=1
names = str(count) + '.jpg'
filenames = base_path.format(names)
filenamess = "G:\\FaceImg\\{}".format(i)
print(filenamess)
with open(filenamess,'rb') as f1:
with open(filenames, 'wb') as f2:
while True:
s_bate = f1.read(1024)
if s_bate == b'':
break
f2.write(s_bate)
|
import itertools
# %% Manually Consuming an Iterator
items = [1, 2, 3]
it = iter(items) # Invokes items.__iter__()
while True:
n = next(it, None) # Invokes items.__next__()
if n == None:
break
print(n)
# %% Iterating in Reverse
a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[a for a in reversed(a)] # Invokes __reversed__()
# %% Taking a Slice of an Iterator
for x in itertools.islice(iter(a), 1, 5):
print(x)
# %% Permutations
items = ['a', 'b', 'c']
[p for p in itertools.permutations(items)]
# %%
[c for c in itertools.combinations(items, 2)]
# %%
[c for c in itertools.combinations_with_replacement(items, 2)]
# %% Index-Value Pairs
my_list = ['a', 'b', 'c']
{idx:val for idx, val in enumerate(my_list)}
# %% Iterating Over Multiple Sequences Simultaneously
xpts = [1, 5, 4, 2, 10, 7]
ypts = [101, 78, 37, 15, 62, 99]
#[(x, y) for x, y in zip(xpts, ypts)]
list(zip(xpts, ypts))
# %% zip_longest
[(x, y) for x, y in itertools.zip_longest(xpts, [1] * 3 + ypts, fillvalue=float('nan'))]
# %% Efficient concatenation
[x for x in itertools.chain(xpts, ypts)]
# %% Merge sorted
import heapq
a = [1, 4, 7, 10]
b = [2, 5, 7, 11]
for c in heapq.merge(a, b):
print(c)
# %%
|
"""This class represents the game state of a 2048 game in progress, intentionally made as general as
possible to accomodate variations on the game."""
from copy import deepcopy
from random import choice
import numpy as np
import make_move
class Board:
"""A 2048 game board with tiles on it."""
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
def __init__(self, width=4, height=4, board=None):
"""Initializes a 2048 game board of the given width and height. If board is not None, it is
interpreted as a list of rows (of shape (height, width)) that contain numerical values
(which should probably be powers of 2, but perhaps wouldn't need to be), interspersed with
zeroes to denote empty squares.
"""
if width <= 1 or height <= 1:
raise ValueError("Need 2+ rows and columns, not shape ({}, {})".format(height, width))
if board is None:
self.board = np.zeros((height, width), dtype=np.int)
else:
self.board = np.array(board, dtype=np.int)
if board.shape != (height, width):
raise ValueError("Expected board of shape" +
" ({}, {}), not {}".format(height, width, board.shape))
self.height, self.width = self.board.shape
def __repr__(self):
return "Board({}, {}, \n{})".format(self.width, self.height, repr(self.board))
def __str__(self):
return '\n'.join(['\t'.join(map(str, row)) for row in self.board])
def game_status(self, goal=2048):
"""Determines if the game has ended. If the game is continuing, returns 0. Otherwise,
returns -1 for a loss (defined as no valid moves) and 1 for a win (defined as any position
with the goal tile or a larger one on the board)."""
if (self.board >= goal).any(): # we have a winner!
return 1
# if the board is filled, you can only keep playing if you have a match to make
if (self.board != 0).all():
# take differences and check for zeros
if (np.diff(self.board) == 0).any() or (np.diff(self.board, axis=0) == 0).any():
# we have a difference of zero, so there is a possible match
return 0 # the game continues
else: # the game ends, no moves: you lose
return -1
else:
return 0 # there are empty squares, so there must be possible moves
def get_tile(self, x, y):
"""Returns the tile at (x, y) (where 0 means nothing is there), and the coordinate system
has (0, 0) at the lower-left corner."""
return self.board[self.height-y-1][self.width-x-1]
def set_tile(self, x, y, num=2, force_replace=False):
"""Adds a tile with the given numerical value at the given x-y coordinate, in a coordinate system
where (0, 0) is the lower-left corner and x is horizontal. If force_replace is True, no
error will be raised if the tile is already occupied: if it is False, a ValueError will
occur.
"""
if self.get_tile(x, y) != 0 and not force_replace:
raise ValueError("Tried to add a tile to a non-empty square!")
else:
self.board[self.height-y-1][self.width-x-1] = num
def can_combine(self, tile1, tile2):
"""Determines if tile1 and tile2 can match or merge together. In standard 2048, this is
simply equality, with an added check so that 0 never combines."""
if tile1 == 0 or tile2 == 0:
return False
return tile1 == tile2
def combine(self, tile1, tile2):
"""Adds together two tiles and returns the numerical value of the new tile. Override this to
change how tiles are added together. Uses the can_combine method to check for the
possibility to match: in standard 2048, that is simply equality, although it will never let
0 combine."""
if self.can_combine(tile1, tile2):
return tile1 + tile2
else:
raise ValueError("{} and {} cannot combine!".format(tile1, tile2))
def rotate(self, num_clockwise_turns=1):
"""Rotates the board with the given amount of clockwise turns, so 4 turns does nothing and 3
turns is one counter-clockwise turn. Example turning once:
- - 2 4 - - - -
- 2 16 8 - 4 - 2
- - 2 4 ==> 2 2 16 2
- 4 2 32 32 4 8 4
If necessary, width and height will change to reflect the new board.
Additionally, this method accepts negative numbers and will do the specified amount of
counter-clockwise turns if the number is negative.
"""
# if you're interested, the way to do this is by transposing and then flipping rows
# but numpy already has this, so why bother?
# this method rotates CCW, so do the negative number of turns..
self.board = np.rot90(self.board, -num_clockwise_turns)
self.height, self.width = self.board.shape
def __collapse_row(self, row):
"""Collapses the numpy array row in-place leftwards according to the logic of 2048: e.g.,
- 16 4 4 ==> 16 8 - -
Returns None.
Uses a Cython backend for efficiency.
"""
make_move.collapse_row(row)
def __move_left(self):
"""Collapses the board leftwards. This method is private and outside users should use
make_move, which just rotates the board, does this, and rotates back. Returns None.
A note on performance: this uses a Cython backend for speed, as this bottlenecks most AI
training."""
make_move.move_left(self.board)
def make_move(self, direction):
"""Shifts the board in the given direction, and merges any tiles that can be merged in the given
direction. May not do anything. Direction is a number 0-3 representing up, right, down, and
left respectively (clockwise), which can be replaced by the constant variables UP, DOWN,
LEFT, and RIGHT from this class. Returns 1 if the given move does something, and 0
otherwise.
"""
# hash to check for equality, because we need to test if the move did anything but copying
# is slow
old_board_hash = hash(self.board.tostring())
# rotate until what was the desired direction is facing left, collapse leftwards, and then
# rotate back
self.rotate(3 - direction) # clockwise numbering jells nicely with rotation
self.__move_left() # do the actual work of collapsing
self.rotate(direction - 3) # undo whatever was done previously
new_board_hash = hash(self.board.tostring())
if new_board_hash == old_board_hash: # same board
return 0
else:
return 1
def show_move(self, direction):
"""Returns a new tuple (board, did_change) that are a new copied Board with the given
directional move made and a 1-0 flag if the given move changed anything. It is a stateless
alternative to make_move."""
new_board = deepcopy(self)
return (new_board, new_board.make_move(direction))
def add_random_tile(self, tiles=(2, 4), weights=(9, 1)):
"""Adds a tile in a randomly chosen unoccupied position according to the given weighted selection of
tiles. If the board is full, does nothing. Returns None.
The default is how the original 2048 (gabrielcirulli.github.io/2048/) does it:
there's a 90% of getting a 2, but a 10% chance of getting a 4.
"""
unoccupied_slots = []
for x in range(self.width):
for y in range(self.height):
if self.get_tile(x, y) == 0:
unoccupied_slots.append((x, y))
if not unoccupied_slots: # nowhere to add
return None
# note: np.random.choice cannot make choices from tuples of tuples
# so we have to import the standard library's random.choice
slot_to_add = choice(unoccupied_slots)
normed_weights = [weight / sum(weights) for weight in weights]
# this one requires weighted sampling, so we use np.random.choice
# because tiles is just a list of integers
val_to_add = np.random.choice(tiles, p=normed_weights)
self.set_tile(*slot_to_add, val_to_add)
|
"""This file has a class that allows someone to play a complete 2048 game with full game history."""
import os
from random import choice
import numpy as np
from board import Board
from verboseprint import *
class Game:
"""A game of 2048."""
def __init__(self, width=4, height=4, board=None, board_obj=None, goal=2048):
"""Initializes a game with the given board. If board_obj is None, initializes a board with the given
width, height, and optional numpy array for the actual squares. If board_obj is given, uses
that instead: use this for subclasses of Board.
Goal is the desired end tile to use for checking. If this is None, will play until a loss.
"""
if board_obj is not None:
self.board = board
else:
self.board = Board(width, height, board)
self.original_board = np.copy(self.board.board) # to make history canonical
self.history = []
self.spawns = []
self.goal = goal
self.terminate_game = False
def __str__(self):
return str(self.board)
def update_history(self, spawns, move_list):
"""Given a list of spawns and moves, takes turns spawning a tile at the given location, and
making the desired move."""
for i in range(len(spawns)):
self.spawns.append(spawns[i])
self.board.set_tile(*spawns[i][0], spawns[i][1])
if i < len(move_list):
self.make_move(move_list[i])
def make_move(self, direction):
"""Direction is 0-3 clockwise from the top (0 = UP, 1 = RIGHT, etc.). Makes a move, saves it to the
history, and updates the board. Stalling moves return 0 and do not update the history; moves
that change something return 1.
"""
if direction == -1:
# -1 indicates request for termination of the game
self.terminate_game = True
return 0
if self.board.make_move(direction):
self.history.append(direction)
return 1
else:
return 0
def game_status(self):
"""Returns 0 if game is still going on, 1 for victory, and -1 for loss."""
if self.terminate_game == True:
return -1
return self.board.game_status(self.goal)
def add_random_tile(self, tiles=(2, 4), weights=(9, 1)):
"""Adds a new tile at a randomly chosen empty spot according to the given tiles and
corresponding weights. The default is the original 2048's default: 90% chance of a 2, and
10% chance of a four. Logs in history so the game can be replayed.
Does not wrap the Board's class, because this needs to be stored. Instead, manually sets a
new tile."""
unoccupied_slots = []
for x in range(self.board.width):
for y in range(self.board.height):
if self.board.get_tile(x, y) == 0:
unoccupied_slots.append((x, y))
if len(unoccupied_slots) == 0:
vprint("Tried to add tile to full board", debug=True)
return
chosen_slot = choice(unoccupied_slots)
normed_weights = [weight / sum(weights) for weight in weights]
chosen_tile = np.random.choice(tiles, p=normed_weights)
self.board.set_tile(*chosen_slot, chosen_tile)
self.spawns.append((chosen_slot, chosen_tile))
def play(self, move_generation_func, tiles=(2, 4), weights=(9, 1)):
"""Make a single move using the given move generation function, and then adds a new random
tile. Returns the current game status after the move and placement. The function takes in a
Board and returns 0-3. If the move does nothing, does not add a tile. The defaults are the
2048 default random tile placements."""
if self.make_move(move_generation_func(self.board)):
self.add_random_tile(tiles, weights)
else:
#self.add_random_tile(tiles, weights)
pass
return self.game_status()
def play_to_completion(self, move_generation_func, per_move_callback=None, tiles=(2, 4), weights=(9, 1)):
"""Given a function that takes in the current board position and returns a move, continues play
until the game is over, returning the game status. Tiles and weights get passed to
add_random_tile.
permove_callback is an optional function that is called after every move. It is used for model-training purposes.
"""
self.add_random_tile(tiles, weights)
while not self.game_status():
self.play(move_generation_func, tiles, weights)
if per_move_callback is not None:
per_move_callback()
return self.game_status
def get_all_boards(self):
"""Returns a list of Boards in order of play, from first to last."""
new_g = Game(board=self.original_board)
boards = [new_g.board]
for spawn, move in zip(self.spawns, self.history):
new_g.update_history([spawn], [move])
boards.append(new_g.board)
return boards
def print_boards(self):
"""Prints the boards in order of appearance in history."""
new_g = Game(board=self.original_board)
for spawn, move in zip(self.spawns, self.history):
new_g.update_history([spawn], [move])
print(new_g)
print('\n' + '-' * 10)
def __write_data(self, outfile):
outfile.write("{}\n".format(self.board.width))
outfile.write("{}\n".format(self.board.height))
outfile.write("{}\n".format(self.goal))
outfile.write(' '.join(map(str, list(self.original_board.flatten()))))
outfile.write('\n')
for i in range(len(self.history)):
curr_spawn = self.spawns[i]
curr_move = self.history[i]
outfile.write("{}-{} {}\n".format(*curr_spawn[0], curr_spawn[1]))
outfile.write("{}\n".format(curr_move))
# Add the final spawn after the last move made, which gets cut off, because len(self.spawns) = len(self.history) + 1
outfile.write("{}-{} {}\n".format(*self.spawns[-1][0], self.spawns[-1][1]))
def save(self, filename):
"""Saves this game to a file as a newline-separated list of WASD with info at the beginning.
"""
with open(filename, 'w+') as outfile:
self.__write_data(outfile)
def append(self, filename, sep='#'):
"""Appends this game to an already-existing file, adding `sep` in between games"""
if not os.path.isfile(filename):
self.save(filename)
return
with open(filename, 'a') as outfile:
outfile.write(sep)
self.__write_data(outfile)
@staticmethod
def open(filename):
"""Generates a Game from the given filename."""
with open(filename, 'r') as infile:
lines = list(infile)
width = int(lines[0])
height = int(lines[1])
goal = int(lines[2])
tiles = [float(x) for x in lines[3].strip().split(' ')]
tiles = np.array(tiles).reshape(height, width)
g = Game(width, height, tiles, None, goal)
spawns = []
moves = []
for i in range(4, len(lines), 2):
spawn_line = lines[i]
if i < len(lines) - 1:
move_line = lines[i+1]
spawn_pos, spawn_tile = spawn_line.split(' ')
spawn_x, spawn_y = spawn_pos.split('-')
spawns.append(((int(spawn_x), int(spawn_y)), int(spawn_tile)))
if i < len(lines) - 1:
moves.append(int(move_line))
g.update_history(spawns, moves)
return g
@staticmethod
def open_from_text(text):
"""Generates a Game object from the given string"""
lines = text.split('\n')
width = int(lines[0])
height = int(lines[1])
goal = int(lines[2])
tiles = [float(x) for x in lines[3].strip().split(' ')]
tiles = np.array(tiles).reshape(height, width)
g = Game(width, height, tiles, None, goal)
spawns = []
moves = []
for i in range(4, len(lines), 2):
spawn_line = lines[i]
if i < len(lines) - 1:
move_line = lines[i+1]
spawn_pos, spawn_tile = spawn_line.split(' ')
spawn_x, spawn_y = spawn_pos.split('-')
spawns.append(((int(spawn_x), int(spawn_y)), int(spawn_tile)))
if i < len(lines) - 1:
moves.append(int(move_line))
g.update_history(spawns, moves)
return g
@staticmethod
def open_batch(filename, sep='#'):
with open(filename, 'r') as infile:
sections = [x.strip() for x in ''.join(list(infile)).split(sep)]
g = [Game.open_from_text(s) for s in sections]
return g
def input_player(board):
return "WDSA".index(input("The board is \n{}\nWhat would you like to do? ".format(board)))
def random_play(board):
return np.random.choice(4)
|
class Animals:
'''Животные'''
interaction = "не кормить"
weight = 0 # кг
weight_max = 0 # кг
voice = "!"
emp_count = 0
weight_sum = 0
def __init__(self, name, weight):
self.name = name
self.weight += weight
Animals.emp_count += 1
Animals.weight_sum += weight
if self.weight > Animals.weight_max:
Animals.weight_max = self.weight
Animals.name_max_weight = self.name
print(f'{self.name}, {self.weight} кг')
def feed(self):
self.interaction = "покормить"
return self.interaction
class Poultry:
eggs = "none"
def collect_eggs(self):
self.eggs = "собрать яйца"
return self.eggs
class Gouse(Poultry, Animals):
'''Гусь'''
def speak(self, voice="Га-га-га"):
print("Гусь-", voice)
class Duck(Poultry, Animals):
'''Утка'''
def speak(self, voice="Га-га"):
print("Утка-", voice)
class Chicken(Poultry, Animals):
'''Курица'''
def speak(self, voice="Ко-Ко-ко"):
print("Курица-", voice)
class Sheep(Animals):
'''Овца'''
wool = "not"
def speak(self, voice="Бее"):
print("Овца-", voice)
def shearning(self):
self.wool = "Постричь овцу"
class MilkAnimals:
milk = "none"
def milk(self):
self.milk = "Подоить"
return self.milk
class Cow(MilkAnimals, Animals):
'''Корова'''
def speak(self, voice="Муу"):
print("Корова-", voice)
class Goat(MilkAnimals, Animals):
'''Коза'''
def speak(self, voice="Мее"):
print("Коза-", voice)
gouse0 = Gouse("Серый ", 6)
gouse1 = Gouse("Белый", 7)
cow0 = Cow("Манька", 500)
sheep0 = Sheep("Барашек", 90)
sheep1 = Sheep("Кудрявый", 85)
chicken0 = Chicken("Ко-ко", 1)
chicken1 = Chicken("Кукареку", 2)
goat0 = Goat("Рога", 6)
goat1 = Goat("Копыта", 7)
duck0 = Duck("Кряква", 3)
gouse0.speak()
cow0.speak()
sheep0.speak()
chicken0.speak()
goat0.speak()
duck0.speak()
print("Всего животных: %d" % Animals.emp_count)
print("Вес всех животных: %d" % Animals.weight_sum, "кг")
print(f'Самое тяжелое животное - {Animals.name_max_weight},{Animals.weight_max} кг')
|
b=[1,2,3,4,5]
print(b)
for i in range(5):
print('i is now:',i)
|
# n = raw_input("ENTER STRING\n")
n = "CAMMAC"
length = len(n)
for i in range(0, int(length/2 + 1)):
if n[i] is not n[-i - 1]: #change logic here.
break
if i < (length / 2):
print("not")
else:
print("yes") |
def interface():
while True:
print("#############################")
list=("1. KMP\n2. Modulo42\n3. AliceNBob\n4. CupsNBall\nEnter 'Q' to quit\n")
select=input(list+"Enter a program to run :").upper()
import Programs.KMP as a
import Programs.Modulo42 as b
import Programs.AliceNBob as c
import Programs.CupsNBall as d
if select=="1":
a.kmp()
elif select=="2":
b.Mod42()
elif select=="3":
c.ANB()
elif select=="4":
d.CNB()
elif select=="Q":
quit() |
import sqlite3
class Database(object):
""" the Silent Disco database. """
def __init__(self):
self.conn = sqlite3.connect('database.db', check_same_thread=False)
self.users_cursor = self.conn.cursor()
self.users_cursor.execute(
""" CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT) """)
def add_user(self, username, password):
""" given a username and a password, adds them to the Users database if not taken. """
if not self.username_password_taken(username, password):
self.users_cursor.execute("INSERT INTO users VALUES(?, ?)", (username, password))
self.conn.commit()
return True # user added successfully.
return False # username was taken. Therefore, user couldn't be added.
def username_password_taken(self, username, password):
""" returns 'true' if username is already taken, 'false' otherwise. """
self.users_cursor.execute('select * from users')
for user in self.users_cursor: # iterating the Users table
if user[0] == username or user[1] == password: # check if the wanted username already exists
return True
return False
def user_exists(self, username, password):
""" checks if the username and password entered actually belong to an existing user. """
self.users_cursor.execute('select * from users')
for user in self.users_cursor: # iterating the Users table
if user[0] == username and user[1] == password: # check if the details match any of the the existing ones.
return True
return False # there is no such user with such password. therefore, return False.
|
# Python内置了字典:dict的支持,dict全称dictionary
# 在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
# 这个通过key计算位置的算法称为哈希算法(Hash)。
# []:list
# ():tuple
# {}: dict
# 学生成绩
score = {"Nicolo":100,"Tom":99,"Jerry":99}
print("打印Nicolo的成绩:",score["Nicolo"])
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
score["Nicolo"] = 101
print("打印Nicolo的成绩:",score["Nicolo"])
# 要避免key不存在的错误,有两种办法,一是通过in判断key是否存在:
print("Nicolo" in score)
# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
score.pop("Jerry")
print(score)
# set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
s = set([1,2,3])
# 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:
s.add(4)
print(s)
# 通过remove(key)方法可以删除元素
s.remove(4)
print("移除后的",s) |
print("tuple一旦初始化就不能修改,比如同样是列出同学的名字")
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
# 现在,classmates这个tuple不能变了,它也没有append(),insert()这样的方法。
# 其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。
# 不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。 |
# InheANDPoly 继承和多态
# 编写了一个名为Animal的class,有一个run()方法可以直接打印:
class Animal(object):
def run(self):
print('Animal is running...')
def eat(self):
print('Eating meat...')
# 当我们需要编写Dog和Cat类时,就可以直接从Animal类继承:
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
# 对于Dog来说,Animal就是它的父类,对于Animal来说,Dog就是它的子类。Cat和Dog类似。
# test
dog = Dog()
dog.run()
dog.eat()
cat = Cat()
cat.run()
# cat.eat()当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。 |
print("hello")
print("这样","可以","连接","起来吗?",",自动识别为空格")
print("试试"+"加好可以连接吗?","事实证明是可以的")
print("100+200 =",100+200)
print(len("abc")) |
import PyPDF2
file1=raw_input("Enter name of first file: ")
file2=raw_input("Enter name of second file: ")
#Access and open the files to merge
pdfFile_1=open("%s" %file1 + '.pdf','rb')
pdfFile_2=open("%s" %file2 + '.pdf','rb')
#Read the two files
pdfRead_1=PyPDF2.PdfFileReader(pdfFile_1)
pdfRead_2=PyPDF2.PdfFileReader(pdfFile_2)
#Create a blank pdf document
pdfWriter=PyPDF2.PdfFileWriter()
#Copy all the pages from file 1
for pageNum in range(pdfRead_1.numPages):
pageObj=pdfRead_1.getPage(pageNum)
pdfWriter.addPage(pageObj)
#Copy all the pages from file 2
for pageNum in range(pdfRead_2.numPages):
pageObj=pdfRead_2.getPage(pageNum)
pdfWriter.addPage(pageObj)
#Create a new merged file
outputFile=open("NewFile.pdf",'wb')
pdfWriter.write(outputFile)
#Close all files
outputFile.close()
pdfFile_1.close()
pdfFile_2.close()
|
"""
Small anonymous functions can be created with the lambda keyword.
This function returns the sum of its two arguments: lambda a, b: a+b.
* Lambda functions can used wherever function objects are required.
* They are syntactically restricted to a single expression.
* Semantically, they are just syntactic sugar for a normal function definition.
* They can reference variables from the containing scope.
"""
# Lambda Function that return a function
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
print(f(0)) # 42
print(f(1)) # 43
print(f(10)) # 52
|
"""
Shortest unique prefix.
Given a list of words, for each word find the shortest unique prefix.
You can assume a word will not be a substring of another word
(i.e. 'play' and 'playing' won't be in the same words list)
Example:
input: ['joma', 'jack', 'john', 'teodore']
poutput: ['jom', 'ja', 'joh', 't']
Use TRIEs usually when thinking in prefixes or strings
A TRIE is basically a tree and for each children theres a counter.
It helps to determine given these words how many words have we passed into certain letters so far
and we will be using these nodes as a references if we can use it as a unique prefix.
1. joma 2. jack 3. john 4. teodore
--> (NODE)
/ \
(j=3) (t=1)
/ \ \
(o=2) (a=1) (...)
/ \ \
(m=0) (h=1) (c=1)
/ \ /
(a=1) (n=1) (k=0)
To get the unique prefix go through each Node in the TRIE, so keep going until you see a 1.
Time complexity: 1st you need to build the TRIE ===> O(n) --> Linear
Because you have to go through all the words
Space: O(n) need to go through all words to build the TRIE
"""
class Node:
def __init__(self):
self.count = 0
self.children = {}
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
curr_node = self.root
for w in word:
if w not in curr_node.children:
curr_node.children[w] = Node()
curr_node = curr_node.children[w]
curr_node.count += 1
def unique_pref(self, word):
curr_node = self.root
prefix = ''
for w in word:
if curr_node.count == 1:
return prefix
else:
curr_node = curr_node.children[w]
prefix += w
return prefix
def get_unique_pref(words):
trie = Trie()
for word in words:
trie.insert(word)
unique_pref = []
for word in words:
unique_pref.append(trie.unique_pref(word))
return unique_pref
words = ['joma', 'jack', 'john', 'teodore']
print(get_unique_pref(words))
|
inputfile = open('{NAME_OF_FILE_HERE}')
emails = inputfile.readlines()
myfuckingset = set()
counter = 0
linecounter = 0
print("Duplicates:")
for line in emails:
linecounter = linecounter + 1
if line not in myfuckingset:
myfuckingset.add(line)
else:
print(line)
counter = counter + 1
print("Number of duplicates:")
print(counter)
|
#!/usr/bin/python
from collections import defaultdict
import string
import os
import sys
from heapq import heappush as push, heappop as pop, heappushpop as pushpop
# Initialization
print "Executing word_count_running_median.py...\n"
max_heap = []
min_heap = []
N = 0
file_names = []
word_count = defaultdict(int)
# Opening files to write results
wc_file = open(sys.argv[2], 'w')
median_file = open(sys.argv[3], "w")
# creating a generator to read files line by line
def sentences(file_name):
with open(file_name) as f:
for line in f:
yield [sentence for sentence in line.lower().translate(string.maketrans("",""), string.punctuation).strip().split()]
# routine to find running median
def median(element):
global N
if N%2 == 0:
push(max_heap, -1*element)
N += 1
if len(min_heap)==0:
return -1*max_heap[0]
elif -1*max_heap[0]>min_heap[0]:
from_max = -1*pop(max_heap)
from_min = pop(min_heap)
push(min_heap, from_max)
push(max_heap, -1*from_min)
else:
from_max = -1*pushpop(max_heap, -1*element)
push(min_heap, from_max)
N += 1
if N%2 == 0:
return float(-1*max_heap[0] + min_heap[0])/2.0
else:
return -1*max_heap[0]
# read all text files in the wc_input directory
for file in os.listdir(sys.argv[1]):
if file.endswith(".txt"):
file_names.append(file)
file_names = sorted(file_names)
# display the number of text files in wc_input and their names
print ("%d text files found in the directory wc_input\nFiles are-" % len(file_names))
for i, name in enumerate(file_names):
print ("%d. %s" % (i+1, name))
# read each file, count word occurences and find running median of the line lenth
for each_file in file_names:
for lines in sentences(sys.argv[1]+"/"+each_file):
if lines==['']:
length_of_line = 0
else:
length_of_line = len(lines)
median_file.write("%.1f \n" % median(float(length_of_line)))
for words in lines:
if words != "" and words != " " and words not in string.punctuation:
word = words.lower().translate(string.maketrans("",""), string.punctuation)
if word != "" and word != " ":
word_count[word] += 1
# save the word counts in a file
for keys in sorted(word_count):
wc_file.write(keys+"\t"+str(word_count[keys])+"\n")
# close result files
wc_file.close()
median_file.close()
print ("\n%d unique words found\n" % len(word_count))
print ("Results have been saved to %s and %s" % (sys.argv[2], sys.argv[3])) |
from time import sleep
#app number call list
# add number call
def addPhone(val, lists):
k = 0
adTrue = False
ref = {0: True, 1: False}
while k < len(lists):
if val == lists[k]:
adTrue = ref[0]
k += 1
if adTrue == True:
print("\n", val, "Ya se encuentra agregado.\n\n")
else:
print("agregando..")
sleep(1)
listPhone.append(val)
print(val, "agregado")
# show contacts
def showPhone(listss):
print("Mostrado..\n")
sleep(1)
it = 0
for lists in listss:
it += 1
print("(",it,")", lists)
print("\n")
# remove number call
def removePhone(lists, val):
ref = False
for k in lists:
if k == val:
ref = True
if ref == True:
print("eliminando..")
sleep(1)
lists.remove(val)
print(val, "Eliminado\n")
else:
print(val, "No encontrado.\n")
# verified existence number call
def verifiedList(lists):
iterators = 0
while iterators < len(lists):
iterators += 1
if lists != []:
if iterators <= 1:
print("\n\tListas de contactos:\n", iterators, "contacto\n")
else:
print("\n\tListas de contactos:\n", iterators, "contactos\n")
else:
print("La lista esta vacia")
# update number call
def updatePhone(lists, oldPhone, newPhone):
n = 0
valid = False
ref = {0: True, 1: False}
print("Verificando..")
sleep(1)
while n < len(lists):
if lists[n] == oldPhone:
lists[n] = newPhone
valid = ref[0]
n += 1
if valid == ref[1]:
print("Ese numero no existe")
else:
print("Actualizado correctamente")
listPhone = ["8297510847", "8092221284", "8295466271"]
configs = {
0: "salir",
1: 0,
2: "mostrar",
3: "eliminar",
4: "agregar",
5: "actualizar",
6: "Agregar numero: "
}
resp = configs[3]
while resp != configs[0]:
resp = input("MOSTRAR | ACTUALIZAR | ELIMINAR | AGREGAR: ")
if resp == configs[2]:
verifiedList(listPhone)
showPhone(listPhone)
elif resp == configs[4]:
val = input(configs[6])
addPhone(val, listPhone)
elif resp == configs[3]:
if listPhone != []:
delete = input("Numero a eliminar: ")
removePhone(listPhone, delete)
else:
verifiedList(listPhone)
elif resp == configs[5]:
if listPhone != []:
oldP = input("Numero viejo: ")
oldNew = input("Numero nuevo: ")
updatePhone(listPhone, oldP, oldNew)
else:
verifiedList(listPhone)
elif resp == configs[0]:
exit(0)
configs[1]+= 1
showPhone(listPhone)
|
class Person(object):
pass
x = Person()
print(type(x)) # module __main__.Person in Py3 , but instance in Py2!!! to make it compatible use Person(object)
# new-style of classes!
# py2 doesn't inherit! https://www.python.org/doc/newstyle/
# use in py2/py3 (object)!!!
print(dir(x))
x.neco = 123 # new attribute without changing class!
print(dir(x))
|
class Person:
Person_id = 1
def __init__(self, name, age):
self.name = name
self.age = age
self.cid = Person.Person_id
Person.Person_id += 1
def printall(self):
print ("Name : %s, age : %d, id : %d" % (self.name, self.age, self.cid))
bob = Person("Bob", 20)
alice = Person("Alice", 19)
bob.printall()
alice.printall()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 11:10:12 2021
@author: frank
"""
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
max = 0
for upper_key in animals:
tem_total = 0
for inner_key in animals[upper_key]:
tem_total+=1
if tem_total > max:
max = tem_total
max_key = upper_key
print(max_key) |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 10:02:02 2017
@author: kashen
"""
import numpy as np
import math
def get_curves(points=1000, radius=2, noise=None, original=False, *args, **kwargs):
"""
Generates syntethic data in the shape of two quarter circles, as in
the example from the paper by Mika et al.
Arguments:
points: number of points in the generated dataset.
noise: name of the distribution to be used as additive noise.
Use one of the distribution from numpy.random, see
https://docs.scipy.org/doc/numpy-1.10.0/reference/routines.random.html
Default is 'uniform', with low=-0.5 and high=0.5. Noise is added to
the semi-circle's radious.
args, kwargs: Any arguments you want to pass to the corresponding
numpy.random sampling function, except size.
Returns:
Arrays with the X and Y coordinates for the new data.
"""
if noise is None:
noise = 'uniform'
kwargs['low'] = -0.5
kwargs['high'] = 0.5
kwargs['size'] = points // 2
dist = getattr(np.random, noise)
angles = np.linspace(0, math.pi/2, num=points//2)
cos = np.cos(angles)
sin = np.sin(angles)
left_center = -0.5
if original==False:
left_radius = radius + dist(*args, **kwargs)
else:
left_radius = radius
left_x = -left_radius*cos + left_center
left_y = left_radius*sin
right_center = 0.5
if original==False:
right_radius = radius + dist(*args, **kwargs)
else:
right_radius = radius
right_x = right_radius*cos[::-1] + right_center
right_y = right_radius*sin[::-1]
return np.concatenate((left_x, right_x)), np.concatenate((left_y, right_y))
def get_square(points=1000, length=4, noise=None, original=False, *args, **kwargs):
"""
Generates syntethic data in the shape of two quarter circles, as in
the example from the paper by Mika et al.
Arguments:
points: number of points in the generated dataset.
noise: name of the distribution to be used as additive noise.
Use one of the distribution from numpy.random, see
https://docs.scipy.org/doc/numpy-1.10.0/reference/routines.random.html
Default is 'uniform', with low=-0.5 and high=0.5. Noise is added
in the direction orthogonal to the current side.
args, kwargs: Any arguments you want to pass to the corresponding
numpy.random sampling function, except size.
Returns:
Arrays with the X and Y coordinates for the new data.
"""
if noise is None:
noise = 'uniform'
kwargs['low'] = -0.5
kwargs['high'] = 0.5
kwargs['size'] = points // 4
dist = getattr(np.random, noise)
real_values = np.linspace(0, length, num=points//4)
x_values = []
y_values = []
# Left side
if original==False:
# Left side
x_values.append(dist(*args, **kwargs))
y_values.append(real_values)
# Right side
x_values.append(dist(*args, **kwargs) + length)
y_values.append(real_values)
# Top side
x_values.append(real_values)
y_values.append(dist(*args, **kwargs) + length)
# Bottom side
x_values.append(real_values)
y_values.append(dist(*args, **kwargs))
else:
# Left side
x_values.append([0]*(points//4))
y_values.append(real_values)
# Right side
x_values.append([length]*(points//4))
y_values.append(real_values)
# Top side
x_values.append(real_values)
y_values.append([length]*(points//4))
# Bottom side
x_values.append(real_values)
y_values.append([0]*(points//4))
return np.concatenate(x_values), np.concatenate(y_values)
def main():
"Example data generation"
X, Y = get_curves(noise='normal', original=True, scale=0.2)
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(5,10))
plt.subplot2grid((2, 1), (0, 0))
plt.axis('off')
plt.plot(X, Y ,'k.')
plt.subplot2grid((2, 1), (1, 0))
plt.axis('off')
X, Y = get_square(noise='normal', original=True, scale=0.2)
plt.plot(X, Y ,'k.')
plt.show()
if __name__ == '__main__':
main() |
#!/user/bin/env python
def quick_sort(arr):
sort_all(arr, 0, len(arr)-1)
return arr
def sort_all(arr, start_index, end_index):
if end_index <= start_index:
return
pivot_index = sort_a_little_bit(arr, start_index, end_index)
sort_all(arr, start_index, pivot_index-1)
sort_all(arr, pivot_index+1, end_index)
def sort_a_little_bit(arr, start_index, end_index):
povit_index = end_index
povit_value = arr[povit_index]
left_index = start_index
while left_index != povit_index:
item = arr[left_index]
if item <= povit_value:
left_index += 1
continue
#-->swap value of left index with value next item of povit
arr[left_index] = arr[povit_index - 1]
#-->shift povit index in next position
arr[povit_index-1] = povit_value
#-->shif item position of pivolt position
arr[povit_index] = item
povit_index -= 1
return povit_index
print(quick_sort([5,3,2,1]))
def test_quick_sort():
test_case = [
([5,3,2,1], [1, 2, 3, 5]),
([8, 3, 1, 7, 0, 10, 2], [0, 1, 2, 3, 7, 8, 10]),
([1, 0], [0, 1]),
]
for args, answer in test_case:
try:
result = quick_sort(args)
if result == answer and answer != "AssertionError":
print("Test Case is Passed!!!")
else:
print("Test Case", args, "Faild")
except AssertionError:
pass
test_quick_sort() |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
'''
The solve of question:
1- I will create a dictionary to record phone number as a key and duration as a value.
2- which check if key in the dictionary or no and add duration as a value for the key.
'''
# initial dictionary
dic = {}
# create function to record phone number and value
def recordDic(key1, key2, value):
if key1 in dic:
dic[key1] += value
else:
dic[key1] = value
if key2 in dic:
dic[key2] += value
else:
dic[key2] = value
def longestTeleSpent():
for row in calls:
num1, num2, time, duration = row
recordDic(num1, num2, int(duration))
# grab phone number and its value
val = dic[max(dic, key=dic.get)]
key = max(dic, key=dic.get)
return "{} spent the longest time, {} seconds, on the phone during September 2016.".format(key, val)
print(longestTeleSpent())
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
|
#!/usr/bin/env python
def count_inversion(ls): #--> Time Complixty O(n)
#-->basic vriables
inversion = 0
#--> get middle
midd = len(ls) //2
#--> divied array to left and right
left = ls[:midd]
right = ls[midd:]
#-->sort left array and right array
left, inv_l = buble_sort(left, inversion)
right, inv_r = buble_sort(right, inversion)
#--> compare between each of item in left array and rigth array
merge, count = compare_sort_left_right_array(left, right, inversion)
inversion += inv_l + inv_r + count
return inversion
def buble_sort(ls, inversion):
for i in range(len(ls)):#--> Time Complixty O(n^2)
for j in range(1, len(ls)):
prev = ls[j-1]
curr = ls[j]
if prev > curr:
ls[j-1] = curr
ls[j] = prev
inversion += 1
return ls, inversion
def compare_sort_left_right_array(left, right, inversion):
#-->basic variables
merged = []
left_index = 0
right_index = 0
while left_index < len(left) and right_index < len(right): #--Time Complixty O(n)
if left[left_index] > right[right_index]:
merged.append(right[right_index])
inversion += len(left[left_index:])
right_index += 1
else:
merged.append(left[left_index])
left_index += 1
merged += left[left_index:]
merged += right[right_index:]
return merged, inversion
def test_merged_sort():
test_case = [
([0,1], 0),
([2, 1], 1),
([3,1,2,4], 2),
([2, 5, 1, 3, 4], 4),
([54, 99, 49, 22, 37, 18, 22, 90, 86, 33], 26),
([1, 2, 4, 2, 3, 11, 22, 99, 108, 389], 2),
]
for args, answer in test_case:
try:
result = count_inversion(args)
if result == answer and answer != "AssertionError":
print("Test Case is Passed!!!")
else:
print("Test Case", args, "Faild")
except AssertionError:
pass
test_merged_sort() |
'''
Exercise 4. Hamming Distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Calculate the Hamming distace for the following test cases.
'''
def hamming_distance(str1, str2):
"""
Calculate the hamming distance of the two strings
Args:
str1(string),str2(string): Strings to be used for finding the hamming distance
Returns:
int: Hamming Distance
"""
# TODO: Write your solution here
# basic variables
distance = 0
#check length of two strings is equal or no
if len(str1) != len(str2):
return None
for char in range(len(str1)):
if str1[char] != str2[char]:
distance += 1
return distance
def test_hamming_distance():
test_cases = [
(("ACTTGACCGGG", "GATCCGGTACA"), 10),
(("shove", "stove"), 1),
(("Slot machines", "Cash lost in me"), None),
(("A gentleman", "Elegant men"), 9),
(("0101010100011101", "0101010100010001"), 2),
]
for (args, answer) in test_cases:
result = hamming_distance(*args)
if result == answer:
print("pass")
else:
print("Test", args, "faild")
test_hamming_distance() |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
'''
create a function that records all phone numbers out calling from telemarketers in a list and search them in the text CSV file if I found the number in the text CSV file I will remove it from the list and in the end I will return with the numbers that are still in the list.
'''
#initial basic variables
sendCall = []
receiveCall = []
result = []
def sendReceiveText():
#
for row in calls:
num1, num2, time, val = row
# create a list with outing calling with no duplicate numbers
if not num1 in sendCall:
sendCall.append(num1)
# create a list with incoming calling with no duplicate numbers
if not num2 in receiveCall:
receiveCall.append(num2)
# create a new list called result to append all numbers which don't found in incoming calling
for call in sendCall:
if not call in receiveCall:
if not call in result:
result.append(call)
# remove all numbers from the result list which sends a text or receive text
for text in texts:
txt1, txt2, time = text
for call in result:
if txt1 == call or txt2 == call:
result.remove(call)
return "These numbers could be telemarketers: \n" + "\n".join([i for i in sorted(result)])
print(sendReceiveText()) |
#!/usr/bin/env python
'''
Problem Statement
You have been given an array containg numbers. Find and return the largest sum in a contiguous subarray within the input array.
'''
def max_sum_subarray(arr):
current_sum = arr[0] # `current_sum` denotes the sum of a subarray
max_sum = arr[0] # `max_sum` denotes the maximum value of `current_sum` ever
# Loop from VALUE at index position 1 till the end of the array
for element in arr[1:]:
'''
# Compare (current_sum + element) vs (element)
# If (current_sum + element) is higher, it denotes the addition of the element to the current subarray
# If (element) alone is higher, it denotes the starting of a new subarray
'''
current_sum = max(current_sum + element, element)
print(current_sum, element)
# Update (overwrite) `max_sum`, if it is lower than the updated `current_sum`
# print(max_sum)
max_sum = max(current_sum, max_sum)
return max_sum
print(max_sum_subarray([-12, 15, -13, 14, -1, 2, 1, -5, 4])) |
import sys
sys.argv.append("..")
from utils import constants
import numpy as np
from typing import Union
class Berry:
"""
Berries are to be eaten by the baby and are randomly spawned
in the environment. They roll around randomly in one of the
four compass directions.
"""
def __init__(
self,
board_size: Union[int, tuple],
movement_probability: float = None,
initial_position: list = None,
):
"""Initializes a berry
Parameters
----------
board_size : Union[int, tuple]
This is the size of the board as an integer if it is a square board
or tuple if rectangular
movement_probability : float, optional
This is the probability that the berry will move one of the four directions per timestep, by default None
initial_position : list, optional
This is the 2 coordinate starting position of a berry, by default None
"""
if type(board_size) == int:
self.board_dimensions = (board_size, board_size)
else:
self.board_dimensions = board_size
if movement_probability:
assert (
0 <= movement_probability <= 1
), "Movement probability needs to be a float between 0 and 1"
self.movement_probability = movement_probability
else:
self.movement_probability = constants.DEFAULT_MOVEMENT_PROBABILITY
if initial_position:
assert (
len(initial_position) == 2
), "Position must be a list of length 2 containing x and y coordinates where top left of the board is [0,0]"
assert (
0 <= initial_position[0] < self.board_dimensions[0]
), "Invalid initial x position"
assert (
0 <= initial_position[1] < self.board_dimensions[1]
), "invalid initial y position"
self.position = initial_position.copy()
else:
self.position = [
np.random.randint(0, self.board_dimensions[0] - 1),
np.random.randint(0, self.board_dimensions[1] - 1),
]
def action(self, direction: str) -> None:
"""The berry randomly moves in one of the four compass directions with
probability given upon initialization
Parameters
----------
direction : str
One of N, E, S, W
"""
if direction == "N":
if self.position[0] != 0:
self.position[0] -= 1
elif direction == "E":
if self.position[1] != self.board_dimensions[1] - 1:
self.position[1] += 1
elif direction == "S":
if self.position[0] != self.board_dimensions[0] - 1:
self.position[0] += 1
elif direction == "W":
if self.position[1] != 0:
self.position[1] -= 1
def get_position(self):
return self.position.copy()
def __str__(self):
position = self.get_position()
return f"Berry at position ({position[0]}, {position[1]}), (row, col)"
|
def RiemanSum(f, a, b, Increment = 0.0001):
"""One dimensional function that returns the riemansum between two points; This implies that the function has the property of Rieman integrability."""
if not callable(f):
raise TypeError("[Rieman.py]: Function RiemanSum needs the input function f to be callabe")
h = Increment #Just a small number
rie = []
if not a < b:
raise ValueError("[Rieman.py] Input a has to be smaller than input b.")
while a < b:
rie.append(f(a)*h)
a += h
return sum(rie)
|
# # 确定中间数 以中间数为基准左右删除
# num_strarr = input().split(' ')
# num_arr = []
# for i in num_strarr:
# num_arr.append(int(i))
#
# index_arr = []
# # 先找出中间数
# for i in range(0,len(num_arr)):
# if i == 0:
# if num_arr[i] >= num_arr[i+1]:
# index_arr.append(i)
# elif i == len(num_arr) - 1:
# if num_arr[i] >= num_arr[i-1]:
# index_arr.append(i)
# else:
# if num_arr[i] >= num_arr[i+1] and num_arr[i] >= num_arr[i-1]:
# index_arr.append(i)
#
# result_dict = []
# # 开始进行删除操作
# for i in index_arr:
# index = num_arr[i]
# temp_arr = num_arr.copy()
# for j in range(len(temp_arr)-1, 0, -1):
# if j == len(temp_arr) - 1:
# if temp_arr[j] > index:
# del temp_arr[j]
# elif j == 0:
# if temp_arr[0] > index:
# del temp_arr[j]
# elif j < i:
# if temp_arr[j] > index or temp_arr[j] > temp_arr[j+1]:
# del temp_arr[j]
# elif j > i:
# if temp_arr[j] > index or temp_arr[j] < temp_arr[j+1]:
# del temp_arr[j]
# result_dict.append(temp_arr)
#
# # 统计最长的数组
# max_num = 0
# for i in result_dict:
# if len(i) > max_num:
# max_num = len(i)
#
# result_str = ''
# for i in result_dict:
# if len(i) == max_num:
# for j in i:
# result_str += str(j) + ' '
# print(result_str.strip())
# result_str = ''
def LIS(a):
a = list(a)
length = len(a)
num = [1] * length # DP中记录每个位置为末尾的最大LIS长度
pos = [0] * length # 记录位置
for i in range(length):
for j in range(i):
if a[j] < a[i] and num[i] < num[j] + 1:
num[i] = num[j] + 1
pos[i] = j
length_max = max(num)
index_max = num.index(length_max)
lis = []
lis.append(a[index_max])
for i in range(length_max - 1):
lis.append(a[pos[index_max]])
index_max = pos[index_max]
# print(lis)
lis.reverse()
return length_max, lis
def print_res(m):
# 按照题目要求格式输出一行
s = ''
m = list(m)
for i in range(len(m)):
s += str(m[i])
s += ' '
print(s.strip())
return
arr = list(map(int, input().strip().split()))
max_i = [] # 分界点(arr[i]包含在m,n中)
len_res = [] # 最大长度
ms = []
ns = []
for i in range(len(arr)):
length_m, m = LIS(arr[:i + 1])
temp = arr[i:len(arr)]
temp.reverse()
length_n, n = LIS(temp)
len_res.append(length_m + length_n - 1)
ms.append(m)
ns.append(n)
len_max = max(len_res)
for i in range(len(len_res)):
if len_res[i] == len_max:
m = ms[i]
n = ns[i]
n.reverse()
if m[-1] == n[0]:
m.extend(n[1:])
else:
m.extend(n)
print_res(m)
|
def swap(arr,i,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def printArr(arr):
s = ""
for i in range(len(arr)):
s+= str(arr[i])
if(i<len(arr)-1):
s+=" "
print(s)
T = int(input())
i=0
arr_big = list()
while i<T:
i+=1
size = int(input())
arr = list(map(int,input().strip().split(" ")))
arr_counter=list()
arr_num = list()
for j in range(len(arr)):
if(arr_num.count(arr[j])==0):
arr_num.append(arr[j])
arr_counter.append(1)
else:
index = arr_num.index(arr[j])
arr_counter[index] += 1
#排序arr_counter
for j in range(len(arr_num)):
for k in range(0,len(arr_num)-1-j):
if(arr_counter[k]<arr_counter[k+1]):
swap(arr_counter,k,k+1)
swap(arr_num,k,k+1)
#对同样数量的按照从小到大排序
for j in range(len(arr_num)):
for k in range(0,len(arr_num)-1-j):
if(arr_counter[k]==arr_counter[k+1]):
if(arr_num[k]>arr_num[k+1]):
swap(arr_num, k, k + 1)
#输出结果
arr_result = list()
for j in range(len(arr_num)):
for k in range(arr_counter[j]):
arr_result.append(arr_num[j])
arr_big.append(arr_result)
for i in range(len(arr_big)):
printArr(arr_big[i])
|
# Assignment 13.1
import xml.etree.ElementTree as ET
import urllib.request, urllib.error, urllib.parse
from urllib.request import urlopen
url = input("Enter location:")
print("Retrieving:", url)
datastring = urlopen(url).read()
stuff = ET.fromstring(datastring)
lst = stuff.findall('comments/comment')
Tot = 0
for num in lst:
n = int(num.find('count').text)
Tot = Tot + n
print(Tot) |
def isAlt(s):
vowels = 'aeiou'
rule = lambda x,y : x in vowels and y not in vowels or x not in vowels and y in vowels
return all(rule(s[i], s[i+1]) for i in range(len(s) - 1)) |
def is_prime(n):
if n == 0 or n == 1: return False
res = True
for i in range(2, int(n**.5)+1):
if n % i == 0:
res = False
break
return res
def generate_primes(x):
return (n for n in range(x+1) if is_prime(n)) |
def one_two_three():
n = 2*one_two() + one_two() - 2
while n not in [1,2,3]:
n = 2*one_two() + one_two() - 2
return n |
from collections import Counter
def first_non_repeating_letter(string):
c = Counter(string)
nonrepetitive = [k for k, v in c.items() if v == 1]
nonrepetitive = [k for k in nonrepetitive if not k.isalpha()] + \
[k for k in nonrepetitive if k.swapcase() not in string]
if nonrepetitive:
return min(nonrepetitive, key=string.index)
else:
return "" |
def yes_no(arr):
res = []
l = arr[:]
i = 0
while len(res) < len(arr):
try:
res.append(l[i])
l.append(l[i+1])
i += 2
except IndexError:
pass
return res
|
def convert_to_mixed_numeral(parm):
n, d = [int(i) for i in parm.split('/')]
if abs(n) < d:
return parm
else:
a, b = divmod(abs(n), d)
if b == 0: return "-" * (n < 0) + "%d" % a
return "-" * (n < 0) + "%d %d/%d" % (a, b, d)
|
def capitalize(s):
return [
"".join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s)),
"".join(c.upper() if i % 2 != 0 else c for i, c in enumerate(s))
] |
def palindrome(num):
if not isinstance(num, int):
return "Not valid"
elif num < 0:
return "Not valid"
else:
num = str(num)
for i in range(len(num) - 1):
for j in range(i+1, len(num)):
if num[i] == num[j]:
p = num[i:j+1]
if p == p[::-1]:
return True
else:
break
return False
|
import re
def parse_example(example):
expression, variable = example.split(" = ")
return variable, "(" + expression + ")"
def only_one_variable_in_expression(expression):
return len(set(select_variables(expression))) == 1
def select_variables(expression):
return re.findall(r"[a-z]+", expression, flags=re.IGNORECASE)
def format_expression_for_eval(expression):
expression = re.sub(r"(\d+)\s*\(", r"\1*(", expression)
expression = re.sub(r"(\d)[a-z]", r"\1", expression, flags=re.IGNORECASE)
expression = re.sub(r"[a-z]", r"1", expression)
return expression
def simplify(examples, formula):
while not only_one_variable_in_expression(formula):
for example in examples:
variable, expression = parse_example(example)
formula = formula.replace(variable, expression)
variable = select_variables(formula)[0]
val = eval(format_expression_for_eval(formula))
ans = "{}{}".format(val, variable)
return ans if ans != "1c" else "1x" |
import re
def triple_double(num1, num2):
tripleMatch = re.search(r"(\d)\1{2}", str(num1))
if tripleMatch is None:
return False
else:
tripleNum = tripleMatch.group(1)
return bool(re.search(r"([%s])\1" % tripleNum, str(num2)))
|
def stairs(n):
w = 2*n + 2*n-1
return '\n'.join((' '.join(str(num%10) for num in range(1, i+1)) + ' ' + ' '.join(str(num%10) for num in range(i, 0, -1))).rjust(w) for i in range(1, n+1))
|
import re
def trump_detector(trump_speech):
duplicates_regex = re.compile(r"([aeiou])\1+", re.IGNORECASE)
duplicates = []
normal_speech = re.sub(duplicates_regex, lambda x: duplicates.append(x.group()) or x.group()[0], trump_speech)
extra_vowels = sum(len(d)-1 for d in duplicates)
total_vowels = sum(1 for c in normal_speech if c.lower() in "aeiou")
return round(extra_vowels/total_vowels, 2) |
def order_word(s):
return "Invalid String!" if not s else ''.join(sorted(s)) |
from string import ascii_lowercase as alphabet
def sort_string(s):
nonEnglishIndex = [i for i in range(len(s)) if s[i].lower() not in alphabet]
nonEnglishChars = ''.join(s[i] for i in nonEnglishIndex)
s2 = "".join(sorted(s, key=lambda x: x.lower())).strip(nonEnglishChars)
for idx in nonEnglishIndex:
s2 = s2[:idx] + s[idx] + s2[idx:]
return s2 |
def reverse(n):
power = len(str(n))-1
if n < 10:
return n
else:
return (n%10)*10**power + reverse(n//10) |
from math import sqrt
def find_divs(n):
divs = []
for i in range(1,int(sqrt(n))+1):
if n % i == 0 : divs.append(i)
return sorted(divs + [n/j for j in divs if j != sqrt(n)])
def oddity(n):
return 'even' if len(find_divs(n)) % 2 == 0 else 'odd' |
def is_increasing(n):
res = True
n0 = str(n)[0]
for d in str(n)[1:]:
if d < n0:
res = False
break
else:
n0 = d
return res
def is_decreasing(n):
res = True
n0 = str(n)[0]
for d in str(n)[1:]:
if d > n0:
res = False
break
else:
n0 = d
return res
def is_bouncy(n):
return not is_decreasing(n) and not is_increasing(n)
def bouncy_ratio(percent):
i, nbouncy = {0: (1, 0), 1: (194, 49), 2: (538, 269), 3: (3088, 2316)}[int(percent/0.25)]
while True:
if float(nbouncy)/i >= percent:
break
else:
i += 1
nbouncy += is_bouncy(i)
return i
|
def unique_in_order(iterable):
if len(iterable) < 2:
return list(iterable)
res = []
for i in range(len(iterable) - 1):
if iterable[i] != iterable[i+1]:
res.append(iterable[i])
return res + [iterable[-1]]
|
def solution(digits):
largest = 0
for i in range(len(digits) - 4):
current_val = int(digits[i: i+5])
if current_val > largest:
largest = current_val
return largest |
def remove_smallest(numbers):
if not numbers:
return []
else:
min = numbers[0]
for number in numbers[1:]:
if number < min:
min = number
numbers.remove(min)
return numbers
|
def fibo(n) :
a = 0
b = 1
for i in range(n-1) :
c = a + b
c = c % 10
a = b
b = c
return b
n = int(input())
sol = 1
if n > 2 :
sol = fibo(n)
sol = str(sol)
print(sol[-1])
|
# Uses python3
import sys
def get_change(n):
#write your code here
#print("hi",n)
c=0
while n>0 :
if n == 0:
break
if n > 10 :
c=c+1
n=n-10
elif n>=5 and n<=9:
c=c+1
n=n-5
else:
# print("hi")
c=c+n
n=n-n
#print(n,c)
return c
n = int(input())
print(get_change(n))
|
import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a vector of dimension D = d_1 * ... * d_k, and
then transform it to an output vector of dimension M.
Inputs:
- x: A numpy array containing input data, of shape (N, d_1, ..., d_k)
- w: A numpy array of weights, of shape (D, M)
- b: A numpy array of biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
out = None
# Reshape x into rows
N = x.shape[0]
x_row = x.reshape(N, -1) # (N,D) 按照样本个数把数组拉直
print(x_row)
print(x_row.shape)
out = np.dot(x_row, w) + b # (N,M)
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
dx, dw, db = None, None, None
dx = np.dot(dout, w.T) # (N,D)
# print(dx)
dx = np.reshape(dx, x.shape) # (N,d1,...,d_k)
# print(dx)
x_row = x.reshape(x.shape[0], -1) # (N,D)
# print(x_row)
dw = np.dot(x_row.T, dout) # (D,M)
db = np.sum(dout, axis=0, keepdims=True) # (1,M)
return dx, dw, db
# x=np.random.randint(2,6,(3,10))
# print(x)
# w = np.random.randint(3,5,(10,5))
# b = np.zeros(5)
# dout=np.random.randint(2,3,(3,5))
# affine_backward(dout,(x,w,b))
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
out = None
out = ReLU(x)
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, x = None, cache
dx = dout
dx[x <= 0] = 0
return dx
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
N = x.shape[0]
correct_class_scores = x[np.arange(N), y]
margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)
margins[np.arange(N), y] = 0
loss = np.sum(margins) / N
num_pos = np.sum(margins > 0, axis=1)
dx = np.zeros_like(x)
dx[margins > 0] = 1
dx[np.arange(N), y] -= num_pos
dx /= N
return loss, dx
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification. Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
loss = -np.sum(np.log(probs[np.arange(N), y])) / N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
return loss, dx
def ReLU(x):
"""ReLU non-linearity."""
return np.maximum(0, x)
def conv_forward_naive(x, w, b, conv_param):
"""卷积层前向传播"""
stride, pad = conv_param['stride'], conv_param['pad']
N, C, H, W = x.shape #N样本个数 #C当前输入channel #H 图像高 #W图像的高
F, C, HH, WW = w.shape #F特征图的个数 #C特征图层数 #HH 特征图高 ##特征图的高
x_padded = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), mode='constant')
# print(x_padded)
H_new = int(1 + (H + 2 * pad - HH) / stride) #output大小
W_new = int(1 + (W + 2 * pad - WW) / stride) #output大小
s = stride
out = np.zeros((N, F, H_new, W_new)) #特征图
for i in range(N): # ith image
for f in range(F): # fth filter
for j in range(H_new):
for k in range(W_new):
#print x_padded[i, :, j*s:HH+j*s, k*s:WW+k*s].shape
#print w[f].shape
#print b.shape
#print np.sum((x_padded[i, :, j*s:HH+j*s, k*s:WW+k*s] * w[f]))
out[i, f, j, k] = np.sum(x_padded[i, :, j*s:HH+j*s, k*s:WW+k*s] * w[f]) + b[f]
cache = (x, w, b, conv_param)
return out, cache #存储器
# if __name__ == '__main__':
# import numpy as np
# x=np.random.randint(1,3,(2,3,8,8))
# w=np.random.randint(2,4,(3,3,2,2))
# b=np.ones(3)
# conv_param = {'stride': 1, 'pad': 2}
#
# # print(w)
# # print(b)
# ret=conv_forward_naive(x,w,b,conv_param)
# # print(ret[0])
# ret1 =relu_forward(ret[0])
# print(ret1[0])
# pool_param ={'pool_height': 2, 'pool_width': 2, 'stride': 2}
# max_pool_forward_naive(ret1[0],pool_param)
def conv_backward_naive(dout, cache):
"""卷积反向传播"""
x, w, b, conv_param = cache
pad = conv_param['pad']
stride = conv_param['stride']
F, C, HH, WW = w.shape
N, C, H, W = x.shape
H_new = int(1 + (H + 2 * pad - HH) / stride)
W_new = int(1 + (W + 2 * pad - WW) / stride)
dx = np.zeros_like(x)
dw = np.zeros_like(w)
db = np.zeros_like(b)
s = stride
x_padded = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant')
dx_padded = np.pad(dx, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant')
for i in range(N): # ith image
for f in range(F): # fth filter
for j in range(H_new):
for k in range(W_new):
window = x_padded[i, :, j*s:HH+j*s, k*s:WW+k*s]
db[f] += dout[i, f, j, k]
dw[f] += window * dout[i, f, j, k]
dx_padded[i, :, j*s:HH+j*s, k*s:WW+k*s] += w[f] * dout[i, f, j, k]
# Unpad
dx = dx_padded[:, :, pad:pad+H, pad:pad+W]
return dx, dw, db
# if __name__ == '__main__':
# dout=np.random.randint(3,4,(2,4,32,32))
# x=np.random.randint(5,7,(2,3,32,32))
# w = np.random.randint(3,4,(4,3,7,7))
# b=np.ones(4)
# conv_param = {'stride': 1, 'pad': int((7 - 1) / 2)}
# ret=conv_backward_naive(dout,(x,w,b,conv_param))
# print(ret[0].shape)
# print(ret[1].shape)
# print(ret[2])
def max_pool_forward_naive(x, pool_param):
HH, WW = pool_param['pool_height'], pool_param['pool_width']
s = pool_param['stride']
N, F, H, W = x.shape
H_new = int(1 + (H - HH) / s)
W_new = int(1 + (W - WW) / s)
out = np.zeros((N, F, H_new, W_new))
for i in range(N):
for j in range(F):
for k in range(H_new):
for l in range(W_new):
window = x[i, j, k*s:HH+k*s, l*s:WW+l*s]
out[i, j, k, l] = np.max(window)
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
x, pool_param = cache
HH, WW = pool_param['pool_height'], pool_param['pool_width']
s = pool_param['stride']
N, C, H, W = x.shape
H_new = int(1 + (H - HH) / s)
W_new = int(1 + (W - WW) / s)
dx = np.zeros_like(x)
for i in range(N):
for j in range(C):
for k in range(H_new):
for l in range(W_new):
window = x[i, j, k*s:HH+k*s, l*s:WW+l*s]
m = np.max(window)
dx[i, j, k*s:HH+k*s, l*s:WW+l*s] = (window == m) * dout[i, j, k, l]
return dx
# if __name__ == '__main__':
# import numpy as np
# x=np.random.randint(1,3,(2,3,32,32))
# w=np.random.randint(2,4,(32,3,7,7))
# b=np.ones(32)
# conv_param = {'stride': 1, 'pad': 3}
#
# # print(w)
# # print(b)
# ret=conv_forward_naive(x,w,b,conv_param)
# # print(ret[0])
# ret1 =relu_forward(ret[0])
# pool_param ={'pool_height': 2, 'pool_width': 2, 'stride': 2}
# ret2=max_pool_forward_naive(ret1[0],pool_param)
# # print(ret2[0])
# w2 = np.random.randn(32*16*16,100)
# b2 = np.ones(100)
# ret3=affine_forward(ret2[0],w2,b2)
# w3 =np.random.randn(100,10)
# b3 = np.ones(10)
# ret4=affine_forward(ret3[0],w3,b3)
# print(ret4[0])
# print(ret4[0].shape)
|
class Student:
def __init__(self, name, carrera, nivel):
self.nombre = name
self.carrera = carrera
self.nivel = nivel
self.calificaciones = []
self.promedio = 0.0
def capturar_calificaciones(self, unidad, calificacion):
self.calificaciones.insert(unidad, calificacion)
def calcular_promedio(self):
suma = 0
for c in self.calificaciones:
suma += c
self.promedio = suma / len(self.calificaciones)
def imprimir(self):
print('\n--------------------------------------')
print("Nombre: %s | Carrera: %s | Cuatri: %s" % (self.nombre, self.carrera, self.nivel))
print("Calificaciones: %s" % self.calificaciones)
print("Promedio: %.2f" % self.promedio)
|
from math import ceil
#import networkx as nx
import shortest_path as sp
import graph
def path_weight(Graph,path):
weight = 0
for i in range(0,len(path)-1):
#print('path_weight edges ',Graph.edges(data=True))
#print('path weight indeces ',path[i],path[i+1])
#weight += Graph.get_edge_data(path[i],path[i+1])['weight']
# ind = Graph.nodes[path[i]].children.index(path[i+1])
# weight += Graph.nodes[path[i]].children[ind]['weight']
weight += Graph.get_edge(path[i],path[i+1])[2]
return weight
def Shortest_Path(Graph,k,start,end):
#paths = [nx.dijkstra_path(Graph,start,end,'weight')]
paths = [sp.Shortest_Path(Graph,start,end)]
if not paths[0]:
print('no path to end')
return
B = []
for i in range(1,k):
#print('i ',i)
for spurNode in paths[i-1][0:-1]: #don't include end node
#print('spurNode ',spurNode)
#print('spurNode ',spurNode, 'last path ',paths[i-1])
spurNodeInd = paths[i-1].index(spurNode)
rootPath = paths[i-1][0:spurNodeInd+1]
edges_removed = []
nodes_removed = []
for p in paths:
#print('p ',p)
#print('spind ',spurNodeInd,' p ',p)
if(len(p) >= len(rootPath)):
if(rootPath == p[0:spurNodeInd+1]):
#print('root path ',rootPath,' otherpath ',p[0:spurNodeInd+1])
#edges = [(p(x),p(x+1)) for x in range(0,len(p)-1)]
#Graph.remove_edges_from(edges)
if(Graph.has_edge(p[spurNodeInd],p[spurNodeInd+1])): #if edge wasn't already removed
edge_to_remove = Graph.get_edge(p[spurNodeInd],p[spurNodeInd+1])
#print('edge to remove ',edge_to_remove)
if(edges_removed.count(edge_to_remove) == 0):
edges_removed.append(edge_to_remove)
#print('edges removed temp1 ',edges_removed)
#Graph.remove_edge(p[spurNodeInd],p[spurNodeInd+1]) #remove edge from spur that was on previous path
#print(Graph.nodes())
for n in rootPath[0:-1]: #all nodes in root path except spur node
#print('n ',n)
edges = Graph.edges()
edges_to_remove = [x for x in edges if (x[0] == n or x[1] == n)]
#print('edges ',edges_to_remove)
if(edges_removed.count(edge_to_remove) == 0):
edges_removed = edges_removed + edges_to_remove
#print('edges removed temp2 ',edges_removed)
nodes_removed.append(n)
#Graph.remove_node(n) #remove node, so that it isn't visited again, which would create a loop
Graph.remove_edges_from(edges_removed)
#Graph.remove_nodes_from(nodes_removed)
#spurPath = nx.dijkstra_path(Graph,spurNode,end,'weight')
spurPath = sp.Shortest_Path(Graph,spurNode,end)
if not spurPath:
continue #no path found
#print('edges removed ',edges_removed,' nodes removed ',nodes_removed)
#Graph.add_nodes_from(nodes_removed)
Graph.add_edges_from(edges_removed)
totalPath = rootPath[0:-1] + spurPath
#print('totalPath, ',totalPath)
#print('Edges: ',Graph.edges(data=True),' nodes ',Graph.nodes())
totalPath_weight = (path_weight(Graph,totalPath),totalPath)
if(B.count(totalPath_weight) == 0):
B.append(totalPath_weight)
if(not B):
break;
B.sort() #sort at the end because we do many additions for 1 min remove, so heap is not as useful
#print('B ',B)
paths.append(B.pop(0)[1])
return paths
def make_graph(num_nodes,edges):
G = graph.Graph()
G.num_nodes = num_nodes
G.num_edges = len(edges)
for i in range(0,G.num_nodes):
G.nodes.append(Node())
for i in range(0,len(edges)):
G.nodes[edges[i][0]].children.append({'end' :edges[i][1],
'weight' :edges[i][2]})
G.nodes[0].parent = -2 #node 1 is the only node that shouldn't have it's weight updated if it hasn't been visited, so mark it differently
return G
# def make_graph_from_networkx(nx_graph):
# G = Graph()
# G.num_nodes = len(nx_graph.nodes())
# edges = nx_graph.edges(data=True)
# G.num_edges = len(edges)
# for i in range(0,G.num_nodes):
# G.nodes.append(Node())
# for i in range(0,len(edges)):
# G.nodes[edges[i][0]].children.append({'end' :edges[i][1],
# 'weight' :edges[i][2]['weight']})
# G.nodes[0].parent = -2 #node 1 is the only node that shouldn't have it's weight updated if it hasn't been visited, so mark it differently
# return G
|
# # 身份验证
# username=input("username:")
# password=input("password:")
# if username== "admin" and password=="12345":
# print("pass")
# else:
# print("failed")
# 分段函数求值
# x=float(input("请输入x的值:"))
# # if x>1:
# # print(3*x-5)
# # elif -1<=x<=1:
# # print(x+2)
# # else:
# # print(5*x+3)
# if x>1:
# y=3*x-5
# elif -1<=x<=1:
# y=x=2
# else:
# y=5*x+3
# print('f(%.2f) = %.2f' % (x, y))
# # print(y)
# 英制单位与公制单位厘米互换
# x=float(input("请输入长度:"))
# a=input("请输入单位(英尺/厘米):")
# if a=="英尺" or a=="in":
# print(x*2.54)
# elif a=="厘米" or a=="cm":
# print(x/2.54)
# else:
# print("请输入正确的单位")
# 百分制成绩转换为等级制成绩。
# 要求:如果输入的成绩在90分以上(含90分)输出A;80分-90分(不含90分)输出B;
# 70分-80分(不含80分)输出C;60分-70分(不含70分)输出D;60分以下输出E。
# grade=float(input("请输入成绩:"))
# # if grade>=90:
# # print("A")
# # elif 80<=grade<90:
# # print("B")
# # elif 70<=grade<80:
# # print("C")
# # elif 60<=grade<70:
# # print("D")
# # else:
# # print("E")
# if grade>=90:
# y="A"
# elif 80<=grade<90:
# y="B"
# elif 70<=grade<80:
# y="C"
# elif 60<=grade<70:
# y="D"
# elif grade<60:
# y="E"
# else:
# y="请输入正确的分数"
# print(y)
# 练习3:输入三条边长,如果能构成三角形就计算周长和面积。
x=float(input("请输入第一条边:"))
y=float(input("请输入第二条边:"))
z=float(input("请输入第三条边:"))
if x+y>z and x+z>y and y+z>x:
print('周长:%0.2f'%(x+y+z))
p=(x+y+z)/2
s=(p*(p-x)*(p-y)*(p-z))**0.5
print('面积:%0.2f'%(s))
else:
print("不是三角形") |
# Importação das biliotecas
import streamlit as st
import pandas as pd
import base64
import geopy
import folium
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
csv = df.to_csv(index=False,float_format='%.10f')
# some strings <-> bytes conversions necessary here
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}" download="dados.csv">Download csv file</a>'
return href
def main():
st.title('Georreferenciamento')
st.subheader('Carregue seu arquivo com os endereços')
file = st.file_uploader(
'Escolha a base de dados que deseja analisar (.csv)', type='csv')
if file is not None:
st.subheader('Analisando os dados')
df = pd.read_csv(file)
df.columns = df.columns.str.upper()
st.write("**Número de endereços:** " +str(df.shape[0]))
st.markdown('**Visualizando o dataframe**')
number = st.slider(
'Escolha o numero de linhas que deseja ver', min_value=1, max_value=df.shape[0])
st.table(df.head(number))
botao = st.button('Executar')
if botao:
georeferenciamento(df)
def georeferenciamento(df):
dir(geopy)
from geopy.geocoders import Nominatim
nom = Nominatim(user_agent="test", timeout=3)
df["ENDERECO"] = df["RUA"]+", " + \
df["BAIRRO"]+", "+df["CIDADE"]+" "+df["ESTADO"]
df["COORDERNADAS"] = df["ENDERECO"].apply(nom.geocode)
df["lat"] = df["COORDERNADAS"].apply(
lambda x: x.latitude if x != None else None)
df["lon"] = df["COORDERNADAS"].apply(
lambda x: x.longitude if x != None else None)
dados = df.copy()
nulos = dados['lat'].isnull().sum()
st.write("Não conseguimos georreferenciar " + str(nulos) + " endereços")
dados.dropna(axis=0, how='any',inplace=True)
mapa = folium.Map(location=[-15.788497,-47.879873], zoom_start=4)
lat = dados["lat"]
long = dados["lon"]
for la, lo in zip(lat, long):
folium.Marker([la, lo]).add_to(mapa)
st.markdown(mapa._repr_html_(), unsafe_allow_html =True)
st.subheader('faça download abaixo : ')
df['lat'] = df['lat'].apply(str)
df['lon'] = df['lon'].apply(str)
st.markdown(get_table_download_link(df), unsafe_allow_html=True)
st.markdown("**Desenvolvido por:**")
st.write("Lucas Ribeiro")
if __name__ == '__main__':
hide_streamlit_style = "<style> #MainMenu {visibility: hidden;}footer {visibility: hidden;}</style>"
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
main()
|
from abc import ABC, abstractmethod
import pygame
# Klasa pod koniec wyłączona z użycia, zastąpiona Spritem
class MovingObjects(ABC, ):
def __init__(self, x, y):
self.speed = 0
self._position = [x, y]
self.direction = []
@abstractmethod
def get_event(self):
pass
@abstractmethod
def update(self):
pass
@abstractmethod
def bounce(self):
pass
def get_speed(self):
return self.speed
def set_speed(self, speed):
self.speed = speed
def get_pos(self):
return tuple(self._position)
def set_pos(self, x, y):
self._position = [x, y]
return x, y
@property
def direction(self):
return self._direction
@direction.setter
def direction(self, xy):
self._direction = xy
|
# -*- coding: utf-8 -*-
sayi1 = int(input("Sayı Giriniz (1.)"))
sayi2 = int(input("Sayı Giriniz (2.)"))
sayi3 = int(input("Sayı Giriniz (3.)"))
if (sayi1>=sayi2) and (sayi1>=sayi3):
enBuyuk = sayi1
elif (sayi2>=sayi1) and (sayi2>=sayi3):
enBuyuk = sayi2
else:
enBuyuk = sayi3
print("En Büyük Sayı = ",enBuyuk) |
def compare(user_number, random_number):
if int(user_number) == random_number:
return 'You win'
elif int(user_number) > random_number:
return 'Вваше число Больше'
elif int(user_number) < random_number:
return 'Вваше число Меньше'
|
"""
Суть задачи:
юзер пришел в казино, сел за автомат, начал игру и у него начали выпадать рандомно величины из представленных выше.
Нужно написать впрограмму, которая за каждым вводом "Играть" (на Ваше усмотрение) - делал вывод полученых очков в комбинации и количество очков
юзера за всю игру. Если юзре ввел "Выйти" (на ваше усмотрение) - выходит из программы и показвает количество очков за игру.
Выше есть таблица со значениями сколько какая комбинация весит.
"""
start_game = input('Do you want to start? Write Y or N: ')
import score
from restart import restart
def total():
res = 0
while start_game == 'Y':
res = res + score.score()
print(f'You have', res, 'points')
if restart() == 'yes':
continue
break
return res
if __name__ == '__main__':
print(f'Your total score', total())
|
"""
Input: Feb 12 2019 2:41PM
Output: 2019-02-12 14:41:00
Функция принимает строку (пример - Input) и возвращает строку (пример - Output)
"""
from datetime import datetime
date_input = "Feb 12 2019 2:41PM"
date_output = str(datetime.strptime(date_input, "%b %d %Y %I:%M%p"))
print(date_output)
"""
Напишите функция is_prime, которая принимает 1 аргумент (число) и возвращает True, если число простое, иначе False
Простое число - это число, которое делится без остатка только на себя и на 1
"""
def is_prime(number):
if number > 1:
for i in range(2, number // 2):
if (number % i) == 0:
return False
return True
return False
print(is_prime(13))
"""
Напишите функцию, которая принимает 1 аргумент (строка) и выполняет ... действия на каждую из букв строки
"""
def parse(rules):
res = []
value = 0
for rule in rules:
if rule == 'i':
value += 1
elif rule == 's':
value *= value
elif rule == 'd':
value -= 1
elif rule == 'o':
res.append(value)
return res
print(parse("iiisdoso"))
|
# Given s, starting location, and n, # of steps to take
# Output all possibilities in sequential order
# s = 1, n = 1 --> [
# [1, 2],
# [1, 4],
# [1, 5]
# ]
# s = 1, n = 2 --> [
# [1, 2, 1], [1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6],
# [1, 4, 1], [1, 4, 2], [1, 4, 5], [1, 4, 7], [1, 4, 8],
# [1, 5, 1], [1, 5, 2], [1, 5, 3], [1, 5, 4], [1, 5, 6], [1, 5, 7], [1, 5, 8], [1, 5, 9]
# ]
directions = {
1:[2, 4, 5],
2:[1, 3, 4, 5, 6],
3:[2, 5, 6],
4:[1, 2, 5, 7, 8],
5:[1, 2, 3, 4, 6, 7, 8, 9],
6:[2, 3, 5, 8, 9],
7:[4, 5, 8, 0],
8:[4, 5, 6, 7, 9, 0],
9:[5, 6, 8, 0],
0:[7, 8, 9]
}
def numPadGame(s, n):
result = []
if n == 1:
result = numPadGameRecurse(s, n)
else:
# Get all directions for the initial starting number
subDirections = directions[s]
for d in subDirections:
subRecurse = numPadGameRecurse(d, n-1)
for i in subRecurse:
result.append([s] + i)
return result
def numPadGameRecurse(s, n):
subResult = []
# Base case of n = 0
if n == 0:
return [s]
# Otherwise, recurse with n-1
else:
subDirections = directions[s]
for d in subDirections:
subNumPad = numPadGameRecurse(d, n-1)
for i in range(len(subNumPad)):
l = [s]
if len(subNumPad) == 1:
l.append(subNumPad[i])
else:
l += subNumPad[i]
subResult.append(l)
return subResult
# Parse cmdline input
if __name__ == "__main__":
import os, sys, getopt
def usage():
print ('Usage: ' + os.path.basename(__file__) + ' start steps')
sys.exit(2)
# extract parameters
try:
opts, args = getopt.getopt(sys.argv[1:],"hc:",["help"])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
start = int(args[0]) if len(args) > 0 else None
steps = int(args[1]) if len(args) > 1 else None
for opt in opts:
if opt in ("-h", "--help"):
usage()
if (start is None):
print('start is missing\n')
usage()
elif (steps is None):
print('steps is missing\n')
usage()
print(numPadGame(start, steps)) |
import numpy as np
import matplotlib.pyplot as plt
import scipy as sci
import scipy.io as sio
from warmUpExercise import warmUpExercise
from computeCost import computeCost
from gradientDescent import gradientDescent
## Machine Learning Online Class - Exercise 1: Linear Regression
# Instructions
# ------------
#
# This file contains code that helps you get started on the
# linear exercise. You will need to complete the following functions
# in this exericse:
#
# warmUpExercise.m
# plotData.m
# gradientDescent.py
# computeCost.py
# gradientDescentMulti.m
# computeCostMulti.m
# featureNormalize.m
# normalEqn.m
#
# For this exercise, you will not need to change any code in this file,
# or any other files other than those mentioned above.
#
# x refers to the population size in 10,000s
# y refers to the profit in $10,000s
#
## Initialization
##clear # close all# clc
## ==================== Part 1: Basic Function ====================
# Complete warmUpExercise.m
print('Running warmUpExercise ... \n')#
print('5x5 Identity Matrix: \n')#
print(warmUpExercise())
print('Program paused. Press enter to continue.\n')#
raw_input(">>>")
#
#
# ## ======================= Part 2: Plotting =======================
print('Plotting Data ...\n')
data = np.loadtxt('ex1data1.txt',delimiter=',')#
X = data[:, 0]
y = data[:, 1]#
m = len(y)# # number of training examples
#
# # Plot Data
# # Note: You have to complete the code in plotData.m
plt.plot(X, y, 'ro')#
plt.show()
#
print('Program paused. Press enter to continue.\n')#
raw_input(">>>")
#
# ## =================== Part 3: Gradient descent ===================
print('Running Gradient Descent ...\n')
#
X = np.column_stack((np.ones((m, 1)), data[:,1]))# # Add a column of ones to x
theta = np.zeros((2, 1))# # initialize fitting parameters
#
# # Some gradient descent settings
iterations = 1500#
alpha = 0.01#
#
# # compute and display initial cost
computeCost(X, y, theta)
#
# # run gradient descent
theta = gradientDescent(X, y, theta, alpha, iterations)#
#
# # print theta to screen
# print('Theta found by gradient descent: ')#
# print('#f #f \n', theta(1), theta(2))#
#
# # Plot the linear fit
# hold on# # keep previous plot visible
# plot(X(:,2), X*theta, '-')
# legend('Training data', 'Linear regression')
# hold off # don't overlay any more plots on this figure
#
# # Predict values for population sizes of 35,000 and 70,000
# predict1 = [1, 3.5] *theta#
# print('For population = 35,000, we predict a profit of #f\n',...
# predict1*10000)#
# predict2 = [1, 7] * theta#
#print('For population = 70,000, we predict a profit of #f\n',predict2*10000)#
#print('Program paused. Press enter to continue.\n')#
raw_input(">>>")
## ============= Part 4: Visualizing J(theta_0, theta_1) =============
#print('Visualizing J(theta_0, theta_1) ...\n')
# Grid over which we will calculate J
#theta0_vals = linspace(-10, 10, 100)#
#theta1_vals = linspace(-1, 4, 100)#
# initialize J_vals to a matrix of 0's
#J_vals = zeros(length(theta0_vals), length(theta1_vals))#
# Fill out J_vals
#for i = 1:length(theta0_vals)
# for j = 1:length(theta1_vals)
# t = [theta0_vals(i)# theta1_vals(j)]#
# J_vals(i,j) = computeCost(X, y, t)#
# end
#end
# Because of the way meshgrids work in the surf command, we need to
# transpose J_vals before calling surf, or else the axes will be flipped
#J_vals = J_vals'#
# Surface plot
#figure#
#surf(theta0_vals, theta1_vals, J_vals)
#xlabel('\theta_0')# ylabel('\theta_1')#
# Contour plot
#figure#
# Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
#contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
#xlabel('\theta_0')# ylabel('\theta_1')#
#hold on#
#plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2)#
|
#Reverse Integer - easy
# Given a signed 32-bit integer x, return x with its digits reversed. If reversing
# x causes the value to go outside the signed 32-bit integer
# range [-231, 231 - 1], then return 0.
# Assume the environment does not allow you to store 64-bit integers
# (signed or unsigned).
def reverse_integer(num):
"""
>>> reverse_integer(123)
321
>>> reverse_integer(-123)
-321
>>> reverse_integer(120)
21
>>> reverse_integer(0)
0
"""
result = ""
if num < 0:
negative = True
elif num > 0:
negative = False
else:
return num
str_num = str(num)
if negative:
str_num = str_num[1:]
str_num = list(str_num)
while len(str_num) > 0:
last = str_num.pop()
result += last
if negative and int(result) * -1 >= -2 ** 31 :
return int(result) * -1
elif int(result) < (2 ** 31) -1:
return int(result)
else:
return 0
# pseudocode:
# check if number is negative
# if so store as a boolean variable
# convert integer to a string
# if negative, slice off first char (the - character)
# while len string is greater than 0
# pop off last character
# append to new string for reversed number
# convert new string back to int
# if negatative boolean is true
# return new int * -1
# else return new int
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print('\n ALL TESTS PASSED!\n') |
import unittest
import passwordGenerator
import itertools
import collections
class TestPasswordGenerator(unittest.TestCase):
def setUp(self):
pass
def test_length(self):
password = passwordGenerator.generatePassword()
self.assertTrue( len(password) > 12)
def test_upper_and_lower(self):
password = passwordGenerator.generatePassword()
self.assertTrue(any(x.isupper() for x in password))
self.assertTrue(any(x.islower() for x in password))
def test_number(self):
password = passwordGenerator.generatePassword()
self.assertTrue( any(x.isdigit() for x in password))
def test_unique_string(self):
array_of_pwd = []
for _ in itertools.repeat(None, 10):
array_of_pwd.append(passwordGenerator.generatePassword())
# print array_of_pwd[-1] #f you want to print our passwords
self.assertFalse([item for item, count in collections.Counter(array_of_pwd).items() if count > 1])
if __name__ == '__main__':
unittest.main()
|
'''
###TODO:
plot on map
compare with regular passport rankings
make it not read any file
find to taiwan
'''
def logger(text):
if logHuh == True:
print(text)
def workWithLog(argz):
logHuh=False
nArgz=[]
if len(argz) > 1 and argz[1]=='log' :
logHuh=True
logger('###log: logging')
nArgz.append(argz[0])
for i in range(2, len(argz)):
nArgz.append(argz[i])
return nArgz
if logHuh==False:
return False
def ppWrite(contents,filename):
#write to file with prettiness
wrt = open('./wikitext/'+filename+'.txt', 'w')
i=0
while i < len(contents):
letter = contents[i]
if letter=="\\":
i=i+1
if contents[i]=="n":
wrt.write("\n")
else:
wrt.write(letter)
else:
wrt.write(letter)
i = i + 1
wrt.close()
def checkValidCountry(nation):
logger("###log: checking validity of "+nation)
nation=nation.strip()
nation=nation.replace('-', ' ')
nation=nation.replace('_', ' ')
nation=nation.lower()
nation=nation.title()
if nation == 'Usa' or nation == 'Us':
nation='United States'
if nation == 'Uae':
nation='United Arab Emirates'
if nation == 'Uk':
nation='United Kingdom'
#check if it exists
exists=False
for i in range(len(cdList)):
if nation.lower() == cdList[i]['country'].lower():
exists=True
if exists==False and webhuh!=True:
print('Error: Invalid country name, '+nation+' entered ')
print('enter \"list\" as argument to see all valid countries')
raise SystemExit()
if exists==False and webhuh==True:
logger('###log: checked validity of '+nation+'. it is not valid')
return False
return nation
def handleArgs(st):
f=''
for i in range(st, len(argz)):
f = f + argz[i] + ' '
nation=f.strip()
nation=checkValidCountry(nation)
return nation
def listValidCountries():
for i in range(len(cdList)):
print(cdList[i]['country'])
def getreply(payload):
url = 'https://en.wikipedia.org/w/api.php?'
# get stuff from url while injecting payload
import requests
logger('###log: Making API request to wikipedia...' )
try:
r = requests.get(url=url, params=payload)
except requests.exceptions.RequestException :
print('Error: Could not establish connectiion to Wikipedia\nCheck your internet connection and try again')
raise SystemExit()
# jData = json.loads(r.content)
jData = r.json()
return (jData)
def getRefTable():
try:
import a2_weightsTable
logger('###log: imported a2_weightsTable.py')
except ImportError:
logger('###log: could not import a2_weightsTable.py ; Using hardcoded weights ')
nTable = [
{'weight': 1.0, 'templates': ['free'], 'desc': 'Freedom of Movement'},
{'weight': 0.9, 'templates': ['yes','yes '], 'desc': 'Visa not Required'},
{'weight': 0.7, 'templates': ['Optional', 'yes-no'], 'desc': 'Visa on Arrival'},
{'weight': 0.5, 'templates': ['yes2'], 'desc': 'Electronic Visa'},
{'weight': 0.4, 'templates': ['no','no ', 'n/a'], 'desc': 'Visa is required'},
{'weight': 0.0, 'templates': ['black', 'BLACK'], 'desc': 'Travel not Allowed'},
]
# write weights table to file
import pprint
c_list = open('a2_weightsTable.py', 'w')
c_list.write('refTable = ' + pprint.pformat(nTable))
c_list.close()
logger('###log: created a2_weightsTable.py ')
else:
nTable = a2_weightsTable.refTable
return nTable
def find_demonym(nation):
flag = False
for i in range(len(cdList)):
if cdList[i]['country'].lower() == nation.lower():
flag = True
return cdList[i]['demonym']
if flag == False:
print('nation & demonym of '+nation+' not found in country_list')
def getGDPtable(): #get info from wikipedia , get wikitext from that , creates the GDPtable and returns it
try:
import a3_GDPtable
logger('###log: imported GDPtable')
except (ImportError, SyntaxError):
logger('###log: cound not import GDPtable')
payload = {
"action": "query",
"format": "json",
"prop": "revisions",
"titles": "List_of_countries_by_GDP_(nominal)",
"rvprop": "content",
"rvlimit": "1",
"rvsection": "1"
}
jData = getreply(payload)
# go inside the nest
jData = jData['query']
jData = jData['pages']
pageNo = list(jData)[0]
jData = jData[pageNo]
jData = jData['revisions']
contents = (str)(jData[0])
### make a list of all the countries and their GDPs (newest available)
# use regex to find
import re
x = re.compile(r'{{[fF]lag\|.*?}}.*?\|\|.*?[\|]{1}?.*?[\|]{1}?[\-}]{1}?', re.DOTALL)
gdpDATA = x.findall(contents)
del contents
GDPtable = []
for i in range(len(gdpDATA)):
t = gdpDATA[i]
# snip tail text
t = (t[0:len(t) - 4])
# find country
y = re.compile(r'{{[fF]lag\|.*?}}')
theCountry = y.findall(t)[0]
theCountry = theCountry[7:len(theCountry) - 2]
# replace accented names with a unique substring without accents to match
if 'voire' in theCountry:
theCountry = 'Ivory Coast'
if 'ncipe' in theCountry:
theCountry = 'Sao Tome and Principe'
if 'Cura' in theCountry:
theCountry = 'Curacao'
# find gdp
y = re.compile(r'{{nts\|.*?}}')
p = y.findall(t)
theGDP = ''
if len(p) <= 0:
j = len(t) - 1
while j >= 0:
if t[j] == '|':
theGDP = t[j + 1:len(t)]
break
j = j - 1
else:
theGDP = p[0]
theGDP = theGDP[6:len(theGDP) - 2]
# remove commas from theGDP and convert to integer
theGDP = float(''.join(i for i in theGDP if i.isdigit()))
theGDP = float("{0:.3f}".format(theGDP))
aDic = {'Country': theCountry, 'GDP': theGDP}
GDPtable.append(aDic)
# write gdp table to file
import pprint
c_list = open('a3_GDPtable.py', 'w')
c_list.write('#uses the first gdp that matches the country \n')
c_list.write('#Ivory Coast, Sao Tome and Principe and Curacao may have been de accented \n')
c_list.write('GDPtable = ' + pprint.pformat(GDPtable))
c_list.close()
logger('###log: created a3_GDPtable.py ')
else:
GDPtable = a3_GDPtable.GDPtable
return (GDPtable)
def find_gdp(nation):
flag = False
for i in range(len(gTable)):
if (gTable[i]['Country'] in nation) or (nation in gTable[i]['Country']):
flag = True
return gTable[i]['GDP']
if flag == False:
logger('###error: gdp for '+nation+' not found in gTable')
class country:
__name = ''
__rank = False
__gdp = 0
#__pppCapita = 0
#__population = 0
__gdpAxsScore = 0.0
__visaScoreList = [] #stores dictionaries with keys, country and visaScore
__demonym = ''
__url = ''
def createUrl(self): #creates url for visa requirements
self.__url='https://en.wikipedia.org/wiki/Visa_requirements_for_'+self.__demonym+'_citizens'
if self.__demonym=='Monegasque':
self.__url='https://en.wikipedia.org/wiki/Visa_requirements_for_Mon%c3%a9gasque_citizens'
def wiki2wText(self,nationality):
# get info from wikipedia and returns wikitext
# check if wikitext exists
PATH = './wikitext/WT-' + nationality + '.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
logger("###log: wikitext file exists and is readable for "+ nationality)
else:
# find rvsection
logger("###log: wikitext file is not readable for "+ nationality)
payload = {
"action": "parse",
"format": "json",
"prop": "sections",
"page": 'Visa_requirements_for_' + nationality + '_citizens'
}
if self.__demonym=='Monegasque':
payload['page']='Visa_requirements_for_Mon\u00E9gasque_citizens'
t = getreply(payload)
t = t['parse']
sections = t['sections']
f = False
for i in range(len(sections)):
# print(sections[i]['anchor']+' is anchor at index '+i+' for '+nationality)
if sections[i]['anchor'].lower() == 'visa_requirements' or sections[i]['anchor'].lower() == 'visa_requirements_by_country':
rvsection = sections[i]['number']
f = True
break
if f == False:
logger('###log: visa_requirements section not found in wiki page for ' + nationality)
payload = {
"action": "query",
"format": "json",
"prop": "revisions",
"titles": 'Visa_requirements_for_' + nationality + '_citizens',
"rvprop": "content",
"rvlimit": "1",
"rvsection": rvsection
}
if self.__demonym=='Monegasque':
payload['titles']='Visa_requirements_for_Mon\u00E9gasque_citizens'
jData = getreply(payload)
# go inside the nest
jData = jData['query']
jData = jData['pages']
pageNo = list(jData)[0]
jData = jData[pageNo]
jData = jData['revisions']
contents = (str)(jData[0])
# write to file with prettiness
ppWrite(contents, 'WT-'+nationality )
logger('###log: got api Data / wikiTable for the ' + nationality + ' citizens ')
return contents
def getTotGDP_Access(self,currentNation, WT): #gets visa score for the country
def getScore(cvList, currentNation): #create list of dictionaries and find final score
def findWeight(level):
flag = False
for i in range(len(refTable)):
found = False
for j in range(len(refTable[i]['templates'])):
if level.lower() == refTable[i]['templates'][j].lower():
found = True
break
if found:
return float("{0:.3f}".format((float(refTable[i]['weight']))))
if flag == False:
logger('###error: template not found in refTable. template was ' + level)
return (0)
def findDesc(level):
flag = False
for i in range(len(refTable)):
found = False
for j in range(len(refTable[i]['templates'])):
if level.lower() == refTable[i]['templates'][j].lower():
found = True
break
if found:
return refTable[i]['desc']
if flag == False:
logger('###error: template not found in refTable. template was ' + level)
return ('n/a')
GDP_AccessList = []
tDic = {}
total_GDP_Access = 0
# find for currentNation
found = 0
for j in range(len(gTable)):
if (currentNation in gTable[j]['Country']) or (gTable[j]['Country'] in currentNation):
tsuff = gTable[j]['GDP'] * findWeight('free')
tDic = {'Country': currentNation, 'VisaTemplate': 'free',
'GDP_Access': float("{0:.3f}".format(tsuff)), 'VisaRequirement': 'Freedom of Movement'}
GDP_AccessList.append(tDic)
total_GDP_Access = total_GDP_Access + gTable[j]['GDP']
found = 1
break
if found == 0:
logger('###log: no GDP_Access for ' + currentNation + ' to itself')
# now the rest of the countries
for i in range(len(cvList)):
found = 0
for j in range(len(gTable)):
if (cvList[i]['country'] in gTable[j]['Country']) or (gTable[j]['Country'] in cvList[i]['country']):
tsuff = gTable[j]['GDP'] * findWeight(cvList[i]['visaTemplate'])
tsuff = float("{0:.3f}".format(tsuff))
tDic = {'Country': cvList[i]['country'], 'VisaTemplate': cvList[i]['visaTemplate'],
'GDP_Access': tsuff , 'VisaRequirement': findDesc(cvList[i]['visaTemplate'])}
GDP_AccessList.append(tDic)
total_GDP_Access = total_GDP_Access + tsuff
found = 1
break
if found == 0:
logger('###log: no GDP_Access for ' + currentNation + ' to ' + cvList[i]['country'])
import pprint
c_list = open('./GDP_Access/GdpAxs'+find_demonym(currentNation) + '.py', 'w')
c_list.write('#GDP Access List for' + currentNation + ' \n')
c_list.write('GDPtable = ' + pprint.pformat(GDP_AccessList))
c_list.close()
logger('###log: created GdpAxs' + currentNation + '.py ')
GDP_AccessList=sorted(GDP_AccessList, key = lambda i: i['GDP_Access'],reverse=True)
self.__visaScoreList = GDP_AccessList
return total_GDP_Access
def createCV_List(cvList): # create list of dictionaries of country and template(visaReq)
neuCV_list = []
cvDic = {}
cExhauster=[]
for i in range(len(cdList)):
cExhauster.append(cdList[i]['country']) #use to make sure countries are only accesed once
for i in range(len(cvList)):
###find Country
x = re.compile(r'{{ *?[fF][lL][aA][gG] *[|].*?}}')
c = x.findall(cvList[i])[0]
# find name
x = re.compile(r'name=.*?}')
if len(x.findall(c)) != 0:
c = x.findall(c)[0]
c = c[5:-1]
else:
# remove state
x = re.compile(r'lag\|[^}]*?\|')
if len(x.findall(c)) != 0:
c = x.findall(c)[0]
c = c[4:-1]
else:
# find regularly
x = re.compile(r'lag\|[^}]*?}')
c = x.findall(c)[0]
c = c[4:-1]
###find visa template
beginer = 0
ender = 0
saveEnd = False
for j in range(5, len(cvList[i]) - 2):
if cvList[i][j] == '{' and cvList[i][j + 1] == '{':
beginer = j + 2
# print('found { {')
saveEnd = True
elif cvList[i][j] == '|' and saveEnd == True:
ender = j
# print('found | ')
break
v = cvList[i][beginer:ender]
cvDic = {'country': c, 'visaTemplate': v}
#check if the country is in country_list
there=False
for i in range(len(cExhauster)):
if c==cExhauster[i] :
there=True
cExhauster.remove(c)
break
elif 'ncipe' in c or 'voir' in c:
there=True
#hmm
break
if there==True:
neuCV_list.append(cvDic)
else:
logger('###log: excluded '+ str(cvDic['country'])+' from '+currentNation)
return neuCV_list
# read wiki table
wikitable = open('./wikitext/WT-'+find_demonym(currentNation) + '.txt', 'r')
wTxt = wikitable.read()
wikitable.close()
# use regex to find
import re
y = re.compile(r'[|] *?{{ *[fF][lL][aA][gG] *[|].*?}}[^}\\\|]*?\n[^}\\\|]*?[|][^}\\\|]*?{{.*?[|].*?}}')
regX_found = y.findall(wTxt)
cvList = list(regX_found)
# create list of dictionaries of country and template(visaReq)
cvList = createCV_List(cvList)
# hardcode to remove accents
for i in range(len(cvList)):
if 'voire' in cvList[i]['country']:
cvList[i]['country'] = 'Ivory Coast'
if 'ncipe' in cvList[i]['country']:
cvList[i]['country'] = 'Sao Tome and Principe'
logger('###log: number of countries found in wiki" for ' + currentNation + ' = ' + str(len(cvList)))
score = getScore(cvList, currentNation)
#convert to trillion
score=score/1000000.0
score = float("{0:.3f}".format(score))
return score
def gen_gdpAxsScore(self):
WT=self.wiki2wText(self.__demonym)
self.__gdpAxsScore = self.getTotGDP_Access(self.__name,WT)
def gen_Rank(self,scoreList):
count=1
for i in range(len(scoreList.z)):
if scoreList.z[i]['Score'] > self.__gdpAxsScore:
count+=1
self.__rank=count
return self.get_Rank()
def __init__(self, name): #TODO: add population and pppcapita
self.__name = name
self.__demonym = find_demonym(name)
self.createUrl()
self.__gdp = find_gdp(name)
self.gen_gdpAxsScore()
self.createUrl()
def get_name(self):
return self.__name
def get_demonym(self):
return self.__demonym
def get_gdp(self):
return self.__gdp
def get_gdpAxsScore(self):
return self.__gdpAxsScore
def get_visaScoreList(self):
return self.__visaScoreList
def get_url(self):
return self.__url
def get_Rank(self):
return self.__rank
def makeAndDisplayFor(nation):
x = country(nation)
print('\n{}'.format( x.get_url()))
print('\nGDP Access Score for {} is {} Trillion USD'.format( x.get_name() , x.get_gdpAxsScore()))
if scoreListExists==True:
print('Rank is {} out of {} countries\n'.format(x.gen_Rank(scoreList),len(scoreList.z)))
return x
def loopThroughAllCountries():
scoreSheet = []
for i in range(len(cdList)):
ctry = cdList[i]['country']
aCountry = country(ctry)
scoreSheet.append(aCountry)
logger('###log: Score Sheet created.')
scoreSheet=sorted(scoreSheet, key = lambda i: i.get_gdpAxsScore(),reverse=True)
oFile = open('scoreList.py', 'w')
oFile.write('#This is the final list of GDP Access Scores in Trillions of US dollars \n')
oFile.write('z = [')
for i in range(len(scoreSheet)-1):
oFile.write('{ \'Country\': \''+scoreSheet[i].get_name()+'\', \'Score\': '+str(scoreSheet[i].get_gdpAxsScore())+' },\n')
oFile.write('{ \'Country\': \''+scoreSheet[len(scoreSheet)-1].get_name()+'\', \'Score\': '+str(scoreSheet[len(scoreSheet)-1].get_gdpAxsScore())+' }]')
oFile.close()
logger('###log: scoreList.py generated')
import scoreList
import csv
#csvOutputFile = open('0_scoreSheet.csv', 'w', newline='')
csvOutputFile = open('0_scoreSheet.csv', 'w')
outputWriter = csv.writer(csvOutputFile)
outputWriter.writerow([ 'Country' , 'Score in $T', 'Rank' , 'GDP in $M' , 'Demonym' , 'Wikipedia Page'])
outputWriter.writerow([ '' , '' ])
for i in range(len(scoreSheet)):
s=scoreSheet[i]
outputWriter.writerow([ s.get_name(), s.get_gdpAxsScore(), s.gen_Rank(scoreList), s.get_gdp(), s.get_demonym(), s.get_url() ])
csvOutputFile.close()
print(' 0_scoreSheet.csv generated')
return scoreSheet
def plotter(pltArgs,createhuh=False): #if pltArgs is None then just display top mid bottom
import matplotlib.pyplot as plt
import numpy as np
if scoreListExists==False:
print('###log: Cannot import scoreList.py generating it')
loopThroughAllCountries()
if scoreListExists==False:
print('Error: Cannot import scoreList.py')
raise SystemExit()
sList=scoreList.z
countries=[]
score=[]
def appendr(i):
countries.append(sList[i]['Country'])
score.append(float(sList[i]['Score']))
if len(sList[i]['Country'])>13:
return True
else:
return False
name2Long=False
if pltArgs == None:
logger("###log: getting top, middle and bottom to plot")
for i in range(7):
name2Long+=appendr(i)
i=int(len(sList)/2)
for i in range(i-1,i+2):
name2Long+=appendr(i)
for i in range(len(sList)-5,len(sList)):
name2Long+=appendr(i)
else:
logger("###log: getting listed countries to plot")
conts=[]
#convert list to a useable string
sArgs=','
for i in range(len(pltArgs)):
sArgs+=pltArgs[i]+' '
sArgs+=','
#print(sArgs)
#extract countries from list
commaPos=0
for i in range(1,len(sArgs)):
if sArgs[i]==',':
j=commaPos+1
tCon=''
while sArgs[j]!=',':
tCon+=sArgs[j]
j+=1
tCon=checkValidCountry(tCon)
if tCon!= False:
logger('###log: found '+tCon+' in pltArgs')
conts.append(tCon)
commaPos=j
#find info to plot
for kont in conts:
for k in range(len(sList)):
if sList[k]['Country']==kont:
name2Long+=appendr(k)
y_pos = np.arange(len(countries))
plt.barh(y_pos, score, align='center', alpha=0.75,)
plt.yticks(y_pos, countries)
plt.xticks(rotation=0)
plt.xlabel('GDP Access Score in Trillions of US Dollars')
plt.ylabel('Civilian Passports of ')
plt.xlim(20)
if pltArgs == None:
plt.title('Bottom 5, Middle 3 and Top 7 Civilian Passports')
if not name2Long:
plt.subplots_adjust(left = 0.210)
else:
plt.subplots_adjust(left = 0.320)
if webhuh==False:
PATH='./0_plot.png'
if not (os.path.isfile(PATH) and os.access(PATH, os.R_OK)):
plt.savefig(PATH)
logger('###log: created 0_plot.png')
plt.show()
return
else:
#create for web version
if createhuh==True:
PATH='./static/images/0_plot.png'
if not (os.path.isfile(PATH) and os.access(PATH, os.R_OK)):
plt.savefig(PATH)
logger('###log: created /static/images/0_plot.png')
else:
import random
locAndFile='./static/images/plot/last_plot_'+str(random.randint(000000, 999999))+'.png'
plt.savefig(locAndFile)
plt.close('all')
logger('###log: saved plot to '+locAndFile)
return locAndFile
def compare( argee ):
logger('###log: comparing')
print(argee)
# remove this part if logic needs to change
if 'plot' in argz :
argz.remove('plot')
if 'show' in argz :
argz.remove('show')
p=''
q=''
pos=-1
for i in range(len(argee)):
if argee[i]=='vs':
pos=i
for i in range(1,pos):
p+=argee[i]+' '
p=p[0: len(p)-1]
p=checkValidCountry(p)
for i in range(pos+1,len(argee)):
q+=argee[i]+' '
q=q[0: len(q)-1]
q=checkValidCountry(q)
# display error in web ver
if (q==None or p==None) and webhuh==True:
return None
a = country( p )
b = country( q )
if a.get_gdpAxsScore() < b.get_gdpAxsScore():
a,b = b,a
p,q = q,p
difL=[]
avL=a.get_visaScoreList()
bvL=b.get_visaScoreList()
#fill the difference list, difL
for i in range( len( avL ) ) :
for j in range( len(bvL) ):
if avL[i]['Country'].lower() == bvL[j]['Country'].lower() :
if avL[i]['VisaRequirement'] != bvL[j]['VisaRequirement'] :
difL.append( { 'Country': avL[i]['Country'] ,
'GDP_Access_Difference': float("{0:.3f}".format(avL[i]['GDP_Access']-bvL[j]['GDP_Access'])),
'aVisaRequirement': avL[i]['VisaRequirement'] ,'bVisaRequirement': bvL[j]['VisaRequirement'] } )
difL=sorted(difL, key = lambda i: abs(i['GDP_Access_Difference']),reverse=True)
logger('###log: sorted difference list, difL')
## output result
if webhuh==True:
if scoreListExists==False:
logger('###log: ScoreList does not exist. creating...')
loopThroughAllCountries()
return difL,a.get_gdpAxsScore(),a.gen_Rank(scoreList),a.get_name(),b.get_name(), b.gen_Rank(scoreList), b.get_gdpAxsScore()
#print the list
print('\nHere is the list of differences ordered in ascending order of the magnitude of the difference\n')
print('The + and - signs identify the countries that are easier to access from the assigned country\n')
for i in range( len(difL)-1, -1, -1):
dMsg=''
if difL[i]['GDP_Access_Difference'] > 0:
dMsg='+ '
else:
dMsg='- '
dMsg=dMsg+difL[i]['Country']+' : '
if len(difL[i]['Country'])+5 < 8*4:
dMsg=dMsg+'\t'
if len(difL[i]['Country'])+5 < 8*3 :
dMsg=dMsg+'\t'
if len(difL[i]['Country'])+5 < 8*2:
dMsg=dMsg+'\t'
dMsg=dMsg+'\t {} \t vs \t {}'.format(difL[i]['aVisaRequirement'],difL[i]['bVisaRequirement'])
print(dMsg)
if scoreListExists==False:
print('\n\t(+) {} = {} vs {} = {} (-)\n'.format( p , a.get_gdpAxsScore(),
b.get_gdpAxsScore(), q ))
else:
print('\n\t(+) {} = {} [#{}] vs [#{}] {} = {} (-)\n'.format( p , a.get_gdpAxsScore(),
a.gen_Rank(scoreList), b.gen_Rank(scoreList), b.get_gdpAxsScore(), q ))
def helpr():
print(
"\n *You can modify the weights in the a2_weightsTable.py and the program"
+"\n ....will use those weights ; else it will use the hardcoded weights\n"
+"\n *\"a2_weightsTable.py\" is generated after the first run\n"
+"\n *The ranks will be displayed after first execution without arguments\n"
+"\n\n==> Here's the list of arguments you can use...\n\n"
+"\n-> `<country>` to find GDP access score for the country input as country\n"
+"\n-> `<country1> vs <country2>` to get a detailed comparison of the access each"
+"\n ....of the two passports grants ordered by the magnitude of difference\n"
+"\n-> `all` to generate a CSV file with all scores\n"
+"\n-> `list` to get a list of valid countries\n"
+"\n-> `show` to open up the created csv file\n"
+"\n-> `plot` to plot countries on a bar graph\n"
+"\n-> `log` before any other argument to get all actions performed, output"
+"\n ....to the terminal\n"
+"\n"
)
############# WEB VERSION
def webbie():
from flask import Flask, request, render_template
app=Flask(__name__)
def refreshPlotFolder():
nuPath="./static/images/plot/"
if os.path.isdir(nuPath):
import shutil
shutil.rmtree(nuPath)
os.makedirs(nuPath)
@app.route('/')
def index():
return render_template("index.html")
@app.route('/country/<countree>')
def test(countree):
x = country(checkValidCountry(countree))
return render_template("country.html",
cName=x.get_name(), cScore=x.get_gdpAxsScore() , cURL=x.get_url(),
cvList=x.get_visaScoreList() )
@app.route('/compare/<c1>-vs-<c2>')
def compareW(c1,c2):
print(c1,c2)
s='blah '+c1+' vs '+c2
ag=s.split()
logger('###log: argument from url is '+str(ag))
difL, aS,aR,aN,bN,bR,bS =compare(s.split())
if difL==None:
return 'Fatal Error: at least one country is invalid'
return render_template("compare.html",rank1=aR,country1=aN,score1=aS,
difL=difL, rank2=bR,country2=bN,score2=bS)
@app.route('/plot', methods = ['POST', 'GET'])
def plotCustom():
if request.method == 'POST':
arg=[]
for i in range(3):
arg.append(request.form['country'+str(i)]+',')
refreshPlotFolder()
url=plotter(pltArgs=arg)
return render_template("plot.html", url =url, shw='block')
elif request.method == 'GET':
refreshPlotFolder()
url=plotter(pltArgs=['chigoo,', 'united states,', 'germany']) #TODO make work
return render_template("plot.html", url =url, shw='none')
@app.route('/plot/top')
def plotTop():
PATH='./static/images/0_plot.png'
if not (os.path.isfile(PATH) and os.access(PATH, os.R_OK)):
logger('###log: no file at ./static/images/0_plot.png ; creating... ')
plotter(None,True)
return render_template("top.html", url ='/static/images/0_plot.png')
app.run()
##################### RUNNING MAIN
import sys
import os
if not os.path.isdir('./wikitext/'):
os.makedirs('./wikitext/')
if not os.path.isdir('./GDP_Access/'):
os.makedirs('./GDP_Access/')
argz=sys.argv
logHuh=False
if workWithLog(argz)!=False:
argz=workWithLog(argz)
logHuh=True
webhuh=False
scoreListExists=False
try:
import scoreList
except ImportError:
logger('###log: scoreList does not exist')
else:
scoreListExists=True
refTable = getRefTable()
gTable = getGDPtable()
import a1_country_list
cdList = a1_country_list.countries
#work with arguments
if len(argz) > 1:
if argz[1]=='list':
listValidCountries()
elif argz[1]=='web':
webhuh=True
webbie()
elif argz[1]=='plot':
try:
if argz[2]=='top':
plotter(pltArgs=None)
else:
plotter(pltArgs=argz[2:])
except IndexError:
print('\n no arguments provided for plot ')
print(' use `top` after plot to get the top 7, bottom 5 and middle 3')
print(' or list countries with `,`\n')
elif argz[1]=='all':
loopThroughAllCountries()
elif argz[1]=='show':
PATH = './0_scoreSheet.csv'
if not (os.path.isfile(PATH) and os.access(PATH, os.R_OK)):
print('Error: CSV file not created yet\nRun with no arguments to generate it')
else:
os.system("xdg-open 0_scoreSheet.csv")
elif 'vs' in argz :
compare(argz)
else:
nation=handleArgs(1)
makeAndDisplayFor(nation)
else:
helpr()
|
def missed_cans( num_1, num_2 ):
sum = num_1 + num_2 - 1
return sum - num_1, sum - num_2
cans_num_1 = int( input( 'the number of cans the first man : ' ) )
cans_num_2 = int( input( 'the number of cans the second man : ' ) )
missed1, missed2 = missed_cans(cans_num_1, cans_num_2)
print(missed1)
print(missed2)
|
st = 'Print only the words that start with s in this sentence'
my_st = st.split(" ")
print(my_st)
for words in my_st:
if words.startswith('s') == True:
print(words)
print(list(range(0,11,2)))
for num in range(0,50):
if num % 3 == 0:
print(num)
st_2 = 'Print every word in this sentence that has an even number of letters'
my_st2 = st_2.split(" ")
print(my_st2)
for words in my_st2:
if len(words)%2 == 0:
print(words)
# Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number,
# and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
numrange = list(range(0,100))
print(numrange)
for num in numrange:
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 5 == 0:
print("Buzz")
elif num % 3 == 0:
print("Fizz")
else:
print(num)
st_3 = 'Create a list of the first letters of every word in this string'
my_st3 = st_3.split(" ")
print(my_st3)
first_letter_list = []
for words in my_st3:
first_letter_list.append(words[0])
print(first_letter_list) |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 19:32:16 2017
@author: rjr
Covering the implementation of a while loop
"""
# Setting variables
i = 0
numbers = []
while i<6:
print(f"At the top i is {i}")
numbers.append(i)
i += 1
print("Numbers now:", numbers)
print(f"At the bottom i is {i}")
print("The numbers")
for num in numbers:
print(num)
|
def funcion_par(num):
res = num % 2
if res == 0:
print(f"EL NUMERO {num} ES PAR ")
else:
print(f"EL NUMERO {num} ES IMPAR ")
def main():
num = int(input("DIGITE UN NUMERO: "))
funcion_par(num)
if __name__ == "__main__":
main() |
#######################################################
#
# MiniBurger.py
# Python implementation of the Class MiniBurger
# Generated by Enterprise Architect
# Created on: 19-6��-2021 18:39:45
# Original author: 70748
#
#######################################################
from .Hamburg import Hamburg
class MiniBurger(Hamburg):
def __init__(self) -> None:
super().__init__("Mini Hamburger")
def box(self):
print("box {}".format(self.name))
def cook(self):
print("cook {}".format(self.name))
def ready(self):
print("Prepare ingredients")
|
# def get_words(sentence):
# return list(filter((lambda x: len(str(x)) > 0), str(sentence).split(sep=' ')))
#
#
# def get_word_count(sentence):
# return get_words(sentence).count()
def get_word_freq_in_sentences(word, sentences):
"""
:param word: the word which frequency we calculate
:param sentences: a list of the sentences, representing the document / search space
:return: the number of occurrences of the given word in the search space. Letter case is ignored
"""
freq = 0
for sentence in sentences:
for w in sentence:
if str(word).lower() == str(w).lower():
freq += 1
return freq
def get_most_popular_word(sentences):
"""
Returns the most widely-used word among the given sentences
"""
word_map = {}
for sentence in sentences:
for word in sentence:
if word not in word_map:
word_map[word] = 1
word_map[word] = word_map[word] + 1
max_freq = 0
max_freq_word = ''
for key in word_map:
if word_map.get(key) > max_freq:
max_freq = word_map.get(key)
max_freq_word = key
return max_freq_word
def get_symbol_freq_in_senteces(symbol, sentences):
"""
:param symbol: The symbol which frequency we calculater
:param sentences: a list of the sentences, representing the document / search space
:return: the number of occurrences of the given symbol among the words in the search space.
"""
freq = 0
for sentence in sentences:
for w in sentence:
for char in w:
if char == symbol:
freq += 1
return freq
def get_punct_symbols():
return [',', '.', '!', '?', '-', ':', ';']
|
import sqlite3
conn = sqlite3.connect('test.db')
print("Opened database successfully")
# conn.execute('''CREATE TABLE USER_NAME
# (USER_ID INTEGER PRIMARY KEY AUTOINCREMENT,
# UNAME CHAR(64) NOT NULL,
# PASSWORD CHAR(128) NOT NULL,
# TYPE_OF_USER CHAR(10) NOT NULL);''')
conn.execute('''DROP TABLE POOL_OF_AWESOMENESS''')
conn.execute('''CREATE TABLE POOL_OF_AWESOMENESS
(ORDER_ID INTEGER PRIMARY KEY AUTOINCREMENT,
FLAG CHAR(1) NOT NULL,
BUYER_ID INTEGER ,
SELLER_ID INTEGER ,
QUANTITY INTEGER NOT NULL,
PRICE REAL NOT NULL,
STATUS CHAR(1) NOT NULL,
MOD_DATE_TIME TEXT)''')
print("Table created successfully")
conn.close() |
base=float(input("Digite a largura do terreno: . . ."))
altura=float(input("Digite o comprimento do terreno: . . ."))
area=base*altura
perimetro=(2*base)+(2*altura)
print("A area do terreno é:",area)
print("O perimetro do terreno é:",perimetro) |
qntkm = float(input("Digite o kilometro percorrido: "))
qntdias = float(input("Digite a quantidade de dias que ele foi alugado: "))
dias=qntdias*60
km=qntkm*0.15
print("O preço a pagar é a quantidade de {} dias mais {} quantidade de km rodados, totalizando em R$:{:.2f}".format(qntdias,qntkm,dias+km))
|
reais = float(input("Digite o valor a ser convertido: "))
dinheiro=reais/5.40
print("O valor R$:{:.2f} são US:{:.2f}".format(reais,dinheiro)) |
nome = input ('Qual é o seu nome? . . .')
print ("olá ",nome,"!, prazer em conhecelo!") |
"""
Desarrolle un programa que grafique los largos de las secuencias de Collatz
de los números enteros positivos menores que el ingresado por el usuario
"""
def Cantidad_Collatz(n):
if n == 1:
return 1
if n%2==0:
return 1 + Cantidad_Collatz(n//2)
else:
return 1+ Cantidad_Collatz(n*3+1)
n=int(input())
str_cantidad=""
for i in range(1,n+1):
cantidad= Cantidad_Collatz(i)
for j in range(cantidad):
str_cantidad += "*"
print(str_cantidad)
str_cantidad=""
|
####Ejercicio Numero 2, Busqueda de un entero en un arreglo
def Busqueda(lista, numero):
return numero in lista
lista = []
consulta = input("Ingrese una Lista seguido del Número a Buscar: ")
numero="";
end = False
for c in consulta :
if end :
if c == ',' or c == ' ':
pass
else :
numero +=c
elif c == '[' :
pass
elif c == "]" :
lista.append(numero)
numero=""
end=True
elif c == ',' :
lista.append(numero)
numero=""
else :
numero += c
print (Busqueda(lista,numero)) |
# unit test
import unittest
class sample(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("calls once before any tests in class")
@classmethod
def tearDownClass(cls):
print("calls once after all tests in class")
def setUp(self):
self.a = 10
self.b = 20
def tearDown(self):
print("end of test caese")
def test_add(self):
res = self.a + self.b
self.assertTrue(res == 30)
|
score = int(input("คะแนนที่ได้ : "))
while score != -1:
score = int(input("คะแนนที่ได้ : "))
print(score) |
from random import randint
from random import seed
seed(135)
class Reverser:
def reverse(self, num):
def to_bits(num):
def binary_sum(num1, num2):
a = []
b = []
c = []
dim = 13
for i in range(dim):
a.append(randint(-2**31, 2**31))
r = Reverser()
for i in range(dim):
b.append(r.reverse(a[i]))
for i in range(dim):
c.append(r.reverse(b[i]))
|
import random
from random import randint
from random import seed
seed(1941706)
i = []
for s in range(19601):
i.append(randint(1,35))
x = 0
def while_1():
while x < 5:
print(x + 1)
def while_2():
while x < 5:
if x == 4:
x = 0
print(x)
x += 1
def while_3():
global x
while x < 5:
print(x)
x += 1
def most_frequent_num(nums, max_num):
|
from random import randint
from random import choice
from random import seed
seed(135)
class P:
def __init__(self, lista = []):
self.lista = lista
def __getitem__(self, index):
decision = choice((-1, 1))
idx = (index + decision)
def __setitem__(self, index ,value):
self.lista[index] = value
def __repr__(self):
str_lista = ""
for i in self.lista:
str_lista += ", " + str(i)
return '[' + str_lista[2:] + ']'
def __len__(self):
return len(self.lista) - 1
a = []
for n in range(13):
value = randint(3, 33)
a.append(value)
p = P(a)
answer_1_true = "sem __getitem__(self, idx) a class P suporta indexing"
answer_2_true = p.__getitem__(0) == p[0]
answer_3_true = " é possível alterara o elementa na lista desta maneira p[index] = valor"
answer_4_true = " print(p)"
answer_5_true = len(p)
print(answer_1_true)
print(answer_2_true)
print(answer_3_true)
print(answer_4_true)
print(answer_5_true)
|
from random import seed
from random import choice
from random import randint
from string import ascii_letters
seed(1850201)
t = []
def random_string_generator():
f = ""
my_str = ""
for z in range(0,3):
my_str += choice(ascii_letters).lower()
for s in range(randint(1,20)):
idx = randint(1,len(my_str) - 1)
f += choice(my_str)
return f
def message_optimizator(my_str):
char_to_evaluate = my_str[0]
finalMessage = ""
counter = 1
char_occurence = 1
if len(my_str) == 1:
return my_str
for char in my_str[1:]:
counter += 1
if char_to_evaluate == char:
char_occurence += 1
if char_to_evaluate != char:
finalMessage += char_to_evaluate
finalMessage += str(char_occurence) if char_occurence > 1 else ''
char_to_evaluate = char
char_occurence = 1
if counter == len(my_str):
finalMessage += char_to_evaluate
finalMessage += str(char_occurence) if char_occurence > 1 else ''
return finalMessage
for z in range(19891):
f = random_string_generator()
l = message_optimizator(f)
t.append(l)
letter = choice(t[1])
def letter_occurence(letter, string):
idx = 0
counter = 0
for ch in string:
if ch != letter: continue
if ch == letter:
counter +=1
if idx < len(string) - 1:
num = int(string[idx + 1]) if string[idx + 1].isdigit() else 0
counter +=num
idx +=1
return counter
def max_num_occurences(lista):
lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
maxOccur = 0
choosenLetter =''
for cod in lista:
for letter in lowercase:
num = letter_occurence(letter, cod)
if num > maxOccur:
maxOccur = num
choosenLetter = letter
return choosenLetter, maxOccur
def find_word_with_bigger_length(lista, length):
newLength = length + 1
while(True):
for word in lista:
if len(word) == newLength:
return word
newLength += 1
# to run this program (in linux/mac):
#
# cat program.py answers_program.py | python3
# just to check
#print('list min = ', min(a))
#print('list max = ', max(a))
answer_1_true = letter_occurence(letter, t[1])
answer_2_true = min(t, key=len)
answer_3_true = t[3]
answer_4_true = max_num_occurences(t)
answer_5_true = len(t[5])
print(answer_1_true)
print(answer_2_true)
print(answer_3_true)
print(answer_4_true)
print(answer_5_true)
|
# Шукуров Фотех Фуркатович
# группа № 181-362
import random
mas = ["КИРИЛЛ", "МЕФОДИЙ"]
random.shuffle(mas)
name = input("Назовите одного из двух братьев, создателей старославянской азбуки: ")
nameUpper = name.upper()
if mas[0] == nameUpper:
print("Ты выиграл!")
else:
print("Я загадывал не это имя.\nПравильный ответ:\n\t\t" + str(mas[0].title()))
input("\n\n\tPress enter to exit")
|
# -*- coding: utf-8 -*-
from math import *
import math
try:
x = int(input("Введите значние X: \n"))
if x <=-2.5: y = -6/7*x-36/7
elif -2.5<x and x<2: y = x**3 + 1.5*x**2-2.5*x-3
elif 2<=x: y = -2*x + 10
print("X={0:.2f} Y={1:.2f}".format(x,y))
except:
print('Ошибка ввода.')
print("\n____________________\nЗадание№2\n")
def two_four():
if x>0 and y<0 and y<x-RADUIS:
true()
elif (x<0 and y>0) and y>x+RADUIS:
true()
else:
error()
def error():
print('Точка не принадлежит области')
def true():
print('Точка принадлежит области')
def one_three():
if x<0 and y<0 and y<-x-RADUIS:
true()
elif x>0 and y>0 and y>-x-RADUIS:
true()
else:
error()
try:
RADUIS = int(input('Введите радиус: \n'))
x = int(input('Введите значение X: \n'))
y = int(input('Введите значение Y: \n'))
po_r = sqrt(x**2+y**2) # point_radius
if math.fabs(x)<=RADUIS and math.fabs(y)<=RADUIS:
if po_r<=RADUIS:
if (x<0 and y>0) or (y<0 and x>0): #первая и четвертая четверть
two_four()
else:
error()
elif po_r>=RADUIS:
if (y>0 and x>0) or (x<0 and y<0):
one_three()
else:
error()
else:
error()
else:
print('Точка находится вне графика')
except:
print('404!')
|
import random
from Num_Racionales import *
class Matriz:
def __init__(self, nombre, filas, columnas):
self.nombre = nombre
self.filas = filas
self.columnas = columnas
self.elementos = []
def elem_Random(self):
elementos = []
for i in range(self.filas):
fila = []
for j in range(self.columnas):
fila.append(str(random.randint(-5, 5)))
elementos.append(fila)
self.elementos = list(elementos)
self.imprimir_Matriz()
def elementos_por_teclado(self):
print(f'........... {self.nombre} ...........')
elementos = []
for fila in range(1, self.filas+1, 1):
filastring = input(f'fila {fila}: ')
lista = []
numstring = ''
for i in filastring+',':
if i == ',':
lista.append(numstring)
numstring = ''
else:
numstring = numstring+i
elementos.append(lista)
self.elementos = list(elementos)
def imprimir_Matriz(self):
print(f'...........{self.nombre}..................')
for fila in self.elementos:
print(fila)
def multiplicar_por_Escalar(self, escalar):
self.nombre = f'({self.nombre})^t'
new_matriz = []
escalar = Numero_Racional(escalar)
for fila in range(0, self.filas, 1):
new_matriz.append([])
for columna in range(0, self.columnas, 1):
new_matriz[fila].append(escalar.multiplicar_dividir(self.elementos[fila][columna]))
self.elementos = list(new_matriz)
def convertir_Transpuesta(self):
print(f'SE APLICO LA TRANSPUESTA A LA MATRIZ')
self.nombre = '(' + self.nombre + ')^t'
new_matriz = []
for fila in range(0, self.columnas, 1):
new_matriz.append([])
for columna in range(0, self.filas, 1):
new_matriz[fila].append(self.elementos[columna][fila])
self.elementos = list(new_matriz)
self.filas, self.columnas = self.columnas, self.filas
def sumar_Matrices(self, matriz1, matriz2, restar=False):
if (matriz1.filas == matriz2.filas) and (matriz1.columnas == matriz2.columnas):
self.filas = matriz1.filas
self.columnas = matriz1.columnas
sig_menos = Numero_Racional('-1')
for fila in range(0, matriz1.filas, 1):
self.elementos.append([])
for columna in range(0, matriz1.columnas, 1):
elem_matriz1 = Numero_Racional(matriz1.elementos[fila][columna])
if restar:
elem_matriz2 = sig_menos.multiplicar_dividir(matriz2.elementos[fila][columna])
else:
elem_matriz2 = matriz2.elementos[fila][columna]
self.elementos[fila].append(elem_matriz1.sumar_restar(elem_matriz2))
else:
print('Las matrices deben ser de la misma dimension para sumar')
def restar_Matrices(self, matriz1, matriz2):
self.sumar_Matrices(matriz1, matriz2, True)
def Elemento_delProducto(self, matriz1, matriz2, fila, columna):
if (fila > matriz1.filas) or (columna > matriz2.columnas):
print('El elemento no existe')
return None
else:
if matriz1.columnas == matriz2.filas:
elemento_ij = '0'
for k in range(0, matriz1.columnas, 1):
acumulador = Numero_Racional(elemento_ij)
numero = Numero_Racional(matriz1.elementos[fila-1][k])
elemento_ij = acumulador.sumar_restar(numero.multiplicar_dividir(matriz2.elementos[k][columna-1]))
return elemento_ij
else:
print('Las operacion no esta definida')
return None
def multiplicar_Matrices(self, matriz1, matriz2):
new_matriz = []
for fila in range(0, matriz1.filas, 1):
new_matriz.append([])
for columna in range(0, matriz2.columnas, 1):
new_matriz[fila].append(self.Elemento_delProducto(matriz1, matriz2, fila+1, columna+1))
self.elementos = list(new_matriz)
self.filas = matriz1.filas
self.columnas = matriz2.columnas
def permutar_filas(self, fila1, fila2, matriz):
print(f'---P{fila1}{fila2}---')
new_matriz = []
for i in range(len(matriz)):
if i == fila1-1:
new_matriz.append(matriz[fila2-1])
elif i == fila2-1:
new_matriz.append(matriz[fila1-1])
else:
new_matriz.append(matriz[i])
return new_matriz
def multiplicar_fila(self, fila, escalar, matriz):
print(f'---M{fila}({escalar})---')
new_matriz = []
constante = Numero_Racional(escalar)
fila_mult = []
for elemento in matriz[fila-1]:
fila_mult.append(constante.multiplicar_dividir(elemento))
for i in range(len(matriz)):
if i == fila-1:
new_matriz.append(fila_mult)
else:
new_matriz.append(matriz[i])
return new_matriz
def sumar_filas(self, fila_a_modificar, fila2, escalar, matriz):
print(f'---A{fila_a_modificar}{fila2}({escalar})---')
new_matriz = []
constante = Numero_Racional(escalar)
fila_mult =[]
for elemento in matriz[fila2-1]:
fila_mult.append(constante.multiplicar_dividir(elemento))
for i in range(len(matriz)):
if i == fila_a_modificar-1:
new_fila = []
for j in range(len(fila_mult)):
constante2 = Numero_Racional(fila_mult[j])
new_fila.append(constante2.sumar_restar(matriz[i][j]))
new_matriz.append(new_fila)
else:
new_matriz.append(matriz[i])
return new_matriz
class Matriz_Cuadrada(Matriz):
def __init__(self, nombre, filas):
super().__init__(nombre, filas=filas, columnas=filas)
def get_determinante(self):
return self.determinante(self.elementos)
def determinante(self, matriz):
if len(matriz) == 2:
diag_prin = Numero_Racional(matriz[0][0])
diag_prin = Numero_Racional(diag_prin.multiplicar_dividir(matriz[1][1]))
diag_sec = Numero_Racional('-1')
diag_sec = Numero_Racional(diag_sec.multiplicar_dividir(matriz[0][1]))
diag_sec = diag_sec.multiplicar_dividir(matriz[1][0])
return diag_prin.sumar_restar(diag_sec)
else:
trayecto, linea = self.recorrido(matriz)
resultado = Numero_Racional('0')
for n in range(len(matriz)):
if trayecto == 'columnas':
coeficiente, matriz_menor = self.decompostor(n, linea, matriz)
coeficiente = Numero_Racional(coeficiente)
else:
coeficiente, matriz_menor = self.decompostor(linea, n, matriz)
coeficiente = Numero_Racional(coeficiente)
termino = coeficiente.multiplicar_dividir(self.determinante(matriz_menor))
resultado = Numero_Racional(resultado.sumar_restar(termino))
return resultado.reprecentacion
def recorrido(self, matriz):
trayecto = 'filas'
linea = 0
cantid_ceros = 0
for fila in range(len(matriz)):
cont_2 = self.contador_ceros('filas', fila, matriz)
if cont_2 > cantid_ceros:
trayecto = 'filas'
linea = fila
cantid_ceros = cont_2
for columna in range(len(matriz)):
cont_2 = self.contador_ceros('columnas', columna, matriz)
if cont_2 > cantid_ceros:
trayecto = 'columnas'
linea = columna
cantid_ceros = cont_2
return (trayecto, linea)
def contador_ceros(self, trayecto, indice, matriz):
contador = 0
if trayecto == 'filas':
for columna in range(len(matriz)):
if matriz[indice][columna] == '0':
contador += 1
return contador
else:
for fila in range(len(matriz)):
if matriz[fila][indice] == '0':
contador += 1
return contador
def decompostor(self, fila_cofactor, colum_cofactor, matriz):
if (fila_cofactor + colum_cofactor) % 2 == 0:
cofactor = matriz[fila_cofactor][colum_cofactor]
else:
sign_negativo = Numero_Racional('-1')
cofactor = sign_negativo.multiplicar_dividir(matriz[fila_cofactor][colum_cofactor])
matriz_menor = []
for i in range(len(matriz)):
new_fila = []
for j in range(len(matriz)):
if i != fila_cofactor and j != colum_cofactor:
new_fila.append(matriz[i][j])
if new_fila != []:
matriz_menor.append(new_fila)
return (cofactor, matriz_menor)
def agregar_Inversa(self, matriz):
matriz_ejerc = matriz.elementos
determinante = self.determinante(matriz_ejerc)
if determinante == '0':
print('La matriz cuadrada ingresada no tiene inversa')
else:
identidad = self.matriz_Identidad(len(matriz_ejerc))
for columna in range(len(identidad)):
if matriz_ejerc[columna][columna] == '0':
fila_permutar = self.fila_optima(columna, columna, matriz_ejerc)
matriz_ejerc = self.permutar_filas(fila_permutar+1, columna+1, matriz_ejerc)
imprimir_elems(matriz_ejerc)
identidad = self.permutar_filas(fila_permutar+1, columna+1, identidad)
imprimir_elems(identidad)
elem_princip = Numero_Racional(matriz_ejerc[columna][columna])
matriz_ejerc = self.multiplicar_fila(columna+1, elem_princip.invertirso(), matriz_ejerc)
imprimir_elems(matriz_ejerc)
identidad = self.multiplicar_fila(columna+1, elem_princip.invertirso(), identidad)
imprimir_elems(identidad)
for fila in range(len(identidad)):
if fila != columna:
elemento = Numero_Racional(matriz_ejerc[fila][columna])
matriz_ejerc = self.sumar_filas(fila+1, columna+1, elemento.multiplicar_dividir('-1'), matriz_ejerc)
imprimir_elems(matriz_ejerc)
identidad = self.sumar_filas(fila+1, columna+1, elemento.multiplicar_dividir('-1'), identidad)
imprimir_elems(identidad)
self.elementos = list(identidad)
def matriz_Identidad(self, dimension):
matriz = []
for i in range(dimension):
fila = []
for j in range(dimension):
if i == j:
fila.append('1')
else:
fila.append('0')
matriz.append(fila)
return matriz
def fila_optima(self, fila, columna, elementos):
fila_optima = None
for i in range(fila+1, len(elementos)):
if elementos[i][columna] != '0':
fila_optima = i
break
return fila_optima
def imprimir_elems(lista):
for fila in lista:
print(fila)
def precentacion():
print('Bienvenido a mi codigo')
print('me llamo Jose y esta es un proyecto en el que he estado trabajando')
print('Es una demostracion de una matriz inversa en Python')
def despedida():
print('Muchas gracias por correr este codigo')
print('me hacia ilucion :3')
print('twitter para sugerencias: @JosMaraOrozcoS1.')
if __name__ == '__main__':
precentacion()
a = Matriz_Cuadrada('A', 3)
a.elementos_por_teclado()
a_inv = Matriz_Cuadrada('A^-1', 3)
a_inv.agregar_Inversa(a)
a_inv.imprimir_Matriz()
despedida()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def checkio(words: str) -> bool:
'''
tmp = []
for word in words.split(' '):
if word.isalpha():
tmp.append(word)
if len(tmp) == 3:
return True
else:
tmp = []
return False
'''
count_word = 0
for word in words.split():
if word.isdigit():
count_word = 0
else:
count_word += 1
if count_word == 3:
return True
return False
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(checkio("1 1 1 1"))
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") |
import base64, urllib2
from PIL import Image
"""
This iteration uses list slicing to get the values at the even and odd pairs.
Once you get this the operation is similar to that in level11.py.
"""
username = 'huge'
password = 'file'
base64string = base64.b64encode('%s:%s' % (username, password))
link = urllib2.Request('http://www.pythonchallenge.com/pc/return/cave.jpg')
link.add_header('Authorization', 'Basic %s' % base64string)
page = urllib2.urlopen(link)
img = Image.open(page)
pixels = list(img.getdata())
even = []
[even.append(i) for i in pixels[::2]]
odd = []
[odd.append(i) for i in pixels[1::2]]
even_img = Image.new(img.mode , img.size)
even_img.putdata(even)
print even_img.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.