text stringlengths 37 1.41M |
|---|
'''
필요할 때만 삽입하여 정렬
정렬되지 않은 배열과 정렬할 배열을 따로 정의
정렬할 배열에 새 값을 넣으면 정렬된 상태를 유지하기위해
비교함
[4, 6, 2, 5]
4vs6 <- 2
'''
input = [4, 6, 2, 9, 1]
def insertion_sort(array):
for i in range(1, len(array)):
for j in range(i):
if array[i-j-1] > array[i-j]:
array[i-j-1], array[i-j] = array[i-j], array[i-j-1]
else:
break
insertion_sort(input)
print(input)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
abcdario='abcdefghijklmnñopqrstuvwxyz'
simbolos = '¡?=)(/&%$#"!°|*[]-_,;.'
def gen(largo):
a = ''
for letra in range(0, largo):
var = random.randrange(4)
if 0 == var:
a += abcdario[random.randrange(26)]
elif 1 == var:
a += abcdario[random.randrange(26)].upper()
elif 2 == var:
a += simbolos[random.randrange(21)]
else:
a += str(random.randrange(9))
return(a)
elecc = input('numero de caracteres --> ')
print(gen(int(elecc)))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
print "Funkcija, kura tiks apskatīta šajā kodā, ir funkcija y=arcsin(x)."
print "Matemaatikā jebkuru funkciju var uzrakstīt, izmantojot Teilora rindu, kas ir"
print "atsevišķu elementu summa."
print "Funkciju y=arcsin(x) pēc izvirzījuma Teilora rindā var uzrakstīt šādi:"
print ""
print ""
print " 500"
print " ------------"
print " \\ \\"
print " \\"
print " \\ 2k+1"
print " \\ (2k)! * x"
print " s(x)= -----------------------"
print " / 2 2k"
print " / (k!) * (2k + 1) * 2"
print " /"
print " / /"
print " ------------"
print " k = 0"
print ""
print ""
print "Katru nākamo Teilora rindas locekli var aprēķināt, esošo locekli"
print "reizinot ar rekurences reizinātāju R."
print "Rekurences reizinātājs izskatās šādi:"
print ""
print ""
print " 2 2"
print " x * (2k - 1)"
print " R = ---------------"
print " 2k (2k + 1)"
print ""
print ""
print "Aprēķināsim funkciju Jūsu ievadītajam argumentam."
from math import asin
def mans_asinuss (x):
k = 0
a = x
S = a
print "Izdruka no liet. f. a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
while k < 500:
k = k + 1
R = x*x*(2*k-1)*(2*k-1)/((2*k)*(2*k+1))
a = a * R
S = S + a
if k == 499:
print "Izdruka no liet. f. a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
if k == 500:
print "Izdruka no liet. f. a%d = %6.2f S%d = %6.2f\n Šīs vērtības tika aprēķinātas ar standarta funkcijas aprēķinu, kas\n ņemts no math bibliotēkas."%(k,a,k,S)
return S
x = 1. * input("Lietotāj, ievadi tādu argumentu (x), lai izpildītos nosacījums 0 < x > 1: ")
y = asin(x)
print "Standarta asin (%6.2f) = %6.2f"%(x,y)
yy = mans_asinuss(x)
print "Mans asin (%.2f) = %6.2f"%(x,yy)
k = 0
a = x
S = a
print "a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
while k < 500:
k = k + 1
a = a*x*x*(2*k-1)*(2*k-1)/((2*k)*(2*k+1))
S = S + a
if k == 499:
print "a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
if k == 500:
print "a%d = %6.2f S%d = %6.2f\n Šīs vērtības tika aprēķinātas, izmantojot izvirzījumu\n Teilora rindā."%(k,a,k,S)
print "Tā kā vērtības, kuras tika aprēķinātas ar math oriģinālo funkciju, ir"
print "vienādas ar vērtībām, kuras aprēķinātas, izmantojot Teilora rindu,"
print "tad var secināt, ka summas funkcija ir izveidota pareizi."
print "Beigas!"
|
class BankAccount:
def __init__(self, int_rate = 0.01, balance = 0):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if(self.balance > 0):
self.balance -= amount
else:
print("insufficent funds")
return self
def display_account_info(self):
print(f"${self.balance}")
def yield_interest(self):
self.balance += (self.balance * self.int_rate)
return self
ba1 = BankAccount()
ba1.display_account_info()
ba1.deposit(300).deposit(200).deposit(1000).withdraw(100).display_account_info()
ba2 = BankAccount()
ba2.display_account_info()
ba2.deposit(500).deposit(500).withdraw(50).withdraw(50).withdraw(50).withdraw(50).yield_interest().display_account_info()
class User:
bank_name = "Chris' Bank of Eternal Debt"
def __init__(self, name, email):
self.name =name
self.email = email
self.account = BankAccount(int_rate=0.02, balance=0)
def deposit(self, amount):
self.account.deposit(amount)
return self
def withdrawl(self, amount):
self.account.withdraw(amount)
return self
def display_balance(self):
print(self.account.display_account_info())
return self
chris = User("Christopher Frederick", "chris@email.com")
nysha = User("Nysha Sims", "nysha@wmail.com")
chris.deposit(600).deposit(18000).display_balance()
nysha.deposit(700).withdrawl(100).deposit(700).display_balance() |
#https://www.codewars.com/kata/5a4e3782880385ba68000018/train/python
def balanced_num(number):
import math
d = [int(x) for x in str(number)]
if len(d) == 1:
return "Balanced"
elif len(d)%2 == 0:
ref = int(len(d)/2)
if sum(d[0:ref-1]) == sum(d[ref+1:len(d)]):
return "Balanced"
else:
return "Not Balanced"
else:
ref = math.ceil((len(d)/2))
if sum(d[0:ref-1]) == sum(d[ref:len(d)]):
return "Balanced"
else:
return "Not Balanced"
|
#https://www.codewars.com/kata/5a53a17bfd56cb9c14000003/train/python
def disarium_number(number):
num = [int(n) for n in str(number)]
output = []
for i, n in enumerate(num):
output.append(n**(i+1))
if sum(output) == number:
return "Disarium !!"
else:
return "Not !!" |
#inheritance method
class Employee:
increament = 1.5
def __init__(self,fname,lname,salary):
self.fname = fname
self.lname= lname
self.salary = salary
def increase(self):
self.salary = int(self.salary *Employee.increament)
@classmethod
def change_increament(cls,amount):
cls.increament = amount
@classmethod
def from_st(cls,emp_str):
fname,lname,salary = emp_str.split("-")
return cls(fname,lname,salary)
@staticmethod
def is_open(day):
if (day== 'sunday'):
return False
else:
return True
harry = Employee.from_st("harry-jackson-70000")
#print(harry.salary)
#print(harry.is_open("monday"))
class programmer(Employee):
pass
jon = programmer("jon","snow",10000000)
Employee.change_increament(3)
jon.increase()
print(jon.salary)
#jon.increase()
#print(jon.salary)
#jon.change_increament(3)
#print(jon.salary)
|
"""This module is here to map the space for the Tello
"""
class Coordinates:
"""Class for representation of coordinates in 3 dimensions.
"""
def __init__(self, x_axis=0, y_axis=0, z_axis=0):
"""3 coordinates to create representation of the tello in space.
:param x_axis: X axis in space (default value = 0).
:type x_axis: int.
:param y_axis: Y axis in space (default value = 0).
:type y_axis: int.
:param z_axis: Z axis in space (default value = 0).
:type z_axis: int.
"""
self.x_axis = x_axis
self.y_axis = y_axis
self.z_axis = z_axis
def __str__(self):
"""Representation of the Coordinate Object.
:return: Representation of the Coordinates.
:rtype: str.
"""
return "Coordinates : | X : {} | Y : {} | Z : {} |".format(self.x_axis, self.y_axis, self.z_axis)
def __repr__(self):
"""Equivalent function than __str__ for the object in python interpreter.
:return: Representation of the Coordinates Object.
:rtype: str.
"""
return "X : {} | Y : {} | Z : {}".format(self.x_axis, self.y_axis, self.z_axis)
class Speed:
"""Class for representation of speed states.
"""
def __init__(self, x_speed=0, y_speed=0, z_speed=0):
"""Representation of the speed of the Tello.
:param x_speed: X speed state in space (default value = 0).
:type x_speed: int.
:param y_speed: Y speed state in space (default value = 0).
:type y_speed: int.
:param z_speed: Z speed state in space (default value = 0).
:type z_speed: int.
"""
self.x_speed = x_speed
self.y_speed = y_speed
self.z_speed = z_speed
def __str__(self):
"""Representation of the Speed state Object.
:return: Representation of the speed.
:rtype: str.
"""
return "Speed states (cm.s⁻¹): | X : {} | Y : {} | Z : {} |".format(self.x_speed, self.y_speed, self.z_speed)
def __repr__(self):
"""Equivalent function than __str__ for the object in python interpreter.
:return: Representation of the Speed Object.
:rtype: str.
"""
return "X : {} | Y : {} | Z : {}".format(self.x_speed, self.y_speed, self.z_speed)
class Velocity:
"""Class for representation of the velocity of the Tello drones
"""
def __init__(self, x_velocity=0, y_velocity=0, z_velocity=0):
"""Representation of the velocity of the Tello drones.
:param x_velocity: Velocity of the X axis.
:type x_velocity: int.
:param y_velocity: Velocity of the y axis.
:type y_velocity: int.
:param z_velocity: Velocity of the Z axis.
:type z_velocity: int.
"""
self.x_velocity = x_velocity
self.y_velocity = y_velocity
self.z_velocity = z_velocity
def __str__(self):
"""Representation of the Velocity Object
:return: Representation of the Velocity.
:rtype: str.
"""
return "Velocity states (cm.s⁻²)| X : {} | Y : {} | Z : {} |".format(self.x_velocity, self.y_velocity, self.z_velocity)
def __repr__(self):
"""Equivalent function than __str__ for the object in python interpreter.
:return: Representation of the Coordinates Object.
:rtype: str.
"""
return "X : {} | Y : {} | Z : {}".format(self.x_velocity, self.y_velocity, self.z_velocity)
|
serial = int(input())
def main():
max_pwr, chances = 0, 0
max_x, max_y, max_size = None, None, None
max_pwr_changed = True
""" FINDS MAX POWER FOR EVERY SQUARE SIZE """
while max_pwr_changed: # assuming if max doesn't change after increasing
chances += 1 # square size, it will never change
max_pwr_changed = False
for y in range(0, 300):
for x in range(0, 300):
total_pwr, size = largest_square_at_corner(x, y, -100, 1, chances, 0)
if total_pwr > max_pwr:
max_pwr = total_pwr
max_x = x
max_y = y
max_size = size
max_pwr_changed = True
print(max_x, max_y, max_size, sep=',')
def largest_square_at_corner(x, y, past_pwr, size, chances, prev_size):
""" FIND THE MAXIMUM POWER POSSIBLE AT A GIVEN CORNER CELL """
total_pwr = 0
if x + size > 300 or y + size > 300 or chances == 0:
return past_pwr, prev_size
for xi in range(x, x + size):
for yi in range(y, y + size):
total_pwr += get_pwr(xi, yi)
if total_pwr >= past_pwr:
return largest_square_at_corner(x, y, total_pwr, size+1, chances, size)
else:
return largest_square_at_corner(x, y, past_pwr, size+1, chances-1, prev_size)
def get_pwr(x, y):
""" FINDS THE POWER AT A GIVEN CELL """
global serial
rack_id = x + 10
pwr = rack_id * y
pwr += serial
pwr *= rack_id
if pwr < 100:
pwr = 0
else:
pwr = int(str(pwr)[-3])
pwr -= 5
return pwr
main()
|
# Time: O(m * n)
# Space: O(m + n)
#
# Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
#
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
#
# For example,
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
#
# X X X X
# X X X X
# X X X X
# X O X X
#
class Solution:
# @param board, a 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
if not board:
return
current = []
for i in xrange(len(board)):
current.append((i, 0))
current.append((i, len(board[0]) - 1))
for i in xrange(len(board[0])):
current.append((0, i))
current.append((len(board) - 1, i))
while current:
i, j = current.pop()
if board[i][j] in ['O', 'V']:
board[i][j] = 'V'
for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 'O':
board[x][y] = 'V'
current.append((x, y))
for i in xrange(len(board)):
for j in range(len(board[0])):
if board[i][j] != 'V':
board[i][j] = 'X'
else:
board[i][j] = 'O'
if __name__ == "__main__":
board = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
Solution().solve(board)
print board
|
# zadanie 3: Zmodyfikuj kod związany z losowaniem liczb z przedziału od 1 do 10, tak aby obliczał przybliżoną wartość oczekiwaną obliczoną jako średnią (z prób). Uśrednienie ma nastąpić 1m razy (milion razy).
from random import Random
rand = Random()
loopCount=1
randSum=0
amountOfDraws = 1000000
while True:
if(loopCount == x):
break
loopCount = loopCount+1
randSum = randSum + rand.randint(1, 10)
print("Avg:",randSum/amountOfDraws) |
# zadanie 6: Napisz program, który wyznacza odległość Levenshteina dla dwóch zadanych łańcuchów znaków.
def levenDist(s1,s2):
if not s1:
return len(s2)
if not s2:
return len(s1)
return min(levenDist(s1[1:], s2[1:]) + (s1[0] != s2[0]),
levenDist(s1[1:], s2) + 1,
levenDist(s1, s2[1:]) + 1)
str1 = input("Write first string: ")
str2 = input("Write second string: ")
print("Levenshtein distance for your strings: ", levenDist(str1,str2)) |
from function import Function
class _DifferentialEvolution(object):
"""
Differential Evolution private base class, holds algorithm parameters.
Public members initialized in constructor:
pop_size -- population size, integer constant greater than zero
(recomended at least 10x number of function parameters)
max_gen -- maximum generations, integer constant greater than zero
(recomended at least 1000)
cr -- crossover constant, float in [0,1]
f -- factor of differential amplification, float in [0,2]
Example:
>>> def func(x):
... return x[0]**2 + x[1]**2
>>>
>>> sphere = Function(func, dim=2, lower=(-2.048,)*2, upper=(2.048,)*2)
>>> de = _DifferentialEvolution(pop_size=40, max_gen=1000, cr=0.9, f=0.9)
>>> de._check_func(sphere)
>>>
"""
def __init__(self, pop_size=20, max_gen=1000, cr=0.9, f=0.5):
"""
Initializes public members pop_size, max_gen, cr and f.
Arguments:
pop_size -- population size, integer constant greater than zero
(recomended at least 10x number of function parameters)
max_gen -- maximum generations, integer constant greater than zero
(recomended at least 1000)
cr -- crossover constant, float in [0,1]
f -- factor of differential amplification, float in [0,2]
Exceptions:
ValueError
"""
if not pop_size > 0:
raise ValueError('pop_size must be integer greater than zero')
if not max_gen > 0:
raise ValueError('max_gen must be integer greater than zero')
if not (cr >= 0 and cr <= 1):
raise ValueError('cr must be float in range [0,1]')
if not (f >= 0 and cr <= 2):
raise ValueError('f must be float in range [0,2]')
self.pop_size = pop_size
self.max_gen = max_gen
self.cr = cr
self.f = f
def _check_func(self, func):
"""
Checks if func is instance of Function.
Arguments:
func -- function to be minimized, instance of Function
Exceptions:
TypeError
"""
if not isinstance(func, Function):
raise TypeError('func must be instance of Function')
if __name__ == "__main__":
import doctest
doctest.testmod()
|
""" Program to find LCA of node1 and node2 using one traversal of
Binary tree
It handles all cases even when node1 or node2 is not there in tree
"""
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def findLCAUtil(root, node1, node2, v):
"""
Additional function to traverse through tree
"""
# Base Case
if root is None:
return None
if root.key == node1 :
v[0] = True
return root
if root.key == node2:
v[1] = True
return root
# Look for keys in left and right subtree
left_lca = findLCAUtil(root.left, node1, node2, v)
right_lca = findLCAUtil(root.right, node1, node2, v)
# If both of the above calls return Non-NULL, then one key
# is present in once subtree and other is present in other,
# So this node is the LCA
if left_lca and right_lca:
return root
# Otherwise check if left subtree or right subtree is LCA
return left_lca if left_lca is not None else right_lca
def find(root, k):
# Base Case
if root is None:
return False
# If key is present at root, or if left subtree or right
# subtree , return true
if (root.key == k or find(root.left, k) or
find(root.right, k)):
return True
# Else return false
return False
def lca(root, node1, node2):
# Initialize node1 and node2 as not visited
v = [False, False]
lca = findLCAUtil(root, node1, node2, v)
# Returns LCA only if both node1 and node2 are present in tree
if (v[0] and v[1] or v[0] and find(lca, node2) or v[1] and
find(lca, node1)):
return lca
# Else return None
return None
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
lca = lca(root, 3, 7)
if lca is not None:
print ("LCA(3, 7) = ", lca.key)
else :
print ("Keys are not present")
|
def func1(x):
if x>1:
return func2(x-1)
return 1
def func2(x):
if x>1:
return x+1
return 1
def main():
print(func1(3))
main()
|
for i in range(1, 10, 2):
aux = i + 6
for j in range(3):
print(f"I={i} J={aux}")
aux -= 1
|
"""
Escreva um algoritmo que leia 2 números e imprima o resultado da divisão do primeiro pelo segundo. Caso não for possível mostre a mensagem “divisao impossivel” para os valores em questão.
Entrada
A entrada contém um número inteiro N. Este N será a quantidade de pares de valores inteiros (X e Y) que serão lidos em seguida.
Saída
Para cada caso mostre o resultado da divisão com um dígito após o ponto decimal, ou “divisao impossivel” caso não seja possível efetuar o cálculo.
Obs.: Cuide que a divisão entre dois inteiros em algumas linguagens como o C e C++ gera outro inteiro. Utilize cast :)
"""
entrada1 = input()
for x in range(int(entrada1)):
entrada2 = input()
aux = entrada2.split(" ")
dividendo = int(aux[0])
divisor = int(aux[1])
if divisor == 0:
print("divisao impossivel")
else:
print(f"{(dividendo / divisor):.1f}")
|
entrada = input()
coord = entrada.split(" ")
x = float(coord[0])
y = float(coord[1])
if x == y == 0:
print("Origem")
elif x == 0:
print("Eixo Y")
elif y == 0:
print("Eixo X")
elif x < 0 and y > 0:
print("Q2")
elif x > 0 and y > 0:
print("Q1")
elif x > 0 and y < 0:
print("Q4")
else:
print("Q3")
|
for x in range(3):
print(x)
if 10 == type(int):
print("int")
print(type(int))
else:
print("nao")
print(type(int))
f = 1.23
print(f.is_integer())
# False
f_i = 100.0
s = f_i.is_integer()
print(s)
# True
inteiro = 10
decimal = 10.0
resp = decimal.is |
"""
Leia um valor inteiro N. Este valor será a quantidade de valores inteiros X que serão lidos em seguida.
Mostre quantos destes valores X estão dentro do intervalo [10,20] e quantos estão fora do intervalo, mostrando essas informações.
Entrada
A primeira linha da entrada contém um valor inteiro N (N < 10000), que indica o número de casos de teste.
Cada caso de teste a seguir é um valor inteiro X (-107 < X <107).
Saída
Para cada caso, imprima quantos números estão dentro (in) e quantos valores estão fora (out) do intervalo.
"""
entrada = int(input())
dentro = 0
fora = 0
for x in range(entrada):
aux = int(input())
if aux >=10 and aux <=20:
dentro += 1
else:
fora += 1
print(f"{dentro} in")
print(f"{fora} out")
|
class Point:
def move(self):
print("Move")
def draw(self):
print("Draw")
point1 = Point()
point1.draw()
point1.move()
point1.name = "Temitope"
print(point1.name)
point2 = Point()
point2.draw()
point2.move() |
'''
for x in range(5):
for y in range(2):
print(x, y)
# Exercise
# 1. Print Letter - F
numbers = [5, 2, 5, 2, 2]
for x in numbers:
print("x" * x)
#Solution 2
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ""
for count in range(x_count):
output += 'x'
print(output)
'''
numbers = [2, 2, 2, 2, 5]
for x_count in numbers:
output = ""
for count in range(x_count):
output += 'x'
print(output) |
# If- Statement
is_hot = True
if is_hot:
print("Drink lot of water")
print("Enjoy your day!\n \n")
is_hot = False
if is_hot:
print("Drink lot of water")
print("Enjoy your day! \n")
is_hot = True
is_cold = True
if is_hot:
print("Drink lot of Water")
elif is_cold:
print("Wear warm clothing")
else:
print("It is a lovely day.\n")
is_hot = False
is_cold = True
if is_hot:
print("Drink lot of Water")
elif is_cold:
print("Wear warm clothing")
else:
print("It is a lovely day.\n")
is_hot = False
is_cold = False
if is_hot:
print("Drink lot of Water")
elif is_cold:
print("Wear warm clothing")
else:
print("It is a lovely day.\n")
# Classwork
price = 10000000
good_credit = True
if good_credit:
down_payment = price * 0.1
else:
down_payment = price * 0.2
print("The down payment is: $%s" %(down_payment))
|
# lambda expressions
def square(num): return num**2
print(square(5))
# Check if a number is even
def even(num): return num % 2 == 0
print(even(4))
def square2(num): return num**2
print(square2(10))
def even1(num): return num % 2 == 0
print(even1(4))
|
#!/usr/bin/env python
import sys
def ceasar(rot, text):
ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
abc = 'abcdefghijklmnopqrstuvwxyz'
res = ''
for ch in text:
if ch >= 'A' and ch <= 'Z':
res += ABC[(ord(ch)-ord('A')+rot) % 26]
elif ch >= 'a' and ch <= 'z':
res += abc[(ord(ch)-ord('a')+rot) % 26]
else:
res += ch
return res
if len(sys.argv) != 3:
print 'Usage: ./ceasar.py <rot> <text>'
print 'Example: ./ceasar.py 3 "SyAhmi Fauzi"'
else:
rot = int(sys.argv[1])
text = sys.argv[2]
print ceasar(rot, text)
|
"""
Create a line plot
=====================
.. currentmodule:: pygeode
Plots a simple line plot using :func:`showvar()`
"""
import pygeode as pyg
import numpy as np
import pylab as pyl
N = 100
p = 0.9
# Create some normally distributed random numbers
rng = np.random.default_rng(seed = 1)
eps = rng.standard_normal(N)
# Generate an AR1 time series
ar1 = np.empty(N)
ar1[0] = eps[0]
for i in range(1, N):
ar1[i] = p * ar1[i-1] + eps[i]
# Create an N-element time axis with no calendar
t = pyg.yearlessn(N)
# Create a pygeode variable from the numpy array
AR1 = pyg.Var((t,), values = ar1, name = 'AR1')
# Plot AR1
ax = pyg.showvar(AR1)
pyl.ion()
ax.render()
# %%
# We can use the formatting options from the underlying :func:`matplotlib.pyplot.plot()`
# command to further customize the plot
pyl.ioff()
ax = pyg.showvar(AR1, color = 'g', marker = 'o', linewidth = 1, linestyle = '--', markersize = 4)
# We can also customize the axis labels and locators
ax.setp(ylim = (-3.5, 3.5), ylabel = '')
#ax.setp_xaxis(major_locator = pyg.timeticker.DayLocator(t, [15]))
pyl.ion()
ax.render()
|
"""
Plot 2 contours and remove the last one
========================================
Use :func:`showvar()` to plot the wind as a filled contour plot and the temperature as grey contour lines on the same axes.
"""
import pylab as pyl
import pygeode as pyg
import numpy as np
from pygeode.tutorial import t2
pyl.ioff()
# Load Temperature and zonal wind
u = t2.U(time='10 May 2002', pres=(1000,500)).mean(pyg.Lon)
T = t2.Temp(time='10 May 2002', pres=(1000,500)).mean(pyg.Lon)
# Change vertical axis to log(pressure) with a scale height of 7 km
u_H = u.replace_axes(pres=u.pres.logPAxis(H=7000))
T_H = T.replace_axes(pres=T.pres.logPAxis(H=7000))
ax = pyg.plot.AxesWrapper()
pyg.showvar(T_H, clines=10, colors='grey', axes=ax)
ax_wrapper =pyg.showvar(u_H, min=10, cdelt=10, ndiv=3, fig=1, cmap=pyl.cm.BuPu_r, axes=ax)
ax.setp(title = 'Plot of temperature and zonal mean wind')
pyl.ion()
ax_wrapper.render()
###########################################################
# ``ax_wrapper.axes[0].plots`` contains a list of all the plotted objects
#
print(*ax_wrapper.axes[0].plots, sep="\n")
###############################################################################################
# Remove the temperatue contours from the list and plot the zonal wind contours and colourbar only.
#
ax_wrapper.axes[0].plots = ax_wrapper.axes[0].plots[1:]
ax.setp(title = 'Plot of zonal mean wind')
ax_wrapper.render()
###############################################################################################
print(*ax_wrapper.axes[0].plots, sep="\n")
|
def abrir(mapa):#Abre el mapa en filas
return [x.split() for x in open(mapa,'r')]
def columnas(mapa):#Convierte el mapa a columnas
return [[fila[i] for fila in mapa] for i in range(len(mapa))]
def recorrer(mapa, x, y):
print(x,y)
print(mapa[x][y])
if y==(len(mapa[x])-1)and x==(len(mapa)-1):
return True
elif y < (len(mapa[x])-1):
return recorrer(mapa,x,y+1)
elif x < (len(mapa)-1):
return recorrer(mapa,x+1,0)
else:
return False
def rec(mapa, x):
if x==(len(mapa)):
return True
elif x<(len(mapa)):
print(mapa[x])
return rec(mapa,x+1)
else:
return False
def caminar(mapa, x, y, camino):
if len(mapa[x])==1:
caminar.append(mapa[x][y])
return camino
elif len(mapa[x])==2 and len(mapa[x+1])==2:
caminar.append(mapa[x][y])
caminar.append(mapa[x][y+1])
caminar.append(mapa[x+1][y])
caminar.append(mapa[x+1][y+1])
return camino
elif y < (len(mapa[0])):
derecha(mapa, x, y, camino)
elif x < (len(mapa)):
def derecha(mapa, x, y, camino):
if y == (len(mapa[0])):
del mapa[0]
return caminar(mapa, x+1, len(mapa[x])-1,camino)
elif y < (len(mapa[0])):
camino.append(mapa[0][y])
return derecha(mapa,x,y+1,camino)
'''
def abajo(mapa, y, camino):
if y == (len(mapa[len(mapa)-1])):
del mapa[len(mapa)-1]
return camino
elif y < (len(mapa[len(mapa)-1])):
camino.append(mapa[len(mapa)-1][y])
return derecha(mapa,y+1,camino)
'''
print(caminar(abrir("mapa.txt"),0,0,[]))
|
#!/usr/bin/python
import sys
# 5045616
def print_intersection(set1,set2):
intersection = set1
intersection &= set2
print_list(sorted(list(intersection)))
def print_list(iarray):
ans = ""
for i in range(len(iarray)-1):
iarray[i]=int(iarray[i])
ans += `iarray[i]` + ','
if(len(iarray) > 0):
ans += `int(iarray[len(iarray)-1])`
print ans
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.rstrip()
# ignore test if it is an empty line
if(0 == len(test)):
continue
inputs = test.split(";")
print_intersection(set(inputs[0].split(",")),set(inputs[1].split(",")))
test_cases.close()
|
#!/usr/bin/python
import sys
import math
class point:
def __init__(self,ilist):
self.cords = ilist
def maxfloat(guess = 1.0):
while(guess * 2 != guess):
guess = guess * 2
return guess
def find_min_distance(points_array):
min_sq_dist = maxfloat()
for i in range(len(points_array)):
for j in range(i+1,len(points_array)):
min_sq_dist = min(min_sq_dist,sq_dist(points_array[i],points_array[j]))
# print "best found = ", math.sqrt(min_sq_dist)
min_distance = math.sqrt(min_sq_dist)
# print min_distance
if(min_distance > 10000):
return "INFINITY"
else:
return '{0:.4f}'.format(min_distance)
def sq_dist(ipoint,jpoint):
sq_dist = 0
for i in range(len(ipoint.cords)):
sq_dist += (ipoint.cords[i]-jpoint.cords[i])**2
# print sq_dist
# print sq_dist
# print
return sq_dist
mypoints = list()
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if(0 == len(test)):
continue
if(1 == len(test.split())):
if(0 < len(mypoints)):
print find_min_distance(mypoints)
mypoints = list()
else:
mypoints.append(point(map(int,test.split())))
test_cases.close()
|
#!/usr/bin/python
import sys
def matrix_print(imat):
for i in range(len(imat)):
for j in range(len(imat[0])):
sys.stdout.write(`imat[i][j]`+" ")
print
def minimum_path(my_matrix):
size = len(my_matrix)
for j in range(size-2, -1, -1):
my_matrix[size - 1][j] += my_matrix[size - 1][j+1]
my_matrix[j][size - 1] += my_matrix[j+1][size - 1]
for k in range(size-2, -1, -1):
for j in range(size-2, -1, -1):
my_matrix[k][j] += min(my_matrix[k + 1][j], my_matrix[k][j + 1])
return my_matrix[0][0]
test_cases = open(sys.argv[1], 'r').readlines()
i = 0
while(i < len(test_cases)):
# ignore test if it is an empty line
if(0 == len(test_cases[i])):
i += 1
continue
size = int(test_cases[i].rstrip())
my_matrix = [[0 for j in range(size)] for k in range(size)]
for j in range(size):
i += 1
this_row = map(int,test_cases[i].rstrip().split(","))
for k in range(size):
my_matrix[j][k] = this_row[k]
print minimum_path(my_matrix)
i += 1
|
#!/usr/bin/python
import sys,itertools
def list_permutations(length, letters):
newletters = list(set(letters))
newletters = newletters * length
myperms = itertools.permutations(newletters,length)
mystringperms = list()
for i in myperms:
mystringperms.append("".join(i))
mystringperms = sorted(list(set(mystringperms)))
print ",".join(mystringperms)
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
# ignore test if it is an empty line
if(0 == len(test)):
continue
length = int(test.split(",")[0])
letters = list(test.split(",")[1].rstrip())
# print length, letters
list_permutations(length, letters)
test_cases.close()
|
#!/usr/bin/python
import sys
# determine if inum is happy
def is_happy(inum):
s = set() # start with the empty set
while((inum != 1) and (inum not in s)): # while we are neither 1 nor in a cycle
s.add(inum) # add inum to the set
inum = sum_square_of_digits(inum) # replace the number with the sum of the squares of its digits
return (1 == inum)
def sum_square_of_digits(inum):
ans = 0 # our accumulator
while(inum > 0):
ans += (inum % 10)**2 # add the square of the 1's place
inum //= 10 # right shift the number (in 10 speak)
return ans
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.rstrip()
if(0 == len(test)):
continue
if(is_happy(int(test))):
print 1
else:
print 0
test_cases.close()
|
#!/usr/bin/python
import sys
def uniquify(iarray):
iarray = sorted(list(set(iarray)))
ans = ""
for i in range(len(iarray)-1):
iarray[i]=int(iarray[i])
ans += `iarray[i]` + ','
ans += `int(iarray[len(iarray)-1])`
print ans
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.rstrip()
# ignore test if it is an empty line
if(0 == len(test)):
continue
# # 'test' represents the test case, do something with it
test = test.split(",")
uniquify(test)
test_cases.close()
|
#!/usr/bin/python
import sys
def sum_of_integers(iarray):
max_sum = 0
for start in range(0,len(iarray)): # this is the length of the sub arrays we're considering
for end in range(start+1,len(iarray)+1):
max_sum = max(max_sum,sum(iarray[start:end]))
return max_sum
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if(0 == len(test)):
continue
print sum_of_integers(map(int,test.split(",")))
test_cases.close()
|
#!/usr/bin/python
import sys
# A robot is located at the top-left corner of a 4x4 grid.
# The robot can move either up, down, left, or right,
# but can not visit the same spot twice.
# The robot is trying to reach the bottom-right corner of the grid.
def solutions_from(x,y,visited):
if(max(x,y) >= size):
return 0 # out of bounds
if(min(x,y) < 0):
return 0 # out of bounds
if((x,y) in visited):
return 0 # this is a path crossing which is illegal, so no solutions
else:
visited.add((x,y)) # add the one where we currently are
if((x,y) == (size-1,size-1)):
paths = 1 # there is exactly this way to get here since you can't leave and come back
else:
paths = (solutions_from(x+1,y,visited)
+ solutions_from(x-1,y,visited)
+ solutions_from(x,y+1,visited)
+ solutions_from(x,y-1,visited))
# the number of solutions using the current path is the
# number using the path and this square from any of the 4 directions
visited.remove((x,y)) # add the one where we currently are, so other paths can use it later
return paths # return the number of solutions from here
size = 4 # the grid is 4x4
visited = set()
print solutions_from(0,0,visited) # print the number of solutions starting from (0,0) with no other squares visited
|
#!/usr/bin/python
import sys
def a_mod_b(a, b):
return (a - ((a//b)*b))
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.rstrip()
# ignore test if it is an empty line
if(0 == len(test)):
continue
# # 'test' represents the test case, do something with it
inputs = test.split(",")
a = int(inputs[0])
b = int(inputs[1])
print a_mod_b(a,b)
test_cases.close()
|
#importing
import pygame, sys, random
#setting up basic stuff and variables
pygame.init()
size = width, height = 504, 504
row, column = 9,9
screen = pygame.display.set_mode((width, height))
white = (255,255,255)
black = (0,0,0)
#draw the grid
def draw_grid(w=None):
for x in range(column):
if x == 3 or x == 6:
w = 5
else:
w = 1
pygame.draw.line(screen, black, (x*width//column, 0), (x*width//column, height),w)
for y in range(row):
if y == 3 or y == 6:
w = 5
else:
w = 1
pygame.draw.line(screen, black, (0, y*height//row), (width, y*height//row), w)
numbers = list()
def add_number(x,y,number):
a = [x,y,number]
for m in numbers:
count = 0
if m[0] == a[0] and m[1] == a[1]:
return
if m[0] == x or m[1] == y:
if m[2] == number:
return
if 0 <= x <= 2 and 0 <= y <= 2 and 0 <= m[0] <= 2 and 0 <= m[1] <= 2 and number == m[2]: return
if 0 <= x <= 2 and 3 <= y <= 5 and 0 <= m[0] <= 2 and 3 <= m[1] <= 5 and number == m[2]: return
if 0 <= x <= 2 and 6 <= y <= 8 and 0 <= m[0] <= 2 and 6 <= m[1] <= 8 and number == m[2]: return
#
if 3 <= x <= 5 and 0 <= y <= 2 and 3 <= m[0] <= 5 and 0 <= m[1] <= 2 and number == m[2]: return
if 3 <= x <= 5 and 3 <= y <= 5 and 3 <= m[0] <= 5 and 3 <= m[1] <= 5 and number == m[2]: return
if 3 <= x <= 5 and 6 <= y <= 8 and 3 <= m[0] <= 5 and 6 <= m[1] <= 8 and number == m[2]: return
#
if 6 <= x <= 8 and 0 <= y <= 2 and 6 <= m[0] <= 8 and 0 <= m[1] <= 2 and number == m[2]: return
if 6 <= x <= 8 and 3 <= y <= 5 and 6 <= m[0] <= 8 and 3 <= m[1] <= 5 and number == m[2]: return
if 6 <= x <= 8 and 6 <= y <= 8 and 6 <= m[0] <= 8 and 6 <= m[1] <= 8 and number == m[2]: return
numbers.append(a)
def draw_numbers():
for num in numbers:
font = pygame.font.Font(None,60)
mytextsurface = font.render(str(num[2]), True, black)
screen.blit(mytextsurface, ((num[0]*width//column)+(width//column//4), (num[1]*height//row)+(height//row//4)))
def get_num(x, y):
global c
num = random.randint(1,9)
for num2 in numbers:
if num2[0] == x or num2[1] == y:
if num2[2] == num:
return
#(x = 0-2, y = 0-8)
if 0 <= x <= 2 and 0 <= y <= 2 and 0 <= num2[0] <= 2 and 0 <= num2[1] <= 2 and num == num2[2]: return
elif 0 <= x <= 2 and 3 <= y <= 5 and 0 <= num2[0] <= 2 and 3 <= num2[1] <= 5 and num == num2[2]: return
elif 0 <= x <= 2 and 6 <= y <= 8 and 0 <= num2[0] <= 2 and 6 <= num2[1] <= 8 and num == num2[2]: return
#(x = 3-5, y = 0-8)
elif 3 <= x <= 5 and 0 <= y <= 2 and 3 <= num2[0] <= 5 and 0 <= num2[1] <= 2 and num == num2[2]: return
elif 3 <= x <= 5 and 3 <= y <= 5 and 3 <= num2[0] <= 5 and 3 <= num2[1] <= 5 and num == num2[2]: return
elif 3 <= x <= 5 and 6 <= y <= 8 and 3 <= num2[0] <= 5 and 6 <= num2[1] <= 8 and num == num2[2]: return
#(x = 6-8, y = 0-8)
elif 6 <= x <= 8 and 0 <= y <= 2 and 6 <= num2[0] <= 8 and 0 <= num2[1] <= 2 and num == num2[2]: return
elif 6 <= x <= 8 and 3 <= y <= 5 and 6 <= num2[0] <= 8 and 3 <= num2[1] <= 5 and num == num2[2]: return
elif 6 <= x <= 8 and 6 <= y <= 8 and 6 <= num2[0] <= 8 and 6 <= num2[1] <= 8 and num == num2[2]: return
c = False
return num
c = True
def gen_board(limit):
global c
for i in range(limit):
X = random.randint(0, 2) * 3 + random.randint(0, 2)
Y = random.randint(0, 2) * 3 + random.randint(0, 2)
c = True
while c: Num = get_num(X, Y)
else: add_number(X, Y, Num)
gen_board(50)
print(numbers)
cursor = pygame.Rect((0),(0),width//column,height//row)
# Game loop.
while True:
screen.fill(white)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key >= 1073741913 and event.key <= 1073741921:
add_number(cursor.left//(width//column), cursor.top//(height//row), event.key - 1073741912)
if event.key == pygame.K_LEFT and cursor.left != 0: cursor.move_ip(-width//column, 0)
elif event.key == pygame.K_RIGHT and cursor.right != width: cursor.move_ip(width//column, 0)
elif event.key == pygame.K_UP and cursor.top != 0: cursor.move_ip(0, -height//row)
elif event.key == pygame.K_DOWN and cursor.bottom != height: cursor.move_ip(0, height//row)
elif event.type == pygame.QUIT:pygame.quit(), sys.exit()
#draw stuff
draw_grid()
draw_numbers()
pygame.draw.rect(screen,(0,255,0), cursor, 7)
#mendatory display commands
pygame.display.flip()
pygame.time.Clock().tick(60)
|
from typing import List
from typing import Optional
import copy
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def generateNextTree(self, newTree: List, index: int, target: int, n: int):
for i in range(index+1, 0, -1):
if newTree[i-1] == target:
newTree.insert(i-1, n)
if i+1 < len(newTree):
newTree.insert(i+1, None)
else:
newTree.append(None)
return i-1
return -1
def generateTreeLists(self, n: int) -> List[Optional[int]]:
treeLists = [[1]]
if n == 1:
return treeLists
for i in range(1, n):
nextTreeLists = []
for tree in treeLists:
newTree = copy.deepcopy(tree)
if tree[-1] == None:
newTree[-1] = i+1
else:
newTree.append(None)
newTree.append(i+1)
nextTreeLists.append(newTree)
index = len(tree) - 1
for target in range(i, 0, -1):
newTree = copy.deepcopy(tree)
ret = self.generateNextTree(newTree, index, target, i+1)
if ret == -1:
continue
index = ret
nextTreeLists.append(newTree)
nextTreeLists, treeLists = treeLists, nextTreeLists
return treeLists
def insert(self, tree: TreeNode, val: int):
if val < tree.val:
if tree.left == None:
tree.left = TreeNode(val)
else:
self.insert(tree.left, val)
elif val > tree.val:
if tree.right == None:
tree.right = TreeNode(val)
else:
self.insert(tree.right, val)
def convert(self, treeList: List) -> TreeNode:
tree = TreeNode(treeList[0])
for node in treeList[1:]:
if node == None:
continue
self.insert(tree, node)
return tree
def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
treeLists = self.generateTreeLists(n)
answer = []
for treeList in treeLists:
treeG = self.convert(treeList)
answer.append(treeG)
return answer
# help functions
def printTree(tree, outList):
if tree == None:
outList.append('null')
return
outList.append(tree.val)
if tree.left != None or tree.right!= None:
printTree(tree.left, outList)
printTree(tree.right, outList)
def printTreeList(treeList):
for tree in treeList:
outList = []
printTree(tree, outList)
print(outList)
if __name__ == '__main__':
sol = Solution()
ans = sol.generateTrees(4)
printTreeList(ans)
|
def search(array, element):
for x in range(len(array)):
if array[x] == element:
return x
return -1
Test_Case_1 = search(['a', 'b', 'c', 'd'], 'b') # 1
Test_Case_2 = search([1, 2, 3, 4, 5, 6], 4) # 3
|
import pandas as pd
from prettytable import PrettyTable
# An overview of the dataset considering the columns defined in groups as revealing of identities
# and also looking the text to detect the identities.
file_path ="train.csv"
# Filter the dataset based on some identity. An identity is identified if its grade is greater than 0.5.
def filter_frame_v2(frame, keyword=None, length=None):
if keyword:
frame = frame[frame[keyword] > 0.5]
if length:
frame = frame[frame['length'] <= length]
return frame
# Compute the rate of some identity is identified as toxic amongst the comments.
def class_balance_v2(frame, keyword, length=None):
frame = filter_frame_v2(frame, keyword, length)
return len(frame.query('toxic')) / len(frame)
wiki_data = pd.read_csv(file_path, sep = ',')
#create a new column to determine toxicity
wiki_data['toxic'] = wiki_data['target'] > 0.5
wiki_data['length'] = wiki_data['comment_text'].str.len()
#these are the groups in the dataset that have more than 500 examples in test
groups = ['black','christian','female',
'homosexual_gay_or_lesbian','jewish','male','muslim',
'psychiatric_or_mental_illness','white']
wiki_data = wiki_data.loc[:,['comment_text','toxic']+groups]
print('overall fraction of comments labeled toxic:', class_balance_v2(wiki_data, keyword=None))
print('overall class balance {:.1f}%\t{} examples'.format(
100 * class_balance_v2(wiki_data, keyword=None), len(wiki_data)))
print('\n')
for term in groups:
fraction = class_balance_v2(wiki_data, term)
frame = filter_frame_v2(wiki_data, term)
num = len(frame)
print('Proportion of identity {:s} in train: {:.3f}%'.format(term,100*(len(frame)/len(wiki_data.index))))
print('Proportion of toxic examples for {:10s} {:.1f}%\t{} examples'.format(str(term), 100 * fraction, num))
print('Overall proportion of toxic examples for {:10s} {:.1f}%\t'.format(str(term), 100 * (len(frame.query('toxic'))/len(wiki_data))))
print('\n')
# This is other way to compute the above loop using pandas group_by
# for each group, print the number of cases that are toxic and not toxic
# for x in groups:
# aux = wiki_data[ wiki_data[x] > 0.5 ] # for each group, select only elements that belong to that group
# wiki_grouped = aux.loc[:,['toxic',x]].groupby('toxic', as_index=False).count()
# print(wiki_grouped.to_string()+'\n')
# The same as above but instead of using the columns to determine identity search the text comment for occurring
# the identity term.
def filter_frame(frame, keyword=None, length=None):
"""Filters DataFrame to comments that contain the keyword as a substring and fit within length."""
if keyword:
if isinstance(keyword,list):
frame = frame[frame['comment_text'].str.contains('|'.join(keyword), case=False)]
else:
frame = frame[frame['comment_text'].str.contains(keyword, case=False)]
if length:
frame = frame[frame['length'] <= length]
return frame
def class_balance(frame, keyword, length=None):
"""Returns the fraction of the dataset labeled toxic."""
frame = filter_frame(frame, keyword, length)
return len(frame.query('toxic')) / len(frame)
print('\n')
print('overall fraction of comments labeled toxic:', class_balance(wiki_data, keyword=None))
print('overall class balance {:.1f}%\t{} examples'.format(
100 * class_balance(wiki_data, keyword=None), len(wiki_data)))
for term in groups:
if term == 'homosexual_gay_or_lesbian':
term = ['homosexual','gay','lesbian']
elif term == 'psychiatric_or_mental_illness':
continue
fraction = class_balance(wiki_data, term)
num = len(filter_frame(wiki_data, term))
print('class balance for {:10s} {:.1f}%\t{} examples'.format(str(term), 100 * fraction, num))
|
t=raw_input('')
if (t>='a' and t<='z' or t>='A' and t<='Z'):
print("Alphabet")
else:
print("No")
|
digit=int(input())
count=0
while(digit>0):
count=count+1
digit=digit//10
print(count)
|
import plotly.graph_objects as go
"""
1. make plot function
2. make classifier function
3. test on real data
"""
o = 102.6
h = 110
l = 100
c = 102.7
def plot_candlestick():
fig = go.Figure(data=[go.Candlestick(x=[1,2], open=[100, o], high=[105, h], low=[99, l], close=[104, c])])
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
def candlestick_classifier(o, h, l, c):
total_height = h - l
body_height = abs(o - c)
polarity = 'up' if c >= o else 'down'
#distance of oc avg from low as percentage of total_height
oc_height_ratio = ((o + c)/2 - l) / total_height
#print("body_height/total_height", body_height / total_height)
#print("oc_height_ratio", oc_height_ratio)
if body_height > 0.90 * total_height:
return 'marubozu_' + polarity
elif body_height < 0.05 * total_height:
if oc_height_ratio < 0.06:
return "gravestone_doji"
elif oc_height_ratio > 0.94:
return "dragonfly_doji"
elif 0.25 < oc_height_ratio < 0.75:
return "neutral_doji"
else:
return None
if __name__ == "__main__":
plot_candlestick()
print(candlestick_classifier(o,h,l,c))
|
import time
print("The epoch on this system starts at: " + time.strftime('%c', time.gmtime(0)))
print("The current time zone is {0}: ".format(time.tzname[0], time.timezone))
if time.daylight != 0:
print("\tDaylight Saving Time is in effect for this location")
print("\tThe DST timezone is: " + time.tzname[1])
print("The local time is: " + time.strftime('%Y-%m-%d %H-%M-%S')) |
import requests
from bs4 import BeautifulSoup
request = requests.get("https://www.johnlewis.com/house-by-john-lewis-hinton-office-chair/grey/p2083183")
content = request.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find("div", {"itemprop": "offers", "class": "prices-container"})
string_price = element.text.strip() # "£129.00"
price_without_symbol = string_price[1:]
print(float(price_without_symbol) < 200 )
price = float(price_without_symbol)
if price < 200:
print("Buy the bloody chair!")
print("The current price is {}".format(string_price))
else:
print("It costs too much, dummy!")
# <p class="price price--large">£129.00</p>
|
locations = {0: "You are sitting in front of a computer learning Python", # VALUES
1: "You are standing at the end of a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside a building, a well house for a small stream",
4: "You are in a valley beside a stream",
5: "You are in the forest"} # End dictionary
exits = { 0: {"Q": 0}, # Exits available for each location, each of these items corresponds to the items above in position
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, # west takes you to the hill, east building, south valley, north forest
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0}, # KEYS
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} } # End dictionary utilizing list
vocabulary = {"QUIT": "Q",
"NORTH": "N",
"SOUTH": "S",
"EAST": "E",
"WEST": "W"}
loc = 1 # Determines starting point of game
while True: # While loop is run until quit is utilized to exit
availableExits = ", ".join(exits[loc].keys()) # retrieving the dictionary from locations
# below is less efficient
# availableExits = "" # Creates string for available exits to be populated in
# for direction in exits[loc].keys(): #
# availableExits += direction + ", "
print(locations[loc])
if loc == 0:
break
direction = input("Available exits are " + availableExits + " ").upper() # .upper allows players to type upper/lower case without consequence, players are allowed to choose from available exits only
print()
# parse the user input, using our vocabulary dictionary if necessary
if len(direction) > 1: # more than 1 letter, so check vocab
for word in vocabulary: # does it contain a word we know?
if word in direction:
direction = vocabulary[word]
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You cannot go in that direction")
|
fruit = {"orange": "a sweet, orange, citrus fruit",
"lemon": "a sour, yellow, citrus fruit",
"grape": "a small, sweet fruit, growing in bunches",
"lime": "a sour, green, citrus fruit",
"apple": "round and crunchy"}
print(fruit)
veg = {"cabbage": "Every child's favorite",
"Sprouts": "Mmmm, lovely",
"Spinach": "Can I have some more fruit please?"}
print(veg)
# veg.update(fruit) # combines fruit and veggies
# print(veg)
nice_and_nasty = fruit.copy() # calling in fruit
nice_and_nasty.update(veg) # calling in veg
print(nice_and_nasty)
print(veg)
print(fruit)
|
# Check the distance
import multiprocessing
from constant import TEMP_LIMIT,DISTANCE_MIN,DISTANCE_MAX
from enterance_check import enterance_check
import time
def distance_check(np):
while (True):
#Here, the distance is measured.
#------------------------------------------------------------------
dist=4 ###### This will be changed during demo
#------------------------------------------------------------------
if (dist<DISTANCE_MIN):
print("Move away from the temperature sensor.")
time.sleep(1)
elif (dist>DISTANCE_MAX):
print("Get close to the temperature sensor.")
time.sleep(1)
else:
#Here, the temperature is measured.
#------------------------------------------------------------------
temp=37 ###### This will be changed during demo
#------------------------------------------------------------------
if(temp>=TEMP_LIMIT): #Fewer case
print("You have fewer. You shall not pass.")
np.put(0)
break
else: #Temperature is fine
# Opening the door code. For temporarily, I used print.
print("You are OK. The door is opening.")
# Launches isEntered_process. It makes sure that the people entered.
isEntered_process = multiprocessing.Process(target=enterance_check, args=(np,))
isEntered_process.start()
isEntered_process.join()
break
|
import time
import tkinter as tk
# initialise the window of the canvas
animation = tk.Tk()
canvas = tk.Canvas(animation, width=400, height=350)
canvas.pack()
PROCESS_RADIUS = 10
MESSAGE_RADIUS = 3
ANIMATION_DELAY = 10
SLEEPTIME = 0.3
INITIAL_COLOUR = 'red'
TERMINATED_COLOUR = 'green'
class Process:
def __init__(self, x, y, radius, colour, pid=0, level=0):
self.x = x
self.y = y
self.radius = radius
self.colour = colour
self.core = canvas.create_oval(self.x-self.radius, self.y-self.radius, self.x+self.radius, self.y+self.radius, fill=self.colour)
self.children = []
self.parent = 0
self.pid = pid
self.level = 0
def change_colour(self):
"""
changing the colour when the transition happens
"""
canvas.itemconfig(self.core, fill=TERMINATED_COLOUR)
def multi_send(Tree, list_from, list_to):
"""
sending messages
"""
# store all msgs
messages = {}
# define parent and child to pass information among them
for index, (_from, _to) in enumerate(zip(list_from, list_to)):
# calculate the length of travel
path_x, path_y = (Tree["p_"+str(_to)].x - Tree["p_"+str(_from)].x)/ANIMATION_DELAY, (Tree["p_"+str(_to)].y - Tree["p_"+str(_from)].y)/ANIMATION_DELAY
# store all msgs
messages["mes_"+str(index)] = {"object": Process(Tree["p_"+str(_from)].x, Tree["p_"+str(_from)].y, MESSAGE_RADIUS, 'blue'),
"path_x": path_x,
"path_y": path_y}
print(messages)
# update the canvas by moving the objects gradually
for j in range(ANIMATION_DELAY):
for index in range(len(list_to)):
mes, path_x, path_y = messages["mes_"+str(index)]['object'], messages["mes_"+str(index)]['path_x'], messages["mes_"+str(index)]['path_y']
canvas.move(mes.core, path_x, path_y)
animation.update()
time.sleep(SLEEPTIME)
# change the colour of the process which finishes a computing phase
for index in list_to:
Tree["p_" + str(index)].change_colour()
animation.update()
def tree_construction(l, level, Tree):
"""
construct tree
"""
level += 1
for unit in l:
if type(unit) == list:
tree_construction(unit, level, Tree)
else:
pid, x, y, radius, colour = unit
Tree["p_"+str(pid)] = Process(x, y, radius, colour, pid, level)
def flatten(l, result):
"""
flatten a list
"""
for i in l:
if type(i) == list:
flatten(i, result)
else:
result.append(i)
return result
if __name__ == '__main__':
# processes
data = [(0, 200, 30, PROCESS_RADIUS, INITIAL_COLOUR),
[(1, 170, 120, PROCESS_RADIUS, INITIAL_COLOUR),[(3, 130, 260, PROCESS_RADIUS, INITIAL_COLOUR),(4, 180, 260, PROCESS_RADIUS, INITIAL_COLOUR)]],
[(2, 230, 120, PROCESS_RADIUS, INITIAL_COLOUR),[(5, 220, 260, PROCESS_RADIUS, INITIAL_COLOUR),(6, 270, 260, PROCESS_RADIUS, INITIAL_COLOUR)]]
]
# relationship among processes
relations = ["0-1",
"0-2",
"1-3",
"1-4",
"2-5",
"2-6"]
# £ of nodes in the layer
layer_nodes = [1,2,4]
Tree = {}
# construct the tree based on data
tree_construction(data, -1, Tree)
print(Tree)
for relation in relations:
parent, child = relation.split("-")
# register children to the parent process
Tree["p_"+str(parent)].children.append(child)
# register the parent to children
Tree["p_"+str(child)].parent = parent
# draw lines to connect nodes and construct a tree on the map
canvas.create_line(Tree["p_"+str(parent)].x, Tree["p_"+str(parent)].y, Tree["p_"+str(child)].x, Tree["p_"+str(child)].y)
# for a in Tree
print("<< processes on the map >>\n", Tree)
sending_order = []
list_from, list_to = [], []
count = 0
# creating the order of delivery
for item in layer_nodes[:-1]:
for i in range(item):
list_from.append([Tree["p_"+str(count)].pid for i in range(len(Tree["p_"+str(count)].children))])
list_to.append(list(map(int, Tree["p_"+str(count)].children)))
count += 1
list_from = flatten(list_from, [])
list_to = flatten(list_to, [])
sending_order.append((list_from, list_to))
list_from, list_to = [], []
print(sending_order)
# sending forward
for i in sending_order:
print("i: ", i)
list_from, list_to = i
multi_send(Tree, list_from, list_to)
# sending backward
for i in sending_order[::-1]:
list_from, list_to = i
multi_send(Tree, list_to, list_from) |
class Animal:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
class Cat(Animal):
def __init__(self, name):
#super().__init__(name不可以写多行
super().__init__(name)#继承父类的初始话函数
cat1 = Cat("大白")
cat1.show()
#self training
print("\n--------------self training-----------------")
#-----------------多态-----------------
class super_class:
def show(self):
print("i am super_class")
class soon_class:
def show(self):
print("i am soon class")
class other:
def show(self):
print("i dont know")
def display(super_class):
super_class.show()
super_class_demo = super_class()
soon_class_demo = soon_class()
other_demo = other()
display(super_class_demo)
#可以传入他的子类
display(soon_class_demo)
#也可以传入其他,只要他有show就行
display(other_demo)
|
'''
Usted ha sido contratado para desarrollar una solución que le permita al dpto.
De RRHH obtener de manera ágil el estado de las vacaciones de sus empleados.
Por cuestiones organizativas la empresa tiene los datos de legajo separados de los datos de vacaciones.
El sistema deberá :
a - Tener un menú de acciones
b - Permitir la carga de datos y guardarlos en un archivo csv cuyo nombre será dado por el usuario.
Si el archivo ya existe deberá preguntar si se desea modificar o sobreescribirlo.
* sólo validar que legajo y total de vacaciones sean números enteros.
c - Dado el número de legajo de un empleado calcular e informar en pantalla los días que le quedan disponibles
de vacaciones junto con el resto de sus datos. Por ejemplo "Legajo 1 : Laura Estebanez, le restan 11 días de vacaciones"
Tenga en cuenta que las acciones del menú no tienen un orden en particular.
'''
import csv
def programa():
while True:
imprimir_menu()
opcion = input("")
if opcion == "3":
exit()
if opcion == "1":
cargar_datos()
if opcion == "2":
calcular_vacaciones()
else:
print("Por favor elija una opcion valida")
def imprimir_menu():
print("\n-GESTOR DE VACACIONES-")
print("1 - Cargar Datos de Legajo")
print("2 - Calcular Vacaciones Disponibles")
print("3 - Salir")
#guarda los nombres de los archivos generados por el usuario
archivos_generados = []
'''
FUNCIONES PARA EL PUNTO B
'''
#OPCION 1 - Cargar Datos de Legajo
def cargar_datos():
campos = ['Legajo', 'Apellido', 'Nombre', 'Total Vacaciones']
empleados_ingresados = []
#ingresar datos: envia los campos a ingresar, y los indices de cuales deben ser numeros enteros
empleados_ingresados = ingresar_datos_entrada(campos, [0,3])
#ingresar nombre archivo: se le pasa la lista de archivos generados, devuelve el nombre y si quiere modificar/sobreescirbir
nombre_archivo, modo_archivo = ingresar_nombre_archivo(archivos_generados)
archivos_generados.append(nombre_archivo)
#guardar
if modo_archivo=='modificar':
modo_archivo='a'
else:
modo_archivo='w'
try:
with open(nombre_archivo, modo_archivo, newline="") as archivo:
cargador_archivo = csv.writer(archivo)
if modo_archivo == 'w':
cargador_archivo.writerow(campos)
cargador_archivo.writerows(empleados_ingresados)
print(f'-El archivo {nombre_archivo} fue guardado con exito.-')
except IOError:
print("Hubo un problema con el archivo")
#funcion usada para que el usuario ingrese los datos de los empleados
def ingresar_datos_entrada(campos, campos_a_validar_enteros):
continuar = "si"
datos_entrada = []
while continuar == "si" or continuar == "" or continuar == "\n":
empleado = []
for contador in range(len(campos)):
#Si el indice del campo esta en la lista de los que hay que validar que sean enteros
if campos_a_validar_enteros.__contains__(contador):
#llama a la funcion especial para ingresar y validar numeros enteros
empleado.append( validar_entrada_enteros(campos[contador]) )
else:
empleado.append(input(f"Ingresar {campos[contador]} del empleado: "))
datos_entrada.append(empleado)
continuar = input("Continuar agregando datos? (escriba 'si' o pulse enter para continuar)")
return datos_entrada
#funcion usada para validar los campos que deben ser numeros enteros
def validar_entrada_enteros(campo):
valor_correcto = False
while not valor_correcto:
try:
valor_ingresado = int(input(f"Ingresar {campo} del empleado: "))
valor_correcto = True
except:
print("-Por favor ingrese un número entero-")
return valor_ingresado
#funcion para ingresar nombre de archivo y elegir el modo con el que se manipulara
def ingresar_nombre_archivo(archivos_generados):
nombre_archivo = ""
opcion = ""
nombre_archivo = input("Ingrese el nombre del archivo donde desea guardar los datos: ")
for nombre in archivos_generados:
if nombre == nombre_archivo:
print("-Ya existe un archivo con ese nombre-")
opcion = input("Si desea sobreescribirlo ingrese 'si'(de lo contrario solo sera modificado): ")
if opcion=='si':
opcion="sobreescribir"
else:
opcion="modificar"
return nombre_archivo, opcion
'''
FUNCIONES PARA EL PUNTO C:
c - Dado el número de legajo de un empleado calcular e informar en pantalla los días que le quedan disponibles
de vacaciones junto con el resto de sus datos. Por ejemplo "Legajo 1 : Laura Estebanez, le restan 11 días de vacaciones"
Tenga en cuenta que las acciones del menú no tienen un orden en particular.
'''
#OPCION 2 - Calcular Vacaciones Disponibles
def calcular_vacaciones():
#ingresar num legajo: se usa la funcion de validar enteros
numero_legajo = validar_entrada_enteros("Número de legajo")
#elegir archivo a usar
if len(archivos_generados) == 0:
print("No hay datos de empleados cargados, por favor primero ingrese los datos al sistema.")
return
print("Elija el archivo de datos que desea utilizar: ")
for contador in range(len(archivos_generados)):
print(f"{contador} - {archivos_generados[contador]}")
ingreso_valido = False
while not ingreso_valido:
archivo_elegido = int(input("Ingrese el numero del archivo a utilizar: "))
if archivo_elegido > len(archivos_generados) or archivo_elegido < 0:
print("-Ingrese un numero valido de los de la lista-")
else:
ingreso_valido=True
#mostar vacaciones
try:
with open(archivos_generados[archivo_elegido]) as file_empleados:
with open("dias.csv") as file_dias:
csv_empleados = csv.reader(file_empleados)
csv_dias = csv.reader(file_dias)
# Saltea los encabezados
next(csv_empleados)
next(csv_dias)
vacaciones_usadas = 0
empleado = next(csv_empleados,None)
dia = next(csv_dias, None)
while empleado:
if(int(empleado[0])==numero_legajo):
while dia:
if int(dia[0])==numero_legajo:
vacaciones_usadas+=1
dia = next(csv_dias, None)
vacaciones_restantes = int(empleado[3]) - vacaciones_usadas
if vacaciones_restantes < 0:
vacaciones_restantes = 0
print(f'Legajo {numero_legajo} : {empleado[2]}{empleado[1]}, le restan {vacaciones_restantes} días de vacaciones')
empleado = next(csv_empleados,None)
except IOError:
print("Error en al abrir el archivo")
#se ejecuta
programa() |
#Group by chosen dataframe index to navigate and pull information out of the data
import numpy as np
import pandas as pds
company = 'GOOG GOOG MSFT MSFT FB FB'.split()
person = 'Sam Charlie Amy Vanessa Carl Sarah'.split()
sales = [200, 120, 340, 124, 243, 350]
data = {'Company': company, 'Person': person, 'Sales': sales}
#print(data)
df = pds.DataFrame(data)
#print(df)
#print(df.groupby('Company'))
byComp = df.groupby('Company') #Group datafram by Company
#print(byComp.mean())
#print(byComp.std())
#print(byComp.sum())
#print(byComp.sum().loc['FB']) #Get sums of groups of row FB
#print(byComp.count()) #Count rows related to each group
# print(byComp.min()) #Gets minimum value of each group
# print(byComp.max())
#print(byComp.describe()) #Gives count, mean, std, min, 25%, 50%, 75%, and max
print(byComp.describe().transpose()['FB']) #Describes row FB
|
#暴力解
class Solution:
def largestRectangleArea(self, heights):
if not heights:
return 0
res_list = []
for i in range(len(heights)):
now_h = heights[i]
r_j = i
while(r_j+1<len(heights) and heights[r_j+1]>=now_h):
r_j += 1
l_j = i
while(l_j-1>=0 and heights[l_j-1]>=now_h):
l_j -= 1
now_area = now_h*(r_j-l_j+1)
res_list.append(now_area)
return max(res_list)
if __name__ == '__main__':
height = [2, 1, 5, 6, 2, 3]
S = Solution()
print(S.largestRectangleArea(height)) |
class Solution:
def __init__(self):
self.used = []
self.flag = False
self.directions = [(0, -1), (-1, 0), (0, 1), (1, 0)]
def exist(self, board, word):
m = len(board)
n = len(board[0])
self.used = [[False]*len(board[0]) for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==word[0]:
if self.backtrack(i,j,m,n,0,word,board):
return True
return False
def backtrack(self,now_x,now_y,m,n,word_index,word,board):
# print(self.used)
# print(now_x,now_y,word_index,len(word))
if word_index == len(word)-1:
if board[now_x][now_y]==word[word_index]:
return True
if board[now_x][now_y] == word[word_index]:
self.used[now_x][now_y] = True
for dir in self.directions:
next_x = now_x + dir[0]
next_y = now_y + dir[1]
if self.index_inlegal(next_x,next_y,m,n) \
and self.used[next_x][next_y]==False \
and self.backtrack(next_x,next_y,m,n,word_index+1,word,board):
return True
self.used[now_x][now_y] = False
return False
def index_inlegal(self,next_x,next_y,m,n):
if 0<=next_x<m and 0<=next_y<n:
return True
else:
return False
if __name__ == '__main__':
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word = "ABCB"
S = Solution()
print(S.exist(board,word)) |
# Definition for a binary tree node.
from copy import deepcopy
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
if not root:
return True
now_queue = []
next_queue = []
res = []
mini_res = []
now_queue.append(root)
while(len(now_queue)>0):
root = now_queue[0]
del now_queue[0]
mini_res.append(root.val)
if root.left:
next_queue.append(root.left)
if root.right:
next_queue.append(root.right)
if len(now_queue)==0:
res.append(mini_res)
mini_res = []
now_queue = next_queue
next_queue = []
return res
#
def isSymmetric(self, root):
root_cp = deepcopy(root)
return self.check(root,root_cp)
def check(self,node,node_cp):
if not node and not node_cp:
return True
if not node or not node_cp:
return False
return node.val==node_cp.val and self.check(node.left,node_cp.right) and self.check(node.right,node_cp.left)
if __name__ == '__main__':
root = TreeNode(0)
l1 = TreeNode(1)
l2 = TreeNode(2)
l3 = TreeNode(3)
l4 = TreeNode(4)
root.left = l1
root.right = l2
l1.left = l3
l3.left =l4
S = Solution()
print(S.isSymmetric(root)) |
import _sqlite3
# tablo bağlantısı kurma ve işaretci oluşturma
#con = _sqlite3.connect("Users.db")
#cursor=con.cursor()
def createTable(): #tablo oluşturma attribute'ları belirleme
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS USERS ("
"userID INT PRIMARY KEY NOT NULL, "
"uName TEXT NOT NULL, "
"uMail TEXT,"
"uPassword TEXT NOT NULL,"
"authorized BOOL NOT NULL, "
"verifyCode INT(6))")
con.commit()
con.close()
def createUser(userID,name,mail,password,authorized,verifyCode): #yetkili kullanicinin id'si 1 diğerleri sıralı olmalı
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("INSERT INTO USERS (userID,uName,uMail,uPassword,authorized,verifyCode) VALUES(?,?,?,?,?,?) ",(userID,name,mail,password,authorized,verifyCode))
con.commit()
con.close()
def fetch(id,req): #userID ye göre istenilen degeri döndürür
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("SELECT "+req+" FROM USERS WHERE userID == "+id+"")
data=cursor.fetchall()
request=data[0][0] # data değişkenin tipi list. listenin ilk elemani aradigimiz deger
con.close
return request
def updateInfo(id,changeX,changeY): #girilen id'nin changeX attribute'undaki değerini changeY ile değiştirir veriler dogru girilmeli
if(changeX == "authorized"):#yetki değerleri degistirilemez
print("izin verilmeyen durum..")
else:
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("UPDATE USERS SET '{}' = '{}' WHERE userID=='{}'".format(changeX,changeY,id))
con.commit()
con.close()
def deleteUser(id):#kullanici silme
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
if(isAuthorized(id)!=1):#yetkili kullanici silinemez
cursor.execute("DELETE FROM USERS WHERE userID== '{}'".format(id))
con.commit()
con.close()
else:
print("islem basarisiz..")
def isAuthorized(id): #kulanıcının yetki durumunu döndürür
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("SELECT authorized FROM USERS WHERE userID == " + id + "")
data = cursor.fetchall()
response = data[0][0]
con.close()
return response
#yüz verilerinin kişilerle eşleşmesi için id değerlerinin 1 ile 5 arasında değerler olması gerek
def genereteID(): #id üretme fonksiyonu
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("SELECT userID FROM USERS")
data = cursor.fetchall()#bütün userID'ler data listesinin içerisine atıldı fakat bu liste bize uygun degil
i=1
IDs=[]#yeni id listemiz
for i in range(len(data)):#data listesindeki bütün id ler istedigimiz formda IDs listesine atılıyor
IDs.append(data[i][0])
IDs.sort() #taramada avantaj saglanması icin liste siralandi
id=1 #deger değişmemeli min id=1 max id =5 olmalı
i=0
for i in range(len(IDs)):#1'den 5'e kadar gezip liste içerisinde eksik olan ilk degeri bulur
if id in IDs:
id=id+1
else:
break
con.close()
return id
def isUserInTable(): #tablo içerisinde kullanıcı var mı?
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("SELECT userID FROM USERS")
data=cursor.fetchall()
con.close()
if data:
return True
else :
return False
def totalUserInTable(): #toplam kullanıcı sayısını döndürür
con = _sqlite3.connect("Users.db")
cursor = con.cursor()
cursor.execute("SELECT userID FROM USERS")
data = cursor.fetchall()
con.commit()
con.close()
return len(data)
#createTable()
#createUser(genereteID(),"Volkan","2@hotmail.com","0123456789",True,"")
#print(fetch("1","uName"))
#print(totalUserInTable())
#deleteUser("5")
#updateInfo("3","uName","kursat")
#newPass="asdae"
#updatePassword(newPass,"1")
|
"""Memento class for saving objects to memory and restoring them."""
import random
class Memento:
def __init__(self, class_name, data_dict):
"""Class name + a random memento id used to idenfity the memento in memory. data_dict should be a python dict"""
self.class_name = class_name
self.data_dict = data_dict
self.memento_id = round(random.random() * 10000)
def serialize(memento):
serialized_memento = {'{}_{}'.format(memento.class_name, memento.memento_id): memento.data_dict}
return serialized_memento
def deserialize(serialized_memento):
for key, value in _.pairs(dict):
class_name, memento_id = key.split('_')
memento = Memento(class_name, value)
memento.memento_id = memento_id
return memento
|
def f(x):
if x<= -2:
return 1-(x+2)**2
elif -2 < x <= 2:
return -x/2
else:
return 1+(x-2)**2 |
# -*- coding: utf-8 -*-
# @Time : 2019/10/12 17:00
# @Author : BaoBao
# @Mail : baobaotql@163.com
# @File : queens.py
# @Software: PyCharm
def is_rule(queen_tup, new_queen):
"""
:param queen_tup: 棋子队列,用于保存已经放置好的棋子,数值代表相应棋子列号
:param new_queen: 被检测棋子,数值代表列号
:return: True表示符合规则,False表示不符合规则
"""
num = len(queen_tup)
for index, queen in enumerate(queen_tup):
if new_queen == queen: # 判断列号是否相等
return False
if abs(new_queen - queen) == num - index: # 判断列号之差绝对值是否与行号之差相等
return False
return True
def arrange_queen(num, queen_tup=list()):
"""
:param num:棋盘的的行数,当然数值也等于棋盘的列数
:param queen_tup: 设置一个空队列,用于保存符合规则的棋子的信息
"""
for new_queen in range(num): # 遍历一行棋子的每一列
if is_rule(queen_tup, new_queen): # 判断是否冲突
if len(queen_tup) == num - 1: # 判断是否是最后一行
yield [new_queen] # yield关键字
else:
# 若果不是最后一行,递归函数接着放置棋子
for result in arrange_queen(num, queen_tup + [new_queen]):
yield [new_queen] + result
for i in arrange_queen(8):
print(i)
|
import unittest
from evens import even_number_of_evens
class TestEvens(unittest.TestCase):
# Remember test names MUST start with the word test
# Keep them related
def test_throws_error_if_value_passed_in_is_not_list(self):
# assertRaises is a method from TestCase and when ran will check if a
# TypeError has been raised when the function is called with a value
# of 4
self.assertRaises(TypeError, even_number_of_evens, 4)
def test_values_in_list(self):
# Returns false if empty list is passed in
self.assertEqual(even_number_of_evens([]), False)
# Returns true if even number of evens is sent
self.assertEqual(even_number_of_evens([2, 4]), True)
# Fails when one even number is sent
self.assertEqual(even_number_of_evens([2]), False)
# Fails when no even numbers are sent
self.assertEqual(even_number_of_evens([1, 3, 5]), False)
if __name__ == "__main__":
unittest.main()
|
"""
Encrypting passwords
"""
import bcrypt
def hash_password(password):
""" Returns a salted, hashed password, which is a byte string """
encoded = password.encode()
hashed = bcrypt.hashpw(encoded, bcrypt.gensalt())
return hashed
def is_valid(hashed_password, password):
""" Validates the provided password matches the hashed password """
valid = False
encoded = password.encode()
if bcrypt.checkpw(encoded, hashed_password):
valid = True
return valid
|
# Code from chapter 3 in ML book
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
# Import the MNIST dataset
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
# Look at the imported data
X, y = mnist['data'], mnist['target']
print(X.shape)
print(y.shape)
# Display some of the data as images
some_digit = X[36000]
some_digit_image = some_digit.reshape(28, 28)
plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation='nearest')
plt.axis('off')
plt.show()
# Plot a set of digits
def plot_digits(instances, images_per_row=10, **options):
size = 28
images_per_row = min(len(instances), images_per_row)
images = [instance.reshape(size, size) for instance in instances]
n_rows = (len(instances) - 1) // images_per_row + 1
row_images = []
n_empty = n_rows * images_per_row - len(instances)
images.append(np.zeros((size, size * n_empty)))
for row in range(n_rows):
rimages = images[row * images_per_row : (row + 1) * images_per_row]
row_images.append(np.concatenate(rimages, axis=1))
image = np.concatenate(row_images, axis=0)
plt.imshow(image, cmap = matplotlib.cm.binary, **options)
plt.axis('off')
plt.figure(figsize=(9,9))
example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]
plot_digits(example_images, images_per_row=10)
plt.show()
# Create train and test sets
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
# Shuffle the training set to make sure there is no bias
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]
# Training a binary classifier
# Ie only trying to detect where it is or isnt a certain digit (5)
y_train_5 = (y_train == 5)
y_test_5 = (y_test == 5)
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier(random_state=42)
sgd_clf.fit(X_train, y_train_5)
# Predict values
sgd_clf.predict([some_digit])
# Measuring accuracy with cross validation ;)
from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring='accuracy')
# Using a confusion matrix
from sklearn.model_selection import cross_val_predict
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)
# In the confusion matrix the top left are true negatives, top right is false positives
# bottom left is false negatives, and bottom right is the true positives
from sklearn.metrics import confusion_matrix
confusion_matrix(y_train_5, y_train_pred)
# Precision and recall
# Precision is True positives / (True postives + False positives)
# Recall is True positives / (True positives + False negatives)
from sklearn.metrics import precision_score, recall_score
print(precision_score(y_train_5, y_train_pred))
print(recall_score(y_train_5, y_train_pred))
# F1 score
#2 * ((Precision * recall) / (precision + recall))
from sklearn.metrics import f1_score
print(f1_score(y_train_5, y_train_pred))
# Plot the precision vs recall curve
from sklearn.metrics import precision_recall_curve
y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method='decision_function')
precision_recall_curve(y_train_5, y_train_pred)
precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)
def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
plt.plot(thresholds, precisions[:-1], 'b--', label='Precision')
plt.plot(thresholds, recalls[:-1], 'g-', label='Recall')
plt.xlabel('Threshold')
plt.legend(loc='upper left')
plt.ylim([0,1])
plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.show()
# Display the precision and recall scores
y_train_pred_90 = (y_scores > 70000)
print(precision_score(y_train_5, y_train_pred_90))
print(recall_score(y_train_5, y_train_pred_90))
# The ROC curve (receiver operating characteristic)
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores)
# Plot them
def plot_roc_curve(fpr, tpr, label=None):
plt.plot(fpr, tpr, linewidth=2, label=label)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plot_roc_curve(fpr, tpr)
plt.show()
# Show the ROC score for our SGD
from sklearn.metrics import roc_auc_score
print(roc_auc_score(y_train_5, y_scores))
# Create a random forest classifier
from sklearn.ensemble import RandomForestClassifier
forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3,
method='predict_proba')
y_scores_forest = y_probas_forest[:, 1] # Score = proba of +ve class
fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5, y_scores_forest)
# Plot
plt.plot(fpr, tpr, 'b:', label='SGD')
plot_roc_curve(fpr_forest, tpr_forest, 'Random Forest')
plt.legend(loc='lower right')
plt.show()
y_train_pred_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3)
print(roc_auc_score(y_train_5, y_scores_forest))
print(precision_score(y_train_5, y_train_pred_forest))
print(recall_score(y_train_5, y_train_pred_forest))
# Multiclass classification
sgd_clf.fit(X_train, y_train)
sgd_clf.predict([some_digit])
sgd_clf.decision_function([some_digit])
# To force use of one versus one.
from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(SGDClassifier(random_state=42))
ovo_clf.fit(X_train, y_train)
ovo_clf.predict([some_digit])
# A random forest classifier can automatically do this.
forest_clf.fit(X_train, y_train)
forest_clf.predict([some_digit])
# Display the prediction probabilities of the classifier
forest_clf.predict_proba([some_digit])
# Evaluate the classifier
cross_val_score(sgd_clf, X_train, y_train, cv=3, scoring='accuracy')
# Scale the inputs
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))
cross_val_score(sgd_clf, X_train_scaled, y_train, cv=3, scoring='accuracy')
# Scaling dramatically increases the accuracy
# Error analysis
# Confusion matrix
y_train_pred = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3)
conf_mx = confusion_matrix(y_train, y_train_pred)
print(conf_mx)
# Plot the confusion matrix
plt.matshow(conf_mx, cmap=plt.cm.jet)
plt.grid('off')
plt.show()
# Focus the plot on the errors
row_sums = conf_mx.sum(axis=1, keepdims=True)
norm_conf_mx = conf_mx / row_sums
# Fill the diag with 0s so we keep the errors only
np.fill_diagonal(norm_conf_mx, 0) # Fill the diagonal of the norm_mx with 0s
plt.matshow(norm_conf_mx, cmap=plt.cm.jet)
plt.grid('off')
plt.show()
# Multilabel classification system
from sklearn.neighbors import KNeighborsClassifier
y_train_large = (y_train >= 7)
y_train_odd = (y_train % 2 == 1)
y_multilabel = np.c_[y_train_large, y_train_odd]
knn_clf = KNeighborsClassifier()
knn_clf.fit(X_train, y_multilabel)
knn_clf.predict([some_digit]) # y is not large and y is odd, both of these are true for 5
# Evaluation of multiclass classifier
# F1 score
#y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_train, cv=3)
#print(f1_score(y_train, y_train_knn_pred, average='macro'))
# Multi output classification
# Ie a label can have more than one possible value :D
# Number noise remover
noise = np.random.randint(0, 100, (len(X_train), 784))
X_train_mod = X_train + noise
noise = np.random.randint(0, 100, (len(X_test), 784))
X_test_mod = X_test + noise
y_train_mod = X_train
y_test_mod = X_test
some_index = 5500
def plot_digit(data):
image = data.reshape(28, 28)
plt.imshow(image, cmap = matplotlib.cm.binary,
interpolation="nearest")
plt.axis("off")
plt.subplot(121); plot_digit(X_test_mod[some_index])
plt.subplot(122); plot_digit(y_test_mod[some_index])
plt.show()
# Cleanthe noise
knn_clf.fit(X_train_mod, y_train_mod)
clean_digit = knn_clf.predict([X_test_mod[some_index]])
plot_digit(clean_digit)
|
#Udit Kaushik
#75825974
#project3_classes.py
class STEPS:
"""
Generates the step by step instruction of the map from the distance
api list and displays it in a readable fashion.
"""
def output_results(self, result_list: list) -> None:
"""
Method of class that is used specifically for duck typing.
"""
results = result_list[0] #API needed to be stored into a list for the sake of duck typing.
#Since we know there is only one api in the distance_api_list, we
#safely hard code the index value to 0.
direction_list = []
#Finds and takes the results from the api.
for i in range(len(results['route']['legs'])):
for j in range(len(results['route']['legs'][i]['maneuvers'])):
direction_list.append(results['route']['legs'][i]['maneuvers'][j]['narrative'])
print()
print('DIRECTIONS')
for direction in direction_list:
print(direction)
class TOTALDISTANCE:
"""
Takes the distance data from the distance api list and
displays the total distance of the entire trip
"""
def output_results(self, result_list: list) -> None:
"""
Method of class that is used specifically for duck typing.
"""
#Finds and takes the results from the api.
results = result_list[0] #API needed to be stored into a list for the sake of duck typing.
#Since we know there is only one api in the distance_api_list, we
#safely hard code the index value to 0.
distance = results['route']['distance']
#Prints the results in the desired format.
print()
print('TOTAL DISTANCE: {} miles'.format(round(distance)))
class TOTALTIME:
"""
Takes the distance api from the distance api list and
displays the total time (in minutes) of the entire trip.
"""
def output_results(self, result_list: list) -> None:
"""
Method of class that is used specifically for duck typing.
"""
#Finds and takes the results from the api.
results = result_list[0] #API needed to be stored into a list for the sake of duck typing.
#Since we know there is only one api in the distance_api_list, we
#safely hard code the index value to 0.
time = results['route']['time'] / 60 #Time taken in the api is in seconds; must divide by 60 to get minutes.
#Prints the results in the desired format.
print()
print('TOTAL TIME: {} minutes'.format(round(time)))
class LATLONG:
"""
Takes the latitude and longitude from the api and presents them
in the desired layout.
"""
def give_direction(lat_list: list, lng_list: list) -> list:
"""
Takes the coordinates from the given data and returns them
with the appropriate direction, i.e. N,S,E,W. Also, if the
coordinate is negative, returns it as a positive.
"""
final_list = []
if len(lat_list) == len(lng_list):
for i in range(len(lat_list)):
if lat_list[i] > 0:
cord = '{:03.2f}N'.format(round(lat_list[i], 2)) #LAT -> NORTH
elif lat_list[i] < 0:
lat_list[i] = -1 * int(lat_list[i]) #Makes the coordinate positive while taking into account the direction.
cord = '{:03.2f}S'.format(round(lat_list[i], 2)) #LAT -> SOUTH
final_list.append(cord)
for i in range(len(lng_list)):
if lng_list[i] > 0:
cord = '{:03.2f}E'.format(round(lng_list[i], 2)) #LON -> EAST
elif lng_list[i] < 0:
lng_list[i] = -1 * lng_list[i] #Makes the coordinate positive while taking into account the direction.
cord = '{:03.2f}W'.format(round(lng_list[i], 2)) #LON -> WEST
final_list.append(cord)
return final_list
def output_results(self, result_list: list) -> None:
"""
Method of class that is used specifically for duck typing.
"""
lat_list = []
lng_list = []
results = result_list[0] #API needed to be stored into a list for the sake of duck typing.
#Since we know there is only one api in the distance_api_list, we
#safely hard code the index value to 0.
#Finds and takes the results from the api.
for i in range(len(results['route']['locations'])):
lng_list.append(results['route']['locations'][i]['latLng']['lng'])
lat_list.append(results['route']['locations'][i]['latLng']['lat'])
final_list = LATLONG.give_direction(lat_list, lng_list)
#Prints the results in the desired format.
print()
print('LATLONGS')
for i in range(len(lat_list)):
print('{} {}'.format(final_list[i], final_list[i+len(lat_list)]))
class ELEVATION:
"""
Takes the data from the apis in the api list and prints out the
elevation for the individual location.
"""
def output_results(self, result_list: list) -> None:
"""
Method of class that is used specifically for duck typing.
"""
#Prints the results in the desired format.
print()
print('ELEVATIONS')
for i in range(len(result_list)): #A loop is used because there are multiple api data in the list (one for each location -> individual elevation).
print(round(result_list[i]['elevationProfile'][0]['height'])) #Finds and takes the results from the api.
|
s=int(input("Space"))
day1=input("yesterday")
day2=input("today")
count=0
a=0
for i in day1:
if i =="c" and i ==day2[count]:
a+=1
count+= 1
print(a)
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
cnt1,cnt2,cnt3,cnt4,fcnt=0,0,0,0,0
for a in password:
if a.isupper()==True:
cnt1+=1
elif a.islower()==True:
cnt2+=1
elif a.isdigit()==True:
cnt3+=1
elif a=="!" or a=="@" or a=="#" or a=="$" or a=="%" or a=="^" or a=="&" or a=="*" or a=="(" or a==")" or a=="-" or a=="+":
cnt4+=1
if cnt1>0:
fcnt+=1
if cnt2>0:
fcnt+=1
if cnt3>0:
fcnt+=1
if cnt4>0:
fcnt+=1
if n<6:
b=6-n
c=4-fcnt
if c>b:
return (c)
else:
return (b)
return(6-n)
else:
return(4-fcnt)
# Return the minimum number of characters to make the password strong
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
password = input()
answer = minimumNumber(n, password)
fptr.write(str(answer) + '\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the utopianTree function below.
def utopianTree(n):
a=0
for i in range(-1,n):
if i==0:
a=a+1
elif i%2!=0:
a=a+1
elif i%2==0:
a=a*2
return (a)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = utopianTree(n)
fptr.write(str(result) + '\n')
fptr.close()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
s=input()
n=int(input())
#to count no of a in complete string
c1=0
for i in s:
if i=="a":
c1+=1
#to count no of "a" in part of string
a=n-(n//len(s))*len(s)
st=s[:a]
c2=0
for i in st:
if i=="a":
c2+=1
print(c1*(n//len(s))+c2)
|
class Triangulo():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return f'Los lados son {self.a} {self.b} {self.c}'
def __enter__(self):
return self.a + self.b + self.c
def __exit__(self, err_type, err_value, traceback):
self.a, self.b = self.b, self.a
def __eq__(self, other_triangle):
first = self.a == other_triangle.a
second = self.b == other_triangle.b
third = self.c == other_triangle.c
return first == second == third == True
primer_triangulo = Triangulo(1,2,3)
segundo_triangulo = Triangulo(1,2,3)
print(primer_triangulo)
print(segundo_triangulo)
print(primer_triangulo == segundo_triangulo)
print(primer_triangulo is segundo_triangulo)
|
# WHILE
counter = 1
counter += 1 # counter = counter + 1
while counter > 0:
print(f'Im bigger than 0 and Im {counter}')
counter += 1
|
import random
from jose.pokemonmvc.controller import PokemonController
# TODO, REFACTORIZAR AL CONTROLADOR
# TODO, CREAR UNA CLASE ARBRITRO QUE AYUDE A GESTIONAR TODO ESTO
pokemon_controller = PokemonController(random)
def choose_one_pokemon(pokemons):
print('elige un pokemon de la lista')
for index, pokemon in enumerate(pokemons):
print(f'{index} .- {pokemon}')
pokemon_index = int(input(' > '))
return pokemons[pokemon_index]
def fight(machine_pokemon, person_pokemon):
while machine_pokemon.stamina > 0 and person_pokemon.stamina > 0:
machine_pokemon.attack_to(person_pokemon)
person_pokemon.attack_to(machine_pokemon)
def winner(machine_pokemon, person_pokemon):
if machine_pokemon.stamina > person_pokemon.stamina:
return machine_pokemon
return person_pokemon
def main():
machine_pokemon = pokemon_controller.random_pokemon()
print(machine_pokemon)
person_pokemons = pokemon_controller.generate_pokemons(5)
person_pokemon = choose_one_pokemon(person_pokemons)
print(f'has elegido {person_pokemon}')
fight(machine_pokemon, person_pokemon)
print('and the winner is :')
print(winner(machine_pokemon, person_pokemon))
main() |
def evaluate_score(player, bank):
# if banca or player == 21, wins, and break
# if banca > 21, and player <= 21 player wins
# if player > 21, and bank <= 21 bank wins
# if both of them < 21
# player - bank < 0 bank wins else player wins
if bank > 21 and player < 21:
return player
if bank <21 and player > 21:
return bank
if bank < 21 and player < 21:
difference = player - bank
if difference >= 0:
return bank
else:
return player
def evaluate_black_jack(player, bank):
if bank == 21:
return bank
if player == 21:
return player
|
# n! = n * n - 1 * n - 2 .......(n-(n - 1)) == 1
def factorial(n):
result = n
for n in range(n, 1, -1):
result *= (n - 1)
print(result)
factorial(3)
def factor_recur(n):
if n == 1:
return 1
else:
return n * factor_recur(n - 1)
print(factor_recur(3))
|
numeros_pares = list()
for num in range(0,10,2): # lista de numeros pares
numeros_pares.append(num)
print(numeros_pares)
texto = '''En un lugar de la Mancha de cuyo nombre no puedo acordarme'
vvia un hidalgo que no me acuerdo si tenia una talla XL'''
|
numero = input('Dame un número: ')
numero = int(numero)
contador = 2
if numero < 2:
print(f'{numero} no es primo')
else:
while contador <= numero:
if numero == 2:
print(f'{numero} es primo')
break
elif numero % contador == 0:
print(f'{numero} no es primo')
break
else:
print(f'{numero} es primo')
break
contador += 1
|
multiplicando = 1
multiplicador = 1
while multiplicando <= 10:
while multiplicador <= 10:
print(f' 1 x {multiplicador} = {multiplicando * multiplicador}')
multiplicador += 1
print('------------------')
multiplicando += 1
multiplicador = 1
|
import random
def crear_baraja():
pass
def evaluar_resultado(player, banca):
print(f'Player tiene {player}')
print(f'banca tiene {banca}')
pass
def dar_carta():
return random.randint(1,30)
def reparte_primera_ronda():
player = dar_carta()
banca = dar_carta()
return player, banca
def pregunta_usuario():
return input('¿Quieres otra carta? > (s/n)')
def turno_banca(banca, banca_se_planta, player, player_se_planta):
if banca_se_planta:
return
if banca < 15:
banca += dar_carta()
else:
banca_se_planta = True
turnos_sucesivos(player, banca, player_se_planta, banca_se_planta)
def turnos_sucesivos(player, banca, player_se_planta, banca_se_planta):
if player_se_planta and banca_se_planta:
evaluar_resultado(player, banca)
return
if player_se_planta:
turno_banca(banca, banca_se_planta, player, player_se_planta)
return
question = pregunta_usuario()
if question.upper() == 'S':
player += dar_carta()
if question.upper() == 'N':
player_se_planta = True
if question and question.upper() != 'N' and question.upper() != 'S':
print(f'Por favor escribe S o N, y nada más')
turnos_sucesivos(player, banca, player_se_planta, banca_se_planta)
turno_banca(banca, banca_se_planta, player, player_se_planta)
crear_baraja()
player, banca = reparte_primera_ronda()
turnos_sucesivos(player, banca, False, False)
evaluar_resultado(player, banca) |
def fizzbuzz():
for numero in range(1, 101):
if numero%3 == 0 and numero%5 !=0:
return('FIZZ')
elif numero%3 != 0 and numero%5 == 0:
return('BUZZ')
elif numero%3 == 0 and numero%5 ==0:
return('FIZZBUZZ')
elif numero%3 != 0 and numero%5 !=0:
return(numero)
#
fizzbuzz()
print(resultado)
|
counter = 2
while counter <= 100:
print(f'Soy un número par y soy el {counter}')
counter += 2 |
'''
This class is used to represent and hold a Twitter message. This could be a
variety of different types and holds the json from this. It can be used
to identify what type of message it is
'''
import json
class StreamMessage:
'''Holds a json message from Twitter'''
def __init__(self, tweet_data, disconnect_closes=True):
'''Sets up the StreamMessage object by passing in a json object'''
try: #assume they are passing in json
self.data = json.loads(tweet_data)
#if not json, assume its a dict and use it as the data
except TypeError:
self.data = tweet_data
self.disconnect_closes = disconnect_closes
def get_type(self):
'''Used to work out what type the message is'''
try:
if "delete" in self.data:
return "delete"
except KeyError:
pass
try:
if "disconnect" in self.data:
if self.disconnect_closes:
print "We have loaded a disconnect object and will close the program"
print "Disconnect message payload:"
print self.data['disconnect']
exit()
else:
return "disconnect"
except KeyError:
pass
try:
if "text" in self.data:
return "tweet"
except KeyError:
pass
return "unknown"
def get_hashtags(self):
'''Used to get the hashtags out of the message'''
hashtags = []
for hashtag in self.data['entities']['hashtags']:
hashtags.append(hashtag['text'])
return hashtags
|
from abc import ABC, abstractmethod
from validate import *
class ValidSolutionGenerator(ABC):
def __init__(self, options: List[Any], length: int=4, duplicates: bool=True):
self.options = options
self.length = length
self.duplicates = duplicates
self.clues = []
def add_clue(self, clue: Clue):
self.clues.append(clue)
@abstractmethod
def generate(self):
pass
def stat_msg(self):
return ''
class InMemoryPruner(ValidSolutionGenerator):
"""
Generates all possibilities in memory and then prunes the possibilities with each additional clue.
A large possibility space will take long to generate and use up lots of memory.
"""
def __init__(self, options: List[Any], length: int=4, duplicates: bool=True):
super().__init__(options, length, duplicates)
self.all_valid_choices = sorted(list(all_choices(options, length, duplicates=duplicates)))
def add_clue(self, clue: Clue):
super().add_clue(clue)
guess, result = clue
# Prune list of possible choices based on newest clue
self.all_valid_choices = [opt for opt in self.all_valid_choices if valid_possibility(guess, result, opt)]
if len(self.all_valid_choices) == 0:
print('Logical inconsistency')
exit()
def generate(self):
return self.all_valid_choices[0]
def stat_msg(self):
return 'Choices available: {}'.format(len(self.all_valid_choices))
class RandomGuessValidator(ValidSolutionGenerator):
"""
Takes random guesses which it then validates with the list of clues.
A large probability space will take longer and longer to generate valid guesses.
"""
def __init__(self, options: List[Any], length: int=4, duplicates: bool=True):
super().__init__(options, length, duplicates)
self.last_guess_count = None
def generate(self):
rnd_choice, self.last_guess_count = generate_random_valid_guess(
self.clues, self.options, self.length, self.duplicates, max_tries=None)
if rnd_choice is None:
print("Couldn't find valid guess")
exit()
return rnd_choice
def stat_msg(self):
return 'Guesses needed: {}'.format(self.last_guess_count)
def generate_random_valid_guess(clues: List[Clue],
options: List[Any], length: int=4, duplicates=True,
max_tries: Optional[int]=1000) -> Tuple[Guess, int]:
guess = None
guess_valid = False
count = 0
while not guess_valid:
guess = generate_combination(options, length, duplicates)
guess_valid = True
for clue in clues:
prev_guess, prev_result = clue
guess_valid = guess_valid and valid_possibility(prev_guess, prev_result, guess)
if not guess_valid:
continue
count += 1
if max_tries is not None and count > max_tries:
guess = None
break
return guess, count
def generate_combination(options: List[Any], length: int=4, duplicates=True):
if not duplicates and len(options) < length:
raise Exception("Not enough options provided to generate non-duplicate combinations")
# Copy options since we might alter it
options = list(options)
combination = []
for i in range(length):
choice_idx = randint(0, len(options) - 1)
combination.append(options[choice_idx])
if not duplicates:
del options[choice_idx]
return combination
def all_choices(options: List[Any], length: int=4, duplicates: bool=True):
all_options = list(options)
if duplicates:
all_options = options * length
# When allowing duplicate options the number of unique permutations and combinations are identical
# i.e. set(combinations) == set(permutations)
return set(itertools.permutations(all_options, length))
|
'''
Problem: Abracadabra
URI Online Judge | 2484
Solution developed by: Alberto Kato
'''
while True:
try:
word = input()
for x in range(len(word), 0, -1):
print(" " * (len(word) - x) + " ".join(word[0:x]))
print()
except EOFError:
break
|
'''
Problem: Sequência Espelho
URI Online Judge | 2157
Solution developed by: Alberto Kato
'''
C = int(input())
for i in range(0, C):
B, E = [int(i) for i in input().split()]
mirror = []
for j in range(B, E + 1):
numStr = str(j)
mirror += list(numStr)
print("".join(mirror) + "".join(mirror[::-1]))
|
'''
Problem: Ordenação por Tamanho
URI Online Judge | 1244
Solution developed by: Alberto Kato
'''
def sortWordsByLen(phrase):
phrase = phrase.split()
orderedPhrase = []
while(phrase):
biggestWordIndex = 0
for i in range(1, len(phrase) + 1):
if len(phrase[biggestWordIndex]) < len(phrase[i - 1]):
biggestWordIndex = i - 1
orderedPhrase.append(phrase[biggestWordIndex])
phrase.pop(biggestWordIndex)
return " ".join(orderedPhrase)
N = int(input())
while N > 0:
phrase = input()
print(sortWordsByLen(phrase))
N -= 1
|
'''
Problem: Falha do Motor
URI Online Judge | 2167
Solution developed by: Alberto Kato
'''
N = int(input())
speeds = [int(x) for x in input().split()]
speed = speeds[0]
index = 0
for i in range(1, len(speeds)):
if speed > speeds[i]:
index = i + 1
break
else:
speed = speeds[i]
print(index)
|
s = "hello, my name is {}".format("Bogdan")
print(s)
lawyer = input("Please give me the name of the lawyer")
client = "Beatriz Pisoni"
sum = "500"
s = f"Lawyer: {lawyer}, Client: {client}, value: {sum}$"
|
from utils import fib
def problem2():
"""
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
"""
seq = fib()
x = seq.next()
even_terms = []
total_sum = 0
while x < 4000000: # 4,000,000
if x % 2 == 0:
total_sum += x
x = seq.next()
return total_sum
if __name__ == '__main__':
print problem2()
|
#!/usr/bin/env python3
from collections import defaultdict
def distances_to_center():
"""Generates all Manhattan distances to center of the spiral."""
_min = 0
_max = 1
yield 0
while True:
_min += 1
yield from range(_max, _min, -1)
_max += 1
yield from range(_min, _max, 1)
yield from range(_max, _min, -1)
yield from range(_min, _max, 1)
yield from range(_max, _min, -1)
yield from range(_min, _max, 1)
yield from range(_max, _min, -1)
_max += 1
yield from range(_min, _max, 1)
def distance_to_center(n):
"""Return Manhattan distance to center of spiral of length <n>."""
dist = distances_to_center()
for _ in range(n - 1):
next(dist)
return next(dist)
def unwind(g, num):
"""Return <num> first elements from iterator <g> as array."""
return [next(g) for _ in range(num)]
# print(unwind(distances_to_center(), 50))
assert distance_to_center(1) == 0
assert distance_to_center(2) == 1
assert distance_to_center(3) == 2
assert distance_to_center(4) == 1
assert distance_to_center(5) == 2
assert distance_to_center(6) == 1
assert distance_to_center(7) == 2
assert distance_to_center(8) == 1
assert distance_to_center(9) == 2
assert distance_to_center(10) == 3
assert distance_to_center(11) == 2
assert distance_to_center(12) == 3
assert distance_to_center(13) == 4
assert distance_to_center(14) == 3
assert distance_to_center(15) == 2
assert distance_to_center(23) == 2
assert distance_to_center(1024) == 31
spiral_length = 277678
print(distance_to_center(spiral_length))
# -------------------------------------
def neighbourhood(p):
"""Returns 9 points belonging to neighbourhood of point <p>."""
x, y = p
return [
p,
(x+1, y+0),
(x+1, y+1),
(x+0, y+1),
(x-1, y+1),
(x-1, y+0),
(x-1, y-1),
(x+0, y-1),
(x+1, y-1)
]
def runs():
n = 1
while True:
yield n
yield n
n += 1
RIGHT = 0
UP = 1
LEFT = 2
DOWN = 3
NUMDIR = 4
def spiral_points(start_pos):
run = runs()
movements = next(run)
direction = RIGHT
pos = start_pos
while True:
yield pos
x, y = pos
if direction == RIGHT:
pos = (x+1, y+0)
elif direction == UP:
pos = (x+0, y+1)
elif direction == LEFT:
pos = (x-1, y+0)
elif direction == DOWN:
pos = (x+0, y-1)
movements -= 1
if movements <= 0:
direction += 1
direction %= NUMDIR
movements = next(run)
def neighbour_sums():
"""Walks through the spiral, generating sums out of neighbouring points."""
value_map = defaultdict(int)
spiral_pos = spiral_points((0, 0))
pos = next(spiral_pos)
value_map[pos] = 1
while True:
value_map[pos] = sum(value_map[p] for p in neighbourhood(pos))
yield value_map[pos]
pos = next(spiral_pos)
actual = neighbourhood((0, 0))
expected = [(0, 0), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
assert actual == expected
def assert_next(iter, expected):
actual = next(iter)
assert actual == expected, "expected %s, got %s" % (expected, actual)
run = runs()
assert_next(run, 1)
assert_next(run, 1)
assert_next(run, 2)
assert_next(run, 2)
assert_next(run, 3)
pts = spiral_points((0, 0))
assert_next(pts, (+0, +0))
assert_next(pts, (+1, +0))
assert_next(pts, (+1, +1))
assert_next(pts, (+0, +1))
assert_next(pts, (-1, +1))
assert_next(pts, (-1, +0))
assert_next(pts, (-1, -1))
assert_next(pts, (+0, -1))
assert_next(pts, (+1, -1))
assert_next(pts, (+2, -1))
assert_next(pts, (+2, +0))
assert_next(pts, (+2, +1))
assert_next(pts, (+2, +2))
sums = neighbour_sums()
assert_next(sums, 1)
assert_next(sums, 1)
assert_next(sums, 2)
assert_next(sums, 4)
assert_next(sums, 5)
assert_next(sums, 10)
assert_next(sums, 11)
assert_next(sums, 23)
assert_next(sums, 25)
assert_next(sums, 26)
def puzzle(spiral_length):
for s in neighbour_sums():
if s > spiral_length:
return s
spiral_length = 277678
print(puzzle(spiral_length))
|
#Python 1 Test program
listX = map(int,raw_input("Enter the input elements with delimiter as space :").split());
for element in range(len(listX)):
for sortingElement in range(len(listX)-1-element):
if (listX[sortingElement]>listX[sortingElement+1]):
temp = listX[sortingElement]
listX[sortingElement]=listX[sortingElement+1]
listX[sortingElement+1] = temp
print "sorted array", element
print "is ", listX
print "End of Array"
|
def raise_to_power(base, pow):
result = 1
for index in range(pow):
result = result * base
return result
# print(raise_to_power(2, 3))
|
class Power(object):
def __init__(self, x, n):
""" calculates power of x to the power x ^n
"""
if not isinstance(x,int):
raise TypeError("x must be type Int")
if not isinstance(n,int):
raise TypeError("n must be type int")
self._x = x
self._n = n
def calculate_power(self, n=None):
if n is None:
n = self._n
if n == 0 :
return 1
else:
partial = self.calculate_power(n//2)
result = partial * partial
if n % 2: #n odd
return result * self._x
return result
|
# Lists can include other lists.
# Creating a Matrix
# Matrices are a structure that has rows and columns.
# To model a matrix in Python,
# we need a new list for each row,
# and we'll need to make sure that each list is the same length
# so that the columns work properly.
# devina has edited twice
# Here's an example matrix not in code:
#
# 1 2 3
# 4 5 6
# To model this matrix in Python:
my_matrix = [[1, 2, 3],
[4, 5, 6]]
print(my_matrix) # [[1, 2, 3], [4, 5, 6]]
# To determine how many rows are in a multi-dimensional list,
# we need to use the len function on the matrix itself.
# To get the number of columns, we would use len on any row in the matrix
# (assuming that it's a proper matrix with each row having the same number of columns):
row_count = len(my_matrix)
column_count = len(my_matrix[0])
print(row_count) # 2
print(column_count) # 3
# Now if we want to interact with an individual item in the matrix,
# we need to index our variable two times,
# first with the row, and second with the column:
print(my_matrix[0][1]) # 2
|
### Simple Linear Regression ###
## Data Preprocessing ##
# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import Imputer # for missing data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder # for categorical data
from sklearn.cross_validation import train_test_split # for train test split
from sklearn.preprocessing import StandardScaler # for features scaling
# import dataset
dataset = pd.read_csv('Salary_Data.csv')
# dependent variable - years experience
# independent variable - salary
X = dataset.iloc[:,0].values
y = dataset.iloc[:,1].values
# train test split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size = float(1)/3,
random_state = 0)
# if one feature, need to do this
X_train = X_train.reshape(-1, 1)
X_test = X_test.reshape(-1, 1)
## Simple Linear Regression Model ##
# import libraries
from sklearn.linear_model import LinearRegression
# create LinearRegression object + fit
regressor = LinearRegression()
regressor.fit(X_train, y_train)
## Predicting the Test Set ##
y_pred = regressor.predict(X_test)
## Visualizing the Results ##
# training set results
plt.scatter(X_train, y_train, color = 'red')
# line is based on X_train and the model's predicted y values for X_train
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Training Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() # ready to plot graph
# test set results
plt.scatter(X_test, y_test, color = 'red')
# same line
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Test Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() # ready to plot graph
|
from typing import Tuple, Optional
import numpy as np
import pandas as pd
import logging
import random
class solvetsp:
def __init__(self,
dist_frame: pd.DataFrame):
"""
This class solves the traveling salesman problem with the 2-opt algorithm. As input, the distance matrix must
be given in a pandas dataframe.
:param dist_frame: dataframe
Dataframe containing the distance matrix for all locations
"""
self.dist_frame = dist_frame
self.num = len(dist_frame) + 1 # Ismaning is at start and end of the list
self.init = None
self.set_init()
# Optimize parameter:
self.sequence = [] # Most recent sequence of locations (in numbers from 0-20)
self.sequence_dists = [] # Distances between the locations
self.dist = 0 # Total distance of the most recent sequence
self.iterated_dists = [] # List of all calculated total distances over the iterations
self.iterated_sequences = [] # List of all calculated sequences over the iterations
self.best_iterated_sequences = [] # List of all sequences from the iteration with the best final result
self.best_iterated_dist = [] # List of all total distances from the iteration with the best final result
def solve_opt2(self,
scorethresh: int = 0.001,
iterations: int = 20):
"""
This function executes the 2-opt algorithm for optimizing the route with the given distance matrix.
Here, the iterations, which always start with a new random route, can be set. the scorethresh defines the
threshold, where the algorithm stops the optimizing process for each iteration. A common default value here is
0.0001. A score of 0 describes no opimization between two steps in the algorithm.
:param scorethresh: float
Lower threshold for the score of each iteration
:param iterations: int
Number of iteration with random initial route
:return:
"""
# Get Initial sequence and distance
self.sequence = self.init
self.dist, sequence_dist = self._get_fulldist(self.sequence)
logging.debug("Initial distance set: {d}".format(d=self.dist))
logging.debug("Initial sequence set: {s}".format(s=self.sequence))
all_sequences = []
all_dists = []
# Iterate over the number of iterations:
for it in range(iterations):
score = 1
iteration_sequences = []
iteration_dists = []
while score > scorethresh:
dist_prev = self.dist
# Iterate over all parts of the sequence:
for start in range(1, self.num - 2):
for stop in range(start + 1, self.num - 1):
# Reorder parts of the sequence:
sequence_new = np.concatenate((self.sequence[0:start],
self.sequence[stop:-len(self.sequence) + start - 1:-1],
self.sequence[stop + 1:len(self.sequence)])).tolist()
# Calculate new total distance of the resulting sequence:
dist_new, sequence_new_dist = self._get_fulldist(sequence_new)
self.sequence_dists.append(dist_new)
iteration_sequences.append(sequence_new)
iteration_dists.append(dist_new)
# Check if new total distance is smaller than recent total distance and save new best sequence
# and total distance (if not do nothing):
if dist_new < self.dist:
self.sequence = sequence_new
self.dist = dist_new
logging.debug("New best distance set: {d}".format(d=dist_new))
score = 1 - self.dist / dist_prev
# Save best distance and sequence from this iteration:
all_sequences.append(iteration_sequences)
all_dists.append(iteration_dists)
self.iterated_dists.append(self.dist)
self.iterated_sequences.append(self.sequence)
logging.info("Score of Iteration {i}: {s}, Distance: {d}".format(i=it, s=score, d=self.dist))
# Start over with new initial sequence:
self.set_init(rand=True)
self.sequence = self.init
self.dist, sequence_dist = self._get_fulldist(self.sequence)
# Get best total distance and sequence:
self.dist = np.min(self.iterated_dists) # Storing total distance of best iteration
try:
ind = np.where(self.iterated_dists == self.dist)[0][0]
except ValueError:
ind = np.where(self.iterated_dists == self.dist)[0]
self.sequence = self.iterated_sequences[ind] # Storing sequence from best iteration
self.best_iterated_sequences = all_sequences[ind] # Storing all sequences from best iteration
self.best_iterated_dist = all_dists[ind] # Storing all total distances from best iteration
logging.info("Best result: Distance: {d} from Iteration {i}".format(i=ind, d=self.dist))
def set_init(self,
rand: Optional[bool] = True,
init_list: Optional[list] = None):
"""
This function sets the initial route to a given order (init_list) or randomly. If nothing is set, the order will
be set to random.
:param rand: bool
:param init_list: list [int]
:return:
"""
if rand or init_list is None:
# Create random list of numbers between 1 and number of cities minus one:
init_list = list(range(1, self.num - 1))
random.shuffle(init_list)
elif init_list is not None and len(init_list) == self.num:
pass
else:
raise ValueError("init_list not set or does not have a length according to the given dist_frame")
# Put Ismaning at start and end of the list:
init_list = np.concatenate(([0], init_list, [0]))
self.init = init_list
def _get_fulldist(self,
sequence: list) -> Tuple[float, list]:
"""
Internal function to calculate the distances over the given sequence. Returns single distance as well as total
distance.
:param sequence: list [int]
List of the locations in calculated order
:return:
fulldist: float
Total distance for the given sequence
sequence_dist: list [float]
List of all single distances for the given sequence
"""
sequence_dist = []
for i in range(len(sequence) - 1):
sequence_dist.append(self.dist_frame[sequence[i]][sequence[i + 1]])
fulldist = sum(sequence_dist)
return fulldist, sequence_dist
def get_result(self) -> Tuple[list, int]:
"""
This function returns the internal objects containing the resulting sequence (in numbers from 0-20) and total
distance for the respective sequence.
:return:
sequence: list [int]
List of the locations in calculated order
dist: float
Total distance for the given sequence
"""
return self.sequence, self.dist
def get_best_sequences(self) -> Tuple[list, list]:
return self.best_iterated_dist, self.best_iterated_sequences
|
import abc
class Animals(object):
__metaclass__ = abc.ABCMeta
def __init__(self,name,age,gender):
self.name = name
self.age = int(age)
self.gender = gender
@property
def name(self):
return self.__name
@name.setter
def name(self,value):
if value:
self.__name = value
else:
print("Invalid input!")
return
@property
def age(self):
return self.__age
@age.setter
def age(self,value):
if not value or value < 0:
print("Invalid input!")
return
else:
self.__age = value
@abc.abstractmethod
def ProduceSound(self):
pass
@abc.abstractmethod
def DesribeYourself(self):
pass
class Dog(Animals):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
def ProduceSound(self):
return "Woof!"
def DesribeYourself(self):
return "Dog"
class Frog(Animals):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
def ProduceSound(self):
return "Ribbit"
def DesribeYourself(self):
return "Frog"
class Cat(Animals):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
def ProduceSound(self):
return "Meow meow"
def DesribeYourself(self):
return "Cat"
class Kitten(Cat):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
self.sound = sound
@property
def gender(self):
return self.__gender
@gender.setter
def gender(self,value):
self.__gender = 'female'
def ProduceSound(self):
return "Meow"
def DesribeYourself(self):
return "Kitten"
class Tomcat(Cat):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
self.sound = sound
@property
def gender(self):
return self.__gender
@gender.setter
def gender(self,value):
self.__gender = 'male'
def ProduceSound(self):
return "MEOW"
def DesribeYourself(self):
return "Tomcat"
if __name__ == "__main__":
#newCat = Cat(name='Gosho',age = 5, gender = 'female')
#print(newCat.ProduceSound())
animals = []
animal_type = input()
while not animal_type == 'Beast!':
if animal_type == 'Dog':
animal_details = input().split()
new_animal = Dog(name = animal_details[0], age = animal_details[1], gender = animal_details[2])
animals.append(new_animal)
if animal_type == 'Frog':
animal_details = input().split()
new_animal = Frog(name = animal_details[0], age = animal_details[1], gender = animal_details[2])
animals.append(new_animal)
if animal_type == 'Kitten':
animal_details = input().split()
new_animal = Kitten(name = animal_details[0], age = animal_details[1], gender = animal_details[2])
animals.append(new_animal)
if animal_type == 'Tomcat':
animal_details = input().split()
new_animal = Tomcat(name = animal_details[0], age = animal_details[1], gender = animal_details[2])
animals.append(new_animal)
animal_type = input()
for animal in animals:
print(animal.DesribeYourself())
print(f'{animal.name} {animal.age} {animal.gender}')
print(animal.ProduceSound())
|
class Employee:
def __init__(self, name, age=None, salary=None, position=None,
age_input_counter=0, salary_input_counter=0, position_input_counter=0):
self.name = name
self.age = age
self.salary = salary
self.position = position
self.age_input_counter = int(age_input_counter)
self.salary_input_counter = int(salary_input_counter)
self.position_input_counter = int(position_input_counter)
def string_checker(input_value):
reference = None
try:
reference = int(input_value)
input_value = reference
except:
try:
reference = float(input_value)
if int(reference) == float(reference):
reference = int(reference)
input_value = reference
except:
pass
return input_value
if __name__ == "__main__":
input_list = input().split(' -> ')
employee_list = []
age_counter = 0
salary_counter = 0
position_counter = 0
while not input_list[0] == "filter base":
new_employee = Employee(name=input_list[0])
if isinstance(string_checker(input_list[1]), int):
new_employee.age = input_list[1]
age_counter += 1
elif isinstance(string_checker(input_list[1]), float):
new_employee.salary = input_list[1]
salary_counter +=1
else:
new_employee.position = input_list[1]
position_counter += 1
new_employee.position_input_counter += position_counter
if not new_employee.name in [some_employee.name for some_employee in employee_list]:
employee_list.append(new_employee)
else:
for one_employee in employee_list:
if one_employee.name == new_employee.name:
if new_employee.age is not None:
one_employee.age = new_employee.age
one_employee.age_input_counter = age_counter
if new_employee.salary is not None:
one_employee.salary = new_employee.salary
one_employee.salary_input_counter = salary_counter
if new_employee.position is not None:
one_employee.position = new_employee.position
one_employee.position_input_counter = position_counter
input_list = input().split(' -> ')
cmd = input()
if cmd == 'Position':
sorted_list = sorted(employee_list, key=lambda x: x.position_input_counter)
for existing_employee in sorted_list:
if existing_employee.position is not None:
print(f'Name: {existing_employee.name}')
print(f'Position: {existing_employee.position}')
print('====================')
elif cmd == 'Salary':
sorted_list = sorted(employee_list, key=lambda x: x.salary_input_counter)
for existing_employee in sorted_list:
if existing_employee.salary is not None:
print(f'Name: {existing_employee.name}')
print(f'Salary: {existing_employee.salary}')
print('====================')
else:
sorted_list = sorted(employee_list, key=lambda x: x.age_input_counter)
for existing_employee in sorted_list:
if existing_employee.age is not None:
print(f'Name: {existing_employee.name}')
print(f'Age: {existing_employee.age}')
print('====================')
|
import re
def case_checker(word):
capital_flag = 0
lower_flag = 0
for letter in word:
if letter.isupper():
capital_flag += 1
else:
lower_flag += 1
if lower_flag == 0 and word.isalpha():
upper_case.append(word)
elif capital_flag == 0 and word.isalpha():
lower_case.append(word)
else:
mixed_case.append(word)
if __name__ == '__main__':
text = re.split(r'[\;\,\:\.\!\(\)\"\'\\\/\[\]\s]',input())
lower_case = []
mixed_case = []
upper_case = []
for word in text:
case_checker(word)
print('Lower-case: ' + ", ".join(filter(None, lower_case)))
print('Mixed-case: ' + ", ".join(filter(None, mixed_case)))
print('Upper-case: ' + ", ".join(filter(None, upper_case))) |
def check_sign(number):
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
if __name__ == '__main__':
n = int(input())
print(f"The number {n} is {check_sign(n)}.") |
numbers_list = list(map(float, input().split(' ')))
numbers_dict = {item: numbers_list.count(item) for item in numbers_list}
for key,value in sorted(numbers_dict.items()):
print(f"{key} -> {value} times") |
import math
def duplicate_remover(x):
return list(dict.fromkeys(x))
def average_calculator(array):
return sum(list(map(int,array))) - sum(list(map(int,array)))/len(array)
if __name__ == '__main__':
region_dict = {}
input_string = input()
while not input_string == 'Aggregate':
city_list = input_string.split(" ")
if city_list[0] in region_dict:
region_dict[city_list[0]] += city_list[1].split(" ")
else:
region_dict[city_list[0]] = city_list[1].split(" ")
input_string = input()
for k,v in region_dict.items():
region_dict[k] = duplicate_remover(v)
for k,v in region_dict.items():
print(f'{k} -> {", ".join(v)} ({math.ceil(average_calculator(v))})') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.