text
stringlengths 37
1.41M
|
---|
#Make the factorial function
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
#Print the answer
print("5! is equal to", factorial(5))
#5! is 5 x 4 x 3 x 2 x 1
#More infomation on how to do this at https://en.wikipedia.org/wiki/Factorial
|
def power(*args):
lista = []
i = 0
n = 1
for a in args:
lista.append(a)
if len(lista) == 2:
p = lista[1]
else:
p = 2
while i < p:
n *= lista[0]
i += 1
return n
def main():
print(power(3, 9))
if __name__ == "__main__":
main()
|
grados = int(input("Introduce la Tª en ºF: "))
grados = (grados - 32) * 5 / 9
print("La temperatura en ºC es", grados)
|
import string
texto = input("Introduzca un texto: ")
i = 0
for char in texto:
if char in string.ascii_uppercase:
i += 1
print("Hay {} mayusculas".format(i))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import xml.etree.ElementTree as etree
raw_input()
xml = sys.stdin.read()
# print xml
tree = etree.ElementTree(etree.fromstring(xml))
print sum(map(lambda x: len(x.attrib), tree.iter()))
|
# -*- coding: utf-8 -*-
import string
# --- part one ---
def parse_inputs(file):
with open(file, "r") as f:
return f.readline().rstrip()
polymer = parse_inputs("input.txt")
def lower_upper():
lower_upper = {}
for letter in string.ascii_lowercase:
lower_upper[letter.lower()] = letter.upper()
lower_upper[letter.upper()] = letter.lower()
return lower_upper
lower_upper = lower_upper()
def find_resulting_polymer(polymer):
result = []
for letter in polymer:
if result and letter == lower_upper[result[-1]]:
result.pop()
else:
result.append(letter)
return result
print(f"The answer of part 1 is: {len(find_resulting_polymer(polymer))}")
# --- part two ---
def remove_letter(polymer, letter):
return [l for l in polymer if l.lower() != letter]
def find_shortest_polymer(polymer):
length_polymer = set()
for letter in string.ascii_lowercase:
altered_polymer = remove_letter(polymer, letter)
length_polymer.add(len(find_resulting_polymer(altered_polymer)))
return min(length_polymer)
print(f"The answer of part 2 is: {find_shortest_polymer(polymer)}")
|
# TO FIND THE AREA OF CIRCLE
pi = 3.14
r = float(input("Enter The Radius Of Circle"))
a = pi * r * r
print("\n The Area Of Circle Is = ", a)
|
''' TO FIND GROSS SALARY BY GETTING BASIC SALARY AS INPUT FROM USER
BASIC SALARY < 25000 : HRA = 20% ; DA = 80%
BASIC SALARY >= 25000 : HRA = 25% ; DA = 90%
BASIC SALARY >= 40000 : HRA = 30% ; DA = 95%'''
basic = float(input("Enter Basic Salary Of Employee"))
if(basic<25000):
da = basic * 80 / 100
hra = basic * 20 / 100
elif(basic>=25000 or basic<40000):
da = basic * 90 / 100
hra = basic * 25 / 100
elif(basic>=40000):
da = basic * 95 / 100
hra = basic * 30 / 100
gross = basic + hra + da
print("\n\t Basic Pay : ", basic)
print("\n\t Dearness Allowance : ", da)
print("\n\t House Rent Allowance : ", hra)
print("\n\t-------------------------------------------")
print("\n\t Gross Salary : ", gross)
print("\n\t-------------------------------------------")
|
'''
@judge ZeroJudge
@id c014
@name Primary Arithmetic
@source UVa 10035
@tag Ad-hoc, Binary Operations
'''
from sys import stdin
def carrying(a, b):
ans = 0
c = 0
while a != 0 or b != 0:
c = 1 if a % 10 + b % 10 + c >= 10 else 0
ans += c
a //= 10
b //= 10
return ans
def solve():
for line in stdin:
a, b = map(int, line.split())
if a == 0 and b == 0:
return
n = carrying(a, b)
if n == 0:
yield 'No carry operation.'
elif n == 1:
yield '1 carry operation.'
else:
yield f'{n} carry operations.'
print('\n'.join(solve()))
|
'''
@judge CodeForces
@id 1097A
@name Gennady and a Card Game
@tag Ad-hoc, Card Game
'''
card = input()
hand = input().split()
res = any(map(lambda x: x[0] is card[0] or x[-1] is card[-1], hand))
print('YES' if res else 'NO')
|
'''
@judge CodeForces
@id 1327A
@name Sum of Odd Integers
@contest Educational Codeforces Round 84
@tag Math
'''
from sys import stdin
def solve(n, k):
if k * k > n:
return False
return n % 2 == k % 2
input()
for line in stdin:
n, k = map(int, line.split())
print('YES' if solve(n, k) else 'NO')
|
'''
@judge CodeForces
@id 394A
@name Counting Sticks
@tag String Manipulation
'''
import re
def stickToTuple(s):
temp = re.match(r'(\|+)\+(\|+)=(\|+)', s)
return tuple(map(len, temp.groups()))
def tupleToStick(a, b, c):
return '{}+{}={}'.format('|' * a, '|' * b, '|' * c)
def solve(a, b, c):
if a + b == c:
return tupleToStick(a, b, c)
if a + b - 1 == c + 1:
if a > 1:
return tupleToStick(a - 1, b, c + 1)
return tupleToStick(a, b - 1, c + 1)
if a + b + 1 == c - 1 and c > 1:
return tupleToStick(a + 1, b, c - 1)
return 'Impossible'
s = input()
print(solve(*stickToTuple(s)))
|
def bubble_sort(lst):
for i in range(len(lst)-1):
for j in range(len(lst)-i-1):
if lst[j] > lst[j+1]:
lst[j],lst[j+1] = lst[j+1],lst[j]
return lst
lst = [2,3,5,1,8,7,6]
print(bubble_sort(lst))
|
import re
msg = '<h1>11111</h1>'
pattern = r'<.+>(.*)</.+>'
result = re.match(pattern, msg)
print(result.group())
# number
msg1 = '<h1>2222</h1>'
pattern1 = r'<(.+)>(.*)</\1>' # \1表示引用分组内容
print(re.match(pattern1, msg1))
print(re.match(pattern, msg))
# 起名的方式 (?P<名字>pattern) (?P=名字)
msg2 = '<html><h1>333<h1><html>'
pattern2 = r'<(?P<name1>\w+)><(?P<name2>\w+)>(.+)<(?P=name2)><(?P=name1)>'
print(re.match(pattern2, msg2))
'''
re模块
match 从开头匹配一次
search 只匹配一次
findall 查找所有
sub(pattern,'新内容' | func,string)
split(pattern,string) 分成列表
基础:
.
[]
|
()
量词:
*
+
?
{m}
{m,n} 前后都包含
预定义:
\s space
\d digit
\w word
\b 边界
\大写字母 反向范围
贪婪:
python中数量词默认是贪婪的,即总是尝试匹配尽可能多的字符
在 * ,?,+,{m,n} 后面加?,使贪婪变非贪婪
'''
# sub
string = 'java:100,python:1000'
print(re.sub('\d+', '90', string))
def func(temp):
num = temp.group()
return str(int(num) + 1)
print(re.sub(r'\d+', func, string))
# split
print(re.split(r'[,:]', string))
# 贪婪
msg45 = 'abc123abc'
pattern4 = r'abc(\d+)' # 贪婪
pattern5 = r'abc(\d+?)' # 非贪婪
print(re.match(pattern4, msg45))
print(re.match(pattern5, msg45))
|
#Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut.
# Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square.
# In other words, check if it is possible to make a square using two given rectangles.
for i in range(1, (int(input()) * 2)+1):
l = list(map(int, input().split()))
if i%2 != 0:
a = l[0]
b = l[1]
else:
if (a == l[0] and b + l[1] == a) or (b == l[0] and a + l[1] == b) or \
(a == l[1] and b + l[0] == a) or (b == l[1] and a + l[0] == b):
print("YES")
else:
print("NO")
|
'''Python 3 Code for the align numbers up to n^2 in a spiral challenge.
The output layout can be slighthly changed by setting another character as SPACINGSYMB.
-nighmared'''
NUMBER = int(input('Base: '))
SPACINGSYMB = ' ' #Symbol used to align the output better
print('{}\n'.format(NUMBER))
def makepowlist(n):return(list(range(1,(n**2)+1)))
def makelist(n,rev=False):return((list(range(n))).reverse() if rev else list(range(n)))
class matrix(list):
def __init__(self,n,makeindex=True):
self.n = n
self.numbrl = len(str(self.n**2))
self.powl = makepowlist(self.n)
self.matrix = [None]*n
self.plan = buildplan(self.n)
for y in self.matrix:self.matrix[self.matrix.index(y)] = [None]*n
if makeindex:
for y in self.matrix:
for x in range(len(y)):self.matrix[self.matrix.index(y)][x] = [self.matrix.index(y)+1,x+1]
def __repr__(self):
retstr = ''
for row in self.matrix:
for e in row:retstr+='{} '.format(e)
if row != self.matrix[-1]:retstr+='\n'
return(str(retstr))
def spiral(self,plan):
for e in plan:
i = str(self.powl.pop(-1))
if len(i)!=self.numbrl:
if (self.numbrl-len(i))%2==0:i = '{0}{1}{0}'.format(int((self.numbrl-len(i))*0.5)*SPACINGSYMB,i)
else:i= ((self.numbrl-len(i))*SPACINGSYMB)+i
self.matrix[e[0]][e[1]] = i
def buildplan(n):
xnull=ynull=x=y=0
round,L,fL,cn,even=1,len(makepowlist(n)),[],n-1,bool
if n%2==0:deadx,deady,even = int((n/2)-1),int(n/2),True
else:deadx,deady,even = int((n-1)/2),int((n-1)/2),False
while L>0:
if cn<1 or L<1:break
x,y=xnull,ynull
while x<cn: #move cursor right
fL.append((y,x))
if (y,x) == (deady,deadx):break
x,L=x+1,L-1
while y<cn: #move cursor down
fL.append((y,x))
if (y,x) == (deady,deadx):break
y,L=y+1,L-1
while x>xnull: #move cursor left
fL.append((y,x))
if (y,x) == (deady,deadx):break
x,L=x-1,L-1
xnull+=1
while y>ynull: #move cursor up
fL.append((y,x))
if (y,x) == (deady,deadx):break
y,L=y-1,L-1
ynull+=1
cn = cn-1
if not even:fL.append((deady,deadx))
return fL
MATRIX = matrix(NUMBER)
MATRIX.spiral(MATRIX.plan)
print(MATRIX)
|
"""
def factorial(n):
f = 1
for i in range(1,n + 1):
f *= i
return f
"""
def Z(n):
"""
20 = 5 * 2 * 2
25 = 5^2
50 = 5^2 * 2
"""
count5 = 0
i = 1
while 1:
a = pow(5, i)
if a > n:
return count5
else:
count5 += n/a
i += 1
def main():
T = int(raw_input())
for t in range(T):
N = int(raw_input())
print Z(N)
main()
|
from functools import reduce
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num_one = []
num_two = []
_sum = 0
while l1:
num_one.append(l1.val)
l1 = l1.next
while l2:
num_two.append(l2.val)
l2 = l2.next
for i in range(len(num_one)):
_sum += num_one[i] * (10 ** i)
for i in range(len(num_two)):
_sum += num_two[i] * (10 ** i)
lst = list(map(int, list(str(_sum))))
prev = None
node = None
for l in lst:
node = ListNode(l)
node.next = prev
prev = node
return node
|
import sys
input = sys.stdin.readline
n = int(input())
coords = [list(map(int, input().split())) for _ in range(n)]
coords.sort(key=lambda x: (x[0], x[1]))
for coord in coords:
print(' '.join(list(map(str, coord))))
|
b = 5
a = 3
a *= b # a * b
print('1. ' + str(a))
a = 99
a /= b # a / b
print('2. ' + str(a))
a = 99
a //= b # a / b の整数値
print('3. ' + str(a))
a = 8
a %= b # a を b で割った余り
print('4. ' + str(a))
a = 3
b = 3
a **= b # a を b 回掛ける
print('5. ' + str(a))
|
# パターン1
def merge(array2):
merge_list = []
array1 = list(range(1, len(array2) + 1))
for a1, a2 in zip(array1, array2):
merge_list.append((a1, a2))
print(merge_list)
# パターン2
def merge2(array):
merge_list = []
for i, a in enumerate(array, start=1):
merge_list.append((i, a))
print(merge_list)
def main():
array = ['hoge', 'foo', 'bar']
merge(array)
merge2(array)
if __name__ == '__main__':
main()
|
"""16. 1부터 50 까지의 숫자 중에서 3의 배수를 공백으로 구분하여 출력하시오."""
for k in range(1, 51):
if k % 3 == 0:
print(k, end = ' ')
|
import random
class WisdomRoom(object):
def __init__(self):
self.rightAns = False
self.count = 0
def intro(self):
print "Now you enter the wisdom room, you can only pass the room by answer the question correctly."
def q1(self):
print "what object has four legs in the morning, two legs at noon, three legs in the evening?"
while self.count < 2 and self.rightAns == False:
ans = raw_input(">")
if ans == "human" or ans == "Human":
print "Correct!"
#print self.right
self.rightAns = True
#print self.right
elif self.count < 1:
print "wrong answer, you can take another shot."
self.count += 1
elif self.count == 1:
print "Wrong again, so stupid you are. you get hit by a lightning and die."
self.count += 1
def q2(self):
print "what always goes up and never goes down?"
while self.count < 2 and self.rightAns == False:
ans = raw_input(">")
if ans == "age" or ans == "Age":
print "Correct."
#print self.right
self.rightAns = True
#print self.right
elif self.count < 1:
print "wrong answer, you can take another shot."
self.count += 1
elif self.count >= 1:
print "Wrong answer again, burn in hell!"
self.count += 1
def q3(self):
print "what will you break once you say it?"
while self.count < 2 and self.rightAns == False:
ans = raw_input(">")
if ans == "silence" or ans == "Silence":
print "Correct"
#print "self.right:",self.rightAns
self.rightAns = True
#print "self.right:",self.rightAns
elif self.count < 1:
print "wrong answer, you can take another shot."
self.count += 1
elif self.count >= 1:
print "Wrong answer again,such a pig you are."
self.count += 1
def random_question(self,con):
number = random.randint(1,3)
if number == 1:
con.q1(); #q1,q2,q3 are local function which cannot been seen in random_question
elif number == 2:
con.q2();
else: #if number ==3:
con.q3();
|
#!/usr/bin/env python3
"""
number_guessing_game.py
This program makes up a secret (random) number between 1 and 10,
and gives the user 3 tries to guess it. If the user hasn't
guessed after three tries, then number is revaled.
"""
import random
def main():
randint = random.randrange(10) + 1 # gets a number 1-10 inclusive
guess = 0
tries = 1
print("I'm thinking of a number between 1 and 10.")
print("You have three tries to guess it!")
while tries < 4 and guess != randint:
print("Your guess: ",end='')
guess = eval(input())
if guess == randint:
print("You got it!")
else:
print("Darnit, that's not it!")
if guess < randint:
print("Guess higher!")
else:
print("Guess lower!")
tries = tries + 1
print("The number was",randint)
main()
|
#!/usr/bin/env python3
"""
random_walker1.py
This program models a "random walker" that starts at location 0,0, an
intersection in the middle of a city laid out in square blocks. Each turn,
the random walker moves one block to the north, east, west, or south, with
the x-coordinate changing by 1 block or the y-coordinate changing by one
block.
Print out the move number and the location of the random walker after every
turn. How long does it take the random walker to return home?
"""
import random
def main():
x = 0
y = 0
turns = 0
print("The random walker is starting at position", x, y)
while not(x == 0 and y == 0) or turns == 0:
randint = random.randrange(4)
if randint == 0: x = x + 1
elif randint == 1: y = y + 1
elif randint == 2: x = x - 1
else: y = y - 1
turns = turns + 1
print(turns, x, y)
print("We're back!")
main()
|
#!/usr/bin/python
import sys
import os
import time
def main():
os.system('clear')
mylst=input("please enter the list of words")
mynum=input("please enter the filter value")
start=time.time()
lst=filter_long_words(mylst,mynum)
print("filtered list=",lst)
print("time taken:",time.time()-start)
def filter_long_words(x,n):
for element in x:
if(len(element)<=n):
x.remove(element)
return x
if __name__=='__main__':
main()
|
#!/usr/bin/python
import sys
import os
import time
def main():
os.system('clear')
given=input("enter the list of numbers\n")
start=time.time()
tot=sum(given)
pro=mul(given)
print("sum="+str(tot))
print("product="+str(pro))
print("time taken:",time.time()-start)
def sum(data):
ans=0
for num in data:
ans=ans+num
return ans
def mul(data):
ans=1
for num in data:
ans=ans*num
return ans
if __name__=='__main__':
main()
|
#!/usr/bin/python
import sys
import os
import time
def main():
os.system('clear')
a="bottles of beer on the wall,"
b="bottles of beer."
c="Take one down, pass it around,"
d=" bottles of beer on the wall."
i=99
start=time.time()
while(i>0):
print(str(i)+a+str(i)+b)
i=i-1
print(c+str(i)+d)
i=i-1
print("time taken:",time.time()-start)
if __name__=='__main__':
main()
|
#!/usr/bin/python
import sys
import os
import time
def main():
os.system('clear')
wrdlst=input("please enter the list of words")
start=time.time()
lenlst=Word_to_Length_map_func(wrdlst)
print("the length of the corresponding words are:",lenlst)
print"time taken",time.time()-start
def Word_to_Length_map_func(mydata):
lenlst=map(lambda x:len(x),mydata)
return lenlst
if __name__=='__main__':
main()
|
# 8 kyu
# Count Odd Numbers below n
# Given a number n, return the number of positive odd numbers below n, EASY!
# oddCount(7) //=> 3, i.e [1, 3, 5]
# oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13]
# Expect large Inputs!
def odd_count(n):
return n // 2
|
import unittest
from tree.tree import Tree,Node
class TestPrintTree(unittest.TestCase):
def test_1(self):
self.test = Node(3,None,None)
self.answer = [[3]]
assert Tree(self.test).printTree()== self.answer
def test_2(self):
self.test = Node(1,Node(2,Node(3,None,None),Node(4,None,None)),Node(5,Node(6,None,None),Node(7,None,None)))
self.answer = [['|','|','|',1,'|','|','|'],
['|',2,'|','|','|',5,'|'],
[3,'|',4,'|',6,'|',7]]
assert Tree(self.test).printTree()== self.answer
def test_3(self):
self.test = Node(1,Node(1,Node(1,Node(1,None,None),None),None),None)
self.answer = [['|','|','|','|','|','|','|',1,'|','|','|','|','|','|','|'],
['|','|','|',1,'|','|','|','|','|','|','|','|','|','|','|'],
['|',1,'|','|','|','|','|','|','|','|','|','|','|','|','|'],
[1,'|','|','|','|','|','|','|','|','|','|','|','|','|','|'],]
assert Tree(self.test).printTree()== self.answer
def test_4(self):
self.test = Node(1,Node(1,None,1),Node(1,Node(1,None,1),None))
self.answer = [['|','|','|','|','|','|','|',1,'|','|','|','|','|','|','|'],
['|','|','|',1,'|','|','|','|','|','|','|',1,'|','|','|'],
['|','|','|','|','|',1,'|','|','|',1,'|','|','|','|','|'],
['|','|','|','|','|','|','|','|','|','|',1,'|','|','|','|'],]
assert Tree(self.test).printTree()== self.answer
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
queue, result = [], []
if root is None: return root # Edge condition
queue.append(root)
while queue:
currentNode = queue.pop(0)
if currentNode.left and currentNode.right:
currentNode.left.next = currentNode.right # Condition 1
if currentNode.next:
currentNode.right.next = currentNode.next.left # Condition 2
queue.append(currentNode.left)
queue.append(currentNode.right)
return root
|
from hasher import decode_password, encode_password, hash_master_password
import elara
from stdiomask import getpass
def new_password(db):
website = input("Enter website for which password must be saved - ")
password = getpass(prompt = "Enter password to be saved - ", mask = '*')
db.set(website, encode_password(password))
print("Password added succesfully.")
return db
def view_password(db):
print("Websites for which passwords have been saved: ")
keys = db.getkeys()
keys.remove("Masterpassword")
len_keys = len(keys)
j = 1
for i in keys:
print(j, ". ", i)
j+=1
index = int(input("Enter website serial no. for which password is to be viewed - "))
if index>0 and index<=len(keys):
print("Password - ",decode_password(db.get(keys[index-1])))
def delete_password(db):
print("Websites for which passwords have been saved: ")
keys = db.getkeys()
keys.remove("Masterpassword")
len_keys = len(keys)
j = 1
for i in keys:
print(j, ". ", i)
j+=1
index = int(input("Enter website serial no. for which password is to be deleted - "))
verify_master_password_unhashed = getpass(prompt = "Enter master password for verification - ", mask = '*')
verify_master_password = hash_master_password(verify_master_password_unhashed)
if verify_master_password == db.get("Masterpassword"):
if index>0 and index<=len(keys):
db.rem(keys[index-1])
# Del website and password from dict
print("Password deletion succesful.")
else:
print("Authentication failed. Password not deleted.")
return db
def update_password(db):
print("Websites for which passwords have been saved: ")
keys = db.getkeys()
keys.remove("Masterpassword")
len_keys = len(keys)
j = 1
for i in keys:
print(j, ". ", i)
j+=1
index = int(input("Enter website serial no. for which password is to be updated - "))
verify_master_password_unhashed = getpass(prompt = "Enter master password for verification - ", mask = '*')
verify_master_password = hash_master_password(verify_master_password_unhashed)
if verify_master_password == db.get("Masterpassword"):
if index>0 and index<=len(keys):
newpass = getpass(prompt = "Enter new password - ", mask = '*')
db.set(keys[index-1], encode_password(newpass))
print("Password updated succesful.")
else:
print("Authentication failed. Password not updated.")
return db
|
class Nodo(object):
def __init__(self, nombre, heuristica=0, profundidad=0):
self.nombre = nombre
self.nodosAdyacentes = dict()
self.heuristica = heuristica
self.profundidad = profundidad
def addNodoAdyacentes(self, nodo, peso=0):
self.nodosAdyacentes[nodo.nombre] = peso
def __ne__(self, other):
if self.nombre != other.nombre:
return True
else:
return False
def __lt__(self, other):
if self.nombre < other.nombre:
return True
else:
return False
def __gt__(self, other):
if self.nombre > other.nombre:
return True
else:
return False
def __eq__(self, other):
if self.nombre == other.nombre:
return True
else:
return False
def __str__(self):
# return self.nombre + ": " + str(self.costo)
# return "(" + self.nombre + ") " + str(self.profundidad)
return "(" + self.nombre + ") "
def __repr__(self):
return str(self.nombre)
if __name__ == '__main__':
n1 = Nodo("n1")
n2 = Nodo("n2")
n3 = Nodo("n3")
n4 = Nodo("n4")
a = list()
a.append(n2)
a.append(n4)
a.append(n3)
a.append(n1)
for i in a:
print(i)
a.sort()
print("----------------------")
for i in a:
print(i)
print(n1 < n2)
|
import random
print("What is your name?")
name = input().capitalize()
secretnumber = random.randint(1,20)
print("Well, " + name + ", guess a number between 1 to 20")
for guessestaken in range(1,7):
guess = input()
try:
if int(guess) < secretnumber:
print("Guess higher.")
elif int(guess) > secretnumber:
print("Guess lower.")
else:
break
except ValueError or TypeError:
print('Thats not a valid asnwer')
if int(guess) == secretnumber:
print("Good job, " + name + ", you guessed the number within " + str(guessestaken) + " tries")
else:
print("Sorry, the number was " + str(secretnumber))
|
#!/usr/bin/env
def digits_count(val):
""" Estimate number of digits for input value.
:param val: input value
:type val: int
:returns: int -- number of digits
"""
if val == 0:
return 0
n_digits = 1
while val // 10 > 0:
n_digits += 1
val /= 10
return n_digits
def transformation(input_string):
""" Convert converts the input string to a number
that is the concatenation of a string byte
("abcd" -> 979899100)
:param input_string: input string
:type input_string: str
:returns: int -- concatenation of a string byte
"""
string_list = list(input_string)
if not string_list:
return 0
else:
value = ord(string_list[::-1][0])
return (value + transformation(string_list[0:-1]) *
(10 ** digits_count(value)))
if __name__ == '__main__':
print(transformation('abcder'))
|
#!/usr/bin/env
import functools
import time
def timing(func):
""" This function calculates time
requires to execute function "func".
:param func: function to input
:type func: function
:returns: time required
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('time: {}'.format(end-start))
return result
return wrapper
@timing
def foo(number):
""" This is function just to test timing decorator.
It returns square of inputed number.
:param number: value to input.
:type number: integer.
:returns: squared number.
"""
return number ** 2
if __name__=='__main__':
print(foo(2))
|
#!/usr/bin/env python3.6
# Декоратор - это обертка для функции, которая позволяет
# трансформировать внутреннюю функцию, как мы хотим.
# Дескриптор делает похожее, переписывая протоколы __get__,
# __set__ и __delete__, поэтому сделав атрибут класса экземпляром
# декскриптора, мы можем воздейстовать на этот атрибут.
class prop(object):
"""Descriptor that triggers function calls
when accessing attribute.
"""
def __init__(self, getting=None, setting=None, deleting=None):
self.get = getting
self.set = setting
self.delet = deleting
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.get is None:
raise AttributeError("can't understand attribute")
return self.get(obj)
def __set__(self, obj, value):
if self.set is None:
raise AttributeError("can't set attribute")
self.set(obj, value)
def __delete__(self, obj):
if self.delet is None:
raise AttributeError("can't delete attribute")
self.delet(obj)
def getter(self, getting):
return type(self)(getting, self.set, self.delet)
def setter(self, setting):
return type(self)(self.get, setting, self.delet)
def deleter(self, deleting):
return type(self)(self.get, self.set, delet)
class Something:
def __init__(self, x):
self.x = x
@prop
def attr(self):
return self.x ** 2
@attr.setter
def attr(self, update):
self.x = update
return self.x
if __name__ == '__main__':
s = Something(10)
print(s.attr)
s.attr = 3
print(s.attr)
|
x = abs(int(input("input 1st value: "))) # 1st value
y = abs(int(input("input 2nd value: "))) # 2nd value
while (x!=0) & (y!=0): # until values become 0
if x > y: # looking for bigger value
x = x % y # updating it with mod
else:
y = y % x # updating
print (x+y) # greatest common diviser
|
import datetime
class InvalidLocationError(Exception):
""" Raised in case of
{"error":true,"detail":"Access forbidden, you have no acces for this locale: 1992"}
"""
pass
class InvalidDateError(Exception):
""" Raised in case of
data isn't in the format YYYY-MM-DD
"""
pass
def validate_date(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise InvalidDateError
|
import sys
DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
OTHER_SYMBOLS = {'+', '-', '*', '/', '(', ')'}
END_EXPRESSION = '.'
class Lexer:
def __init__(self, word):
self.word = word
self.cur = 0
self.last = False
def next_token(self):
symbol = self.word[self.cur]
if symbol in DIGITS:
result = ''
while symbol in DIGITS:
result += symbol
self.cur += 1
symbol = self.word[self.cur]
self.cur -= 1
elif symbol in OTHER_SYMBOLS:
result = symbol
else:
self.last = True
result = ''
self.cur += 1
return result
class Parser:
def __init__(self, lexer):
self.tokens = []
self.cur = 0
while not lexer.last:
self.tokens.append(lexer.next_token())
self.size = len(self.tokens)
def parse(self):
result = self.parse_operation()
if self.cur != self.size - 1:
raise ValueError()
return result
def parse_operation(self):
num1 = self.parse_mult()
while self.cur < self.size:
operation = self.tokens[self.cur]
if operation == '+' or operation == '-':
self.cur += 1
else:
break
num2 = self.parse_mult()
if operation == '+':
num1 += num2
else:
num1 -= num2
return num1
def parse_mult(self):
num1 = self.parse_bracket()
while self.cur < self.size:
operation = self.tokens[self.cur]
if operation == '*':
self.cur += 1
else:
break
num2 = self.parse_bracket()
num1 *= num2
return num1
def parse_bracket(self):
current_token = self.tokens[self.cur]
if current_token == '(':
self.cur += 1
result = self.parse_operation()
if self.cur == self.size:
raise ValueError()
next_token = self.tokens[self.cur]
if next_token != ')':
raise ValueError()
else:
result = int(current_token)
self.cur += 1
return result
def main():
word = sys.stdin.readline().strip()
lexer = Lexer(word)
parser = Parser(lexer)
try:
sys.stdout.write(str(parser.parse()))
except ValueError:
sys.stdout.write('WRONG')
if __name__ == '__main__':
main()
|
import sys
class Node:
"""Binary tree node"""
def __init__(self, key: int):
self.left = None
self.right = None
self.key = key
self.height = 1
def balance_tree(root: Node):
root.height = 1 + max(get_height(root.left), get_height(root.right))
if get_balance(root) > 1:
if get_balance(root.right) < 0:
root.right = rotate_right(root.right)
root = rotate_left(root)
if get_balance(root) < -1:
if get_balance(root.right) > 0:
root.left = rotate_left(root.left)
root = rotate_right(root)
return root
def insert(root: Node, key: int):
if root is None:
return Node(key)
else:
if root.key == key:
return root
elif key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return balance_tree(root)
def delete(root: Node, key: int):
"""Remove key from tree"""
if root is None:
return None
if key < root.key:
root.left = delete(root.left, key)
elif key > root.key:
root.right = delete(root.right, key)
else:
q = root.left
r = root.right
if not r:
return q
root_min = findmin(r)
root_min.right = remove_min(r)
root_min.left = q
return balance_tree(root_min)
return balance_tree(root)
def findmin(root: Node):
while root.left is not None:
root = root.left
return root
def remove_min(root: Node):
if root.left is None:
return root.right
root.left = remove_min(root.left)
return balance_tree(root)
def rotate_left(q: Node):
p = q.right
temp = p.left
p.left = q
q.right = temp
q.height = 1 + max(get_height(q.left), get_height(q.right)) # fix height
p.height = 1 + max(get_height(p.left), get_height(p.right)) # fix height
return p
def rotate_right(p):
q = p.left
temp = q.right
q.right = p
p.left = temp
p.height = 1 + max(get_height(p.left), get_height(p.right)) # fix height
q.height = 1 + max(get_height(q.left), get_height(q.right)) # fix height
return q
def get_balance(root):
if not root:
return 0
return get_height(root.right) - get_height(root.left)
def get_height(root):
if not root:
return 0
return root.height
def prev(root: Node, key: int):
cur_root = root
res = None
while cur_root is not None:
if cur_root.key < key:
res = cur_root.key
cur_root = cur_root.right
else:
cur_root = cur_root.left
return res
def findmax(root: Node):
while root.right is not None:
root = root.right
return root.key
def find_k_max(root: Node, k: int) -> int:
max_key = findmax(root)
if k < 2:
return max_key
for _ in range(k - 1):
max_key = prev(root, max_key)
return max_key
tree = None
n = int(sys.stdin.readline())
for _ in range(n):
inp = sys.stdin.readline().split(' ')
if int(inp[0]) == 1:
tree = insert(tree, int(inp[1].strip()))
elif int(inp[0]) == -1:
tree = delete(tree, int(inp[1].strip()))
elif int(inp[0]) == 0:
k_max = find_k_max(tree, int(inp[1].strip()))
sys.stdout.write(str(k_max) + '\n')
else:
pass
|
from random import randint
list_lenght = int(input())
raw_list = list(map(int, input().split(' ')))
assert(len(raw_list) == list_lenght)
def quick_sort_step(input_list, l, r):
ind = randint(l+1, r)
x = input_list[ind]
input_list[ind], input_list[l] = input_list[l], input_list[ind]
i = l
ll = l
h = r
for j in range(l, r+1):
if input_list[j] < x:
input_list[i], input_list[j] = input_list[j], input_list[i]
i += 1
elif input_list[i] > x:
input_list[i], input_list[h] = input_list[h], input_list[i]
h -= 1
else:
i += 1
input_list[l], input_list[i] = input_list[i], input_list[l]
return i
def partition3(A, l, r):
lt = l # We initiate lt to be the part that is less than the pivot
i = l # We scan the array from left to right
gt = r # The part that is greater than the pivot
pivot = A[
l] # The pivot, chosen to be the first element of the array, that why we'll randomize the first elements position
# in the quick_sort function.
while i <= gt: # Starting from the first element.
if A[i] < pivot:
A[lt], A[i] = A[i], A[lt]
lt += 1
i += 1
elif A[i] > pivot:
A[i], A[gt] = A[gt], A[i]
gt -= 1
else:
i += 1
return lt, gt
def quick_sort1(init_list, l, r):
if l < r:
n = partition3(init_list, l, r)
quick_sort(init_list, l, n - 1)
quick_sort(init_list, n + 1, r)
else:
return init_list
def quick_sort(A, l, r):
if l >= r:
return
k = randint(l, r)
A[k], A[l] = A[l], A[k]
lt, gt = partition3(A, l, r)
quick_sort(A, l, lt - 1)
quick_sort(A, gt + 1, r)
quick_sort(raw_list, 0, len(raw_list)-1)
print(' '.join(list(map(str, raw_list))))
|
import sys
class Node:
def __init__(self):
self.next = [None] * 26
self.is_terminal = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, s, node):
ind = ord(s[0]) - 97
if node.next[ind] is not None:
next_node = node.next[ind]
else:
next_node = Node()
node.next[ind] = next_node
if len(s) == 1:
next_node.is_terminal = True
else:
substring = s[1:]
self.insert(substring, next_node)
def contains(self, s, node):
ind = ord(s[0]) - 97
if node.next[ind] is None:
return False
next_node = node.next[ind]
if len(s) == 1:
if next_node.isTerminal:
return True
return False
else:
substring = s[1:]
return self.contains(substring, next_node)
def main():
trie = Trie()
word = sys.stdin.readline().strip()
n = int(sys.stdin.readline())
len_word = len(word)
for i in range(len_word):
for j in range(1, min(30 + 1, len_word - i + 1)):
substring = word[i: i + j]
if trie.contains(substring, trie.root):
set_of_found_words.add(substring)
if __name__ == '__main__':
main()
|
import random
elementos = [1, 1, 5, 1, 3]
probabilidades = [0, 0.027, 0.054, 0.729, 0.756, 1]
dardo = random.random()
print(dardo)
elegido = 0
for i in range(len(probabilidades)):
if dardo < probabilidades[i+1]:
elegido = elementos[i]
print(elegido)
break
|
'''brain-progression game logic'''
from random import randint
WELCOME_STRING = 'What number is missing in the progression?'
LENGTH_MIN = 5
LENGTH_MAX = 10
FIRST_ELEMENT_MIN = 5
FIRST_ELEMENT_MAX = 15
DELTA_MIN = 5
DELTA_MAX = 15
def get_progression(first_element, delta, length):
progression = []
for step in range(0, length):
element = first_element + delta * step
progression.append(str(element))
return progression
def game_set():
length = randint(LENGTH_MIN, LENGTH_MAX)
first_element = randint(FIRST_ELEMENT_MIN, FIRST_ELEMENT_MAX)
delta = randint(DELTA_MIN, DELTA_MAX)
progression = get_progression(first_element, delta, length)
random_index = randint(0, len(progression) - 1)
random_element = progression[random_index]
progression[random_index] = '..'
data_to_show = ' '.join(progression)
correct_answer = str(random_element)
return (data_to_show, correct_answer)
|
import sys, random, time, os, datetime, square, board, misc, learning
class game:
"""A game object. Contains the 9 boards and other attributes associated with a game.
Also contains the functions required to play the game to supplement the helper function in board.py"""
def __init__(self):
"""Game object"""
self.boards = [board.board(), board.board(), board.board(), board.board(), board.board(), board.board(), board.board(), board.board(), board.board()]
self.turn = 1 #cosmetic move count
self.player = square.square.x #current player to move, starts on X
self.prev = None #previous move, used when printing the board.
def __eq__(self, other):
"""Overrides default ==. Ignores irrelevent attributes when comparing games"""
for i in range(0,9):
for j in range(0,9):
if (self.boards[i].squares[j] != other.boards[i].squares[j]):
return False
if (self.player != other.player):
return False
return True
def __str__(self):
"""Print the boards for str(self)"""
final = ""
key = {0:[0,1,2],1:[3,4,5],2:[6,7,8]}
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
for l in range(0,3):
if (self.prev == [key[i][k], key[j][l]]):
final += "\033[34m "+self.boards[key[i][k]].squares[key[j][l]].value+"\033[00m"
elif (self.boards[key[i][k]].active):
final += "\033[36m "+self.boards[key[i][k]].squares[key[j][l]].value+"\033[00m"
elif (self.boards[key[i][k]].winner == square.square.x):
final += "\033[32m "+self.boards[key[i][k]].squares[key[j][l]].value+"\033[00m"
elif (self.boards[key[i][k]].winner == square.square.o):
final += "\033[31m "+self.boards[key[i][k]].squares[key[j][l]].value+"\033[00m"
elif (self.boards[key[i][k]].winner == square.square.draw):
final += "\033[33m "+self.boards[key[i][k]].squares[key[j][l]].value+"\033[00m"
else:
final += " "+self.boards[key[i][k]].squares[key[j][l]].value
final += "\t"
final += "\n"
final += "\n\n"
return final
def switchPlayer(self):
"""Switches players from x to o or vice versa"""
if (self.player == square.square.o):
self.player = square.square.x
elif (self.player == square.square.x):
self.player = square.square.o
def setAllInactive(self):
"""Set all boards to inactive"""
for i in self.boards:
i.active = False
def setAllActive(self):
"""Set all boards to active if not done"""
for i in self.boards:
if (i.winner == square.square.none):
i.active = True
def allCompleted(self):
"""Returns true if all boards can't be played on"""
for i in self.boards:
if (i.winner == square.square.none):
return False
return True
def isFull(self):
"""Returns true if all boards are completly full"""
for i in self.boards:
if (not i.isFull()):
return False
return True
def isFinished(self):
"""Returns the winner if there is one, otherwise returns none"""
for i in board.board.lines:
if (self.boards[i[0]].winner == self.boards[i[1]].winner and self.boards[i[1]].winner == self.boards[i[2]].winner and self.boards[i[0]].winner != square.square.none and self.boards[i[0]].winner != square.square.draw):
return self.boards[i[0]].winner
if (self.isFull() or self.allCompleted()):
return square.square.draw
return square.square.none
def place(self, boardX, squareX, verbose=False):
"""Try to make a move, and sets up boards for next move"""
if (self.boards[boardX].place(self.player, squareX)):
if (not self.boards[squareX].isFull() and self.boards[squareX].winner == square.square.none):
self.setAllInactive()
self.boards[squareX].active = True
else:
self.setAllActive() #wildcard!!
if (self.player == square.square.o):
self.turn += 1
self.switchPlayer()
self.prev = [boardX, squareX]
return True
return False
# ============= HELPER FUNCTIONS FOR AI BELOW ===================
def getAllPossibleMoves(self):
"""Returns a list of every legal move in the current position. Use len() to get number of legal moves"""
final = []
for i in range(0,9):
for j in range(0,9):
if (self.boards[i].active and self.boards[i].squares[j] == square.square.none):
final.append([i,j])
return final
def numCompleted(self, tile):
"""Get number of completed boards by a certain player"""
total = 0
for i in self.boards:
if (i.winner == tile):
total += 1
return total
def numCenterCompleted(self, tile):
"""If the center board is completed by tile, return 1"""
if (self.boards[4].winner == tile):
return 1
return 0
def numCornerCompleted(self, tile):
"""How many corner boards are won by tile"""
total = 0
for i in [0,2,6,8]:
if (self.boards[i].winner == tile):
total += 1
return total
def numSideCompleted(self, tile):
"""How many side boards are won by tile"""
total = 0
for i in [1,3,5,7]:
if (self.boards[i].winner == tile):
total += 1
return total
def numAlmostCompleted(self, tile):
"""Number of boards almost completed by a certain tile"""
total = 0
for i in self.boards:
if (i.almostCompleted(tile)):
total += 1
return total
def almostCompleted(self, tile):
"""Returns true if the player has 2 in a row"""
for i in board.board.lines:
if ((self.boards[i[0]].winner == square.square.none and self.boards[i[1]].winner == tile and self.boards[i[2]].winner == tile) or (self.boards[i[0]].winner == tile and self.boards[i[1]].winner == square.square.none and self.boards[i[2]].winner == tile) or (self.boards[i[0]].winner == tile and self.boards[i[1]].winner == tile and self.boards[i[2]].winner == square.square.none)):
return True
return False
def total(self, tile):
"""Returns number of tiles on the board"""
total = 0
for i in self.boards:
if (i.winner == square.square.none and not i.isFull()):
total += i.numOfTile(tile)
return total
def squaresOnCenter(self, tile):
"""Returns number of centered squares"""
total = 0
for i in self.boards:
if (i.squares[4] == tile):
total += 1
return total
def squaresOnCorners(self, tile):
"""Returns number of corner squares"""
total = 0
for i in self.boards:
for j in [0,2,6,8]:
if (i.squares[j] == tile):
total += 1
return total
def squaresOnSides(self, tile):
"""Returns number of side squares"""
total = 0
for i in self.boards:
for j in [1,3,5,7]:
if (i.squares[j] == tile):
total += 1
return total
# ============= END HELPERS ======================
def start(self, agent1=None, agent2=None, verbose=True, debug=False, useHistory=True):
"""
Play a game. Agents are whatever is playing; none is a human and otherwise it is a learning object.
"""
if (verbose):
print("Starting game.")
try:
while True:
if (verbose):
os.system("clear") #clear the screen
print(str(self))
print("Turn "+str(self.turn)+"")
if (agent1 != None):
print("Eval: ", end="")
misc.printEval(agent1.eval(self, debug=debug))
elif (agent2 != None):
print("Eval: ", end="")
misc.printEval(agent2.eval(self, debug=debug))
if (debug):
print("Number of possible moves: "+str(len(self.getAllPossibleMoves())))
print("Winners: ", end="")
for i in self.boards:
print(i.winner.value+", ", end="")
print("\nhistory len: "+str(len(learning.history.all))+" bytes: "+str(sys.getsizeof(learning.history.all)))
while True:
try:
if ((self.player == square.square.x and agent1 == None) or (self.player == square.square.o and agent2 == None)):
if (verbose):
print("Player "+self.player.value+"'s move (board# square#): ", end="", flush=True)
rawinput = input()
if (rawinput == "debug"):
debug = not debug
continue
move = [int(rawinput.split(' ')[0]) - 1, int(rawinput.split(' ')[1]) - 1]
elif (self.player == square.square.x): #agent1's move
move = agent1.choose(self, depth=agent1.depth, useHistory=useHistory, verbose=verbose)
elif (self.player == square.square.o): #agent2's move
move = agent2.choose(self, depth=agent2.depth, useHistory=useHistory, verbose=verbose)
if (self.place(move[0],move[1])):
break
else:
raise IndexError
except (IndexError, ValueError):
misc.printColor("Invalid move")
if (self.isFinished() != square.square.none):
if (verbose):
if (self.isFinished() == square.square.draw):
misc.printColor("Game ended as a draw", 34)
else:
misc.printColor("Player "+self.isFinished().value+" is victorious!", 32)
return self.isFinished()
except KeyboardInterrupt:
if (verbose):
misc.printColor("\nGame interrupted")
#except Exception as e:
#if (verbose):
#misc.printException(e)
|
#!/usr/bin/python3
# Shyam Govardhan
# 6 December 2018
# Coursera: The Raspberry Pi Platform and Python Programming for the Raspberry Pi
# Module 4 Assignment
import time
import RPi.GPIO as GPIO
ledPin = 7
buttonPin = 8
BLINK_SPEED = .5
def init():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.add_event_detect(buttonPin, GPIO.BOTH, callback=buttonCallback, bouncetime=200)
print("GPIO Version:", GPIO.VERSION)
def blinkLed():
print('Blinking LED')
GPIO.output(ledPin,True)
time.sleep(BLINK_SPEED)
GPIO.output(ledPin,False)
time.sleep(BLINK_SPEED)
def constantLed():
print("Setting LED to constant")
GPIO.output(ledPin,True)
def process():
print("Executing process()")
try:
while True:
if not GPIO.input(buttonPin):
print("process(): Button pressed")
constantLed()
else:
print("process(): Button released")
blinkLed()
except KeyboardInterrupt:
print("Interrupted by user (^C)... Cleaning up...")
GPIO.cleanup()
exit()
except:
print("Unexpected error:", sys.exc_info()[0])
raise
finally:
GPIO.cleanup()
print("Done")
# Main Program
init()
process()
|
import re
def keywordsExtract():
sentence = input("Enter your string: ")
words_list = []
keywords_list = []
userless_list = ["in", "on", "the", "hii", "and", "for", "if", "the", "else", "then", "but", "of", "then", "or", "get", "put", "why", "how", "are", "you", "is", "contain", "this", "a", "an", "iff", "hello", "what"]
word = ""
for letter in sentence:
if letter == " ":
words_list.append(word)
word = ""
else:
word += letter
words_list.append(word)
for keyword in words_list:
print(keyword)
if keyword not in useless_list:
regEx1 = re.findall(r"ed\B", keyword)
regEx2 = re.search(r"ing\B", keyword)
if (regEx1):
continue
else:
keywords_list.append(keyword)
print("\n")
print("_________________________")
for final_keywords in keywords_list:
print(final_keywords)
print("___________________________")
keywordExtract()
|
from tools import estrutura_dados as No
def breadth_first_search(mapa, inicio, fim):
# Criar listas para nós abertos e nós fechados
aberto = []
fechado = []
# Crie um nó representando o inicio e o objetivo
inicio_node = No.No(inicio, None)
objetivo = No.No(fim, None)
# Adiciona nó inicial
aberto.append(inicio_node)
# Repetir até que a lista aberta esteja vazia
while len(aberto) > 0:
# Pegue o primeiro nó (FIFO)
no_atual = aberto.pop(0)
# Adicione o nó atual à lista fechada
fechado.append(no_atual)
# Verifique se atingimos a meta, retorne o caminho
if no_atual == objetivo:
caminho = []
while no_atual != inicio_node:
caminho.append(no_atual.posicao)
no_atual = no_atual.pai
# Retornar caminho invertido
return caminho[::-1]
# Pega a posição atual do nó
(x, y) = no_atual.posicao
# Pega os vizinhos
vizinhos = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
# Loop nos vizinhos
for proximo in vizinhos:
# Pega valor do mapa
valor = mapa.get(proximo)
# Verifique se é uma parede, fantasma ou obstáculo
if (valor == '#') or (valor == '&') or (valor == ' '):
continue
# Crie o nó vizinho
vizinho = No.No(proximo, no_atual)
# Checa se o vizinho está em fechado
if (vizinho in fechado):
continue
# Adicione o nó se não estiver aberto
if (vizinho not in aberto):
aberto.append(vizinho)
return None
|
# -*- coding: utf-8 -*-
def foreign_exchange_calculator(ammount):
mex_to_col_rate = 145.97
return mex_to_col_rate * ammount
def run():
print('CALCULADORA')
print('Convierte de pesos meicanos a pesos colombianos.')
print('')
ammount = float(raw_input('Ingresa la cantidad de pesos mexicanos que quieres convertir'))
result = foreign_exchange_calculator(ammount)
print('${} pesos mexicanos son ${} pesos colombianos'.format(ammount,result))
print('')
if __name__ == '__main__':
run()
|
#AIM: Write a Python program to plot the function y=x**2 using the pyplot or matplotlib libraries.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( -10 , 10 )
y = np.square( x )
plt.plot( x , y )
plt.show()
|
FavoritePokemon = "crobat, squirtle, pikachu, chikorita, lugia, sylveon"
reverse = []
index = len(FavoritePokemon)
while index > 0 :
reverse =+ FavoritePokemon [index -1 ]
index= index - 1
print reverse
|
#Albert
'''
this function asks for age, citizen, and residency. If the age is atleast 35,
the person is an American citizen, and years of residency is atleast 14, the
person is elgible to run for president. If these requirements are not met, there
would be text indicating what the person is missing.
'''
def president(name=None):
age = int(input("Age: "))
citizen = input("Born in the U.S.? (Yes/No): ")
residency = int(input("Years of Residency: "))
if age >= 35 and citizen == "Yes" and residency >= 14:
print("You are eligible to run for president!")
else:
print("You are not eligible to run for president.")
if age < 35:
print("You are too young.")
if citizen == "No":
print("You must be born in the U.S. to run for president.")
if residency < 14:
print("You have not been a resident for long enough.")
president()
|
data = [1, 2, 3, 2, 5]
m = 5
n = 5
start = 0
end = 0
count = 0
interval_sum = 0
# 고려해야 하는 사항들
# 1. interval_sum > m 일때
# 2. interval_sum < m 일때
# 3. interval_sum == m 일때
while end < n and start < n:
if interval_sum > m :
print("전 start", start)
interval_sum -= data[start]
start += 1
print("후 start", start, "interver_sum", interval_sum)
elif interval_sum < m :
print("end",end)
interval_sum += data[end]
end += 1
print("interval_sum < m",interval_sum)
elif interval_sum == m:
print("전 interval_sum", interval_sum, "data[start]", data[start])
count += 1
interval_sum -= data[start]
print("후 interval_sum", interval_sum, "data[start]", data[start], "count", count)
print("count", count)
|
numbers = [0, 1, 0, 0, 0]
numbers = list(map(str, numbers))
numbers.sort(key = lambda x : x*3, reverse = True)
print(numbers)
print((''.join(numbers)))
# def change(numbers,x,y):
# temp = 0
# index_x = numbers.index(x)
# index_y = numbers.index(y)
# temp = numbers[index_x]
# numbers[index_x] = numbers[index_y]
# numbers[index_y] = temp
#
# for b in range(len(numbers)):
# for x,y in zip(numbers, numbers[1:]):
# X = str(x)
# Y = str(y)
# # X,Y가 몇의 자리 수인지 판단하기
# if len(X) >= len(Y):
# n = len(Y)
# else:
# n = len(X)
# for i in range(n):
# if X[i] < Y[i]:
# change(x,y)
# break
# elif X[i] > Y[i]:
# break
# else: # X[i] == Y[i]
# if X in Y or Y in X:
# m = max(x,y)
# # print(m)
# if str(m)[i] < str(m)[i+1]:
# if m == x:
# break
# else:
# change(x,y)
# elif str(m)[i] > str(m)[i+1]:
# if m == x:
# change(x,y)
# else:
# break
# answer = str(numbers.pop(0))
# for num in numbers:
# num = str(num)
# answer += num
# print(answer)
# import heapq
# from collections import deque
# numbers = [3, 30, 34, 5, 9]
# temp = []
# answer = []
# deque_answer = deque(answer)
# answer = 0
# for z in numbers:
# heapq.heappush(temp, str(z))
# for i in range(len(temp)):
# deque_answer.appendleft(heapq.heappop(temp))
# x = deque_answer[0]
# for y in range(1, len(deque_answer)):
# x += deque_answer[y]
# print(x)
# #실패 다시 시도할 것!
|
from random import random, randint
from skimage import draw
import math
import numpy as np
class ImageAugmenter():
""" Modify input images for data augmentation.
Draw ellipse_count ellipses, each with a random color in the part of the image given by 'area'.
Area is height x width
fraction is from 0.0 to 1.0
"""
def __init__(self, fraction, image_shape=(120,120,3), area=(30,120) ):
self.percent = fraction
self.image_shape = image_shape
self.area = area
self.area_shape = (area[0], area[1], image_shape[2])
self.ellipse_count = 10
def __call__(self, images):
for img in images:
if random() < self.percent:
self.ellipses(img)
#before = np.count_nonzero(img)
self.noisy(img)
#after = np.count_nonzero(img)
#print( "Diff: {}".format( after - before ) )
return images
def random_color(self):
return (random(), random(), random())
def _highlight(self, image):
""" Test to make sure we're augmenting in the right place """
print( "Area shape: {}".format( (self.area_shape[0], self.area_shape[1]) ) )
rr, cc = draw.rectangle( (0,0), end=(self.area_shape[0]-1, self.area_shape[1]-1) )
image[rr,cc,:] = (0.5,0.5,0.5)
def ellipses(self, image):
#for i in range(randint(1,self.ellipse_count)):
for i in range(self.ellipse_count):
row = randint(0,self.area_shape[0])
col = randint(0,self.area_shape[1])
r_rad = randint(5,self.area_shape[0]/5)
c_rad = randint(5,self.area_shape[1]/5)
rot = (random() * math.pi * 2.0) - math.pi
#self._highlight(img)
rr, cc = draw.ellipse(row, col, r_rad, c_rad, self.area_shape, rot)
image[rr, cc, :] = self.random_color()
return image
def noisy(self, image, noise_typ="gaussian"):
"""
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str
One of the following strings, selecting the type of noise to add:
'gaussian' Gaussian-distributed additive noise.
'poisson' Poisson-distributed noise generated from the data.
's&p' Replaces random pixels with 0 or 1.
'speckle' Multiplicative noise using out = image + n*image,where
n is uniform noise with specified mean & variance.
From: https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv
"""
if noise_typ == "gaussian":
row,col,ch= image.shape
mean = 0.0
var = 0.01
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
image += gauss
np.clip(image, 0.0, 1.0, image)
return image
elif noise_typ == "s&p":
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
elif noise_typ == "poisson":
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy = np.random.poisson(image * vals) / float(vals)
return noisy
elif noise_typ =="speckle":
row,col,ch = image.shape
gauss = np.random.randn(row,col,ch)
gauss = gauss.reshape(row,col,ch)
noisy = image + image * gauss
return noisy
def runTests():
import matplotlib.pyplot as plt
import numpy as np
n = 10
images = np.zeros( (n,120,120,3) )
aug = ImageAugmenter( 0.5 )
aug(images)
plt.figure(figsize=(20, 4))
plt.suptitle( "Sample Images", fontsize=16 )
for i in range(n):
ax = plt.subplot(1, n, i+1)
plt.imshow(images[i])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
if __name__ == "__main__":
runTests()
|
__author__ = 'dare7'
# for development in external local IDE and to be complied with Codeskulptor at the same time
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
simplegui.Frame._hide_status = True
import random, math
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
# default values for global vars
player_number = 0
secret_number = 0
game_mode = 100
current_count = 0
max_count = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global player_number
global secret_number
global game_mode
global inp
if game_mode == 1000:
range1000()
else:
#default
range100()
# cheat mode below for a quick test
#print(secret_number)
tries_calc()
print("==========================================")
print("New game started!")
print("Maximum number of tries for this game %s" % str(max_count))
#default guess is 0
inp.set_text("0")
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number
global game_mode
secret_number = random.randrange(0,100)
game_mode = 100
def handler100():
#handler for 100 range button
range100()
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global game_mode
secret_number = random.randrange(0,1000)
game_mode = 1000
def handler1000():
#handler for 1000 range button
range1000()
new_game()
def handler_check():
#handler for result check button
global inp
#forward number to guess func
input_guess(inp.get_text())
def tries_calc():
# calculate numbers of tries depending on game mode
global game_mode
global max_count
global current_count
max_count = int(math.ceil(math.log(game_mode, 2)))
current_count = max_count
return max_count
def input_guess(guess):
# main game logic goes here
global player_number
global secret_number
global current_count
try:
# if no exceptions
player_number = int(guess)
except:
# if user entered non digit
print("Try to enter a number next time! Setting your choice to last choice or default")
print("Guess was %s" % str(player_number))
current_count -= 1
if (player_number < secret_number) and (current_count > 0):
print("Higher")
elif (player_number > secret_number) and (current_count > 0):
print("Lower")
elif (player_number == secret_number) and (current_count > 0):
print("Correct! You may now take that cookie")
new_game()
elif current_count == 0:
print("You lost!")
new_game()
print("Guesses left: %s" % str(current_count))
if __name__ == '__main__':
# for future import as module usage
# create frame
frame = simplegui.create_frame('Guess the number! (c) Epic Gamedev Corporation', 200, 200, 300)
# register event handlers for control elements and start frame
inp = frame.add_input('Enter your guess', input_guess, 50)
frame.add_button("Check my number", handler_check, 150)
frame.add_button("Reset", new_game, 150)
frame.add_button("Range: 0 - 100", handler100, 150)
frame.add_button("Range: 0 - 1000", handler1000, 150)
frame.add_button('Quit', frame.stop, 150)
# call new_game
new_game()
frame.start()
|
from random import choice
# Q2
gestures = ["rock", "paper", "scissors"]
# Q3
def numb_rounds():
while True:
n_rounds = input("Please input an odd number of rounds to play: ")
try:
if int(n_rounds) % 2 != 0:
print("Got it.")
break
elif int(n_rounds) % 2 == 0:
print("This is an even number.")
except ValueError:
if isinstance(n_rounds, str) is True:
print("This is not a number.")
return int(n_rounds)
n_rounds = numb_rounds()
# Q4
rounds_to_win = int((n_rounds / 2) + 1)
print("The player needs to win " + str(rounds_to_win) + " rounds to win \
the game.")
# Q5
cpu_score = 0
player_score = 0
# Q6
def computer_gesture():
return choice(gestures)
comp_choice = computer_gesture()
# Q7
def player_gesture():
while True:
gesture = input("Please choose between 'rock', \
'paper' or 'scissors': ")
if gesture.lower() == "rock" or gesture.lower() == "paper" or gesture.lower() == "scissors":
break
else:
continue
return gesture
player_choice = player_gesture()
# Q8
def round_winner(comp_choice, player_choice):
if comp_choice == "rock" and player_choice == "paper":
return 2
elif comp_choice == "rock" and player_choice == "scissors":
return 1
elif comp_choice == "paper" and player_choice == "rock":
return 1
elif comp_choice == "paper" and player_choice == "scissors":
return 2
elif comp_choice == "scissors" and player_choice == "rock":
return 2
elif comp_choice == "scissors" and player_choice == "paper":
return 1
else:
return 0
who_won_round = round_winner(comp_choice, player_choice)
# Q9
def results_printer(who_won_round, comp_choice, player_choice):
print(comp_choice)
print(player_choice)
if who_won_round == 1:
print("Computer won.")
global cpu_score
cpu_score += 1
return cpu_score
elif who_won_round == 2:
print("Player won.")
global player_score
player_score += 1
return player_score
elif who_won_round == 0:
print("Tie.")
cpu_score += 0
player_score += 0
return cpu_score and player_score
results = results_printer(who_won_round, comp_choice, player_choice)
# Q10
# I think now it is working 100% properly!!!
def game():
round_counter = 0
"""
Had to set the cpu and player scores back to 0 here,
otherwise they would assume previous values from the first time
I had to run everything
"""
global cpu_score
cpu_score = 0
global player_score
player_score = 0
while (cpu_score != rounds_to_win or player_score != rounds_to_win) and round_counter != n_rounds:
comp_choice = computer_gesture()
player_choice = player_gesture()
who_won_round = round_winner(comp_choice, player_choice)
results = results_printer(who_won_round, comp_choice, player_choice)
round_counter += 1
print("Number of rounds played:", round_counter)
game()
# Q11
"""
Added these print statements to help me check whether or not
previous wins were being computed, and they were.
So that's why I set the global scores back to 0 in the 'game' function above
"""
print("Computer score:", cpu_score)
print("Player score:", player_score)
if cpu_score > player_score:
print("The final winner is: The Computer")
elif cpu_score == player_score: # added possibility of game ending in a tie.
print("The game ended in a tie.")
else:
print("The final winner is: The Player")
|
birthdays = {'alice':'4/1','bob':'2/1', 'iva':'2/21'}
while True:
print('please input the name. if you want to quite, please enter ')
name = input()
if name == '':
break
if name in birthdays:
print(name + 'birthday is' + birthdays[name])
else:
print(name + 'birthday is not recorded')
print('please input birthday')
birthday = input()
birthdays[name] = birthday
print('update birthday!!!')
|
# Welcome to the Week 7 CodeBench exercise set. As with the Week 6 set, we start with some revision exercises, and then have some slightly longer algorithm design questions to finish.
#
# The code below defines a Person class. Each person has a name and a list of friends that other pople can be added to.
#
# You jobs are to:
#
# Implement the constructor for person so that the name given to the constructor is stored in a member variable called name and a member variable called friends is initialised to an empty list.
#
# Implement the method is_friends_with. If a and b are people then this method should return true if a has been added as a friend of b or if b has been added as a friend of a.
#
# Implement the add_friend method. If a and b are instances of Person then after a.add_friend(b) is called a must be a friend of b and b must be a friend of a.
#
# The tests at the end of the program will check whether all the above conditions are properly implemented by your code.
#
# An exercise on Classes, lecture 12.
# class Person:
#
# def __init__(self, name):
# """Create a new person with the given name and no friends."""
#
# # TODO: Implement this
#
# def add_friend(self, other):
# """Make this person and the given other person friends."""
#
# # TODO: Implement this.
#
# def is_friends_with(self, other):
# """Returns True if and only if other is a friend of this person."""
# # TODO: Fix this
# return False
#
#
# # DO NOT MODIFY CODE BELOW THIS LINE
# import unittest
#
#
# class FriendTests(unittest.TestCase):
#
# def test_init(self):
# alice = Person('Alice')
# self.assertEqual(alice.name, 'Alice')
# self.assertEqual(alice.friends, [])
#
# def test_add(self):
# alice = Person('Alice')
# bob = Person('Bob')
# # alice.add_friend(bob)
# # self.assertTrue(alice.is_friends_with(bob))
# # self.assertTrue(bob.is_friends_with(alice))
#
# # Q3 Classes are a useful way of storing related data items (in much the same way that a dictionary can store key-value pairs).
# # The code in this exercise implements a class for holding name and email address information.
# # The function extract_names operates on a list of Contact objects to extract the names and return them in sorted order.
class Contact:
"""Encapsulates an email contact."""
def __init__(self, name, email):
self.name = name
self.email = email
# # DO NOT MODIFY CODE ABOVE THIS LINE
def extract_names(address_book):
"""Return a sorted list of all names in an address book,
implemented as a list of Contact objects."""
names = []
for contact in address_book:
names.append(contact.name)
return sorted(names)
# DO NOT MODIFY CODE BELOW THIS LINE
addr_book = []
addr_book.append(Contact("Mickey Mouse", "[email protected]"))
addr_book.append(Contact("Minnie Mouse", "[email protected]"))
addr_book.append(Contact("Goofy", "[email protected]"))
addr_book.append(Contact("Pluto", "[email protected]"))
addr_book.append(Contact("Winnie the Pooh", "[email protected]"))
print("\n".join(extract_names(addr_book)))
|
import timeit
import copy
print("Ingrese el tamaño del arreglo.")
basura = input()
print('Ingrese los numeros del arreglo.')
entrada = input()
def transformar_input(entrada):
res = []
for num in entrada.split():
res.append(int(num))
return res
entrada = transformar_input(entrada)
def crear_lista(tamanio):
res = list()
for elem in range(tamanio):
res.append(0)
return res
def crear_matriz(tamanio):
matriz = crear_lista(tamanio+1)
i = 0
while(i < tamanio+1):
matriz[i] = crear_lista(tamanio+1)
i += 1
return matriz
def max_posibles_pintados_azules_desde(vector_entrada, matriz, j,fila):
res = matriz[fila][0]
for k in range(len(matriz)):
if(vector_entrada[j-1] < vector_entrada[k-1] and matriz[fila][k] > res):
res = matriz[fila][k]
return res
def max_posibles_pintados_rojos_desde(vector_entrada, matriz, j, columna):
res = matriz[0][columna]
for k in range(len(matriz)):
if(vector_entrada[j-1] > vector_entrada[k-1] and matriz[k][columna] > res):
res = matriz[k][columna]
return res
def ej3(vector_entrada,matriz):
maximo = 0
posible_maximo1 = 0
posible_maximo2 = 0
tamanio = range(len(matriz))
for fila in tamanio:
for column in tamanio:
if(fila < column):
posible_maximo2 = max_posibles_pintados_azules_desde(vector_entrada, matriz, column, fila)
matriz[fila][column] = posible_maximo2 + 1
maximo = max(maximo,posible_maximo2)
if(fila > column):
posible_maximo1 = max_posibles_pintados_rojos_desde(vector_entrada, matriz, fila, column)
matriz[fila][column] = posible_maximo1 + 1
maximo = max(maximo,posible_maximo1)
if(fila == column):
matriz[fila][column] = 0
return maximo
def dinamico(vector_entrada):
matriz = crear_matriz(len(vector_entrada))
max_cant_pintados = ej3(vector_entrada,matriz)
return (len(vector_entrada) - max_cant_pintados - 1)
start = timeit.default_timer()
print(dinamico(entrada) )
print(timeit.default_timer() - start)
|
n = int(input('Enter a number: '))
print(f'''Predecessor: {n - 1}
Successor: {n + 1}''')
|
t = int(input('How many days rented? '))
d = int(input('How many kilometers traveled? '))
print(f'Total: R${(60 * t) + (0.15 * d)}')
|
n1 = int(input('Enter a value: '))
n2 = int(input('Enter another value: '))
print(f'The sum between {n1} and {n2} is {n1 + n2}')
|
#! /usr/bin/env python
"""
regularized_logistic.py
Python implementation of part 2 of coding exercise 2 for Andrew Ng's coursera machine learning class (week 3 assignment)
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as optimize
"""
Part 1: visualize the data
"""
# load data
dat2 = np.loadtxt('../ex2data2.txt', delimiter=',')
X = dat2[:, 0:2]
y = dat2[:, 2]
# get group indices
indT = np.where(y==1)[0]
indF = np.where(y==0)[0]
# scatter plot by accept/reject status
fig, ax = plt.subplots()
ax.plot(X[indT, 0], X[indT, 1], marker='+', markeredgecolor='black', linestyle='none', label='Accepted')
ax.plot(X[indF, 0], X[indF, 1], marker='o', markerfacecolor='yellow', linestyle='none', label='Rejected')
ax.legend(numpoints=1, loc='upper right')
ax.set_xlabel('Microchip Test 1')
ax.set_ylabel('Microchip Test 2')
fig.show()
"""
Part 2: Add polynomial expansion features and compute initial conditions
"""
def mapFeature(X, max_degree) :
# make all power combinations up to max_degree
# initialize with 0 exponent - just ones
if len(X.shape) == 1 :
features_out = np.ones(1)
else :
features_out = np.ones(X.shape[0])
for i in np.linspace(1, max_degree, max_degree) :
for j in np.linspace(0, i, i+1) :
# print i-j, j
try :
new_feature = (X[:,0]**(i-j) * X[:,1]**j)
features_out = np.column_stack((features_out, new_feature))
except IndexError :
new_feature = (X[0]**(i-j) * X[1]**j)
features_out = np.append(features_out, new_feature)
return features_out
max_degree = 6
X = mapFeature(X, max_degree)
init_theta = np.zeros(X.shape[1])
lam = 1.0
def sigmoid(z) :
g = 1.0/(1+np.exp(-z))
return g
def costFuncReg(theta, X, y) :
m = len(y)
predictions = sigmoid(np.dot(X, theta))
J = (1.0/m) * sum(-y * np.log(predictions) - (1-y) * np.log(1-predictions))
J_reg = lam/(2*m) * sum(theta[1:len(theta)]**2)
J = J + J_reg
grad = (1.0/m) * np.sum((predictions -y) * X.T, axis=1)
grad_reg = np.append(0, lam/m * theta[1:len(theta)])
grad = grad + grad_reg
return J, grad
init_J, init_grad = costFuncReg(init_theta, X, y)
"""
Part 3: Optimize theta
"""
def Jreg(theta) :
m = len(y)
predictions = sigmoid(np.dot(X, theta))
J = (1.0/m) * sum(-y * np.log(predictions) - (1-y) * np.log(1-predictions))
J_reg = lam/(2*m) * sum(theta[1:len(theta)]**2)
J = J + J_reg
return J
def gradreg(theta) :
m = len(y)
predictions = sigmoid(np.dot(X, theta))
grad = (1.0/m) * np.sum((predictions -y) * X.T, axis=1)
grad_reg = np.append(0, lam/m * theta[1:len(theta)])
grad = grad + grad_reg
return grad
res = optimize.minimize(Jreg, init_theta, method='BFGS', jac=gradreg, options={'disp': True})
opt_theta = res.x
"""
Part 4: plot boundary and compute training accuracy
"""
# define a plotting area
u = np.linspace(-1, 1.5, 50)
v = np.linspace(-1, 1.5, 50)
# compute theta.T * X over all points in the grid
z = np.zeros((len(u), len(v)))
for i in xrange(len(u)) :
for j in xrange(len(v)) :
z[i,j] = np.dot(mapFeature(np.array((u[i], v[j])), max_degree), opt_theta)
# plot contour with only 0-level shown (corresponds to decision boundary)
fig, ax = plt.subplots()
ax.contour(v, u, z, levels=[0], colors='green', label='Decision boundary') # for contour, either transpose z, or put v as rows and u as columns
ax.plot(X[indT, 1], X[indT, 2], marker='+', markeredgecolor='black', linestyle='none', label='Accepted')
ax.plot(X[indF, 1], X[indF, 2], marker='o', markerfacecolor='yellow', linestyle='none', label='Rejected')
ax.legend(numpoints=1, loc='upper right')
ax.set_xlabel('Microchip Test 1')
ax.set_ylabel('Microchip Test 2')
fig.show()
# compute training set accuracy
def predict(theta, X) :
# return a vector p of 0/1 classifications
p = np.zeros(X.shape[0])
predictions = sigmoid(np.dot(X, theta))
pred0 = np.where(predictions<0.5)[0]
pred1 = np.where(predictions>=0.5)[0]
p[pred0] = 0
p[pred1] = 1
return p
p = predict(opt_theta, X)
print 'Our accuracy on the training set was', np.mean(p==y)*100, '%'
|
'''
"Факторіал"
Реалізуйте функцію factorial(n) яка повертає факторіал натурального числа.
'''
def factorial(n):
# ваш код
assert factorial(1) == 1
assert factorial(2) == 2
assert factorial(3) == 2 * 3
assert factorial(4) == 2 * 3 * 4
assert factorial(5) == 2 * 3 * 4 * 5
assert factorial(6) == 2 * 3 * 4 * 5 * 6
assert factorial(7) == 2 * 3 * 4 * 5 * 6 * 7
|
# Double Every Other
# https://www.codewars.com/kata/5809c661f15835266900010a
def double_every_other(lst):
for i in range(1, len(lst), 2):
lst[i] *= 2
return lst
assert double_every_other([1,2,3,4,5]) == [1,4,3,8,5]
assert double_every_other([1,19,6,2,12,-3]) == [1,38,6,4,12,-6]
assert double_every_other([-1000,1653,210,0,1]) == [-1000,3306,210,0,1]
|
# Count of positives / sum of negatives
# https://www.codewars.com/kata/576bb71bbbcf0951d5000044
def count_positives_sum_negatives(arr):
if len(arr) == 0:
return []
positives_count = 0
sum_negatives = 0
for i in arr:
if i > 0:
positives_count += 1
if i < 0:
sum_negatives += i
return [positives_count, sum_negatives]
assert count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]) == [10,-65]
assert count_positives_sum_negatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]) == [8,-50]
assert count_positives_sum_negatives([1]) == [1,0]
assert count_positives_sum_negatives([-1]) == [0,-1]
assert count_positives_sum_negatives([0,0,0,0,0,0,0,0,0]) == [0,0]
assert count_positives_sum_negatives([]) == []
|
'''
"Матриця"
Реалізуйте функцію print_matrix().
Функція отримує матрицю чисел — список, елементами якого є списки (рядки), елементами яких у свою чергу є цілі числа (колонки).
Функція виводить матрицю у вигляді таблиці.
Якщо функції передано матрицю
[[1,2,3],[4,5,6],[7,8,9]]
то вивід має бути наступним:
1 2 3
4 5 6
7 8 9
'''
def print_matrix(matrix):
# ваш код тут
row = 0
while row < len(matrix):
line = ''
col = 0
while col < len(matrix[row]):
line += str(matrix[row][col]) + ' '
col += 1
print(line)
row += 1
def print_matrix(matrix):
print('\n'.join(('{:5} '*len(row)).strip().format(*row) for row in matrix))
matrix = [[1,2,3],[4,5,6],[7,8,9]]
# випадково сгенерована матриця, можна розкоментувати наступний код
'''
from random import randint
n = randint(3, 6)
matrix = [[randint(0, 9) for col in range(n)] for row in range(n)]
'''
print_matrix(matrix)
|
'''
""
, .
-: 23, 35, 100, 12121.
: 123, 9980.
next_doubleton(num).
num.
- num.
'''
#
# https://www.codewars.com/kata/604287495a72ae00131685c7
def is_doubleton(num):
digits = [0] * 10
for ch in str(num):
digits[int(ch)] = 1
return sum(digits) == 2
def next_doubleton(num):
while True:
num += 1
if is_doubleton(num):
return num
# ,
assert next_doubleton(120) == 121
assert next_doubleton(1234) == 1311
assert next_doubleton(10) == 12
assert next_doubleton(1) == 10
assert next_doubleton(111) == 112
|
'''
"Сума цифр"
Реалізуйте функцію sum_of_digits().
Функція отримує число, повертає суму цифр цього числа.
'''
def sum_of_digits(number):
# ваш код
num_as_str = str(number)
sum = 0
index = 0
while index < len(num_as_str):
if num_as_str[index] in '0123456789':
sum += int(num_as_str[index])
index += 1
return sum
assert sum_of_digits(0) == 0
assert sum_of_digits(1) == 1
assert sum_of_digits(5000005) == 10
assert sum_of_digits(-2) == 2
assert sum_of_digits(-2.3) == 5
|
'''
Напишіть програму яка виконує наступне:
1. Змінній a присвоїти значення 4
2. Змінній b присвоїти значення 3
3. Обчислити суму квадратів a та b. Результат присвоїти змінній result
4. Вивести в термінал значення змінної result
'''
# ваш код починається з наступного рядка
a = 4
b = 3
result = a*a + b*b
print(result)
# не міняйте наступний код, це тести
assert a == 4
assert b == 3
assert result == 25
|
# Data cleaning means fixing bad data in your data set.
# Bad data could be:
# 1. Empty cells
# 2. Data in wrong format
# 3. Wrong data
# 4. Duplicates
import pandas as pd
our_dataset = pd.read_csv("dirtydata.csv")
print(our_dataset)
# The data set contains some empty cells ("Date" in row 22, and "Calories" in row 18 and 28).
# The data set contains wrong format ("Date" in row 26).
# The data set contains wrong data ("Duration" in row 7).
# The data set contains duplicates (row 11 and 12).
|
# Cells with data of wrong format can make it difficult, or even impossible, to analyze data.
# To fix it, you have two options: remove the rows, or convert all cells in the columns into the same format.
# Convert Into a Correct Format
# In our Data Frame, we have two cells with the wrong format.
# Check out row 22 and 26, the 'Date' column should be a string that represents a date:
import pandas as pd
abc = pd.read_csv("dirtydata.csv")
print(abc)
# Let's try to convert all cells in the 'Date' column into dates.
# Pandas has a to_datetime() method for this:
abc['Date'] = pd.to_datetime(abc['Date'])
print(abc.to_string())
# As you can see from the result, the date in row 26 where fixed, but the empty date in row 22 got a NaT (Not a Time) value, in other words an empty value.
# One way to deal with empty values is simply removing the entire row.
# Removing Rows
# The result from the converting in the example above gave us a NaT value, which can be handled as a NULL value.
# We can remove the row by using the dropna() method.
abc.dropna(subset=['Date'], inplace = True)
print(abc.to_string())
# "Wrong data" does not have to be "empty cells" or "wrong format", it can just be wrong, like if someone registered "199" instead of "1.99".
# Sometimes you can spot wrong data by looking at the data set, because you have an expectation of what it should be.
# If you take a look at our data set, you can see that in row 7, the duration is 450, but for all the other rows the duration is between 30 and 60.
# It doesn't have to be wrong, but taking in consideration that this is the data set of someone's workout sessions, we conclude with the fact that this person did not work out in 450 minutes.
# How can we fix wrong values, like the one for "Duration" in row 7?
# Replacing Values
# One way to fix wrong values is to replace them with something else.
# In our example, it is most likely a typo, and the value should be "45" instead of "450", and we could just insert "45" in row 7:
abc.loc[7, 'Duration'] = 45
print(abc.to_string)
# For small data sets you might be able to replace the wrong data one by one, but not for big data sets.
# To replace wrong data for larger data sets you can create some rules, e.g. set some boundaries for legal values, and replace any values that are outside of the boundaries.
# Loop through all values in the "Duration" column.
# If the value is higher than 120, set it to 120:
abc = pd.read_csv("dirtydata.csv")
abc['Date'] = pd.to_datetime(abc['Date'])
abc.dropna(subset=['Date'], inplace = True)
for x in abc.index:
if abc.loc[x, "Duration"] > 120:
abc.loc[x, "Duration"] = 120
print(abc.to_string())
# Removing Rows
# Another way of handling wrong data is to remove the rows that contains wrong data.
# This way you do not have to find out what to replace them with, and there is a good chance you do not need them to do your analyses.
# Example
# Delete rows where "Duration" is higher than 120:
abc = pd.read_csv("dirtydata.csv")
abc['Date'] = pd.to_datetime(abc['Date'])
abc.dropna(subset=['Date'], inplace = True)
for y in abc.index:
if abc.loc[y, "Duration"] > 120:
abc.drop(y, inplace = True)
print(abc.to_string())
|
'''
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
'''
class Solution(object):
def reconstructQueue(self, people):
if not people: return []
# obtain everyone's info
# key=height, value=k-value, index in original array
peopledct, height, res = {}, [], []
for i in range(len(people)):
p = people[i]
if p[0] in peopledct:
peopledct[p[0]] += (p[1], i),
else:
peopledct[p[0]] = [(p[1], i)]
height += p[0],
height.sort() # here are different heights we have
# sort from the tallest group
for h in height[::-1]:
peopledct[h].sort()
for p in peopledct[h]:
res.insert(p[0], people[p[1]])
return res
|
class Student(object):
def __init__(self, name, gpa, age):
self.name = name
self.gpa = gpa
self.age = age
def __str__(self):
return "Name: %s GPA: %f Age: %d" % (self.name, self.gpa, self.age)
def __lt__(self, other):
""" comparison based on:
https://piazza.com/class/idrrytrfdew2ns?cid=23
"""
return any([self.name < other.name,
self.name == other.name and self.age < other.age,
self.name == other.name and self.age == other.age and
self.gpa < other.gpa])
def __eq__(self, other):
return all([self.name == other.name, self.gpa == other.gpa,
self.age == other.age])
def __hash__(self):
return hash((self.name, self.age, self.gpa))
|
from student import Student
from random import shuffle
import unittest
def custom_cmp(x, y):
if cmp(x.gpa, y.gpa):
return cmp(x.gpa, y.gpa)
elif cmp(x.name, y.name):
return cmp(x.name, y.name)
else:
return cmp(x.age, y.age)
class StudentTests(unittest.TestCase):
def test__str__(self):
matt = Student("Matt", 4.000000, 24)
self.assertEqual(str(matt), "Name: Matt GPA: 4.000000 Age: 24")
def test__lt__(self):
jingwen = Student("Jingwen", 3.800000, 26)
yuhao = Student("Yuhao", 3.800000, 27)
matt = Student("Matt", 4.000000, 24)
younger_matt = Student("Matt", 4.000000, 23)
self.assertTrue(jingwen < matt) # compare gpa
self.assertTrue(jingwen < yuhao) # compare name
self.assertTrue(younger_matt < matt) # compare age
def test__eq__(self):
jingwen = Student("Jingwen", 3.800000, 26)
yuhao = Student("Yuhao", 3.800000, 27)
matt = Student("Matt", 4.000000, 24)
other_matt = Student("Matt", 4.000000, 24)
self.assertFalse(jingwen == yuhao)
self.assertFalse(jingwen == matt)
self.assertFalse(yuhao == matt)
self.assertTrue(matt == other_matt)
def test__hash__(self):
matt = Student("Matt", 4.000000, 24)
other_matt = Student("Matt", 4.000000, 24)
self.assertNotEqual(id(matt), id(other_matt)) # two different objects
self.assertEqual(hash(matt), hash(other_matt)) # still same hash
def test_sorted(self):
jingwen = Student("Jingwen", 3.800000, 26)
younger_matt = Student("Matt", 4.000000, 23)
dumber_matt = Student("Matt", 3.800000, 24)
matt = Student("Matt", 4.000000, 24)
yuhao = Student("Yuhao", 3.800000, 27)
students = [jingwen, younger_matt, dumber_matt, matt, yuhao]
expected_order = [jingwen, younger_matt, dumber_matt, matt, yuhao]
shuffle(students)
self.assertFalse(all([current == expected for current, expected in
zip(students, expected_order)]))
sorted_order = sorted(students)
self.assertTrue(all([current == expected for current, expected in
zip(sorted_order, expected_order)]))
def test_dict(self):
jingwen = Student("Jingwen", 3.800000, 26)
yuhao = Student("Yuhao", 3.800000, 27)
matt = Student("Matt", 4.000000, 24)
other_matt = Student("Matt", 4.000000, 24)
students = [jingwen, yuhao, matt]
d = {}
for student in students:
d[student] = student.name
self.assertNotEquals(id(matt), id(other_matt))
self.assertEquals(d[other_matt], matt.name)
self.assertEquals(d[matt], matt.name)
self.assertEquals(d[jingwen], jingwen.name)
self.assertEquals(d[yuhao], yuhao.name)
def test_array(self):
jingwen = Student("Jingwen", 0.000000, 26)
yuhao = Student("Yuhao", 1.000000, 21)
matt = Student("Matt", 2.000000, 24)
daniel = Student("Daniel", 3.000000, 20)
chuck = Student("Chuck", 4.000000, 24)
students = [jingwen, yuhao, matt, daniel, chuck]
expected_order = [jingwen, yuhao, matt, daniel, chuck]
shuffle(students)
self.assertFalse(all([current == expected for current, expected in
zip(students, expected_order)]))
sorted_order = sorted(students, cmp=lambda x, y: custom_cmp(x, y))
self.assertTrue(all([current == expected for current, expected in
zip(sorted_order, expected_order)]))
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(StudentTests)
unittest.TextTestRunner(verbosity=2).run(suite)
|
print('Ingresa un numero, y te dare todos los naturales hasta él')
entrada = int(input())
for i in range(entrada+1):
print(i)
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
lst1=[]
def lst_sqre(lst):
for i in lst:
lst1.append(i*i)
return lst1
# In[2]:
lst_sqre([1,3,5,7,8])
# In[4]:
lst=[1,2,3,4,5,6,7,8]
# In[5]:
lst1=[i*i for i in lst]
print(lst1)
# In[8]:
lst1=[i*i for i in lst if i%2!=0]
print(lst1)
# In[ ]:
|
#!/usr/bin/env python
# coding: utf-8
# In[6]:
class Teach:
def __init__(self,n,w):
self.name=n
self.work=w
def do_work(self):
if self.work=="teacher":
print(self.name,"teaching java")
elif self.work=="labasst":
print(self.name," teaching you practical")
def speaks(self):
print(self.name,"how are you...")
chb=Teach("chirag bhatt","teacher")
chb.do_work()
chb.speaks()
dhb=Teach("Navin patel","labasst")
dhb.do_work()
dhb.speaks()
# In[ ]:
|
"""asd"""
# from random import choice, randrange
from math import sin, cos
from drawable_item import DrawableItem
from random import randrange
class Enemy(DrawableItem):
"""Enemy is something that moves..."""
def __init__(self, hero, background):
self.hero = hero
super(Enemy, self).__init__('batwing.png', background.boundaries)
self.background = 0
self.background = background
self.angle = 0
self.delay = 0
self.position['vert'] = background.size['h']/2
def move(self):
self.angle = (self.angle + randrange(-1, 1)) % 360 # circle the hero
if self.background.x > -self.size['w']:
self.position['hori'] = self.background.x
else:
self.position['hori'] = self.background.x1
self.position['hori'] += cos(self.angle)*50
self.position['vert'] += sin(self.angle)*50
self.delay = self.delay % 10
vertical_displacement = randrange(-100, 100) if self.delay == 0 else 0
bottom = self.background.size['h']-self.size['h']
if not (0 <= self.position['vert']+vertical_displacement <= bottom):
vertical_displacement *= -1
self.position['vert'] += vertical_displacement
self.position['vert'] = max(0, self.position['vert'])
self.position['vert'] = min(bottom, self.position['vert'])
|
class PriorityQueue:
"""Implementation of priority queue"""
def __init__(self):
self.array = []
self.heap_size = 0
def _sift_up(self, index):
parent_node = index//2
if index == 1 or self.array[index-1] <= self.array[parent_node-1]:
return
self.array[index-1], self.array[parent_node-1] =\
self.array[parent_node-1], self.array[index-1]
self._sift_up(parent_node)
def _sift_down(self, array, root):
left = root*2 + 1
right = root*2 + 2
largest = root
if left < self.heap_size and array[left] > array[largest]:
largest = left
if right < self.heap_size and array[right] > array[largest]:
largest = right
if largest != root:
array[root], array[largest] = array[largest], array[root]
self._sift_down(array, largest)
return
def insert(self, element):
self.array.append(element)
self.heap_size += 1
self._sift_up(self.heap_size)
return
def extract_max(self):
max_element = self.array[0]
self.heap_size -= 1
if self.heap_size < 1:
self.array = []
return max_element
self.array[0] = self.array.pop(-1)
self._sift_down(self.array, 0)
return max_element
if __name__ == "__main__":
n = int(input())
a = PriorityQueue()
for i in range(n):
try:
action, element = input().split(" ")
a.insert(int(element))
except ValueError:
max_element = a.extract_max()
print(max_element)
|
import unittest
from binary_search import binary_search
class TestBinarySearch(unittest.TestCase):
def test_1(self):
array = [1, 5, 8, 12, 13]
numbers = [8, 1, 23, 1, 11]
result = []
for n in numbers:
result.append(binary_search(array, n))
self.assertEqual(result, [3, 1, -1, 1, -1])
if __name__ == '__main__':
unittest.main()
|
# 求100以内所有的奇数之和
# 获取所有100以内数
# i = 0
# # 创建一个变量,用来保存结果
# result = 0
# while i < 100 :
# i += 1
# # 判断i是否是奇数
# if i % 2 != 0:
# result += i
# print('result =',result)
# 获取100以内所有的奇数
# i = 1
# while i < 100:
# print(i)
# i += 2
# 求100以内所有7的倍数之和,以及个数
i = 7
# 创建一个变量,来保存结果
result = 0
# 创建一个计数器,用来记录循环执行的次数
# 计数器就是一个变量,专门用来记录次数的变量
count = 0
while i < 100:
# 为计数器加1
count += 1
result += i
i += 7
print('总和为:',result,'总数量为:',count)
|
# 水仙花数是指一个 n 位数(n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身(例如:1**3 + 5**3 + 3**3 = 153)。
# 求1000以内所有的水仙花数
# 获取1000以内的三位数
i = 100
while i < 1000:
# 假设,i的百位数是a,十位数b,个位数c
# 求i的百位数
a = i // 100
# 求i的十位数
# b = i // 10 % 10
b = (i - a * 100) // 10
# 求i的个位数字
c = i % 10
# print(i , a , b , c)
# 判断i是否是水仙花数
if a**3 + b**3 + c**3 == i :
print(i)
i += 1
|
def sub_num(a,b):
return a-b
print(sub_num(1,3)) # -2
def mul_num(a,b):
return a*b
print(mul_num(1,3)) # 3
|
#1. 1,2,3,4 요소를 가진 배열을 생성하고 다음을 구현하라.
list1 = [1,2,3,4]
##생성한 배열에 5,6,7,8을 추가하라.
list1 = list1 + [5,6,7,8]
print(list1)
##생성한 배열의 인덱스가 4인 값을 찾아라.
print(list1[4])
##생성한 배열의 인덱스가 3~6인 값을 찾아라.
print(list1[3:6])
#2. “I love you, John!”이라는 문자열을 생성하고 다음을 구현하라.
##위 문자열을 공백을 기준으로 나누어 배열 a에 저장하라.
##John이 들어있는 배열은 a의 몇 번째 배열에 저장되어 있는가.
##배열 a의 길이를 구하라.
str1 = "I love you, John!"
a = str1.split(" ")
print(a)
print("a의 길이:", len(a))
|
"""sierpinski_triangle.py
Author: Harman Suri
Nov 15, 2020
Description: Draws the Sierpinski Triangle fractal by using the turtle
module and recursion.
"""
import turtle
# creates new turtle
drawer = turtle.Turtle()
# height and width of screen
h = 600
w = 600
# creates new screen with custom width and height
screen = turtle.Screen()
screen.setup(width=w, height=h)
# makes screen not re-sizable
screen.cv._rootwindow.resizable(False, False)
def draw_triangle(level, ax, ay, bx, by, cx, cy):
"""Based on a level and 3 points, the sierpinski triangle is drawn to a certain iteration
using a recursive function that draws 3 new triangles based on the midpoints of the old triangle.
Args:
level: specify which iteration to draw the sierpinski triangle.
ax, ay, bx, by, cx, cy: x and y coordinates of the three points needed to form a triangle
"""
if level <= 1:
# final triangle when level is 1
drawer.penup()
drawer.goto(ax, ay)
drawer.pendown()
drawer.goto(bx, by)
drawer.goto(cx, cy)
drawer.goto(ax, ay)
else:
drawer.penup()
# AB midpoint
abMidX = (ax + bx) / 2
abMidY = (ay + by) / 2
# BC midpoint
bcMidX = (bx + cx) / 2
bcMidY = (by + cy) / 2
# CA midpoint
caMidX = (cx + ax) / 2
caMidY = (cy + ay) / 2
# main triangle at current level
drawer.goto(ax, ay)
drawer.pendown()
drawer.goto(bx, by)
drawer.goto(cx, cy)
drawer.goto(ax, ay)
# draw 3 new triangles based of midpoints of the current triangle
draw_triangle(level - 1, ax, ay, abMidX, abMidY, caMidX, caMidY)
draw_triangle(level - 1, bx, by, bcMidX, bcMidY, abMidX, abMidY)
draw_triangle(level - 1, cx, cy, caMidX, caMidY, bcMidX, bcMidY)
# sets turtle speed to max
drawer.speed("fastest")
# asks user for the iteration of sierpinski triangle
iteration = int(
input("What iteration of the sierpinski triangle would you like to see?"))
# triangles initial coordinates are based on the width and height of the screen to get a perfect triangle
draw_triangle(iteration, 0, h - 400, -w + 400, -h + 450, w - 400, -h + 450)
# return turtle to origin
drawer.penup()
drawer.goto(0, 0)
turtle.done()
|
from cs50 import SQL
from sys import argv
if len(argv) != 2: # Checks for the correct amount of argv
print("Usage: python roster.py house")
exit()
db = SQL("sqlite:///students.db")
# Reads all the info the program is going to print from the table
roster = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", argv[1])
# For each students prints out the info
for student in roster:
if student["middle"] == None: # If the student has no middle name it is not printed out
print(student["first"], student["last"] + ",", "born", student["birth"])
else:
print(student["first"], student["middle"], student["last"], student["birth"])
|
"""
classes.py
This is a rough prototype of the discrete data entities in this project. It's intended more to be a reference than a functioning prototype, but it should run and you should be able to perform basic tests with it for your own understanding.
I'm making it for mine too, to start. It's to make the way ahead clear. Some people can't intuitively get the math, and I can't express math with mathematical language with any efficiency, but I can build this fucking thing.
"""
print("classes.py began successfully")
def IDMAKER(Keyspace):
"""
This is a function to generate integer ID's that will probably be unique within a given keyspace. Basically just sequential keys.
assumes a UTF-8-formatted ID. Just for simplicity."""
try:
print(Keyspace)
Keyspace = Keyspace + 1
return(int(Keyspace))
except:
print("something's fucked! \n\n Value entered was: " + Keyspace + "\n\nHappy Debugging!")
# IDMAKER("10")
class User:
"""
Users are people. People have money, content, and computers.
This class is intended to accomodate four distinct sets of behavior:
Makers
Makers are the people who create content and put it up for sale. The "make" set of functionality includes:
CRUD of content
CRUD of media
Buyers
Buyers are customers. People who pay, through the network, for content hosted by it.
Pirates
Pirates are users who have content that we can't determine how they got or verify that They've paid for. As far as identical content goes, they can supply and earn from content pieces that are identical to the pieces sold by the network.
Note that a pirate is only a pirate in relation to a specific piece of binary data. by default, the intention is to have any other data they own pay for the data they don't.
Inmates
Inmates are abusive users who seek to undermine the network deliberately. This can be anything from trying to steal other user's data or content to adding backdoors to content or what have you. The intention is to not simply treat this as an error, but to make the network actively hostile to abuse and even revenge-seeking, to the scale of the damage done (corrupting inmate data, adding backdoors back into their systems with the very data they steal through their own backdoor, recuperating financial losses or inflicting expenses upon them to undo any benefit they gain, etc).
Do unto others, after all.
"""
UID = "" # Unique Identification. every user is unique.
Username = "" # username
Email = "" # email address
PhoneNumber = "" # Phone number, stored as a string, formatted as [country][region][number]
# User Cultural and National Identity attributes
Languages = [] # list of languages user speaks
Interface_Language = "" # Still, everybody has a preferred default.
Time_Zone = "" # The user's time zone <default London, UK>
Country = "" # The national borders this user is logged into from within
# Website attributes
Owned_Content = [] # list of content this user owns
Held_Content = [] # list of content this user doesn't own but has anyway
# Network attributes
User_Nodes = [] # list of all nodes that this user has logged in on
# User Fiscal Attributes
User_Local_Currency = "" # what the default unit is for earned income
Earned_Income = 0.0 # How much money a user has earned
Accumulated_Debt = 0.0 # How much the user has that they still need to pay for
Connected_Accounts = [] # List of accounts that the user can make a withdrawal to
# User Functions
def __init__(self, Keyspace, Username, email):
"""
in production, this needs to handle user acount generation and adding users to the program logic from memory. For now, though, the idea is to start with a function that can be called to generate "test users".
"""
self.UID = IDMAKER(Keyspace)
self.Username = Username
self.Email = email
# self.Time_Zone = Time_Zone
# str function, so that
def __str__(self):
print(self.UID)
return (self.UID)
def CalculateDebt(Owned_Content, Held_Content, Earned_Income):
#self.Accumulated_Debt =
pass
class Node:
"""
nodes are computers on the network.
A node holds data (the content pieces, assembled into the content that the user bought or pirated, which are supplied to the network), processes input (user Authentication), and takes actions (sending and receiving content pieces, authenticating with the central server, etc).
"""
mac_address = "" # all computers have one, although spoofing is a risk
user_credentials = "" # a representation of the username/pass the node proves it has
content = [] # a list of the content items a node has (human abstraction 'content')
pieces = [] # a list of the content pieces node has (network 'content' data)
#Node internal attributes
# File_Path is commented out because it's unneccessary for local testing
#File_Path = "" # default directory. Should have a 'gitignore' knockoff for local files.
Local_Files = [] # list of local files
#server and network attributes
Local_Keys = [] # list of keys node possesses
# Default Functions
def __init__(self, mac, usercred):
self.mac_address = mac
self.user_credentials = usercred
def __str__(self):
return(self.mac_address, self.user_credentials)
def read(self):
pass
def update(self):
pass
def delete(self):
pass
# Network behavior functions
def upload(self, target, ContentPiece):
pass
def Bawkserver(self, recipientkey, ContentPiece): #Inform server of successful receipt of contentpiece with x key
pass
def getkeys (self, credentials): #get a new set of authentication keys from the server for uploading
pass
class Content:
"""
Content is the stuff people make and put up for sale.
The structure of content is this:
content is a "doubletree", where branches dictate version and platform.
"version" branches dictate *specific attributes*-
"platform" branches dictate *specific implementations*- mac vs Windows vs Linux, etc
This stricture sounds complicated, but the idea is to implement versions on platform, and so there are two tools to update
"""
#Base Attributes
Content_Name = "" # Content Name, for humans to refer to it by.
Content_ID = "" # Content unique identifier, for machines to use.
Content_Description = "" # a brief (tweet length) description of what it is, for humans to use
Content_PieceTree = "" # A tree that describes the structure of the content. This is what becomes a tracker on the server
#Fiscal attributes
Content_Price = 0.0 # Monetary price to buy a single instance of the content.
Content_version = "" # Version ID of this content.
# TODO: version control. For now, new versions are new content.
def __init__(Name, Owner, ID, Description):
self.Content_Name = Name
self.Content_ID = ID
self.Content_Description = Description
def read(self):
pass
def update(self):
pass
def delete(self):
pass
def Price_Setting(price, Content):
print("build successful")
class ContentPiece:
"""
A ContentPiece is the individual packet of data transferred between nodes of the network.
"""
Piece_ID = "" # UniqueID of this piece.
Piece_FormatType = "" # The filetype (size- determined compression block, discrete file, etc)
Size = 0 # integer, if you can type it. It needs to represent the size, in bytes
Value = 0.0 # the value of one successful transfer. Used to calculate payment.
# data members where client and server use the same variables, but for local tasks
Seeders = 0 # int or longint, depending on scale
leechers = 0 # ""
Downloaders = 0 # ""
Pirates = 0 # integer number of pirates uploading this piece
LastCheck = "" # datetime of the last time these variables were updated
# data members used only by the client
successful_uploads = 0 # tracking successful uploads for money.
attempted_uploads = 0 # tracking unsuccessful upload attempts
network_density = 0 # tracking number of nodes attempting to upload this piece
# data members used only be the server
#initialize
def __init__(self, ID, Size, Value):
self.Piece_ID= ID
def read(self):
pass
def update(self):
pass
def delete(self):
self.dispose()
class Media:
"""
Media is web stuff that presents the content for sale on the website. By default, it describes HTML and javascript, but this is a major security hole. Maybe some workaround with another markup will work better. But for now, the prototype should show vanilla HTML. I'll add more constraints as they are needed. **More Research Needed**
"""
Media_ID = "" # tracking ID.
Media_Name = "" # a name for humans to track.
Media_Val = "" # the actual stuff that the media represents.
Media_Type = "" # the actual type of the media in question
Content_ID = "" # ID of the content the media is in relation to
#security stuff, so different people can have different media
Media_Owner_Account = "" # ID of the User who owns the content/media in question
def __init__(self, owner):
self.Media_Owner_Account = owner
pass
def read(self):
pass
def update(self):
pass
def delete(self):
pass
class Authentication:
"""
Authentication is how the network tracks who's who, has what, and has sent which, when and to whom. It consists of a set of keys that are recycled, and the combinations of which correlate to an interior database for record keeping. there are other parts to this, mostly based around making it difficult to predict, intercept, decipher, and use, even in long-term attacks, and so for the long term players the idea is to send them on a rat race of the same data over and over, and to change what it means every time. In old-school encryption terms, the idea is to keep anybody outside at a permanent depth of one (ref leo marks between silk and cyanide).
"""
# Attributes
UniqueID = "" # the ID of the Authentication Key
UserID = "" # the ID of the user who holds it
log = {} # a log of instances where this key has been used to sign a transfer
def __init__(self):
pass
def read(self):
pass
def update(self):
pass
def delete(self):
pass
class Money:
"""
Money is the stuff everybody wants.
A "Money" is an object that describes the value for a ContentPiece. Value is determined by dividing the content by the number of bits- or failing that, bytes- arriving at a base value per bit- and then this is multiplied by the size of each ContentPiece to determine the size of each of their moneys.
Linguistic note for humans: singular "Money", plural "Moneys".
This class describes arbitrary amounts of value, in specific currencies, for specific ContentPiece instances. This is important, because a foundational premise of this network is the idea that transactions can be infinitely arbitrarily sized- to the extreme low end, and to the extreme high end.
When Content iterates (new versions), Moneys need to be recalculated.
Hmm. That smells like bullshit. Maybe there's a better way than that.
Anyway, this is a server attribute. Moneys are assigned centrally, upon verification. A transfer that can't be verified can't be paid for, logically, because it opens the system up to paying out outputs that have no input.
However, there is one thing the client side of the network can know about money: The amount. This allows a client node to make decisions based on fiscal outcomes. This is how money is used in the network as a dimension of data along which more efficient transfers can be optimized, rather than simply the scarcity model used in traditional peer networks.
"""
# base attributes
Currency_ID = ""
Currency_Name = ""
Content_ID = ""
# Server-only Attributes
Cash_Value = 0.0 #this is a float by default (provisional early research)
# Client side attribuets
HashKey = ""
"""
User_Keyspace = 0
TestUser1 = User(User_Keyspace, "derp", "derp")
TestUser2 = User(User_Keyspace, "derp", "derp")
TestUser1.__str__()
TestUser2.__str__()
TestUser3 = User(User_Keyspace, "derp", "derp")
TestUser3.__str__()
"""
|
from calendar_automation import get_calendar_service
def calendar_list():
service = get_calendar_service()
print('\nHere are the names of your calendars:\n')
calendars_result = service.calendarList().list().execute()
calendars = calendars_result.get('items')
if not calendars:
print('No calendars found.')
for calendar in calendars:
summary = calendar['summary']
primary = "(Primary)" if calendar.get('primary') else ""
print("%s\t%s" % (summary, primary))
calendar_name = input("\nWhat is the name of the calendar you would like to use?: ")
# Gets the calendar id given the calendar name:
return str(next(item for item in calendars if item['summary'] == calendar_name)['id'])
|
def main():
count = 0
mylist = []
while count < 10:
element = input("Enter the element of list: ")
try:
element = int(element)
except:
print("Invalid input. Enter again.")
else:
count +=1
mylist.append(element)
count = len(mylist)-1
flag = True
while flag == True: #It will end the loop when there is no swapping
for i in range(count): #this loop is used for the number of times a list is sorted
for j in range (count): #this loop is used for moving the higest number towards the end.
flag = False
if mylist[j] > mylist[j+1]:
temporary = mylist[j]
mylist[j] = mylist[j+1]
mylist[j+1] = temporary
print(mylist)
flag = True
count -=1
print("The sorted list is:",mylist)
main()
|
def leng(a):
required = len(a)
return required
def two():
string = input("Enter a string: ")
print(leng(string))
two()
|
def main():
count = 0
mylist = []
while count < 10:
element = input("Enter the element of list: ")
try:
element = int(element)
except:
print("Invalid input. Enter again.")
else:
count +=1
mylist.append(element)
for i in range(len(mylist)-1): #this loop is used for the number of times a list is sorted
for j in range (len(mylist)-1): #this loop is used for moving the higest number towards the end.
if mylist[j] > mylist[j+1]:
temporary = mylist[j]
mylist[j] = mylist[j+1]
mylist[j+1] = temporary
print(mylist)
print("The sorted list is:",mylist)
main()
|
def main():
#taking two variables as 0 and 1 to start the series
var01 = 0
var02 = 1
fibonacci = [var01,var02] #The starting values of the series are included in the list
for var in range(1,10):
var03 = var01 + var02
var01 = var02
var02 = var03
fibonacci.append(var03) #appending each new value in the list
print(fibonacci)
main()
|
def main():
listing = []
num = input("enter a number between 10-100: ")
try:
num = int(num)
except:
print("invalid input.")
num = 0
while (num>= 10) and (num <= 100):
if not(num in listing):
listing.append(num)
num = input("enter a number between 10-100: ")
try:
num = int(num)
except:
print("invalid input.")
num = 0
count = 0
while count < len(listing):
print(listing[count])
count += 1
main()
|
def reverse(a):
required1 = a.find(" ")
if required1:
reversing1 = a[required1::-1]
required2 = a.find(" ",required1+1)
if required2:
reversing2 = a[required2:required1:-1]
required3 = a.find(" ",required2+1)
if required3:
reversing3 = a[required3:required2:-1]
required4 = a.find(" ",required3+1)
if required4:
reversing4 = a[required4:required3:-1]
required5 = a.find(" ",required4+1)
if required5:
reversing5 = a[required5:required4:-1]
required6 = a.find(" ",required5+1)
if required6:
reversing6 = a[required6:required5:-1]
required7 = a.find(" ",required6+1)
if required7:
reversing7 = a[required7:required6:-1]
required8 = a.find(" ",required7+1)
if required8:
reversing8 = a[required8:required7:-1]
required9 = a.find(" ",required8+1)
if required9:
reversing9 = a[required9:required8:-1]
required10 = a.find(".",required9+1)
if required10:
reversing10 = a[required10:required9:-1]
if required1 == -1:
print(reversing1)
if required2 == -1 and required1 != -1:
print(reversing1+reversing2)
if required3 == -1 and required2 != -1:
print(reversing1+reversing2+reversing3)
if required4 == -1 and required3 != -1:
print(reversing1+reversing2+reversing3+reversing4)
if required5 == -1 and required4 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5)
if required6 == -1 and required5 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5+reversing6)
if required7 == -1 and required6 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5+reversing6+reversing7)
if required8 == -1 and required7 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5+reversing6+reversing7+reversing8)
if required9 == -1 and required8 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5+reversing6+reversing7+reversing8+reversing9)
if required10 == -1 and required9 != -1:
print(reversing1+reversing2+reversing3+reversing4+reversing5+reversing6+reversing7+reversing8+reversing9+reversing10)
def main():
string = input("Enter a string of not more that 10 words:")
reverse(string)
main()
|
"""
判断输入的边长能否构成三角形,如果能则计算出三角形的周长和面积
Version: 0.1
Author: Robert Xu
"""
first_edge = float(input('请输入第一条边的长度:'))
second_edge = float(input('请输入第二条边的长度:'))
third_edge = float(input('请输入第三条边的长度:'))
if first_edge + second_edge > third_edge and first_edge + third_edge > second_edge and second_edge + third_edge > first_edge:
print('周长:', first_edge + second_edge + third_edge)
p = (first_edge + second_edge + third_edge) / 2
area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
print('面积:', area)
else:
print("不能构成三角形")
|
def without_string(base, remove):
output = []
normalised_remove = remove.lower()
remove_length = len(normalised_remove)
normalised_base = base.lower()
base_length = len(base)
i = 0
while i < base_length:
candidate = normalised_base[i:i + remove_length]
if candidate == normalised_remove:
i += remove_length
continue
output.append(base[i])
i += 1
return ''.join(output)
print without_string("Hello there", "llo"), "Should be He there"
print without_string("Hello there", "e"), "Should be Hllo thr"
print without_string("Hello there", "x"), "Should be Hello there"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.