text
stringlengths 37
1.41M
|
---|
values = [0,1]
def fill_to(number):
start = len(values)
for index in range(start, number+1):
values.append(values[index-2] + values[index-1])
def fib(number):
if len(values) > number:
return values[number]
fill_to(number)
return values[number]
|
"""
Modelar: un auto
atributos:
- una velocidad, al iniciar esta parado
puede:
- puede ver su velocidad
- puede acelerar una determinada velocidad
- puede frenar
"""
velocidadAuto = [10]
def verVelocidad() -> int:
"""Devuelve la velocidad del auto"""
return velocidadAuto[0]
def acelerar(velocidad: int) -> None:
""" Acelera el auto """
velocidadAuto[0] += velocidad
def frenar() -> None:
velocidadAuto[0] = 0
if __name__ == '__main__':
print(verVelocidad())
acelerar(320)
print(verVelocidad())
frenar()
print(verVelocidad())
|
# // A. Way Too Long Words
# // time limit per test1 second
# // memory limit per test256 megabytes
# // inputstandard input
# // outputstandard output
# // Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
# // Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
# // This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
# // Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
# // You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
# // Input
# // The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
# // Output
# // Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
n = int(input())
for i in range(n):
s = input()
if len(s)<=10:
print(s)
else:
print(s[0:1],len(s)-2,s[len(s)-1:len(s)],sep="") |
# Given integers a and b, determine whether the following pseudocode results in an infinite loop
# while a is not equal to b do
# increase a by 1
# decrease b by 1
# Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever.
def isInfiniteProcess(a, b):
if a>b:
return True
elif a%2==0 and b%2==0:
return False
elif a%2!=0 and b%2!=0:
return False
else:
return True |
# D.A.N_3002 Đơn giản 100 Điểm
# Giới hạn ký tự: 3000
# Cho mảng arr chứa các số nguyên. Bạn hãy tính tổng các phần tử ở các vị trí là số nguyên tố trong mảng arr. Biết các vị trí trong mảng đếm bắt đầu từ 1.
# Ví dụ:
# Với arr = [1, 2, 3, 4, 5, 6, 7] thì sumPrimeIndex(arr) = 17.
# Giải thích: các vị trí 2, 3, 5 7 là các vị trí số nguyên tố. ta có arr[2]+arr[3]+arr[5]+arr[7]= 2+3+5+7 = 17
def isPrime(a):
if a<2:
return False
for i in range(2,int(a**0.5)+1):
if a%i==0:
return False
return True
def sumPrimeIndex(arr):
return sum([arr[i] for i in range(len(arr)) if isPrime(i)])
print(sumPrimeIndex([1,2,3,2, 1, 4, 1, 4]))
print(isPrime(3)) |
# You are working on a brand new dictionary. Instead of adding weird contractions for various parts of speech (like v, n, adj, adv, etc.), you decided to provide far more useful information: you put an article before each noun (you haven't chosen between definite and indefinite articles yet, so you use a, an or the), to before each verb, and write all other words as is. This is a dictionary, so the words are still supposed to go in alphabetical order disregarding supplementary words. For example, what was cat (n), hiss (v), kitten (n), meow (v), playful (adj), purr (v), now may become the cat, to hiss, a kitten, to meow, playful, to purr. If a list contains two words which belong to different parts of speech but are written in the same way, include supplementary words into comparison, i.e. to desert should be preceded by the desert, and to upset should go before upset.
# You're afraid that people will not understand your groundbreaking approach. To make sure that your time is not wasted, you decide first to apply your method only to a short list of words, show it to your friends and see how it goes. Before showing the list to friends, you would like to make sure that you didn't mess up the order. Given a list of words wordList (some of which are preceded by supplementary parts), check if they are sorted lexicographically according to the above-described rules.
# Example
# For wordList = ["the cat", "to hiss", "a kitten", "to meow", "playful", "to purr"], the output should be
# unusualDictionary(wordList) = true;
# For wordList = ["to desert", "the desert", "a dessert"], the output should be
# unusualDictionary(wordList) = false.
# The correct order is the desert, to desert, a dessert: the first two words should be compared together with supplementary words (so they differ at the second position where h precedes o), while the last two words should be compared without supplementary words (so they differ at the fourth position where e precedes s).
# .........................................................................
def unusualDictionary(wordList):
def key(w):
xs = w.split()
return (xs[1], xs[0]) if len(xs) >= 2 else (w, w)
return sorted(wordList, key=key) == wordList
print(unusualDictionary(["to desert",
"the desert",
"a dessert"])) |
# Given a string, find the number of different non-empty substrings in it.
# Example
# For inputString = "abac", the output should be
# differentSubstringsTrie(inputString) = 9.
# They are:
# "a", "b", "c",
# "ab", "ac", "ba",
# "aba", "bac",
# "abac"
def differentSubstringsTrie(inputString):
def addNode(lastVersion):
line = []
for i in range(26):
line.append(0)
lastVersion.append(line)
nodesCount = 1
trie = []
addNode(trie)
for i in range(len(inputString)):
currentNode = 0
for j in range(i, len(inputString)):
symbol = ord(inputString[j]) - ord('a')
if trie[currentNode][symbol] == 0:
addNode(trie)
trie[currentNode][symbol] = nodesCount
nodesCount += 1
currentNode = trie[currentNode][symbol]
return nodesCount-1
|
# Find the smallest integer that is divisible by all integers on a given interval [left, right].
# Example
# For left = 2 and right = 4, the output should be
# smallestMultiple(left, right) = 12.
from fractions import gcd
def smallestMultiple(left, right):
res = left
for i in range(left,right+1):
res = (res*i)//gcd(res,i)
return res
|
# A. I Wanna Be the Guy
# time limit per test1 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
# Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
# Input
# The first line contains a single integer n (1 ≤ n ≤ 100).
# The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≤ ai ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.
# Output
# If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).
# Examples
# inputCopy
# 4
# 3 1 2 3
# 2 2 4
# outputCopy
# I become the guy.
# inputCopy
# 4
# 3 1 2 3
# 2 2 3
# outputCopy
# Oh, my keyboard!
n = int(input())
a = list(set([int(i) for i in input().split()]))
b = list(set([int(i) for i in input().split()]))
ok = True
for i in range(1,n+1):
if i not in a and i not in b:
ok = False
break
if ok:
print("I become the guy.")
else:
print("Oh, my keyboard!") |
# A. Beautiful Year
# time limit per test2 seconds
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
# Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
# Input
# The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.
# Output
# Print a single integer — the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
# Examples
# inputCopy
# 1987
# outputCopy
# 2013
# inputCopy
# 2013
# outputCopy
# 2014
#Check year is beatiful
def isBeautifulYear(n):
return len(set([i for i in str(n)]))==len(str(n))
n = int(input())
n +=1
while not isBeautifulYear(n):
n+=1
print(n) |
# A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
# He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
# Input
# The first line contains three positive integers k, n, w (1 ≤ k, w ≤ 1000, 0 ≤ n ≤ 109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
# Output
# Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
k,n,w = input().split(" ")
k,n,w = int(k),int(n),int(w)
def calculator(k,w):
res = 0
for i in range(1,w+1):
res = k*i + res
return res
r = calculator(k,w) - n
print(r) if r>0 else print(0) |
# A. HQ9+
# time limit per test2 seconds
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# HQ9+ is a joke programming language which has only four one-character instructions:
# "H" prints "Hello, World!",
# "Q" prints the source code of the program itself,
# "9" prints the lyrics of "99 Bottles of Beer" song,
# "+" increments the value stored in the internal accumulator.
# Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.
# You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
# Input
# The input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.
# Output
# Output "YES", if executing the program will produce any output, and "NO" otherwise.
# Examples
# inputCopy
# Hi!
# outputCopy
# YES
# inputCopy
# Codeforces
# outputCopy
# NO
cmd = input()
if cmd.count("H") ==0 and cmd.count("Q")==0 and cmd.count("9")==0:
print("NO")
else:
print("YES") |
# A. Boring Apartments
# time limit per test1 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# There is a building consisting of 10 000 apartments numbered from 1 to 10 000, inclusive.
# Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11,2,777,9999 and so on.
# Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order:
# First he calls all apartments consisting of digit 1, in increasing order (1,11,111,1111).
# Next he calls all apartments consisting of digit 2, in increasing order (2,22,222,2222)
# And so on.
# The resident of the boring apartment x answers the call, and our character stops calling anyone further.
# Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.
# For example, if the resident of boring apartment 22 answered, then our character called apartments with numbers 1,11,111,1111,2,22 and the total number of digits he pressed is 1+2+3+4+1+2=13.
# You have to answer t independent test cases.
# Input
# The first line of the input contains one integer t (1≤t≤36) — the number of test cases.
# The only line of the test case contains one integer x (1≤x≤9999) — the apartment number of the resident who answered the call. It is guaranteed that x consists of the same digit.
# Output
# For each test case, print the answer: how many digits our character pressed in total.
# Example
# inputCopy
# 4
# 22
# 9999
# 1
# 777
# outputCopy
# 13
# 90
# 1
# 66
t = int(input())
a = [1,11,111,1111,2,22,222,2222,3,33,333,3333,4,44,444,4444,5,55,555,5555,
6,66,666,6666,7,77,777,7777,8,88,888,8888,9,99,999,9999]
for i in range(t):
n = int(input())
idx = a.index(n)
res = 0
for i in range(0,idx+1):
res+=len(str(a[i]))
print(res) |
# John has just entered a college, and should now pick several courses to take. He knows nothing, except that number x is a bad luck for him, which is why he won't even consider courses whose title consist of x letters.
# Given a list of courses, remove the courses with titles consisting of x letters and return the result.
# Example
# For x = 7 and
# courses = ["Art", "Finance", "Business", "Speech", "History", "Writing", "Statistics"],
# the output should be
# collegeCourses(x, courses) = ["Art", "Business", "Speech", "Statistics"].
#Xoa cac mon hoc co ten bao gom x chu cai
def collegeCourses(x,courses):
def shouldConsider(courses):
return len(courses)!=x
return list(filter(shouldConsider,courses)) |
# Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
# Note, that during capitalization all the letters except the first one remains unchanged.
s = input()
a = [i for i in s]
a[0] = a[0].upper()
print("".join(a))
|
# Define a multiplication table of size n by m as follows: such table consists of n rows and m columns. Cell on the intersection of the ith row and the jth column (i, j > 0) contains the value of i * j.
# Given integers n and m, find the number of different values that are found in the table.
# Example
# For n = 3 and m = 2, the output should be
# differentValuesInMultiplicationTable(n, m) = 5.
def differentValuesInMultiplicationTable(n, m):
res = []
a =[[x*y for x in range(1,n+1) for y in range(1,m+1)]]
for i in range(len(a)):
for j in range(len(a[i])):
res.append(a[i][j])
return len(set(res))
|
# Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# For example, the square matrix is shown below:
# 1 2 3
# 4 5 6
# 9 8 9
# The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .
# Function description
# Complete the function in the editor below.
# diagonalDifference takes the following parameter:
# int arr[n][m]: an array of integers
# Return
# int: the absolute diagonal difference
# Input Format
# The first line contains a single integer, , the number of rows and columns in the square matrix .
# Each of the next lines describes a row, , and consists of space-separated integers .
# Constraints
# Output Format
# Return the absolute difference between the sums of the matrix's two diagonals as a single integer.
# Sample Input
# 3
# 11 2 4
# 4 5 6
# 10 8 -12
# Sample Output
# 15
# Explanation
# The primary diagonal is:
# 11
# 5
# -12
# Sum across the primary diagonal: 11 + 5 - 12 = 4
# The secondary diagonal is:
# 4
# 5
# 10
# Sum across the secondary diagonal: 4 + 5 + 10 = 19
# Difference: |4 - 19| = 15
# Note: |x| is the absolute value of x
# Lay hieu cua 2 duong cheo
def diagonalDifference(arr):
right = 0
left = 0
n = len(arr)-1
for i in range(len(arr)):
left += arr[i][n-i]
for j in range(len(arr[i])):
if i==j:
right += arr[i][j]
return abs(right-left)
print(diagonalDifference([[1,2,3],[4,5,6],[9,8,9]])) |
def restoreString(str, indices):
d = {}
res = ""
for i in range(len(indices)):
d[indices[i]]= str[i]
for i in sorted(d.keys()):
res+=d[i]
return res
#Best solution:
def shuffleString(s,indices):
return ''.join([s[indices.index(counter)] for counter in list(range(len(s)))])
return ''.join([s[indices.index(i)] for i in range(len(s))])
print(restoreString("codeleet",[4,5,6,7,0,2,1,3])) |
# this line prints out a statement
print ("I will now count my chickens:")
#this line counts hens and roosters
print ("Hens", 25.0 + 30.0 / 6.0)
print ("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
#this line counts eggs
print ("Now I will count the eggs:")
#this line does some math
print(3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0)
#this line makes a statement
print("Is it true that 3 + 2 < 5 - 7")
#this line does some math
print(3.0 + 2.0 < 5.0 - 7.0)
#this line prints a statement with math answer
print("What is 3 + 2", 3.0 + 2.0)
print("What is 5-7", 5.0 - 7.0)
#this line prints a statement
print("Oh, that is why its False.")
#printed another statement
print("How about some more.")
#some comparision statements
print("Is it greater?", 5.0 > -2.0)
print("Is it greater or equal?", 5.0 >= -2.0)
print("Is it less or equal?", 5.0 <= -2.0)
|
# assigns this variable to 10
types_of_people = 10
# assigns a variable of x to this phrase
x = f"There are {types_of_people} types of people."
# assigns variable binary to a string
binary = "binary"
# assigns variable to a string
do_not = "don't"
# creates a variable assigned to a string concatenation
y = f"Those who know {binary} and those who {do_not}."
#prints the 2 strings
print(x)
print(y)
# creates a printed statement with the variables assigned inside
print(f"I said: {x}")
print(f"I also said: '{y}'")
# assigns a variable hilarious to false
hilarious = False
# assigns a variable of joke_evaluation to a string
joke_evaluation = "isnt that joke so funny?! {}"
# prints the joke statement
print(joke_evaluation.format(hilarious))
# assigns these variables to strings
w = "this is the left side of .."
e = " a string with a right side."
# concatenates the strings
print (w + e)
|
from abc import ABC, abstractmethod
__copyright__ = "Copyright © 2020 RPS Group, Inc. All rights reserved."
__license__ = "See LICENSE.txt"
__email__ = "[email protected]"
class StorageService(ABC):
""" Abstract base class for cloud storage.
It defines a generic interface to implement
"""
def __init__(self):
return
@abstractmethod
def uploadFile(self, filename: str, bucket: str, key: str, public: bool = False):
""" Interface to upload a file to the storage provider
Parameters
----------
filename : str
The path and filename to upload
bucket : str
The S3 bucket to use
key : str
The key to store the file as
public : bool
If file should be made publicly accessible or not
"""
pass
@abstractmethod
def downloadFile(self, bucket: str, key: str, filename: str):
""" Interface to download a file from the storage provider
Parameters
----------
bucket : str
The S3 bucket to use
key : str
The key for the file
filename : str
The path and filename to save the file as
"""
pass
@abstractmethod
def file_exists(self, bucket: str, key: str):
""" Test if the specified file exists in the storage provider bucket
Parameters
----------
bucket : str
The S3 bucket to use
key : str
The S3 key for the file to check
Returns
-------
bool
True if file exists
False if file does not exist
"""
pass
if __name__ == '__main__':
pass
|
""""Ejercicio 3: Imprimir una columna de asteriscos,
donde su altura se recibe como parámetro"""
#funcion
def asterix(a):
for i in range (0,a):
print( "*")
#programa
alt=int(input("ingrese altura de columna:"))
print=asterix(alt) |
"""Ejercicio 1: Dados dos parámetros numéricos,
calcular y devolver el resultado de la multiplicación
de ambos utilizando sólo sumas."""
#funcion sumulti
def sumulti (a,b):
suma=0
for i in range(0,b):
suma=suma+a
return suma
#programa
nro1=int(input("ingrese nro 1: "))
nro2=int(input("ingrese nro 2: "))
resultado=sumulti(nro1, nro2)
print("El nro1 multiplicado por el nro2 es: ", resultado) |
#TRABAJO PRACTICO Nº 2
#Ejercicio 1
#Paso 1: Introducir dos variables de enteros
nro1=int(input("Ingrese un numero: "))
nro2=int(input("Ingrese otro numero: "))
#Paso 2: Operar variables
suma=nro1+nro2
dif=nro1-nro2
#Paso 3: Devolver resultado
print("La suma entre ", nro1, " y ", nro2, "es: ", suma)
print("La diferencia entre ", nro1, " y ", nro2, " es: ", dif)
|
#Ejercicio 4: Invertir aquellos valores ubicados en posiciones impares de una lista.
def dolist():
listex=[]
nro=int(input("ingrese nro: "))
while nro!=-1:
if nro>0 and nro<21:
listex.append(nro)
else:
print("nro no valido")
nro=int(input("ingrese nro: "))
return (listex)
def invertidex(a):
largo=len(a)
#va saltando de a dos desde la primera hasta la ultima cifra de la lista
for i in range(1,largo,2):
a[i]=a[i]*-1
return a
lista=dolist()
res=lista
print(res)
invertida=invertidex(res)
print(invertida) |
nro=int(input("ingrese nro positivo (-1 para salir): "))
binario="."
while nro!=-1:
if nro>=0:
if nro>=2:
if nro%2==0:
binario="0"+ binario
nro=nro//2
else:
binario="1" + binario
nro=nro//2
else:
if nro==1:
binario="1"+binario
nro=-1
else:
binario="0"+binario
nro=-1
print("el nro ingresado en binario es: ", binario)
else:
print("el numero ingresado no es positivo")
print("fin del conteo")
|
#ENCUESTA
#defino iteración
i=1
#defino consumidor
costumer=1
#defino valores de verdad a y b
a=0
b=0
#cantidades
aa=0
bb=0
justa=0
justb=0
none=0
both=0
while i<=100:
print("Bienvenido cliente Nro", costumer,"!")
acca=int(input("Acepta A? Si=1 / No=0: "))
if acca==1:
a=1
aa=aa+1
else:
a=0
accb=int(input("Acepta B? Si=1 / No=0: "))
if accb==1:
b=1
bb=bb+1
else:
b=0
if a==1 and b==0:
justa=justa+1
if a==0 and b==1:
justb=justb+1
if a==0 and b==0:
none=none+1
if a==1 and b==1:
both=both+1
i=i+1
costumer=costumer+1
print("cant a: ", aa)
print("cant b: ", bb)
print("cant a y no b: ", justa)
print("cant b y no a: ", justb)
print("cant ninguna: ", none)
print("cant ambas: ", both)
|
"""
EJERCICIO EXTRA FUNDAMENTOS-
Leer dos listas de numeros M y N , ambas ordenadas de menor a mayor.
Generar e imprimir una tercera lista que resulte de intercalar todos los elementos de M y N.
La nueva lista también debe quedar ordenada, sin usar ningun metodo de ordenamiento
"""
#Funciones
def generarLista():
l=[]
print("Ingrese numeros a su lista. (-1 para finalizar)")
while len(l)==0:
print("Debe ingresar por lo menos un valor a la lista")
n=int(input("Ingrese numero: "))
while n != (-1):
l.append(n)
n=int(input("Ingrese numero: "))
return l
def seleccion(l):
for i in range (len(l)-1):
for j in range (i+1, len(l)):
if l[i]>l[j]:
aux=l[i]
l[i]=l[j]
l[j]=aux
return l
def maxMas1(l,k):
largol=len(l)
largok=len(k)
valorl=l[largol-1]+1
valork=k[largok-1]+1
mayor=valorl
if valorl<valork:
mayor=valork
return mayor
def app0(l,n):
l.append(n)
return l
#Programa
#1)
print("------LISTA M------")
m=seleccion(generarLista())
print("------LISTA N------")
n=seleccion(generarLista())
#2)
ciego=maxMas1(m,n)
mrange=app0(m,ciego)
nrange=app0(n,ciego)
#3)
ñ=[]
vM=0
vN=0
while (vN<(len(n)-1)) or (vM<(len(m)-1)):
if (m[vM])==(n[vN]):
ñ.append(m[vM])
ñ.append(n[vN])
vM=vM+1
vN=vN+1
else:
if (m[vM])>(n[vN]):
ñ.append(n[vN])
vN=vN+1
else:
if (m[vM])<(n[vN]):
ñ.append(m[vM])
vM=vM+1
#4
m=m.pop()
n=n.pop()
print("-------------------------------------------------------------")
print ("M=", mrange)
print ("N=", nrange)
print ("La lista intercalada es: Ñ=", ñ)
"""
ESTRATEGIA:
1) El usuario genera dos listas, M y N, previendo que no pueden quedar vacías.
Se ordenan con Método de Selección.
2) A las listas se les agrega un "numero ciego".
Se genera tomando el mayor valor de las listas y se le suma 1.
Este numero ciego no se agrega a la lista final "Ñ", y sólo
sirve para que no quede fuera de rango el programa que las une y ordena.
3) El programa principal almacena en la lista "Ñ" los valores de las 2 listas,
de menor a mayor. Para ello, sigue los siguientes pasos:
-Se genera un contador de subíndices por lista, iniciado en 0,
que va a ir aumentando a medida que se agreguen valores de la lista M o N respectivamente.
-Si los valores tomados son iguales, se agregan ambos y se aumentan ambos contadores.
Si el valor tomado de la lista M es menor que el de la N, se agrega el de la M y
se aumenta su contador. Obviamente, lo mismo sucede con los valores de la lista N.
4) Finalmente, se imprimen las listas M y N, ambas sin el numero ciego, y la lista Ñ.
"""
|
# -------------------- Section 3 -------------------- #
# ---------- Part 1 | Patterns ---------- #
print(
'>> Section 3\n'
'>> Part 1\n'
)
# 1 - for Loop | Patterns
# Create a function that will calculate and print the first n numbers of the fibonacci sequence.
# n is specified by the user.
#
# NOTE: You can assume that the user will enter a number larger than 2
#
# Example Output
#
# >> size... 6
#
# 1, 1, 2, 3, 5, 8
#
# Write Code Below #
user=int(input("Enter a term higher than 2: "))
def fibonacci(n):
sequence = [0,1]
for i in range(2,n+1):
next_num = sequence[-1] + sequence[-2]
sequence.append(next_num)
return sequence
sequence = fibonacci(user)
print(sequence) |
C = input('來自哪個國家:')
Y = input('請書輸入年齡:')
Y = int(Y)
if C == '台灣':
if Y >= 18:
print('可以考駕照')
else:
print('你還不能考駕')
elif C == '美國':
if Y >= 16 :
print('可以開車')
else :
print('不能開車')
|
'''
@version: 1.1
@since: 21.03.2015
@author: Alexander Kuzmin
@return: None
@note: print a table with frequencies of letters in sorted order
'''
from sys import stdin
from operator import itemgetter
from collections import Counter
__author__ = 'Alexander Kuzmin'
def getSortedTableWithFrequencies(text):
letters_counter = Counter()
for word in text:
lower_word = word.lower()
if lower_word.isalpha():
letters_counter[lower_word] += 1
return sorted(sorted(letters_counter.items(), key=itemgetter(0)),
key=itemgetter(1), reverse=True)
if __name__ == '__main__':
for line in getSortedTableWithFrequencies(stdin.read()):
print("{0}: {1}".format(line[0], line[1]))
|
'''
@version: 1.0
@since: 07.04.2015
@author: Alexander Kuzmin
@note: Tools for processing a text: tokenizing, writing probabilities, generating and testing.
'''
#import enum # there are no such module in the contest
import argparse
import unittest
import random
import sys
from collections import Counter, defaultdict
from copy import copy
from itertools import chain
from operator import itemgetter
__author__ = 'Alexander Kuzmin'
def BinSearch(arr, predicate):
'''
Binary search by predicate.
:param arr: list - where to search
:param predicate: function - we looking for the element that satisfies the predicate
:return: index of the first element that satisfies predicate(element) is True
'''
left, right = 0, len(arr) - 1
while left <= right:
mid = int(left + (right - left) / 2)
if predicate(arr[mid]):
if not predicate(arr[mid - 1]) or mid == 0:
return mid
right = mid - 1
else:
left = mid + 1
return -1
def ToProcessText(input_text, args):
'''
Processor of the input_text.
:param input_text: list of texts - the texts to be needed to process.
:param args: argparse.ArgumentParser() - the command to be processed and the arguments for it.
:return: result of command process.
'''
if (args.command == 'tokenize'):
if (len(input_text) > 0):
return Tokenize(input_text[0])
elif (args.command == 'probabilities'):
return GetProbabilities(input_text, args.depth)
elif (args.command == 'generate'):
return Generate(input_text, args.depth, args.size)
elif (args.command == 'test'):
return UnitTests()
# there are no module enum.Enum() in the contest
class State:
alpha = 1
digit = 2
punctuation = 3
space = 4
def Tokenize(text):
'''
Tokenize the current text.
:param text: str - the text to be needed to tokenize.
:return: list of tokens.
'''
tokens = []
# there are no module enum in the contest
# state = enum.Enum('state', 'alpha digit space punctuation')
current_token = []
current_state = -1
for letter in text:
if letter.isalpha():
if current_state == State.alpha:
current_token.append(letter)
else:
tokens.append("".join(current_token))
current_state = State.alpha
current_token = [letter]
elif letter.isdigit():
if current_state == State.digit:
current_token.append(letter)
else:
tokens.append("".join(current_token))
current_state = State.digit
current_token = [letter]
elif letter.isspace():
if current_state == State.space:
current_token.append(letter)
else:
tokens.append("".join(current_token))
current_state = State.space
current_token = [letter]
else:
if current_state == State.punctuation:
current_token.append(letter)
else:
tokens.append("".join(current_token))
current_state = State.punctuation
current_token = [letter]
tokens.append("".join(current_token))
return tokens[1:]
def GetNGrams(tokens, n, predicate, tokens_counter=defaultdict(Counter)):
'''
put words n_grams from the list of different tokens into tokens_counter
:param tokens: list fo str - the list of tokens
:param n: int - the amount of words in one n-gram
:param predicate: object - determines the correct predicates: predicate(token) should be true
:param tokens_counter: collections.defaultdict - buffer for n-grams (may be not empty!)
:return: defaultdict = collections.defaultdict of collections.Counter - dict of n-grams:
'd-gram[:-1]': ('d-gram[-1]' : count)
'''
n_gram = []
index = 0
while (len(n_gram) != n + 1 and index < len(tokens)):
if predicate(tokens[index]):
n_gram.append(tokens[index])
index += 1
if (len(n_gram) == 0):
return tokens_counter
tokens_counter[tuple(n_gram[:-1])][n_gram[-1]] += 1
while (index < len(tokens)):
if predicate(tokens[index]):
n_gram.pop(0)
n_gram.append(tokens[index])
tokens_counter[tuple(n_gram[:-1])][n_gram[-1]] += 1
index += 1
return tokens_counter
def GetProbabilities(input_text, depth):
'''
Get Probabilities of the text chains.
:param input_text: list of str - the texts to be needed to tokenize.
:param depth: int - the depth of the chain.
:return: list of defauldict of Counters:
'd-gram[:-1]': ('d-gram[-1]' : probability) for each d in 0..depth
'''
list_of_probabilities_counters = []
tokens_lists = [Tokenize(text) for text in input_text]
for current_depth in range(depth + 1):
tokens_counter = defaultdict(Counter)
for tokens in tokens_lists:
tokens_counter = GetNGrams(tokens,
current_depth,
lambda x: x.isalpha(),
tokens_counter)
total_count = {k: sum(v.values()) for k, v in tokens_counter.items()}
list_of_probabilities_counters.append(
{prefix: {k: v / total_count[prefix] for k, v in counter.items()}
for prefix, counter in tokens_counter.items()})
return list_of_probabilities_counters
def Generate(input_text, depth, size, seed=None):
'''
generate new text according with probabilities of depth-grams from the text
:param text: list of str - text, from which we get distribution of d-grams
:param depth: int - the depth (length) of d-grams
:param size: int - the length of the text
:param seed: int - random seed for random.seed()
:return: generated text
'''
random.seed(seed)
n_gram_probabilities = defaultdict(Counter)
for line in input_text:
n_gram_probabilities = GetNGrams(Tokenize(line),
depth,
lambda x: not x.isspace() and not x.isdigit(),
n_gram_probabilities)
total_arrays = {key: list(chain(*[[k] * v for k, v in counter.items()]))
for key, counter in n_gram_probabilities.items()}
prefices = [word for word in n_gram_probabilities.keys()
if len(word) == 0 or word[0][0].isupper()]
generated_text = []
prefix_tokens = []
if (prefices != []):
prefix_tokens = list(random.choice(prefices))
for token in prefix_tokens:
if token[0].isalpha():
generated_text.append(token)
else:
generated_text[-1] += token
current_size = sum([len(word) for word in generated_text])
while(current_size < size):
current_array = total_arrays.get(tuple(prefix_tokens))
if (current_array is not None):
word = random.choice(current_array)
if word[0].isalpha():
generated_text.append(word)
else:
generated_text[-1] += word
current_size += len(word) + 1
prefix_tokens.append(word)
prefix_tokens.pop(0)
else:
# is punctuation
if (len(prefix_tokens) > 0 and not prefix_tokens[-1][-1].isalpha()):
prefix_tokens = []
if (prefices != []):
prefix_tokens = list(random.choice(prefices))
else:
prefix_tokens = list(random.choice(list(n_gram_probabilities.keys())))
for token in prefix_tokens:
if token[0].isalpha():
generated_text.append(token)
else:
generated_text[-1] += token
current_size += sum([len(word) for word in prefix_tokens]) + 1
return " ".join(generated_text)
class TestProgram(unittest.TestCase):
'''
Unit tests for the program
'''
def test_Tokenize_01(self):
self.assertListEqual(Tokenize("Hello, world!"),
["Hello", ",", " ", "world", "!"],
"Tokenize test failed.")
def test_Tokenize_02(self):
self.assertListEqual(Tokenize("Abracadabra"), ["Abracadabra"], "Tokenize test failed.")
def test_Tokenize_03(self):
self.assertListEqual(Tokenize("18572305232"), ["18572305232"], "Tokenize test failed.")
def test_Tokenize_04(self):
self.assertListEqual(Tokenize(",!...%^&*@()!@"),
[",!...%^&*@()!@"],
"Tokenize test failed.")
def test_Tokenize_04(self):
self.assertListEqual(Tokenize(" "), [" "], "Tokenize test failed.")
def test_Tokenize_05(self):
self.assertListEqual(
Tokenize("What's that? I don't know..."),
["What", "'", "s", " ", "that", "?", " ",
"I", " ", "don", "'", "t", " ", "know", "..."],
"Tokenize test failed.")
def test_Tokenize_06(self):
self.assertListEqual(Tokenize("2kj2h5^fa$s.64f"),
["2", "kj", "2", "h", "5", "^", "fa", "$", "s", ".", "64", "f"],
"Tokenize test failed.")
def test_Tokenize_07(self):
self.assertListEqual(Tokenize(" "),
[" "],
"Tokenize test failed.")
def test_Probabilities_01(self):
self.assertListEqual(
GetProbabilities(["First test string", "Second test line"], 1),
[{(): {'First': 0.16666666666666666,
'line': 0.16666666666666666,
'string': 0.16666666666666666,
'test': 0.3333333333333333,
'Second': 0.16666666666666666}},
{('First',): {'test': 1.0},
('test',): {'line': 0.5, 'string': 0.5},
('Second',): {'test': 1.0}}],
"Probabilities test failed.")
def test_Probabilities_02(self):
self.assertListEqual(
GetProbabilities(["a a a a a", "b b b b b b"], 1),
[{(): {'a': 0.45454545454545453, 'b': 0.5454545454545454}},
{('a',): {'a': 1.0}, ('b',): {'b': 1.0}}],
"Probabilities test failed.")
def test_Probabilities_03(self):
self.assertListEqual(
GetProbabilities(["a b c d e f g"], 4),
[{(): {'a': 0.14285714285714285,
'b': 0.14285714285714285,
'c': 0.14285714285714285,
'f': 0.14285714285714285,
'e': 0.14285714285714285,
'd': 0.14285714285714285,
'g': 0.14285714285714285}},
{('a',): {'b': 1.0},
('b',): {'c': 1.0},
('c',): {'d': 1.0},
('d',): {'e': 1.0},
('e',): {'f': 1.0},
('f',): {'g': 1.0}},
{('a', 'b'): {'c': 1.0},
('b', 'c'): {'d': 1.0},
('c', 'd'): {'e': 1.0},
('d', 'e'): {'f': 1.0},
('e', 'f'): {'g': 1.0}},
{('a', 'b', 'c'): {'d': 1.0},
('b', 'c', 'd'): {'e': 1.0},
('c', 'd', 'e'): {'f': 1.0},
('d', 'e', 'f'): {'g': 1.0}},
{('a', 'b', 'c', 'd'): {'e': 1.0},
('b', 'c', 'd', 'e'): {'f': 1.0},
('c', 'd', 'e', 'f'): {'g': 1.0}}],
"Probabilities test failed.")
def test_Probabilities_04(self):
self.assertListEqual(GetProbabilities(["a b c"], 10),
[{(): {'a': 0.3333333333333333,
'b': 0.3333333333333333,
'c': 0.3333333333333333}},
{('a',): {'b': 1.0},
('b',): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}},
{('a', 'b'): {'c': 1.0}}],
"Probabilities test failed.")
def test_Probabilities_05(self):
self.assertListEqual(GetProbabilities(["Hello, world!"], 1),
[{(): {'world': 0.5, 'Hello': 0.5}},
{('Hello',): {'world': 1.0}}],
"Probabilities test failed.")
def test_Generate_01(self):
self.assertLess(
len(Generate(["Python - активно развивающийся язык программирования, новые версии "
"(с добавлением/изменением языковых свойств) выходят примерно раз в два"
" с половиной года.",
"Вследствие этого и некоторых других причин на Python отсутствуют "
"стандарт ANSI, ISO или другие официальные стандарты, их роль "
"выполняет CPython."],
1,
10,
seed=321)),
30,
"Generate test failed.")
def test_Generate_02(self):
self.assertGreater(
len(Generate(["Python - активно развивающийся язык программирования, новые версии "
"(с добавлением/изменением языковых свойств) выходят примерно раз в два"
" с половиной года.",
"Вследствие этого и некоторых других причин на Python отсутствуют "
"стандарт ANSI, ISO или другие официальные стандарты, их роль "
"выполняет CPython."],
10,
10,
seed=321)),
40,
"Generate test failed.")
def UnitTests():
'''
Unit tests for the program
:return: None
'''
unittest.main()
def ReadInputText(args):
'''
read input data depending on args
:param args: argparse.ArgumentParser() - the arguments of the program.
:return: list of str - text from the input
'''
input_text = []
if args.command == 'tokenize':
input_text.append(input())
elif (args.command == 'generate' or args.command == 'probabilities'):
for text in sys.stdin:
input_text.append(text)
elif (args.command == 'test'):
None
return input_text
def Print(text, args):
'''
print the text in format according with args
:param text: str - the text to be printed.
:param args: argparse.ArgumentParser() - the command to be processed and the arguments for it.
:return: None
'''
if (args.command == 'tokenize'):
for word in text:
print(word)
elif (args.command == 'generate'):
with open("output.txt", "w", encoding='utf-8') as writer:
writer.write(text)
elif (args.command == 'probabilities'):
for depth_dict in text:
sorted_keys = sorted(depth_dict.keys())
for prefix in sorted_keys:
print(" ".join(prefix))
sorted_dict = sorted(depth_dict[prefix].items(), key=itemgetter(0))
for word, count in sorted_dict:
print(" {0}: {1:.2f}".format(word, count))
elif (args.command == 'test'):
None
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.description = ("Tools for processing a text: tokenizing, writing probabilities, "
"generating and testing.")
parser.add_argument("command", type=str,
help="command to process")
parser.add_argument("-d", "--depth", action="store", type=int, default=1,
help="The maximum depth of chains.")
parser.add_argument("-s", "--size", action="store", type=int, default=32,
help="Approximate amount of words for generating.")
input_text = []
with open("input.txt", encoding='utf-8') as reader:
input_text = reader.read()
input_text = input_text.split("\n")
args = parser.parse_args(input_text[0].split())
Print(ToProcessText(input_text[1:], args), args)
# args = parser.parse_args(input().split())
# input_text = ReadInputText(args)
# Print(ToProcessText(input_text, args), args)
|
import pandas as pd
from types import MethodType
ATTRIBUTES = {'loc', 'iloc', 'ix', 'index', 'shape', 'values'}
def _operator(op):
def func(self, *args, **kwargs):
operations = self._operations + [(op, args, kwargs)]
return Where(operations)
return func
class Where(object):
"""
Usage examples:
from generic_utils.pandas.where import where as W
df = pd.DataFrame([[1, 2, True],
[3, 4, False],
[5, 7, True]],
index=range(3), columns=['a', 'b', 'c'])
# On specific column:
print(df.loc[W['a'] > 2])
print(df.loc[-W['a'] == W['b']])
print(df.loc[~W['c']])
# On entire - or subset of a - DataFrame:
print(df.loc[W.sum(axis=1) > 3])
print(df.loc[W[['a', 'b']].diff(axis=1)['b'] > 1])
# Reusable conditions:
increased = (W['a'] > W.loc[0, 'a']) | (W['b'] > W.loc[0, 'b'])
print("Increased:\n", df.loc[increased])
print("Decreased:\n", (-df).loc[increased])
# Filter based on index:
to_keep = ((W.index % 3 == 1) &
(W.index % 2 == 1))
print("Non-multiples:\n", df.loc[to_keep])
"""
def __init__(self, operations=[]):
self._operations = operations
def __getattr__(self, attr):
if attr in ATTRIBUTES:
# Just transform this into something callable, for uniformity:
return Where(self._operations + [('__getattribute__',
(attr,), {})])
return MethodType(_operator(attr), self)
def _evaluate(self, obj):
res = obj
for method, args, kwargs in self._operations:
args = list(args)
for idx, arg in enumerate(args):
if isinstance(arg, Where):
args[idx] = arg._evaluate(obj)
for key in kwargs:
if isinstance(kwargs[key], Where):
kwargs[key] = kwargs[key]._evaluate(obj)
res = getattr(res, method)(*args, **kwargs)
return res
# Since Python checks "hasattr" for these to understand wether an operation is
# supported, the "__getattr__" above is not sufficient:
for op in ('lt', 'le', 'eq', 'ne', 'ge', 'gt',
'invert',
'and', 'or', 'xor',
'add', 'sub', 'mul', 'floordiv', 'truediv', 'pow',
'mod',
'neg', 'pos',
'getitem'):
op_label = '__{}__'.format(op)
setattr(Where, op_label, _operator(op_label))
# Monkey patching:
_old_getitem_axis = pd.core.indexing._LocIndexer._getitem_axis
def _new_getitem_axis(self, key, axis=None):
if isinstance(key, Where):
new_key = key._evaluate(self.obj)
return _old_getitem_axis(self, new_key, axis=axis)
return _old_getitem_axis(self, key, axis=axis)
pd.core.indexing._LocIndexer._getitem_axis = _new_getitem_axis
where = Where()
|
# set ====================================================================
# l = [1,2,3,5,6,7,8]
# d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
# d2 = dict({'Michael': 95, 'Bob': 75, 'Tracy': 85})
# # print(d,d2)
# s = set(l)
# # print(s.pop(), s.remove())
# print(l.pop(1), l.remove(8))
# print(l)
a = {1,2,3,0,4}
b = {4,5,6,0}
c = {7,8,9}
print(a&b)
print(a|b)
print(a-b)
print(a^b)
|
# type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
# 我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
# type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
# 要创建一个class对象,type()函数依次传入3个参数:
# 1. class的名称;
# 2. 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
# 3. class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
# 通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
# 正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。
def fn(self, name='word'):
print('Hello, %s' % name)
Hello = type('Hello', (object,), dict(hello = fn))
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import pyautogui, time
# 获取焦点
pyautogui.click(200,200)
pyautogui.typewrite('hello world!', 0.1)
pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y'], 0.1)
pyautogui.keyDown('shift')
pyautogui.press('4')
pyautogui.keyUp('shift')
def commentAfterDelay():
# pyautogui.click(200,200)
# pyautogui.typewrite('\n')
pyautogui.press('enter')
pyautogui.typewrite('In IDLE, alt-3 comments out a line', 0.1)
time.sleep(1)
pyautogui.hotkey('ctrl', 'a')
commentAfterDelay()
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
my_list = [12, 5, 13, 8, 9, 65, 1, 2,6]
# def bubble(bad_list):
# length = len(bad_list) - 1
# sorted = False
# while not sorted:
# sorted = True
# for i in range(length):
# if bad_list[i] > bad_list[i+1]:
# sorted = False
# bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
# my_list = [12, 5, 13, 8, 9, 65,1]
def bubble(bad_list):
length = len(bad_list) - 1
for j in range(length):
for i in range(length):
if bad_list[i] > bad_list[i+1]:
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
bubble(my_list)
print (my_list)
|
# test __str__ __repr__====================================
# class Student(object):
# def __init__(self, name):
# self.name = name
# def get_name(self):
# return self.name
# def __str__(self):
# return 'Student object (name: %s)' % (self.name)
# def __repr__(self):
# return self.__str__()
# __repr__ = __str__
# s = Student('xvc')
# # 类可以直接访问实例方法,不过好像得传入实例 =============================
# name = Student.get_name(Student('d'))
# print(name)
# print(s)
|
# source.py for Algorithms - Project 1
#
# This program implements a simple asymmetric cryptography system for use
# in cybersecurity applications
#
# @author Ross Adams, Longtin Hang, and Riley Williams
import math
import random
def test_prime_brute_force(p=10):
if p == 2:
return True
else:
for b in range(2, math.floor(math.sqrt(p))):
if math.gcd(p, b) > 1:
return False
else:
continue
return True
def generating_prime_numbers():
my_prime_list = []
i = 0
while len(my_prime_list) != 10 and i < 1000:
value = random.randint(10000, 20000)
if test_prime_brute_force(value):
my_prime_list.append(value)
i += 1
return my_prime_list
def calc_n_fn(p, q):
n = p * q
fn = (p-1) * (q-1)
return n, fn
def extended_gcd(a=1,b=1):
if a < b:
a, b = b, a
print('Switched two arguments to ensure a >= b.')
if b == 0:
return 1, 0, a
(x, y, d) = extended_gcd(b, a % b)
return y, x - a//b*y, d
def generate_keys():
# Public key
primes = generating_prime_numbers()
while True:
p = primes[random.randint(0, len(primes) - 1)]
q = primes[random.randint(0, len(primes) - 1)]
if math.gcd(p, q) == 1:
break
n, fn = calc_n_fn(p, q)
while True:
e = random.randint(2, fn)
if math.gcd(fn, e) == 1:
break
# Private key
(x, y, d) = extended_gcd(fn, e)
if y < 0:
y += fn
return n, e, y
def encrypt_message(message='Hello', e=5, n=119):
encrypted = []
for i in range(0, len(message)):
a = ord(message[i])
c = pow(a, e, n)
encrypted.append(c)
return encrypted
def decrypt_message(encrypted=[4, 33, 75, 75, 76], d=77, n=119):
decrypted = ''
for i in range(0, len(encrypted)):
a = encrypted[i]
m = pow(a, d, n)
decrypted = decrypted + chr(m)
return decrypted
def main_menu():
print('\nWelcome to the RSA encryption and decryption service.')
while True:
print('\nMain Menu')
menu_input = input('Input(1) for Message, Input(2) for Digital Signature, Input(3) to quit: ')
if menu_input == '1':
message_menu()
elif menu_input == '2':
digital_signature_menu()
elif menu_input == '3':
break
else:
print('You have enter the wrong input')
def message_menu():
n, e, y = generate_keys()
while True:
print('\nMessage Menu')
menu_input = input('Select (1) for Encryption,(2) for Decryption, or (3) to Return: ')
if menu_input == '1':
message = input('Message to encrypt: ')
encrypted_message = encrypt_message(message, e, n)
print('\nEncrypted message: ', encrypted_message)
print('The magic phrase: This group gets a 100')
elif menu_input == '2':
while True:
message = input('Enter the magic phrase: ').upper()
if message == 'THIS GROUP GETS A 100':
message = decrypt_message(encrypted_message, y, n)
print('\nDecrypted message: ', message)
break
elif message == '999':
break
else:
print('\nYou have enter the wrong magic word!')
print('Enter 999 to return to the menu: ')
elif menu_input == '3':
break
else:
print('Invalid input. Try again.')
def digital_signature_menu():
n, e, y = generate_keys()
while True:
print('\nDigital Signature Menu')
menu_input = input('Select (1) to Sign, (2) to Verify, or (3) to Return: ')
if menu_input == '1':
signature = input('Signature: ')
encrypted_signature = encrypt_message(signature, y, n)
print('\nEncrypted signature: ', encrypted_signature)
elif menu_input == '2':
signature = decrypt_message(encrypted_signature, e, n)
print('\nDecrypted signature: ', signature)
elif menu_input == '3':
break
else:
print('\nInvalid input. Try again.')
def main():
main_menu()
main_menu()
|
# basic print string
print("myBeautifulString")
# passing an array
print(["m", "y", "A", "r", "r", "y"])
# splitting the array as positional arguments
print(*["m", "y", "A", "r", "r", "y"])
# printing the array as one string
print(*["m", "y", "A", "r", "r", "y"], sep="")
# printing two lines as one string
print(*["m", "y"], sep="", end="")
print(*["A", "r", "r", "y"], sep="")
# prints to a file
fsock = open("debbuging.log", "w") # this returns a file object that has a write(string) method
print("Printing in a file debbuging my code", file = fsock)
# outputs each print in execution time to the default output
print("MyFirstPrint", flush=True)
print("MySecondPrint", flush=True)
print("MyThirdPrint", flush=True)
|
if __name__ == "__main__":
xo=str(input("Ingrese el valor de la semilla: "))
n=int(len(xo)/2)
if len(xo)%2==0: #Si el modulo 2 del tamaño de la semilla es cero entonces...
veces=int(input("Ingrese la cantidad de numeros a generar: "))
for i in range(veces):
d=len(xo)
zero=""
xo=int(xo)
xo2=xo*xo
y=str(xo2)
for j in range((4*n)-len(y)):
zero+="0"
y=zero+y
xo=str(xo)
y2=y[int((2*d)/4):int((2*d*3)/4)] #Se escoge la mitad del numero total
print 'x =',y2
out=y2
xo=out
i=i+1
else:
print("Intente de nuevo con un numero de cifras par") |
#!/usr/bin/env python3
import sys
from datetime import datetime
found = False
data = []
frequency = 0
loops = 0
duplicates = []
duplicates.append(frequency)
def calc_freq(total, arg ):
if arg.startswith("+"):
total = total + int(arg.lstrip('-'))
elif arg.startswith("-"):
total = total - int(arg.lstrip('-'))
else:
raise Exception("unknown operand")
return total
for line in sys.stdin:
data.append(line.rstrip("\n"))
while found == False:
loops = loops + 1
if loops % 100 == 0:
print("{} loops = {} duplicates = {}".format(datetime.now().time(), loops, len(duplicates)))
for value in data:
frequency = calc_freq(frequency,value )
if frequency in duplicates:
print("Found duplicate: {}".format(frequency))
print("Loop count {}".format(loops))
sys.exit(0)
duplicates.append(frequency)
|
s1 = input().strip()
s2 = input().strip()
s1 = s1.replace(s2.upper(), '').replace(s2.lower(), '')
print("result: {}".format(s1))
|
a = input()
cnt=0
for n in a :
if n.isupper() and n!="A" and n!="E" and n!="I" and n!="O" and n!="U":
cnt=cnt+1
print(cnt)
|
def isPrime(num):
if not num.isdigit():
return False
elif int(num) == 1:
return False
elif int(num) == 2:
return True
else :
for i in range(2,int(num)):
if int(num) % i == 0:
return False
return True
|
x=int(input())
if(x<=15):
y=4*x/3
print("{:.2f}".format(y))
else:
y=x*2.5-17.5
print("{:.2f}".format(y))
|
# example of a loop
# for i in [2,4,5,6,7]:#using actual values
# print("i = ",i)
#
# for i in range(10):#cycles through the range, from 0 for 10 values not to 10!
# print("i = ", i)
#
#
# for i in range(2,10):#cycles through the range, from 2 for 10 values not to 10!
# print("i = ", i)
#
# using modulus
# i = 2
# print((i%2==0))
# Use for loop to cycle list from 1 to 21
for i in range(1,21):
# Use modulus to check for NOT equal to 0
if (i % 2 != 0):
# Print the Odds
print(i) |
# we'll provide different outputs dependent on age
# 1 - 18 > Important
# 21, 50, > 65 > Important
# All others > Not Important
# Receive age and store in age
age = eval(input("Enter age: "))
# and : If both are true it returns true
# or : If either are true it returns true
# not : Converts true to false
# if statement age is both greater than or equal and less than or equal to 18 Important
if (age >= 1) and (age <= 18):
print("Important birthday")
# if age is 21 or 50 important
elif (age == 21) or (age == 50):
print("Important birthday")
# we check if age is less than 65 and then convert true to false
elif not (age < 65):
print("Important birthday")
# else not important
else:
print("Not important birthday")
|
''' Project Euler 0046
====================
'''
import eulerlib as lib
import math
N = 33
def f(k: int):
return 2 * k * k
def is_prime(n: int):
try:
return is_prime.cache[n]
except KeyError:
p = lib.is_prime(n)
is_prime.cache[n] = p
return p
is_prime.cache = {}
def find(n):
while True:
n+= 2
if lib.is_prime(n):
continue
else:
k = 1
m = 2
while m < n:
if is_prime(n - m):
break
else:
k+= 1
m = f(k)
else:
return n
@lib.answer
def main(n: int):
return find(n)
if __name__ == '__main__':
main(N)
|
'''
Created on Dec 7, 2020
@author: RICKY
'''
import math
def Inputkalimat (kalimat):
temp = float(input(kalimat))
return temp
# Dapatkan nilai T
def HitungNilaiT(s1,s2,s3):
NilaiT = 0.5*(s1+s2+s3)
return NilaiT
# Hitung Luas Segitiga :
def HitungLuasSegitiga(t,s1,s2,s3):
LuasSegitiga = math.sqrt(t*((t-s1)*(t-s2)*(t-s3)))
return LuasSegitiga
# Cetak Luas Segitiga :
def CetakLuasSegitiga(luas):
print ("Luas Segitiga =",end=" ")
print(luas)
kalimat = "Masukkan Nilai s1 = "
s1 = Inputkalimat(kalimat)
kalimat = "Masukkan Nilai s2 = "
s2 = Inputkalimat(kalimat)
kalimat = "Masukkan Nilai s3 = "
s3 = Inputkalimat(kalimat)
t = HitungNilaiT(s1,s2,s3)
luas = HitungLuasSegitiga(t, s1, s2, s3)
CetakLuasSegitiga(luas) |
'''
Created on Nov 2, 2020
@author: RICKY
'''
bil1 = 70
bil2 = 80
bil3 = 90
if bil1 <90 :
print("nilai bil1 < 90")
if bil2 < bil3:
print("nilai bil2 < nilai bil3")
elif bil1 > 90 :
print("nilai bil1 > 90")
if bil1 < bil3 :
print("nilai bil1 < nilai bil3")
#Operator Logika "and" dan "or"
if bil1 > 50 and bil1 > 10 :
print("bil1 nilainya lebih besar dari 10 dan 50")
#Not berfungsi untuk membalik hasil
if not(bil1 > 50 or bil1 < 10) :
print("bil1 nilainya lebih besar dari 50 tapi lebih kecil dari 10") |
'''
Created on Nov 19, 2020
@author: RICKY
'''
# Bilangan Fibonanci
# 1,1,2,3,5,8,13,dst
n = int(input('Masukkan bilangan ke-n Fibonnaci : '))
x = 1
y = 1
z = 0
fib = []
for i in range(n+1):
x = y
y = z
z = x + y
fib.append(z)
for j in range(i):
print(fib[j], end=" ")
print(" ") |
'''
Created on Nov 23, 2020
@author: RICKY
'''
n = int(input("Masukkan Angka :"))
if (n-1)%2 == 0 and n >= 5:
for i in range (n):
if i == 0 or i == n -1 :
print("* "*n)
else:
print("* "+" "*(n-2)+"*")
else:
print("Angka masukkan angka yang sisa baginya 0") |
'''
Created on Nov 19, 2020
@author: RICKY
'''
#Program N! atau N faktorial
while True:
n = int(input("Masukkan bilangan anda :"))
if n < 0:
print("bilangan tidak boleh negatif")
faktorial = 1
i = n
while i >= 1 :
print (i,end=" x ")
faktorial *= i
i -= 1
print("")
print("Hasil faktorial adalah",faktorial)
|
# Simple analysis of the Collatz Conjecture
import random
import matplotlib.pyplot as plt
def collatz_function(n):
if(n % 2 == 0):
n = n/2
else:
n = (3 * n + 1)
return n
def collatz_several():
n = random.randrange(1, 1000, 1)
org = n
print(n)
counter = 0
plt.figure(1)
while(n != 1):
n = collatz_function(n)
print(n)
plt.plot(counter, n, 'bo');
counter += 1
print("Counter: " + str(counter))
plt.figure(2)
plt.plot(counter, org, 'bo');
for i in range(100):
collatz_several()
plt.figure(1)
plt.title('Value of numbers for 100 random values between 0 and 1000')
plt.ylabel('Integer value')
plt.xlabel('Iteration Number')
plt.figure(2)
plt.title('Correspondence of original value to total iteration')
plt.ylabel('Original Value')
plt.xlabel('Total Iterations: ')
plt.show()
|
#!/usr/bin/python -tt
# Expense Calculator
class Expense_Calculator(object):
def Expenses(self, Age, Retirement_Age, Inflation, Current_Expenses):
self.Future_Expenses={}
for x in range(Age,Retirement_Age+1):
if x==Age:
self.Future_Expenses[Age]=Current_Expenses
else:
self.Future_Expenses[x]=self.Future_Expenses[x-1]*(1+Inflation/100)
return self.Future_Expenses
# Modify Expenses
def Modify_Expense(self, Future_Expenses, Age, Value):
self.Future_Expenses[Age]=Value
return self.Future_Expenses
# Calculate Balance available for given corpus
def Balance(self, Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses):
self.Current_Balance={}
for x in range(Age,Retirement_Age+1):
if x==Age:
self.Current_Balance[Age]=Corpus
else:
self.Monthly_Expenses=Expenses[x-1]/12
self.Monthly_rate=Deposit_Rate/1200
self.Current_Balance[x]=(((1 + self.Monthly_rate)**12 * (self.Monthly_rate*self.Current_Balance[x-1] - self.Monthly_Expenses) + self.Monthly_Expenses)/self.Monthly_rate)
return self.Current_Balance
# Calculate Final Balance available at the end
def Final_Balance(self, Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses):
self.End_Balance=self.Balance(Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)
return self.End_Balance[Retirement_Age]
# Calculate minimum Balance to keep handy
def Minimum_Balance(self, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses):
self.Initial_Corpus=Expenses[Retirement_Age]
epsilon=0.001
self.End_Balance=self.Final_Balance(self.Initial_Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)
if self.End_Balance>0:
Min=self.Initial_Corpus/2
while self.Final_Balance(Max, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)>0:
Min=Min/2
Max=self.Initial_Corpus
elif self.End_Balance<0:
Min=self.Initial_Corpus
Max=self.Initial_Corpus*2
while self.Final_Balance(Max, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)<0:
Max=Max*2
self.Minimum_Corpus=(Min+Max)/2
while abs(self.Final_Balance(self.Minimum_Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses))>=epsilon:
if self.Final_Balance(self.Minimum_Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)>0:
Max=self.Minimum_Corpus
elif self.Final_Balance(self.Minimum_Corpus, Age, Retirement_Age, Deposit_Rate, Inflation_rate, Expenses)<0:
Min=self.Minimum_Corpus
self.Minimum_Corpus=(Min+Max)/2
return self.Minimum_Corpus
# Age=int(input("Enter your Age : "))
# Retirement_Age=int(input("Enter your Retirement Age : "))
# Inflation_rate=int(input("Enter the Inflation rate : "))
# Deposit_rate=int(input("Enter the Deposit rate : "))
# Corpus=int(input("Enter the Corpus : "))
# Annual_Expenses=int(input("Enter current Annual Expenses : "))
# Future_Expenses=Expenses(Age, Retirement_Age, Inflation_rate, Annual_Expenses)
# for key in Future_Expenses:
# print(f'Age->{key} Expenses->{Future_Expenses[key]}')
# Annual_Balance=Balance(Corpus, Age, Retirement_Age, Deposit_rate, Inflation_rate, Future_Expenses)
# for key in Annual_Balance:
# print(f'Age->{key} Balance->{Annual_Balance[key]}')
# Min_Corpus=Minimum_Balance(Age, Retirement_Age, Deposit_rate, Inflation_rate, Future_Expenses)
# print(f'Minimum Corpus required is {Min_Corpus}')
#if __name__ == '__main__':
# main()
|
#!/usr/bin/env python
"""
Renames a dataset file by appending _purged to the file name so that it can later be removed from disk.
Usage: python rename_purged_datasets.py purge.log
"""
from __future__ import print_function
import os
import sys
assert sys.version_info[:2] >= ( 2, 4 )
def usage(prog):
print("usage: %s file" % prog)
print("""
Marks a set of files as purged and renames them. The input file should contain a
list of files to be purged, one per line. The full path must be specified and
must begin with /var/opt/galaxy.
A log of files marked as purged is created in a file with the same name as that
input but with _purged appended. The resulting files can finally be removed from
disk with remove_renamed_datasets_from_disk.py, by supplying it with a list of
them.
""")
def main():
if len(sys.argv) != 2 or sys.argv == "-h" or sys.argv == "--help":
usage(sys.argv[0])
sys.exit()
infile = sys.argv[1]
outfile = infile + ".renamed.log"
out = open( outfile, 'w' )
print("# The following renamed datasets can be removed from disk", file=out)
i = 0
renamed_files = 0
for i, line in enumerate( open( infile ) ):
line = line.rstrip( '\r\n' )
if line and line.startswith( '/var/opt/galaxy' ):
try:
purged_filename = line + "_purged"
os.rename( line, purged_filename )
print(purged_filename, file=out)
renamed_files += 1
except Exception as exc:
print("# Error, exception " + str( exc ) + " caught attempting to rename " + purged_filename, file=out)
print("# Renamed " + str( renamed_files ) + " files", file=out)
if __name__ == "__main__":
main()
|
number = input('Введите целое число n: ')
print(int(number)+int(number+number)+int(number+number+number))
|
#Taking inputs
print("Enter the number of lines \nof the triangle you want to print:", end="")
n = int(input())
while True:
print("Press 1 for upwards pointing triangle \n"
"or"
"\nPress 0 for downwords pointing triangle", end=":")
b = int(input())
if b==1 or b==0:
break
else :
print("\nKindly try again\n")
#Checking conditions and print stars
if bool(b)==True:
j=0
while j<n:
j=j+1
i = 0
print("")
#Printing stars
while i < j:
print("*", end=" ")
i = i + 1
elif bool(b)==False:
while n>0:
n=n-1
print("")
#Printing stars
i = 0
while i < n+1:
print("*", end=" ")
i = i + 1 |
#This is a Demo File which shows you how to use Math101.py
#Some new functions are available although I will be adding new functions soon
from Math101 import isPrime,factorial,isPallindrome,GCD,LCM
#Taking Input
n = int(input('Enter the No'))
# Using isPrime() Function
if isPrime(n) == True:
print('Prime No')
else:
print('Not a Prime no')
#Using factorial function()
print(factorial(n))
#Using isPallindrome() Function
print(isPallindrome(n))
#Using GCD
print(GCD(15,35))
#Using LCM
print(LCM(10,20))
#In the same manner you can use functions such as swap, average etc..
#Don't Forget to import Math101 and Math101 and your file should be in same folder
#....
|
#-*- coding:UTF-8 -*-
import sys
import thread
import socket
import time
def socket_server_run():
msocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9001
print 'host = ' ,host ,' <> port ',port
msocket.bind((host,port))
msocket.listen(10)
while True:
conn, address = msocket.accept()
print 'client address is ',address
msg = conn.recv(512)
bak_msg = '''hello %s,i'm server socket.'''%(msg)
conn.sendall(bak_msg)
conn.close()
def socket_client_run(name):
msocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9001
msocket.connect((host ,port))
msocket.sendall(name)
msg = msocket.recv(512)
msocket.close()
print name ,''' receive msg is "''' + msg + '''"'''
def socket_client2_run(msg):
host = ''
port = 9001
res = socket.getaddrinfo(host, port)
af ,socktype ,proto ,canonname ,sd = res[1]
msocket = socket.socket(af ,socktype ,proto)
msocket.connect(sd)
msocket.sendall(msg)
msocket.close()
# thread.start_new_thread(socket_server_run,())
# time.sleep(2)
# thread.start_new_thread(socket_client_run ,('lilong',))
# thread.start_new_thread(socket_client_run ,('zhang3',))
# thread.start_new_thread(socket_client_run ,('wang5',))
#======================================================
if __name__ == '__main__':
msg = None
if len(sys.argv) > 1:
msg = sys.argv[1]
else:
msg = 'default client connected to server socket.'
socket_client2_run(msg)
time.sleep(10)
print 'Main thread will exit !!!'
|
x = "There are %d types of people." % 10 # variable x
binary = "binary" #variable binary
do_not = "don't" #variable do_not
y = "Those who know %s and those who %s." % (binary, do_not) #variable y, String inside string #1
print x
print y
print "I said: %r" % x #print string using %r String inside string #2
print "I also said: '%s'." % y #print string using %s String inside string #3
hilarious = True #variable hilarious
joke_evaluation = "Isn't that joke so funny?! %r" #varioble joke_evaluation with %r
print joke_evaluation % hilarious #String inside string #4
w = "This is the left side of..."
e = "a string with a right side."
print w + e # string cat
|
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
#return a list of the sections in ten_things, using ' ' as the delimiter
#call split with ten_things and ' '
stuff = ten_things.split(' ') # split(ten_things, ' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
#remove and return last item in more_stuff
#call pop with more_stuff
next_one = more_stuff.pop() # pop(more_stuff)
print "Adding: ", next_one
#append next_one to the end of stuff
#call append with stuff and next_one
stuff.append(next_one) # append(stuff, next_one)
print "There's %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] #whoa! fancy
#remove and return last item in stuff
#call pop with stuff
print stuff.pop() #pop(stuff)
# join stuff with ' ' between them.
# Call join with ' ' and stuff.
print ' '.join(stuff) #what? cool! join(' ', stuff)
print '#'.join(stuff[3:5]) #super stellar! join('#', stuff[3:5]) |
import math
first_number = int(input())
second_number = int(input())
if second_number > 1:
result = math.log(first_number, second_number)
else:
result = math.log(first_number)
print(round(result, 2))
|
#Exercise 8 LPTHW: Printing, Printing
# Initialize a string variable that has variable placeholders. Use .format as an easy way to create strings
formatter = "{} {} {} {}" # Initialize a string variable that has variable placeholders.
print(formatter.format(1,2,3,4)) #The .format function allows arguments (the numbers) to be passed into the varable placeholders of a string witch is called by the variable formatter
print(formatter.format("one","two","three","four")) #Passing strings rather than numbers into the string with variable placeholders
print(formatter.format(True, False, False, True)) #Pass the type true or false
print(formatter.format(formatter,formatter,formatter,formatter)) # It's going to return nothing (wrong! returns the curly brackets if nothing gets passed) because there were no variables passed into the formatter(2nd degree)
# This will print a sentence by inserting 4 separate strings into the placeholders of the formatter string
print(formatter.format(
"Try your",
"Own text here.",
"Maybe a poem,",
"Or a song about fear."
))
|
# Exercise 7 LPTHW: More Printing
print("Mary had a little lamb.")
print("It's fleece was white as {}".format('snow')) #format function inserts argument in variable placeholder
print("And everywhere that Mary went.")
print("." * 10) # what did that do? Added 10 periods to the end....
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try and remove it to see what happens
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') #end is an argument in print that says what to do at the end of the print, default is probably new line
print(end7 + end8 + end9 + end10 + end11 + end12)
|
#Exercise 12 LPTHW: Prompting People
#Instead of printing the prompt before the input line, use he prompt argument in input([prompt])
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh in lbs? ")
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
|
import random
def weighted_choice(weights):
"""
The following is a simple function to implement weighted random selection in Python.
Given a list of weights, it returns an index randomly, according to these weights
:param weights: list of weights
:return: the index with the probability
"""
totals = []
running_total = 0
for w in weights:
running_total += w
totals.append(running_total)
rnd = random.random() * running_total
for i, total in enumerate(totals):
if rnd < total:
return i
def xstr(s):
if s is None:
return 'none'
return s
def state_str1(state):
aux = xstr(state[0]) + '_' + xstr(state[1]['light']) + '_' + xstr(state[1]['oncoming']) + '_' + xstr(state[1]['left'])
aux = aux.replace("__", "_")
if aux[-1:] == "_":
aux = aux[:(len(aux) - 1)]
return aux
def state_str2(state):
aux = xstr(state[0]) + '_' + xstr(state[1]) + '_' + xstr(state[2]) + '_' + xstr(state[3])
aux = aux.replace("__", "_")
if aux[-1:] == "_":
aux = aux[:(len(aux) - 1)]
return aux
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
寻找“完美数”
"""
import math
def main():
for num in range(1,10000):
sum = 0
for factor in range(1, int(math.sqrt(num))+1):
if num % factor == 0:
sum += factor
if (factor > 1) and (num / factor != factor):
sum += num / factor
if num != 1 and sum == num:
print(num)
if __name__ == "__main__":
main() |
from darts.dart import Dart
# Here is all the logic required to set the optimal goals for a given score left and given number of darts in hand.
# For scores in range(60, 159), the target scores are hardcoded
# to reduce redundant calculations and ensure optimal targets.
def hardcoded_dart(score):
assert score in range(60, 159)
if score in [72, 76, 84, 88, 92, 96] + list(range(98, 125)) + list(range(127, 159)):
return Dart(20, 3)
elif score in (69, 73, 89, 93, 95, 97, 126):
return Dart(19, 3)
elif score in (70, 86, 90, 94):
return Dart(18, 3)
elif score in (67, 75, 83, 87, 91):
return Dart(17, 3)
elif score in (64, 68, 80, ):
return Dart(16, 3)
elif score in (61, 77, 81, 85):
return Dart(15, 3)
elif score in (74, 78, 82):
return Dart(14, 3)
elif score in (63, 71, 79):
return Dart(13, 3)
elif score in (62, 66):
return Dart(10, 3)
elif score in (65, 125):
return Dart(25, 1)
def below_40(score):
assert score <= 40
if score % 2 == 0:
return Dart(int(score/2), 2)
targets = [20, 16, 8, 18, 12, 4, 2, 1]
for dart in targets:
single = score - dart * 2
if single > 0:
return Dart(single, 1)
return None
sequences = {
(1, 40): lambda x: below_40(x),
(40, 60): lambda x: Dart(x-40, 1),
(60, 158): lambda x: hardcoded_dart(x),
(158, 501): lambda x: Dart(20, 3)
}
def get_target(score, in_hand):
assert score >= 2
if in_hand == 1:
if score == 50: return Dart(25, 2)
elif score in (182, 185, 188): return Dart(18, 3)
elif score in (183, 186, 189): return Dart(19, 3)
elif in_hand == 2:
if score in range(61, 71): return Dart(score-50, 3)
elif score in (101, 104, 107, 110): return Dart(int((score-50)/3), 3)
for score_range, algorithm in sequences.items():
if score_range[0] < score <= score_range[1]:
return algorithm(score)
def get_sequence(score):
sequence = []
value = 0
for in_hand in range(3, 0, -1):
dart = get_target(score - value, in_hand)
sequence.append(dart)
value += dart.score()
if value == score: break
return sequence
# This is the final function to get optimal checkout for given score
def get_checkout(score):
if score <= 158 or score in (160, 161, 164, 167, 170):
return get_sequence(score)
return None
if __name__ == '__main__':
for i in range(2, 171):
if sequence := get_checkout(i):
print(i, [str(dart) for dart in sequence])
else:
print(i)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# auth : pangguoping
user_file = open('user.txt','r') #保存用户名密码
message_dict = { }
#下面for循环是把用户名密码转换为字典
for i in user_file:
line = i.strip()
line_list = line.split()
message_dict[line_list[0]] = line_list[1]
user_file.close()
counter = 0 #定义一个计数器
last_name = "" #定义一个空变量,用于保存登录的用户名
while True:
user_name = input("please input your name:") #输入用户名
user_passwd = input("please input your password:") #输入密码
black_file = open('black_user.txt', 'r') # 用户黑名单
line = black_file.read().split("\n")
black_file.close()
if user_name in line: #判断用户是否在黑名单里
print('your name is blackuser,please call administrator !')
break
else:
if user_name in message_dict.keys() and user_passwd == message_dict[user_name]: #判断用户名密码是否正确
print("Welcom to login !")
break #登录成功并退出
elif user_name in message_dict.keys(): #判断账号是否在用户名单里
if last_name == user_name: #判断输入的账号和上次是否一样
if counter < 2: #判断输入是否小于3次
last_name = user_name #把输入的账户赋值给last_name变量,用于判断是否为连续输入相同账户
print("Invalid username or password !")
counter += 1 #计数器的值加一
print('times', counter)
continue
else: #如果同一个账号连续输错3次,加入黑名单
add_black = open('black_user.txt', 'a') #打开黑名单文件
add_black.write(user_name+'\n') #把账号添加到黑名单
add_black.close() #关闭文件
print("Sorry ,your name is clock !",user_name)
break
else: #如果输入的不是上次的账户,
last_name = user_name #重新赋值
counter = 0 #计数器重新开始
print("Invalid username or password !")
counter += 1 #计数器的值加1
print('times', counter)
else:
last_name = user_name #重新赋值,保证和连续输入的账户相同
counter = 0 #计数器归零
print("Invalid username or password !")
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
import sys
import os
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(base_dir)
sys.path.append(base_dir)
from modules.menu import menu_show
while True:
user = input("\033[1;32;40mPlease input your name:\033[0m")
with open('../db/user_list', 'r', encoding='utf-8') as f:
for line in f:
n = line.split()[0]
p = line.split()[1]
if user == n:
while True:
password = input('\033[1;32;40mPlease input your password:\033[0m')
if password != p:
print("\033[1;31;40mThe password is incorrect\033[0m")
continue
else:
print("\033[1;32;40myes let you in.\033[0m")
global MONEY
money_total = 15000
while True:
print('You total Money is :' ,money_total)
money_total = menu_show(user,money_total)
else:
print("\033[1;31;40mThe user is not vaild, please re-input:\033[0m")
continue
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#list __init__,内部
'''
# 1、set,无序,不重复序列
#创建
#方法一:
s1 = {"123","456"}
print(type(s1))
#方法二:
s2 = set() #创建空集合
#方法三:
#列表转换为集合
li = [11,22,11,22]
s3 = set(li)
print(s3)
#二、操作集合
#1.集合添加元素
s = set()
s.add(123)
print(s)
#A中存在,B中不存在
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.difference(s2)
print(s3)
#对称chaji
s4 = s1.symmetric_difference(s2)
print(s3)
#
s1.difference_update(s2)
print(s1)
s1.symmetric_difference_update(s2)
'''
'''
#移除
s1 = {11,22,33}
s1.discard(1111) #移除的不存在不会报错,最常用
#s1.remove(1111) #移除的值不存在会报错
ret = s1.pop() #随机移除一个元素,并打印被移除的元素
print(ret)
'''
'''
#交集
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.intersection(s2)
s1.intersection_update(s2)
print(s3)
'''
'''
#并集
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.union(s2)
print(s3)
'''
'''
#批量添加元素
li = [11,22,33,44]
s1.update(li) #update接受一个可以被迭代的对象,也就是可以被for循环的。update相当于调用多次add函数
print(s1)
'''
'''
li = [11,22,33] #list __init__
li() #list __call__
li[0] # list __getitem__
li[0] = 123 # list __setitem__
def li[1] #list __delitem__
'''
old_dict = {
"#1":8,
"#2":4,
"#4":2,
}
new_dict = {
"#1": 4,
"#2": 4,
"#3": 2,
}
'''
#应该删除那个几个曹位
old_set = set(old_dict)
print(old_set)
new_set = set(new_dict)
print(new_set)
#需要删除的
remove_set = old_set.difference(new_set)
print(remove_set)
old_list = list(old_dict)
print(old_list)
'''
old_set = set(old_dict.values())
print(old_set)
#需要删除的,取 old_set中存在的,而new_set 中不存在的
old_set = set(old_dict.keys()) # 把知道的key转换成集合
new_set = set(new_dict.keys())
#print(old_set)
#print(new_set)
remove_set = old_set.difference(new_set)
print(remove_set)
#需要增加的曹位 ,取new_set中存在的,而old_set 中不存在的
add_set = new_set.difference(old_set)
print(add_set)
#需要更新的曹位, 取 new_set和old_set 中的交集
update_set = new_set.intersection(old_set)
update_set2 = old_set.intersection(new_set)
print(update_set)
print(update_set2) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
'''
from xml.etree import ElementTree as ET
tree = ET.parse('xo.xml')
root = tree.getroot()
print(root)
for child in root:
print(child)
print(child.tag,child.attrib)
for gradechild in child:
#print(gradechild)
print(gradechild.tag,gradechild.text,gradechild.attrib)
'''
'''
from xml.etree import ElementTree as ET
str_xml = open('xo.xml','r').read()
root = ET.XML(str_xml)
print(root)
'''
'''
from xml.etree import ElementTree as ET
str_xml = open('xo.xml','r').read()
root = ET.XML(str_xml)
print(root.tag)
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('name','alex')
node.set('age','18')
'''
from xml.etree import ElementTree as ET
root = ET.Element("famliy")
son1 = ET.Element('son',{'name':'er1'})
son2 = ET.Element('son',{'name':'er2'})
grandson1 = ET.Element('grandson',{'name':'er11'})
grandson2 = ET.Element('grandson',{'name':'er22'})
son1.append(grandson1)
son2.append(grandson2)
root.append(son1)
root.append(son2)
tree = ET.ElementTree(root)
tree.write('ooo.xml',encoding='utf-8',short_empty_elements=False) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
message_dict = { }
user_file = open('user.txt','r')
f=open('black_user.txt','r')
user_name = input("please input your name:")
user_passwd = input("please input your password:")
while True:
line = f.readline()
if user_name in line:
print('your name is blackuser,please call administrator')
print(user_name)
break
else:
f.close()
for i in user_file:
line = i.strip()
line_list = line.split()
message_dict[line_list[0]] = line_list[1]
user_file.close()
print(message_dict)
while True:
user_name = input("please input your name:")
user_passwd = input("please input your password:")
if user_name in message_dict.keys() and user_passwd == message_dict[user_name]:
print("Welcom to login !")
break
else:
print("Invalid username or password")
print(user_passwd)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
import sys,os
# base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(base_dir)
# sys.path.append(base_dir)
#
# print(sys.path)
from modules.shopping import show_shopping_list
#from moprintlist import print_list
from modules.printlist import print_list
from modules.withdraw import with_draw
from modules.cashin import cash_in
def menu_show(n,mo):
print('Welcom %s, This is The ATM system:' %n)
print('Select what you want to do:')
print('1.Shopping:\n 2.提现:\n 3.还款\n 4.打印记录:\n 5.退出')
user_input = int(input("请输入您的选择 0 ~ 5:"))
global CURRENT_USER
CURRENT_USER = n
mo = menu_select(user_input,mo)
return mo
def menu_select(choose,money):
if choose == 1:
money = show_shopping_list(CURRENT_USER,money)
if choose == 2:
money = with_draw(CURRENT_USER,money)
if choose == 3:
money = cash_in(CURRENT_USER,money)
if choose == 4:
print_list(CURRENT_USER)
if choose == 5:
print('\033[1;33;40mThank you for using ATM, Good bye!\033[0m')
sys.exit()
return money
#menu_show('user1',15000) |
#gives us randoms
import random
potential_words = ["example", "words", "someone", "can", "guess"]
word = random.choice(potential_words)
#to test: print(word)
#converts the word to lowercase
word = word.lower()
#make it a list of letters for someone to guess
current_word = list(word) #the number of letters should match the word
#print(current_word)
#some useful variables
guesses = [] #holds all previously guessed letters
maxfails = 7
fails = 0
while fails < maxfails:
guess = input("Guess a letter: ").lower()
#if the guess is a single letter if not guessed already
if guess.isalpha() and len(guess) == 1 and guess not in guesses:
guesses.append(guess)
print(guesses)
if guess in current_word:
#guess is right
print("You guessed a letter correctly!")
else:
#guess is wrong
print("You guessed incorrectly.")
fails += 1
else:
#not valid input
print("Invalid guess. Try again!")
#check if the guess is valid. is it one letter? have they already guessed it?
#check if the guess is correct: is it in the word? if so, reveal the letters
#print(current_word)
print("You have " + str(maxfails - fails) + " tries left!")
#display the status of the word
display = ""
winning = ""
for i in current_word:
if i in guesses:
display += i + " "
winning += i
#print(i)
else:
display += "_ "
#print("_ ")
print(display)
if winning == word:
print("You won!")
exit(0)
print(f"You have lost; the word was {word}.")
|
# Given an array of integers, find the first missing positive integer in linear time
# and constant space. In other words, find the lowest positive integer that does not exist in the array.
# The array can contain duplicates and negative numbers as well.
# For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
# You can modify the input array in-place.
def solve(numbers):
numbers.sort()
index=1
for i in range(0,len(numbers)):
if numbers[i]>0:
if numbers[i]==index:
if i+1 < len(numbers):
if numbers[i+1]!=index:
index+=1
else:
index+=1
else:
return index
return index
def test_solve():
assert solve([3, 4, -1, 1]) == 2
assert solve([1, 2, 0]) == 3
assert solve([2, 3, 7, 6, 8, -1, -10, 15]) == 1
assert solve([2, 3, -7, 6, 8, 1, -10, 15]) == 4
assert solve([1, 1, 0, -1, -2]) == 2
assert solve([-1,-2,0,3]) == 1
assert solve([-1,-2,0,1]) == 2
assert solve([-1,-2,0,1,1,2,2]) == 3
assert solve([-1,-2,0,1,1,3,3]) == 2
|
listOfList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for rowIndex in range(0,3):
for colIndex in range(0,3):
print( listOfList[rowIndex][colIndex], end=' ')
print()
|
import turtle
def draw_square(shape):
for i in range(4):
shape.forward(200)
shape.right(90)
def draw_fractal():
screen = turtle.Screen()
screen.bgcolor("red")
fractal = turtle.Turtle()
fractal.shape("arrow")
fractal.speed(10)
fractal.color("white")
for i in range(36):
draw_square(fractal)
fractal.right(10)
screen.exitonclick()
draw_fractal()
|
a=[1,12,15,26,38]
b=[2,13,17,30,45]
def median(a):
if len(a)%2==0:
return (a[len(a)//2-1]+a[len(a)//2])/2
else :
return (a[len(a)//2])
def findmedian(a,b):
if len(a)==2:
m=(max(a[0],b[0])+min(a[1],b[1]))/2
return m
m1 = median(a)
m2 = median(b)
if m1==m2:
return m1
if m1>m2:
return findmedian(a[:len(a)//2+1],b[len(b)//2:])
if m1<m2:
return findmedian(a[len(a)//2:],b[:len(b)//2+1])
print(findmedian(a,b))
|
import random
print("welcome to stone-paper-scissor game with computer!!","*****************************",sep="\n")
print("you can press 0 whenever you want to quit")
print("let's start the game")
while True:
print("press 1,2,3 for indicating stone,paper,scissor respectively!!")
turn=int(input("it's your turn ,enter your choice:"))
comp=random.randint(1,3)
if(turn>3):
print("enter a valid choice")
elif (turn==comp):
print("match draw!")
elif (turn==1 and comp==3) or (turn==3 and comp==2) or (turn==2 and comp==1):
print("congratulations!! you won the match...")
elif(turn==0):
exit(0)
else:
print("you lost!! better luck next time")
|
t = int(input())
word_list = []
for _ in range(t):
s = input()
word_list.append(s)
for _ in range(t):
if len(word_list[_]) == 1:
print(f"Case #{_ + 1}: 0")
else:
letter = 26 * [0]
vowel, consonant, max_vowel, max_consonant = 0, 0, 0, 0
for i in word_list[_]:
letter[ord(i) - 65] += 1 # เพิ่มจำนวนของตัวอักษร
if i == 'A' or i == 'E' or i == 'O' or i == 'U' or i == 'I':
vowel += 1
if letter[ord(i) - 65] > max_vowel:
max_vowel = letter[ord(i) - 65]
else:
consonant += 1
if letter[ord(i) - 65] > max_consonant:
max_consonant = letter[ord(i) - 65]
if vowel <= consonant:
print(f"Case #{_ + 1}: {consonant + 2 * (vowel - max_vowel)}")
else:
print(f"Case #{_ + 1}: {vowel + 2 * (consonant - max_consonant)}")
|
def area(base, height):
'''(number, number) -> float
Return the area of triangle with given base and height.
>>>area(10, 40)
200.0
>>>area(3.4, 7.5)
12.75
'''
return base * height / 2
|
x = 15
y = 3
z = "this is a string"
a = "hello"
b = "world"
c = "again"
myList = [1,12,3,45,5]
def myPrint(words):
print(words, ", ok.")
myPrint("are you")
def myFunction(start, vList, step):
for i in range(start,len(vList),step):
print(vList[i])
def myRecursiveFunction(start, vList, step):
if len(vList) > start + step:
print(vList.pop())
myRecursiveFunction(start, vList, step)
myRecursiveFunction(1,["hello",1,True,3.14159],2)
|
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.style.use('bmh')
import matplotlib
matplotlib.rc('lines',linewidth=3)
matplotlib.rc('font',size=16)
# revenue we make from each ticket sold ($)
revenue_per_ticket = 250
# cost of a voucher ($)
cost_per_voucher = 800
# probability any given passenger who bought a ticket will show up for his/her flight
p = 0.9
# total number of seats on the airplane.
nb_total_seats = 100
# Goal: find expected net revenue per flight as a function of `x`, the number of tickets sold beyond capaacity.
# i.e. we are selling `nb_total_seats` + `x` tickets.
# net revenue = (revenue from tickets) - (cost of voucher payoffs to overbook customers)
# We will find net revenue for `x` = 0, 1, 2, ..., N_x
# (Note we only consider `x` >= 0 b/c we at least sell a ticket for each seat!)
N_x = 55
# pre-allocate here. net_revenue[i] := net revenue for x = i.
expected_net_revenue = np.zeros((N_x, ))
## expected net revenue as a function of x
for x in range(N_x):
# mean and variance in binomial distribution for this $x$.
# e.g. mean is referring to the # of customers we expect to show up given we sold (nb_total_seats+x) tickets
mean = (nb_total_seats + x) * p
sig2 = (nb_total_seats + x) * p * (1 - p)
# pre-allocate expected voucher payoffs and ticket revenue we expect for this `x`
expected_voucher_payoffs = 0.0
expected_ticket_revenue = 0.0
# consider the probability that $k$ customers show up to the flight
# anywhere from 0, 1, 2, ..., nb_total_seats+x customers could show up
# ... since we sold nb_total_seats+x tickets!
for k in range(nb_total_seats + x + 1):
# to calculate Pr(N=k| x), governed by binomial dist'n, use normal approximation to binomial
# let Z ~ Normal(0, 1)
# Pr(N=k|x) ~ Prob(l < Z < h)
# subtract cumulative distribution (cdf) functions for this
h = (k + 0.5 - mean) / math.sqrt(sig2) # -0.5 is for continuity correction
l = (k - 0.5 - mean) / math.sqrt(sig2)
prob_k_show_up = norm.cdf(h) - norm.cdf(l)
# calculate ticket revenue given `k` customers show up
ticket_revenue = revenue_per_ticket * np.min([nb_total_seats, k])
expected_ticket_revenue += prob_k_show_up * ticket_revenue
# calculate voucher payoffs
voucher_payoffs = cost_per_voucher * np.max([0, k - nb_total_seats])
expected_voucher_payoffs += prob_k_show_up * voucher_payoffs
expected_net_revenue[x] = expected_ticket_revenue - expected_voucher_payoffs
# plot expected net revenue as a function of `x`
fig = plt.figure()
plt.plot(range(N_x), expected_net_revenue, linewidth=3)
plt.xlim([0, x])
plt.axhline(y=0, linestyle='--', color='k')
plt.axhline(y=nb_total_seats * revenue_per_ticket, linestyle='--', color='r')
plt.xlabel('# tickets beyond capacity ($x$)')
plt.ylabel('Expected revenue (\$)')
plt.tight_layout()
plt.savefig('overbook.png',format='png')
plt.show()
|
import sys
answer = []
hint = []
guess = []
wrongAns = []
score = 0
heart = 11
def chooseCategory(number):
category = ""
if number == "1":
category = "astronomy"
elif number == "2":
category = "fastfood"
elif number == "3":
category = "africa"
readFile(category)
def readFile(category):
with open(category +'.txt') as File:
for line in File:
answer.append(line.split(':')[0])
hint.append(line.split(':')[1].rstrip())
question()
def question():
global heart
for word in range(len(answer)):
heart = 11
print("hint: "+ hint[word])
guess.append([])
for i in range(len(answer[word])):
if isAlphabet(answer[word][i]):
guess[word].append('_')
else:
guess[word].append(answer[word][i])
print(*guess[word])
for time in range(11):
guessWord = input(">> ")
heart -= 1
checkAns(guessWord.lower(),word)
if isDone(word):
break
print("THE ANSWER IS: " + answer[word] + "\n")
wrongAns.clear()
def isAlphabet(x):
if x >= 'a' and x <= 'z':
return True
def checkAns(guessWord,word):
global score
isValid = False
for i in range(len(answer[word])):
if guessWord == answer[word][i]:
guess[word][i] = guessWord
score += 1
isValid = True
if isValid == False:
wrongAns.append(guessWord)
print(*guess[word],end="")
print(" score: " + str(score) + ", remaining life: " + str(heart) + " ,wrong guessed: ", end="")
print(*wrongAns)
def isDone(word):
for i in range(len(answer[word])):
if guess[word][i] == '_':
return False
print("YOU ARE AMAZING!")
return True
def main():
print("Welcome to Hangman!\n1. Astronomy\n2. Fastfood restaurant\n3. African wildlife\nchoose number of category you want to play")
number = input("\n>>> ")
chooseCategory(number)
print("total score: " + str(score))
main() |
# Massive + methods + SLICE
massive.append(var) #| в кінець
massive.insert(index, var) #| на місці індекса вставити елемент
massive.remove(var) #| видалити елемент з масиву
massive.clear() #| очистити
massive.pop() #| повертає останній елемент і видаляє його з масиву
massive.index(var) #| повертає індекс елементу
massive.count(var) #| повертає к-сть var в масиві
massive.sort() #| сортує масив
massive.reverse() #| реверс масиву
massive2 = massive1.copy() #| копіювання масиву
massive2 = list(massive1) #| копіювання масиву
massive1.extend(massive2) #| конкатенація списків
del thislist[0] #| видаляє вказаний елемент по індексу
del thislist #| видаляє список
# Додавання масивів
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
l + ll # Конкатенація
l * n | n * l # n копій
v1,v2, ... , vn = l # Розпаковка
x in s | x not in s # Перевірка на вхід
all(s) # True якщо всі не False
any(s) # True якщо хоча б один True
print(c_string[0]) // "s"
print(c_string[-1]) // "g"
print(c_string[0:3]) // "str"
print(c_string[:3]) // "str"
print(c_string[1:]) // "tring"
print(c_string[2:-1]) // "ring"
a = m[0:100:10]
b = m[1:10, 3:20]
c = m[0:100:10, 50:75:5]
m[0:5, 5:10] = n
del m[:10, 15:]
a = m[..., 10:20]
m[10:20, ...] = n
a = [1,2,3,4,5]
>>> a[::2] # Указываем шаг
[1,3,5]
>>> a[::-1] # Переворачиваем список
[5,4,3,2,1]
a = list(range(5))
print(" ".join(str(i) for i in a)) # -> 0 1 2 3 4
###############################################
>>> a = [3,4,5]
>>> b = [a]
>>> c = 4*b
>>> c
[[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]]
>>> a[0] = -7
>>> c
[[-7, 4, 5], [-7, 4, 5], [-7, 4, 5], [-7, 4, 5]]
>>>
# Удаление дубликатов!
items = [2, 2, 3, 3, 1]
print(list(set(items)))
# [1, 2, 3]
# COPY
li = [1,2,3]
new_li = [:]
print (li is new_li)
>>> False
>>> a = [ 1, 2, [3,4] ]
>>> b = list(a) # поверхнева копія
>>> b is a
False
>>> b.append(100)
>>> b
[1, 2, [3, 4], 100]
>>> a
[1, 2, [3, 4]]
>>> b[2] [0] = -100 # зміна внутрішнього списку
>>> b
[1, 2, [-100, 4], 100]
>>> a
[1, 2, [-100, 4]]
>>>
############################################
# Нумеровані списки
for i, item in enumerate(['a', 'b', 'c']):
print(i, item)
# 0 a
# 1 b
# 2 c
for i, item in enumerate(['a', 'b', 'c'], 1): # 1 - start iteration
print(i, item)
# 1 a
# 2 b
# 3 c
|
# CLASSES
# Method
method.__doc__ # Doc
method.__name__ # Ім'я методу
method.__class__ # Class в якому визначений метод
method.__func__ # Object of func що реалізує даний метод
method.__self__ # Силка на екземпляр, асоціований з даним методом
# None - для незв'язаних методів
# Class
c.__doc__ # Документація
c.__name__ # Ім'я класу
c.__bases__ # Кортеж з базовими класами
c.__dict__ # Словник, що містить методи та атрибути класу
c.__module__ # Ім'я модулю, в ямоу визначений клас
c.__abstractmetods__ # Множина імен абстрактних методів (None - якщо немає)
# Example
r.__class__ # Name class
r.__dict__ # Словник, що містить дані про клас
class Point:
def __init__ (self, x, y)
body of constr
self.x = x
self.y = y
def function (self):
body of function
Initialization
point = Point()
point.function()
class Animal:
class Dog(Animal):
class Cat(Animal):
__lt__(self,other) self < other
__le__(self,other) self <= other
__gt__(self,other) self > other
__ge__(self,other) self >= other
__eq__(self,other) self == other
__ne__(self,other) self != other
__len__(self) # len(a) # a.__len__()
__getitem__(self, key) # x = a[2] # x = a.__getitem__(2)
__setitem__(self, key, value) # a[1] = 7 # a.__setitem__(1,7)
__delitem__(self, key) # del a[2] # a.__delitem__(2)
__contains__(self, obj) # 5 in a # a.__contains__(5)
# a = [1,2,3,4,5,6]
# x = a[1:5] # x = a.__getitem__(slice(1,5,None))
# a[1:3] = [10,11,12] # a.__setitem__(slice(1,3,None), [10,11,12])
# del a[1:4] # a.__delitem__(slice(1,4,None))
__add__(self,other) self + other
__sub__(self,other) self - other
__mul__(self,other) self * other
__div__(self,other) self / other (Только в Python 2)
__truediv__(self,other) self / other (Python 3)
__floordiv__(self,other) self // other
__mod__(self,other) self % other
__divmod__(self,other) divmod(self,other)
__pow__(self,other [,modulo]) self ** other, pow(self, other, modulo)
__lshift__(self,other) self << other
__rshift__(self,other) self >> other
__and__(self,other) self & other
__or__(self,other) self | other
__xor__(self,other) self ^ other
__radd__(self,other) other + self
__rsub__(self,other) other - self
__rmul__(self,other) other * self
__rdiv__(self,other) other / self (Только в Python 2)
__rtruediv__(self,other) other / self (Python 3)
__rfloordiv__(self,other) other // self
__rmod__(self,other) other % self
__rdivmod__(self,other) divmod(other,self)
__rpow__(self,other) other ** self
__rlshift__(self,other) other << self
__rrshift__(self,other) other >> self
__rand__(self,other) other & self
__ror__(self,other) other | self
__rxor__(self,other) other ^ self
__iadd__(self,other) self += other
__isub__(self,other) self -= other
__imul__(self,other) self *= other
__idiv__(self,other) self /= other (Только в Python 2)
__itruediv__(self,other) self /= other (Python 3)
__ifloordiv__(self,other) self //= other
__imod__(self,other) self %= other
__ipow__(self,other) self **= other
__iand__(self,other) self &= other
__ior__(self,other) self |= other
__ixor__(self,other) self ^= other
__ilshift__(self,other) self <<= other
__irshift__(self,other) self >>= other
__neg__(self) –self
__pos__(self) +self
__abs__(self) abs(self)
__invert__(self) ~self
__int__(self) int(self)
__long__(self) long(self) (Только в Python 2)
__float__(self) float(self)
__complex__(self) complex(self)
#####################
class foo:
def normal_call(self):
print("normal_call")
def call(self):
print("first_call")
self.call = self.normal_call
>>> y = foo()
>>> y.call()
first_call
>>> y.call()
normal_call
>>> y.call()
normal_call
######################
class Circle(object):
def __init__(self,radius):
self.radius = radius
@property
def area(self):
return math.pi*self.radius**2
@property
def perimeter(self):
return 2*math.pi*self.radius
>>> c = Circle(4.0)
>>> c.radius
4.0
>>> c.area
50.26548245743669
>>> c.perimeter
25.132741228718345
>>> c.area = 2
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: can’t set attribute
class Foo(object):
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self,value):
if not isinstance(value,str):
raise TypeError("Ім'я повинне бути стрічкою")
self.__name = value
@name.deleter
def name(self):
raise TypeError("Неможливо видалити атрибут Ім'я")
>>> f = Foo("Гвидо")
>>> n = f.name # викличе f.name() – поверне функцію
>>> f.name = "Монти" # викличе метод зміни name(f,”Монти”)
>>> f.name = 45 # викличе метод зміни name(f,45) -> TypeError
>>> del f.name # викличе метод видалення name(f) -> TypeError
class TypedProperty(object):
def __init__(self,name,type,default=None):
self.name = "_" + name
self.type = type
self.default = default if default else type()
def __get__(self,instance,cls):
return getattr(instance,self.name,self.default)
def __set__(self,instance,value):
if not isinstance(value,self.type):
raise TypeError("Значення повинно бути типом %s" % self.type)
setattr(instance,self.name,value)
def __delete__(self,instance):
raise AttributeError("Неможливо видалити атрибут")
class Foo(object):
name = TypedProperty(“name”,str)
num = TypedProperty(“num”,int,42)
f = Foo()
a = f.name # Неявно викличе метод Foo.name.__get__(f,Foo)
f.name = “髬” # Викличе Foo.name.__set__(f,”Guido”)
del f.name # Викличе Foo.name.__delete__(f)
class A(object):
def __init__(self):
self.__X = 3 # Буде змінено на self._A__X
def __spam(self): # Буде змінено на _A__spam()
pass
def bar(self):
self.__spam() # Викличе тільки метод A.__spam()
class B(A):
def __init__(self):
A.__init__(self)
self.__X = 37 # Буде змінено на self._B__X
def __spam(self): # Буде змінено на _B__spam()
pass
from abc import ABCMeta, abstractmethod, abstractproperty
class Foo(metaclass = ABCMeta):
@abstractmethod
def spam(self,a,b):
pass
@abstractproperty
def name(self):
pass
>>> f = Foo()
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: Can’t instantiate abstract class Foo with abstract methods spam |
import tkinter as tk
class Question:
def __init__(self, main):
self.entry1 = tk.Entry(main, width = 10, font = 15)
self.button1 = tk.Button(main, text = " Check ")
self.label1 = tk.Label(main, width = 20, font = 15)
self.entry1.grid(row = 0, column = 0)
self.button1.grid(row = 0, column = 1)
self.label1.grid(row = 0, column = 2)
self.button1.bind("<Button-1>",self.answer)
def answer(self, event):
txt = self.entry1.get()
try:
if int(txt) > 18:
self.label1["text"] = "Cool"
else:
self.label1["text"] = "Bad"
except ValueError:
self.label1["text"] = "No int"
root = tk.Tk()
root.title = "Class Question"
q = Question(root)
root.mainloop() |
# addition
2 + 3 # 5
# subtraction
3 - 2 # 1
# multiplication
2 * 3 # 6
# division
3 / 2 # 1.5
# python 2.7
# 3 / 2 = 1
# 3.0 / 2 = 1.5
# 3 / 2.0 = 1.5
# 3.0 / 2.0 = 1.5
# modulus (remainder after division)
4 % 2 # 0 (4 / 2 is 2 with no remainder)
7 % 3 # 1 (7 / 3 is 2 with a remainder of 1)
# floor division (quotient after remainder is removed)
9//2 # 4 (9 / 2 is 4 with a remainder of 1)
6//3 # 2 (6 / 3 is 2 with no remainder)
# exponents
3 ** 2 # 9
# floats
0.1 + 0.2 # 0.3
2 * 0.2 # 0.4
# order of operation
2 + 3 * 4 # 14
(2 + 3) * 4 # 20
(4 - 1) * 3 + 2 * 4 # 17
# greater than (equal to)
3 > 2
3 >= 3
# less than (equal to)
2 < 3
2 <= 3
# equal to
2 == 2
# not equal to
3 != 2
# assignment
total = 3 + 5 # assign 8 to total
total += 1 # total = 9
total -= 1 # total = 8
total *= 2 # total = 16
total /= 2 # total = 8
total %= 3 # total = 2
total **= 3 # total = 8
total //= 2 # total = 4
# bitwise
a = 60 # 0011 1100
b = 13 # 0000 1101
# binary AND (bit exists in both)
a & b # 0000 1100
# binary OR (bit exists in either)
a | b # 0011 1101
# binary XOR (bit exists in one but not the other)
a ^ b # 0011 0001
|
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Tests for the class Employee"""
def setUp(self):
"""Create base employee."""
self.employee = Employee("Nelson", "Ripoll", 50000)
def test_give_default_raise(self):
"""Give raise using default amount."""
self.employee.give_raise()
self.assertEqual(self.employee.salary, 55000)
def test_give_raise(self):
"""Give raise."""
self.employee.give_raise(10000)
self.assertEqual(self.employee.salary, 60000)
unittest.main()
|
# -*- coding: utf-8 -*-
"""Logistic Regression Classification for machine learning.
In statistics, logistic regression, or logit regression, or logit model is a
regression model where the dependent variable (DV) is categorical. This project
covers the case of a binary dependent variable—that is, where it can take
only two values, "0" and "1", which represent outcomes such as pass/fail,
win/lose, alive/dead or healthy/sick.
The binary Logistic regression model is an example of a qualitative
response/discrete choice model. It is used to estimate the probability of a
binary response based on one or more predictor (or independent) variables
(features).
Example:
$ python regularLogisticRegression.py
Todo:
*
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
# importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
features = dataset.iloc[:, [2, 3]].values # Country, Age, Salary
labels = dataset.iloc[:, 4].values # Purchased
# Splitting the Dataset into a Training set and a Test set
feature_train, feature_test, label_train, label_test = train_test_split(
features, labels, test_size=0.25)
# Feature scaling, normalize scale is important. Especially on algorithms
# involving euclidian distance. Two main feature scaling formulas are:
# Standardisation: x_stand = (x-mean(x))/(standard_deviation(x))
# Normalisation: x_norm = (x-min(x))/(max(x)-min(x))
sc_feature = StandardScaler()
feature_train = sc_feature.fit_transform(feature_train)
feature_test = sc_feature.transform(feature_test)
# Fitting the Logistic Regression to the dataset
classifier = LogisticRegression()
classifier.fit(feature_train, label_train)
# Predicting the results of the Test set
y_pred = classifier.predict(feature_test)
# Creating the Confusion Matrix
cm = confusion_matrix(label_test, y_pred)
# Visualize the Training set results
"""X_set, y_set = feature_train, label_train
X1, X2 = np.meshgrid(
np.arange(
start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01
),
np.arange(
start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01
)
)
plt.contourf(
X1, X2, classifier.predict(
np.array([X1.ravel(), X2.ravel()]).T
).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('red', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c=ListedColormap(('red', 'blue'))(i), label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()"""
# Visualize the Test set results
X_set, y_set = feature_test, label_test
X1, X2 = np.meshgrid(
np.arange(
start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01
),
np.arange(
start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01
)
)
plt.contourf(
X1, X2, classifier.predict(
np.array([X1.ravel(), X2.ravel()]).T
).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('red', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c=ListedColormap(('red', 'blue'))(i), label=j)
plt.title('Logistic Regression (Testing set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
|
# -*- coding: utf-8 -*-
"""Support Vector Machine (SVM) classification for machine learning.
SVM is a binary classifier. The objective of the SVM is to find the best
separating hyperplane in vector space which is also referred to as the
decision boundary. And it decides what separating hyperplane is the 'best'
because the distance from it and the associating data it is separating is the
greatest at the plane in question.
This is the file where I create use scikit-learn to use the algorithm.
dataset is breast cancer data from: http://archive.ics.uci.edu/ml/datasets.html
Example:
$ python regularSupportVectorMachine.py
Todo:
*
"""
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split
df = pd.read_csv('breast-cancer-wisconsin.data')
df.replace('?', -99999, inplace=True) # make missing attribute values outliers
df.drop(['id'], 1, inplace=True) # remove useless column
X = np.array(df.drop(['class'], 1)) # features
y = np.array(df['class']) # labels
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = svm.SVC()
clf.fit(X_train, y_train)
# Could have saved in a pickle, but not a very large data set.
accuracy = clf.score(X_test, y_test)
print(accuracy)
example1 = [4, 2, 1, 1, 1, 2, 3, 2, 1]
example2 = [4, 2, 1, 2, 2, 2, 3, 2, 1]
example_measures = np.array([example1, example2])
example_measures = example_measures.reshape(len(example_measures), -1)
prediction = clf.predict(example_measures)
print(prediction)
|
# -*- coding: utf-8 -*-
"""K-Means unsupervised classification for machine learning.
K-means clustering is a unsupervised method to cluser or group the data.
K-means allows you to choose the number (k) of categories/groups and
categorizes it automatically when it has come up with solid categories.
This algorithm is usually used for research and finding structure and is not
expected to be super precise.
Example:
$ python howItWorksKMeans.py
Todo:
* Rewrite code to function with Titanic data set.
"""
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
colors = ["g", "r", "c", "b", "k"]
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
class KMeans:
"""K-means class.
This class is for creating an instance of K Means. To avoid retraining or
refitting (as it's also called) every time it is used.
"""
def __init__(self, k=2, tol=0.001, max_iter=300):
"""The __init__ method of the K-means class.
Args:
k (int): The number of clusters/groups that we are looking for
tol (float): tolerance is basically how much the centroid is going
to move.
max_iter (int): Max iteration is basically how many times we run
this algorithm before we decide it's enough.
"""
self.k = k
self.tol = tol
self.max_iter = max_iter
def fit(self, data):
"""Method to fit/train data and find clusters."""
self.centroids = {}
for i in range(self.k):
# Centroids are two first in data, if random is wanted then
# shuffle data randomly before fitting.
self.centroids[i] = data[i]
for i in range(self.max_iter):
self.classifications = {}
for i in range(self.k):
self.classifications[i] = []
for featureset in data:
distances = [
np.linalg.norm(featureset - self.centroids[centroid])
for centroid in self.centroids]
classification = distances.index(min(distances))
self.classifications[classification].append(featureset)
prev_centroids = dict(self.centroids)
for classification in self.classifications:
self.centroids[classification] = np.average(
self.classifications[classification], axis=0)
optimized = True
for c in self.centroids:
original_centroid = prev_centroids[c]
current_centroid = self.centroids[c]
if np.sum((current_centroid - original_centroid) /
original_centroid * 100) > self.tol:
optimized = False
if optimized:
break
def predict(self, data):
"""Method to predict what cluster data belongs to."""
distances = [
np.linalg.norm(data - self.centroids[centroid])
for centroid in self.centroids]
classification = distances.index(min(distances))
return classification
clf = KMeans()
clf.fit(X)
for centroid in clf.centroids:
plt.scatter(clf.centroids[centroid][0], clf.centroids[centroid][1],
marker="x", color="k", s=150, linewidths=5)
for classification in clf.classifications:
color = colors[classification]
for featureset in clf.classifications[classification]:
plt.scatter(featureset[0], featureset[1], marker="o", color=color,
s=150, linewidths=5)
unknowns = np.array([[1, 3], [8, 9], [0, 3], [5, 4], [6, 4]])
for unknown in unknowns:
classification = clf.predict(unknown)
plt.scatter(unknown[0], unknown[1], marker="*",
color=colors[classification], s=150, linewidths=5)
plt.show()
|
import numpy as np
import matplotlib.pyplot as plt
y0 = 1972
n0 = 0.0025
year_predicted = np.arange(1972, 2013, 2)
num_predicted = np.log10(n0) + ((year_predicted - y0) / 2) * np.log10(2)
year_observed = [1972, 1974, 1978, 1982, 1985, 1989, 1993, 1997, 1999, 2000, 2003, 2004, 2007, 2008, 2012]
num_observed = [0.0025, 0.005, 0.029, 0.12, 0.275, 1.18, 3.1, 7.5, 24.0, 42.0, 220.0, 592.0, 1720.0, 2046.0, 3100.0]
plt.plot(year_predicted, num_predicted,'c--o', label='Prediction')
plt.plot(year_observed, np.log10(num_observed),'b-s', label='Observation')
plt.title('Moore\'s Law -- Observation VS Prediction', fontsize=20, fontname='Calibri', c='brown')
plt.xlabel('Year', fontsize=20, fontname='Calibri', )
plt.ylabel('Number of transistors (log)', fontsize=20, fontname='Calibri')
plt.grid()
plt.legend()
plt.show()
|
def quicksort(A, p, r):
"""A: array to be sorted
p: left index
q: right index"""
if len(A) == 1:
return A
if p < r:
"""q is partitioning index, A[q] is not at right place"""
q = partition(A, p, r)
"""Separately sort elements before and after partition"""
quicksort(A, p, q)
quicksort(A, q + 1, r)
def partition(A, p, r):
"""Function to partition for recursion"""
pivot = A[p]
i = p
j = r
while True:
while A[i] <= pivot and i <= j:
i += 1
while A[j] >= pivot and i <= j:
j -= 1
if i < j:
A[i], A[j] = A[j], A[i]
else:
break
A[p], A[j] = A[j], A[p]
return j
A = [13,19,9,5,12,8,7,4,11,2,6,21]
quicksort(A, 0, len(A) - 1)
print(A)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Helper functions to reduce code reuse and misc other uses
"""
from urllib.parse import quote
def create_url(token, url, customerid):
""" Creates the url for sending data to NodePing
Formats the url based on whether or not the
customerid is None
:type token: string
:param token: Your NodePing API token
:type url: string
:param url: full URL to API excluding the token and/or custid
:type customerid: string
:param customerid: Optional subaccount ID for your account
:return: URL that will be used for HTTP request
:rtype: string
"""
if "?" in url:
token_str = "&token="
else:
token_str = "?token="
if customerid:
url = "{0}{1}{2}&customerid={3}".format(
url, token_str, token, customerid)
else:
url = "{0}{1}{2}".format(url, token_str, token)
return url
def escape_url_string(string):
""" Escape invalid strings that will be used for a url
"""
return quote(string)
|
"""Given a string, return a string where for every char in the original, there are two chars. Eg.
double_char(The) = TThhee"""
def double_func(user_input):
new_string = ""
for char in user_input:
new_string += char * 2
return new_string
print double_func(raw_input("Enter the string :"))
|
# -*- coding:utf-8 -*-
# author:"Xianglei Kong"
class People:
school = "CUIT"
def __init__(self,name,gender,age):
self.name = name
self.gender = gender
self.age = age
class Teacher(People):
def __init__(self,name,gender,age,level,salary):
super().__init__(name,gender,age)
self.level = level
self.salary = salary
class Student(People):
def __init__(self,name,gender,age,class_time):
super().__init__(name,gender,age)
self.class_time = class_time
class Course:
def __init__(self,course_name,course_price,course_period):
self.course_name = course_name
self.course_price = course_price
self.course_period = course_period
def tell_info(self):
print ('课程:%s 价格:%s 周期%s ' % (self.course_name, self.course_price, self.course_period))
class Date:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
def tell_date(self):
print('生日:%s-%s-%s' % (self.year, self.month, self.day))
teal = Teacher('alex', '男', 22, 'SSS', 99999)
stu1 = Student('张三', '男', 32, '8:45')
python = Course('python', 9999, '4mons')
linux = Course('linux', 9999, '4mons')
go = Course('go', 9999, '4mons')
teal.course = python # 组合
stu1.course = python # # doc1.属性 = python对象
teal.date = Date(1994,11,14)
print (python) #python 对象
print (teal.course) #teal的属性
print (stu1.course)
print(python.course_name) #打印python对象的course_name属性
print(teal.course.course_name) #打印teal.course属性的course_name的属性
teal.course.tell_info() # #可以使用组合的类产生的对象所持有的方法
teal.date.tell_date()
teal.courses = []
teal.courses.append(python)
teal.courses.append(linux)
teal.courses.append(go)
for item in teal.courses: # 多个对象添加到第一个对象的属性 [ ]
item.tell_info() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.