text
stringlengths 37
1.41M
|
---|
# Feature Category : sourcing_channel, residence_area_type
import pandas as pd
from sklearn import preprocessing
def categorize(df):
'''
This method takes panda.dataframe having single category column as its data as param.
It then does apply sklearn.preprocessing.LabelEncoder() on the category column
and then transforms singular category column into multiple columns using sklearn.preprocessing.OneHotEncoder()
'''
prefix = df.columns[0]+'_'
print('prefix :', prefix)
# Convert string values to numbers in target column
le = preprocessing.LabelEncoder()
df1 = df.apply(le.fit_transform)
new_cols = [prefix+c for c in le.classes_]
# Split One Column As Many
enc = preprocessing.OneHotEncoder() # 1. Instantiate
arr2d = enc.fit_transform(df1).todense() # 2&3. Fit n Transform returns 2d-array as sparse Matrix
df2 = pd.DataFrame(arr2d, columns=new_cols) # Convert array-Matrix to Pandas' DataFrame
return df2 |
#No argument
def func1():
print("I am a function")
func1() #prints the value
print(func1()) #prints the value through func1() and then python constant NONE as func1() does not retun a value
#With argument
def func2(a):
return("The cube of the given value is " + str(a**3))
func2(4)
print(func2(4))
#multiple argument
def add(*args):
sum=0
for x in args:
sum=sum + x
return sum
print(add(1,2,3,4,5))
####
def inc(a,b=1):
return(a+b)
a=inc(1)
a=inc(a,a)
print(a) |
# WAP
# 1
# 12
# 123
# 1234
# 12345
#example to print in same line or to avoid new line after each print. print(value, end="")
print("geeks", end =" ")
print("geeksforgeeks")
def function1():
for i in range(1,6):
for j in range(1,i+1):
print(j, end =" ")
print()
function1()
print()
for i in range(1,6):
for j in range(1,i+1):
print(i, end=" ")
print()
|
#read line by line
#upper to change all the content to upper case
fhand = open('test.txt')
inp = fhand.read()
print(inp.upper())
|
import random
import config as cfg
class Deck:
def __init__(self):
self.cards = self.init_deck()
self.remaining_cards = len(self.cards)
def init_deck(self):
cards = []
for colour in range(cfg.NUM_COLOURS):
for value in range(cfg.NUM_VALUES):
for i in range(cfg.NUM_CARDS_PER_VALUE[value]):
cards.append((colour, value))
random.shuffle(cards)
return cards
def draw_card(self):
assert(self.remaining_cards > 0)
self.remaining_cards -= 1
return self.cards.pop()
def remaining_cards(self):
return self.remaining_cards
|
import math
from numbers import Number
class Point:
"""this class create point you cant insert only int by defult is (0,0)"""
__counter = 0
def __init__(self, x=0.0, y=0.0):
if isinstance(x, Number) and isinstance(y, Number):
self.x = float(x)
self.y = float(y)
else:
raise TypeError("you need to insert int or float")
def __del__(self):
Point.__counter -= 1
del self
def __str__(self):
"""This method print the x and y var """
return "Point" + "(" + str(self.x) + "," + str(self.y) + ")"
def __add__(self, other):
"""this method take 2 Point and addition aim and return new point"""
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
def __iadd__(self, other):
"""this method take 2 Point and addition aim and return new point"""
self.x += other.x
self.y += other.y
return self
def __sub__(self, other):
"""this method take 2 Point and sun aim and return new point"""
x = self.x - other.x
y = self.y - other.y
return Point(x, y)
def __isub__(self, other):
"""this method take 2 Point and sun aim and return new point"""
self.x -= other.x
self.y -= other.y
return self
def __mul__(self, other):
x = self.x * other.x
y = self.y * other.y
return Point(x, y)
def __imul__(self, other):
self.x *= other
self.y *= other
return self
def __len__(self):
return len(self.__dict__)
def __truediv__(self, other):
if other.x != 0 and other.y != 0:
x = self.x / other.x
y = self.y / other.y
return Point(x, y)
def __itruediv__(self, other):
if other.x != 0:
self.x /= other
self.y /= other
return self
@staticmethod
def get_counter():
return Point.__counter
def distance_from_origin(self):
"""this func check the distance"""
return math.sqrt(self.x ** 2 + self.y ** 2)
if __name__ == "__main__":
"""EX1 """
print(Point.get_counter())
# a = Point(2, 2)
# b = Point(2, 2)
# c = Point(1, 2, 3)
# # a /= 2
# print(c)
# a.z = 5
#
# print(a.__len__())
#
# """EX2"""
# # print(a*b)
# print(id(a))
#
# p1_id = id(a)
# print(a)
# print(id(a) == p1_id)
#
# list_of_point = []
# for i in range(10):
# list_of_point.append(Point())
# print(Point.get_counter())
# for i in range(10):
# list_of_point[i].__del__()
# print(Point.get_counter())
|
from numbers import Number
class Point:
"""this class create point you cant insert only int by defult is (0,0)"""
def __init__(self, x=0.0, y=0.0):
""" Exercises 1 build constructor"""
if isinstance(x, Number) and isinstance(y, Number):
self.__x = float(x)
self.__y = float(y)
else:
self.x = 0
self.y = 0
print("you need to insert a number ")
@property
def x(self):
return self.__x
@x.setter
def x(self, val):
if isinstance(val, Number):
self.__x = val
else:
raise TypeError("You need to insert a number !")
@x.deleter
def x1(self):
"""Delete method for x """
print("You cant delete x")
@property
def y(self):
"""getter method"""
return self.__y
@y.setter
def y(self, val):
"""set the data for y """
if isinstance(self, val):
self.__y = val
else:
raise TypeError("You need to insert a number !")
@y.deleter
def y(self):
"""Delete method for x """
print("You cant delete x")
def __str__(self):
"""Print the data"""
return str(p.__x) + "," + str(p.__y)
class Property:
"""Exercises 2 implement descriptor class"""
def __init__(self, fget, fset=None, fdel=None, doc=None):
"""constructor for property"""
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self, instance, objtype=None):
"""implementation geter for property class """
if instance is None:
return self
if self.fget is None:
raise AttributeError("No attribute")
return self.fget(instance)
def __set__(self, instance, value):
"""implementation setter for property class """
if self.fset is None:
raise AttributeError("cant set attribute")
self.fset(instance, value)
def __delete__(self, obj):
"""implementation delete for property class """
if self.fdel is None:
raise AttributeError("cant delete attribute")
self.fdel(obj)
def getter(self, fget):
self.fget = fget
return self
def setter(self, fset):
self.fset = fset
return self
def deleter(self, fdel):
print("i am in dele func")
self.fdel = fdel
return self
class X:
def __init__(self, val):
"""Constructor"""
self.__x = int(val)
@Property
def x(self):
"""add the option for getter"""
return self.__x
@x.setter
def x(self, val):
"""add the option for setter"""
self.__x = int(val)
@x.deleter
def x(self):
"""add the option for del object """
print("i am in dele func")
del self.__x
if __name__ == "__main__":
"""EX1"""
p = Point(3, 3)
p.x = 10
del p.x
print(p)
"""EX2"""
a = X(0)
print(a.x)
a.x = 1
del (a.x)
|
from math import *
def divide(x, y):
if y < 1:
raise(Exception("The second argument must be larger than 1"))
if x == 0:
(q, r) = (0, 0)
return (q, r)
(q, r) = divide(floor(x/2), y)
q = 2*q
r = 2*r
if x%2 == 1:
r += 1
if r >= y:
r = r - y
q += 1
return (q, r)
|
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
def fibonacci():
i = 1
j = 2
k = 0
y = 0
listf = []
while (j < 4000000):
k = i + j
#listf.append(i)
if(j%2 == 0):
y += j
#listf.append(j)
i = j
j = k
return y
print fibonacci()
|
def main():
x = ["a","b","c"]
y = ["1","2","3"]
for a in x:
for b in y:
print(a,b)
main() |
def main():
print("range upto end num:")
for x in range(10):
#0-->5
print(x)
print("range function with starting and ending:")
for x in range(2,10):
#2-->9
print(x)
print("range function with jump:")
for x in range(2,30,3):
#2-->30 with 3 increment
print(x)
main() |
""" HW2.py
a cryptanalytic toolkit in Python to analyze the statistical properties of files
Usage: cipher.py COMMAND [OPTIONS] [ARGS]...
Commands:
dist Calculate frequency distributions of symbols...
Help for each command is avaible:
HW2.py COMMAND -h
Example usage:
Trigram distribution printed to console ( STDOUT indicated by '-' )
Qingchen Meng
"""
import click
class Distribution(object):
""" Base class for analysis routines for symbol distributions.
Results are dictionary objects with human readable keys.
"""
def to_readable(self):
""" Convert dictionary of symbols to readable text """
pp = []
for nary in self.result:
pp.append( "{}: {}\n".format( nary, self.result[nary]))
return ''.join(pp)
class Ngraph(Distribution):
""" Looking 'n' symbols at a time, create a dictionary
of the occurrences of the n-ary string of symbols.
Default is n=1, a monograph.
"""
def __init__(self, n=1 ):
self.n = n
def analyze(self, text):
n = self.n
self.result = {} # results are stored as a dictionary
for i in range( len(text) - n - 1 ):
nary = text[ i:i+n ]
if nary in self.result:
self.result[nary] += 1
else:
self.result[nary] = 1
return self.result
class Monograph(Distribution):
def analyze(self, text): self.result = Ngraph( n=1 ).analyze(text)
class Digraph(Distribution):
def analyze(self, text): self.result = Ngraph( n=2 ).analyze(text)
class Trigraph(Distribution):
def analyze(self, text): self.result = Ngraph( n=3 ).analyze(text)
# -- additional CLI for HW2
# collect all distribution routines for cli usage
dist_dict = {'mono':Monograph, 'di':Digraph, 'tri':Trigraph, 'ng':Ngraph}
dist_name_list =[ key for key in dist_dict]
# --- 'click' based command-line interface ------------------------------------
@click.version_option(0.1)
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
@click.pass_context # ctx
def cli(ctx):
""" A tool to encrypt or decrypt a file using simple ciphers. """
pass
@cli.command()
@click.option('--dtype', '-d', 'dist_name', type=click.Choice( dist_name_list ) )
@click.argument('input_file', type=click.File('rb'))
@click.argument('output_file', type=click.File('wb'))
def Dist(dist_name, input_file, output_file):
""" Calculate frequency distributions of symbols in files.
"""
D = dist_dict[dist_name] # instantiate class from dictionary
dist = D()
text = input_file.read()
dist.analyze(text)
output_file.write( dist.to_readable() )
charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ" # The list of characters to be encrypted
numchars=len(charset) # number of characters that are in the list for encryption
def caesar_crack(crackme,i,newkey):
print '[*] CRACKING - key: %d; ciphertext: %s' % (i,crackme)
crackme=crackme.upper()
plaintext='' #initialise plaintext as an empty string
while i <= 26:
for ch in crackme: #'for' will check each character in plaintext against charset
if ch in charset:
pos=charset.find(ch) #finds the position of the current character
pos=pos-newkey
else:
new='' # do nothing with characters not in charet
if pos>=len(charset): #if the pos of the character is more or equal to the charset e.g -22 it will add 26 to get the correct letter positioning/value
pos=pos+26
else:
new=charset[pos]
plaintext=plaintext+new
print '[*] plaintext: ' + plaintext
if i <= 27:
newkey=newkey+1
i=i+1
return plaintext
def main():
# test cases
newkey=0
i=0
crackme = 'PBATENGHYNGVBAFLBHUNIRPENPXRQGURPBQRNAQGURFUVSGJNFGUVEGRRA'
# call functions with text cases
caesar_crack(crackme,i,newkey)
# boilerplate
if __name__ == '__main__':
cli()
main() |
#!/usr/bin/env python
# encoding: utf-8
"""
euler_10.py
"""
def primes_lt(n):
primes = [2]
numbers = range(n+2)
next_prime = 2
while True:
print next_prime
counter = next_prime + next_prime
while counter <= n:
numbers[counter] = -1
counter += next_prime
num = next_prime + 1
while numbers[num] == -1 and num < n:
num += 1
if num < n:
next_prime = num
primes.append(next_prime)
else:
print 'DONE', sum(primes)
return
primes_lt(2000000)
|
"""
Section class is an abstract class.
Local axis of the section is as follows:
x-axis is the longitudinal axis that is directed from the start node to the end node of the element
y-axis is directed upward the section
z-axis is directed to the left
Properties(abstract methods):
properties are overridden by the inheriting section classes.
area = area of the section
inertia_y = second moment of area about the y-axis
inertia_z = second moment of area about the z-axis
polar_inertia = polar moment of inertia about the x-axis (J)
warping_rigidity = warping rigidity that applies to non-circular sections
Derived classes:
Circle
Square
ArbitrarySection: section with user-defined properties
"""
from math import pi
from abc import ABC, abstractmethod
class Section(ABC):
def __init__(self):
self.__area = None
self.__inertia_y = None
self.__inertia_z = None
self.__polar_inertia = None
self.__warping_rigidity = None
@property
@abstractmethod
def area(self):
return self.__area
@property
@abstractmethod
def inertia_y(self):
return self.__inertia_y
@property
@abstractmethod
def inertia_z(self):
return self.__inertia_z
@property
@abstractmethod
def polar_inertia(self):
return self.__polar_inertia
@property
@abstractmethod
def warping_rigidity(self):
return self.__warping_rigidity
class Circle(Section):
def __init__(self, radius):
super().__init__()
self.radius = radius
@property
def area(self):
return pi*self.radius**2
@property
def inertia_y(self):
return pi*self.radius**4/2
@property
def inertia_z(self):
return pi*self.radius**4/2
@property
def polar_inertia(self):
return self.inertia_y + self.inertia_z
@property
def warping_rigidity(self):
return None
class Rectangle(Section):
def __init__(self, breadth, depth):
super().__init__()
self.breadth = breadth
self.depth = depth
@property
def area(self):
return self.breadth * self.depth
@property
def inertia_y(self):
return self.depth * self.breadth**3 / 12
@property
def inertia_z(self):
return self.breadth * self.depth**3 / 12
@property
def polar_inertia(self):
return self.inertia_y + self.inertia_z
@property
def warping_rigidity(self):
return None
class ArbitrarySection(Section):
def __init__(self, area, inertia_y, inertia_z, polar_inertia, warping_rigidity):
super().__init__()
self.__area = area
self.__inertia_y = inertia_y
self.__inertia_z = inertia_z
self.__polar_inertia = polar_inertia
self.__warping_rigidity = warping_rigidity
@property
def area(self):
return self.__area
@property
def inertia_y(self):
return self.__inertia_y
@property
def inertia_z(self):
return self.__inertia_z
@property
def polar_inertia(self):
return self.__polar_inertia
@property
def warping_rigidity(self):
return self.__warping_rigidity
|
def inInside(matrix, i, j):
if(i<0 or j<0 or i>len(matrix)-1 or j>len(matrix[0])-1):
return False
return True
def getsum(matrix, i, j):
sum = 0
for x in range(-1,2):
for y in range(-1, 2):
if(x!=y or x!=0 or y!=0):
if(inInside(matrix, i+x, j+y) and matrix[i+x][j+y]):
sum+=1
return sum
def minesweeper(matrix):
b = []
l = []
for i in range(len(matrix)):
l=[]
for j in range(len(matrix[0])):
l.append(getsum(matrix, i, j))
print l
b.append(l)
return b
"""did a collaboration work on this also some code from other sources...not very proud of it but hey..i need to finish this task."
|
def alternatingSums(a):
b = [0,0]
for x in range(len(a)):
if ((x+1)%2 == 1):
b[0] += a[x]
else:
b[1] += a[x]
return b
|
def select_a_friend():
item_number=0
for friend in friends:
print '%d. %s aged %d with rating %.2f is online' % (item_number + 1, friend['name'], friend['age'],friend['rating'])
item_number = item_number+1
friend_choice = raw_input("Choose from your friends")
friend_choice_position = int(friend_choice-1)
return friend_choice_position |
from math import *
def f(x):
return x * sin(x)
def integral(f, a, b):
n = 10000
dx = (b-a) / n
y = 0
for k in range(1, n):
y = y + f(a + k * dx)
y = y + (f(a) + f(b)) / 2
return dx * y
a = 0
b = 2 * 3.14
print(integral(f, a, b))
# def f2(x):
# return x * x - 2
#
# def derivative(f, x):
# d = 1e - 10
# return (f(x+d) - f(x)) / d
#
# def newton(f, x):
# epsilon = 1e - 10 |
#!/usr/bin/env python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
if N >= 2 and N <=5 and N % 2 == 0:
print('Not Weird')
elif N % 2 != 0:
print('Weird')
elif N >= 6 and N <= 20 and N % 2 == 0:
print('Weird')
elif N % 2 != 0:
print('Not Weird')
elif N > 20 and N % 2 == 0:
print('Not Weird')
elif N % 2 != 0:
print('Weird')
|
__author__ = 'achandelkar'
def NeutralizeList(L1):
i = 0
L2 = []
while (i < len(L1)):
if type(L1[i]) != list:
L2.append(L1[i])
else:
ExtendList(L2,L1[i])
i+=1
return L2
def ExtendList(L2,L3):
j = 0
while (j < len(L3)):
if type(L3[j]) != list:
L2.append(L3[j])
else:
ExtendList(L2,L3[j])
j+=1
if __name__ == '__main__':
L1 = eval(input("Enter the List to neutralize::"))
res = (NeutralizeList(L1))
print("The Neutralized List is :: {0}".format(res))
|
__author__ = 'achandelkar'
'''
def ReplaceFirstCharOccurences(S1,ReplaceBy):
return S1[0] + S1[1:].replace(S1[0],ReplaceBy)
'''
def ReplaceFirstCharOccurences(S1,ReplaceBy):
S2 = S1[0]
ch = S1[0]
i = 1
while i < len(S1):
if S1[i] == ch:
S2+=ReplaceBy
else:
S2+=S1[i]
i+=1
return S2
if __name__ == '__main__':
S1 = eval(input("Enter a string::"))
ReplaceBy = eval(input("Enter the char to be replaced by::"))
res = ReplaceFirstCharOccurences(S1,ReplaceBy)
print("The new string is :: {0}".format(res)) |
__author__ = 'achandelkar'
#!C:\Python34\python.exe
print("Its fun", __name__)
def SumOfEvenOdd(lb , ub):
sum_even = 0
sum_odd = 0
while lb <= ub:
if lb % 2 == 0:
sum_even += lb
else:
sum_odd += lb
lb +=1
return sum_even,sum_odd
if __name__ == '__main__':
lb,ub = input("Enter lower and upper bound numbers:")
r1,r2 = SumOfEvenOdd(lb,ub)
#print("The sum of even numbers is:%d"%r1)
#print("the sum of odd numbers is :%d"%r2)
print(r1,r2) |
import os
def humanize_filename(filename):
filename = os.path.splitext(filename)[0]
replace_map = {
'-': ' ',
'_': ' ',
'.': ' '
}
for search, replace in replace_map.iteritems():
filename = filename.replace(search, replace)
return filename |
"""
Simple Game Lab
We will be writing our first simple game in this lab!
We will write a simple game where the objective of the player is to evade the boss.
Do the following:
1) Create a player and boss Sprite using "tank.png" and "boss.png". Initialize player on the left
side of the screen and boss on the right side of the screen. If you are using Processing, use
set_left(new_left) or set_right(new_right) methods.
If you're using the original Arcade library, you can use
self.player.left = new_left or self.player.right = new_right.
2) Move the player with arrow keys and move the boss with the mouse.
3) If boss catch the player, player resets to the left side of the screen.
If you are using Processing, use set_left(new_left) method.
If you're using the original Arcade library, you can use self.player.lives = new_left.
Use arcade.check_for_collision function which returns whether two sprites are colliding.
4) Add a lives variable that keep track of the number of lives of the player, initialize it to 3.
5) Each time the player gets caught, decrease his lives by 1.
6) If the player's lives is 0, display "Game Over" and "Press r to restart" screen. At this point
the player and boss should still be drawn but they are frozen.
7) If user presses "r", call setup() to restart the game.
8) (Optional) Add a respawning feature. If the player is reset, gives him 4-5 seconds where the boss
can't get him. (Hint: use transparency(alpha attribute), 0-255, 255 is opaque, 0 is invisible))
"""
from __future__ import division, print_function
import arcade
from constants import *
class Window:
def __init__(self):
""" Declare the variables, set them to None. """
def setup(self):
""" Set up the game and initialize the variables. """
def on_draw(self):
""" Called automatically 60 times a second to draw objects."""
def on_update(self):
""" Called to update our objects. Happens approximately 60 times per second."""
pass
def on_mouse_motion(self, x, y, dx, dy):
""" Called whenever the mouse moves. """
pass
def on_mouse_press(self, x, y, button):
""" Called whenever the mouse is pressed. """
pass
def on_mouse_release(self, x, y, button):
""" Called whenever the mouse is released. """
pass
def on_key_press(self, key):
""" Called automatically whenever a key is pressed. """
if key == LEFT:
self.player.change_x = -5
def on_key_release(self, key):
""" Called automatically whenever a key is released. """
if key == LEFT:
self.player.change_x = 0
|
"""
Pick Up Coins Lab
Do the following:
1) The player Sprite along with some other variables have already been created for you.
2) In setup(), inititalize a SpriteList. Use a for loop to initialize coins at random positions
on the screen. Use the imported random module and random.randrange(n) generates a random integer
from 0 to n - 1 (similar to range()) to initialize the positions of the coins. Add to the SpriteList.
3) Use arcade.check_for_collision_with_list to get a list of Sprites collided with player.
4) For each one in the list, update the number of coins collected and remove from SpriteList.
5) If all coins have been removed, display "You win! Press r to restart!". If the user presses "r",
reset the game.
"""
from __future__ import division, print_function
import arcade
from constants import *
import random
WIDTH = 800
HEIGHT = 600
BACKGROUND_COLOR = color(255) # or RGB: color(255, 0, 255)
PLAYER_SCALE = 0.5
TANK_SCALE = 0.5
PLAYER_SPEED = 5
class Window:
def __init__(self):
""" Declare the variables, set them to None. """
self.setup()
def setup(self):
""" Set up the game and initialize the variables. """
self.player = arcade.Sprite("tank.png", 0.5)
self.num_coins = 0
self.total_coins = 5
self.game_over = False
self.coin_list = arcade.SpriteList()
for i in range(self.total_coins):
coin = arcade.Sprite("coin.png", 0.5)
coin.center_x = random.randrange(WIDTH)
coin.center_y = random.randrange(HEIGHT)
self.coin_list.append(coin)
def on_draw(self):
""" Called automatically 60 times a second to draw objects."""
self.player.draw()
self.coin_list.draw()
arcade.draw_text("Coins: " + str(self.num_coins), 50, HEIGHT - 50)
if self.game_over:
arcade.draw_text("You win! Press r to restart!", WIDTH/2 - 200, HEIGHT/2)
def on_update(self):
""" Called to update our objects. Happens approximately 60 times per second."""
if not self.game_over:
self.player.update()
self.check_coin_collision()
self.check_game_over()
def check_coin_collision(self):
collision_list = arcade.check_for_collision_with_list(self.player, self.coin_list)
if len(collision_list) > 0:
for coin in collision_list:
self.num_coins += 1
self.coin_list.remove(coin)
def check_game_over(self):
if self.num_coins == self.total_coins:
self.game_over = True
def on_mouse_motion(self, x, y, dx, dy):
""" Called whenever the mouse moves. """
# if x is within width of rectangle and y within height of rectangle
# return True otherwise return False.
pass
def on_mouse_press(self, x, y, button):
""" Called whenever the mouse is pressed. """
pass
def on_mouse_release(self, x, y, button):
""" Called whenever the mouse is released. """
pass
def on_key_press(self, key):
""" Called automatically whenever a key is pressed. """
if key == LEFT:
self.player.change_x = -5
elif key == RIGHT:
self.player.change_x = 5
elif key == UP:
self.player.change_y = -5
elif key == DOWN:
self.player.change_y = 5
elif key == 'r' and self.game_over:
self.setup()
def on_key_release(self, key):
""" Called automatically whenever a key is released. """
if key == LEFT:
self.player.change_x = 0
elif key == RIGHT:
self.player.change_x = 0
elif key == UP:
self.player.change_y = 0
elif key == DOWN:
self.player.change_y = 0
|
guess = input("Guess number: ")
secret = input("Secret number: ")
# Makes each digit into a string; puts them in a list
secret_digit_list = list(str(secret))
guess_digit_list = list(str(guess))
# Compares the digits of `secret` and `guess !!! NOT WORKING !!!
for n,(a,b) in enumerate(zip(guess_digit_list,secret_digit_list)):
if a!=b:
print('numbers on index {} are different'.format(n))
else:
print('numbers on index {} are same'.format(n))
# if int(secret_digit_list[1]) == int(guess_digit_list[1]):
# print("The second digits are the same.")
#
# else:
# print("The second digits are different.") |
#input the total number of inputs
n = int(input("Number of inputs: "))
#a: total number of positive even numbers
a=0
while not n<=0:
x = int(input("Enter Number: "))
if x%2 == 0 :
a = a+1
n=n-1
print("Positive even numbers:",a) |
for i in range(0,4):
print(i)
for move in range(0,4):
print(move)
for i in range(1,5):
print(i)
for kitty in range(0,1+2):
print(kitty)
for Supercalifragilisticexpialidocious in range(0,1):
print(Supercalifragilisticexpialidocious)
for i in range(11,0,-2):
print(" "*int((12-i)/2) + "*"*i, end="")
print()
sum = 0
for i in range(11):
sqr = i**2
sum += sqr
print(sum)
donor = [10, 12, .75, 5.23, 25.35, 14.53, 15.99, 8.00, 8.01, .25]
dontotal = 0
if donor == []:
print("no donations")
else:
for i in donor:
dontotal += i
if dontotal > 100:
print("The total is over $100! The professor will double it!")
|
code = {"A":"=.===",
"B":"===.=.=.=",
"C":"===.=.===.=",
"D":"===.=.=",
"E":"=",
"F":"=.=.===.=",
"G":"===.===.=",
"H":"=.=.=.=",
"I":"=.=",
"J":"=.===.===.===",
"K":"===.=.===",
"L":"=.===.=.=",
"M":"===.===",
"N":"===.=",
"O":"===.===.===",
"P":"=.===.===.=",
"Q":"===.===.=.===",
"R":"=.===.=",
"S":"=.=.=",
"T":"===",
"U":"=.=.===",
"V":"=.=.=.===",
"W":"=.===.===",
"X":"===.=.=.===",
"Y":"===.=.===.===",
"Z":"===.===.=.="}
d = {}
for k,v in code.items():
d[v] = k
def letter_to_code(letter):
return code[letter]
space_between_letters= "..."
space_between_words= "......."
def word_to_code(word):
word = word.upper()
codeofword=""
for i in range(len(word)):
if i == (len(word)-1):
x = letter_to_code(word[i])
codeofword += x
return codeofword
else:
x = letter_to_code(word[i]) + space_between_letters
codeofword += x
def sentence_to_code(s):
wordsins = s.split()
translation = ""
for i in range(len(wordsins)):
if i == (len(wordsins)-1):
x = word_to_code(wordsins[i])
translation += x
return translation
else:
x = word_to_code(wordsins[i]) + space_between_words
translation += x
def code_to_letters(s):
return d[s]
def code_to_word(s):
lstfolttrs =s.split(space_between_letters)
word = ""
for i in lstfolttrs:
x = code_to_letters(i)
word += x
return word
def code_to_sentence(s):
lstowrds = s.split(space_between_words)
sentence = ""
for i in range(len(lstowrds)):
if i == (len(lstowrds)-1):
x = code_to_word(lstowrds[i])
sentence += x
return sentence
else:
x = code_to_word(lstowrds[i]) + " "
sentence += x
def testing(s,c):
if sentence_to_code(s) == c:
print("S->C for {0} passed.".format(s))
else:
print("S->c for {0} failed.".format(s))
if code_to_sentence(c) == s:
print("C->S for {0} passed.".format(s))
else:
print("C->S for {0} failed.".format(s))
test_strings = ["MORSE CODE", "I NEED MONEY", "ORDER PIZZA"]
test_code = ["===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=",
"=.=.......===.=...=...=...===.=.=.......===.===...===.===.===...===.=...=...===.=.===.===",
"===.===.===...=.===.=...===.=.=...=...=.===.=.......=.===.===.=...=.=...===.===.=.=...===.===.=.=...=.==="]
#for s,c in zip(test_strings, test_code):
# testing(s,c)
#with open("c.txt") as c:
# Mcode = c.read().splitlines()
#for line in Mcode:
# print(code_to_sentence(line))
print(sentence_to_code("I dont know"))
|
def passThroughDoor(string):
for i in range(0,len(string)):
if i == (len(string)-1):
return False
if string[i] == string[(i+1)]:
return True
print(passThroughDoor("ballon"))
print(passThroughDoor("color"))
print(passThroughDoor("wendall"))
print(passThroughDoor("gary baker"))
print(passThroughDoor("Peanut butter")) |
def sumListWhile(aList):
counter = 0
result = 0
while counter < len(aList):
result = result + aList[counter]
counter = counter + 1
return result
def multiplyListFor(aList):
result = 1
for i in aList:
result = result * i
return result
def factorialWhileLoop(n):
if n == 0:
return 1
counter = 1
result = 1
while counter <= (n):
result = result * counter
counter = counter + 1
return result
def multiplywhile(x,y):
counter = 0
result = 0
while counter < y:
result = result + x
counter = counter + 1
return result
a = [1,2,3]
print(sumListWhile(a))
print(multiplyListFor(a))
print(factorialWhileLoop(3))
print(multiplywhile(2,3)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 10 19:10:00 2017
@author: Dustin
"""
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def calcMMP (mr, b):
return mr*b
def calcUB (b, mmp):
return b - mmp
def updateB(r, ub):
return ub + (r * ub)
for x in range(12):
min = calcMMP(monthlyPaymentRate, balance)
balance = round(updateB(annualInterestRate/12, calcUB(balance, min)), 2)
print("Remaining balance: " + str(balance)) |
class InstansiKesehatan:
def __init__(self, id, nama, alamat, kontak):
self._id = id
self._nama = nama
self._alamat = alamat
self._kontak = kontak
def setNamaInstansi(self, x):
self._nama = x
def setAlamatInstansi(self, x):
self._alamat = x
def setKontakInstansi(self, x):
self._kontak = x
def getNamaInstansi(self):
return self._nama
def getAlamatInstansi(self):
return self._alamat
def getKontakInstansi(self):
return self._kontak
class Masyarakat:
def __init__(self, id, nama, kontak):
self._id = id
self._nama = nama
self._kontak = kontak
def setNamaMasyarakat(self, x):
self._nama = x
def setKontakMasyarakat(self, x):
self._kontak = x
def getNamaMasyarakat(self):
return self._nama
def getKontakMasyarakat(self):
return self._kontak
class APD:
def __init__(self, nama, jumlah):
self._nama = nama
self._jumlah = jumlah
def setNamaAPD(self, x):
self._nama = x
def setJumlahAPD(self, x):
self._jumlah = x
def getNamaAPD(self):
return self._nama
def getJumlahAPD(self):
return self._jumlah
print('Masukan data')
end = False
while(end == False):
print('1. Instansi Kesehatan: ')
print('2. Masyarakat: ')
print('3. APD: ')
print('4. Selesai')
choice = int(input('Masukan pilihan: '))
if (choice == 1):
id = input('id: ')
nama = input('Nama instansi: ')
alamat = input('Alamat Instansi: ')
kontak = input('Kontak instansi: ')
nama = InstansiKesehatan(id, nama, alamat, kontak)
print('Nama: ', nama.getNamaInstansi())
print('Alamat: ', nama.getAlamatInstansi())
print('Kontak: ', nama.getKontakInstansi())
print()
elif (choice == 2):
id = input('id: ')
nama = input('Nama Masyarakat: ')
kontak = input('Kontak Masyarakat: ')
nama = Masyarakat(id, nama, kontak)
print('Nama: ', nama.getNamaMasyarakat())
print('Kontak: ', nama.getKontakMasyarakat())
print()
elif (choice == 3):
id = input('id: ')
nama = input('Nama APD: ')
jumlah = input('Jumlah APD: ')
nama = APD(nama, jumlah)
print('Nama: ', nama.getNamaAPD())
print('Jumlah: ', nama.getJumlahAPD())
print()
elif (choice == 4):
end = True
else:
print('Input salah')
|
# List to Dictionary Exercise
# Given a person variable:
# person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# Create a dictionary called `answer`, that makes each first item
# in each list a key and the second item a corresponding value.
# Output should look like this:
# {'name': 'Jared', 'job': 'Musician', 'city': 'Bern'}
person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# my solution
answer = {person[i][0]: person[i][1] for i in range(0, len(person))}
print(answer)
# alternate solution
answer = {p[0]: p[1] for p in person}
print(answer)
# alternate solution
answer = {k: v for k, v in person}
print(answer)
# if you have a list of pairs, it can be turned into a dictionary
# using dict()
answer = dict(person)
print(answer)
|
# Given the string 'amazing', create a variable called answer,
# which is a list containing all the letters from 'amazing'
# but not the vowels (a, e, i, o, and u)
answer = [letter for letter in 'amazing' if letter not in [
'a', 'e', 'i', 'o', 'u']]
print(answer)
# Alternate solution
answer2 = [letter for letter in 'amazing' if letter not in 'aeiou']
print(answer2)
|
# State Abbreviations
# Given two lists `['CA', 'NJ', 'RI']` and
# `['California', 'New Jersey', 'Rhode Island']` create a
# dictionary that looks liek this:
# {'CA': 'California', 'NJ': 'New Jersey', 'RI': 'Rhode Island'}
# and save it to a variable called *answer*
list1 = ['CA', 'NJ', 'RI']
list2 = ['California', 'New Jersey', 'Rhode Island']
answer = {list1[i]: list2[i] for i in range(0, len(list1))}
print(answer)
|
#####################################################################################
# It is compulsory that for usage of '+' operator -> both parameter should be str
# For usage of '*' operator , one parameter should be int and other should be str
#####################################################################################
a='Vikas' * 10
print(a)
# Output : VikasVikasVikasVikasVikasVikasVikasVikasVikasVikas
a=5 * 'vikas'
print(a)
# Output : vikasvikasvikasvikasvikas
# a='vikas' + 10
# print(a)
# Output : TypeError: can only concatenate str (not "int") to str
# a=10 + 'vikas'
# print(a)
# Output : TypeError: unsupported operand type(s) for +: 'int' and 'str'
a=10 * '#'
b='Vikas'
c=10 * '#'
print(a) , print(b) , print(c)
# Output :
# ##########
# Vikas
# ##########
a=10 * '#'
b='Vikas'
c=10 * '#'
print(a)
print(b)
print(c)
# Output :
# ##########
# Vikas
# ##########
#####################################################################################
|
# Mutable : Changes can be made
# Immutable : Non changeable behaviour
# Once we create an Object , we cannot perform any changes in that Object.
# If we are trying to perform any changes with those changes , a new Object will be created
# Example : Immutable
# Case 1 :
x=10
y=10
print(x)
print(y)
print("Address of X : ",id(x)," | " , "Address of Y : ",id(y))
# Output : Address of X : 2354605288016 | Address of Y : 2354605288016
# If i do below changes to value of x
x=x+1
print(x)
print("Address of X : ",id(x))
# Output : Address of X : 2195332688496 (Note : New Object is created for x)
# Previously defined Object for x is not have any reference ,
# it is garbage collected by python
# Case 2 :
x=15
y=x
print(x)
print(y)
print("Address of X : ",id(x)," | " , "Address of Y : ",id(y))
# Output : Address of X : 2748700584688 | Address of Y : 2748700584688
# Now if i add below changes to value of y
y=y+1
print(y)
print("Address of X : ",id(x)," | " , "Address of Y : ",id(y))
# Output : Address of X : 2748700584688 | Address of Y : 2748700584720
# In this case both values x and y are having reference ,
# nothing will be garbage collected.But immutable behaviour can be seen
###############################################################################################
# Example : Mutable
# Case 1 :
a=[10,20,40]
print("List of A : ",a)
print("Address of A : ",id(a))
# Output :
# List of A : [10, 20, 40]
# Address of A : 1914046399040
# if i make changes to one value of list a
a[0]=54
print("List of A : ",a)
print("Address of A : ",id(a))
# Output :
# List of A : [54, 20, 40]
# Address of A : 1914046399040
# If you observe carefully you can see the Address remain same for both of them , But the
# changes are refelected in list this kind of behaviour is called mutable
# Case 2 :
b1=[20,40,50]
b2=b1
print("List of B1 : ",b1)
print("Address of B1 : ",id(b1))
print("List of B2 : ",b2)
print("Address of B2 : ",id(b2))
# Output :
# List of B1 : [20, 40, 50]
# Address of B1 : 2197982806912
# List of B2 : [20, 40, 50]
# Address of B2 : 2197982806912
# Now if i make changes to value of list b1
b1[0]=19
print("List of B1 : ",b1)
print("Address of B1 : ",id(b1))
print("List of B2 : ",b2)
print("Address of B2 : ",id(b2))
# Output :
# List of B1 : [19, 40, 50]
# Address of B1 : 2197982806912
# List of B2 : [19, 40, 50]
# Address of B2 : 2197982806912
# if you see the newly added value is reflected in both the list b1 and b2
# as they were pointing to the same Object , this is another example of mutable behaviour
###############################################################################################
# All fundamental data types have Object reusability concept
# except for complex data type a new object is created
# why their is a need for immutable
# 1.
# if the 2 variables as the same value , before the new object is created the PVM searches for
# values if not found then new object is created , otherwise the reusable of object happen
# if value is found
# 2.
# performance is also improved , as creation of Object is very costly
###############################################################################################
|
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import h5py
def load_dataset():
"""
The dataset is taken from Coursera
The dataset contains: train_catvnoncat.h5 and test_catvnoncat.h5
-> a training set of m_train images labeled as cat (y=1) or non-cat (y=0)
-> a test set of m_test images labeled as cat or non-cat
-> each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB).
"""
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
def preprocessing():
"""
Common steps for pre-processing a new dataset are:
-> Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, …)
-> Reshape the datasets such that each example is now a vector of size (num_px * num_px * 3, 1)
-> “Standardise” the data
Many software bugs in deep learning come from having matrix/vector dimensions that don’t fit.
If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating
many bugs.
"""
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_set_x = train_set_x_flatten / 255
test_set_x = test_set_x_flatten / 255
return train_set_x, train_set_y, test_set_x, test_set_y
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -> size of the w vector we want (or number of parameters in this case)
Returns:
w -> initialized vector of shape (dim, 1)
b -> initialized scalar (corresponds to the bias)
"""
w = np.zeros((dim, 1))
b = 0
assert (w.shape == (dim, 1))
assert (isinstance(b, float) or isinstance(b, int))
return w, b
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -> A scalar or numpy array of any size.
Return:
s -> sigmoid(z)
"""
s = 1 / (1 + np.exp(-z))
return s
def propagate(w, b, X, Y):
"""
Implement the cost function and its gradient for the propagation explained above
Arguments:
w -> weights, a numpy array of size (num_px * num_px * 3, 1)
b -> bias, a scalar
X -> data of size (num_px * num_px * 3, number of examples)
Y -> true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
Return:
cost -> negative log-likelihood cost for logistic regression
dw -> gradient of the loss with respect to w, thus same shape as w
db -> gradient of the loss with respect to b, thus same shape as b
"""
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = -1 / m * (np.sum((np.multiply(Y, np.log(A)) + (np.multiply((1 - Y), np.log(1 - A)))))) # compute cost
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = (1 / m) * np.dot(X, (A - Y).T)
db = (1 / m) * np.sum(A - Y)
assert (dw.shape == w.shape)
assert (db.dtype == float)
cost = np.squeeze(cost)
assert (cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
"""
This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -> weights, a numpy array of size (num_px * num_px * 3, 1)
b -> bias, a scalar
X -> data of shape (num_px * num_px * 3, number of examples)
Y -> true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
num_iterations -> number of iterations of the optimization loop
learning_rate -> learning rate of the gradient descent update rule
print_cost -> True to print the loss every 100 steps
Returns:
params -> dictionary containing the weights w and bias b
grads -> dictionary containing the gradients of the weights and bias with respect to the cost function
costs -> list of all the costs computed during the optimization, this will be used to plot the learning curve.
"""
costs = [] # keep track of cost
iterations = [] # keep track of iterations
for i in range(num_iterations):
# Cost and gradient calculation
grads, cost = propagate(w, b, X, Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w - learning_rate * dw
b = b - learning_rate * db
# Record the costs
if i % 100 == 0:
costs.append(cost)
iterations.append(i)
# Print the cost every 100 training iterations
if print_cost and i % 100 == 0:
print("Cost after iteration %i: %f" % (i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs, iterations
def predict(w, b, X):
"""
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -> weights, a numpy array of size (num_px * num_px * 3, 1)
b -> bias, a scalar
X -> data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -> a numpy array (vector) containing all predictions (0/1) for the examples in X
"""
m = X.shape[1] # Gives the number of training example
Y_prediction = np.zeros((1, m)) # The number of predication for m training example
w = w.reshape(X.shape[0], 1)
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = sigmoid(np.dot(w.T, X) + b)
for i in range(A.shape[1]): # A.shape[1] is the number of training example
# Convert probabilities A[0,i] to actual predictions p[0,i]
if A[0, i] > 0.5:
Y_prediction[0, i] = 1
else:
Y_prediction[0, i] = 0
assert (Y_prediction.shape == (1, m))
return Y_prediction
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -> training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -> training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -> test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -> test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -> hyperparameter representing the number of iterations to optimize the parameters
learning_rate -> hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -> Set to true to print the cost every 100 iterations
Returns:
d -> dictionary containing information about the model.
"""
# initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
# Predict test/train set examples
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
# Print train/test Errors
print("\nTrain accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("Test accuracy: {} %\n".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train": Y_prediction_train,
"w": w,
"b": b,
"learning_rate": learning_rate,
"num_iterations": num_iterations
}
"""
Simple Graph to see the cost after every 100 iterations
"""
# plot the cost
plt.plot(iterations, costs)
plt.ylabel('Cost')
plt.xlabel('Iterations (per hundreds)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
"""
You can test this algorithm, simply giving your path name of your image
"""
# Change this to the name of your image file
my_image = "Dinosaurs.jpeg"
# Preprocess the image to fit into the algorithm.
fname = "Images/" + my_image
image = np.array(Image.open(fname).resize((64, 64)))
image = image / 255
final_image = image.reshape(1, 64 * 64 * 3).T
my_predicted_image = predict(d["w"], d["b"], final_image)
plt.imshow(image)
plt.show()
if my_predicted_image[0][0] == 1:
print('Your algorithm predicts a "Cat" picture.')
else:
print('Your algorithm predicts a "Non-Cat" picture.')
return d
# Calling preprocessing function to preprocess the data
train_set_x, train_set_y, test_set_x, test_set_y = preprocessing()
# Training the model by calling the model function
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=2000, learning_rate=0.01, print_cost=True)
|
# short lecture on backpropagation by Geoffrey Hinton:
# https://www.youtube.com/watch?v=H47Y7pAssTI
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.insert(0, "../..")
sys.path.insert(0, "..")
import PyRat as pr
def run():
#generate n samples of random 2d data from each class
#such that classes are not linearly separable
n = 400
m_pos1 = np.array([-0.5, -0.5]).reshape(2, -1)
x_pos1 = np.random.randn(2, n/2)/4 + m_pos1
m_pos2 = np.array([0.5, 0.5]).reshape(2, -1)
x_pos2 = np.random.randn(2, n/2)/4 + m_pos2
x_pos = np.concatenate((x_pos1, x_pos2), axis=1)
y_pos = np.ones(n)
m_neg1 = np.array([-0.5, 0.5]).reshape(2, -1)
x_neg1 = np.random.randn(2, n/2)/4 + m_neg1
m_neg2 = np.array([0.5, -0.5]).reshape(2, -1)
x_neg2 = np.random.randn(2, n/2)/4 + m_neg2
x_neg = np.concatenate((x_neg1, x_neg2), axis=1)
y_neg = np.zeros(n)
#concatenate positive and negative examples
x = np.concatenate((x_pos, x_neg), axis=1)
y = np.concatenate((y_pos, y_neg))
#set y as 't'arget
t = y.reshape(1, -1)
#initialize hidden layer with 2 logistic units
n_dims = len(x)
n0 = 4
h0 = pr.logistic(n0, n_dims)
#initialize output layer with 1 logistic unit
h1 = pr.logistic(1, h0.n_outputs)
#define number of training epochs (decreasing learning rate)
n_epochs = 4
#number of iterations in each epoch
n_iter = 1000
#learning rate
learning_rate = 10.0
rmse = np.zeros(n_epochs*n_iter)
#train network
for e in range(n_epochs):
for i in range(n_iter):
y0 = h0.forward(x)
y1 = h1.forward(y0)
rmse[e*n_iter + i], dEdy = pr.squared_error(t, y1)
dEdx1 = h1.backprop(dEdy, learning_rate)
h0.backprop(dEdx1, learning_rate)
#print error and weights at end of each iteration
if(i % 1000 == 0):
print "RMSE:" + str(rmse[e * n_iter + i]) + " w: " + str(h0.w)
learning_rate *= 0.1
#plot data
plt.figure(figsize=(20, 9))
plt.subplot(121)
plt.title('Separation in feature space')
plt.scatter(x_pos[0,:], x_pos[1,:], color='blue', marker='+')
plt.scatter(x_neg[0,:], x_neg[1,:], color='red', marker='o')
#separation line at p=0.5 is defined as x2 = -w1/w2 * x1 - w0/w2
w = h0.w
l_x = np.linspace(-1, 1, 2)
for i in range(n0):
l_y = -w[0,i]/w[1,i] * l_x -w[n_dims,i]/w[1,i]
plt.plot(l_x, l_y, color='black')
#plot mean error over iterations
e_x = np.linspace(1, n_epochs*n_iter, n_epochs*n_iter)
plt.subplot(122)
plt.title('Root mean squared error')
plt.plot(e_x, rmse)
plt.show()
|
import numpy as np
class logistic:
#constructor
def __init__(self, n_units, n_inputs):
print 'Initializing logistic layer with ' + str(n_units) + ' units and ' + str(n_inputs) + ' inputs per unit '
self.n_outputs = n_units
self.n_inputs = n_inputs
self.w = (np.random.rand(self.n_inputs+1, self.n_outputs)- 0.5)/n_inputs
#take data from previous layer as input
def forward(self, x):
#store x for back-propagation
self.x = np.vstack([x, np.ones(len(x[0]))])
#estimate logit
z = np.dot(self.w.T, self.x)
#estimate activation and store for back-propagation
self.y = 1/(1 + np.exp(-z))
return self.y
#take error-derivative with respect to output as parameter
def backprop(self, dEdy, learning_rate):
self.dEdy = dEdy
#estimate dE/dz = dE/dy * dy/dz, where
#dy/dz = y(1-y)
dydz = self.y*(1-self.y)
dEdz = self.dEdy*dydz
#estimate dE/dw = dE/dy * dy/dz * dz/dw, where
# - dz/dw = x and
# and sum over all training samples
n_samples = dEdz.shape[1]
dEdw = np.dot(self.x, dEdz.T)/n_samples
#dE/dx for each training sample
dEdx = np.dot(self.w[0:self.n_inputs,:], dEdz)
#update weights
self.w += learning_rate * dEdw
return dEdx
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Esta script prepara las mustras leidas del csv, para su posterior tratamiento.
'''
import csv
def load_regions(path):
'''Load regions of csv.'''
with open(path, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
next(csv_reader)
locations = {}
for row in csv_reader:
locations[row['Geo_Location'].split(':')[0]] = {}
return locations
def load_samples_of_csv(path):
'''Load samples of regions.'''
with open(path, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
next(csv_reader)
samples = load_regions(path)
for row in csv_reader:
length = {'Length':int(row['Length'])}
samples[row['Geo_Location'].split(':')[0]][row['Accession']] = length
return samples
def quick_sort(list_to_sort):
'''Sorting algorithm'''
less = []
pivotlist = []
more = []
if len(list_to_sort) <= 1:
return list_to_sort
pivot_pos = len(list_to_sort) // 2
pivot = list_to_sort[pivot_pos]
for i in list_to_sort:
if i[1] < pivot[1]:
less.append(i)
elif i[1] > pivot[1]:
more.append(i)
else:
pivotlist.append(i)
less = quick_sort(less)
more = quick_sort(more)
return less + pivotlist + more
def median(samples):
'''This function calculates the median length sample from a list.'''
lengths = [(sample, samples[sample]['Length']) for sample in samples.keys()]
return calculate_median(lengths) #get id of sample
def calculate_median(lengths):
'''Calculate the median with quick_sort'''
sorted_lengths = quick_sort(lengths)
return sorted_lengths[len(sorted_lengths) // 2]
def get_median_samples_of_csv(path):
'''This function obtains the median sample of each country'''
samples = load_samples_of_csv(path)
median_samples = []
for country in list(samples.keys()):
median_sample = median(samples[country])[0]
median_samples.append({'country':country, 'sample':median_sample})
return median_samples
|
from termcolor import colored
#colored(string, color)
class Game():
def __init__(self):
self.board = [[], [], [], [], [], [], [], [], [], [colored('+', 'red')]]
self.main()
def main(self):
self.placePieces()
self.display()
def placePieces(self):
uniDict = {'WHITE' : {'Pawn' : "♙", 'Rook' : "♖", 'Knight' : "♘", 'Bishop' : "♗", 'King' : "♔", 'Queen' : "♕" }, 'BLACK' : {'Pawn' : "♟", 'Rook' : "♜", 'Knight' : "♞", 'Bishop' : "♝", 'King' : "♚", 'Queen' : "♛" }}
pieces = ['Rook', 'Knight', 'Bishop', 'King', 'Queen', 'Bishop', 'Knight', 'Rook']
for i in range(8):
self.board[i+1].insert(0, colored(8 - i, 'red'))
self.board[1].append(uniDict['WHITE'][pieces[i]])
self.board[2].append(uniDict['WHITE']['Pawn'])
self.board[3].append(colored('·', 'blue'))
self.board[4].append(colored('·', 'blue'))
self.board[5].append(colored('·', 'blue'))
self.board[6].append(colored('·', 'blue'))
self.board[7].append(uniDict['BLACK']['Pawn'])
self.board[8].append(uniDict['BLACK'][pieces[i]])
self.board[9].append(colored(chr(ord('`')+(i+1)), 'red'))
self.board[0] = self.board[9]
for i in range(9):
self.board[i+1].append(colored(8 - i, 'red'))
self.board[0][9] = colored('+', 'red')
def display(self):
print('\n')
for row in self.board:
for i in row:
print(i, end=" ")
print('\n')
Game()
|
#!/usr/bin/env python
# coding: utf-8
# In[4]:
from Tkinter import *
from math import *
from sys import argv
import numpy as np
import matplotlib.pyplot as plt
pi = np.pi
#inital conditions
def drawCircle(canvas, x, y, rad, fill):
# color circle according to phase
# draw a circle of given radius
return canvas.create_oval(x-rad, y-rad, x+rad, y+rad, width=1, fill=fill)
def planet(canvas):
x=1
y=0
vx=0
vy=2*pi
t=0
dt=0.001
xj=5 #Jupiter inital position in x
yj=0 #Jupiter inital position in y
vxj=0 #Jupiter inital velocity in x
vyj=2.755 #Jupiter inital velocity in y
Mj = 1000*(1.9e27) #Mass of Jupiter
Ms=2.0e30 #Mass of Sun
Me=6.0e24 #Mass of Earth
yellow = "#FFD700"
blue = "#0000CD"
black = "#000000"
crimson = "#DC143C"
xc = 400
yc = 400
scale = 70
sunrad = scale/3
erad = scale/20
jrad = scale/10
sun = drawCircle(canvas, xc, yc, sunrad, yellow)
xe_array=[]
ye_array=[]
xj_array=[]
yj_array=[]
tj_array=[]
vxe_array=[]
xpl = xc + (scale*x)
ypl = yc + (scale*y)
xjpl = xc + (scale*xj)
yjpl = yc + (scale*yj)
xp = 0
yp = 0
xjp = 0
yjp = 0
planet = drawCircle(canvas, xpl, ypl, erad, blue)
jupiter = drawCircle(canvas, xjpl, yjpl, jrad, crimson)
canvas.after(1)
gui.update()
while t<12: #Note that this is in years and the orbital period of Jupiter is 12 Earth Years
re = np.sqrt(x**2+y**2) #distance Earth-Sun
rj = np.sqrt(xj**2+yj**2) #distance Jupiter - Sun
rej = np.sqrt((x-xj)**2+(y-yj)**2) #distance Earth - Jupiter
vx = vx - ((4*pi**2*x)/re**3)*dt-((4*pi**2*(Mj/Ms)*(x-xj))/rej**3)*dt #Earth x velocity
vy = vy - ((4*pi**2*y)/re**3)*dt-((4*pi**2*(Mj/Ms)*(y-yj))/rej**3)*dt #Earth y velocity
vxj = vxj - ((4*pi**2*xj)/rj**3)*dt-((4*pi**2*(Me/Ms)*(xj-x))/rej**3)*dt #Jupiter x velocity
vyj = vyj - ((4*pi**2*yj)/rj**3)*dt-((4*pi**2*(Me/Ms)*(yj-y))/rej**3)*dt #Jupiter y velocity
x = x + vx*dt #Earth positonal updates in x
y = y + vy*dt #Earth positonal updates in y
xj = xj + vxj*dt #Jupiters positional updates in x
yj = yj + vyj*dt #Jupiters positional updates in y
t=t+dt
xp = xc + (scale*x)
yp = yc + (scale*y)
xjp = xc + (scale*xj)
yjp = yc + (scale*yj)
canvas.create_line(xp, yp, xpl, ypl,fill = black, width=1)
canvas.delete(planet)
planet = drawCircle(canvas, xp, yp, erad, blue)
canvas.create_line(xjp, yjp, xjpl, yjpl,fill = black, width=1)
canvas.delete(jupiter)
jupiter = drawCircle(canvas, xjp, yjp, jrad, crimson)
canvas.after(1)
gui.update()
xpl = xp
ypl = yp
xjpl = xjp
yjpl = yjp
xe_array.append(x)
ye_array.append(y)
xj_array.append(xj)
yj_array.append(yj)
tj_array.append(t)
vxe_array.append(vx)
gui = Tk()
#root.mainloop()
width, height = 800, 800
x_center, y_center = 0.5*width, 0.5*height
x_scale, y_scale = 70, 70
# create a canvas
canvas = Canvas(gui, width=width, height=height, bg='white')
canvas.pack(expand=YES, fill=BOTH)
canvas.create_text(115, 25, font=("Purisa", 12), text="Earth's Orbit")
# begin recursive drawing
planet(canvas)
gui.mainloop() |
#List 有序可動列表
grades=[12,60,45,70,90]
print(grades)
print(grades[1:4])
grades[0]=55
print(grades)
grades=grades+[25,59]
print(grades)
print(len(grades))
grades[1:4]=[]
print(grades)
#巢狀列表
data=[[3,4,5],[6,7,8]]
print(data)
print(data[0][:2])
data[0][0:2]=[5,5,5]
print(data)
|
#set 集合
s1={3,4,5}
print(10 not in s1)
s2={4,5,6,7}
r1=s1&s2 #交集
r2=s1|s2 #聯集
r3=s1-s2 #差集
r4=s1^s2 #反交集
print(r1,"\n",r2,"\n",r3,"\n",r4)
s=set("Hello")
print(s)
print("H" in s) |
def avg(*ns):
sum=0
for n in ns:
sum=sum+n
print(sum/len(ns))
avg(3,4,5)
avg(99,56,78,85) |
import numpy as np
import matplotlib.pyplot as plt
def step_function(x):
y = x > 0 # Bool로 출력
return y.astype(np.int64) # y의 자료형을 int로 바꾸기
def sigmoid(x):
return 1 / (1+np.exp(-x))
x = np.arange(-5, 5, 0.1)
y = step_function(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1) # y축 범위 지정
x1 = np.arange(-5, 5, 0.1)
y1 = sigmoid(x1)
plt.plot(x1, y1, linestyle='--')
plt.ylim(-0.1, 1.1)
plt.show() |
#Ejercicio #43
# Programa que lea N valores y que cuente cuantos de ellos son positivos y cuantos
# son negativos (0 es condici'on de fin de lectura)
# Audny D. Correa Ceballos (Equipo 'about:blank')
#ENTRADAS
#Es el n'umero de valores que el usuario ingresa
rangoDeValores = int(input())
#Inicializar en 0 nuestros contadores
contadorNegativo = 0
contadorPositivo = 0
#PROCESO
for i in range(0, rangoDeValores+1):
#El usuario ingresa los valores
numero = int(input())
#Si el numero ingresado el diferente es 0
if (numero != 0):
#Si es positivo
if (numero > 0):
contadorPositivo += 1
#Si es negativo
else:
contadorNegativo += 1
#Si el numero es 0
else:
#Se detiene el for
break
#SALIDAS
#Todos los numeros positivos que se contaron (contadorPositivo)
print( contadorPositivo)
#Todos los numeros negativos que se contaron (contadorNegativo)
print(contadorNegativo)
|
#Autores: Programa realizado por Equipo2_CodePain
#Version 1.0
#Programa que calcula el MCD de dos números enteros mediante el algoritmo de Euclides
#Entrada: Dos números enteros aNum y bNum
aNum=-1
bNum=-1
res=1
save=0
while aNum<0 or bNum<0: #Comprueba que sean numeros positivos
aNum=int(input())
bNum=int(input())
#Proceso: Usando el algoritmo de Euclides se determina el MCD de los números
if aNum<bNum:
save=bNum
bNum=aNum
aNum=save
while res!=0:
res=aNum%bNum
aNum=bNum
bNum=res
#Salida: El MCD de los dos números
print(aNum)
|
# Ejercicio 7
# Escribir el programa para un programa que reciba un numero positivo, si este numero es mayor a 1000 se le sumara un 5%, si el numero es mayor a 3000 se le sumara otro 10% adicional y si el numero es mayor a 5000 se le sumara otro 5% adicional.
# Autor: Jorge Reyes (Equipo 'about:blank')
# Dato de entrada: valor numérico
# Dato de salida: valor numérico con el agregado correspondiente
def percentageCalc(num):
# Se asigna el valor de entrada a la variable "result"
result = num
# Compara y re-asigna valores
if (num > 1000):
result += num * .05
if (num > 3000):
result += num * .1
if (num > 5000):
result += num * .05
return int(result)
inp = int(input())
print(percentageCalc(inp))
|
#Autor: Deyberth Carrillo
#Entrada: El numero del cual se desean conocer los factoriales
#Salida: Los factoriales del numero ingresado
#Se solicita el numero a evaluar
print("Ingrese el numero del cual desea saber sus factoriales:")
numero=int(input())
factores=str(1)
posibleFactor=0
#Se evaluan los factores del numero que se ingreso
for posibleFactor in range(2,numero+1):
esFactor=numero%posibleFactor
if esFactor==0:
factores+=","+str(posibleFactor)
#Se imprimen los facores del numero que se ingreso
print("Los factores de "+str(numero)+" son: "+str(factores)) |
file=open("/ago-dic-2020/practicas/PrimerParcial/triangulo.txt", "r")
print(file.read())
def tipo(a, b, c):
if a==b and a==c:
return 'Equilatero'
elif a!=b and a!=c:
return 'Escaleno'
elif a==0 or b==0 or c==0:
return 'No es triangulo'
else:
return 'Isóceles'
print(tipo(1, 1, 1)) |
current_users=['jaden', 'yonatan', 'jose', 'raul', 'kio']
new_users=['KIO', 'marcos', 'jose','jonathan', 'estefanio']
new_userss=[x.lower() for x in new_users]
for new_user in new_userss:
if new_user in current_users:
print(f"{new_user} already been taken")
else:
print(f"welcome {new_user}")
|
#alien_0={'color': 'green', 'points': 5}
#print(alien_0['color'])
#print(alien_0['points'])
#new_points=alien_0['points']
#print(f"You just earned {new_points} Points!")
#print(alien_0)
#alien_0['x_position']=25
#alien_0['y_position']=5
#print(alien_0)
#alien_0={}
#alien_0['color']='green'
#alien_0['points']=25
#print(f"the aliens color is {alien_0['color']}")
#alien_0['color']= 'yellow'
#print(f"Then new aliens color is {alien_0['color']}")
alien_1={'x_position': 0, 'y_position': 25, 'speed': 'fast'}
print(f"Original position: {alien_1['x_position'], alien_1['y_position']}")
#Move alien to the right
#Determine how far to move the alien based on it current speed.
if alien_1['speed'] == 'slow':
x_increment = 1
elif alien_1['speed'] == 'medium':
x_increment = 2
else:
#this must be a fast alien
x_increment = 3
#The position is the old position plus the increment
alien_1['x_position'] = alien_1['x_position'] + x_increment
print(f"New position: {alien_1['x_position'], alien_1['y_position']}")
del alien_1['y_position']
print(alien_1) |
# pantry.py
import ast, collections
class Pantry:
def __init__(self, name, email, address, food_and_amt_needed):
self.name = name
self.email = email
self.address = address
self.food_and_amt_needed = food_and_amt_needed
def get_pantries():
restaurant_dicts = []
with open("pantry_data.txt", "r") as res_data:
for line in res_data.readlines():
dict_line = ast.literal_eval(line)
restaurant_dicts.append(dict_line)
return restaurant_dicts
def add_pantry(pantry):
pantry = pantry.__dict__
pantries = get_pantries()
pantries.append(pantry)
pantries = [x for n, x in enumerate(pantries) if x not in pantries[:n]]
with open("pantry_data.txt", "w") as pan_file:
for pan in pantries:
pan_file.write(f"{pan}\n")
if __name__ == "__main__":
foods_needed = {
"Beans": 24, # ounces
"Pepperoni Slices": 89, # grams
"Salad": 15 # pounds or kilos
}
helping_place = Pantry("Helper", "[email protected]", "Our Address", foods_needed)
add_pantry(helping_place)
b = get_pantries()
for thing in b:
print(thing) |
from __future__ import division
# Get a and b 's the Maximum common divisor
def Max_Common_Divisor(a, b):
while b != 0:
c = a % b
a = b
b = c
return a # a is max common divisor
# Get a and b's the least common multiple
def Min_Common_Multiple(a, b):
return a * b / a
# Fractional Addition
# a is the first fraction's molecular, b is the first fraction's Denominator
# c is the second fraction's molecular, d is the second fraction's Denominator
# return the molecular and Denominator of Fraction_Add_Fraction's Add and Minus
def Add_Minus_Of_Fraction_Fraction(a, b, c, d):
list = []
New_Multiple = Min_Common_Multiple(b, d)
b_Business = New_Multiple / b
d_Business = New_Multiple / d
a = a * b_Business
c = c * d_Business
# Get Add of Fractions
Add_Molecular = a + c
Add_Divisor = Max_Common_Divisor(New_Multiple, Add_Molecular)
list.append(int(Add_Molecular / Add_Divisor))
list.append(int(New_Multiple / Add_Divisor))
# Get Minus of Fractions
Minus_Molecular = a - c
Minus_Divisor = Max_Common_Divisor(New_Multiple, Minus_Molecular)
list.append(int(Minus_Molecular / Minus_Divisor))
list.append(int(New_Multiple / Minus_Divisor))
print "%d/%d + %d/%d = %d/%d" % (a, b, c, d, list[0], list[1])
print "%d/%d - %d/%d = %d/%d" % (a, b, c, d, list[2], list[3])
|
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def DetermineDateOfYear(date):
# To Determine the days of month
IntOfMonth = int(date[4:6])
for i in range(IntOfMonth - 1):
DaysOfMonth = (i + 1) * month[i]
# To Determine Leap year
IntOfYear = int(date[0:4])
if ((IntOfYear % 4 == 0) and (IntOfYear % 100 != 0)) or (IntOfYear % 400 == 0):
TotalDays = DaysOfMonth + 1 + int(date[6:8])
else: # Is not leap year
TotalDays = DaysOfMonth + int(date[6:8])
return TotalDays
DATE = raw_input("Enter the date(19700701):")
TotalDATE = DetermineDateOfYear(DATE)
print "The days of DATE is %d" % TotalDATE
|
for number in range(-100, 10000):
a = (number + 100) ** 0.5
b = (number + 268) ** 0.5
#if (a % 1 == 0) and (b % 1 == 0):
#if (not a % 1) and (not b % 1):
if a.is_integer() == True and b.is_integer() == True:
print number
|
def splitStr(s): return [ch for ch in s]
def buildGrid(lines, level):
grid = {}
for y, line in enumerate(lines):
for x, ch in enumerate(splitStr(line)):
pos = (x, y, level)
grid[pos] = ch
return grid
def adjacent(pos):
x, y, level = pos
return [(x - 1, y, level), (x + 1, y, level), (x, y - 1, level), (x, y + 1, level)]
def adjacentRecursive(pos):
x, y, level = pos
naive = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
ret = []
for px, py in naive:
if px == 2 and py == 2:
# adjacent square is the middle square, so expand and increase level
if x == 1:
# entire left side of inner grid
newOnes = [(0, yy, level + 1) for yy in range(0, 5)]
elif x == 3:
# entire right side of inner grid
newOnes = [(4, yy, level + 1) for yy in range(0, 5)]
elif y == 1:
# entire top side of inner grid
newOnes = [(xx, 0, level + 1) for xx in range(0, 5)]
elif y == 3:
# entire bottom side of inner grid
newOnes = [(xx, 4, level + 1) for xx in range(0, 5)]
for no in newOnes:
ret.append(no)
elif px < 0:
# adjacent square is to the left of the grid, identify square and decrease level
ret.append((1, 2, level - 1))
elif py < 0:
# adjacent square is above the grid, identify square and decrease level
ret.append((2, 1, level - 1))
elif px > 4:
# adjacent square is to the right of the grid, identify square and decrease level
ret.append((3, 2, level - 1))
elif py > 4:
# adjacent square is below the grid, identify square and decrease level
ret.append((2, 3, level - 1))
else:
# square on the same level
ret.append((px, py, level))
return ret
BUG = "#"
EMPTY = "."
def countAdjacentBugs(grid, pos):
adj = adjacent(pos)
chs = [grid.get(a, EMPTY) for a in adj]
return len(list(filter(lambda ch:ch==BUG, chs)))
def countBugs(grid, positions):
chs = [grid.get(a, EMPTY) for a in positions]
return len(list(filter(lambda ch:ch==BUG, chs)))
def transform(grid):
nxt = {}
for pos, ch in grid.items():
cnt = countAdjacentBugs(grid, pos)
if ch == BUG:
nch = BUG if cnt == 1 else EMPTY
else:
nch = BUG if cnt == 1 or cnt == 2 else EMPTY
nxt[pos] = nch
return nxt
def newBugState(ch, cnt):
if ch == BUG:
nch = BUG if cnt == 1 else EMPTY
else:
nch = BUG if cnt == 1 or cnt == 2 else EMPTY
return nch
def transformRecursive(grid):
nxt = {}
positionsToConsider = set(grid.keys())
# add in all adjacent
for pos in positionsToConsider.copy():
adj = adjacentRecursive(pos)
for a in adj:
positionsToConsider.add(a)
for pos in positionsToConsider:
adj = adjacentRecursive(pos)
ch = grid.get(pos, EMPTY)
cnt = countBugs(grid, adj)
nch = newBugState(ch, cnt)
nxt[pos] = nch
return nxt
def biodiversity(grid):
s = 0
for pos, ch in grid.items():
x, y, _ = pos
power = y * 5 + x
value = 2 ** power
if ch == BUG:
s += value
return s
INPUT = [
"#..#.",
".....",
".#..#",
".....",
"#.#.."
]
def part1():
grid = buildGrid(INPUT, 1)
seen = [grid]
while True:
grid = transform(grid)
if grid in seen:
print(biodiversity(grid))
return
seen.append(grid)
def p2(lines, cutoff):
grid = buildGrid(lines, 1)
del grid[(2, 2, 1)]
minutes = 0
while minutes < cutoff:
grid = transformRecursive(grid)
minutes += 1
print(countBugs(grid, grid.keys()))
def p2test():
lines = [
"....#",
"#..#.",
"#..##",
"..#..",
"#...."
]
p2(lines, 10)
def part2():
p2(INPUT, 200)
if __name__ == "__main__":
#part1() # 32526865
#p2test()
part2() # 2009 |
from functools import reduce
import itertools
import intcode
def readNumbers(name):
with open(name) as f:
for line in f.readlines():
return list(map(lambda x: int(x), line.split(",")))
# Directions:
# 0 - up
# 1 - right
# 2 - down
# 3 - left
def rotate(currentDirection, turnDirection):
delta = 1 if turnDirection == 1 else -1
currentDirection = (currentDirection + delta) % 4
return currentDirection
def move(xyPosition, direction):
(x, y) = xyPosition
if direction == 0: y -= 1
elif direction == 1: x += 1
elif direction == 2: y += 1
elif direction == 3: x -= 1
else: raise Exception("Unknown direction %d" % (direction,))
return (x, y)
def paintAndMove(hullMap, xyPosition, currentDirection, output):
(paint, turnDirection) = output
hullMap[xyPosition] = paint
newDirection = rotate(currentDirection, turnDirection)
return (move(xyPosition, newDirection), newDirection)
def readColor(hullMap, xyPosition):
if not (xyPosition in hullMap):
return 0
return hullMap[xyPosition]
def paintHull(numbers, hullMap):
state = None
currentDirection = 0 # up
currentPos = (0, 0)
while True:
input = [readColor(hullMap, currentPos)]
output = []
state = intcode.run(numbers, input, output, state)
if state[0] == True:
break
(currentPos, currentDirection) = paintAndMove(hullMap, currentPos, currentDirection, output)
def part1():
"""
>>> part1()
2392
"""
numbers = readNumbers("input")
hullMap = {}
paintHull(numbers, hullMap)
return len(hullMap.keys())
def renderColor(xyPosition, color, canvas):
(x, y) = xyPosition
# offset so that (0,0) is in the middle
x += 50
y += 50
row = canvas[y]
row[x] = "#" if color == 1 else " "
def render(hullMap):
canvas = []
for _ in range(0, 100):
emptyRow = [" "] * 100
canvas.append(emptyRow)
for k in hullMap.keys():
pos = k
color = hullMap[k]
renderColor(pos, color, canvas)
ascii = "\n".join(map(lambda r: "".join(r), canvas))
return ascii
def part2():
numbers = readNumbers("input")
hullMap = {}
hullMap[(0, 0)] = 1 # white
paintHull(numbers, hullMap)
print(render(hullMap))
if __name__ == "__main__":
#import doctest
#doctest.testmod()
part2()
|
from random import randint
import prompt
def even_description():
print('Answer \'yes\' if the number is even, otherwise answer \'no\'.')
def even_logic():
number = randint(1, 99)
even = not bool(number % 2)
if even:
correct_answer = 'yes'
else:
correct_answer = 'no'
print('Question: {}'.format(number))
answer = prompt.string('Your answer: ')
if answer == correct_answer:
return {
'passed': True,
'answer': answer,
'correct_answer': correct_answer,
}
else:
return {
'passed': False,
'answer': answer,
'correct_answer': correct_answer,
}
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 15:37:49 2020
@author: ibrahim
"""
#Pythonda veri saklamak için oluşturdugumuz alanlara değişken denir.
x = 5
y = 10
z=x+y # 15
k
print(x) # 5
print(y) # 10
print(z) # 15
print(k) # NameError: name 'k' is not defined.
#String bir değişken oluştururken tek veya çift tırnak kullanmalıyız.
name = "İbrahim"
surname = 'Yıldız'
age = "50" #String bir değerdir.
a = 50 # sayısal olarak 50 değeri tanımladık.
b = "50" # sözel (string) olarak 50 değeri tanımladık.
toplam = a + b #100 değerini döndürmesi beklenirken 5050 gibi bir değer döndürür.
print(type(toplam)) #Bu tiü bir yazdırma işlemi hata verir.String bir değer ile int değer toplanamaz!
x = 10
x = 20 #x'in içindeki değer silinir ve 20 değerini alır.
x += 10 #x en son 20 iken +10 değer alır ve 30 olur.
#Değişken isimleri rakam ile başlayamaz!!!
1ad => hatalı
ad1 => geçerli
_ad => geçerli
#Büyük küçük harf duyarlılığı vardır.
yas = 50
Yas = 100
#bool(Boolean) veri tipi bir durumun doğru(True, 1) yada yanlış(False, 0) olması hakkında bilgi tutar.
isStudent = True
isEngineer = 0
print(type(isStudent)) # <class 'bool'>
#Pythonda aynı satırlarda değişkenler tanımlayabiliriz.
a, b, name, isStudent = 1, 5.0, 'Ahmet', True
|
# 1) Declare two variables, a string and an integer
# named "fullName" and "age". Set them equal to your name and age.
fullName = "Scott Anderson"
age = 51
# 2) Declare an empty array called "myArray".
# Add the variables from #1 (fullName and age) to the empty array using the push method.
# Print to the console.
myArray = []
myArray.append(fullName)
myArray.append(age)
print myArray
print fullName.split()
import datetime
now = datetime.datetime.now()
currentYear = now.year
def myAge(yearBorn):
print (currentYear - yearBorn)
def sayName():
print "Hello, %s" % fullName.split()[0]
sayName()
myAge(1966)
In the beginning...alpha Omega
|
def longVowel(aWord):
longVowel = list(aWord)
returnWord = longVowel
for i in range (0,(len(aWord))):
if (longVowel[i] == 'A' or longVowel[i] == 'a'):
if (longVowel[i].upper() == longVowel[i+1].upper()):
# Magic happens here....insert 3 vowels
returnWord.insert(i+1, 'aaa')
elif (longVowel[i] == 'E' or longVowel[i] == 'e'):
if (longVowel[i].upper() == longVowel[i+1].upper()):
# Magic happens here....insert 3 vowels
returnWord.insert(i+1, 'eee')
elif (longVowel[i] == 'I' or longVowel[i] == 'i'):
if (longVowel[i].upper() == longVowel[i+1].upper()):
# Magic happens here....insert 3 vowels
returnWord.insert(i+1, 'iii')
elif (longVowel[i] == 'O' or longVowel[i] == 'o'):
if (longVowel[i].upper() == longVowel[i+1].upper()):
# Magic happens here....insert 3 vowels
returnWord.insert(i+1, 'ooo')
elif (longVowel[i] == 'U' or longVowel[i] == 'u'):
if (longVowel[i].upper() == longVowel[i+1].upper()):
# Magic happens here....insert 3 vowels
returnWord.insert(i+1, 'uuu')
return ''.join(returnWord)
testParagraph = "bookkeeper"
newParagraph = longVowel(testParagraph)
print "\nTest Paragraph:\n"
print testParagraph
print "\nNew Paragraph:\n"
print newParagraph
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Z Lei on 01/01/2018.
class StackUnderflow(ValueError): pass
class SStack(object):
"""顺序表栈"""
def __init__(self):
self._elem = []
def is_empty(self):
return self._elem == []
def top(self):
if self._elem == []:
raise StackUnderflow("in top")
return self._elem[-1]
def push(self, elem):
self._elem.append(elem)
def pop(self):
if self._elem == []:
raise StackUnderflow("in pop")
return self._elem.pop()
s = SStack()
s.push(3)
s.push(5)
while not s.is_empty():
print s.pop()
class LinkedListUnderflow(ValueError):
pass
class LNode(object):
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
class LStack(object):
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def top(self):
if self.top is None:
raise StackUnderflow
else:
return self.top.elem
def push(self, elem):
self.top = LNode(elem, self.top)
def pop(self):
if self.top is None:
raise StackUnderflow
tmp = self.top
self.top = self.top.next
return tmp.elem
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Z Lei on 17/08/2017.
def quicksort(array):
if len(array) < 2:
return array
else:
jizhun = array[0]
less = [i for i in array[1:] if i <= jizhun]
more = [i for i in array[1:] if i > jizhun]
return quicksort(less) + [jizhun] + quicksort(more)
print quicksort( [1, 4, 2, 6, 9, 8, 3, 7, 5, 0])
print quicksort([1,3,4,5,6,7,32,5423,4523,65,35423,5454,6534])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Z Lei on 28/12/2017.
def list_sort(lst):
"""
插入排序
:param lst:
:return:
"""
for i in range(1, len(lst)):
value = lst[i]
j = i
while value < lst[j - 1] and j > 0:
lst[j] = lst[j - 1]
j = j - 1
lst[j] = value
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Z Lei on 17/08/2017.
input = [2, 4, 6]
def dedai(input):
if len(input) == 1:
return input[0]
elif len(input) == 0:
return 0
else:
return input[0] + dedai(input=input[1:])
print 12 == dedai(input)
def count_len(input):
if len(input) == 1:
return 1
elif len(input) == 0:
return 0
else:
return 1 + count_len(input=input[1:])
print count_len(input)
max_value = 0
def get_max(input, max_value):
print max_value, input
if len(input) == 0:
return max_value
else:
if max_value < input[0]:
max_value = input[0]
return get_max(input=input[1:], max_value=max_value)
# print get_max([1, 3, 4, 5], 0)
# print get_max([1, 3, 7, 5], 0)
print get_max([100, 3, 4000, 5], 0)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @DateTime :
# @Author : Z LEI
class ProtectAndHideX(object):
def __init__(self, x):
assert isinstance(x, int), 'x must be an integer'
self.__x = ~x
def get_x(self):
return ~self.__x
x = property(get_x)
inst = ProtectAndHideX(333333)
print inst.x
from math import pi
def get_pi(dummy):
return pi
class PI(object):
pi = property(get_pi, )
inst = PI()
print inst.pi
|
'''
함수만들기
def add(a,b):
c = a+b
print(c)
add(3, 2)
def add(a,b):
c = a + b
return c
x = add(3, 2)
print(x)
def add(a, b):
c = a + b
d = a - b
return c, d
print(add(3,2))
'''
def isPrime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
a = [12, 13, 7, 9, 19]
for y in a:
if isPrime(y):
print(y, end = ' ')
|
# 최솟값 구하기
arr = [5, 3, 7, 9, 2, 5, 2, 6]
# 가장작은 숫자가 저장될 변수 지정
arrMin = float('inf') # 파이썬에서 가장 큰값으로 저장하여 초기화
for i in range(len(arr)):
if arr[i] < arrMin:
arrMin = arr[i]
print(arrMin) |
smallestValue = None
for i in [1, 5, 6, 7, 10, 15, 16]:
if smallestValue is None:
smallestValue = i
elif smallestValue > i :
smallestValue = i
print("Smallest Value:", smallestValue)
|
first = 0
print("first thing: ", first)
for i in [1, 4, 5, 9, 12] :
first = i + first
print("Sum: ", first)
|
# Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for
# all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function called computepay() and use
# the function to do the computation.
# The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program
# (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
def computepay(hours, ratePerHours):
if hours <= 40 :
pay = hours * ratePerHours
else :
print("alo:", ratePerHours)
pay = 40 * ratePerHours + (hours - 40) * ratePerHours * 1.5
return pay
hours = input("Input the hours: ")
ratePerHours = input("Input rate per hours: ")
try:
hoursFloat = float(hours)
except:
print("Please input an float")
quit()
try:
ratePerHoursFloat = float(ratePerHours)
except:
print("Please input an float")
quit()
pay = computepay(hoursFloat, ratePerHoursFloat)
print(pay)
|
#!/usr/bin/python3
"""
| Purpose: To Give a frequency count of the titles and give information to help decide on a cutoff.
|
| History: Created on November 21, 2018 by Greg Colledge
|
"""
import sys
import operator
import statistics as stats
#-----READ IN DATA-----
titleFreq = {}
with open(sys.argv[1],'r') as dataFile:
for line in dataFile:
for title in line.split():
if(title not in titleFreq):
titleFreq[title] = 0;
titleFreq[title] += 1;
print("Finished counting titles")
#-----SortedList----
sortedList = sorted(titleFreq.items(), key=operator.itemgetter(1))
titles = []
freq = []
for (title, num) in sortedList:
titles.append(title)
freq.append(num)
keepList = [] #this is the list of (title, freq) tuples that pass the criterion.
if(sys.argv[2]=='-f'):
#frequency cut off
target = int(sys.argv[3])
print("length of sorted: %s" %str(len(sortedList)))
print(str(sortedList[0]))
print(str(sortedList[-1]))
for i in range(len(sortedList)-1,0,-1):
print("value to compare: %s" %str(sortedList[i]))
if sortedList[i][1] > target:
print(sortedList[i])
keepList.append(sortedList[i]);
else:
print(target)
break;
elif(sys.argv[2]=='-c'):
#title count cutoff
target = int(sys.argv[3])
for i in range(len(sortedList)):
keepList.append(sortedList[i]);
print("length of keepList: %d" %len(keepList))
keepFreq = []
keepTitles = []
for each in keepList:
keepFreq.append(each[1])
keepTitles.append(each[0])
#-----Stats stuff-----
avgFreq = sum(freq) / len(titleFreq);
stdDev_of_Freq = stats.stdev(freq)
avgKeepFreq = stats.mean(keepFreq)
sd_of_Keep = stats.stdev(keepFreq)
#-----OUTPUT-----
for i in range(20):
print(str(freq[i]) + "\t" + str(titles[i]))
print(len(titleFreq))
print("average frequency: %d" % avgFreq)
print("std deviation: %d" % stdDev_of_Freq)
print("average Kept frequency: %d" % avgKeepFreq)
print("std deviation of Kept: %d" % sd_of_Keep)
for i in range(1,11):
print(sortedList[-i])
|
altura=float(input('A altura da parede é :'))
largura=float(input('A largura da parede é :'))
area=altura*altura
print('A area da parede é {} e voce vai precisar de {} litros de tinta'.format(area,(area)/2))
|
frase = str(input('Digite uma frase : ')).strip().lower()
a='a'
print('A letra "A" aparece nessa string {} vezes, pela primeira vez na posiçao {} na a ultima {}'.format(frase.count(a), frase.find(a)+1,frase.rfind(a)+1))
|
nome=str(input('Digite seu nome completo : '))
masc=nome.upper()
mins=nome.lower()
sep=nome.split()
print('''Nome com maiusculas: {}
Nome com tudo minusculo {}
O nome tem {} letras e
O primeiro nome, {}, tem {} letras'''.format(masc,mins,len(''.join(sep)),sep[0], len(sep[0])))
'''Na 1ª resoluçao do guanabara, achei que criou uma complexidade desnescessaria, no input colocou o .strip() e no numero de letras colocou
len(nome)-nome.count(' ') , isso apenas para remover todos os espaços,
Me parece muito mais facil transformar em lista e juntar de novo, isso remove ja todos os espaços,
pareceu que ele fez isso para fazer tudo com apenas uma variavel ''' |
"""from math import floor,trunc
num = float(input('Digite um numero real'))
print('O numero é {} e a sua parte inteira é {}'.format(num, floor(num)))
#podemos usar o trunc(num)"""
num = float(input('Digite um valor : '))
print('O valor é {} e a sua parte inteira é {} '.format(num, int(num)))
|
frase = ' Curso em Video Python '
print(frase.capitalize(), frase.lower().title(), frase.lower().title().replace('Em', 'em'))
print('Curso ' in frase, frase.find('Curso'))
print(frase.split())
separado=frase.split()
print(separado," ".join(separado))
|
from random import randint
itens = ('pedra', 'papel', 'tesoura')
print('''escolha e digite
0 para pedra
1 para papel
2 para tesoura
Qualquer outro digito encerra o programa''')
while True:
escolha = int(input('escolha : '))
pc = randint(0, 2)
if pc == 0 and escolha == 1:
print('{:=^40}'.format(' GANHOU :D '))
print('pc escolheu {}'.format(itens[pc]))
elif pc ==1 and escolha == 2:
print('{:=^40}'.format(' GANHOU :D '))
print('pc escolheu {}'.format(itens[pc]))
elif pc ==2 and escolha == 0:
print('{:=^40}'.format(' GANHOU :D '))
print('pc escolheu {}'.format(itens[pc]))
elif pc==escolha:
print('{:-^60}'.format(' EMPATOU '))
print('voce e o pc escolheram {}'.format(itens[pc]))
elif 0 < escolha > 2 :
print('voce nao digitou uma opçao valida, mas o computador escolheu a opçao {} so para vc saber,encerrando...'.format(itens[pc]))
break
else:
print('perdeu, vc jogou {} e o computador {}'.format(itens[escolha],itens[pc]))
'''while usado para facilitar testes a soluçao original nao usa operadores logicos e nem loop, fica gigante
pq esse exercicio é antes da aula de while ...
'''
|
import pygame as pg
import math
pg.init()
black = (0, 0, 0)
yellow = (255, 255, 0)
grey = (127, 127, 127)
width = 1200
height = 600
screen = pg.display.set_mode((width, height))
pg.display.set_caption("game of life")
grid = []
length = 10
class grid_cell:
def __init__(self, x, y, cell_length):
self.x = x
self.y = y
self.cell_length = cell_length
self.cell_color = black
def toggle_state(self):
if self.cell_color == black:
self.cell_color = yellow
else:
self.cell_color = black
def show_cell(self):
pg.draw.rect(screen, self.cell_color, (self.x,self.y,self.cell_length,self.cell_length))
def make_grid():
for y in range(0, height, length):
row = []
for x in range(0, width, length):
row.append(grid_cell(x+1,y+1,length-2))
grid.append(row)
def show_grid():
for row in grid:
for cell in row:
cell.show_cell()
def count_neighbour(i, j):
count = 0
if i != len(grid)-1:
count += 1 if grid[i+1][j].cell_color == yellow else 0
if i != len(grid)-1 and j != len(grid[i])-1:
count += 1 if grid[i+1][j+1].cell_color == yellow else 0
if j != len(grid[i])-1:
count += 1 if grid[i][j+1].cell_color == yellow else 0
if i != 0 and j != len(grid[i])-1:
count += 1 if grid[i-1][j+1].cell_color == yellow else 0
if i != 0:
count += 1 if grid[i-1][j].cell_color == yellow else 0
if i != 0 and j != 0:
count += 1 if grid[i-1][j-1].cell_color == yellow else 0
if j != 0:
count += 1 if grid[i][j-1].cell_color == yellow else 0
if i != len(grid)-1 and j != 0:
count += 1 if grid[i+1][j-1].cell_color == yellow else 0
return count
def update_grid():
for i in range(len(grid)):
for j in range(len(grid[i])):
grid[i][j].cell_neighbour = count_neighbour(i, j)
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j].cell_color == black and grid[i][j].cell_neighbour == 3:
grid[i][j].toggle_state()
elif grid[i][j].cell_color==yellow and (grid[i][j].cell_neighbour>3 or grid[i][j].cell_neighbour<2):
grid[i][j].toggle_state()
def simulate():
time_step = 0
running = True
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
return False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
running = False
screen.fill(grey)
show_grid()
time_step += 1
if time_step == 10:
time_step = 0
update_grid()
pg.display.update()
return True
def initialize():
running = True
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.MOUSEBUTTONDOWN:
x, y = pg.mouse.get_pos()
grid[y//length][x//length].toggle_state()
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
running = simulate()
screen.fill(grey)
show_grid()
pg.display.update()
make_grid()
initialize()
|
class SparseList(list):
def __setitem__(self, index, value):
missing = index - len(self) + 1
if missing > 0:
self.extend([None] * missing)
list.__setitem__(self, index, value)
def insert(self, index, value):
self[index] = value
return self
def __getitem__(self, index):
try:
return list.__getitem__(self, index)
except IndexError:
return None
def get_by_id(key, keys, items):
"""
Creates a dictionary from the results of an index lookup by key on items.
Provide a list of keys to map to the found item.
"""
details = items[key]
if details is None:
return None
return dict(
(keys[i], value) for i, value in enumerate(details) if bool(value))
|
#rock paper scissor game
import random
player_wins=0
computer_wins=0
winner=3
while player_wins<winner and computer_wins<winner:
print(f"\nPlayer score:{player_wins} Computer score:{computer_wins}")
print(" ...rock...")
print("...paper...")
print("...scissors...")
choice= input("(Enter player's choice):").lower()
if(choice=="quit" or choice=="q"):
break
computer=random.randint(0,2)
if(computer==0):
computer="rock"
elif(computer==1):
computer="scissors"
else:
computer="paper"
print(f"The computer chose {computer}")
if(choice==computer):
print("Draw!!")
elif(choice=="rock"):
if(computer=="scissors"):
print("Player wins")
player_wins+=1
else:
print("computer wins")
computer_wins+=1
elif(choice=="scissors"):
if(computer=="rock"):
print("Computer wins")
computer_wins+=1
else:
print("Player wins")
player_wins+=1
elif(choice=="paper"):
if(computer=="rock"):
print("Player wins")
player_wins+=1
else:
print("Computer wins")
computer_wins+=1
else:
print("Enter something valid")
if(player_wins<computer_wins):
print("\nOH NOO! Computer won")
elif(player_wins==computer_wins):
print("It's a tie")
else:
print("\nYAYYYY!!! You won")
print(f"Final scores: \nPlayer:{player_wins} \t computer:{computer_wins}")
|
from core.Config import alphabet, C_list
class HillTrigraph_Cipher:
"""
Name: {cyan}The Hill-Trigraph Cipher{reset}
Description: {cyan}An encryption and decryption technique that use 3x3 integer matrices as keys.{reset}
Possibility: {cyan}5,429,503,678,976{reset}
Author: {yellow}@Khiem Nguyen{reset}
[+] There are 9 keys that you need to input!!
{cyan}HINT{reset}:
(a = ODD ,b = ODD,c = EVEN) (a = EVEN,b = ODD,c = ODD )
(d = EVEN,e = ODD,f = EVEN) or (d = EVEN,e = ODD,f = ODD )
(g = EVEN,h = ODD,i = ODD ) (g = ODD ,h = ODD,i = ODD )
"""
def __init__(self, msg, keys):
self.msg = msg
if keys is None:
try:
self.keys = [int(input('Your key ({}): '.format(name))) for name in ['A','B','C','D','E','F','G','H','I']]
except ValueError as e:
raise ValueError()
def encrypt(self):
A,B,C,D,E,F,G,H,I = self.keys
enc_list = [self.msg[i:i+3] for i in range(0, len(self.msg), 3)]
determinant = ((A * E * I) - (A * F * H) - (D * B * I) + (D * C * H) + (G * B * F) - (G * C * E)) % 26
encrypt_num_list = []
new_num_list = []
result = []
if determinant not in C_list:
return []
if len(enc_list[-1]) == 1:
enc_list.append(enc_list[-1] + 'xx')
enc_list.pop(-2)
elif len(enc_list[-1]) == 2:
enc_list.append(enc_list[-1] + 'x')
enc_list.pop(-2)
for pair in enc_list:
encrypt_num_list.append([alphabet.get(char.lower()) for char in pair])
for num_pair in encrypt_num_list:
first_digit, second_digit, third_digit = num_pair
temp_first_digit = ((A * first_digit) + (B * second_digit) + (C * third_digit)) % 26
temp_second_digit = ((D * first_digit) + (E * second_digit) + (F * third_digit)) % 26
temp_third_digit = ((G * first_digit) + (H * second_digit) + (I * third_digit)) % 26
if temp_first_digit == 0:
temp_first_digit = 26
elif temp_second_digit == 0:
temp_second_digit = 26
elif temp_third_digit == 0:
temp_third_digit = 26
new_num_list.append([temp_first_digit, temp_second_digit, temp_third_digit])
for pair in new_num_list:
for number in pair:
if number == 0:
result.append('Z')
else:
for letter, index in alphabet.items():
if number == index:
result.append(letter.upper())
return ''.join(result)
def decrypt(self):
A,B,C,D,E,F,G,H,I = self.keys
dec_list = [self.msg[i:i+3] for i in range(0, len(self.msg), 3)]
determinant = ((A * E * I) - (A * F * H) - (D * B * I) + (D * C * H) + (G * B * F) - (G * C * E)) % 26
decrypt_num_list = []
new_num_list = []
result = []
if not determinant in C_list:
return []
inverse_determinant = C_list.get(determinant)
new_A = ((((E * I) - (F * H)) % 26) * inverse_determinant) % 26
new_B = ((((C * H) - (B * I)) % 26) * inverse_determinant ) % 26
new_C = ((((B * F) - (C * E)) % 26) * inverse_determinant) % 26
new_D = ((((F * G) - (D * I)) % 26) * inverse_determinant) % 26
new_E = ((((A * I) - (C * G)) % 26) * inverse_determinant) % 26
new_F = ((((C * D) - (A * F)) % 26) * inverse_determinant) % 26
new_G = ((((D * H) - (E * G)) % 26) * inverse_determinant) % 26
new_H = ((((B * G) - (A * H)) % 26) * inverse_determinant) % 26
new_I = ((((A * E) - (B * D)) % 26) * inverse_determinant) % 26
for pair in dec_list:
decrypt_num_list.append([alphabet.get(letter.lower()) for letter in pair])
for num_pair in decrypt_num_list:
first_digit, second_digit, third_digit = num_pair
temp_first_digit = ((new_A * first_digit) + (new_B * second_digit) + (new_C * third_digit)) % 26
temp_second_digit = ((new_D * first_digit) + (new_E * second_digit) + (new_F * third_digit)) % 26
temp_third_digit = ((new_G * first_digit) + (new_H * second_digit) + (new_I * third_digit)) % 26
if temp_first_digit == 0:
temp_first_digit = 26
elif temp_second_digit == 0:
temp_second_digit = 26
elif temp_third_digit == 0:
temp_third_digit = 26
new_num_list.append([temp_first_digit, temp_second_digit, temp_third_digit])
for num_pair in new_num_list:
for number in num_pair:
for letter,index in alphabet.items():
if number == index:
result.append(letter)
if result[-1] == 'x' and result[-2] == 'x':
result.pop()
result.pop()
elif result[-1] == 'x':
result.pop()
return ''.join(result) |
valor = float(input("Informe o valor da casa: R$"))
sal = float(input("Informe seu salário: R$"))
anos = int(input("Informe em quantos anos vai querer pagar: "))
prestacao = valor/(anos*12)
excede = sal * 0.30
if prestacao > excede:
print("\nEmpréstimo negado, salário muito baixo para prestação do imóvel. \nSalário: R${:.2f} \nPrestação: R${:.2f}".format(sal, prestacao))
else:
print("\nEmpréstimo concedido! \nPrestação de R${:.2f} por mês, durante {} anos.".format(prestacao, anos))
|
s =0
c =0
for i in range (1, 501, 2):
# print(i, end = " ")
if i % 3 == 0:
c = c + 1
s = s +i
print("O valor total dos {} valores é: {}".format(c,s))
|
n= float(input("Quantos reais você pretende converter para dólares?"))
print("A sua conversão para dólares é igual à: US${:.2f}".format(n/3.27)) |
s=0
c=0
for i in range (0, 6):
n = int(input("Informe o n°: "))
if n % 2 == 0:
c = c +1
s = s + n
if s > 0:
print("A soma dos {} números pares foi {}.".format(c, s))
else:
print("Não houveram números pares!")
|
n1= float(input("Qual a altura da parede em metros? "))
n2= float(input("Qual a largura da parede em metros? "))
a= n1*n2
q= a/2
print("A quantidade de tinta em litros necessária pra pintar a parede é igual à: {}".format(q))
|
days = int(input("Informe a quantidade de dias: "))
km = float(input("Informe a quantidade de km's rodados: "))
preco = (days *60) + (km * 0.15)
print("Total: {:.2f}" .format(preco)) |
input('Hi, Isabella! How can I help you today?')
print("I'll set everything ready as you command me to do, just wait patiently")
print('My system is ready now to do whatever account you tell me to do.')
n1 = int(input('Now, please, put the first number:'))
n2 = int(input('Now, please, put the second one:'))
print("First I'm going to make the number one plus the second one")
s= n1+n2
print ('It results at:{}.'.format(s))
print('I guess you want to know what is the type of the account, I will show you')
print(type(s))
|
# coding: utf-8
# ## Question 2
# #### To run this code, ensure that the version of the following are correct: python3.6, anaconda3
import csv
import numpy as np
inp=[]
out=[]
testinp=[]
testout=[]
with open("train_1_5.csv", newline ='\n') as f: #read the training data
reader =csv.reader(f)
for row in reader:
inp += [[float(row[0]), float(row[1])]] #obtain the input values which are of colm 1 and 2 as the vector X
out += [[float(row[2])]] #obtain the label which are of colm 3 as Y
X = np.array(inp) #convert the list to array
Y = np.array(out)
with open("test_1_5.csv", newline ='\n') as ftest: #read the test data
reader =csv.reader(ftest)
for row in reader:
testinp += [[float(row[0]), float(row[1])]]
testout += [[float(row[2])]]
testX = np.array(testinp)
testY = np.array(testout)
#print (testX)
def perceptron(X,Y,iterations):
theta = np.zeros(len(X[0])) #initialise zero vector
theta0 =0
#print (theta)
for iteration in range(iterations):
for i,x in enumerate(X):
#when the signs are different then the output will be smaller or equal to zero
if (((np.dot(X[i],theta))+theta0)*Y[i]) <=0 : #there is classification error
theta0 = theta0 +Y[i] #update the theta0 value each time there is an error by the y(i)
theta = theta + X[i]*Y[i] #update the theta value each time there is an error by the y(i)
return (theta,theta0)
#interations 5
theta_5 = (perceptron(X,Y,5))[0] #theta
theta0_5 = (perceptron(X,Y,5))[1] #theta0
#iterations 10
theta_10 = (perceptron(X,Y,10))[0] #theta
theta0_10 = (perceptron(X,Y,10))[1] #theta0
def perceptronTest(testX,testY,theta,theta0):
numerror = 0
numentries = len(testY) #total number of entries in Test data set
for i,x in enumerate(testX):
if (((np.dot(testX[i],theta)) +(theta0))*testY[i]) <= 0: #there is classification error
numerror += 1 #the number of data sets that had classification error
accuracy = (1- (numerror / numentries)) * 100
return accuracy
print ('For 5 iterations, accuracy: '+ str(perceptronTest(testX,testY,theta_5,theta0_5)) + '%' )
print ('For 10 iterations, accuracy: '+ str(perceptronTest(testX,testY,theta_10,theta0_10)) + '%')
|
'''------==================Задача 16 (2/10)====================------
Заданное число N записали 100 раз подряд и затем возвели в квадрат. Что получилось?
>*Вводится целое неотрицательное число N не превышающее 1000.'''
# str(данные);
y = 100
n = int(input("Введите число:"));
if(n < 0 or n > 1000):
print("Введите не отрицательное число и не превышающее 1000.");
else:
a1 = str(n);
a2 = a1 * y;
a3 = int(a2);
a4 = a3*a3;
print(a4); |
'''------==================Задача 14 (1/10)=================------
Вводится число 0 или 1, необходимо вывести 1 или 0 соответственно.
>*Число 0 или 1.'''
x = int(input("Введите 0 или 1:"));
if (x == 0):
print(1);
elif (x == 1):
print(0);
else:
print("Введите 1 или 0!!!"); |
"""
Esse modulo contem funcoes matematicas
"""
from math import exp
def distancia_euclidiana(x, y, n):
"""
Essa funcao calcula a distancia euclidiana entre n pontos
:param x: um numero ou uma lista de numeros
:param y: um numero ou uma lista de numeros
:param n: quantidade de pontos
:return: a distancia euclidiana
"""
distancia = 0
for i in range(n):
distancia += (x[i]-y[i])**2
distancia = distancia**(1/2)
return distancia
def gaussiana(distancia, abertura):
"""
Essa funcao calcula uma funcao de gauss
:param 0.1: altura do pico da curva
:param distancia: posicao do centro do pico
:param abertura: largura do sino
:return: o resultado da funcao exponencial
"""
return 0.1 * exp((-(distancia**2)/(2*abertura**2)))
def aprendizado(epoca):
"""
Essa funcao calcula o aprendizado
:param epoca: numerador
:param decaimento: denominador
:return: o resultado da funcao exponencial
"""
decaimento = 10
return 0.1 * exp(-epoca/decaimento)
|
from player import Player
import random
class Human(Player):
def __init__(self):
"""Default constructor"""
self.playerName = "Human"
# *********************************************************************
# Function Name: play
# Purpose: To let the human play the game of Duell
# Parameters:
# self, the Human the method is called on
# board, the Board that is being played on
# Return Value: none
# Local Variables:
# helpAnswer, an integer that stores input of whether the player wants the computer's help or not
# dieRow and dieColumn, integers that store input of the die that the player wishes to move
# spaceRow and spaceColumn, integers that store input of the space that the player wishes to move to
# isValidMove, a boolean that determines if the move the player wants to make is valid or not
# frontalMove and lateralMove, booleans that store whether or not a frontal or lateral move is initially possible
# secondFrontalMove and secondLateralMove, booleans that store whether or not a frontal or lateral move is possible after a
# 90 degree turn
# rowRolls and columnRolls, integers that store how many spaces a die needs to move frontally and laterally to get to the
# space
# answer, a string that stores the answer of whether the player wants to initially move frontally or laterally
# dieNameBefore and dieNameAfter, strings that store the names of a die before it is moved and after it is moved respectively
# Algorithm:
# 1) Ask the player if they want to make a move or get help from the computer. Store result in helpAnswer
# 2) If helpAnswer is 2, call getHelp
# 3) Otherwise, enter a while loop to get the coordinates of the die the player wants to move and the space they want to
# move to
# 4) Perform necessary checks for the die and space coordinates. If they do not pass, start at the beginning of the loop again
# 5) Perform checks to see if the die is able to move to the space without problems. If they do not pass, start at the
# beginning of the loop again
# 6) See if the die can move laterally or frontally from its position. If it can, check to see if it can move again in a
# 90 degree turn. Should they pass checks, isValidMove becomes true and the move can be made
# 7) Get the name of the die before it is moved and store it in dieNameBefore
# 8) If the human is able to move in either direction at first, ask them which direction they would like to move in
# 9) Make the move, get the die name after it is moved, and store it in dieNameAfter
# 10) Call printMove() to output the move that was just made to the window
# Assistance Received: none
# *********************************************************************
def play(self, board):
# Integer to store the answer of whether ot not the human wants help.
helpAnswer = 0
# See if the human wants help.
while helpAnswer != 1:
helpAnswer = input("Enter 1 to make a move or 2 to get a recommendation from the computer: ")
# 1 means they want to play:
if (int(helpAnswer) == 1): break
# 2 means they want help:
elif (int(helpAnswer) == 2): self.getHelp(board)
# Otherwise, not a valid input:
else: print("Invalid input, please try again.")
# Boolean value of whether or not a move is valid.
isValidMove = False
# Enter a while loop to get the coordinates of the die you want to move and where to move it to:
while (not isValidMove):
# Get the coordinates of the die to move
dieRow = input("Enter the row of the die you want to move: ")
dieColumn = input("Enter the column of the die you want to move: ")
spaceRow = input("Enter the row of the space you want to move to: ")
spaceColumn = input("Enter the column of the space you want to move to: ")
# Convert to integers
dieRow = int(dieRow)
dieColumn = int(dieColumn)
spaceRow = int(spaceRow)
spaceColumn = int(spaceColumn)
# If the coordinates entered are greater than what should be accepted, don't accept them.
if (dieRow < 1 or dieRow > 8):
print("A die row cannot be " + str(dieRow) + ". Please enter valid coordinates.")
continue
if (dieColumn < 1 or dieColumn > 9):
print("A die column cannot be " + str(dieColumn) + ". Please enter valid coordinates.")
continue
# Otherwise, check the space to see if the human can move from there.
if (board.isDieOn(dieRow, dieColumn) and board.isDiePlayerType(dieRow, dieColumn, 'H')):
pass
else:
print("You cannot move from (" + str(dieRow) + "," + str(dieColumn) + "). Please enter different coordinates.")
continue
# The die coordinates are valid. Check if a move can be made to the space coordinates entered.
if (not self.canMoveToSpace(board, dieRow, dieColumn, spaceRow, spaceColumn, 'H')):
print("You cannot move the die to (" + str(spaceRow) + "," + str(spaceColumn) + "). Please enter different coordinates.")
continue
else:
isValidMove = True
# We can make a move. Get the name of the die before it is moved.
dieNameBefore = board.getDieName(dieRow, dieColumn)
# Get the directions of possible moves.
rowRolls = abs(spaceRow - dieRow)
columnRolls = abs(spaceColumn - dieColumn)
topNum = board.getDieTopNum(dieRow, dieColumn)
lateralMove = self.canMoveLaterally(board, dieRow, dieColumn, spaceColumn, topNum, 'H')
frontalMove = self.canMoveFrontally(board, dieRow, dieColumn, spaceRow, topNum, 'H')
secondFrontalMove = False
secondLateralMove = False
if lateralMove:
if ((not self.canMoveFrontally(board, dieRow, spaceColumn, spaceRow, rowRolls, 'H')) and rowRolls != 0): secondFrontalMove = False
else: secondFrontalMove = True
if frontalMove:
if ((not self.canMoveLaterally(board, spaceRow, dieColumn, spaceColumn, columnRolls, 'H')) and columnRolls != 0): secondLateralMove = False
else: secondLateralMove = True
# If you can move frontally or laterally first, ask which direction to move in.
# Player's answer to the direction:
directionAnswer = 0
if ((lateralMove and secondFrontalMove) and (frontalMove and secondLateralMove)):
while ((directionAnswer != 1) and (directionAnswer != 2)):
directionAnswer = input("Which direction would you like to go in first? Enter 1 for frontally or 2 for laterally: ")
directionAnswer = int(directionAnswer)
if (directionAnswer == 1):
# Move frontally first, then laterally.
self.makeMove(board, dieRow, dieColumn, spaceRow, "frontally")
self.makeMove(board, spaceRow, dieColumn, spaceColumn, "laterally")
# Get the new name of the die.
dieNameAfter = board.getDieName(spaceRow, spaceColumn)
# Print the move that was just made.
self.printMove(dieNameBefore, dieNameAfter, dieRow, dieColumn, spaceRow, spaceColumn, "frontally")
return
elif (directionAnswer == 2):
# Move laterally first, then frontally.
self.makeMove(board, dieRow, dieColumn, spaceColumn, "laterally")
self.makeMove(board, dieRow, spaceColumn, spaceRow, "frontally")
# Get the new name of the die.
dieNameAfter = board.getDieName(spaceRow, spaceColumn)
# Print the move that was just made.
self.printMove(dieNameBefore, dieNameAfter, dieRow, dieColumn, spaceRow, spaceColumn, "frontally")
return
else:
# Input not recognized.
print("Direction not recognized, please reenter where you want to go.")
# If you can only move frontally, only move frontally.
if (frontalMove and secondLateralMove):
self.makeMove(board, dieRow, dieColumn, spaceRow, "frontally")
self.makeMove(board, spaceRow, dieColumn, spaceColumn, "laterally")
# Get the new name of the die.
dieNameAfter = board.getDieName(spaceRow, spaceColumn)
# Print the move that was just made.
self.printMove(dieNameBefore, dieNameAfter, dieRow, dieColumn, spaceRow, spaceColumn, "frontally")
# If you can only move laterally, only move laterally.
if (lateralMove and secondFrontalMove):
self.makeMove(board, dieRow, dieColumn, spaceColumn, "laterally")
self.makeMove(board, dieRow, spaceColumn, spaceRow, "frontally")
# Get the new name of the die.
dieNameAfter = board.getDieName(spaceRow, spaceColumn)
# Print the move that was just made.
self.printMove(dieNameBefore, dieNameAfter, dieRow, dieColumn, spaceRow, spaceColumn, "frontally")
# *********************************************************************
# Function Name: printMove
# Purpose: To print the move that was just made by the human to the window
# Parameters:
# self, the Human the method is called on
# dieNameBefore, a string containing the name of the die before it was moved
# dieNameAfter, a string containing the name of the die after it was moved
# dieRow, an integer containing the row of the die before it was moved
# dieColumn, an integer containing the column of the die before it was moved
# spaceRow, an integer containing the row of the die after it was moved
# spaceColumn, an integer containing the column of the die after it was moved
# direction, a string that stores the direction that the die first moved in
# Return Value: none
# Local Variables:
# rowRolls and columnRolls, integers that store the amount of spaces that the die needed to move frontally and laterally
# Algorithm:
# 1) Calculate the rowRolls and columnRolls needed to move
# 2) Print the name of the die before it was moved and where it originally was
# 3) Use the direction passed into the function to determine how the die was first moved.
# 4) Check if there was a 90 degree turn that was made by looking at rowRolls and columnRolls. If greater than 0, print
# the number of spaces moved
# 5) Print the rest of the sentence: the name of the die after it was moved and where it is now located
# Assistance Received: none
# *********************************************************************
def printMove(self, dieNameBefore, dieNameAfter, dieRow, dieColumn, spaceRow, spaceColumn, direction):
# Integers to store spaces traversed in each row and column
rowRolls = abs(spaceRow-dieRow)
columnRolls = abs(spaceColumn-dieColumn)
# Print the name of the die before it was moved
print(str(dieNameBefore) + " was rolled from square (" + str(dieRow) + "," + str(dieColumn) + ") ", end="")
# Use the direction passed into the function to determined how the die was rolled.
if (direction == "frontally"):
print("frontally by " + str(rowRolls), end="")
# If columnRolls is not 0 then it was also moved laterally
if (columnRolls != 0):
print(" and laterally by " + str(columnRolls), end="")
else:
print("laterally by " + str(columnRolls), end="")
# If rowRolls is not 0 then it was also moved frontally
if (rowRolls != 0):
print(" and frontally by "+ str(rowRolls), end="")
# Display the rest of the sentence.
print(" to square (" + str(spaceRow) + "," + str(spaceColumn) + "). The die is now " + str(dieNameAfter) + ".")
# *********************************************************************
# Function Name: getHelp
# Purpose: To get help from the computer on a move recommenation
# Parameters:
# self, the Human the method is called on
# board, the Board that is being played on
# Return Value: none
# Local Variables:
# dieRow and dieColumn, integers that store the coordinates of the die to move
# spaceRow and spaceColumn, integers that store the coordinates of the space to move to
# Algorithm:
# 1) Call each score function in Player to help determine a move
# 2) First try to see if a key die can be captured. If so, recommend the move
# 3) Then try to see if a key space can be captured. If so, recommend the move
# 4) Then try to see if the human's key die needs to be blocked. If so, recommend the move
# 5) Then try to see if the human's key space needs to be blocked. If so, recommend the move
# 6) Then try to see if an enemy die can be captured. If so, recommend the move
# 7) Otherwise, just recommend a random move
# Assistance Received: none
# *********************************************************************
def getHelp(self, board):
# The computer will determine which of the human's dice that it could move. It needs to check for certain scenarios
# to make the appropriate move. This is actually quite similar to how Computer.play() works, but it does not actually
# make moves.
# The key die results in an immediate win, so find where the human's key die is. If it can be captured, do it.
scoreResult = self.captureKeyDieScore(board, 'H')
if (scoreResult[0] != 0):
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "keyDieCapture")
return
# Key space capture results in a win as well, so see if the human can travel to it.
scoreResult = self.captureKeySpaceScore(board, 'H')
if (scoreResult[0] != 0):
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "keySpaceCapture")
return
# Should also recommend defensive moves, like blocking the key die...
scoreResult = self.blockKeyDieScore(board, 'H')
if (scoreResult[0] != 0):
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "blockKeyDie")
return
# Or blocking the key space...
scoreResult = self.blockKeySpaceScore(board, 'H')
if (scoreResult[0] != 0):
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "blockKeySpace")
return
# No reason to play defensively at this point. Seek a die capture.
scoreResult = self.captureDieScore(board, 'H')
if (scoreResult[0] != 0):
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "dieCapture")
return
# Otherwise, random move.
else:
scoreResult = self.randomMove(board, 'H')
# Recommend a move.
self.recommendMove(board, scoreResult[0], scoreResult[1], scoreResult[2], scoreResult[3], "random")
# *********************************************************************
# Function Name: recommendMove
# Purpose: To print the move recommendation from the computer
# Parameters:
# self, the Human the method is called on
# board, the Board that is being played on
# dieRow, an integer that contains the row of the die to move
# dieColumn, an integer that contains the column of the die to move
# spaceRow, an integer that contains the row of the space to move to
# spaceColumn, an integer that contains the column of the space to move to
# strategy, a string that contains the strategy the computer is recommending
# Return Value: none
# Local Variables:
# spacesToMove, an integer that stores the top number of the die located at (dieRow,dieColumn)
# rowRolls and columnRolls, integers that store the amount of spaces needed to move frontally and laterally to the space
# frontalMove and lateralMove, boolean values that store whether or not a frontal or lateral move is initially possible
# secondFrontalMove and secondLateralMove, boolean values that store whether or not a frontal or lateral move is possible
# after a potential 90 degree turn
# Algorithm:
# 1) Store the result of getDieTopNum in spacesToMove
# 2) Calculate the rowRolls and columnRolls needed to move to (spaceRow,spaceColumn)
# 3) Start printing the recommendation using getDieName to get the name of the die to move.
# 4) Print the recommendation that goes with the strategy passed in the parameters.
# 5) Use canMoveFrontally and canMoveLaterally to determine how the die can be moved and print how the human can move it.
# 6) Print the reason for moving the die in that direction using the strategy passed in the parameters.
# Assistance Received: none
# *********************************************************************
def recommendMove(self, board, dieRow, dieColumn, spaceRow, spaceColumn, strategy):
# The spaces to move the die.
spacesToMove = board.getDieTopNum(dieRow, dieColumn)
# The amount of spaces needed to traverse the board.
rowRolls = abs(spaceRow - dieRow)
columnRolls = abs(spaceColumn - dieColumn)
# Boolean values for frontal and lateral moves
secondLateralMove = False
secondFrontalMove = False
# Random seed.
random.seed(None)
# Begin printing the recommenation.
print("The computer recommends moving " + str(board.getDieName(dieRow, dieColumn)) + " at (" + str(dieRow) + "," + str(dieColumn) + ") because ", end="")
# Print based on the strategy passed into the function.
if (strategy == "keyDieCapture"):
print("it is within distance of the computer's key die.")
if (strategy == "keySpaceCapture"):
print("it is within distance of the computer's key space.")
if (strategy == "blockKeyDie"):
print("the key die is in danger of being captured, and needs to be blocked.")
if (strategy == "blockKeySpace"):
print("the key space is in danger of being captured, and needs to be blocked.")
if (strategy == "dieCapture"):
print("it is within distance of a computer's die that can be captured.")
if (strategy == "random"):
print("the computer could not determine a decisive move to make, so it is making a move at random.")
# Print the rest of the recommendation.
print("It recommends rolling ", end="")
# Determine if the die can be moved frontally or laterally.
frontalMove = self.canMoveFrontally(board, dieRow, dieColumn, spaceRow, spacesToMove, 'H')
lateralMove = self.canMoveLaterally(board, dieRow, dieColumn, spaceColumn, spacesToMove, 'H')
# Determine if it can be moved in a 90 degree turn.
if (frontalMove):
if ((not self.canMoveLaterally(board, spaceRow, dieColumn, spaceColumn, columnRolls, 'H')) and columnRolls != 0):
secondLateralMove = False
else:
secondLateralMove = True
if (lateralMove):
if ((not self.canMoveFrontally(board, dieRow, spaceColumn, spaceRow, rowRolls, 'H')) and rowRolls != 0):
secondFrontalMove = False
else:
secondFrontalMove = True
# Check if both directions are possible. If so, the computer will randomly decide whether to move frontally or laterally.
if ((frontalMove and secondLateralMove) and (lateralMove and secondFrontalMove)):
# Generate 0 or 1 randomly. 0 = frontal move, 1 = lateral move.
decision = random.randrange(0,2)
if (decision == 0):
# Recommend frontal move first
lateralMove = False
else:
# Recommend lateral move first
frontalMove = False
# Continue the recommendation...
if (frontalMove and secondLateralMove):
print("frontally by " + str(rowRolls), end="")
# If you can also move laterally, describe that as well.
if (columnRolls != 0): print(" and laterally by " + str(columnRolls), end="")
if (lateralMove and secondFrontalMove):
print("laterally by " + str(columnRolls), end="")
# If you can also move frontally, describe that as well.
if (rowRolls != 0): print(" and frontally by " + str(rowRolls), end="")
# Finish it up.
print(" because ", end="")
# Look at the strategy passed into the function once more.
if strategy == "keyDieCapture":
print("it can capture the key die with this move.")
if strategy == "keySpaceCapture":
print("it can capture the key space with this move.")
if strategy == "blockKeyDie":
print("it can block the key die with this move.")
if strategy == "blockKeySpace":
print("it can block the key space with this move.")
if strategy == "dieCapture":
print("it can capture the die with this move.")
if strategy == "random":
print("the die is able to make this move without any problems.")
|
"""
黄金螺旋线
- 黄金比例的定义是把一条线段分割为两部分,较短部分与较长部分长度之比等于较长部分与整体长度之比,其比值的近似值是0.618。
- 而斐波那契相邻两位数刚好符合这种黄金比例,而且前一项与后一项的比值无限接近0.618。
- 黄金螺线的画法:
在以斐波那契数为边的正方形拼成的长方形中画一个90度的扇形,连起来的弧线就是斐波那契螺旋线。
它来源于斐波那契数列(FibonacciSequence),又称黄金螺旋分割。
"""
import numpy as np
import turtle
import random
def generate_fibonacci(n):
"""
fibonacci生成
"""
if n == 0:
return [1]
elif n == 1:
return [1]
fib_list = [1, 1]
for i in range(2, n):
fib_list.append(fib_list[i-2]+fib_list[i-1])
return fib_list
def draw(n):
# turtle设置
turtle.speed(10)
# 绘制图形时笔的宽度
turtle.pensize(5)
# 放大倍率,用于更好的显示图形
f0 = 50
turtle.color("black")
# 提笔
turtle.penup()
# 设置当前画笔位置为原点,朝向东
turtle.home()
# 落笔
turtle.pendown()
# 生成fibonacci数列
fib_list = generate_fibonacci(n)
# 遍历fibonacci数列,绘制黄金螺线
for i in range(len(fib_list)):
turtle.speed(1)
turtle.pendown()
# 画矩形
if i == 0:
fill_color = "black"
else:
fill_color = (random.random(), random.random(), random.random())
# 绘制图形的填充颜色
turtle.fillcolor(fill_color)
# 准备开始填充图形
turtle.begin_fill()
# 画笔向绘制方向的当前方向移动distance(integer or float)的pixels距离
turtle.forward(fib_list[i] * f0)
# 逆时针移动90度
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.left(90)
# 填充完成
turtle.end_fill()
# 画圆弧
# 随机产生填充颜色
fill_color = (random.random(), random.random(), random.random())
turtle.fillcolor(fill_color)
if i == 0:
# 画圆360度
turtle.forward(fib_list[i] * f0 / 2)
turtle.begin_fill()
turtle.circle(fib_list[i] * f0 / 2, 360)
turtle.end_fill()
turtle.forward(fib_list[i] * f0 / 2)
continue
else:
# 画圆弧90度
turtle.begin_fill()
turtle.circle(fib_list[i] * f0, 90)
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.end_fill()
# 移动到一下起点
turtle.speed(0)
turtle.penup()
turtle.left(90)
turtle.forward(fib_list[i] * f0)
turtle.left(90)
turtle.forward(fib_list[i] * f0)
# 启动事件循环,turtle的最后一条语句
turtle.done()
if __name__ == "__main__":
n = 2
draw(n)
|
"""
特殊矩阵的生成:单位阵、对角阵等等
"""
import numpy as np
# 单位阵
std_mat = np.eye(3)
print("=== standard mat ===")
print(std_mat)
# 偏移主对角线1个单位的伪单位矩阵
offset_std_mat = np.eye(3, k=1)
print("=== offset mat ===")
print(offset_std_mat)
# 全填充生成矩阵
full = np.full((2,3), 10)
print("=== full mat ===")
print(full)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.