text stringlengths 37 1.41M |
|---|
# temp_convert_function.py
# Matthew Shaw
# Sunday, 4 October 2015 14:40:03
def c2f(celcius):
fahrenheit = celcius * 9/5 + 32
print (celcius, "degrees Celcius is", fahrenheit , "degrees fahrenheit")
celcius = float(input("Please enter the tempreature to be converted: "))
c2f(celcius)
|
#quadratic solver
from math import sqrt
a = int(input('Enter a value for a: '))
b = int(input('Enter a value for b: '))
c = int(input('Enter a value for c: '))
discriminant = b*b - 4*a*c
discriminant = sqrt(discriminant)
xplus = (-b + discriminant) / (2*a)
xminus = (-b - discriminant) / (2*a)
print ('The roots of ax **2 + bx + c = 0 with',
'a =', a, ' b =', b ,' c =', c, 'are\n\n', xminus , xplus)
|
a = [3, 4, 5, 6]
b = ['a', 'b', 'c', 'd']
def zipper(a,b):
newZip = []
if len (a) == len(b):
for i in range(len(a)):
newZip.append([a[i], b[i]])
print (newZip)
if len(a)!= len(b):
print("lists do not match")
zipper(a,b)
|
from math import sqrt
prev = 1
L = [prev]
for n in range (19):
rooted_number = sqrt(prev + 1)
L.append(rooted_number)
prev = rooted_number
for i in L:
print(i)
|
user_sum = input("keep entering numbers, end with q or Q: ")
total = []
while user_sum != 'q':
total.append(int(user_sum))
user_sum = input("keep entering numbers, end with q or Q: ")
print(sum(total)/len(total))
|
S = 'A'
n = 10
rules = {'A':'AB', 'B' : 'A'}
def srs_print(S):
"""Re-write an axiom according to given rules"""
newaxiom = ''
for i in S:
## if i in rules.items():
## newaxiom +=
for k, v in rules.items():
if i ==k:
newaxiom += v
## if i is 'B':
## newaxiom +='A' #append newaxiom according to the rules of rewriting the string
S = newaxiom
## print(axiom) Uncomment to see the axiom re-written each time
return S #(above line can crash computer with 30 re-writes)
def give_back(S, n):
'''Keep re-writing an axiom a number of times by calling the function algae'''
for i in range (n):
S = srs_print(S)
return S
print( S)
print(give_back(S, n))
print(len(give_back(S, 30)))
|
# Program name: Ch 11 Example 2 transfer film records.py
# transfer records to film database from text file
import sqlite3
# function to read text records and store in record filmDBRec[]
def readTextFile(filmFile):
connection = sqlite3.connect("./Chapt 11/MyFilms.db")
cursor = connection.cursor()
numRecs = 0
filmDBRec = []
filmTextRec = filmFile.readline()
while filmTextRec != "":
numRecs += 1
field = filmTextRec.split(",")
ID = field[0]
title = field[1]
yearReleased = field[2]
rating = field[3]
duration = int(field[4])
genre = field[5]
# strip off the newline character \n from genre
lastchar = len(genre)- 1
genre = genre[0:lastchar]
# append fields to the list variable filmDBRec ton construct the record to be inserted
filmDBRec.append(ID)
filmDBRec.append(title)
filmDBRec.append(yearReleased)
filmDBRec.append(rating)
filmDBRec.append(duration)
filmDBRec.append(genre)
# insert this record into the database
cursor.execute("INSERT INTO tblFilms VALUES (?,?,?,?,?,?)", filmDBRec)
connection.commit()
# empty the list of fields ready for next record
filmDBRec = []
# read the next record from the text file
filmTextRec = filmFile.readline()
connection.close
return numRecs
# main
filmFile = open("./Chapt 11/films.txt", "r")
numRecs = readTextFile(filmFile)
print("\n", numRecs, "records transferred")
# close the text file
filmFile.close() |
# Creates a table called tbleTemps in database CityTemperatures.db
# then adds temperatures for several cities to tblTemps
import sqlite3
conn = sqlite3.connect("./Chapt 11/CityTemperatures.db")
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE tblTemps
(city TEXT,
temperature INTEGER,
localTime TEXT,
primary key (city))
""")
# insert multiple records
tblTemps = [('London',7,'1200'),
('Accra', 30,'1200'),
('Baghdad',20,'1500'),
('Winnipeg',-12,'0600'),
('New York',14,'0700'),
('Nairobi',27,'1500'),
('Sydney',22,'2300')
]
cursor.executemany("INSERT INTO tblTemps VALUES (?,?,?)",tblTemps)
# save data to database
conn.commit()
conn.close()
print("Table successfully created")
|
"""
You are climbing a stair case. it takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
"""
import unittest
def climb_stairs(n):
# n represents number of steps on the stairs
prev_steps = {1: 1,
2: 2}
if n not in prev_steps:
prev_steps[n] = climb_stairs(n-1) + climb_stairs(n-2)
return prev_steps[n]
class Test(unittest.TestCase):
def test_climb_stairs(self):
self.assertEqual(climb_stairs(5), 8)
self.assertEqual(climb_stairs(1), 1)
if __name__ == '__main__':
unittest.main() |
"""
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
"""
def reorder(head):
if not head:
return
slow, curr, fast = head, head, head
prev = None
while fast != None:
if fast.next == None:
break
slow = slow.next
fast = fast.next.next
fast = slow.next
slow.next = None
# reverse second half
while fast != None:
hold = fast.next
fast.next = prev
prev = fast
fast = hold
while prev != None:
hold = curr.next
curr.next = prev
prev = prev.next
curr.next.next = hold
curr = curr.next.next
|
"""
Invert the tree given the root
"""
def invert_tree(root):
if root:
stack = [root]
else:
return root
while len(stack) > 0:
curr = stack.pop()
hold = curr.left
curr.left = curr.right
curr.right = hold
if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)
return root
def invert_tree_recursive(root):
if root:
curr = root
else:
return root
hold = curr.left
curr.left = curr.right
curr.right = hold
if curr.left:
invert_tree_recursive(curr.left)
if curr.right:
invert_tree_recursive(curr.right)
|
"""
Write a program that outputs the string representation of numbers from 1 to n
Multiples of three should output Fizz
Multipes of five should output Buzz
Multiples of three and five should output FizzBuzz
"""
def fizz_buzz(n):
for num in range(1, n+1):
if num % 3 == 0 and num % 5 == 0:
print 'FizzBuzz'
elif num % 3 == 0:
print 'Fizz'
elif num % 5 == 0:
print 'Buzz'
else:
print num
fizz_buzz(15) |
import pygame
from pygame import sprite
import sys
import random
import time
import math
TIME_TO_WAIT = 100
DROP_ALL = False
SHOTS = []
MARCH_RIGHT = True
PLAYING_GAME = True
pygame.init()
class Move(sprite.Sprite):
def __init__(self):
pass
def move_up(self):
self.rect.y -= 1
pass
def move_down(self):
self.rect.y += 1
pass
def move_left(self):
if self.rect.x > 0:
self.rect.x -= 1
pass
def move_right(self):
if self.rect.x < 590:
self.rect.x += 1
pass
def load_image(name):
image = pygame.image.load(name).convert_alpha()
return image
class Alien(pygame.sprite.Sprite):
def __init__(self, image_name1, image_name2, Value):
super().__init__()
self.images = []
self.index = 0
self.images.append(load_image(image_name1))
self.images.append(load_image(image_name2))
self.image = self.images[self.index]
self.rect = self.image.get_rect()
self.score = Value
def Drop(self):
self.rect.y += 10
def update(self):
'''This method iterates through the elements inside self.images and
displays the next one each tick. For a slower animation, you may want to
consider using a timer of some sort so it updates slower.'''
self.index += 1
global MARCH_RIGHT
global DROP_ALL
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
if self.rect.x >= 600 and MARCH_RIGHT == True:
MARCH_RIGHT = False
DROP_ALL = True
elif self.rect.x <= 10 and MARCH_RIGHT == False:
MARCH_RIGHT = True
DROP_ALL = True
if MARCH_RIGHT == True:
self.rect.x += 20
else:
self.rect.x -= 20
class PlayerShip(sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("resources\images\ship.png").convert_alpha()
self.rect = self.image.get_rect()
self.score = 0
class Shot(sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("resources\images\shotFriendly.png").convert_alpha()
self.rect = self.image.get_rect()
def update(self, pos):
self.rect = pos
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
DIMENSIONS = (640, 480)
RADS = 0
ALIENS_FORMATION = [
['resources\\images\\InvaderA.png', 'resources\\images\\InvaderA1.png', [220, 60]],
['resources\\images\\InvaderB.png', 'resources\\images\\InvaderB1.png', [225, 100]],
['resources\\images\\InvaderC.png', 'resources\\images\\InvaderC1.png', [220, 140]]
]
pygame.mouse.set_visible ( False )
screen = pygame.display.set_mode(DIMENSIONS)
all_aliens = pygame.sprite.Group()
all_offence = pygame.sprite.Group()
player_goup = pygame.sprite.Group()
target_group = pygame.sprite.Group()
shot_group = pygame.sprite.Group()
for v in ALIENS_FORMATION:
for i in range(5):
alien = Alien(v[0], v[1], 10)
alien.rect.x = v[2][0] + (50 * i)
alien.rect.y = v[2][1]
all_aliens.add(alien)
player = PlayerShip()
player.rect.x = 285
player.rect.y = 380
player_goup.add(player)
keys_pressed = { pygame.K_w: False, pygame.K_a: False, pygame.K_s: False, pygame.K_d: False, pygame.K_SPACE: True, pygame.K_RIGHT: False, pygame.K_LEFT: False }
score_font = pygame.font.SysFont("monospace", 15)
winner_font = pygame.font.SysFont("monospace", 75)
while PLAYING_GAME:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key in keys_pressed:
keys_pressed[event.key] = True
elif event.type == pygame.KEYUP:
if event.key in keys_pressed:
keys_pressed[event.key] = False
if keys_pressed[pygame.K_a] or keys_pressed[pygame.K_LEFT]:
Move.move_left(player)
elif keys_pressed[pygame.K_d] or keys_pressed[pygame.K_RIGHT]:
Move.move_right(player)
elif not keys_pressed[pygame.K_SPACE]:
shot = Shot()
shot.rect.x = player.rect.x + 25
shot.rect.y = player.rect.y
shot_group.add(shot)
keys_pressed[pygame.K_SPACE] = True
for shot in shot_group:
Move.move_up(shot)
aliens_hit_list = pygame.sprite.spritecollide(shot, all_aliens, True)
for alien in aliens_hit_list:
player.score += alien.score
alien.kill()
shot.kill()
alien_count = len(all_aliens.sprites())
for alien in all_aliens:
if TIME_TO_WAIT <= 0 and alien_count >= 0:
alien_count -= 1
alien.update()
if DROP_ALL and alien_count <= 0:
for alien in all_aliens:
alien.Drop()
if TIME_TO_WAIT <= 0 and alien_count <= 0:
TIME_TO_WAIT = 200
DROP_ALL = False
TIME_TO_WAIT -= 1
screen.fill(WHITE)
all_aliens.draw(screen)
all_offence.draw(screen)
player_goup.draw(screen)
target_group.draw(screen)
shot_group.draw(screen)
score_label = score_font.render("Score: {}".format(player.score), 1, BLACK)
screen.blit(score_label, ((DIMENSIONS[0] / 2) - score_label.get_rect().width / 2, 10))
if len(all_aliens.sprites()) == 0:
winner_label = winner_font.render("WINNER", 1, BLACK)
screen.blit(winner_label, ((DIMENSIONS[0]/2 - winner_label.get_rect().width /2, 10)))
# PLAYING_GAME = False
pygame.display.flip()
|
mylists = ["banana", "cherry", "apple"]
print(mylists)
item = mylists.sort()
print(mylists)
mylists.sort()
new_list = sorted(mylists)
print(mylists)
item = mylists.reverse()
print(mylists)
mylists2 = [5, True, "apple", "apple"]
print(mylists2)
item = mylists[0]
print(item)
for i in mylists:
print(i)
if "banana" in mylists:
print("Yes")
else:
print("No")
print(len(mylists))
mylists.append("Lemon")
print(mylists)
mylists.insert(1, "blueberry")
print(mylists)
item = mylists.pop()
print(item)
print(mylists)
item = mylists.remove("cherry")
print(mylists)
item = mylists.clear()
print(mylists)
ch = [0] * 5
print(ch)
myl = [1, 2, 3, 4, 5]
new = myl + ch
print(new)
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = mylist[1:5]
print(a)
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = mylist[:-5]
print(a)
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = mylist[::2]
print(a)
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = mylist[::-1]
print(a)
my1 = ["banana", "cherry", "apple"]
my2 = my1
my2.append("lemon")
print(my1)
print(my2)
my1 = ["banana", "cherry", "apple"]
my2 = my1.copy()
my2.append("lemon")
print(my1)
print(my2)
mylist = [1, 2, 3, 4, 5, 6]
sqaure = [i*i for i in mylist]
print(mylist)
print(sqaure)
|
#
# Project Euler: https://projecteuler.net/problem=4
#
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
# (Solution: )
#
def solve():
print(solve())
|
import turtle
from turtle import *
turtle.setup(1000, 600)
screensize(2000, 1200)
def r(a,color): #a es el ancho
fillcolor(color)
b = int(a/2)
begin_fill()
goto(a,0)
goto(a,a*2)
goto(a*3,0)
goto(a*4,0)
goto(a*2,a*2)
LinInv(a*2,a*5)
turtle.circle(-(b*3),180)
LinInv(a*2,a*5)
goto(0,a*5)
goto(0,0)
end_fill()
LinInv(a*2,a*3)
goto(a*2+5,a*3)
goto(a*2,a*3)
CirInv(-25,180)
fillcolor('white')
begin_fill()
turtle.circle(-25,180)
end_fill()
LinInv(a*2,a*4)
fillcolor('white')
begin_fill()
goto(a,a*4)
goto(a,a*3)
goto(a*2,a*3)
end_fill()
turtle.hideturtle()
return a*4
def LinInv(x,y):
penup()
goto(x,y)
pendown ()
def CirInv(x,y):
penup()
turtle.circle(x,y)
pendown ()
r(50,"green")
|
buildings = [0, 0, 3, 5, 2, 4, 9, 0, 6, 4, 0, 6, 0, 0]
result = 0
view_building = 0
for i in range(2, len(buildings) - 2):
if buildings[i] > buildings[i - 1] and buildings[i] > buildings[i - 2] and buildings[i] > buildings[i + 1] and \
buildings[i] > buildings[i + 2]:
max_building = max(buildings[i - 1], buildings[i - 2], buildings[i + 1], buildings[i + 2])
view_building = buildings[i] - max_building
result += view_building
print(result) |
from collections import deque
numbers = int(input())
for number in range(numbers):
N, M = map(int, input().split())
arrays = [list(map(int, input().split())) for i in range(M)]
result = deque() # result를 deque로 설정해서 최종적인 수열을 여기에 넣을거다.
result.extend(arrays[0][:]) # 그리고 시작점을 설정한다. 첫번째 수열은 딱 다 들어가기!! insers는 인덱스를 써야함
searchArray = 1 # Array마다 탐색
Flag = False
while searchArray < M: # 갯수(번째)보다 작은거면 들어가기
for i in range(searchArray * N): # 수열 번째 * 각 수열 길이 = 총(하나) 수열 길이
if result[i] > arrays[searchArray][0]: # 탐색시작, 만약 총수열 i번째 숫자가 다음 수열(searchArray번째)의 첫번째 숫자보다 작으면
Flag = True # 찾았당
index = i # index는 i이다
break #for문을 빠져 나가자(index찾기끝났으니 다른 작업아래에서 하자.)
if Flag: #Flag가 True면
for i in range(N-1, -1, -1): # 인덱스 역순으로
result.insert(index, arrays[searchArray][i]) #insert는 하나만 넣을 수 있어
# 그니까, 같은자리에 계속 넣으려면 뒤부터 넣어야지 정방향으로 전부 들어감
searchArray += 1 # 지금 어레이에서 할일 끝났으니까 다음 어레이로 넘어가기
Flag = False #이것도 다시쓰려면 초기화 해주기
else: # 위에서 전부 돌았는데 플레그가 안바뀌면! 뒤에 붙여주기
result.extend(arrays[searchArray][:])
searchArray += 1
print('#{} '.format(number+1), end='')
for i in range(10):
print(result.pop(), end=' ')
print('')
|
numbers = int(input())
for number in range(numbers):
str1 = input()
str2 = input()
Maxval = 0
str_dict = {}
for i in str1:
str_dict[i] = 0
for i in str2:
if i in str_dict:
str_dict[i] = str_dict[i] + 1
for key, val in str_dict.items():
if val > Maxval:
Maxval = val
print('#{} {}'.format(number+1, Maxval)) |
TF = [0]*2
def makingRoom(room, dipth, wantN, TF):
TF[0] = 1
TF[1] = 0
return 2
def backtrack(room, dipth, wantN):
global powerset
if dipth == wantN:
result = 0
for jj in range(1, 11):
if room[jj] == 1:
result += powerset[jj-1]
if result == 10:
subset = []
for i in range(1, 11):
if room[i] == 1:
subset.append(powerset[i-1])
print(subset)
else:
dipth += 1
two = makingRoom(room, dipth, wantN, TF)
for i in range(two):
room[dipth] = TF[i]
backtrack(room, dipth, wantN)
Maxroom = 11
room = [0]*Maxroom
powerset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
backtrack(room, 0, 10) |
# UNION --> Perform union of 2 arrays .
list1 = [1,23,7,89,231,45,78,11]
list2 = [2,78,23,111,56,78,0,9]
list3=[]
print("List 1 : ",list1)
print("List 2 : ",list2)
length=len(list1)+len(list2)
for i in list1:
list3.extend([i])
for i in list3:
for j in list2:
if j in list3:
continue
else:
list3.append(j)
print("Union of List 1 and List 2 : ",list3) |
# TriangleAsum --> In case of 3*3 matrix , TriangleAsum contains elements of index (00,01,02,11,22,22)
# Condition to check if triangle exists in the matrix --> No. of rows = No. of columns of the given matrix
list1=[[10,20,30],[40,50,60],[70,80,90]]
len_r=len(list1)
len_c=[] # To store number of columns of each row of given Matrix
# Checking number of columns in each row of given Matrix
for i in range(len_r):
x=len(list1[i])
len_c.extend([x])
#print(len_c)
flag=0
# Matrix Validity (no. of columns of each row should be same)
for i in range(len(len_c)):
for j in range(i+1,len(len_c)):
if len_c[i] == len_c[j]:
flag = 1
else:
print("Given Matrix : InValid")
exit()
if flag==1:
print("Given Matrix : Valid")
print()
# Given Matrix
print("Given Matrix is : ")
for i in range(len_r):
for j in range(len_c[0]):
print(list1[i][j],end=" ")
print()
print()
# Triangle Validity (both dimensions of the given matrix should be same)
if flag==1:
if len_r==len_c[0]:
print("Given matrix : Valid to perform further operation(both dimensions of the given matrix are same)")
else:
print("Given Matrix : InValid to perform further operation (both dimensions of the given matrix aren't same)")
exit()
print()
# Triangle A Elements
print("Elements of Triangle A in given matrix : ")
for i in range(len_r):
for j in range(i,len_c[0]):
print(list1[i][j],end=" ")
#print()
print()
print()
# Calculating sum of elements of Triangle A
print("Sum of elements of Triangle A in given matrix : ",end="")
sum=0
for i in range(len_r):
for j in range(len_c[0]):
if i<=j:
sum=sum+list1[i][j]
print(sum) |
"""Custom Variable classes"""
import tkinter as tk
class PrefixNumberVar(tk.DoubleVar):
"""A number unit that can have an ISO prefix """
prefixes = {
'pico': 10 ** -12,
'nano': 10 ** -9,
'micro': 10 ** -6,
'milli': 10 ** -3,
'': 1,
'kilo': 10 ** 3,
'mega': 10 ** 6,
'giga': 10 ** 9
}
def __init__(self, parent, *args, prefix='', **kwargs):
super().__init__(parent, *args, **kwargs)
self.prefix = tk.StringVar(parent, value=prefix)
def get(self, *args, **kwargs):
try:
return super().get(*args, **kwargs)
except tk.TclError as e:
if str(e) == "expected floating-point number but got \"\"":
return 0
raise e
def set(self, value, prefix=None, *args, **kwargs):
if prefix is None:
pass
elif prefix not in self.prefixes:
raise ValueError(f'Invalid Prefix: {prefix}')
else:
self.prefix.set(prefix)
super().set(value, *args, **kwargs)
def get_absolute(self):
return self.get() * self.prefixes[self.prefix.get()]
def set_absolute(self, value):
"""Set an absolute value with no prefix"""
divisor = self.prefixes[self.prefix.get()]
self.set(value / divisor)
|
# Given an array of integers, print all subarrays having 0 sum.
# O(n^2)
def subarray_sum_0(array):
for i in range(len(array)):
total = 0
for j in range(i, len(array)):
total += array[j]
if total == 0:
print('Subarray: {}...{}'.format(i, j))
l = [3, 4, -7, 3, 1, 3, 1, -4, -2, -2]
subarray_sum_0(l)
|
# Given an binary array, find maximum length sub-array having equal number of 0's and 1'.
# O(n^2)
def max_length_subarray(array):
start = 0
end = -1
length = 0
for i in range(len(array)):
zeros = ones = 0
for j in range(i, len(array)):
if array[j] == 0:
zeros += 1
else:
ones += 1
if zeros == ones and j - i > length:
start = i
end = j
length = j - i + 1
print('Sub-array {}...{}, length {}'.format(start, end, length))
# O(n)
def max_length_subarray_two(array):
dct = {0: -1}
length = 0
ending_index = -1
total = 0
for i in range(len(array)):
total += -1 if array[i] == 0 else 1
if total in dct.keys():
if length < i - dct[total]:
length = i - dct[total]
ending_index = i
else:
dct[total] = i
print('Sub-array {}...{}, length {}'.format(ending_index - length + 1, ending_index, length))
l = [0, 0, 1, 0, 1, 0, 0]
max_length_subarray(l)
max_length_subarray_two(l)
|
import numpy as np
# Create a matrix
A = np.array([[1,2],[3,4]])
print "A"
print A
# Find inverse
Ainv = np.linalg.inv(A)
print "A inverse"
print Ainv
# Find whether Identity matrix arrives
print "Identity Matrix = Ainv * A"
print Ainv.dot(A)
print A.dot(Ainv)
# Find determinant
D = np.linalg.det(A)
print "Determinant of A"
print D
# Find diagonal --> returns vector
# Passing 2D array returns a 1D array
diag = np.diag(A)
print "Diagonal of A - 1D array"
print diag
# Passing a 1D array returns a 2D array
print "Diagonal of A - 2D array"
print np.diag([1,2])
I = np.array([1,2])
J = np.array([3,4])
print "I"
print I
print "J"
print J
# Find outer product of two vectors
print "Outer product of I and J"
print np.outer(I,J)
# Find inner product of two vectors
print "Inner product of I and J"
print np.inner(I,J)
print I.dot(J)
# Find trace
print "Trace of A"
print np.trace(A)
print np.diag(A).sum()
# Eigen values and Eigen vectors
# Each sample takes the row
# Each column takes the feature
# Sample - 100; Feature - 3
X = np.random.randn(100,3)
# Covariance of a matrix
# Remember to transpose it first!
cov = np.cov(X.T)
print cov
# np.eigh(C) --> For symmetric and Hermitian matrix
(eigenvalues, eigenvectors) = np.linalg.eigh(cov)
print eigenvalues
print eigenvectors |
# Create a nice greeting to welcome your users to your Brand Name Generator App
# code...
# initialize the two variables as empty strings
#code..
# simple check to make sure the user has entered the first word {Hint: use while loop}
# if there's no input, ask again
# if there's any input at all, continue to next step
# do the same for the second word
#code...
# count the number of strings in the brand name
#code...
# output using f-strings makes the code much more readable
#code...
|
number1 = int(input("Sisesta number: "))
number2 = int(input("Sisesta number: "))
print ("Esimene number on" + str(number1)+ "ja teine number on"+ str(number2), end="")
#liidab teise lause esimesega: end=""
print ("Esimene number on " + str(number1)+ " ja teine number on "+ str(number2))
print ("Numberite 1 ja 2 summa on :" +str(number1+number2) )
print ("Numberite 1 ja 2 korrutis on :" +str(number1*number2) )
print ("Numberite 1 ja 2 jagatis on :" +str(number1/number2) )
print ("Numberite 1 ja 2 täisjagatis on :" +str(number1//number2) )
print ("Numberite 1 ja 2 jäägiga jagamine on :" +str(number1%number2) )
|
# line 2 prints the text "I will now count my chickens:"
print("I will now count my chickens:")
# line 4 prints the word "Hens" then does a calculation for the result of 25 + 30 / 6
print("Hens", 25 + 30 / 6)
# line 6 prints the word "Roosters then does a calculation for the result of 100 - 25 * 3 % 4
print("Roosters", 100 - 25 * 3.0 % 4)
# line 8 prints the text "Now I will count the eggs:"
print("Now I will count the eggs:")
# line 10 calculates the result of 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
# line 12 prints the text "Is it true that 3 + 2 < 5 - 7?
print("Is it true that 3 + 2 < 5 - 7?")
# line 14 calculates the result of the left hand side of the inequality 3 + 2 and of the right hand side of the inequality 5 - 7 then compares the results of the left hand side and the right hand side of the inequality
print(3 + 2.0 < 5.0 - 7)
# line 16 prints the text "What is 3 + 2?" and the result of 3 + 2 beside it
print("What is 3 + 2?", 3.0 + 2)
# line 18 prints the text "What is 5 - 7?" and the result of 5 - 7 beside it
print("What is 5 - 7?", 5.0 - 7)
# line 20 prints the text "Oh, that's why it's False."
print("Oh, that's why it's False.")
# line 22 prints the text " How about some more."
print("How about some more.")
# line 24 prints the text "Is it greater?" and the result of 5 > -2 beside it
print("Is it greater?", 5 > -2)
# line 26 prints the text "Is it greater or equal?" and the result of 5 >= -2 beside it
print("Is it greater or equal?", 5 >= -2)
# line 28 prints the text "Is it less or equal?" and the result of 5 <= -2 beside it
print("Is it less or equal?", 5 <= -2) |
import numpy as np
class MatMul:
def __init__(self, W):
self.params = [W]
self.grads = [np.zeros_like(W)] # W와 같은 크기의 0행렬 생성
self.x = None
def forward(self,x):
W, = self.params
out = np.matmul(x,W)
self.x = x
return out
def backward(self,dout):
W, = self.params
dx = np.matmul(dout, W.T)
dW = np.matmul(self.x.T,dout)
# a[...] = b 의 경우 a의 주소는 그대로고 b의 값이 복사 된다.
self.grads[0][...] = dW
return dx
'''의문점
# parmas를 W 하나만 할거면 뭐하러 list를 쓴건가
self.grads를 따로 저장하는 이유가 뭔가? 그리고 이 역시 리스트를 쓰는 이유는 뭔가?
'''
|
# python-day-1-assignment
#dictionary
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
print(person.items())
print(person.copy())
print(person.keys())
print(person.values())
print ('name: ',person.get('name'))
|
import random
class Max_Heap:
def __init__(self,arr=[]):
self.Heapify(arr)
self.h=arr
self.removed=set()
def Heapify(self,arr):
for i in range(len(arr)//2,-1,-1):
self.NodeHeapifyDown(arr,i)
def NodeHeapifyDown(self,arr,i=0):
largest=i
if (2*i)+1<len(arr):
if arr[(2*i)+1]>arr[i]:
largest=(2*i)+1
if (2*i)+2<len(arr):
if arr[(2*i)+2]>arr[largest]:
largest=(2*i)+2
if largest!=i:
arr[i],arr[largest]=arr[largest],arr[i]
self.NodeHeapifyDown(arr,largest)
return
def NodeHeapifyUp(self,arr,i):
if i==0:
return
p=((i-1)//2)
if arr[i]>arr[p]:
arr[i],arr[p]=arr[p],arr[i]
self.NodeHeapifyUp(arr,p)
return
def Add(self,val):
self.h.append(val)
self.NodeHeapifyUp(self.h,len(self.h)-1)
return
def Maximum_peek(self):
if len(self.h)==0: return -1
return self.h[0]
def Maximum_pop(self):
if len(self.h)==0: return -1
self.h[0],self.h[-1]=self.h[-1],self.h[0]
popped=self.h.pop()
self.NodeHeapifyDown(self.h,0)
return popped |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 16:33:47 2020
@author: max
"""
def taxi_zum_zum(moves):
x=0
y=0
direction= 1
for i in range(len(moves)):
if moves[i] == 'F':
if direction == 1:
y+= 1
if direction == 2:
x+= 1
if direction == 3:
y-= 1
if direction == 4:
x-= 1
if moves[i] == 'R':
direction+= 1
if direction == 5:
direction = 1
if moves[i] == 'L':
direction-= 1
if direction == 0:
direction = 4
return(x,y)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 22:48:02 2020
@author: max
"""
def dubfind(a_list):
compstart=1
for i in a_list:
comps= a_list[compstart:]
for c in comps:
print(i,c)
if c == i:
return True
compstart+= 1
print('__')
return False
list_a= [n for n in range(10)]
#list_a.append(1)
print(list_a)
print(dubfind(list_a)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 18:01:08 2020
@author: max
"""
def factorial(num):
if num==0:
return 1
return num*factorial(num-1)
vowels= ['a', 'i', 'e', 'o', 'u']
def all_strings(letters):
print(all_strings)
all_strings(vowels)
|
def evenNumber():
n = int(input())
a = list(map(int, input().split()))
for x in a:
if(x % 2 == 0):
print(x)
evenNumber() |
def solution():
m = input()
a = []
previous = ""
for x in range(len(m)):
if(previous == "" or previous == " "):
a.append(m[x].upper())
previous = m[x]
l = len(a)
for y in range(l):
if(y == l - 1):
print(a[y])
else:
print(a[y], end = "")
solution()
|
def solution():
n = int(input())
t = recursive(n)
print(t)
def recursive(n):
if(n == 0 or n == 1):
return 1
return recursive(n - 1) + recursive(n - 2)
solution() |
import math
class Triangle:
def __init__(self, a = 1, b = 1, c = 1):
self.a = a
self.b = b
self.c = c
def dt(self):
s = (self.a + self.b + self.c) / 2
dt = math.sqrt(s*((s - self.a)*(s - self.b)*(s - self.c)))
return dt
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
s = "{0} {1}".format(self.x, self.y)
return s
def distance(self, p2):
xD = math.pow((self.x - p2.x), 2)
yD = math.pow((self.y - p2.y), 2)
d = math.sqrt(xD + yD)
return d
def solution():
n = int(input())
d = 0
while(n > 0):
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
p1 = Point(x1, y1)
p2 = Point(x2, y2)
p3 = Point(x3, y3)
a = p1.distance(p2)
b = p1.distance(p3)
c = p2.distance(p3)
t = Triangle(a, b, c)
d += t.dt()
n -= 1
print("{0:.2f}".format(d))
solution() |
def resursive(ar, index):
if(index == len(ar) - 1):
return ar[index]
return ar[index] + resursive(ar, index + 1)
def simpleArraySum(ar):
total = resursive(ar, 0)
print(total)
simpleArraySum([1,2,3,4,10,11]) |
def maxLike():
n = int(input())
a = list(map(int, input().split()))
max = 0
for l in a:
if(l > max):
max = l
print(max)
maxLike() |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y= dataset.iloc[:,4].values
# Encoding categotrical data
#encoding the Independant Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X= LabelEncoder()
X[:,3]= labelencoder_X.fit_transform(X[:,3])
onehotencoder = OneHotEncoder(categorical_features=[3])
X = onehotencoder.fit_transform(X).toarray()
#Voidnig the Dummy variable trap
X = X[:,1:]
# Spliting the dataset into the Traing set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test= train_test_split(X,y,test_size= 0.2, random_state=0)
# Fitting Multiple Linear Regression to the Traing set
from sklearn.linear_model import LinearRegression
regressor= LinearRegression()
regressor.fit(X_train, y_train)
#Predicting the Test set result
y_pred=regressor.predict(X_test)
|
def compare (a,b):
if len(a)==len(b):
l = len(a)
result = ""
remains_a, remains_b = "",""
for i in range(l):
if a[i]==b[i]:
result += "1"
else:
remains_a += a[i]
remains_b += b[i]
for char in remains_a:
for i in range(len(remains_b)):
if char==remains_b[i]:
result+="0"
remains_b = remains_b[:i]+remains_b[i+1:]
break
for char in remains_b:
result+="_"
return result
return ""
code = input("What's the solution?\n")
guess = input("What's the guess?\n")
print(compare(code,guess))
##print(compare("aaab","aabb"))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 09:57:55 2018
@author: usov
"""
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'
def intersect(self, other):
"""
returns a new intSet containing elements that appear in both sets.
In other words,
s1.intersect(s2) return a new intSet of integers that appear in both s1 and s2.
"""
z = intSet()
for x in self.vals:
if other.member(x):
z.insert(x)
return z
def __len__(self):
"that len(s) returns the number of elements in s"
return len(self.vals)
a = intSet()
a.insert(1)
a.insert(2)
a
print('a', a)
b = intSet()
b.insert(3)
b.insert(1)
print('b', b)
c = a.intersect(b)
print('c', c)
print('a', a)
print('len:', len(a), len(b), len(c)) |
#import time
#start_time = time.time()
# the outstanding balance on the credit card
balance = 3329
# annual interest rate as a decimal
annualInterestRate = 0.2
avgMonthPayment = ((balance + annualInterestRate * balance)//12)//10*10
def dept(monthBalance, annualInterestRate, minMonthPayment):
# print(minMonthPayment)
monthBalanceTest = monthBalance
for _ in range(12):
monthUnpaidBal = monthBalanceTest - minMonthPayment
monthBalanceTest = monthUnpaidBal + (annualInterestRate/12 * monthUnpaidBal)
print('For: Month', _+1, monthBalanceTest)
if monthBalanceTest>0:
return minMonthPayment+10
else:
return dept(monthBalance, annualInterestRate, minMonthPayment-10)
print('Lowest Payment:', int(dept(balance, annualInterestRate, avgMonthPayment)))
#for _ in range(10000):
# dept(balance, annualInterestRate, avgMonthPayment)
#
#print("Recursive test: --- %s seconds ---" % (time.time() - start_time)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 11:09:44 2018
@author: ART
"""
def longestRun(L):
tmp = 1
ans = 1
for idx in range(len(L[:-1])):
# print(L[idx], L[idx+1])
if L[idx] <= L[idx+1]:
tmp += 1
if tmp > ans:
ans = tmp
else:
tmp = 1
return ans
L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2, 3, 4]
print('Should return:', 5)
print(longestRun(L)) |
#!/usr/bin/env python
""" Given scores of N athletes, find their relative ranks and the people with
the top three highest scores, who will be awarded medals: "Gold Medal", "Silver
Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest
scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative ranks according to their scores.
Note:
N is a positive integer and won't exceed 10,000.
All the scores of athletes are guaranteed to be unique.
"""
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
medals = ["Gold Medal","Silver Medal", "Bronze Medal"]
scores = [(i, score) for i, score in enumerate(nums)]
sorted_scores = sorted(scores, key=lambda (index, score): score, reverse=True)
for i in range(0,len(nums)):
score_index=sorted_scores[i][0]
if i > 2:
nums[score_index] = str(i+1)
else:
nums[score_index] = medals[i]
return nums |
TYPES:
how python represents different type of data.
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
EX: type(11)= int
type(21.21)= float
type("Hello")= str
TYPECASTING
str(1):"1"
str(4.5): '4.5'
Boolean : int(True)=1
int(False)=0
bool(1)=True
bool(0)= False |
a=int(input('vvedi chislo'))
def chisla(a):
'''выводит четные числа'''
for i in range(2, a, 2):
print(i)
chisla(a)
print(chisla.__doc__) |
def sayHello(name):
print('hello {0}'.format(name))
coun=input('how many users?')
for i in range(1,int(coun)+1):
n=input('{0} user name?'.format(i))
sayHello(n)
print('end')
|
import random
from asciicards import assignArt
class Player():
def __init__(self):
self.name = ""
self.age = 0
self.stack = 0
self.position = ""
self.card = []
def print_register(self):
print("---------------------------------------------------------------------------------------------------------------------------------")
print(" Register ")
print("---------------------------------------------------------------------------------------------------------------------------------")
print("poker username: ")
self.name = input("")
print("age: ")
self.age = input("")
class Card(object):
def __init__(self, value, suit):
self.value = value
self.suit = suit
self.showing = True
def __repr__(self):
value_name = ""
suit_name = ""
if self.showing:
if self.value == 0:
value_name = "Two"
if self.value == 1:
value_name = "Three"
if self.value == 2:
value_name = "Four"
if self.value == 3:
value_name = "Five"
if self.value == 4:
value_name = "Six"
if self.value == 5:
value_name = "Seven"
if self.value == 6:
value_name = "Eight"
if self.value == 7:
value_name = "Nine"
if self.value == 8:
value_name = "Ten"
if self.value == 9:
value_name = "Jack"
if self.value == 10:
value_name = "Queen"
if self.value == 11:
value_name = "King"
if self.value == 12:
value_name = "Ace"
if self.suit == 0:
suit_name = "Clubs"
if self.suit == 1:
suit_name = "Diamond"
if self.suit == 2:
suit_name = "Hearts"
if self.suit == 3:
suit_name = "Spades"
return value_name + " of " + suit_name
else:
return "[CARD]"
class StandardDeck(list):
def __init__(self):
super().__init__()
suits = list(range(4))
values = list(range(13))
[[self.append(Card(i, j)) for j in suits] for i in values]
def __repr__(self):
return f"Standard deck of cards\n{len(self)} cards remaining"
def shuffle(self):
random.shuffle(self)
print("\n\n--deck shuffled--")
def deal_fromdeck(self):
deal_card = self[0]
self.pop(0)
return deal_card
class Game():
def __init__(self):
self.buyin = 0
self.pot = 0
self.bigblind = 0
self.smallblind = 0
self.numofbot = 0
self.positionList = []
self.tableList = []
self.activeplayer = []
self.handtoplay = 0
self.handcount = 0
def setup(self,player_name,player_age):
checkdigit = True
while checkdigit:
print("---------------------------------------------------------------------------------------------------------------------------------")
print(" Game Set-Up ")
print("---------------------------------------------------------------------------------------------------------------------------------")
self.buyin = input("Enter buy-in amount: ")
if self.buyin.isdigit():
self.buyin = int(self.buyin)
self.smallblind = input("Enter small-blind price: ")
if self.smallblind.isdigit():
self.smallblind = int(self.smallblind)
self.bigblind = self.smallblind * 2
if self.bigblind == self.smallblind * 2:
self.bigblind = int(self.bigblind)
self.numofbot = input("Enter the amount of bot(max 5): ")
if self.numofbot.isdigit():
self.numofbot = int(self.numofbot)
if self.numofbot > 5 or self.numofbot < 1:
print("Invalid amount of bot, please retry")
continue
else:
self.handtoplay = input("Please enter the amount of hand to play(Minimum-10 Maximum-30): ")
if self.handtoplay.isdigit():
self.handtoplay = int(self.handtoplay)
if self.handtoplay >= 10:
if self.handtoplay > 30:
print("Maximum of 30 hands, please retry")
else:
print("---------------------------------------------------------------------------------------------------------------------------------")
print(" Selected settings ")
print("---------------------------------------------------------------------------------------------------------------------------------")
print("--Player Profile--")
print("Name:",player_name)
print("Age:",player_age)
print("\n")
print("--Game settings--")
print("Buy-in:",self.buyin)
print("Small-blind:",self.smallblind)
print("Big-blind:",self.bigblind)
print("Number of bot:",self.numofbot)
print("Playing hand:",self.handtoplay)
print("\n")
setup_complete = input("Press 'y' to confirm, 'n' to reset...")
if setup_complete == "y":
print("--Setup completed--")
break
elif setup_complete == "n":
continue
else:
print("Invalid decision, game reset")
continue
else:
print("Minimum of 10 hands, please retry")
else:
print("Invalid amount")
continue
else:
print("Invalid amount")
continue
else:
print("Invalid amount")
continue
else:
print("Invalid amount")
continue
else:
print("Invalid amount")
continue
def setup_position(self,player,numofbot,handcount):
if handcount == 0:
if numofbot > 0:
self.positionList.append("Dealer")
self.positionList.append("Smallblind")
if numofbot > 1:
self.positionList.append("Bigblind")
if numofbot > 2:
self.positionList.append("UTG")
if numofbot > 3:
self.positionList.append("Middle Postion")
if numofbot > 4:
self.positionList.append("Late Postion")
#--------player--------
self.tableList.append(player)
#set starting stack equals table buy-in
if handcount == 0:
player.stack = game.buyin
#-------init bot-------
for i in range(numofbot):
bot = Player()
bot.name = "Bot " + str(i+1)
self.tableList.append(bot)
#set starting stack equals table buy-in
if handcount == 0:
bot.stack = game.buyin
#shuffle seating
random.shuffle(self.tableList)
#asssign position
for i, ply in enumerate(self.tableList):
ply.position = self.positionList[i]
print("\n\n\n\n")
print("---------------------------------------------------------------------------------------------------------------------------------")
print("\n\n\n")
print(" ------------------------------------------- ")
print(" | | ")
print(" | Poker Bot | ")
print(" | by Kan | ")
print(" | | ")
print(" ------------------------------------------- ")
print("\n\n\n")
print("---------------------------------------------------------------------------------------------------------------------------------")
player = Player()
player.print_register()
game = Game()
game.setup(player.name,player.age)
bot = Player()
#print(player.name,player.age)
gamecontinue = True
preflop = False
flop = False
turn = False
river = False
while gamecontinue == True and game.handcount <= game.handtoplay:
game.pot = 0
card = Card(0,0)
deck = StandardDeck()
deck.shuffle()
preflop = True
print("---------------------------------------------------------------------------------------------------------------------------------")
print(" Preflop ")
print("---------------------------------------------------------------------------------------------------------------------------------")
#____________________init bot__________________________
"""
botList = []
for i in range(game.numofbot):
bot = Player()
botList.append(bot)
"""
#_______________init table position________________
game.setup_position(player,game.numofbot,game.handcount)
# _____________Deal all player & bot 2 cards____________________
"""
print(player.name + " hand: ")
#deal 2 cards and store in list for player
player.card.append(deck.deal())
player.card.append(deck.deal())
print(player.card[0], ",",player.card[1])
"""
#deal 2 cards for each bot
for i, bot in enumerate(game.tableList):
print(bot.name , "hand:",)
bot.card.append(deck.deal_fromdeck())
bot.card.append(deck.deal_fromdeck())
print(bot.card[0],",",bot.card[1])
print("Position:", bot.position)
print("Stack:", bot.stack)
#reset all player to active
game.activeplayer = game.tableList
#_______________________Bet Preflop____________________________
x = Player()
bet_amount = game.bigblind
game.pot += (game.smallblind + game.bigblind)
preflop = True
while preflop == True:
actionlist = []
for x in game.tableList:
valid_bet = False
print("----------------",x.name, "'s turn ----------------")
print("'c' - call | 'f' - fold | 'r' - raise | 'a' - allin")
decision = input("Decision: ")
if decision == 'c':
x.stack -= bet_amount
game.pot += bet_amount
actionlist.append(False)
if decision == 'f':
if x.position == 'Smallblind':
x.stack -= game.smallblind
if x.position == 'Bigblind':
x.stack -= game.bigblind
actionlist.append(False)
#game.activeplayer.remove(x)
if decision == 'r':
while valid_bet == False:
input_amount = input("Please enter the amount of raise: ")
if input_amount.isdigit():
input_amount = int(input_amount)
if input_amount >= bet_amount * 2:
bet_amount = input_amount
game.pot += bet_amount
x.stack -= bet_amount
actionlist.append(True)
valid_bet = True
else:
print("Raise need to be at least 2 times of the last bet")
continue
else:
print("Invalid amount")
continue
if decision == 'a':
bet_amount += x.stack
x.stack = 0
for i, bot in enumerate(game.tableList):
print(bot.name)
print("Stack:", bot.stack)
if True in actionlist:
continue
else:
preflop = False
print("End Preflop")
break
|
def reverse(word):
x = ''
for i in range(len(word)):
x += word[len(word) - 1 - i]
return x
word = raw_input('Give a text: ')
y = reverse(word)
if y == word:
print 'It is a Palindrome'
else:
print 'It is NOT a Palindrome'
|
num = int(raw_input("Please choose a number to divide: "))
list_range = list(range(1, num + 1))
divisors = []
for i in list_range:
if num % i == 0:
divisors.append(i)
print divisors
|
'''
Gauss Seidel :
Number of Inputs (4) :
- (Ax = b) A matrix of coffecients,
- b vector ,
- initial vector,
- espilon(stopping criteria)
Number of outputs (2) :
- solution(vector) ,
- approximate error.
SOR :
Number of Inputs(5) :
- A matrix of coffecients,
- b vector ,
- initial vector,
- omega ,
- espilon(stopping criteria)
Number of outputs (2) :
- solution(vector) ,
- approximate error.
'''
import numpy as np
#Calculating Permutation of A list. used to convert a matrix into a diagonally dominant one.
#by manipulating the order of the rows.
def permutation(lst):
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i]+lst[i+1:]
for p in permutation(remLst):
l.append([m] + p)
return l
#Checks if abs(A[i,i])> sum(Abs(A[i,j!=i])).
def CheckDiagDominant(mat):
# Assuming a square matrix
flag = True
for i in range(mat.shape[0]):
x = 2*np.abs(mat[i,i])
y = np.sum(np.abs(mat[i,:]))
if(x<=y):
flag = False
break
return flag
#uses CheckDiagDominant and Permutation to get A diagonally dominant matrix.
def MakeItDiagDominant(mat):
m,n = mat.shape
if(m != n):
#print("Error : Not A Square Matrix.")
return mat
lst = []
for i in range(n):
lst.append(i)
per = permutation(lst)
flag = True
w = len(per)
temp = np.empty([n,m])
for i in range(w):
for j in range(n):
temp[j] = mat[per[i][j]]
if(CheckDiagDominant(temp)):
return temp
flag = False
break
if (not (flag)):
break
return mat
# In[61]:
# solving a linear system of equations using gauss seidel.
# mat : the coeffecients matrix.
# vec : the result vector.
# init : initial solution.
#epsilon : stopping criteria.
def SolveGaussSeidel(mat,vec,init,epsilon):
error = np.zeros([mat.shape[0],1],dtype='float64')
#print(error.shape)
prev = np.copy(init)
ddmat = MakeItDiagDominant(mat)
#print(ddmat)
#print(vec)
#TODO : Add the Relation.
# the Relation is R[i] = (v[i] - sigma(R[j]*A[j,j]))/A[i,i]
# where A is the coeffecients matrix, v is the result vector and R is the solution vector
maxError = 10000
n = 100
while(n>0 and maxError >epsilon) :
for i in range(mat.shape[0]):
x = vec[i]
for j in range(mat.shape[1]):
x -= (init[j]*ddmat[i,j])
x+= init[i]*ddmat[i,i]
x /= ddmat[i,i]
init[i] = x
#print(x)
error[i] = abs((init[i]-prev[i])/init[i]).astype('float64')
n -=1
#print(error)
maxError = max(error)
prev = np.copy(init)
#print(init)
#print(maxError)
return init,maxError
# solving a linear system of equations using successive over relaxation.
# mat : the coeffecients matrix.
# vec : the result vector.
#init : initial solution.
#omega : relaxation factor.
#epsilon : stopping criteria.
def SolveSOR(mat,vec,init,omega,epsilon):
error = np.zeros(mat.shape[0])
prev = np.copy(init)
ddmat= MakeItDiagDominant(mat)
myvec=vec.copy()
n = 100
maxError = 10000
#TODO : Add the Relation.
# the Relation is R[i] = (v[i] - sigma(R[j]*A[j,j]))/A[i,i]
# where A is the coeffecients matrix, v is the result vector and R is the solution vector
while(n>0 and maxError > epsilon):
for i in range(mat.shape[0]):
#print(vec)
x = vec[i].copy()
for j in range(mat.shape[1]):
x -= (init[j]*ddmat[i,j])
x+= init[i]*ddmat[i,i]
x*= omega
x /= ddmat[i,i]
x += (1-omega)*init[i]
#print(x)
init[i] = x
error[i] = abs((init[i]-prev[i])/init[i]).astype(float)
n -=1
maxError = max(error)
prev = np.copy(init)
return init,maxError
# In[64]:
#TESTING.
# mat = np.array([[9,2,1],[1,7,3],[1,1,8]])
# vec = np.array([12,11,11])
# epsilon = 0.1
# init= np.array([1.2,1.2,1.2])
# result,error= SolveSOR(mat,vec,init,1.0,epsilon)
# print(result)
# print(error) |
import numpy as np
def curve_fitting(x,y,degree=1):
"""
calculates the coefficients to fit (x, y) using a polynomial
of the specified degree
:param x the input data points
:param y the output data points
:return the coefficients of the polynomial that best fits (x, y)
"""
x=np.array(x)
y=np.array(y)
#x=x[:degree+1]
#y=y[:degree+1]
if(degree > x.shape[0]):
print("inputs values not enough for degree")
return 0
elif(degree < np.linalg.matrix_rank(np.dot(x,x.T))):
print("singular.")
return 0
powers=np.ones([x.shape[0],degree+1])
help_vectors=np.array([range(0,degree+1)])
powers=(powers*help_vectors).T
x=x**powers
y=np.dot(x,y)
#invx=np.linalg.inv(np.dot(x,x.T))
#coeff=np.dot(invx,y)
coeff = np.linalg.solve(np.dot(x,x.T), y)
return coeff
# some tests
def fun(x):
return x ** 3 + 3 * x * x - 24 * x + 2
def fun1(x):
return x ** 4 + x ** 3 + x ** 2 + x ** 1 +6565656
if __name__ =="__main__":
x=[1,2,3,4,5]
y=[1 + 3,8 + 3,27 + 3,64 + 3,125 + 3]
print(curve_fitting(x,y,degree=9))
x = list(range(100))
y = list(map(fun, x))
print(curve_fitting(x,y,degree=4))
x = list(range(100))
y = list(map(fun1, x))
print(curve_fitting(x,y,degree=4)) |
print("FOLLOW THE INSTRUCTIONS TO FIND THE USER")
print("*************************************************************")
In1="To search by ID: Go to Facebook.com and find the UserID which would look something like this: 10003340872XXXX"
In2="To search by Phone Number: Type the phone number in the prompt"
print(In1)
print(In2)
print("*************************************************************")
#Taking the user input of the parameter to search from
id= input("Enter the Number ID of the user:")
#Adding the database file of the leaked Data. If you want to add more database text files, youu can add it here.
file_a = open('.\India 2.txt' ,encoding="utf8")
file_b = open('.\India 1.txt' ,encoding="utf8")
#Creating the function the read the database and print the result.
for line in file_a or file_b:
if id in line:
print("Your Data Has Been Compromised")
print("*************************************************************")
print(line)
print("*************************************************************")
break
if id not in line:
print("Your Data is Safe")
|
"""Custom topology example
Two directly connected switches plus a host for each switch:
3 switches, 4 hosts
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class MyTopo( Topo ):
"Simple topology example."
def __init__( self ):
"Create custom topo."
# Initialize topology
Topo.__init__( self )
# Add hosts and switches
leftHost = self.addHost( 'h0' )
rightHost = self.addHost( 'h2' )
middleHost = self.addHost( 'h1' )
postcardHost = self.addHost( 'h3')
leftSwitch = self.addSwitch( 's0' )
rightSwitch = self.addSwitch( 's2' )
middleSwitch = self.addSwitch( 's1' )
# Add links
self.addLink( leftHost, leftSwitch )
self.addLink( leftSwitch, middleSwitch )
self.addLink( middleHost, middleSwitch )
self.addLink( middleSwitch, rightSwitch )
self.addLink( rightSwitch, rightHost )
self.addLink( leftSwitch, postcardHost )
self.addLink( middleSwitch, postcardHost )
self.addLink( rightSwitch, postcardHost )
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
#!/usr/bin/python
import sys
import os
import re
import copy
#import networkx as nx
#import matplotlib.pyplot as plt
#atom = value[]
def atom_intersection(atom1,atom2):
ans = []
for i in range(len(atom1)):
if (atom1[i] == atom2[i]):
ans.append(atom1[i])
elif (atom1[i] == -1):
ans.append(atom2[i])
elif (atom2[i] == -1):
ans.append(atom1[i])
else:
return None
return ans
#molecule[0] = a list of +atoms
#molecule[1] = a list of -atom
def molecule_intersection(molecule1, molecule2):
ans=[[],[]]
if molecule1==None or molecule2==None:
#print "Molecule1",molecule1,"Molecule2",molecule2
return None
for sign1 in range(2):
for sign2 in range(2):
for i in range(len(molecule1[sign1])):
for j in range(len(molecule2[sign2])):
ret = atom_intersection(molecule1[sign1][i],molecule2[sign2][j])
if ret != None:
ans[sign1 ^ sign2].append(ret)
return molecule_trim(ans)
#set is a list of atoms
def merge_place(atom1, atom2):
place = -1
dif_num = 0
for i in range(len(atom1)):
if atom1[i] != atom2[i]:
dif_num +=1
if dif_num>1:
return -1
if atom1[i]!=-1 and atom2[i]!=-1:
place=i
if place>=6 and place<=69:
return place
else:
return -1
#brute force a smarter idea is sort
def set_merge(set):
find=True
while find:
find = False
for i in range(len(set)):
for j in range(i):
place = merge_place(set[i],set[j])
if place > 0:
find=True
set[j][place]=-1
del set[i]
break
if find:
break
return set
def molecule_trim(ans):
find = True
ans[0]=set_merge(ans[0])
ans[1]=set_merge(ans[1])
while find:
find = False
for i in range(len(ans[0])):
for j in range(len(ans[1])):
if ans[0][i] == ans[1][j]:
del ans[0][i]
del ans[1][j]
find = True
break
if find:
break
if (len(ans[1]) == 0) and (len(ans[0]) == 0):
return None
else:
return ans
def molecule_minus(molecule1, molecule2):
ans = molecule1
intersection = molecule_intersection(molecule1,molecule2)
if intersection != None:
for atom in intersection[0]:
ans[1].append(atom)
for atom in intersection[1]:
ans[0].append(atom)
return molecule_trim(ans)
#rules[index] = molecule
def dag_generator(rules):
dag = []
for i in range(len(rules)):
match_range=copy.deepcopy(rules[i])
#print "loop on",i
#print "---------------------------------"
for j in range(i+1,len(rules)):
#print "Comparing",match_range," and rule",j,":",rules[j]
if molecule_intersection(match_range, rules[j])!=None:
dag.append((i,j))
match_range = molecule_minus(match_range,rules[j])
#print "match changes to ",match_range
rules[j] = molecule_minus(rules[j],rules[i])
#print "rule",j,"changes to ",rules[j]
if match_range == None:
break
return dag
def type_parse(fileName):
fileHandle = open(fileName)
types=[]
lines = fileHandle.readlines()
for line in lines:
reg = re.compile(r'"(.+?)"')
types.append(reg.findall(line)[0])
fileHandle.close()
return types
def rule_parse(types,filename):
fileHandle = open(filename)
rule_pattern = re.compile(r'pattern=([\s\S]*?)action=')
content = fileHandle.read()
#print content
patterns = rule_pattern.findall(content)
#print patterns
rules=[]
for line in patterns:
rule=[]
for type in types:
pattern = type +'=(\d+?),'
reg = re.compile(pattern)
value = reg.findall(line)
if len(value)==0:
rule.append(-1)
else:
rule.append(int(value[0]))
#print rule
rules.append([[rule],[]])
fileHandle.close()
return rules
def draw_dag(rules,dag):
dg = nx.DiGraph()
for i in range(len(rules)):
dg.add_node(i)
for p in dag:
dg.add_edge(p[0],p[1])
nx.draw_circular(dg)
plt.show()
def transitive_reduction(dag, maxi):
connected =[]
for i in range(maxi):
connected.append([0 for i in range(maxi)])
for i in range(len(dag)):
connected[dag[i][1]][dag[i][0]] = 1
tr_dag = []
for i in range(maxi):
for j in range(i):
if (connected[i][j] == 1):
for k in range(j+1,i):
if (connected[i][k] ==1 and connected[k][j] ==1):
connected[i][j] =0
break
if (connected[i][j] == 1):
tr_dag.append((j,i))
return tr_dag
# Structure
# singularity = [value1,value2,....., ,] value -1 means a wildcard
# atom = main singularity - {singularity i}
# atom = [main singularity, singularity 1, singularity 2, ....]
# molecule = [atom1, atom2, atom......]
#singu a include singu b
def include_singu(a,b):
for i in range(0,len(a)):
if (a[i] != b[i] and a[i] != -1):
return False
return True
#intersection of singu1 and singu2
# -1 means a wildcard
def intersect_singu(a,b):
# print "a ",a
# print "b ",b
ans = []
for i in range(0,len(a)):
if (a[i] == b[i]):
ans.append(a[i])
elif (a[i] == -1):
ans.append(b[i])
elif (b[i] == -1):
ans.append(a[i])
else: # a and b differing on any value domain indicates that they don't intersect
return None
return ans
# intersection of atom1 and atom2 : a new atom whose main area is the intersection of the two main areas
# and whose holes are old holes of atom1 and atom2 that remain in the new main area
# Potential optimization: check repetition
def intersect_atom(a,b):
ans=[]
domain = intersect_singu(a[0],b[0])
if (domain == None):
return None
ans.append(domain)
for i in range(1,len(a)):
temp = intersect_singu(domain, a[i])
if (temp != None):
ans.append(temp)
for i in range(1,len(b)):
temp = intersect_singu(domain, b[i])
if (temp != None):
ans.append(temp)
for i in range(1,len(ans)):
if (ans[i] == ans[0]):
return None
return ans
# using '^' to represent intersect
# atomA ([mainA, singuA1, singuA2....]) - atomB ([mainB, singuB1, singuB2, ...] =
# [mainA, mainA ^ mainB, singuA1, singuA2.., singuAn] +
# [singuBi ^ mainA ^ main B, singuA1, singuA2...., singuAn]
# Reason: any hole in A will still be a hole
# intersection of mainA and mainB will be a new hole
# the part of a hole in B that falls into (mainA^mainB) and doesn't intersect with any hole in A results in a concrete piece after A-B
# always return a molecule
def subtract_atom(a,b):
newAtom1 = []
newDomain = intersect_singu(a[0],b[0])
if (newDomain == None):
return None
for i in range(1,len(a)):
if include_singu(a[i],newDomain):
return None
ans = []
if (include_singu(newDomain,a[0]) == False):
newAtom1.append(a[0])
newAtom1.append(newDomain)
for i in range(1,len(a)):
if (include_singu(newDomain,a[i]) == False):
#only subtract holes of A that don't fall into the new hole mainA^mainB
newAtom1.append(a[i])
ans.append(newAtom1)
for i in range(1,len(b)):
atomMain = intersect_singu(b[i],a[0]) #b[i] is already in mainB
if (atomMain == None):
continue
newAtom = [];
newAtom.append(atomMain)
valid = True
for j in range(1,len(a)):
singu = intersect_singu(atomMain,a[j])
if (singu != None):
if (singu == atomMain):
valid = False
break
else:
newAtom.append(singu)
if (valid):
ans.append(newAtom)
return ans
#moleculeA @ moleculeB = atoms in A @ atoms in B
# atoms in the same molecule don't intersect
def intersect_molecule(a,b):
ans = []
for atomA in a:
for atomB in b:
newAtom = intersect_atom(atomA, atomB)
if (newAtom != None):
ans.append(newAtom)
if (len(ans) == 0):
return None
else:
return ans
# this is not the most efficient but the correctness can be guarenteed.
# after A - B: all atoms in A don't intersect with any atom in B
def subtract_molecule(a,b):
ans = [copy.deepcopy(atom) for atom in a]
cursor =0
while (cursor < len(ans)):
deleted = False
for atom in b:
temp = subtract_atom(ans[cursor],atom)
if (temp != None):
del ans[cursor]
if (len(temp) == 0): # A[cursor] is subtracted to empty
deleted= True
break
ans.insert(cursor,temp[0]) # replace A[cursor] with a subtracted atom
for i in range(1,len(temp)):
ans.append(temp[i]) #append the rest subtracted atoms
if (not deleted):
cursor+=1
if (len(ans) == 0):
return None
else:
return ans
#new dag generator
def new_dag_generator(rules):
dag = []
# print "len",len(rules)
for i in range(len(rules)):
if rules[i] == None:
continue
match_range=copy.deepcopy(rules[i])
if match_range == None:
continue
#print "loop on",i
#print "loop on",i
#print "---------------------------------"
for j in range(i+1,len(rules)):
if i == 56 and j == 71:
pass#print intersect_molecule(match_range, rules[j])#pass#print rules[i],rules[j]
if rules[j] == None:
print j
continue
#print " and rule",j,":",rules[j]
if intersect_molecule(match_range, rules[j])!=None:
if i == 56 and j == 71:
pass#print i,j
dag.append((i,j))
#match_range = subtract_molecule(match_range,rules[j])
#print "match changes to ",match_range
#print rules[i]
#print rules[j]
rules[j] = subtract_molecule(rules[j],rules[i])
#print "rule",j,"changes to ",rules[j]
return dag
def new_rule_parse(types,filename):
fileHandle = open(filename)
rule_pattern = re.compile(r'pattern=([\s\S]*?)action=')
content = fileHandle.read()
#print filename
#print content
patterns = rule_pattern.findall(content)
#print patterns
rules=[]
for line in patterns:
rule=[]
for type in types:
pattern = type +'=([0-9]+)'
reg = re.compile(pattern)
value = reg.findall(line)
if len(value)==0:
rule.append(-1)
else:
#print type," ",int(value[0])
rule.append(int(value[0]))
#print rule
rules.append([[rule]])
fileHandle.close()
return rules
def new_new_rule_parse(types,filename):
fileHandle = open(filename)
content = fileHandle.read()
rule_pattern = re.compile(r'pattern=([\s\S]*?)action=')
patterns = rule_pattern.findall(content)
#print patterns[56]
#print patterns[71]
types1 = type_parse("typename.txt")
ret = []
for pattern in patterns:
rules = {}
types = ["tcpSrcPort","tcpDstPort","ipSrc","ipDst"]
for typ in types:
#process port
patt = typ +'=([0-9]+)'
reg = re.compile(patt)
#print "patterns[0]",patterns[0]
#print patterns
#print patterns[0]
#print reg.findall(patterns[0])
value = reg.findall(pattern)
if not (len(value)==0):
rules[typ] = value[0]
#process ip
pattern1 = typ +'=((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))(\/{1})(([1-3]\d)|[0-9]))'
reg1 = re.compile(pattern1)
value1 = reg1.findall(pattern)
if not (len(value1)==0):
rules[typ] = value1[0][0]
#print rules
rule = {}
for typ in types:
if (not rules.has_key(typ)) or (rule.has_key(typ)):
continue
if typ == "tcpSrcPort":
rule[typ] = int(rules[typ])
if typ == "tcpDstPort":
rule[typ] = int(rules[typ])
if typ == "ipSrc":
dt = rules[typ]
dt = dt.split('/')
ln = int(dt[1])
dt = dt[0]
dt = dt.split('.')
ip = 0
for i in dt:
ip <<= 8
ip += int(i)
for i in range(0,ln):
if (ip&(1<<(31-i))) != 0:
rule["ipSrc"+str(i)] = 1
else:
rule["ipSrc"+str(i)] = 0
rule[typ] = -1
elif typ == "ipDst":
dt = rules[typ]
dt = dt.split('/')
if len(dt) == 1:
ln = 32
else:
ln = int(dt[1])
dt = dt[0].split('.')
ip = 0
for i in dt:
ip <<= 8
ip += int(i)
for i in range(0,ln):
if (ip&(1<<(31-i))) != 0:
rule["ipDst"+str(i)] = 1
else:
rule["ipDst"+str(i)] = 0
rule[typ] = -1
rl = []
for typ in types1:
if rule.has_key(typ):
rl.append(rule[typ])
else:
rl.append(-1)
ret.append([[rl]])
for i in range(0,len(types1)):
typ = types1[i]
#print typ,ret[56][0][0][i]
for i in range(0,len(types1)):
typ = types1[i]
#print typ,ret[71][0][0][i]
return ret
if __name__=="__main__":
#parse all the types
types = type_parse("typename.txt")
if len(sys.argv) != 2:
print "Usage: python dag_generator.py rule_file_path"
print "One pattern on each line in rule_file."
sys.exit(0)
# rules = rule_parse(types,sys.argv[1])
# print len(rules)
# print (rules)
# dag=dag_generator(rules)
# print "-----original dag-------"
# print dag
# print "-----after reduction----"
# tr_dag = transitive_reduction(dag, len(rules))
# print tr_dag
rules = new_new_rule_parse(types,sys.argv[1])
#print rules
dag=new_dag_generator(rules)
# print "-----new dag-------"
# print dag
# print "-----after reduction----"
#dag = transitive_reduction(dag, len(rules))
print dag
#draw_dag(rules,dag)
|
# Function based Test Case
def test_one_plus_one():
assert 1 + 1 == 2
# Grouping similar Test Case into a Class
class TestArithmetic:
def test_addition(self):
assert 1 + 1 == 2
def test_multiplication(self):
assert 2 * 3 == 6
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 22:00:27 2018
@author: Alina
"""
def foo(x, y = 5):
def bar(x):
return x + 1
return bar(y * 2)
foo(3, 0)
print(foo(3, 0) )
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 15:22:28 2018
@author: Alina
"""
def factorial(x):
multiply = 1
while x > 0:
multiply *= x
x=x-1
return multiply
print(factorial(4)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 22:56:40 2018
@author: Alina
"""
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
# Don't forget to return your new list!
print(double_list(n)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 10 23:03:06 2018
@author: Alina
"""
def recur_power(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
if exp == 0:
return 1
elif exp == 1:
return base
else:
return base * recurPower(base,exp-1)
print(recur_power(2,4))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
a = set()
output=""
n = int(raw_input())
for i in range(0,n):
line = raw_input()
input = re.split("(<\w.*?>)", line)
for x in input:
m = re.search("<([^/].*?)[\s>]", x)
if m:
a.add(str(m.group(1)))
output = sorted(a)
empty = ""
for i in output:
empty += i + ";"
size = len(empty)
print(empty[0:size-1]) |
import random
import time
DELAY = 0.5
SUITS = ["hearts", "diamonds", "clubs", "spades"]
NAMES_SCORES = [
("one", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
("jack", 10),
("queen", 10),
("king", 10),
("ace", (11, 1)),
]
class Card(object):
""" A card in the game.
Attributes
----------
name: str
name of the card
suit: str
suit of the card
primary_score: int
the primary score of the card
secondary_score: int
the secondary score of the card, only for aces
"""
def __init__(self, name, suit, score):
self.name = name
self.suit = suit
if isinstance(score, tuple):
self.primary_score = score[0]
self.secondary_score = score[1]
else:
self.primary_score = score
self.secondary_score = score
def __str__(self):
return "{} of {}".format(self.name, self.suit)
def __repr__(self):
if self.primary_score == self.secondary_score:
score = self.primary_score
else:
score = (self.primary_score, self.secondary_score)
return "Card({}, {}, {})".format(self.name, self.suit, score)
class Deck(object):
""" A deck of cards.
This deck will never run out, in case all 52 cards are exhausted, a fresh
set is created. Quasi an infinity deck.
Attributes
----------
cards: List of Cards
The cards left in the deck.
"""
def __init__(self):
self.init_cards()
def init_cards(self):
""" Initialise a fresh set of cards. """
self.cards = [Card(name, suit, score)
for suit in SUITS
for (name, score) in NAMES_SCORES]
random.shuffle(self.cards)
def draw(self):
""" Pop a single card from the deck. """
if len(self.cards) == 0:
self.init_cards()
return self.cards.pop()
class Hand(object):
""" The hand of a player/dealer.
Attributes
----------
cards: List of Cards
The cards in hand.
"""
def __init__(self):
self.cards = []
def __str__(self):
return str([str(c) for c in self.cards])
def add(self, card):
""" Add a card to the hand. """
self.cards.append(card)
def score(self):
""" Compute the score of this hand. """
s = sum((c.primary_score for c in self.cards))
if s > 21:
s = sum((c.secondary_score for c in self.cards))
return s
class Game(object):
""" The game itself.
Contains all attributes and methods to hold and operate on the game state.
"""
def __init__(self):
self.deck = Deck()
self.player_hand = Hand()
self.dealer_hand = Hand()
def player_setup(self):
""" Initialise the player hand. """
self.player_hand.add(self.deck.draw())
self.player_hand.add(self.deck.draw())
def player_round(self):
""" Do a player round. """
while True:
# print status
print("Player hand is: {}".format(str(self.player_hand)))
player_score = self.player_hand.score()
print("Player score is: {}".format(player_score))
# check if player looses
if player_score > 21:
print("You loose!")
return False
# request input
print("draw? (y/n)")
response = input()
if response == "y":
# add another card
self.player_hand.add(self.deck.draw())
elif response == "n":
# player is done
return True
def dealer_setup(self):
""" Initialise the dealer hand. """
self.dealer_hand.add(self.deck.draw())
self.dealer_hand.add(self.deck.draw())
def dealer_round(self):
""" Do a dealer round. """
player_score = self.player_hand.score()
while True:
# print status
print("Dealer hand is: {}".format(str(self.dealer_hand)))
dealer_score = self.dealer_hand.score()
print("Dealer score is: {}".format(dealer_score))
time.sleep(DELAY)
if dealer_score > 21:
# check if the dealer drew too much
print("You win!")
break
elif dealer_score >= player_score:
# check if the dealer wins
print("You loose!")
break
else:
# dealer must draw more
time.sleep(DELAY)
print("Dealer will draw again...")
self.dealer_hand.add(self.deck.draw())
def play(self):
""" Play a game. """
print("Starting new game...")
# do the player round
self.player_setup()
still_playing = self.player_round()
if still_playing:
# do the dealer round
self.dealer_setup()
self.dealer_round()
game = Game()
game.play()
|
import unittest # Importing the unittest module
from password2 import Credential # Importing the contact class
class TestCredential(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
# Items up here .......
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_credential = Credential("instagram","hyacinthe","0123") # create contact object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_credential.account,"instagram")
self.assertEqual(self.new_credential.username,"hyacinthe")
self.assertEqual(self.new_credential.password,"0123")
def test_save_credential(self):
'''
test_save_contact test case to test if the contact object is saved into
the contact list
'''
self.new_credential.save_credential() # saving the new contact
self.assertEqual(len(Credential.credential_list),1)
# Items up here...
# setup and class creation up here
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
Credential.credential_list = []
# other test cases here
def test_save_multiple_credential(self):
'''
test_save_multiple_contact to check if we can save multiple contact
objects to our contact_list
'''
self.new_credential.save_credential()
test_credential = Credential("instagram","hyacinthe","0123") # new contact
test_credential.save_credential()
self.assertEqual(len(Credential.credential_list),2)
# More tests above
def test_delete_credential(self):
'''
test_delete_contact to test if we can remove a contact from our contact list
'''
self.new_credential.save_credential()
test_credential = Credential("instagram","hyacinthe","0123") # new contact
test_credential.save_credential()
self.new_credential.delete_credential()# Deleting a contact object
self.assertEqual(len(Credential.credential_list),1)
def test_credential_exists(self):
'''
test to check if we can return a Boolean if we cannot find the contact.
'''
self.new_credential.save_credential()
test_credential =Credential("instagram","hyacinthe","0123") # new contact
test_credential.save_credential()
credential_exists = Credential.credential_exist("hyacinthe")
self.assertTrue(credential_exists)
def test_display_all_credential(self):
'''
method that returns a list of all credentials saved
'''
self.assertEqual(Credential.display_credentials(),Credential.credential_list)
def test_find_credential_by_username(self):
'''
test to check if we can find a credential by username and display information
'''
self.new_credential.save_credential()
test_credential = Credential("account","username","0123") # new credential
test_credential.save_credential()
found_credential = Credential.find_by_username("hyacinthe")
self.assertEqual(found_credential.password,test_credential.password)
if __name__ == '__main__':
unittest.main()
|
# names = ["Joanna", "Luis", "Anna"]
#
# print(names)
# print(type(names))
#
#
# #indexing
# print(names[0])
#
# #index 1 to the last element
# print(names[1:])
ten_objects = ["orange", "banana", "pear", "strawberry", 500, "grape", "cherry", "pineapple", "eggs", "milk"]
print(type(ten_objects))
print("The 3rd element is: ", ten_objects[2])
print("The last element is: ",ten_objects[-1])
print(type(ten_objects[2]))
print("i like", ten_objects[5]+"'s")
|
import random
def starting():
user_input = input("\ndo you want to play a game? Y/N ")
if user_input == "Y" or user_input == "y":
start_game()
else:
print("Goodbye..!")
def start_game():
print("i will try to guess your number\n")
random_number_to_add_later = random.randrange(1,500)
computer_number = random.randrange(1,100)
computer_double = computer_number * 2
computer_add = computer_double + random_number_to_add_later
computer_half = computer_add / 2
computer_subtract = computer_half - computer_number
user_think_of_num = input("Think of a number...type y when done: ")
user_double_it = input("\ndouble your number, please type y when done: " )
print("\nadd", random_number_to_add_later, "with your current number.")
add_number = input("\nplease type y when done: ")
half_number = input("\nhalf your current number. please type y when done: ")
subtract_number = input("\nsubtract your current number with the number you started with. please type y when done: ")
print("\nis your number", computer_subtract,"?" )
am_i_correct = input("y/n: ")
if am_i_correct == "y":
print("\nI am a genius.\n")
else:
print("you win!")
play_again()
def play_again():
again = input("do you want to play again? y/n: ")
if again == "y":
starting()
else:
print("Goodbye...!")
starting() |
lst = [1,4,2,6,-2,3]
sml = lst[0]
for i in lst:
if(i < sml):
sml = i
print("Smallest Number = ",sml)
|
# abrindo arquivo excel
from openpyxl import load_workbook
# a função load_workbook('arquivo.xlsx') retorna um objeto
# book com os dados do arquivo excel. Para saber quais os nomes
# das planilhas existentes pode usar a propriedade book.sheetnames
book = load_workbook('sample.xlsx')
# print(book.sheetnames)
# obter o objeto sheet do arquivo aberto
sheet = book['Sheet']
# recuperar valor de uma célula, basta se referenciar a célula
# e obter a propriedade "value" dela.
valorA1 = sheet['A1'].value
print(valorA1)
# para saber quais as células ocupadas na planilha, é possivel
# obter os limites através da propriedade "dimensions" do objeto sheet.
# é possivel exibir o seu conteúdo, utilizando as dimensões
# junto com a estrutura de repetição "for" para poder ler todo
# o conteúdo da planilha de maneira dinâmica
d = sheet.dimensions
for c1, c2 in sheet[d]:
print(c1.value+" "+str(c2.value))
if type(c2.value) != str :
soma = soma + c2.value
print("Soma total..: ", soma)
|
start = '''
It is the year 2030, global warming has not been solved, and because humans suck
we have broke out in a zombie apocalypse. Your goal is to survive, but if you
decide that you don't want to anymore than that is cool too. You do you homie.
'''
keepplaying = "yes"
print(start)
while keepplaying == "Yes" or keepplaying == "yes":
print(" ")
print("You wake up in the morning and see no one in sight, not even your dog.")
userChoice = input("Do you go outside to meet someone or stay indoors? Type 1 to go outside or 2 to stay indoors.")
if userChoice == "2":
print(" ")
print("Congrats! You didn't die, since you were too scared to even go outside")
print("The zombies weren't able to break through, since they didn't even think there was anyone inside.")
keepplaying = "no"
elif userChoice == "1":
print(" ")
print("You realize you have no survival skills and didn't even bring a weapon with you.")
print("You didn't even make it a mile out of your house before you got killed by a zombie in 7-11")
print(" ")
keepplaying = input("Would you like to try again? Type yes or no. ")
if keepplaying == "no":
quit()
else:
print(" ")
print("Please select one of the valid options: 1 or 2.")
keepplaying = input("would you like to try again? Type yes or no.")
if keepplaying == "no":
quit()
keepplaying = "yes"
while keepplaying == "Yes" or keepplaying == "yes":
print(" ")
print("Someone is knocking in your door, they don't make any sounds that resemble a zombie.")
userChoice = input("Do you open the door for them or do you not answer to the door? Type 1 to open the door or type 2 to not.")
if userChoice == "1":
print(" ")
print("You escaped death once again! There is no need to be selfish and let others die.")
print("Liam Neeson is at the door and behind him is a van of supplies that will keep you guys alive for about 6 months.")
elif userChoice == "2":
print(" ")
print("What kind of human are you?")
print("This is the reason why this apocalypse even started. Selfish.")
print("You could have met Liam Neeson but instead you were an introvert that failed to get supplies")
print(" ")
keepplaying = input("Would you like to try again? Type yes or no. ")
if keepplaying == "no":
quit()
else:
print(" ")
print("Please select one of the valid options: 1 or 2.")
keepplaying = input("would you like to try again? Type yes or no.")
if keepplaying == "no":
quit()
|
def isPalindrome(s):
return s == s[::-1]
def dec_to_bin(x):
return int(bin(x)[2:])
# Driver code
i = 11
s = str(11)
b = dec_to_bin(i)
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
print(b)
|
class PiggyBank:
def __init__(self,dollars,cents):
if cents < 100:
self.dollars = dollars
self.cents = cents
else:
self.dollars = dollars + cents // 100
self.cents = cents - 100 * (cents//100)
def add_money(self,dollars,cents):
self.dollars += dollars
self.cents += cents
if self.cents >= 100:
self.dollars = self.dollars + self.cents // 100
self.cents = self.cents - 100 * (self.cents//100)
|
##### 2.2
# Write Python code that prints out the number of hours in 7 weeks.
print
7 * 7 * 24
# 1176
##### 2.6 Bodacious Udacity
# Given the variables s and t defined as:
s = 'udacity'
t = 'bodacious'
# write Python code that prints out udacious
# without using any quote characters in
# your code.
print
s[:2] + t[3:]
# udacious
##### 2.7
# Assume text is a variable that
# holds a string. Write Python code
# that prints out the position
# of the first occurrence of 'hoo'
# in the value of text, or -1 if
# it does not occur at all.
text = "first hoo"
# ENTER CODE BELOW HERE
print
text.find('hoo')
# 6
##### 2.8 Find 2
# Write Python code
# that prints out the position
# of the second occurrence of 'zip'
# in text, or -1 if it does not occur
# at least twice.
text = "all zip files are zipped"
first_zip = text.find('zip')
second_zip = text.find('zip', first_zip + 1)
print
second_zip
# OR
first_zip = text.find('zip')
print
text.find('zip', first_zip + 1)
# OR
print
text.find('zip', text.find('zip') + 1)
##### 2.9 Rounding Numbers
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
x = 3.14159
# ENTER CODE BELOW HERE
print
round(3.14159)
print
round(2.5)
print
round(1.4)
print
round(3.5)
|
#!/usr/bin/env python
# import re
# import math
# import collections
DEFAULT_INPUT_FILE = "input/part1.txt"
def perform_calculation(codes, index=0):
code = codes[index]
if code == 1:
a = codes[index+1]
b = codes[index+2]
c = codes[index+3]
codes[c] = codes[a] + codes[b]
elif code == 2:
a = codes[index+1]
b = codes[index+2]
c = codes[index+3]
codes[c] = codes[a] * codes[b]
elif code == 99:
return
perform_calculation(codes, index=index+4)
def main(args):
with open(args.file, "r") as fh:
for line in fh:
if line.strip() == '':
pass
x = map(int, line.split(','))
x[1] = 12
x[2] = 2
perform_calculation(x)
print("value at index 0 is {}".format(x[0]))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='Input file, default: {}'.format(DEFAULT_INPUT_FILE), default=DEFAULT_INPUT_FILE)
args = parser.parse_args()
main(args)
|
#!/usr/bin/env python
import re
# import math
# import collections
from itertools import permutations
from fractions import gcd
# Wrong answer: 9172794540
DEFAULT_INPUT_FILE = "input/part1.txt"
DEFAULT_STEPS = 5
class Moon(object):
def __init__(self, name, x, y, z):
self.name = name
self.x = x
self.y = y
self.z = z
self.xv = 0
self.yv = 0
self.zv = 0
self.xc = 0
self.yc = 0
self.zc = 0
def __repr__(self):
return "name={}, pos=<x={}, y={}, z={}>, vel=<xv={}, yv={}, zv={}>".format(self.name, self.x, self.y, self.z, self.xv, self.yv, self.zv)
def get_change(self, a, b):
if a < b:
return 1
elif a > b:
return -1
return 0
def apply_gravity_changes(self):
self.xv += self.xc
self.yv += self.yc
self.zv += self.zc
self.xc = 0
self.yc = 0
self.zc = 0
def add_gravity_changes(self, other_moon):
self.xc += self.get_change(self.x, other_moon.x)
self.yc += self.get_change(self.y, other_moon.y)
self.zc += self.get_change(self.z, other_moon.z)
def apply_velocity(self):
self.x += self.xv
self.y += self.yv
self.z += self.zv
@property
def total_energy(self):
return self.potential_energy * self.kinetic_energy
@property
def potential_energy(self):
return abs(self.x) + abs(self.y) + abs(self.z)
@property
def kinetic_energy(self):
return abs(self.xv) + abs(self.yv) + abs(self.zv)
def print_moons(moons, step = 0):
print("Step: {}".format(step))
for m in moons:
print(m)
def get_factors(n):
f = []
for i in range(2,n):
if n % i == 0:
f.append(i)
return f
def is_prime(n):
for i in range(2,n):
if n % i == 0:
return False
return True
def get_lcm(nums):
max_values = {}
for i in nums:
factors = get_factors(i)
prime_factors = filter(is_prime, factors)
for pf in set(prime_factors):
c = prime_factors.count(pf)
if pf not in max_values or c > max_values[pf]:
max_values[pf] = c
x = [k * v for k,v in max_values.items()]
lcm = 1
for n in x:
lcm *= n
return lcm
def main(args):
moons = []
with open(args.file, "r") as fh:
moon_count = 0
for line in fh:
if line.strip() == '':
pass
mobj = re.match(r'<x=(\-?\d+), y=(\-?\d+), z=(\-?\d+)>', line)
if mobj:
moons.append(Moon(str(moon_count), int(mobj.group(1)), int(mobj.group(2)), int(mobj.group(3))))
moon_count += 1
moon_perms = list(permutations(moons, 2))
if args.debug:
print_moons(moons)
initial_locations = [(m.x, m.y, m.z, m.xv, m.yv, m.zv) for m in moons]
previous_locations = [{(m.x, m.y, m.z, m.xv, m.yv, m.zv): 0} for m in moons]
cycle_steps = [None for x in moons]
count_cycles = [0 for x in moons]
freq_counts = [{(m.x, m.y, m.z, m.xv, m.yv, m.zv): 0} for m in moons]
step_count = 0
while True:
step_count += 1
for (m1, m2) in moon_perms:
m1.add_gravity_changes(m2)
for i,m in enumerate(moons):
m.apply_gravity_changes()
m.apply_velocity()
if cycle_steps[i] is None or count_cycles[i] < 100:
p = (m.x, m.y, m.z, m.xv, m.yv, m.zv)
# if p == initial_locations[i]:
# print("Got back to initial location for moon {} at step {}".format(m.name, step_count))
# cycle_steps[i] = step_count
if p in previous_locations[i]:
print("Hit previous location (from step {}) for moon {} at step {}: {}".format(previous_locations[i][p], m.name, step_count, p))
cycle_steps[i] = step_count
count_cycles[i] += 1
freq_counts[i][p] += 1
else:
previous_locations[i][p] = step_count
freq_counts[i][p] = 1
if all(cycle_steps) and all([bool(q >= 100) for q in count_cycles]):
break
if args.debug:
print_moons(moons, n)
for n,m in enumerate(moons):
print("cycle steps for {}: {}".format(m.name, cycle_steps[n]))
foo = filter(lambda x: x[1] > 1, freq_counts[n])
print("freq_counts for {}: {}".format(m.name, foo))
# lcm = get_lcm(cycle_steps)
# print("LCM: {}".format(lcm))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='Input file, default: {}'.format(DEFAULT_INPUT_FILE), default=DEFAULT_INPUT_FILE)
parser.add_argument('-s', '--steps', help="number of steps, default: {}".format(DEFAULT_STEPS), type=int, default=DEFAULT_STEPS)
parser.add_argument('-d', '--debug', help="debug", default=False, action="store_true")
parser.add_argument('-T', '--test_cycle', help="Planet index to test cycling on", type=int)
args = parser.parse_args()
main(args)
|
#!/usr/bin/env python
from math import floor
DEFAULT_INPUT_FILE = "input/part1.txt"
def main(args):
with open(args.file, "r") as fh:
total = 0
for line in fh:
if line.strip() == '':
pass
x = int(line.strip())
total += floor(x/3) - 2
print(int(total))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='Input file, default: {}'.format(DEFAULT_INPUT_FILE), default=DEFAULT_INPUT_FILE)
args = parser.parse_args()
main(args)
|
# -*- coding: utf8
'''ContiguousID class'''
from __future__ import print_function, division
from collections import Mapping
class ContiguousID(Mapping):
'''
A ContiguousID is a dict in which keys map to integer values where values
are contiguous integers.
Example:
>>> x = ContiguousID()
>>> x['a']
0
>>> x['b']
1
>>> x['a']
0
>>> x['c']
2
This class does not support setting items, values are automatic determined
when the item is first accessed.
'''
def __init__(self):
'''
Creates a new empty mapping.
'''
self.mem = {}
self.reverse = {}
self.curr_id = -1
def __getitem__(self, key):
'''
Get's the value associated with the item. If the item has already been
"looked up" it returns the previous key. Else, it will return the next
integer beginning with 0. Example:
>>> x = ContiguousID()
>>> x['a']
0
>>> x['b']
1
>>> x['a']
0
>>> x[0]
2
'''
if key in self.mem:
return self.mem[key]
else:
self.curr_id += 1
self.mem[key] = self.curr_id
self.reverse[self.curr_id] = key
return self.curr_id
def boost(self, boost_val):
'''
Boost all ids by increment the `boost_val` param.
Arguments
---------
boost_val: int
The value to boost by
'''
for key in self.mem.keys(): #This creates a copy, concurrent safe.
self.mem[key] = self.mem[key] + boost_val
def reverse_lookup(self, id_):
return self.reverse[id_]
def __iter__(self):
return iter(self.mem)
def __len__(self):
return len(self.mem)
|
import time
import os
import sys
import transposition
class InvalidInputException(Exception):
pass
def main():
mode = input("Enter 'E' to encrypt or 'D' to decrypt ")
input_filename = input('Enter filename for input text: ')
if not os.path.exists(input_filename):
raise InvalidInputException("Input file does not exist")
output_filename = input('Enter filename for output: ')
if os.path.exists(output_filename):
proceed = input("Output filename already exists. Continue? (Y/N)")
if proceed not in ('Y', 'y', 'yes'):
sys.exit()
key = int(input('Enter the key value: '))
text = ''
with open(input_filename, encoding='utf-8') as input_file:
text = input_file.read()
start_translate_time = time.time()
if mode in ('E', 'e', 'encrypt'):
translated = transposition.encode_transposition(text, key)
elif mode in ('D', 'd', 'decrypt'):
translated = transposition.decode_transposition(text, key)
translate_time = round(time.time() - start_translate_time, 2)
print('Translated in ', translate_time, ' seconds')
start_write_time = time.time()
with open(output_filename, mode='w', encoding='utf-8') as output_file:
output_file.write(translated)
write_time = round(time.time() - start_write_time, 2)
total_time = translate_time + write_time
print('Translated/wrote ', len(text), ' chars in ', total_time, ' seconds')
if __name__ == '__main__':
main()
|
from tkinter import *
class VentanaPrincipal(Frame):
def __init__(self, geom):
Frame.__init__(self, )
self.hig, self.wid = geom
Label(self, text='Cantidad de alimentos escogidos por grupo etario Diario', font=18).place(x=20, y=30)
Label(self, text='Edad', font=12).place(x=100, y=60)
Label(self, text='Hombre', font=12).place(x=20, y=80)
Label(self, text='0-14').place(x=100, y=100)
Label(self, text='15-64').place(x=100, y=130)
Label(self, text='65+').place(x=100, y=160)
Label(self, text='Mujer', font=12).place(x=20, y=190)
Label(self, text='0-14').place(x=100, y=220)
Label(self, text='15-64').place(x=100, y=250)
Label(self, text='65+').place(x=100, y=280)
Label(self, text='Nuez[gr]').place(x=190, y=60)
Label(self, text='Papa Cocida[gr]').place(x=240, y=60)
Label(self, text='Espinaca[gr]').place(x=330, y=60)
Label(self, text='Pimiento Rojo[gr]').place(x=410, y=60)
Label(self, text='Almendras[gr]').place(x=500, y=60)
Label(self, text='230[gr]').place(x=190, y=100)
Label(self, text='210[gr]').place(x=240, y=100)
Label(self, text='60[gr]').place(x=330, y=100)
Label(self, text='10[gr]').place(x=410, y=100)
Label(self, text='10[gr]').place(x=500, y=100)
Label(self, text='270[gr]').place(x=190, y=130)
Label(self, text='250[gr]').place(x=240, y=130)
Label(self, text='50[gr]').place(x=330, y=130)
Label(self, text='120[gr]').place(x=410, y=130)
Label(self, text='10[gr]').place(x=500, y=130)
Label(self, text='80[gr]').place(x=190, y=160)
Label(self, text='130[gr]').place(x=240, y=160)
Label(self, text='290[gr]').place(x=330, y=160)
Label(self, text='170[gr]').place(x=410, y=160)
Label(self, text='60[gr]').place(x=500, y=160)
Label(self, text='140[gr]').place(x=190, y=220)
Label(self, text='180[gr]').place(x=240, y=220)
Label(self, text='0[gr]').place(x=330, y=220)
Label(self, text='100[gr]').place(x=410, y=220)
Label(self, text='60[gr]').place(x=500, y=220)
Label(self, text='20[gr]').place(x=190, y=250)
Label(self, text='200[gr]').place(x=240, y=250)
Label(self, text='60[gr]').place(x=330, y=250)
Label(self, text='20[gr]').place(x=410, y=250)
Label(self, text='180[gr]').place(x=500, y=250)
Label(self, text='0[gr]').place(x=190, y=280)
Label(self, text='190[gr]').place(x=240, y=280)
Label(self, text='220[gr]').place(x=330, y=280)
Label(self, text='140[gr]').place(x=410, y=280)
Label(self, text='50[gr]').place(x=500, y=280)
|
class Person:
def __init__(self, f, l):
self.first = f
self.last = l
def print(self):
print(self.first, self.last)
def swapFirstLast(p):
p.first , p.last = p.last, p.first
person = Person("Jon", "Snow")
person.print()
swapFirstLast(person)
person.print()
|
import time
DIR_RIGHT = 0
DIR_UP = 1
DIR_LEFT = 2
DIR_DOWN = 3
class AdventOfCode:
def __init__(self, filename):
with open(filename) as f:
self.input = f.read().splitlines()
def make_grid(self):
grid = Grid(len(self.input[0]), len(self.input))
for y, line in enumerate(self.input):
for x, char in enumerate(line):
if char == '/':
grid.add_corner(x, y, 1)
elif char == '\\':
grid.add_corner(x, y, -1)
elif char == '+':
grid.add_intersection(x, y)
elif char == '>':
grid.add_cart(Cart(x, y, DIR_RIGHT))
elif char == '^':
grid.add_cart(Cart(x, y, DIR_UP))
elif char == '<':
grid.add_cart(Cart(x, y, DIR_LEFT))
elif char == 'v':
grid.add_cart(Cart(x, y, DIR_DOWN))
elif char in ' -|':
pass
else:
raise Exception(f'Unhandled character! ({char})')
return grid
def part1(self):
self.grid = self.make_grid()
while not self.grid.wreck_location:
self.grid.process_step()
return self.grid.wreck_location
def part2(self):
self.grid = self.make_grid()
while len(self.grid.carts) > 1:
self.grid.process_step()
last_cart = self.grid.carts.pop()
return (last_cart.x, last_cart.y)
class Grid:
def __init__(self, width, height):
self.w = width
self.h = height
self.corners = {}
self.intersections = set()
self.carts = set()
self.wreck_location = None
def print(self):
chars = [[' ' for i in range(self.w)] for i in range(self.h)]
for corner in self.corners:
corner_type = self.corners[corner]
if corner_type == 1:
chars[corner[1]][corner[0]] = '/'
else:
chars[corner[1]][corner[0]] = '\\'
for inter in self.intersections:
chars[inter[1]][inter[0]] = '+'
for cart in self.carts:
char = {
DIR_RIGHT: '>',
DIR_UP: '^',
DIR_LEFT: '<',
DIR_DOWN: 'v',
}.get(cart.direction)
chars[cart.y][cart.x] = char
for line in chars[0:10]:
print(''.join(line))
def add_corner(self, x, y, corner_type):
self.corners[(x, y)] = corner_type
def add_intersection(self, x, y):
self.intersections.add((x, y))
def add_cart(self, cart):
self.carts.add(cart)
def process_step(self):
# Order carts for processing
carts_ordered = list(sorted(self.carts, key=lambda c: c.y*1000 + c.x))
# Process carts:
for c in carts_ordered:
if c.crash_location:
continue
# Move
c.move()
# Check for collisions
for c2 in carts_ordered:
if c2.crash_location or c2 is c:
continue
if c.x == c2.x and c.y == c2.y:
c.crash_location = (c.x, c.y)
c2.crash_location = (c.x, c.y)
self.wreck_location = (c.x, c.y)
self.carts.remove(c)
self.carts.remove(c2)
break
# Turn if needed
if (c.x, c.y) in self.corners:
corner_type = self.corners[(c.x, c.y)]
if corner_type == 1:
c.direction = {
DIR_RIGHT: DIR_UP,
DIR_UP: DIR_RIGHT,
DIR_LEFT: DIR_DOWN,
DIR_DOWN: DIR_LEFT
}.get(c.direction)
elif corner_type == -1:
c.direction = {
DIR_RIGHT: DIR_DOWN,
DIR_DOWN: DIR_RIGHT,
DIR_LEFT: DIR_UP,
DIR_UP: DIR_LEFT
}.get(c.direction)
if (c.x, c.y) in self.intersections:
c.turn_intersection()
class Cart:
TURN_LEFT = 0
TURN_STRAIGHT = 1
TURN_RIGHT = 2
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.direction = direction
self.next_turn = Cart.TURN_LEFT
self.crash_location = None
def move(self):
if self.direction == DIR_RIGHT:
self.x += 1
elif self.direction == DIR_LEFT:
self.x -= 1
elif self.direction == DIR_UP:
self.y -= 1
elif self.direction == DIR_DOWN:
self.y += 1
else:
raise Exception(f'Unhandled direction! {self.direction}')
def turn_intersection(self):
if self.next_turn == Cart.TURN_LEFT:
self.direction = (self.direction + 1) % 4
elif self.next_turn == Cart.TURN_RIGHT:
self.direction = (self.direction + 3) % 4
self.next_turn = (self.next_turn + 1) % 3
|
class AdventOfCode:
def __init__(self, filename):
with open(filename) as f:
lines = f.read().splitlines()
self.nodes = {}
for line in lines:
node = TreeNode(line)
self.nodes[node.id] = node
self.top_node = None
def part1(self):
for node in self.nodes.values():
for child_str in node.child_strings:
node.add_child(self.nodes[child_str])
while node.parent:
node = node.parent
self.top_node = node
return node.id
def part2(self):
node_before = self.top_node
while True:
node_after = node_before.find_imbalance()
if node_after == node_before:
break
node_before = node_after
return node_after.parent.correct_child_weight() - sum(node_after.children_weights())
class TreeNode:
def __init__(self, node_string):
self.string = node_string
split_str = node_string.split()
self.id = split_str[0]
self.weight = int(split_str[1][1:-1])
self.total_weight = -1
self.good_kid_weight = -1
self.child_strings = set()
if len(split_str) > 2:
for i in range(len(split_str)-3):
self.child_strings.add(split_str[i+3].strip(','))
self.parent = None
self.children = set()
def add_child(self, child_node):
self.children.add(child_node)
child_node.parent = self
def get_total_weight(self):
if self.total_weight > -1:
return self.total_weight
self.total_weight = self.weight + sum(child.get_total_weight() for child in self.children)
return self.total_weight
def find_imbalance(self):
if not self.children:
return self
if self.good_kid_weight == -1:
child_list = list(self.children)
self.good_kid_weight = child_list[0].get_total_weight() if child_list[0].get_total_weight() == child_list[1].get_total_weight() else child_list[2].get_total_weight()
for child in self.children:
if child.get_total_weight() != self.good_kid_weight:
return child
return self
def correct_child_weight(self):
if self.good_kid_weight > -1:
return self.good_kid_weight
child_list = list(self.children)
self.good_kid_weight = child_list[0].get_total_weight() if child_list[0].get_total_weight() == child_list[1].get_total_weight() else child_list[2].get_total_weight()
return self.good_kid_weight
def children_weights(self):
if not self.children:
return tuple([0])
return [child.weight + sum(child.children_weights()) for child in self.children]
|
#the game!
import random
print("This is me making a game!")
#character_stats():
name=""
level=1
max_hp=10+(level*5)
current_hp=15
current_exp=0
req_exp=10*level
max_level=10
#name=input("What is your name? ")
print("Your name is",name)
print("level:",level)
print("Max HP:", max_hp)
print("Current HP:", current_hp)
print("Current Exp:", current_exp)
print("Exp for level up:", req_exp)
print("======================")
#equipment_stats():
weapon="fist"
weapon_damage=1
armour="none"
armour_defence=0
#weapon dict
weapon_list = {
1:{"name": "dagger", "damage":2},
2:{"name": "sword", "damage":3},
3:{"name": "dragon mace", "damage":5}
}
#armour dict
armour_list = {
1:{"name": "leather armour", "defence": 1},
2:{"name": "platemale armour", "defence": 2},
3:{"name": "dragon armour", "defence": 3}
}
#treasure event
def treasure(treas_num):
global weapon
global weapon_damage
global armour
global armour_defence
if treas_num in (0,1,2,3,4):
weap_num=random.randint(1,10)
print("weap_num",weap_num)
if weap_num in (1,2,3,4):
weap_choice=1
elif weap_num in (5,6,7):
weap_choice=2
elif weap_num in (8,9):
weap_choice=3
else:
print("You found a broken weapon.")
return
print("You found a", weapon_list[weap_choice]["name"])
if weapon_list[weap_choice]["damage"] > weapon_damage:
weapon = weapon_list[weap_choice]["name"]
weapon_damage = weapon_list[weap_choice]["damage"]
print("and equipped it.")
return weapon, weapon_damage
else:
print("but your current weapon is better.")
return
elif treas_num in (5,6,7,8,9):
print("You found some armour.")
arm_num=random.randint(1,10)
print("arm_num",arm_num)
if arm_num in (1,2,3,4):
arm_choice=1
elif arm_num in (5,6,7):
arm_choice=2
elif arm_num in (8,9):
arm_choice=3
else:
print("You found some broken armour.")
print("You found some", armour_list[arm_choice]["name"])
if armour_list[arm_choice]["defence"] > armour_defence:
armour = armour_list[arm_choice]["name"]
armour_defence = armour_list[arm_choice]["defence"]
print("and equipped it.")
return armour, armour_defence
else:
print("but your current armour is better.")
return
else:
print("You didn't find anything special")
turn=1
while turn <=10:
print("turn",turn)
treas_num=random.randint(0,10)
print("treas_num",treas_num)
treasure(treas_num)
turn+=1
print("---------------")
|
import numpy as np
import elliptical_u_est as ellip
# household functions
def FOCs(b_sp1, n_s, *args):
'''
For the S-period problem, we have 2S-1 FOCs corresponding to the savings variable b, and the labor supply variable n
Note that we were dealing with three dimensional vectors earlier. We now have an S-1 dim vector corresponding
to b, and an S dim vector corresponding to n.
Refer to equations (4.9) and (4.10) of chapter 4 for details on where the variables foc_errors_b and foc_errors_n are coming from
Args:
b_sp1: The savings values for each period. The call to this function should provide initial guesses for this variable.
n_s: The labor supply values for each period. The call to this function should provide initial guesses for this variable.
l_tilde: maximum amount of labor supply
chi: scale parameter
theta: Frisch elasticity of labor supply
n is not contained in the remaining arguments anymore. If someone decides to change this, please provide detailed documentation
on why you are doing so.
Returns:
foc_errors: A list where the first S-1 values are b2, b3, ..., bS, and the next S values are n1, n2, ..., nS.
'''
beta, sigma, r, w, b_init, l_tilde, chi, theta = args
b_s = np.append(b_init, b_sp1) # When working on SS.py, note that b_sp1_guess is now of length S-1
b_sp1 = np.append(b_sp1, 0.0)
c = get_c(r, w, n_s, b_s, b_sp1)
mu_c = mu_cons(c, sigma)
mu_n = mu_labor(n_s, l_tilde, chi, theta)
# First get the Euler equations defined by Equation (4.10) - S-1 of these
lhs_euler_b = mu_c
rhs_euler_b = beta * (1+r) * mu_c
foc_errors_b = lhs_euler_b[:-1] - rhs_euler_b[1:]
# The above line doesn't need to be changed since it works for a general S as well (writing out the vectors helps to see this)
# Next get the Euler equations defined by (4.9) - S of these
lhs_euler_n = w * mu_c
rhs_euler_n = mu_n
foc_errors_n = lhs_euler_n - rhs_euler_n
foc_errors = np.append(foc_errors_b, foc_errors_n)
return foc_errors
def get_c(r, w, n, b_s, b_sp1):
'''
Use the budget constraint to solve for consumption
'''
c = w * n + (1 + r) * b_s - b_sp1
return c
def mu_cons(c, sigma):
'''
Computes marginal utility with respect to consumption.
Please note that this was initially called u_prime. If anyone finds function calls on u_prime, please change it to mu_cons
Marginal utility of consumption
'''
mu_c = c ** -sigma
return mu_c
def mu_labor(n_s, l_tilde, chi, theta):
'''
Computes marginal utility with respect to labor supply
'''
b_ellipse, nu = ellip.estimation(theta, l_tilde) # b_ellipse is the constant defined in Equation (4.9) - has nothing to do with savings
mu_n = chi * (b_ellipse / l_tilde) * (n_s / l_tilde) ** (nu - 1) * (1 - (n_s / l_tilde) ** nu) ** ((1 - nu) / nu )
return mu_n |
# MIT 6.189
# Project 1
# Author: Denis Savenkov
# File: questions sol.py
def all_less_6(a_list):
for val in a_list:
if val >= 6:
return False
return True
list1 = [1, 5, 3, 4]
list2 = [5, 3, 7, 5]
print all_less_6(list1)
print all_less_6(list2)
def one_less_6(a_list):
for val in a_list:
if val < 6:
return True
return False
list3 = [7, 8, 7, 9]
list4 = [7, 2, 5, 8]
print one_less_6(list3)
print one_less_6(list4)
|
# Savenkov Denis
# rps.py
#create variables for rock,paper,scissor and for results:
r = "rock"
p = "paper"
s = "scissors"
t = "Tie."
p1 = "Player 1 wins."
p2 = "Player 2 wins."
#get figure from players
player1 = raw_input("Player 1? ")
player2 = raw_input("Player 2? ")
#create conditions for output
if (player1 == r and player2 == r):
print t
elif (player1 == r and player2 == s):
print p1
elif (player1 == r and player2 == p):
print p2
elif (player1 == s and player2 == s):
print t
elif (player1 == s and player2 == r):
print p2
elif (player1 == s and player2 == p):
print p1
elif (player1 == p and player2 == p):
print t
elif (player1 == p and player2 == r):
print p1
elif (player1 == p and player2 == s):
print p2
#if not valid input print out a message
else:
print "This is not a valid object selection"
|
# Denis Savenkov
# zellers.py
# collect date of birth from user
print "Enter your date of birth:"
month = input("Month as a number between 1 and 12, starting from March? ")
day = input("Day? ")
year = input("Year? ")
#create zellers algorithm
a = month
if a == 11 or a == 12:
c = c - 1
b = day
c = year % 100
d = year / 100
w = (13*a - 1) / 5
x = c / 4
y = d / 4
z = w + x + y + b + c - 2*d
r = z % 7
if r < 0:
r += 7
#print out the day
if r == 0:
print "Sunday"
if r == 1:
print "Monday"
if r == 2:
print "Tuesday"
if r == 3:
print "Wednesday"
if r == 4:
print "Thursday"
if r == 5:
print "Friday"
if r == 6:
print "Saturday"
|
a = int(input("Введите А = "))
b = int(input("Введите B = "))
ch = 0
nech = 0
n = a
while (n >= a) and (n <= b) and (a <= 100) and (b <= 100):
if n % 2 == 0:
ch = ch + n
n = n + 1
else:
nech = nech + n
n = n + 1
print("Сумма четных = " + str(ch))
|
"""Defines class responsible for cars' table in database."""
import sqlite3
class CarsDatabase:
"""This class operates on a table 'cars' in database."""
def __init__(self, db):
"""Inits CarsDatabase."""
self.conn = sqlite3.connect(db)
self.c_cursor = self.conn.cursor()
self.c_cursor.execute("""CREATE TABLE IF NOT EXISTS cars (
car_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
brand TEXT,
model TEXT,
color TEXT,
year INTEGER,
instock INTEGER NOT NULL DEFAULT 1,
price REAL
)""")
self.conn.commit()
def fetch(self):
"""Displays all cars in database."""
self.c_cursor.execute("SELECT car_id, brand, model, color, year, instock, price FROM cars")
return self.c_cursor.fetchall()
def fetch_available(self):
"""Displays all cars that are not booked by anybody."""
self.c_cursor.execute(
"SELECT car_id, brand, model, color, year, instock, price FROM cars WHERE instock=1")
return self.c_cursor.fetchall()
def insert(self, brand, model, color, year, price):
"""Inserts car to a database."""
self.c_cursor.execute("INSERT INTO cars (brand,model,color,year,price) VALUES (?,?,?,?,?)",
(brand, model, color, year, price))
self.conn.commit()
def remove(self, id_car):
"""Deletes car from a database."""
self.c_cursor.execute("DELETE FROM cars WHERE car_id=?", (id_car,))
self.conn.commit()
def update(self, id_car, brand, model, color, year, price):
"""Updates chosen car."""
self.c_cursor.execute(
"UPDATE cars SET brand=?, model=?,color=?,year=?,price=? WHERE car_id=?",
(brand, model, color, year, price, id_car))
self.conn.commit()
def outofstock(self, id_car):
"""Sets status of chosen car to 0."""
self.c_cursor.execute("UPDATE cars SET instock=0 WHERE car_id=?", (id_car,))
self.conn.commit()
def isout(self, id_car):
"""Returns the column 'instock' of chosen car."""
self.c_cursor.execute("SELECT instock FROM cars WHERE car_id=?", (id_car,))
return self.c_cursor.fetchone()
def search(self, year, price, brand='', model='', color=''):
"""Returns cars that meet the criteria."""
self.c_cursor.execute(
"SELECT car_id, brand, model, color, year, instock, price FROM cars WHERE brand=? OR"
" model=? OR color=? OR year=? OR price=?",
(brand.capitalize(), model.capitalize(), color.capitalize(), year, price))
return self.c_cursor.fetchall()
def search_available(self, year, price, brand='', model='', color=''):
"""Returns cars that meet the criteria."""
self.c_cursor.execute(
"SELECT car_id, brand, model, color, year, instock, price FROM cars WHERE (brand=? OR"
" model=? OR color=? OR year=? OR price=?) AND (instock=1)",
(brand.capitalize(), model.capitalize(), color.capitalize(), year, price))
return self.c_cursor.fetchall()
|
def swap(index1, index2, array):
temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
return array
def bubble_sort(array):
length = len(array)
for i in range(length):
swaps = 0
for n in range(length - 1 - i):
if array[n] > array[n+1]:
swap(n, n+1, array)
swaps += 1
if swaps == 0:
break
alist = [5, 4, 3, 2, 1]
bubble_sort(alist)
print alist
|
# Princeton algo course
# Linear time
import random
def shuffle(alist):
# Iterate through all positions of alist
for i in range(1, len(alist)):
# Generate a random number between 0 and i
random_index = random.randrange(0, i)
# Swap the values of random number and i
temp = alist[i]
alist[i] = alist[random_index]
alist[random_index] = temp
return alist
print shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]) |
from tkinter import *
root = Tk()
label1 = Label(root, text="First label", bg="Grey", fg="White")
# the fill=X adjusts the size of the label in the horizontal plane with change in the size of the window
label1.pack(fill=X)
label2 = Label(root, text="Second label", bg="Black", fg="White")
# the fill=Y adjusts the size of the label in the vertical plane with change in the size of the window
# and the side=LEFT makes the widget appear on the left side of the window
label2.pack(side=LEFT, fill=Y)
root.mainloop()
|
'''
dengan membaca file kita bisa menampilkan isi dari sebuah file
sumber referensi: https://www.petanikode.com/python-file/
ditulis pada padal: 14-02-2021
'''
#membuka isi dari sebuah file
#r = read, memungkinkan untuk membaca isi dari sebuah file
file = open('file.txt', 'r')
#membaca hanya 1 baris
isi_file = file.readline()
#membaca semua baris pada file
isi_file2 = file.readlines()
#output 1 baris
print(isi_file)
#menampilkan semua isi dari file
for x in isi_file2:
print(x, end='')
#menutup isi dari file
file.close() |
'''
dengan menggunakan metode ini kita bisa menentukan jenis variable yang akan digunakan
sumber referensi: pintaar module
ditulis pada: 06-03-2021
'''
class Variable:
def __init__(self):
'''
Public Variable
Merupakan Variable yang dapat diakses semua orang dan dapat dipanggil dengan mudah seperti biasanya
'''
self.Var = 'Ini Public Variable'
'''
Protected Variable
Merupakan variable yang dapat diakses semua orang dan mirip seperti public variable yang membedakannya adalah pada underscore _
'''
self._Var = 'Ini Protected Variable'
'''
Private Variable
Merupakan Variable yang tidak dapat diakses. Variable jenis ini dapat diakses melalui panggilan difunction atau method
'''
self.__Var = 'Ini Private Variable'
def Pri_Var(self):
self.__Var = 'Ini Private Variable Yang Terpanggil'
return self.__Var
Variable_Class = Variable()
# Contoh untuk pemanggilan untuk public variable
print(Variable_Class.Var)
# Contoh untuk pemanggilan untuk protected variable
print(Variable_Class._Var)
# Dan ini contoh untuk private variable
# karena namanya private jadi tidak bisa dipanggil
# print(Variable_Class.__Var)
# untuk memanggil private variable yang dapat terpanggil bisa dilakukan apabila private variablenya berada pada function atau method
print(Variable_Class.Pri_Var())
|
entradaNum = list(map(int, input().split()))
entradaNum.sort()
entradaLet = input()
if (entradaLet == 'ABC'):
print(entradaNum[0], entradaNum[1], entradaNum[2])
elif (entradaLet == 'ACB'):
print(entradaNum[0], entradaNum[2], entradaNum[1])
elif (entradaLet == 'BAC'):
print(entradaNum[1], entradaNum[0], entradaNum[2])
elif (entradaLet == 'BCA'):
print(entradaNum[1], entradaNum[2], entradaNum[0])
elif (entradaLet == 'CAB'):
print(entradaNum[2], entradaNum[0], entradaNum[1])
elif (entradaLet == 'CBA'):
print(entradaNum[2], entradaNum[1], entradaNum[0])
|
import json
import requests
from datetime import datetime
from local import USERNAME, PASSWORD
def translate(text, source_language, target_language):
# GET REQUEST
url = "https://gateway.watsonplatform.net/language-translator/api/v2/translate"
querystring = {"text":text,"model_id":"{0}-{1}".format(source_language, target_language)}
response = requests.get(url,auth=(USERNAME, PASSWORD),params=querystring)
return response.text
if __name__ == '__main__':
text = input("In English what do you want to translate: ")
print("Now which language?")
print("Enter (1) Spanish")
print("Enter (2) Arabic")
print("Enter (3) French")
print("Enter (4) Portuguese")
print("Enter (5) Italian")
print("Enter (6) German")
print("Enter (7) Dutch")
which_language = str(input('Number from 1 to 7 for language to translate to: '))
if which_language == "1":
which_language = 'es'
elif which_language == "2":
which_language = 'ar'
elif which_language == "3":
which_language = 'fr'
elif which_language == "4":
which_language = 'pt'
elif which_language == "5":
which_language = 'it'
elif which_language == "6":
which_language = 'de'
elif which_language == "7":
which_language = 'nl'
else:
raise ValueError('The value entered, is not accepted.')
translation = translate(text,'en', which_language)
print('In your choice of language.\n')
print(translation)
|
#!/usr/bin/env python
'''
Counting DNA Nucleotides
'''
def count_dna_nucleobases(data):
'''
Count the number of times each DNA nucleobase occurs in data.
Input:
- data: string of DNA nucleotides
Output:
- A: number of times A occurs in data
- C: number of times C occurs in data
- G: number of times G occurs in data
- T: number of times T occurs in data
'''
count = {'A':0, 'C':0, 'G':0, 'T':0}
for base in data:
count[base] += 1
A, C, G, T = count['A'], count['C'], count['G'], count['T']
return A, C, G, T
def main():
with open('datasets/rosalind_dna.txt', 'r') as file:
data = file.read().rstrip('\n')
results = map(str, count_dna_nucleobases(data))
with open('output/001_DNA.txt', 'w') as output:
output.write(' '.join(results))
if __name__ == '__main__':
main() |
if __name__ == '__main__':
klist = [
"good ", "good ", "study",
" good ", "good", "study ",
"good ", " good", " study",
" good ", "good", " study ",
"good ", "good ", "study",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
]
print("编写Python程序打印输出字符串中重复的所有字符")
newlist=[i.strip() for i in klist]
newset={i for i in newlist}
for i in newset:
num=newlist.count(i)
if num>=2:
print("重复的单词为:{mya},重复的次数为:{mynum}".format(mya=i,mynum=num)) |
if __name__ == '__main__':
s=[1,2,3,4,5]
q=s.__len__()
print(q)
q=len(s)
print(q)
for l in s:
print("下标为{1}[{0}]".format(l.__index__()-1,l)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.