text
stringlengths 37
1.41M
|
---|
def w(func):
print('装饰的函数')
func(1,2)
return 1
@w
def inside(a,b):
print('被装饰的函数')
print(a,b)
return 2
inside
# s=inside
# print(s)
# def bracket(data):
# return data
#
#
# if __name__ == '__main__':
# # 不带括号调用的结果:<function bracket at 0x0000000004DD0B38>,a是整个函数体,是一个函数对象,不须等该函数执行完成
# a = bracket
# print(a)
# # 带括号调用的结果:6 ,b是函数执行后返回的值6,须等该函数执行完成的结果
# b = bracket(6)
# print(b)
# def w1(func):
# def inner():
# print('--验证权限---')
# func() #这里是执行f1()函数
# print('123')
# return inner
#
# @w1 #相当于f1=wi(f1())
# def f1():
# print('f1 called')
#
# # @w1
# # def f2():
# # print('调用了该函数')
#
# f1()
# f2()
# 可变类型和不可变类型:
# 可变类型:列表,字典,集合
# 不可变类型:数字,字符串,元祖
#可变类型 两个变量同时赋值给一个时,修改了一个另一个也变了
#不可变类型:两个变量同时赋值给一个时,修改了一个另一个不变
# a,b=1,'啊'
# print(a,':',b)
# def func(*args):
# def inner():
# print(123456)
# return inner
# func(1)()
# func()()
# func(1,2,3)()
'''闭包函数'''
# def f(a):
# def f2(b):
# return a+b
# return f2
# print(f(1)(2))
# def w1(func):
# print('123')
# def inner():
# print('---1---')
# func()
# return inner
# @w1 #相当于f=w1(f)
# def fi():
# print('555')
# fi()
# def w1(func):
# print('123')
# def s():
# print('lalala')
# return s
# @w1 #相当于f1=w1(f1)
# def f1():
# print('555')
# def w1(func):
# print('123')
# def s():
# print('lalala')
# return s
# @w1 #相当于f1=w1(f1)
# def f1():
# print('555')
# f1()
#
# def w1(func):
# def inner():
# print('---1---')
# func() #这里执行的是f1()函数
# print('123')
# return inner
# @w1 #相当于f=w1(f)
# def f():
# print('555')
# f()
#
# '''
# 结果为:
# 123
# ---1---
# 555
# '''
#
# def func(a):
# print('123')
# def f(b):
# print('--权限认证--',b)
# a()
# return f
# @func #f2=func(f2)
# def f2():
# print('lalala')
# f2(1)
# import os
# os.rename('修饰器.py','装饰器.py')
# def w(n):
# def q(a,b):
# print(a)
# n(a)
# return q
# @w
# def f(a):
# print(2)
# f(1,2)
#当给装饰器有传参的时候,传的虽然是给装饰器的子函数传的参数,但也可以给调用函数传参,但传参名要一样,并且调用函数的参数个数要小于等于装饰器的子函数的传参个数,都有的形参名要相等 不然会报错
# def w(f):
# def a():
# print('a的函数')
# f()
# return a
# # @w #a1=w(a1)
# def a1():
# print('a1函数')
# @w #a2=w(a2)
# def a2():
# a1()
# print('a2的函数')
# a2()
# def ooo(a):
# print("1")
# def qqq():
# print("2")
# a() #执行rrr函数
# return qqq
#
#
# def www(a):
# print("3")
# def rrr():
# print("4")
# a() #执行pop函数
# return rrr
#
# @ooo #pop->相当于www(pop)->相当于rrr=ooo(pop->相当于www(pop)->相当于rrr) 执行ooo函数
# @www #pop=www(pop)
#
# def ppp():
# print("5")
#
# ppp() #执行www()函数
# def w(func):
# def f1():
# print('01-----开始')
# func()
# print('01----结束')
# return f1
# def w2(func):
# def f2():
# print('02-----开始')
# func()
# print('02----结束')
# return f2
# @w
# @w2
# def f3():
# print('修复漏洞')
# f3()
# def zhs(func):
# print("第一个装饰器")
# def haha():
# print("1开始")
# func()
# print("1结束")
# return haha
# def zhs1(func):
# print("第二个装饰器")
# def haha():
# print("2开始")
# func()
# print("2结束")
# return haha
# @zhs # xixi = zhs(xixi)
# @zhs1
# def xixi():
# print("我是嘻嘻")
#
# if __name__ == '__main__':
# xixi()
|
# Code to Get Co-Ordinates
import math
import requests
import operator
def get_cords(my_lat,my_long,dist,angle):
"""The function get_cords() returns the user defined latitude and longitude coordinates in degrees"""
R = 3963.167 #Radius of the Earth in miles
brng = math.radians(angle) #Bearing is converted to radians.
d = dist #Distance in miles
lat1 = math.radians(my_lat) #Current lat point converted to radians
lon1 = math.radians(my_long) #Current long point converted to radians
lat2 = math.asin( math.sin(lat1)*math.cos(d/R) +
math.cos(lat1)*math.sin(d/R)*math.cos(brng))
lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat1),
math.cos(d/R)-math.sin(lat1)*math.sin(lat2))
lat2 = math.degrees(lat2)
lon2 = math.degrees(lon2)
return(lat2,lon2)
#Code to Get Extents of Map Range within our mile radius
def get_extent(my_lat,my_long,dist):
"""This function intends to calculate the latitude and longitude range in which the airports will be located.
The 3 angles were assumed on the basis of the understanding that the user is in the middle of a rectangle
(inside a circle) and to calculate the extent of latitude and longitude, we would require coordinates on
the 3 edges which makes the 3 respective angles with the center: 45, -45 and -135"""
top_left=get_cords(my_lat,my_long,dist,-45)
bot_left=get_cords(my_lat,my_long,dist,-135)
top_right=get_cords(my_lat,my_long,dist,45)
lat_range=[bot_left[0],top_left[0]]
long_range=[top_left[1],top_right[1]]
return(lat_range,long_range)
def test_sorted_airport(my_loclat,my_loclong,myrange):
"""This function returns the list of airports in the vicinity of the user provided location coordinates,
sorted on the basis of their distance from the user. The limit of displayed airports have been increased
to 200 instead of the default 25. This function also takes care of the case in which the airport's distance
from the user falls outs of the given range - for which their would be no output"""
lat_range,long_range=get_extent(my_loclat,my_loclong,myrange)
url="https://mikerhodes.cloudant.com/airportdb/_design/view1/_search/geo?q=lat:["+str(lat_range[0])+"00%20TO%20"+str(lat_range[1])+"]%20AND%20lon:["+str(long_range[0])+"%20TO%20+"+str(long_range[1])+"]&sort=%22%3Cdistance,lon,lat,"+str(my_loclong)+","+str(my_loclat)+",mi%3E%22&limit=200"
my_result=[]
r = requests.get(url)
for i in r.json()['rows']:
airport_name=(i['fields']['name'])
dist=(i['order'][0])
if(dist>myrange):
break
else:
my_result.append(str('Airport: ' + airport_name+', Distance From Location = '+str(dist)))
return(my_result)
def main():
mlat=input("Enter Your Location Latitude = ")
mlong=input("Enter Your Location Longitude = ")
mdist=input("Enter Your Distance Range for Airports in Miles = ")
print(sorted_airport(mlat,mlong,mdist))
if __name__== "__main__":
main()
|
# I am going to do some counting and math.
print "#1: What is 5 + 5?", 5 + 5
print "#2: What is 5 * 3?", 5 * 3
print "Is #1 greater than #2?", 5 + 5 > 5 * 3
print "Is #1 greater than equal #2?", 5 + 5 >= 5 * 3
print "Here is the second counting."
print "Do math:4 + 3 - 3 / 1 + 4 % 2 equals", 4 + 3 - 3 / 1 + 4 % 2
|
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'orange', 'pears', 'appricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quaters']
# the first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
#also we can go through mixed lists too
# notice we have to use %r since we dont know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in elements:
print "Element was: %d" % i
#update list
elements.append(2009);
print "updated list is: %r" % elements
|
#!/usr/bin/python
class Solution(object):
def hammingDistance(self,x,y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
if __name__ == '__main__':
x = int(input("input x :"))
y = int(input("input y :"))
print("Hamming Distance:",Solution().hammingDistance(x,y))
|
#!/usr/bin/python
class Solution(object):
def reverseWords(self,s):
'''
:type s : str
:rtype: str
'''
#return ' '.join(s.split()[::-1])[::-1]
return ' '.join(word[::-1] for word in s.split())
if __name__ == '__main__':
x = str(input("input a string:"))
print(Solution().reverseWords(x))
|
#!/usr/bin/python
class Solution(object):
def detectCapitalUse(self,word):
'''
:type word: str
:rtype: bool
'''
return word.isupper() or word.islower() or word.istitle()
if __name__ == '__main__':
x = str(input("input a string:"))
print("Capital detection:",Solution().detectCapitalUse(x))
|
# Name: Dusty Stepak
# Date: 04.12.2021
# Program: BruteForce.py
# Purpose: Create a brute force password cracking program in Python.
# This program asks the user to enter a password, and the
# program tries to crack it by checking all possible passwords
# with the characters a-zA-Z0-9. Search is limited to passwords
# of length 4 or less.
# Prompts the user for a password. Sores value into global variable
# password.
#
# @Author Dusty Stepak
# @Since 04.12.2021
#
def askForUserInput():
password = input("Enter password: ")
print(password) #Debug
guessPassword(password)
# Loops through every possible value that could be contained within the
# password, up to length 4.
def guessPassword(check):
guess = "" #Stores the current 'guess'
passcode = str(check)
print(passcode)
# guess = guess[0:i] + letter
# Checks String Length of 1
# ------------------------------------------------------------------------
for letter in POSSIBLE_ALPHA_VALUES:
guess = letter
print(guess)
if guess == passcode:
break
if guess != passcode:
for number in POSSIBLE_NUMERIC_VALUES:
guess = number
print(guess)
if guess == passcode:
break
# Checks String Length of 2
# ------------------------------------------------------------------------
# Letter + Letter
if guess != passcode:
for first_letter in POSSIBLE_ALPHA_VALUES:
for second_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter + second_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Letter + Number
if guess != passcode:
for first_letter in POSSIBLE_ALPHA_VALUES:
for second_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter + second_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Number + Number
if guess != passcode:
for first_number in POSSIBLE_NUMERIC_VALUES:
for second_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number + second_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Number + Letter
if guess != passcode:
for first_number in POSSIBLE_NUMERIC_VALUES:
for second_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number + second_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Checks String Length of 3
# ------------------------------------------------------------------------
# Letter + Letter + Letter
if guess != passcode:
for first_letter in POSSIBLE_ALPHA_VALUES:
# Letter + Letter + []
for second_letter in POSSIBLE_ALPHA_VALUES:
# Letter, Letter, Letter
for third_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter + second_letter + third_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Letter, Letter, Number
for third_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter + second_letter + third_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# Letter + Number + []
for second_number in POSSIBLE_NUMERIC_VALUES:
# Letter, Number, Letter
for third_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter + second_number + third_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Letter, Letter, Number
for third_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter + second_number + third_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess != passcode:
# Number + [] + []
for first_number in POSSIBLE_NUMERIC_VALUES:
# Number + Letter + []
for second_letter in POSSIBLE_ALPHA_VALUES:
# Letter, Letter, Letter
for third_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number + second_letter + third_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Number, Letter, Number
for third_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number + second_letter + third_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# Number + Number + []
for second_number in POSSIBLE_NUMERIC_VALUES:
# Number, Number, Letter
for third_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number + second_number + third_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# Number, Letter, Number
for third_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number + second_number + third_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# Checks String Length of 4
# ------------------------------------------------------------------------
# Letter + Letter + Letter + Letter
if guess != passcode:
# letter + [] + [] + []
for first_letter in POSSIBLE_ALPHA_VALUES:
# letter + letter + [] + []
for second_letter in POSSIBLE_ALPHA_VALUES:
# letter + letter + letter + []
for third_letter in POSSIBLE_ALPHA_VALUES:
# letter + letter + letter + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter+second_letter+third_letter+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + letter + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter+second_letter+third_letter+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + number + []
for third_number in POSSIBLE_NUMERIC_VALUES:
# letter + letter + number + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter+second_letter+third_number+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + number + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter+second_letter+third_number+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# letter + number + [] + []
for second_number in POSSIBLE_NUMERIC_VALUES:
# letter + letter + letter + []
for third_letter in POSSIBLE_ALPHA_VALUES:
# letter + letter + letter + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter+second_number+third_letter+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + letter + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter+second_number+third_letter+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + number + []
for third_number in POSSIBLE_NUMERIC_VALUES:
# letter + letter + number + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_letter+second_number+third_number+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# letter + letter + number + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_letter+second_number+third_number+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess != passcode:
# number + [] + [] + []
for first_number in POSSIBLE_ALPHA_VALUES:
# number + letter + [] + []
for second_letter in POSSIBLE_ALPHA_VALUES:
# number + letter + letter + []
for third_letter in POSSIBLE_ALPHA_VALUES:
# number + letter + letter + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number+second_letter+third_letter+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# number + letter + letter + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number+second_letter+third_letter+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# number + letter + number + []
for third_number in POSSIBLE_NUMERIC_VALUES:
# number + letter + number + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number+second_letter+third_number+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# number + letter + number + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number+second_letter+third_number+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# number + number + [] + []
for second_number in POSSIBLE_NUMERIC_VALUES:
# number + letter + letter + []
for third_letter in POSSIBLE_ALPHA_VALUES:
# number + letter + letter + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number+second_number+third_letter+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# number + letter + letter + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number+second_number+third_letter+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
# number + letter + number + []
for third_number in POSSIBLE_ALPHA_VALUES:
# number + letter + number + letter
for fourth_letter in POSSIBLE_ALPHA_VALUES:
guess = str(first_number+second_number+third_number+fourth_letter)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
# number + letter + number + number
for fourth_number in POSSIBLE_NUMERIC_VALUES:
guess = str(first_number+second_number+third_number+fourth_number)
print(guess)
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
if guess == passcode:
break
print()
print("You've been HACKED!")
print("Your password: " + str(passcode))
print("Our password: " + str(guess))
# --------------------------------------------------------------------------
# Global Variable Declaration
# --------------------------------------------------------------------------
# Constants
POSSIBLE_ALPHA_VALUES = ["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"]
POSSIBLE_NUMERIC_VALUES = ["0","1","2","3","4","5","6","7","8","9"]
# --------------------------------------------------------------------------
# Main function call
# --------------------------------------------------------------------------
askForUserInput()
|
#####################################
# Exercícios do site Codecombat.com #
# Autor: Rodrigo Vieira Peres #
# Data: 24/04/2016 #
# #
# Site: http://www.rodrigoperes.tk/ #
# #
# Arquivo: Lv7 - Loop Da Loop.py #
#####################################
"""Your hero must survive. Navigate the maze. Under 6 statements. You only need one while-true loop. It will repeat!"""
# Use a while-true loop to navigate the maze!
while True:
self.moveRight()
self.moveUp()
self.moveRight()
self.moveDown()
|
__author__ = 'madeira'
def average ( x, y, z):
if x > y:
if x > z:
if z > y:
return z
else:
return y
else:
return x
elif x > z:
return x
elif z > y:
return y
else:
return z
assert average (1,3,6) == 3
assert average (1,6,3) == 3
assert average (3,1,6) == 3
assert average (3,6,1) == 3
assert average (6,3,1) == 3
assert average (6,1,3) == 3
|
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
:param n:
:return:
"""
if n < 0:
n = n*-1
return find_largest_digit_helper(n, 0)
def find_largest_digit_helper(n, lar):
"""
:param n:
:param lar:
:return:
"""
if n < 10:
if n > lar:
return n
return lar
else:
num = n % 10
if num > lar:
lar = num
new_n = n//10
return find_largest_digit_helper(new_n, lar)
if __name__ == '__main__':
main()
|
# https://www.codewars.com/kata/51c8e37cee245da6b40000bd/python
def solution(string,markers):
lines = string.split('\n')
stripped_lines = []
for line in lines:
stripped_line = line
for marker in markers:
if marker in stripped_line:
stripped_line = stripped_line[0:line.find(marker)].strip(' ')
stripped_lines.append(stripped_line)
return '\n'.join(stripped_lines)
solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
|
def fibonacci(limit):
fib = [1,2]
limit_hit = False
while(not limit_hit):
next_fib = fib[len(fib)-1] + fib[len(fib)-2]
if next_fib < limit:
fib.append(next_fib)
else:
limit_hit = True
return fib
def main():
fibs = fibonacci(4000000)
print sum([x for x in fibs if x % 2 == 0])
if __name__ == '__main__':
main()
|
print(1 > 3)
print(2 < 4)
print(4 <= 5)
print(4 >= 5)
print(6 == 9)
print(6 != 9)
# 복합 관계식
a = 6
print(0 < a and a < 10)
print(0 < a < 10)
# 수치형 이외의 다른 타입의 객체 비교
print("abcd" > "abd")
print((1,2,4) < (1,3,1))
print([1,2,4] < [1,2,0])
# 동질성 비교 : ==, 동일성 비교 : is
print("동질성 비교")
a = 10
b = 20
c = a
print(a == b)
print(a is b)
print(a is c)
print(a == c)
|
from numpy import array
from numpy import mean
from numpy import cov
from numpy.linalg import eig
# define a small 5×3 matrix
matrix = array([[5, 6,3],
[8, 10,2],
[12, 18,4],
[8, 10,1],
[6, 12,5],])
print("original Matrix: ")
print(matrix)
# step-1 calculate the mean of each column
Mean_col = mean(matrix, axis=0)# [7.8,11.2 3]
print("Mean of each column: ")
print(Mean_col)
# center columns by subtracting column means
normalized_data = matrix - Mean_col
print("Normalized Data: ")
print(normalized_data)
# calculate covariance matrix of centered matrix
cov_matrix = cov(normalized_data.T)
print("Covariance Matrix",cov_matrix)
# eigendecomposition of covariance matrix
values, vectors = eig(cov_matrix)
print("Eigen vectors: ",vectors)
print("Eigen values: ",values)
# project data on the new axes
projected_data = vectors.T.dot(normalized_data.T) # (3x3)(3x5)->(3x5)
print("projected data",projected_data.T) # (5x3)
|
#!/usr/bin/env python3
# 12 - O python tem uma implementacão padrão de uma funcão sum para achar a soma dos elementos de uma lista, faca sua própria implementacão da funcão
#sum([1, 2, 3])
#6
index = int(input("Insira a quantidade de elementos: "))
def somaLista(index):
lista = []
for i in range(0, index):
elemento = int(input())
lista.append(elemento)
print(lista)
#Função:
somaLista(index)
|
#!/usr/bin/env python3
#11 - Escreva uma funcão que imprima todos os números primos entre 0 e limit (um parâmetro).
limit = int(input("Insira o limite: "))
def prime(limit):
for i in range(2,limit+1):
multiplos = 0
for j in range(2,i):
if i % j ==0:
multiplos += 1
if multiplos == 0:
print ("{} é primo".format(i))
prime(limit)
|
import random
def selection_sort( arr):
for i in range(len(arr)):
midx = i
for j in range(i,len(arr)):
if arr[j] < arr[midx]:
midx = j
if midx != i:
arr[midx],arr[i] = arr[i],arr[midx]
return arr
def tester():
for _ in range(25):
rand_arr = [random.randint(-10**3,10**3) for i in range(1000)]
print(sorted(rand_arr) == selection_sort(rand_arr))
tester()
|
# Part one
with open("words.txt","r") as f:
words = set(word.rstrip() for word in f)
from itertools import permutations
def allwords(s, n=1):
perm = list()
while len(s) >= n:
p = permutations(s, n)
for i in p:
i = ''.join(i)
i = i.lower()
if i in words and i not in perm:
perm.append(i)
n += 1
# Python sort is stable, so will be left in alphabetical order when sorting
# by length.
perm = sorted(perm)
perm = sorted(perm, key=len)
return perm
# Testing part one
print allwords('things')
print allwords('stuff', 3)
# Part two
import random
randomWord = list()
while (len(randomWord) != 6):
randomWord = list(''.join(random.sample(words, 1)))
random.shuffle(randomWord)
guess = ""
answers = allwords(randomWord, 4)
fourl = [word for word in answers if len(word) == 4]
fivel = [word for word in answers if len(word) == 5]
sixl = [word for word in answers if len(word) == 6]
guessedfour, guessedfive, guessedsix = [], [], []
while (guess != 'q'):
print "\n%s:\n" % ''.join(randomWord)
print "%s:" % guessedfour
print "%d 4-letter words left." % len(fourl)
print "%s:" % guessedfive
print "%d 5-letter words left." % len(fivel)
print "%s:" % guessedsix
print "%d 6-letter words left." % len(sixl)
guess = raw_input("\nEnter a guess: ")
if guess in fourl:
fourl = [word for word in fourl if word != guess]
guessedfour.append(guess)
# Could use bisect or binary/linear search rather than sorted to
# improve efficiency, though these lists will always be small.
guessedfour = sorted(guessedfour)
print "Correct!"
elif guess in fivel:
fivel = [word for word in fivel if word != guess]
guessedfive.append(guess)
guessedfive = sorted(guessedfive)
print "Correct!"
elif guess in sixl:
sixl = [word for word in sixl if word != guess]
guessedsix.append(guess)
guessedsix = sorted(guessedsix)
print "Correct!"
elif guess != 'q': print "Incorrect."
if ((len(fourl) + len(fivel) + len(sixl)) == 0):
print "\nCongratulations! You've won."
guess = 'q' # Could reset start rather than quitting.
|
def extractfiles(zipf, regex):
import zipfile, os, re
zfile = zipfile.ZipFile(zipf, "r")
for f in zfile.namelist(): # Using the file list circumvents the underscore problem.
if re.match(regex, os.path.basename(f)):
zfile.extract(f, 'extractfilesresult') # Extracting to special directory to ensure correctness.
if __name__ == '__main__':
import sys
if len(sys.argv) == 3:
extractfiles(sys.argv[1], sys.argv[2])
else:
print "Too many/few arguments supplied: extractfiles.py takes (2) arguments."
|
# Problem link: https://www.codewars.com/kata/525c7c5ab6aecef16e0001a5/train/python
## Work in progress
wordMap = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'fourty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninty': 90,
'hundred': 100,
}
def parse_int(string):
string = string.split(" ")[::-1]
for word in string:
if word.lower() in wordMap.keys():
print (wordMap[word.lower()])
return # number
parse_int("two hundred and three")
|
class EvenIterator:
def __init__(self, lst):
self.lst = lst
self.elem = 0
def __iter__(self):
return self
def __next__(self):
if self.elem < len(self.lst):
self.elem += 2
return self.lst[self.elem - 2]
else:
raise StopIteration
for x in EvenIterator([6, 1, 0, 8, 5, 13, 24]):
print(x)
|
# ex. 1
def sq(a, x):
res = []
count = 0
for i in range(0, x+1):
if i % 2 != 0:
res += [i**2]
count += 1
i += 1
print(*res, 'всего чисел -', count)
sq(0, 9)
# ex. 2
def div_by_c(a, b, c):
count = 0
for i in range(a+1, b):
if i % c == 0:
count += 1
i += 1
print(count)
div_by_c(-11, 12, 4)
# ex. 3
def fact(a):
result = 1
for i in range(2, a+1):
result *= i
i += 1
print(result)
fact(45)
# ex. 4
def old_range(a, b, c=1):
range_list = []
i = a
while i < b:
range_list += [i]
i += c
print(range_list)
old_range(-8, 2)
old_range(2, 26, 3)
# ex. 5
name_password = {
'Vasyliy': '123456',
'123ya': '123ya',
'Angelina': 'porosenochek'
}
name = input("Введите имя пользователя ")
password = input("Введите пароль ")
for key, value in name_password.items():
if name_password[name] == password:
print("Password for user:", name, "is correct")
break
else:
print("Password for user:", name, "is incorrect")
print("Please try again...")
password = input("Введите пароль ")
|
import time
import sys
import random
number=random.randint(1,100)
def intro():
print("WELCOME TO GUESS THE NUMBER GAME\nHERE YOU NEED TO GUESS THE NUMBER")
time.sleep(1)
print("BETWEEN 1 TO 100\n5 CHANCES WILL BE GIVEN\nWITH SOME INTRESTING HINTS\n\n")
def lesser_or_greater(guess):
global number
if guess>number:
print("THE NUMBER IS LESS THAN YOUR GUESS\n")
elif guess==number:
print("CONGRATS..YOU GUESSED THE RIGHT NUMBER\n")
sys.exit()
else:
print("THE NUMBER IS GREATER THAN YOUR GUESS\n")
def divisible(guess):
global number
if guess==number:
print("CONGRATS..YOU GUESSED THE RIGHT NUMBER\n")
sys.exit()
lesser_or_greater(guess)
time.sleep(1)
num_list=list()
for x in range(1,9):
if number%x == 0:
num_list.append(x)
if len(num_list)==1:
print("THE NUMBER IS ONLY DIVISIBLE BY 1\n")
else:
print("THE NUMBER IS DIVISIBLE BY ",random.choice(num_list[1:]))
print("\n")
def sum_digits(guess):
global number
if guess==number:
print("CONGRATS..YOU GUESSED THE RIGHT NUMBER\n")
sys.exit()
divisible(guess)
time.sleep(1)
total=0
num1=number
while num1 != 0:
total=total+int(num1%10)
num1=int(num1/10)
print("THE SUM OF DIGITS OF THE NUMBER IS ",total)
print("\n")
def diff(guess):
global number
if guess==number:
print("CONGRATS..YOU GUESSED THE RIGHT NUMBER\n")
sys.exit()
divisible(guess)
time.sleep(1)
difference=abs(number-guess)
if difference<=10:
print("YOUR GUESS IS ATMOST 10 NUMBERS AWAY FROM THE CORRECT NUMBER\n")
else:
print("YOUR GUESS IS ATLEAST 11 NUMBERS AWAY FROM THE CORRECT NUMBER\n")
def error_handling(guess):
if guess<1:
print("GUESS NUMBER SHOULD NOT BE NEGETIVE\n")
guess=int(input("PLEASE ENTER THE GUESS NUMBER : "))
else:
if guess>100:
print("GUESS NUMBER SHOULD NOT EXCEED 100\n")
guess=int(input("PLEASE ENTER THE GUESS NUMBER : "))
intro()
guess=int(input("FIRST GUESS : "))
error_handling(guess)
lesser_or_greater(guess)
guess=int(input("SECOND GUESS : "))
error_handling(guess)
divisible(guess)
guess=int(input("THIRD GUESS : "))
error_handling(guess)
sum_digits(guess)
guess=int(input("FOURTH GUESS : "))
error_handling(guess)
diff(guess)
guess=int(input("FIFTH GUESS : "))
if guess==number:
print("HURREY..FINALLY YOU WON\n")
time.sleep(5)
else:
print("YOU LOST,THE NUMBER IS",number)
time.sleep(5)
|
# The game Fizz AND Buzz!
# multiple of 3 are POP
# multiple of 5 are TOC
# multiples of 3 and 5 are FizzBuzz
# as a user I should be ask for a number,
# so that I can play the game with my input
# As a player, I should see the game counting up to my number and
# substituting the multiples of 3 and 5 with the appropriate values,
# So that I can see if it is working
# import time
while True:
num = int(input("give a numnber to count up to, enter 000 to end the game"))
count_num = 1
if num == 000:
break
while num >= count_num:
if count_num % 15 == 0:
print("fizzbuzz")
time.sleep(1)
elif count_num % 3 == 0:
print("fizz")
elif count_num % 5 == 0:
print("buzz")
else:
print(count_num)
count_num += 1
def fizz(x):
if x % 5 == 0:
return "fizz"
def buzz(x):
if x % 3 == 0:
return "buzz"
def fizz_buzz(x):
if x % 15 == 0:
return "fizzbuzz"
print(buzz(6))
while True:
question = (input("what is your question sir ")).strip().lower()
print("questions are wise, but for now. Wax on, and Wax off!")
if "sensei" not in question:
print("You are smart, but not wise, address me as sensei please")
elif "block" or "blocking:" in question:
print("Rememeber, best block, not to be there")
elif "sensei im at peace" in question:
print('Sometimes, what heart know, head forget')
elif "sensei" or "block" or "blocking" or "sensei im at peace" not in question:
print("do not lose focus. Wax on. Wax off")
else:
print("do not lose focus. Wax on. Wax off.")
|
# Variables in Python
# A variable is a box. And we put stuff inside and give it a name
# Assign a variable
box_pillows = 'Pillows and stuff' # gave the box a name and put stuff inside
print(box_pillows) # Look inside a box
box_pillows = 'Books' # changing the stuff inside the box
print(box_pillows)
box_pillows = 14 # reassigning to different data types
print(box_pillows)
# Important functions in python
# print()
# type() returns the data type of the variable inside
# input() prompts user for input
print('Hello there!, What is your name?')
what_is_your_name = input()
print('Hi There, ', (what_is_your_name))
|
#Fruit Machine:
#Write a program to simulate a Fruit Machine that displays three symbols
#at random from Cherry, Bell, Lemon, Orange, Star, Skull.
#The player starts with £1 credit, with each go costing 20p.
#If the Fruit Machine “rolls” two of the same symbol, the user wins 50p.
#The player wins £1 for three of the same and £5 for 3
#Bells. The player loses £1 if two skulls are rolled and all of his/her money
#if three skulls are rolled. The player can choose to quit with the winnings
#after each roll or keep playing until there is no money left.
#display 3 symbols from list
import random
def display_cred(credit):
print("\nCredit: £" + format(credit, ".2f"))
return capture_input("Would you like to play again for £0.20?")
def capture_input(output_string = ""):
captured = ""
while captured == "":
print("\n" + output_string)
try:
captured = input("(Y)es or (N)o? ").lower().strip()
if captured == "y":
return True
elif captured == "n":
return False
else:
raise Exception
except:
print("Error: Please enter a Y/N.\n")
captured = ""
def play(credit):
#Rolling reels
symbols = ["Cherry", " Bell ", "Lemon ", "Orange", " Star ", "Skull "]
reels = []
print("\nReels rolling!\n\n| ", end = "")
for i in range(3):
#test
#reels.append("Skull")
reels.append(random.choice(symbols))
print(reels[i], end = " | ")
print()
print()
if reels[0] == reels[1] and reels[0] == reels[2]:
#3 reels
if reels[0] == "Bell":
#big payout £5
print("Three Bells! £5 won!")
return 5
elif reels[0] == "Skull":
#dead!
print("Three Skulls! You lose!")
return credit * -1
else:
#little payout £1
print("Three symbols! £1 won!")
return 1
elif reels[0] == reels [1] or \
reels[1] == reels[2] or \
reels[2] == reels[0]:
if reels[0] == "Skull":
#injury -£1
print("Two Skulls! £1 lost!")
return -1
else:
#tiny payout £.5
print("Two symbols! £0.50 won!")
return .5
else:
print("Sorry, no win here...")
print("")
print("")
return 0
def cash_out(credit):
print("You cashed out. \nCongratulations on walking out with £" + format(credit, ".2f"))
def ran_out():
print("Sorry you've ran out of money. \nPlease restart to try again.")
def main():
credit = 1
keep_playing = True
while keep_playing and credit >= .2:
keep_playing = display_cred(credit)
if keep_playing:
credit -= .2
credit += play(credit)
if not keep_playing:
cash_out(credit)
else:
ran_out()
main()
|
arr = []
maxHourGlass = 0
row = 6
column = 6
for i in range(0, row):
temp_row = []
for j in range (0, column):
temp_row.append(int(input()))
#print(temp_row)
arr.append(temp_row)
#print(arr)
#print(arr)
for i in range(0, row - 2):
for j in range(0, column - 2):
sumHourGlass = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]
maxHourGlass = max(sumHourGlass, maxHourGlass)
print(maxHourGlass)
|
entryNo = int(input("How many records would you like to add?: "))
phoneNumber = dict()
def addNumber(Name, Number):
if Name in phoneNumber:
print("Error")
else:
phoneNumber[Name] = Number
for i in range (entryNo):
Name, Number = input("Enter the name and Number you want to add: ").split()
Name = Name.lower()
if len(Number) < 8:
print("Phone Number error")
continue
else:
addNumber(Name, Number)
while True:
print("Enter a name:(blank to quit)")
Name = input()
if Name == "":
break
if Name in phoneNumber:
print(Name + "=" + phoneNumber[Name])
else:
print("Not Found")
#print(phoneNumber)
|
num=int(input("Enter a number"))
fact=1
for x in range (1,num+1):
fact =fact*x
print("Factorial of {} is {}".format(num,fact))
|
import numpy as np
from typing import Tuple, List
from numpy import sqrt
NN = np.nan
def in_range(data, minval=-np.inf, maxval=np.inf):
"""
Find values in range [minval, maxval).
Parameters
---------
data : np.ndarray
Data set of arbitrary dimension.
minval : int or float, optional
Range minimum. Defaults to -inf.
maxval : int or float, optional
Range maximum. Defaults to +inf.
Returns
-------
selection : np.ndarray
Boolean array with the same dimension as the input. Contains True
for those values of data in the input range and False for the others.
"""
return (minval <= data) & (data < maxval)
def relative_error_ratio(a : float, sigma_a: float,
b :float, sigma_b : float) ->float:
"""
Error of a/b
"""
return sqrt((sigma_a / a)**2 + (sigma_b / b)**2)
def mean_and_std(x : np.array,
range_ : Tuple[float, float])->Tuple[float, float]:
"""
Computes mean and std for an array within a range:
takes into account nans
"""
mu = NN
std = NN
if np.count_nonzero(np.isnan(x)) == len(x): # all elements are nan
mu = NN
std = NN
elif np.count_nonzero(np.isnan(x)) > 0:
mu = np.nanmean(x)
std = np.nanstd(x)
else:
x = np.array(x)
if len(x) > 0:
y = x[in_range(x, *range_)]
if len(y) == 0:
print(f'warning, empty slice of x = {x} in range = {range_}')
print(f'returning mean and std of x = {x}')
y = x
mu = np.mean(y)
std = np.std(y)
return mu, std
def gaussian_experiment(nevt : int = 1000,
mean : float = 100,
std : float = 10)->np.array:
Nevt = int(nevt)
e = np.random.normal(mean, std, Nevt)
return e
def gaussian_experiments(mexperiments : int = 1000,
nsample : int = 1000,
mean : float = 1e+4,
std : float = 100)->List[np.array]:
return [gaussian_experiment(nsample, mean, std) for i in range(mexperiments)]
def gaussian_experiments_variable_mean_and_std(mexperiments : int = 1000,
nsample : int = 100,
mean_range : Tuple[float, float] = (100, 1000),
std_range : Tuple[float, float] = (1, 50))->List[np.array]:
"""
Run mexperiments gaussina experiments each with nsample samples
"""
Nevt = mexperiments
sample = nsample
stds = np.random.uniform(low=std_range[0], high=std_range[1],
size=sample)
means = np.random.uniform(low=mean_range[0], high=mean_range[1],
size=sample)
exps = [gaussian_experiment(Nevt, mean,
std) for mean in means for std in stds]
return means, stds, exps
def smear_e(e : np.array, std : float)->np.array:
"""
Gaussian smearing to array (e)
"""
return np.array([np.random.normal(x, std) for x in e])
# Binning data
def bin_data_with_equal_bin_size(data : List[np.array],
bin_size : float)->List[np.array]:
"""
Given a list of numpy arrays (or any sequence with max() and min())
and a bin size (the same for all arrays) return arrays with the bin edges
"""
BinData = []
for x in data:
nbins = int((x.max() - x.min()) / bin_size)
assert nbins >= 1, "bin size must be at least same size that xmax-xmin"
_, bin_edges = np.histogram(x, bins=nbins + 1)
#xbins = np.linspace(x.min(), x.max(), nbins)
BinData.append(bin_edges)
return BinData
|
inp = int(input('請輸入n,製造乘法表:'))
print("")
print("用if方式寫n*n乘法表")
for i in range(1,inp+1):
print("")
for j in range(1,inp+1):
print(f"{i}*{j}:{i*j}")
print("")
print("用while方式寫n*n乘法表")
print("")
a = 1
while 1 <= a <= inp:
b = 1
while 1 <= b <= inp:
print(f"{a}*{b}:{a*b}")
b += 1
print(" ")
a +=1
|
n=int(input("enter a number"))
a=0
b=0
for i in range(2,n+1):
c=a+b
a=b
b=a
print(b, end=" ")
|
n=input("enter a number")
asc=n[0] <= n[1]
dsc=n[0] >= n[1]
i=1
while (i<(len(n)-1)):
if asc:
asc =n[i] <= n[i+1]
elif dsc:
dsc = n[i] >= n[i+1]
else:
break
i+-1
if asc:
print("ascending")
elif dsc:
print("decending")
else:
print("not found")
|
###################################
# INTERPOL, which stands for Integer Program Oriented Language, is a language specifically designed for IS 214 students.
# Compared to its IS 214 predecessors, INTERPOL is the simplest of them all.
# What makes it “integer oriented” is that the PL primarily deals with integers and consequently,
# no floating-point values are allowed.
# This implies that the results of arithmetic operations are automatically converted to integers.
# Strings are also allowed for printing purposes.
# The goal of this programming assignment is to implement an INTERPOL interpreter using Python,
# which you have learned at the beginning of the semester. You may accomplish the assignment individually or by pair.
# Your interpreter should be able to perform the following:
# Accept expressions from the user.
# Parse the code entered by the user and check for lexical and syntax errors.
# Properly execute INTERPOL expressions by the user.
# Spaces are used to demarcate tokens in the language.
# Multiple spaces and tabs are treated as single spaces and are otherwise considered irrelevant.
# Indentation is also irrelevant.
# INTERPOL is case sensitive.
#INTERPOL only has one section.
# The section begins with the CREATE keyword and ends with the RUPTURE keyword.
# All coding - variable declarations and actual instructions - are to be placed between these keywords.
# CREATE
# DSTR stringmo WITH [I have a pen]
# GIVEYOU!! stringmo
# DINT x WITH PLUS 1 MINUS 9 9
# DINT y
# STORE 100 IN y
# GIVEYOU!! x
# GIVEYOU! y
# RUPTURE
# Output:
# I have a pen
# 1
# 100
DINT,DST,STORE = "DINT","DSTR","STORE"
PLUS,MINUS,MULT,DIV,MODU = "PLUS","MINUS","MULT","DIV","MODU"
class Token(object):
def __init__(self,type,value):
self.type = type
self.value = value
def __str__(self):
return 'Token({type},{value})'.format(type = self.type, value = repr(self.value))
def __repr__(self):
return self.__str__()
# There are only 2 main data types: integer and string.
# The interpreter shall follow the principles of strong typing.
# Therefore, intermixing of integers and strings in arithmetic operations is not allowed.
# All variables are declared and are global in scope.
# Any attempts to use floating-point values should result to an error.
# A string is enclosed by square brackets.
# Declaring an integer variable without an initial value: DINT <variable_name>
# Declaring an integer variable with an initial value: DINT <variable_name> WITH <expression>
# Declaring a string variable without an initial value: DSTR <variable_name>
# Declaring a string variable with an initial value: DSTR <variable_name> WITH <expression>
# Assignment: STORE <expression> IN <variable>
# An expression can be a literal/value, a variable, or it can be composed of several adjacent operators.
# Hence, nested expressions should be successfully implemented as well in your interpreter.
# InterpolBody is for the processing of the entire code block
class InterpolBody(object):
def __init__(self,code_block):
self = self
self.code_block = code_block
def processBlock(self):
# process code block
# segregate code blocks
# create tokens
temp_tokens = []
for i in range(len(self.code_block)):
temp_tokens = self.code_block[i].replace('\t','').split(' ')
if self.checkGrammar(temp_tokens) == True:
print("correct grammar")
else:
print("Syntax Error! Invalid syntax")
print(temp_tokens)
i+=1
return self
def checkGrammar(self,block_line):
symbol_table = []
lexemes = []
tokens = []
isDeclaration = False
isAssignment = False
startToken = 0
token_type = ""
for i in range(len(block_line)):
# check if declaration
# check type of declaration
if (block_line[i] == DINT or block_line[i] == DST) and i==0:
isDeclaration = True
startToken = 1
token_type = "Identifier"
if block_line[i] == STORE and i==0:
isAssignment = True
startToken = 1
token_type = "Identifier"
elif isinstance(block_line[i],int):
token_type = "Integer"
elif block_line[i] == "WITH" or block_line[i] == "IN":
token_type = "Identifier"
elif block_line[i] == PLUS or block_line[i] == MINUS or block_line[i] == DIV or block_line[i] == MULT or block_line[i] == DIV or block_line[i] == MODU:
token_type = "Expression"
symbol_table.append(Token(token_type,block_line[i]))
i+=1
print(symbol_table)
# check if assignment
# check if expression
return True
def checkContext(self):
return self
def getResult(self):
return self.code_block
class InputOutput(object):
def __init__(self):
self = self
def inputFromUser(self):
# Asking input from the user: GIVEME? <variable_name>
return input("GIVEME? ")
def printOutput(self,tag,output_block):
if tag == 1:
# Printing values, variables, and expressions: GIVEYOU! <expression>
return print("GIVEYOU!",output_block)
elif tag == 2:
# Printing values, variables, and expressions with a new line affixed at the end: GIVEYOU!! <expression>
return print("GIVEYOU!",output_block,"\n")
class ArithmeticOperations(object):
import math
def __init__(self,arith_values):
self = self
self.arith_values = arith_values
def add(self,val1,val2):
# Addition: PLUS <expression1> <expression2>
return val1+val2
def sub(self,val1,val2):
# Subtraction: MINUS <expression1> <expression2>
return val1-val2
def mul(self,val1,val2):
# Multiplication: TIMES <expression1> <expression2>
return val1*val2
def div(self,val1,val2):
# Division: DIVBY <expression1> <expression2>
return val1/val2
def mod(self,val1,val2):
# Modulo: MODU <expression1> <expression2>
return val1%val2
class AdvancedArithmetic(ArithmeticOperations):
def __init__(self):
self = self
def exp(self,expr,expo):
# Exponentiation: RAISE <expression> <exponent>
return expr**expo
def nthRoot(self,N,expr):
# Nth Root of a No. : ROOT <N> <expression>
return expr
def avg(self,values):
# Average: MEAN <expr1> <expr2> <expr3> … <exprn>
# This is the only operation that accepts an unlimited number of parameters.
return values
def distance(self,pt1,pt2):
# Distance between two points: DIST <expr1> <expr2> AND <expr3> <expr4>
# # The 2 points are separated by ‘AND’
# # The coordinates of the first point are <expression1> and <expression2>
# # The coordinates of the second point are <expression3> and <expression4>
return (pt2[1]-pt1[1])+(pt2[0]-pt1[0])
def readIpolFile():
# read indicated .ipol file
return True
def checkIpolFile():
# verifies if .ipol file is valid
return True
def main():
# TEST FOR INTERPRETER. NOT ACTUAL INPUT METHOD
block_end = False
block_start = False
code_block = []
while block_end == False:
text_input = input('interpol>')
if text_input == "CREATE":
# start reading in cobe block
block_start = True
elif text_input == "RUPTURE":
block_end = True
break
elif block_start == True:
code_block.append(text_input)
# process code block
code_block = InterpolBody(code_block)
code_block.processBlock()
print(code_block.getResult())
main()
# Do not use graphical user interface, databases (eg. MySQL), and other unnecessary libraries in Python.
# Focus on what’s core in this assignment – the interpreter itself.
# Your interface should be command line.
# Implement your interpreter with the following use case in mind:
# a) The user writes his INTERPOL source code using any text editor. Take note that the source code has “.ipol” extension.
# b) From the command prompt, the user runs your interpreter. Your interpreter then asks for the file name of the .ipol code to be executed.
# c) Still in the command prompt, the following outputs are displayed to the user:
# Actual output of the source code
# If there’s an error, the user should be informed of the error and possibly, the source of the error.
# Symbol table
# Lexemes and tokens table
# Submission
# Submit your programming assignment on or before Monday, 25 November 2017 at 11:59:59 pm (GMT+8).
# Your assignment should be in a single Python source code that contains your implementation of the INTERPOL interpreter.
# Filename: (all lowercase letters please) surname.py (if solo) or surname1_surname2.py (if by pair).
# This is the file that I will immediately compile and run to test out your interpreter.
# Please don’t forget to document your code properly by using comments.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module Description:
This module is for converting dataset type.
"""
import numpy as np
import torch
import tensorflow as tf
from ai_dataset.types.keras import KerasData
from ai_dataset.types.torchvision import TorchData
def torch2keras():
pass
def keras2torch(keras_data: KerasData):
"""
Dataset type conversion to TorchData
Torchvision dataset's image(X) shape: [filter][width][height]
label(y) type: integer (e.g. 3)
Keras dataset's image(X) shape: [width][height][filter]
label(y) type: a list with the length of classes
(e.g. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] )
:param keras_data: an instance of KerasData
:return: an instance of TorchData
"""
images = []
labels = []
ext_labels = []
for sample in keras_data.get_dataset():
# np.swapaxes internally convert the type of Tensor to numpy(only for tf.Tensor)
# swap input parameter 0, 2 means the highest dim. goes to the lowest.
# swap input parameter 2, 1, means change height and width dimension.
reshape_image = np.swapaxes(sample[0], 0, 2)
images.append(np.swapaxes(reshape_image, 2, 1))
int_label = tf.where(sample[1] == 1)[0][0]
labels.append(int_label.numpy())
ext_labels.append(sample[2].numpy() if len(sample) > 2 else np.zeros(1))
torch_data = torch.utils.data.TensorDataset(torch.tensor(images),
torch.tensor(labels),
torch.tensor(ext_labels))
return TorchData(type=keras_data.type, is_train=keras_data.is_train, dataset_in=torch_data)
|
from fractions import Fraction
def solution(pegs):
dist = pegs[1]-pegs[0]
if len(pegs) == 2 and dist >= 3:
result=Fraction('2/3')*dist
return [result.numerator,result.denominator]
i=(3*dist)-1
while i >= 3 :
radius = i*Fraction('1/3')
candidate=assign(radius,pegs)
first=candidate[0]
last=candidate[-1]
if first==2*last and last >= 1:
return [candidate[0].numerator,candidate[0].denominator]
i-=1
return([-1,-1])
def assign(radius,pegs):
if len(pegs) == 1:
return [radius]
else:
dist = pegs[1]-pegs[0]
remaindius = dist-radius
if remaindius >= 1:
return([radius]+assign(remaindius,pegs[1:]))
else:
return [-1]
def printDistance(pegs):
i=0
distances=[None]*(len(pegs)-1)
while i < len(pegs)-1:
distances[i]=pegs[i+1]-pegs[i]
i+=1
print('{}\n'.format(distances))
# print solution([4, 30, 50])
# print solution([10,20,30,40])
print('---------------')
print solution([4, 17, 50])
print('---------------')
print solution([4, 33, 50])
print('---------------')
print solution([4, 17, 50, 85])
print('---------------')
print solution([4, 17, 50, 100])
print('---------------')
print solution([5, 17, 50, 100, 128])
print('---------------')
print solution([1, 10])
# print solution([10,26,45,60])
|
word=int('9'*309)
print('{} : {}'.format(len(word),word))
|
import itertools
def bananas(s) -> set:
res = set()
for comb in itertools.combinations(range(len(s)), len(s) - len('banana')):
sep = list(s)
for i in comb:
sep[i] = '-'
med_res = ''.join(sep)
if med_res.replace('-', '') == 'banana':
res.add(med_res)
return res
assert bananas("banann") == set()
assert bananas("banana") == {"banana"}
assert bananas("bbananana") == {"b-an--ana", "-banana--", "-b--anana", "b-a--nana", "-banan--a",
"b-ana--na", "b---anana", "-bana--na", "-ba--nana", "b-anan--a",
"-ban--ana", "b-anana--"}
assert bananas("bananaaa") == {"banan-a-", "banana--", "banan--a"}
assert bananas("bananana") == {"ban--ana", "ba--nana", "bana--na", "b--anana", "banana--", "banan--a"}
|
# For directed graph nodes with edges with integer weights
class Node:
def __init__(self, id, name):
self.id = id
self.name = name
self.outgoingEdges = {}
return
def insertNeighbor(self, neighborNodeID, weight):
self.outgoingEdges[neighborNodeID] = weight
return
def getNeighborWeight(self, neighborNodeID):
if neighborNodeID in self.outgoingEdges.keys():
return self.outgoingEdges[neighborNodeID]
else:
return -1
|
# 해당수가 소수인지 찾기
def find(n):
for i in range(2,n):
if(n%i==0):
return
print(n)
if __name__ == '__main__':
n = int(input())
for i in range(2,n+1):
find(i)
|
from urllib import urlencode
import urllib2
import numpy
def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Symbol format is 'symbol'
Date format is 'YYYYMMDD'
By VC Analytics on 09/27/2014
"""
params = urlencode({
's': symbol,
'a': int(start_date[4:6]) - 1,
'b': int(start_date[6:8]),
'c': int(start_date[0:4]),
'd': int(end_date[4:6]) - 1,
'e': int(end_date[6:8]),
'f': int(end_date[0:4]),
'g': 'd',
'ignore': '.csv',
})
url = 'http://ichart.yahoo.com/table.csv?%s' % params
req = urllib2.Request(url)
resp = urllib2.urlopen(req)
content = str(resp.read().decode('utf-8').strip())
daily_data = content.splitlines()
t = len(daily_data)
data = daily_data[1].split(',')
for i in range(2,t):
datatemp = daily_data[i].split(',')
data = numpy.c_[data,datatemp]
datetemp = data[0]
opentemp = data[1]
hightemp = data[2]
lowtemp = data[3]
closetemp = data[4]
voltemp = data[5]
adjclosetemp = data[6]
datetemp = datetemp[::-1]
opentemp = opentemp[::-1]
hightemp = hightemp[::-1]
lowtemp = lowtemp[::-1]
closetemp = closetemp[::-1]
voltemp = voltemp[::-1]
adjclosetemp = adjclosetemp[::-1]
date = datetemp
open = opentemp
high = hightemp
low = lowtemp
close = closetemp
vol = voltemp
adjclose = adjclosetemp
return date, open, high, low, close, vol, adjclose
|
def three_sum(nums):
"""Generate all tuples of three numbers in the input array which sum to 0.
The numbers must be at distinct indices in the array. Duplicate tuples are not allowed.
:param nums: an array of integers
:type nums: List[int]
:return: a list of tuples satisfying sum(t) == 0
:rtype: List[Tuple[int, int, int]]
"""
nums.sort()
solutions = []
for i, num in enumerate(nums[:-1]):
target = 0 - num
low, high = i + 1, len(nums) - 1
while low < high:
s = nums[low] + nums[high]
if s == target:
solutions.append((num, nums[low], nums[high]))
low += 1
high -= 1
while low < high and nums[low] == nums[low - 1]:
low += 1
while low < high and nums[high] == nums[high + 1]:
high -= 1
elif s < target:
low += 1
else:
high -= 1
return solutions
if __name__ == '__main__':
print(three_sum([-1, 0, 1, 2, -1, -4]))
print(three_sum([0, 0, 0, 0]))
print(three_sum([-1, 0, 1, 0]))
|
# Задача №201. Числа Фибоначи
# https://informatics.mccme.ru/mod/statements/view.php?id=649#1
class FibonacciNumbers:
def __init__(self):
self.fibonacci_numbers = [None] * 45
def set_initial_states(self):
self.fibonacci_numbers[0] = self.fibonacci_numbers[1] = 1
def get_fibonacci_number(self, num):
for i in range(2, num):
self.fibonacci_numbers[i] = self.fibonacci_numbers[i - 1] + self.fibonacci_numbers[i - 2]
return self.fibonacci_numbers[num - 1]
if __name__ == '__main__':
number = int(input())
fibonacci = FibonacciNumbers()
fibonacci.set_initial_states()
print(fibonacci.get_fibonacci_number(number))
|
def prime_definition(number):
answer = "prime"
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
answer = "composite"
break
return answer
num = int(input())
result = prime_definition(num)
print(result)
|
from pprint import pprint
def create_list_members(count_members: int):
list_results_members = []
for i in range(count_members):
result_each_member = [int(i) for i in input().split()]
list_results_members.append(result_each_member)
return list_results_members
def bubble_sort(nums: list, count_nums: int):
swapped = True
while swapped:
swapped = False
for i in range(1, count_nums):
if nums[i - 1][1] < nums[i][1]:
nums[i - 1], nums[i] = nums[i], nums[i - 1]
swapped = True
if nums[i - 1][1] == nums[i][1] and nums[i - 1][0] > nums[i][0]:
nums[i - 1], nums[i] = nums[i], nums[i - 1]
swapped = True
return nums
count_participants = int(input())
list_results = bubble_sort(create_list_members(count_participants), count_participants)
for j in range(count_participants):
for elem in list_results[j]:
print(elem, end=' ')
print()
|
# Задача №1170. Построение кучи просеиванием вниз
# https://informatics.mccme.ru/mod/statements/view3.php?id=1234&chapterid=1170#1
class BuildHeap:
def __init__(self, size_heap, list_elements):
self.heap_elements = list_elements
self.size_heap = size_heap
def presence_left_child(self, i):
"""
the function of determining whether this node has at least one child (left)
:param i: index of current node
:return: 1. True if the left child is
2. False if the left child is not
"""
return 2 * i + 1 < self.size_heap
def presence_right_child(self, right_child):
"""
function for determining whether a node has a right child in a heap
:param right_child: formal legal child index
:return: 1. True if the right child is
2. False if the right child is not
"""
return right_child < self.size_heap
def sift_down(self, position):
while self.presence_left_child(position):
left_child = 2 * position + 1
right_child = 2 * position + 2
child_index = left_child
if self.presence_right_child(right_child) and self.heap_elements[right_child] > self.heap_elements[left_child]:
child_index = right_child
if self.heap_elements[position] >= self.heap_elements[child_index]:
break
self.heap_elements[position], self.heap_elements[child_index] = \
self.heap_elements[child_index], self.heap_elements[position]
position = child_index
return position + 1
def main_program(self):
for i in range(self.size_heap // 2, -1, -1):
self.sift_down(i)
if __name__ == '__main__':
count_elements = int(input())
elements = [int(i) for i in input().split()]
build_heap = BuildHeap(count_elements, elements)
build_heap.main_program()
for i in range(count_elements):
print(build_heap.heap_elements[i], end=' ')
|
number_eng_words = int(input())
dict_latin_eng = dict()
for i in range(number_eng_words):
eng_word, all_translations_latin_words = input().split(' - ')
latin_translations = all_translations_latin_words.split(', ')
for latin_word in latin_translations:
if latin_word not in dict_latin_eng:
dict_latin_eng[latin_word] = eng_word
else:
dict_latin_eng[latin_word] += ', ' + eng_word
print(len(dict_latin_eng))
# print(eng_word)
# print(latin_translations)
for key_latin, value_eng in sorted(dict_latin_eng.items()):
print(key_latin + ' - ' + value_eng)
|
number_countries = int(input())
dict_countries = dict()
for i in range(number_countries):
country_cities = input().split()
for city in country_cities[1:]:
dict_countries[city] = country_cities[0]
numb_find_cities = int(input())
for k in range(numb_find_cities):
find_city = input()
if find_city in dict_countries:
print(dict_countries[find_city])
|
numbers_sentences = int(input())
set_words = set()
list_sentences = []
for i in range(numbers_sentences):
sentence = input().split()
list_sentences.append(sentence)
for sentence in list_sentences:
for word in sentence:
set_words.add(word)
print(len(set_words))
|
hours = int(input())
minutes = int(input())
seconds = int(input())
print(30 * hours + 0.5 * minutes + seconds / 120)
|
number = int(input())
digits_with_one_circle = "069"
digits_with_two_circles = "8"
count_circles = 0
try:
for symbol in str(number):
if symbol in digits_with_one_circle:
count_circles += 1
if symbol in digits_with_two_circles:
count_circles += 2
except str(number) == '':
count_circles = 0
print(count_circles)
|
# Задача №764. Сбалансированность
# https://informatics.mccme.ru/mod/statements/view3.php?id=599&chapterid=764#1
class Node:
def __init__(self, value: int):
self.value: int = value
self.left: Node = None
self.right: Node = None
self.node_height = 0
self.is_balanced: bool = True
class BinaryTree:
def __init__(self):
self.root: Node = None
def add_element(self, x: int):
if self.root is None:
self.root: Node = Node(x)
return
current_node: Node = self.root
parent_current_node: Node = None
while current_node is not None:
parent_current_node = current_node
if x > current_node.value:
current_node = current_node.right
elif x < current_node.value:
current_node = current_node.left
else:
break
if x > parent_current_node.value:
parent_current_node.right = Node(x)
elif x < parent_current_node.value:
parent_current_node.left = Node(x)
def visit(self, node: Node):
height = 1
if node.left is not None:
self.visit(node.left)
height = node.left.height + 1
if node.right is not None:
self.visit(node.right)
height = max(height, node.right.height + 1)
node.height = height
def check_is_balanced(self, node: Node):
left_height = 0
right_height = 0
left_balanced = True
right_balanced = True
if node.left is not None:
left_height = node.left.height
self.check_is_balanced(node.left)
left_balanced = node.left.is_balanced
if node.right is not None:
right_height = node.right.height
self.check_is_balanced(node.right)
right_balanced = node.right.is_balanced
node.is_balanced = right_balanced and left_balanced and abs(right_height - left_height) <= 1
return node.is_balanced
def summary(self):
self.visit(self.root)
result = self.check_is_balanced(self.root)
if result:
return 'YES'
else:
return 'NO'
if __name__ == '__main__':
elements = [int(i) for i in input().split()]
binary_tree = BinaryTree()
k = 0
while elements[k] != 0:
binary_tree.add_element(elements[k])
k += 1
print(binary_tree.summary())
|
number_pairs_words = int(input())
dict_synonyms = dict()
for i in range(number_pairs_words):
pair_words_list = list(input().split())
dict_synonyms[pair_words_list[0]] = pair_words_list[1]
word_synonym_for_finding = input("Введите слово для нахождения:")
for key, value in dict_synonyms.items():
if key == word_synonym_for_finding:
print(value)
elif value == word_synonym_for_finding:
print(key)
else:
continue
|
N = int(input())
sum_of_cubes = 0
for i in range(1, N + 1):
sum_of_cubes += (i ** 3)
print(sum_of_cubes)
|
def insertion_sort(list_nums: list, count_nums: int):
for i in range(1, count_nums):
x = list_nums[i]
index_prev_item_from_x = i - 1
while x < list_nums[index_prev_item_from_x] and index_prev_item_from_x >= 0:
list_nums[index_prev_item_from_x + 1] = list_nums[index_prev_item_from_x]
index_prev_item_from_x -= 1
list_nums[index_prev_item_from_x + 1] = x
return list_nums
len_list = int(input())
list_numbers = [int(i) for i in input().split()]
for elem in insertion_sort(list_numbers, len_list):
print(elem, end=' ')
|
sentence = input()
while sentence.find(' ') != -1:
sentence = sentence.replace(' ', ' ')
print(sentence)
|
def leftside_binary_search(list_num: list, key: int) -> tuple:
"""Реализация левостороннего двоичного поиска"""
left_border = -1
right_border = len(list_num)
while right_border - left_border > 1:
mid = (left_border + right_border) // 2
if list_num[mid] < key:
left_border = mid
else:
right_border = mid
if list_num[left_border] != key and list_num[right_border] != key:
return 'NO'
else:
return 'YES'
|
a = int(input())
b = int(input())
c = int(input())
minimal = a
if b < minimal:
minimal = b
if c < minimal:
minimal = c
print(minimal)
|
num_states = int(input())
dict_votes = dict()
for i in range(num_states):
name_president, num_votes_in_state = input().split()
if name_president not in dict_votes:
dict_votes[name_president] = int(num_votes_in_state)
else:
dict_votes[name_president] += int(num_votes_in_state)
for key, value in sorted(dict_votes.items()):
print(key, value)
|
def bubble_sort(nums: list, count_nums: int):
swapped = True
num_exchanges = 0
while swapped:
swapped = False
for i in range(1, count_nums):
if nums[i - 1] > nums[i]:
nums[i - 1], nums[i] = nums[i], nums[i - 1]
num_exchanges += 1
swapped = True
return nums, num_exchanges
count_numbers = int(input())
list_numbers = [int(i) for i in input().split()]
print(bubble_sort(list_numbers, count_numbers)[1])
|
count_numbers = int(input())
list_numbers = [int(i) for i in input().split()]
inserted_number, index_inserted_number = map(int, input().split())
def insert_element(nums: list, ins_num: int, index_ins_num):
index_ins_num -= 1
nums = nums[:index_ins_num] + [ins_num] + nums[index_ins_num:]
return nums
for elem in insert_element(list_numbers, inserted_number, index_inserted_number):
print(elem, end=' ')
|
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if abs(x2 - x1) == 2 and abs(y2 - y1) == 1 or abs(x2 - x1) == 1 and (abs(y2 - y1) == 2):
print('YES')
else:
print('NO')
|
import csv
import sys
from livros import Livro
def main():
opcao = "0";
#Cria o menu e sai apenas quando selecionar a opção 6
while opcao != "6":
print()
opcao = input("""Selecione uma das opções abaixo:
1 - Cadastrar livro
2 - Listar todos os livros em ordem alfabética
3 - Buscar livros pelo título
4 - Buscar livros pelo autor
5 - Listar todos os livros não lidos
6 - [x] Fechar """)
if opcao == "1":
titulo = input("Digite o título do livro: ")
autor = input("Digite o autor do livro: ")
editora = input("Digite a editora do livro: ")
ano_publicacao = input("Digite o ano de publicação do livro: ")
ano_aquisicao = input("Digite o ano de aquisição do livro: ")
lido = input("Digite 1 se o livro foi lido e 0 caso contrário: ")
data_lido = ''
if(lido == '1'):
data_lido = input("Digite a data de leitura do livro: ")
livro = Livro(titulo, autor, editora, ano_publicacao, ano_aquisicao, lido, data_lido);
Livro.cadastrar(livro)
elif opcao == "2":
Livro.listar()
elif opcao=="3":
titulo = input("Digite o título a pesquisar: ")
Livro.buscarPeloTitulo(titulo)
elif opcao=="4":
autor = input("Digite o autor a pesquisar: ")
Livro.buscarPeloAutor(autor)
elif opcao=="5":
Livro.listarNaoLidos()
main()
|
def curdatfun():
from datetime import date
today = date.today()
print("Today's date:", str(today))
li=str(today).split('-')#1.0.1907.0
dyearcur=int(li[0][2:4])
dmonthcur=int(li[1])
return(dyearcur,3)
def mainfuncForNext():
n=input('enter:')
try:
li=n.split('.')
if len(li[2])!=4:
print('u r input is wrong')
exit()
yrget=int(li[2][0:2])
mnthget=int(li[2][2:4])
num=int(li[3])
print(yrget,mnthget,num)
d=curdatfun()
d=list(d)
if d[0]==yrget and d[1]==mnthget:
num+=1
# print(num)
else:
num=0
d[0]=str(d[0])
d[1]=str(d[1])
num=str(num)
if len(d[1])==1:
d[1]='0'+d[1]
print('next data=','1.0.'+d[0]+d[1]+'.'+num)
except ValueError:
print('u r input is wrong')
except IndexError:
print('what u have entered????')
mainfuncForNext()
|
x1=int(input("Введите число от 1 до 8"))
y1=int(input("Введите число от 1 до 8"))
x2=int(input("Введите число от 1 до 8"))
y2=int(input("Введите число от 1 до 8"))
if (x1+y1)%2==0 and (x2+y2)%2==0:
print("yes")
else:
print("NO")
|
import random
import os
class Food():
def __init__(self, meat=10, water=5, fish=8):
self.meat = meat
self.water = water
self.fish = fish
class Critter():
def __init__(self, name, hunger=100, boredom=100, sleep=100):
self.name = name
self.hunger = hunger
self.boredom = boredom
self.sleep = sleep
def __str__(self):
print(self.hunger, '%')
print(self.boredom, '%')
print(self.sleep, '%')
def __pass_hunger(self):
self.hunger -= random.randint(1, 11)
def __pass_boredom(self):
self.boredom -= random.randint(1, 11)
def __pass_sleep(self):
self.sleep -= random.randint(1, 11)
def mood(self):
happy = self.hunger + self.boredom
res = ''
if happy > 200:
res = 'i am crazy happiness'
elif 150 < happy <= 200:
res = 'i am so happy'
elif 100 < happy <= 150:
res = 'i am ok'
elif 50 < happy <= 100:
res = 'i am bad'
elif 0 < happy <= 50:
res = 'i am mad'
elif happy < 0:
res = 'I AM DEAD!!!'
return res
def talk(self):
print('I am', self.name, 'and', self.mood())
self.__pass_boredom()
self.__pass_hunger()
self. __pass_sleep()
def eat(self, food):
print('Om-nom-nom...')
self.hunger += food
self.__pass_boredom()
self.__pass_sleep()
def play(self, fun=random.randint(10, 21)):
print('Wheeeeeee!')
self.boredom += fun
self.__pass_hunger()
self.__pass_sleep()
def m_sleep(self, sleep=random.randint(10, 21)):
print('Zzzzzz')
self.sleep += sleep
self.__pass_hunger()
self.__pass_boredom()
def crit_helth(self):
if self.hunger < 0 or self.boredom < 0:
exit()
def main():
name = input('What name of your critter? \n')
crit = Critter(name)
food = Food()
while True:
print("""\r
0 - exit game;
1 - talk with {};
2 - eat to {};
3 - play to {};
4 - sleep to {};
""".format(name, name, name, name))
choice = input('Choice game mode: \n')
if choice == '0':
break
elif choice == '1':
os.system('cls')
crit.talk()
crit.crit_helth()
elif choice == '2':
os.system('cls')
print("""
1 - give meat to {};
2 - give water to {}
3 - give fish to {}
""".format(name, name, name))
choiceFood = input('Choice food mode: \n')
if choiceFood == '1':
os.system('cls')
crit.eat(food.meat)
crit.crit_helth()
elif choiceFood == '2':
os.system('cls')
crit.eat(food.water)
crit.crit_helth()
elif choiceFood == '3':
os.system('cls')
crit.eat(food.fish)
crit.crit_helth()
elif choice == '3':
os.system('cls')
crit.play()
crit.crit_helth()
elif choice == '4':
os.system('cls')
crit.m_sleep()
crit.crit_helth()
elif choice == '5':
os.system('cls')
crit.__str__()
else:
print('Wrong choice')
if __name__ == '__main__':
print('Welcome to game "Critter"')
main()
|
from fractions import Fraction
#returns the expansion of the n'th iteration as a Fraction
def iterationApproximation(iteration):
numerator = 1
denominator = 2
for i in range(1,iteration):
numerator += (denominator*2)
#swapping the variables (division by a fraction)
tempNumerator = numerator
numerator = denominator
denominator = tempNumerator
numerator += denominator
return Fraction(numerator,denominator)
#counts the number of digits in a number
def numOfDigits(num):
numDigits = 0
while (num != 0):
numDigits += 1
num = (int)(num/10)
return numDigits
numFractionsMoreNumeratorDigits = 0
for i in range (1, 1001):
approxFraction = iterationApproximation(i)
if (numOfDigits(approxFraction.numerator) > numOfDigits(approxFraction.denominator)):
numFractionsMoreNumeratorDigits += 1
print numFractionsMoreNumeratorDigits
|
print("")
print("1.Listes")
print("1.1 Modifier une liste")
print("")
print("1.1.1 Supprimez les trois derniers éléments un par un, dans un premier temps")
print("")
annee = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre',10,11,12]
x=0
while x <3:
annee.remove(len(annee))
x+=1
print(annee)
print("")
print("1.1.2 Puis rajoutez les mois 'Octobre', 'Novembre', 'Décembre' à la fin")
print("")
annee.append("Octobre")
annee.append("Novembre")
annee.append("Décembre")
print(annee)
print("")
print("1.1.3 Supprimez les trois derniers éléments un par un, dans un premier temps")
print("")
annee = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre',10,11,12]
x=0
while x <3:
annee.remove(len(annee))
x+=1
print(annee)
print("")
a="Octobre"
b= "Novembre"
c= "Décembre"
print("Remplacez les 3 derniers éléments par le nom du mois correspondant")
print("")
annee.extend([a,b,c])
print(annee)
print("")
print("1.1.4 Pour aller plus loin : la liste 'en compréhension'")
print("")
x = [1, 2, 3, 4, 3, 5, 3, 1, 3, 2]
resultat = [y+1 for y in x]
print(resultat)
print("")
print("2.Tuples")
print("2.1 Accès aux éléments d'un tuple")
print("")
moisDeLannee = ('Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre')
quatriemeElement = moisDeLannee [4]
print(quatriemeElement)
print("")
print("2.2 Vérifier la présence d’un élément dans un tuple")
print("")
trouver = 'Mars' in moisDeLannee
print("Mars est-il dans la liste ?")
print(trouver)
print("")
print("3. Dictionnaires")
print("3.1 Ajoutez des éléments au dictionnaire")
print("")
age = {"Pierre" : 35 , "Paul" : 32 , "Jacques" : 27 , "Andre" : 23}
age2 = {"David" : 22 , "Veronique": 21 , "Sylvie" : 30,"Damien" :37}
age.update(age2)
print(age)
print("")
print("3.3 Accéder à une valeur à partir d’une clé")
print("")
print("L'age de Sylvie est :")
print(age["Sylvie"])
print("")
print("3.3 Accéder à une valeur à partir d’une clé")
print("")
if 'Jean' in age:
print("Jean est dnas la liste")
else:
print("Jean n'est pas dans la liste")
print("")
print("3.4 Gérer des valeurs multiples")
print("")
club = {
"Pierre Durand" :(1986,1.72,70),
"Victor Dupont" :(1987,1.89,57),
"Paul Dupuis" :(1989,1.60,92),
"Jean rieux" :(1985,1.88,77)
}
print("")
print("3.5 Afficher les données d’un sportif")
print("")
prenom = input("Entrez le prénom de votre choix :")
nomSportif = prenom
dateNaissSportif = club[prenom][0]
poidsSportif = club[prenom][2]
tailleSportif = club[prenom][1]
phrase = 'Le sportif nommé est %s, il est né en %s , sa taille est de %sm et son poids est de %s Kg'
print(phrase % (nomSportif,dateNaissSportif,tailleSportif,poidsSportif))
print("")
print("4.1 Club sportif : variante")
print("")
|
def divisible_by(num, list_):
is_divisible = False
for n in list_:
if num % n == 0:
is_divisible = True
break
return is_divisible
divisibles = []
for number in range(1000):
if divisible_by(number, [3, 5]):
divisibles.append(number)
print sum(divisibles)
|
# coding=utf-8
# python3
def func():
print("Hello World")
class A:
name = "A"
def __init__(self):
self.id = 0
self.username = "beijing"
if __name__ == '__main__':
print(A.name)
print(A().username)
|
import re
import sys
class tracksInfo:
"""
Simply used to extracts the information of video which is generated by mkvmerge.exe
Constructor needs path to input txt file which contains information of the video.
"""
def __init__(self, infoFile=''):
try:
if infoFile == '':
raise Exception("- Error: Input file is not given to tracksInfo class.")
except Exception as e:
print(e)
exit(1)
self.fileName = ''
self.TrackIDs = {}
self.Videos = {}
self.Audios = {}
self.Subtitles = {}
self.Languages = {}
self.TrackNames = {}
self.allInfoList = []
# enums
self.TYPE_FILENAME = 0
self.TYPE_TRACKINFO = 1
# extract information from text file
self.getInfo(infoFile)
def getInfo(self, infoFile):
file = open(infoFile, 'r')
for line in file:
dType = self.getdType(line)
key = ''
encType = ''
if dType == self.TYPE_FILENAME:
self.fileName = line[line.find("'")+1:line.find("'", line.find("'")+1)]
key = ''
elif dType == self.TYPE_TRACKINFO:
key = self.getID(line)
self.TrackIDs[key] = self.getType(line)
encType = self.getEncType(line)
self.Languages[key] = self.deEscapeChars(self.getLanguage(line))
self.TrackNames[key] = self.deEscapeChars(self.getTrackName(line))
if key != '':
if self.TrackIDs[key] == 'video':
self.Videos[key] = encType
elif self.TrackIDs[key] == 'audio':
self.Audios[key] = encType
elif self.TrackIDs[key] == 'subtitles':
self.Subtitles[key] = encType
if self.isInfoEmpty() == True:
print("- Error: Unable to extract any information.")
exit(1)
self.allInfoList = [self.fileName, self.TrackIDs, self.Videos, self.Audios, self.Subtitles, self.Languages, self.TrackNames]
print("Tracks information has been extracted of video file:", self.fileName)
def getdType(self, line):
if line[0:4] == 'File':
return self.TYPE_FILENAME
elif line[0:8] == 'Track ID':
return self.TYPE_TRACKINFO
def getID(self, line):
return line[9:line.find(':')]
def getType(self, line):
return line[line.find(':')+2:line.find('(')-1]
def getEncType(self, line):
return line[line.find('(')+1:line.find(')')]
def getLanguage(self, line):
language = 'und'
languageList = re.compile(r'language:.*?\s').findall(line)
if len(languageList) < 1:
languageList = re.compile(r'language:.*?\]').findall(line)
if len(languageList) > 0:
language = languageList[0]
language = language[language.find(':')+1:len(language)-1]
return language
def getTrackName(self, line):
trackName = ''
tracksList = re.compile(r'track_name:.*?\s').findall(line)
if len(tracksList) < 1:
tracksList = re.compile(r'track_name:.*?\]').findall(line)
if len(tracksList) > 0:
trackName = tracksList[0]
trackName = trackName[trackName.find(':')+1:len(trackName)-1]
return trackName
def isInfoEmpty(self):
if self.fileName == '':
return True
elif self.TrackIDs == {} and self.Videos == {} and self.Audios == {} and self.Subtitles == {} and self.Languages == {} and self.TrackNames == {}:
return True
else:
return False
def getAllInfoList(self):
return self.allInfoList
def deEscapeChars(self, text):
return text.replace(r'\s', ' ').replace(r'\2', '"').replace(r'\c', ':').replace(r'\h', '#').replace(r'\b', '[').replace(r'\B', ']').replace('\\\\', '\\')
if __name__ == '__main__':
if len(sys.argv) > 1:
print(tracksInfo(sys.argv[1].replace('\\\\', '\\')).getAllInfoList())
|
#Converting miles into kilometers
miles = float(input("Enter miles:"))
kilometers = miles * 1.60934
print("Number of kilometers ={0:.3f}".format(kilometers))
|
# Longest Collatz sequense (14)
# 837799
def longest_Collatz_sequence(n):
longest_sequence = 0
for i in range(n+1, 2, -1):
sequence = 0
m = i
while m != 1:
if m % 2 == 0:
m = m / 2
sequence += 1
elif m % 2 == 1:
m = (m*3) + 1
sequence += 1
if sequence > longest_sequence:
longest_sequence = sequence
longest_sequence_number = i
print(str(i), str(longest_sequence))
return longest_sequence, longest_sequence_number
print(str(longest_Collatz_sequence(1000000)))
'''
odd 1,000,000 --> 333,333
even 1,000,000 --> 500,000 -1
'''
|
# Prime permutations (49)
# 125925919521
import itertools
def sieve(limit):
numbers = list(range(2, limit+1))
primes = []
for i in numbers:
for m in numbers[numbers.index(i)+1:]:
if m % i == 0:
numbers.remove(m)
return numbers
prime_list = sieve(10000)
for i in prime_list[prime_list.index(997):]:
permutations = 0
primes = []
for perm in itertools.permutations(str(i)):
if int(''.join(perm)) in prime_list:
permutations += 1
primes.append(''.join(perm))
if permutations == 3:
print(''.join(sorted(primes)))
break
|
# Even Fibonacci numbers (2)
# 4613732
def fib(n):
fib_list = []
a, b = 0, 1
while b < n:
a, b = b, a+b
if b % 2 == 0:
fib_list.append(b)
return(fib_list)
print(sum(fib(4*10**6)))
|
my_str = input('Enter several words: ')
line = my_str.split()
for n, word in enumerate(line, start=1):
print(n, word[:10])
|
# Task 1
def my_func(var_1, var_2):
try:
var_1, var_2 = float(var_1), float(var_2)
result = round((var_1 / var_2), 2)
except ValueError:
return 'You had to enter numbers'
except ZeroDivisionError:
return 'Деление на ноль невозможно'
return result
divided_var = my_func(input('Enter number: '), input('Enter another number: '))
print(divided_var)
|
# # Task 1
a = 100
b = 200
print(a, b, sep=', ')
name = input('Введите ваше имя: ')
age = int(input('Введите ваш возраст: '))
print(name, age, sep=', ')
# # Task 2
time = int(input('Введите время в секундах: '))
hours = time // 3600
hours_left = time % 3600
minutes = hours_left // 60
minutes_left = hours_left % 60
seconds = minutes_left % 60
print(f"{hours:02}:{minutes:02}:{seconds:02}")
# Task 3
num = input('Введите число: ')
print(f"{num} + {num + num} + {num + num + num} = {int(num) + int(num + num) + int(num + num + num)}")
# Task 4
n = int(input('Введите целое положительное число: '))
max_n = 0
while n > 0:
last_num = n % 10
if last_num > max_n:
max_n = last_num
if max_n == 9:
break
n = n // 10
print(f'Наибольшая цифра в числе: ', max_n)
# Task 5
rev = int(input('Введите значение выручки: '))
costs = int(input('Введите значение издержек: '))
profit = rev - costs
ros = rev / costs
if rev > costs:
print('Ваша компания прибыльна!')
print('Рентабельность выручки: ', ("%.2f" % ((ros - 1) * 100)), '%')
employees = int(input('Введите численность сотрудников'))
print('Прибыль на сотрудника составила: ', ("%.2f" % (profit / employees)))
else:
print('Ваша компания работает в убыток!')
# Task 6
a = int(input('Введите результат пробежки в первый день: '))
b = int(input('Введите желаемый результат пробежки: '))
n = 1
while a < b:
a = a * 1.1
n += 1
print('Спортсмен достиг результата не менее - ', b, 'километров на ', n, 'день')
|
my_list = list(input('Введите текст: '))
for i in range(1, len(my_list), 2):
my_list[i - 1], my_list[i] = my_list[i], my_list[i - 1]
print(my_list)
|
#date 2021.10.23
#author ltw
#dec 字典的遍历
myinfo={
'first name':'li',
'last name':'tianwang',
'age' :18,
'city':'beijing',
}
for key,values in myinfo.items(): #注意使用items转换为键值对列表
print(f'The people {key} is {values}')
print('\n')
revers={
'china':'changjiang',
'us':'mixixibi',
'aiji':'nile',
'egypt':'nile',
}
#遍历键
for country in revers.keys():
if country=='china':
print(f'{country} has {revers[country]}')
else:
print(country)
print('\n')
#遍历值,并去重(利用集合的互异性)
for rever in revers.values():
print(rever)
print('\n')
for rever in set(revers.values()):
print(rever)
|
''' -----------------------------------------------------------------
UNIVERSIDADE PAULISTA - ENG COMPUTAÇÃO - BACELAR
Nome: Mauricio Silva Amaral
RA : D92EJG-0
Turma : CP6P01
Data: 10/10/2021
Lista: 06 - 08
Enunciado: 08 – Escreva um programa que lê duas notas de vários
alunos e armazena tais notas em um dicionário, onde a chave é o
nome do aluno. A entrada de dados deve terminar quando for lida
uma string vazia como nome.
Escreva uma função que retorna a média do aluno, dado seu nome.
----------------------------------------------------------------- '''
def pesquisarAluno(dicionario, procurar):
for key, valor in dicionario.items():
if procurar in key:
notaM1 = int(valor[0])
notaM2 = int(valor[1])
media = notaM1 + notaM2 / 2
print(f'Aluno : {key} \n'
f'Nota 1 : {valor[0]}\n'
f'Nota 2 : {valor[1]}\n'
f'Media : {media}\n\n')
else:
print('aluno não cadastrado\n')
notas = {}
sair = ' '
while True:
opcao = input("Digite uma das opções \n"
"1 - Cadastro de aluno / nota \n"
"2 - Media do aluno \n"
"S - Sair"
"Opção : ")
if opcao == '1':
print('\nCadastro e aluno /nota')
nome = input('Digite o nome do aluno : ')
nota_1 = input('Digite a primeira nota 1 : ')
nota_2 = input('Digite a segunda nota 2 : ')
notas.update({nome: [nota_1, nota_2]})
print(f'lista cadastrada\n {notas}')
sair = input('\nDeseja sair , precione "S". ').lower()
elif opcao == '2':
procura = input('\nDigite o nome do aluno na lista : ')
pesquisarAluno(notas, procura)
elif sair == 's' or opcao == 's':
break
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""prefix expression
CHALLENGE DESCRIPTION:
You are given a prefix expression. Write a program which evaluates it.
INPUT SAMPLE:
Your program should accept a file as its first argument. The file contains one prefix expression per line.
For example:
* + 2 3 4
Your program should read this file and insert it into any data structure you like. Traverse this data structure and evaluate the prefix expression. Each token is delimited by a whitespace. You may assume that sum ‘+’, multiplication ‘*’ and division ‘/’ are the only valid operators appearing in the test data.
OUTPUT SAMPLE:
Print to stdout the output of the prefix expression, one per line.
For example:
20
CONSTRAINTS:
The evaluation result will always be an integer ≥ 0.
The number of the test cases is ≤ 40.
"""
import sys
import re
class stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def empty(self):
return self.size() == 0
def calc_result(calc_exp):
if calc_exp[-1] == '*':
return str(float(calc_exp[-2]) * float(calc_exp[-3]))
elif calc_exp[-1] == '+':
return str(float(calc_exp[-2]) + float(calc_exp[-3]))
elif calc_exp[-1] == '/':
return str(float(calc_exp[-2]) / float(calc_exp[-3]))
try:
test_case = open(sys.argv[1], 'r')
except:
print "No input file specified"
sys.exit()
for test in test_case:
stack_l = stack()
stack_r = stack()
for i in test.strip().split(' '):
stack_l.push(i)
while stack_l.size() > 0:
element = stack_l.pop()
stack_r.push(element)
if element.isdigit():
pass
else:
calc_exp = stack_r.items[-3:]
tmp_result = calc_result(calc_exp)
stack_r.pop()
stack_r.pop()
stack_r.pop()
stack_r.push(tmp_result)
print int(float(stack_r.pop()))
test_case.close()
|
'''
Sequential Search
**Computational complexity**:
- best case = 1
- Worst Case = n
- Average Case = n/2
**Advantages**:
- Simple
- small data
**Disadvantages**:
- high computational complex
- big data is slow
- inefficient
'''
def busca_sequencial_for(lista, valor_procurado):
for i in range(len(lista)):
if lista[i] == valor_procurado:
return True;
return False
def busca_sequencial_while(lista, valor_procurado):
indice = 0
found = False
while indice < len(lista):
if lista[indice] == valor_procurado:
found == True
else:
indice += 1
return found
# test
lista = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(busca_sequencial_for(lista, 13))
print(busca_sequencial_while(lista, 3))
# love python
print("\nlove python")
print(42 in lista)
|
# A code snippet to demostrate the use of
# pandas python library
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
# reading data from a file
data = pd.read_csv('data/food.csv')
print(data.head())
print('The size of the data set is' + str(data.shape))
print()
# Getting the names of all the columns
column_names = data.columns[:]
print('The name of all the columns are - ')
print(column_names)
print()
# Finding unique values in a column
values = data['Do you celebrate Thanksgiving?'].unique
print(values)
print()
# Getting the count of all the values in a column
print(data['What is your gender?'].value_counts(dropna=False))
print()
# a function to change the value of the gender field
def gender_code(gender_string):
if isinstance(gender_string, float) and math.isnan(gender_string):
return gender_string
return int(gender_string == 'Female')
# Transforming the values of a column in the data set
# The apply method transforms the Series
data['gender'] = data["What is your gender?"].apply(gender_code)
print(data['gender'].value_counts(dropna=False))
print()
# applying a function to a column using a lambda expression
print(data.apply(lambda x: x.dtype).tail(25))
print()
# analyzing a column
print(data['How much total combined money did all members of your HOUSEHOLD earn last year?'].unique)
print(data['How much total combined money did all members of your HOUSEHOLD earn last year?'].value_counts(dropna=False))
print()
# a function to transform data in a column
def clean_income(value):
if value == 'Prefer not to answer':
return np.nan
elif value == '$200,000 and up':
return np.nan
elif isinstance(value, float) and math.isnan(value):
return value
else:
value = value.replace(',', '').replace('$', '')
low_value, high_value = value.split(' to ')
return (int(low_value) + int(high_value)) / 2
# transform a column in the data set
data['income'] = data['How much total combined money did all members of your HOUSEHOLD earn last year?'].apply(clean_income)
print(data['income'].value_counts(dropna=False))
print()
# analyzing the data
print(data['What type of cranberry saucedo you typically have?'].value_counts(dropna=False))
print()
# GROUPING A DATA SET
# creating a data set based in a filter
canned = data[data['What type of cranberry saucedo you typically have?'] == 'Canned']
homemade = data[data['What type of cranberry saucedo you typically have?'] == 'Homemade']
print(canned.head(20))
print()
print(homemade.head(20))
print()
canned_income = canned['income'].mean()
homemade_income = homemade['income'].mean()
print(f'The income for those who eat canned and homemade cranberry sauce is as follows {canned_income, homemade_income}')
print()
# the above method of grouping data by providing a filter is not efficient,
# there is another way to group data in python by making use of the groupby method
grouped_data = data.groupby('What type of cranberry saucedo you typically have?')
# the groupby method returns a DataFrameGroupBy Object
print(grouped_data.head())
print()
# displays all the groups in the geouped data frame
print(grouped_data.groups)
print()
# the size method returns the number of rows in each group present in data group
print(grouped_data.size())
print()
# a simple for loop can be used to iterate through the data present in the DataFrameGroupObject
for name, group in grouped_data:
print(name)
print(group['What type of cranberry saucedo you typically have?'])
print(type(group))
# NOTE: DataFrameGroupBy object contains multiple DataFrames
# Extracting a column from a DataFrameGroupBy Object
print(grouped_data['income'].size())
print()
# AGGREGATING VALUES IN GROUPS
# The data present in the DataFrameGoup Object can be aggregated
print(grouped_data['income'].agg(np.mean))
# NOTE: If nothing is specified, mean will be calculated for all those columns on which arithmetic calculations
# can be performed
# PLOTTING GRAPHS
grouped_data['income'].plot(kind='bar')
plt.show()
# many columns in the data set can be grouped together too
another_grouped_data = data.groupby(['What type of cranberry saucedo you typically have?', 'What is typically the main dish at your Thanksgiving dinner?'])
print(another_grouped_data.groups)
# The grouped data can be aggregated in multiple ways
print(another_grouped_data.agg([np.mean, np.sum, np.std]).head(25))
watermelon_data = data.groupby('How would you describe where you live?')['What is typically the main dish at your Thanksgiving dinner?']
watermelon_data.apply(lambda x:x.value_counts())
|
from Card import Card
import random
class Deck():
def __init__(self,symbols,cards_per_symbol):
self.cards = []
# TODO: nested list comprehension to make it faster
for name,symbol in symbols.items():
for card_number in range(1,cards_per_symbol+1):
self.cards.append(Card(card_number,symbol,name))
def suffle(self):
random.shuffle(self.cards)
def __str__(self):
return str([f"{''.join(str(x.number))}-{''.join(x.name)}" for x in self.cards])
if __name__ == "__main__":
print(Deck())
|
#!/usr/bin/python
from random import randint
def is_even(n): return n % 2 == 0
def square(n): return n**2
def expmod(base, exp, modu):
##your code
if (exp==0):
return 1
elif (is_even(exp)):
expm = expmod(base,exp/2, modu)
return (expm*expm)%modu
else:
return (base*expmod(base,exp-1, modu))%modu
def fermat_test(n):
if n < 3:
if n == 2:
return True
a = 2
else:
a = randint(2, n-1)
return expmod(a,n,n)==a
def is_fermat_prime(n, ntimes):
if (ntimes ==0):
return True
elif (fermat_test(n)):
return is_fermat_prime(n, ntimes-1)
else:
return False
## your code
## This is the test you can use to test your code
def sum_of_fermat_primes(n):
sum = 0
for i in xrange(n+1):
if is_fermat_prime(i, 70):
sum += i
return sum
print sum_of_fermat_primes(10)
print sum_of_fermat_primes(20)
print sum_of_fermat_primes(560)
print sum_of_fermat_primes(570)
|
STARTING_NUMBER_ERROR = "Please enter a 0 or 1!"
def fibonacci(starting_number, sequence_length=10):
if starting_number == 0:
a, b = 0, 1
elif starting_number == 1:
a, b = 1, 1
else:
print(STARTING_NUMBER_ERROR)
return
sequence = str(starting_number)
for i in range(sequence_length - 1):
sequence = sequence + " {}".format(b)
a, b = b, a + b
print(sequence)
#### DO NOT ADJUST THE TEST PARAMETERS BELOW
#### THE CONSOLE OUTPUT SHOULD MATCH THIS:
# Please enter a 0 or 1!
# 0 1 1 2 3
# 1 1 2 3 5
# 1 1 2 3 5 8 13 21 34 55
fibonacci(2, 5)
fibonacci(0, 5)
fibonacci(1, 5)
fibonacci(1)
|
from game.next_card import Dealer_card
class Dealer:
def __init__(self):
"""The class constructor.
Args:
self (Dealer): an instance of Dealer.
"""
# keep_playing is = to True, so that the game can start
self.keep_playing = True
# The user score
self.score = 300
# calls the Dealer_card class.
self.next_card = Dealer_card()
def start_game(self):
"""Starts the game loop to control the sequence of play.
Args:
self (Dealer): an instance of Dealer.
"""
self.init_card = self.next_card.throw_card()
self.current_card = ""
self.final_score = 0
while self.keep_playing:
"""Functions to start the game"""
# Calls the output functions, making the game start
self.output(self.init_card)
#Evaluating if the score is zero or not
if self.score == 0:
#if the score is zero, it is game over and end of the game.
print("=============================================================================")
print("GAME OVER! \nThank you for you time playing this game. \nWe hope you have fun")
print("=============================================================================")
break
else:
#Else we will ask for the user if they wanted to play or not.
play = input("Keep Playing? [y/n]")
if "n" in play:
print("Thank you for playing with us. Have a nice day!")
break
def updates(self, next_card):
"""Updates the important game information for each round of play. In
this case, that means updating the score.
Args:
self (Dealer): an instance of Dealer.
next_card: variable that store the next card for the game
Return:
final_score: return updated scores
"""
# calls the get_points function from Dealer_card class, and store the points into a value called score
points = self.next_card.get_points(next_card, self.current_card)
final_score = self.score + points
return final_score
def output(self, init_card):
"""Outputs the important game information for each round of play. In
this case, that means the card that were showed and the score.
Args:
self (Dealer): an instance of Dealer.
init_card: the inital card
"""
#storing card from the Dealer_card class to store as a next_card
next_card = self.next_card.throw_card()
#Storing initial card as the current card for the comparison purposes
self.current_card = init_card
print(f"\nThe Card is: {init_card}")
#asking the player for his/her guess.
choice = input("Higher or Lower? [H/L] ").lower()
#getting the response of the player
self.next_card.player_response = choice
#Showing the next card
print(f"Next Card was: {next_card}")
#Update of scores and storing the return of the update function.
self.score = self.updates(next_card)
#printing of the current score
print(f"Your current score is: {self.score}")
#Getting the value of next_card to be used as a parameter
self.init_card = next_card
|
#
import numpy as np
total_tosses = 30
num_heads = 24
prob_head = 0.5
#0 is tail. 1 is heads. Generate one experiment
experiment = np.random.randint(0,2,total_tosses)
print ("Data of the Experiment:", experiment)
#Find the number of heads
print ("Heads in the Experiment:", experiment[experiment==1]) #This will give all the heads in the array
head_count = experiment[experiment==1].shape[0] #This will get the count of heads in the array
print ("Number of heads in the experiment:", head_count)
#Now, the above experiment needs to be repeated 100 times. Let's write a function and put the above code in a loop
def coin_toss_experiment(times_to_repeat):
head_count = np.empty([times_to_repeat,1], dtype=int)
for times in np.arange(times_to_repeat):
experiment = np.random.randint(0,2,total_tosses)
head_count[times] = experiment[experiment==1].shape[0]
return head_count
head_count = coin_toss_experiment(100)
head_count[:10]
print ("Dimensions:", head_count.shape, "\n","Type of object:", type(head_count))
#Number of times the experiment returned 24 heads.
head_count[head_count>=24]
print ("No of times experiment returned 24 heads or more:", head_count[head_count>=24].shape[0])
print ("% of times with 24 or more heads: ", head_count[head_count>=24].shape[0]/float(head_count.shape[0])*100)
|
'''This file contains classes for modeling state parameters and modules.
The Estimator class represents a distribution over a scalar state variable
(e.g., the distance to the leader car, or the current agent's speed).
Estimators are grouped together in Modules, which use state variable estimates
of various world values to generate control signals for a driving agent. This
file contains implementations for three Modules, namely a Follow module (which
helps a driving agent to follow a leader car), a Speed module (which tries to
maintain a target speed), and a Lane module (which tries to keep the driving
agent in the nearest lane).
'''
import math
import numpy
import numpy.random as rng
import cars
TAU = 2 * numpy.pi
def pid_controller(kp=0., ki=0., kd=0., r=0.7):
'''This function creates a PID controller with the given constants.
The derivative is smoothed using a moving exponential window with time
constant r.
'''
state = {'p': 0, 'i': 0, 'd': 0}
def control(error, dt=1):
state['d'] = r * state['d'] + (1 - r) * (error - state['p']) / dt
state['i'] += error * dt
state['p'] = error
return kp * state['p'] + ki * state['i'] + kd * state['d']
return control
def normalize_angle(theta):
'''Convert an angle from [-2pi, 2pi] to one in [-pi, pi].'''
return (theta + TAU / 2) % TAU - TAU / 2
def relative_angle(target, source, heading):
'''Compute the relative angle from source to target, a value in [-PI, PI].
'''
dx, dy = target - source
return normalize_angle(math.atan2(dy, dx) - heading)
class Estimator:
'''An estimator holds a distribution over a scalar state variable.
The current implementation uses a sort of particle filter to estimate the
variance (uncertainty) in the distribution over the state variable. A small
set of particles keep track of the error (distance from last-observed value)
in the estimate.
Whenever the system allocates a look to a module, the estimate is recentered
at the observed value, and all errors in the estimate are reset to 0.
Whenever the system does not allocate a look to a module, estimates grow in
uncertainty by displacing the particles through a random walk.
'''
def __init__(self, threshold, noise, accrual=0.5, particles=10):
'''Initialize this estimator.
threshold: Indicates the maximum tolerated error in the estimate
before this estimate becomes a candidate for a look.
noise: The step size for a random walk in measurement error.
accrual: The rate at which observed state information is incorporated
into the particle values.
particles: The number of particles to use for estimating variance.
'''
self._noise = noise
self._accrual = accrual
self._threshold = threshold
self._particles = rng.randn(particles)
def __str__(self):
return 'threshold: %s, step: %s' % (self._threshold, self._noise)
@property
def mean(self):
'''Get the current estimated value of this parameter.'''
return self._particles.mean()
@property
def std(self):
'''Get the current absolute error of this parameter.'''
return self._particles.std()
@property
def uncertainty(self):
'''Uncertainty of a module is exp(rmse - threshold).
This value is small for error below the threshold, and large for error
exceeding the threshold.
'''
return numpy.exp(self.std - self._threshold)
def sample(self):
'''Return a sample from this estimator.'''
return rng.normal(self.mean, self.std)
def step(self):
'''Distort the error in our estimate by taking a random step.'''
self._particles += self._noise * rng.randn(len(self._particles))
def observe(self, value):
'''Move the estimated value towards observed values.'''
self._particles += self._accrual * (value - self._particles)
class Module:
'''A module uses a set of state estimates to issue control signals.
Estimates of state values are handled by the Estimator class.
This class contains some high-level methods for providing control signals to
a driving agent (the control() and _control() methods), and for
incorporating state updates based on observations of the world (the
observe() and _observe() methods).
In the driving simulator, there are really only ever three types of state
variable estimates -- distance, speed, and angle. These are used in some
combination in each of the Follow, Lane, and Speed modules below.
'''
def __init__(self, *args, **kwargs):
self.estimators = dict(self._setup(*args, **kwargs))
self.updating = False # whether this module is receiving updates.
def __str__(self):
return '%s module\n%s' % (
self.__class__.__name__.lower(),
'\n'.join('%s: %s' % i for i in self.estimators.iteritems()))
@property
def est_distance(self):
'''Return the estimated distance for this module, if any.'''
return self.estimators['distance'].sample()
@property
def est_speed(self):
'''Return the estimated speed for this module, if any.'''
return self.estimators['speed'].sample()
@property
def est_angle(self):
'''Return the estimated angle for this module, if any.'''
return self.estimators['angle'].sample()
@property
def mean(self):
'''Return the mean of the primary estimator.'''
return self.estimators[self.KEY].mean
@property
def std(self):
'''Return the uncertainty of the primary estimator.'''
return self.estimators[self.KEY].std
@property
def threshold(self):
'''Return the uncertainty of the primary estimator.'''
return self.estimators[self.KEY]._threshold
@property
def uncertainty(self):
'''Return the uncertainty of the primary estimator.'''
return self.estimators[self.KEY].uncertainty
def observe(self, agent, leader):
'''Update this module given the true states of the agent and leader.'''
if not self.updating:
return
values = dict(self._observe(agent, leader))
for name, est in self.estimators.iteritems():
est.observe(values.get(name, 0))
def control(self, dt):
'''Provide a control signal using current state estimates.'''
[est.step() for est in self.estimators.itervalues()]
return self._control(dt)
class Speed(Module):
'''This module attempts to maintain a specific target speed.
The relevant state variable for this task is the driving agent's speed.
'''
KEY = 'speed'
def _setup(self, threshold=1, noise=0.1, accrual=0.3):
'''Set up this module with the target speed.'''
self._pedal = pid_controller(kp=0.5, kd=0.05)
yield 'speed', Estimator(threshold=threshold, noise=noise, accrual=accrual)
def _observe(self, agent, leader):
'''Update the module by observing the actual speed of the agent.'''
yield 'speed', agent.speed
def _control(self, dt):
'''Return the delta between target and current speeds as a control.'''
return self._pedal(cars.TARGET_SPEED - self.est_speed, dt), None
class Follow(Module):
'''This module attempts to follow a leader car.
Relevant state variables for this task are the distance to the leader car,
and the relative angle to the leader car.
'''
KEY = 'distance'
def _setup(self, threshold=1, noise=0.1, angle_scale=0.1, accrual=0.3):
'''Create PID controllers for distance and angle.'''
self._pedal = pid_controller(kp=0.2, kd=0.1)
self._steer = pid_controller(kp=0.01)
yield 'distance', Estimator(threshold=threshold, noise=noise, accrual=accrual)
yield 'angle', Estimator(
threshold=angle_scale * threshold,
noise=angle_scale * noise)
self.ahead = True
def _observe(self, agent, leader):
'''Observe the leader to update distance and angle estimates.'''
err = leader.target - agent.position
self.ahead = numpy.dot(err, agent.velocity) > 0
yield 'distance', numpy.linalg.norm(err) * [-1, 1][self.ahead]
yield 'angle', relative_angle(leader.position, agent.position, agent.angle)
def _control(self, dt):
'''Issue PID control signals for distance and angle.'''
return self._pedal(self.est_distance, dt), self._steer(self.est_angle, dt)
class Lane(Module):
'''This module tries to keep the car in one of the available lanes.
The relevant state variable for this task is the angle to the nearest lane.
'''
KEY = 'angle'
def _setup(self, lanes, threshold=1, noise=0.1, accrual=0.3):
'''Set up this module by providing the locations of lanes.'''
self.lanes = numpy.asarray(lanes)
self._steer = pid_controller(kp=0.01)
yield 'angle', Estimator(threshold=threshold, noise=noise, accrual=accrual)
def _observe(self, agent, leader):
'''Calculate the angle to the closest lane position.'''
dists = ((self.lanes - agent.position) ** 2).sum(axis=-1)
l, t = numpy.unravel_index(dists.argmin(), dists.shape)
# update the angle to the lane based on the position of the lane at some
# short distance ahead.
t = (t + 50) % dists.shape[1]
yield 'angle', relative_angle(self.lanes[l, t], agent.position, agent.angle)
def _control(self, dt):
'''Return the most recent steering signal for getting back to a lane.'''
return None, self._steer(self.est_angle, dt)
|
#Exercise 19.1
'''from tkinter import messagebox
import tkinter as tk
class Window1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'Press Me', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Window2(self.newWindow)
#Creates Window2 with button2 that displays a "Nice Job" message
class Window2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button2 = tk.Button(self.frame, text = 'Now Press Me', width = 25, command = self.new_window)
self.button2.pack()
self.frame.pack()
def new_window(self):
msg=messagebox.showinfo(message="Nice Job!")
self.master.destroy()
def main():
root = tk.Tk()
app = Window1(root)
root.mainloop()
if __name__ == '__main__':
main()'''
#Exercise 19.2
'''from tkinter import *
from tkinter import Canvas
top = Tk()
top.geometry("300x250")
def circleWindow():
C = Canvas(top,bg='blue', height=250, width=300)
oval = C.create_oval(70, 30, 200, 200, fill="Red")
C.pack()
b = Button(top, text= "Click me for Graph", command = circleWindow)
b.place(x=90,y=100)
top.mainloop()'''
#Exercise 19.3
'''from swampy.Gui import *
g = Gui()
g.title('circle demo')
canvas = g.ca(width=500, height=500, bg='white')
circle = None
def callback1():
"""called when the user presses 'Create circle' """
global circle
circle = canvas.circle([0, 0], 100)
def callback2():
"""called when the user presses 'Change color' """
# if the circle hasn't been created yet, do nothing
if circle == None:
return
# get the text from the entry and try to change the circle's color
color = entry.get()
try:
circle.config(fill=color)
except TclError, message:
# probably an unknown color name
print message
# create the widgets
g.bu(text='Create circle', command=callback1)
entry = g.en()
g.bu(text='Change color', command=callback2)
g.mainloop()'''
#Exercise 19.4
'''import os, sys
from Gui import *
import Image as PIL # to avoid name conflict with Tkinter
import ImageTk
class ImageBrowser(Gui):
"""An image browser that scans the files in a given directory and
displays any images that can be read by PIL.
"""
def __init__(self):
Gui.__init__(self)
# clicking on the image breaks out of mainloop
self.button = self.bu(command=self.quit, relief=FLAT)
def image_loop(self, dirname='.'):
"""loop through the files in (dirname), displaying
images and skipping files PIL can't read.
"""
files = os.listdir(dirname)
for file in files:
try:
self.show_image(file)
print file
self.mainloop()
except IOError:
continue
except:
break
def show_image(self, filename):
"""Use PIL to read the file and ImageTk to convert
to a PhotoImage, which Tk can display.
"""
image = PIL.open(filename)
self.tkpi = ImageTk.PhotoImage(image)
self.button.config(image=self.tkpi)
def main(script, dirname='.'):
g = ImageBrowser()
g.image_loop(dirname)
if __name__ == '__main__':
main(*sys.argv)
'''
|
#Exercise 17.1
'''class Time(object):
def time_to_int(self):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
print time.time_to_int()'''
#Exercise 17.2
'''class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def print_point(self):
print "x =", self.x, ",",
print "y =", self.y
point = Point()
point.print_point()
point = Point(10)
point.print_point()
point = Point(20, 30)
point.print_point()'''
#Exercise 17.3
'''class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(%d, %d)' % (self.x, self.y)
point = Point()
print point
point = Point(10)
print point
point = Point(10, 15)
print point'''
#Exercise 17.4
'''class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(%d, %d)' % (self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
point1 = Point(1, 3)
point2 = Point(4, 5)
print point1 + point2'''
#Exercise 17.5
'''class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
point_ = Point()
if isinstance(other, Point):
point_.x += self.x + other.x
point_.y += self.y + other.y
return point_
elif type(other) == tuple:
point_.x += self.x + other[0]
point_.y += self.y + other[1]
return point_
def __radd__(self, other):
return self.__add__(other)
def __str__(self):
return "(%s, %s)" % (self.x, self.y)
point1 = Point(1, 6)
point2 = (5, 2)
point3 = point1 + point2
point4 = point2 + point1
print point3, point4'''
#Exercise 17.6
'''class Kangaroo(object):
def __init__(self):
self.pouch_contents = []
def put_in_pouch(self, thing):
self.pouch_contents.append(thing)
def __str__(self):
return "I have {} in my pouch".format(self.pouch_contents)
def __repr__(self):
return 'Kangaroo <{}>'.format(self.pouch_contents)'''
|
#Trevor Little- 3D Printed Statues
import sys, math, functools
statues= int(input())
numberOfPrinters= 1
numberOfStatuesPrinted= 0
days= 0
while numberOfStatuesPrinted < statues:
if (statues-numberOfStatuesPrinted) > numberOfPrinters:
days+=1
numberOfPrinters+= numberOfPrinters
else:
days+=1
numberOfStatuesPrinted+= numberOfPrinters
print(days)
|
# 44.1 Namn och Ålder som string och int i en tuple.
'''
a = input("Namn: ")
b = int(input("Ålder:"))
t = (a, b)
print(type(a))
print(type(b))
print(t)
'''
# 44.2
'''
def switchT(t):
(a, b) = t
(a, b) = (b, a)
t = (a, b)
return t
t = (5, 6)
print(switchT(t))
'''
# 44.3
'''
def l_to_t(l):
return tuple(l)
print(l_to_t([1, 2, 3]))
'''
# alt 44.3
'''
def convert(l):
a = l[0]
b = l[1]
c = l[2]
t = (a, b, c)
return t
print(convert([1, 2, 3]))
'''
|
# 1 Bygg ett program som låter användaren mata in ett reg.nr och skriv ut de två grupperna
# var för sig; använd slicing-syntax för att dela upp inputsträngen. Klar!
def reg():
answer = input("Ange Regnummer: ")
bokstäver = answer[0:]
siffror = answer[3:]
print(f"Bokstävsgrupp: {bokstäver}\nSiffergrupp: {siffror}")
# 2
def heltal():
nummerlist = input("Ange tal med komma imellan: ")
str_of_num = nummerlist.split(",")
numbers = []
for elem in str_of_num:
numbers.append(int(elem))
backwards = ''.join(list(reversed(nummerlist)))
print(f"Första talet i listan: {nummerlist[0]}\n Sista talet i listan: {nummerlist[-1]}\n")
print(f"Summa av talen i listan: {sum(numbers)}\nListan baklänges: {backwards}")
if __name__ == '__main__':
# reg()
heltal()
|
# 40.1
def rev_text(text):
res = ''
for char in text:
res = char + res
return res
y = []
for i in text:
y.append(i)
# print(f"{y[4]}{y[3]}{y[2]}{y[1]}{y[0]}")
print("40.1")
print(rev_text("12345"))
print("\n")
# 40.2
def big_L(text):
upper = 0
for c in range(len(text)):
if text[c].isupper():
upper += 1
return upper
str = "AbCDefG"
print(big_L(str))
'''
def middle(value, min, max):
if min < value > max:
'''
'''
# 41 - Tankeövning.
def fn(a):
print(a)
a = 2
print(a)
return a
a = 1
print(a) # Kommer printa 1
fn(1) # Kommer printa 1 sedan 2
b = a + fn(1) # Kör igenom fn igen och returnerar värdet från a. B får sedan värdet av a + return av fn(). Som blir 3.
print(b)
print(a) # Kommer printa 1
'''
|
from math import sqrt,cos,pi
import matplotlib.pyplot as plt
two_pi = 2*pi
takel_1 = []
takel_2 = []
takel_3 = []
takel_4 = []
takel_5 = []
takel_6 = []
phase = 0
length = 100
b=6
tilt=45
'''
square fucntion
for i in range(length):
output.append(sqrt((1+b**2)/((1+b**2)*(cos((two_pi*0)+phase)**2)))*cos((two_pi*0)+phase))
phase+= two_pi*(1/length)
'''
def rope_function(position,phase,b=2,tilt=1):
return (((sqrt((1+(b**2))/(1+((b**2)*(cos((two_pi*(position))+phase)**2))))*(cos((two_pi*(position))+phase)))+1)/2)*tilt
for i in range(length):
takel_1.append(rope_function(0,phase,b,tilt))
takel_2.append(rope_function(1/6,phase,b,tilt))
takel_3.append(rope_function(2/6,phase,b,tilt))
takel_4.append(rope_function(3/6,phase,b,tilt))
takel_5.append(rope_function(4/6,phase,b,tilt))
takel_6.append(rope_function(5/6,phase,b,tilt))
phase+= (two_pi*(1/length))
plt.plot(takel_1)
plt.plot(takel_2)
plt.plot(takel_3)
plt.plot(takel_4)
plt.plot(takel_5)
plt.plot(takel_6)
plt.show()
|
'''
Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print '\n'.join(l)
'''
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print str(n1)+str(n2)+str(n3)+str(n4)
'''
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
'''
|
"""Object and functions for working with Loans for Game Simulations."""
from dataclasses import dataclass
import logging
log: logging.Logger = logging.getLogger(__name__)
@dataclass(kw_only=True)
class Loan:
"""Object to manage Loans in Game Simulations."""
name: str
balance: int
monthly_payment: int
partial_payment_allowed: bool = False
def make_payment(self, *, payment: int) -> bool:
"""Make a Payment on a Loan."""
log.info(f"Making a Payment on a Loan: {self.name}")
log.info(f"self.partial_payment_allowed: {self.partial_payment_allowed}")
log.info(f"payment: {payment}")
log.info(f"self.balance: {self.balance}")
if (
(not self.partial_payment_allowed and payment != self.balance)
or (payment % 1000) != 0
or payment < 1000
or payment > self.balance
):
log.info(f"Not able to make payment on the loan")
return False
if payment == self.balance:
log.info(
f"Loan is being paid-off. This leaves a zero balance loan on player's books"
)
log.info(f"Able to make payment on the loan")
self.balance -= payment
log.info(f"New balance: {self.balance}")
# Rule for Bank Loan, the only partially payable loan
self.monthly_payment = int(self.balance * 0.10)
return True
def __str__(self):
"""Create string to be returned when str method is called."""
return (
f"Loan Name: {self.name}"
f"\n Loan Balance: {self.balance}"
f"\n Loan Payment: {self.monthly_payment}"
f"\n Part. Pay. Allowed: {self.partial_payment_allowed}"
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.