text stringlengths 37 1.41M |
|---|
import numpy as np
data_list = [0,1,2,3,4,5,6,7,8,9]
mean = np.mean(data_list)
median = np.median(data_list)
std = np.std(data_list)
print("mean -> ",mean)
print("median -> ",median)
print("std -> ",std)
|
import fileinput
from typing import List, Dict
orbits: Dict[str, str] = {}
def listOrbits(obj: str) -> List[str]:
if obj in orbits:
chain: List[str] = listOrbits(orbits[obj])
chain.append(obj)
return chain
else:
return []
def main():
for line in fileinput.input():
tokens = line.rstrip().split(')')
orbits[tokens[1]] = tokens[0]
you: List[str] = listOrbits('YOU')
san: List[str] = listOrbits('SAN')
you.reverse()
for obj in you[1:]:
if obj in san:
transfers: int = you.index(obj) + len(san) - san.index(obj)
transfers -= 3 # Account for YOU, SAN, and double-counting the common root object
print(transfers)
break
if __name__ == '__main__':
main()
|
print("Hello World")
message = "Hello World"
print(message)
def printme( str ):
"This prints a passed string into this function"
print (str)
return
printme("Hello")
def main():
print("I have defined main here")
return
main()
|
__author__ = '100068'
# coding:utf-8
# !/usr/bin/env python
#乘法运算符重载
class mulList(list):
def __mul__(self, b):
result=[]
a=self[:]
c=b[:]
if len(a)>=len(c):
for i in range(len(c)):
result.append(a[i]*b[i])
else:
for i in range(len(a)):
result.append(a[i]*b[i])
return result
print mulList([1,2,3]) * mulList([3,4]) |
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def print_level_order(root):
for h in range(1, height(root) + 1):
print_given_level(root, h)
print()
def print_given_level(root, level):
if root is None: return
if level == 1:
print(root.data, end=" ")
else:
print_given_level(root.left, level-1)
print_given_level(root.right, level-1)
def height(root):
if root == None:
return 0
else:
lheight = height(root.left)
rheight = height(root.right)
if lheight > rheight:
return lheight + 1
else:
return rheight + 1
def main():
root = Node(1)
root.left = Node(5)
root.left.left = Node(4)
root.left.right = Node(7)
root.left.left = Node(6)
root.right = Node(3)
root.right.left = Node(8)
root.right.left.left = Node(2)
root.right.left.left.right = Node(7)
root.right.left.left.left = Node(3)
h = height(root)
print("height = %s" % h)
print_level_order(root)
if __name__ == '__main__': main()
|
animal = ['dog', 'cat', 'parrot', 'goldfish']
for x in animal:
print('%s %d' % (x, len(x)))
|
num = int(input())
for i in range(1, num+1):
print (i, i * i)
|
"""Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have a next node it is point to."""
def insert_after(self, value):
current_next = self.next
self.next = ListNode(value, self, current_next)
if current_next:
current_next.prev = self.next
"""Wrap the given value in a ListNode and insert it
before this node. Note that this node could already
have a previous node it is point to."""
def insert_before(self, value):
current_prev = self.prev
self.prev = ListNode(value, current_prev, self)
if current_prev:
current_prev.next = self.prev
"""Rearranges this ListNode's previous and next pointers
accordingly, effectively deleting this ListNode."""
def delete(self):
if self.prev:
self.prev.next = self.next
if self.next:
self.next.prev = self.prev
"""Our doubly-linked list class. It holds references to
the list's head and tail nodes."""
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node
self.tail = node
self.length = 1 if node is not None else 0
def __len__(self):
return self.length
"""Wraps the given value in a ListNode and inserts it
as the new head of the list. Don't forget to handle
the old head node's previous pointer accordingly."""
def add_to_head(self, value):
self.length += 1
new_node = ListNode(value)
if not self.head and not self.tail:
self.head = self.tail = new_node
else:
self.head.insert_before(value)
self.head = self.head.prev
"""Removes the List's current head node, making the
current head's next node the new head of the List.
Returns the value of the removed Node."""
def remove_from_head(self):
value = self.head.value
self.delete(self.head)
return value
"""Wraps the given value in a ListNode and inserts it
as the new tail of the list. Don't forget to handle
the old tail node's next pointer accordingly."""
def add_to_tail(self, value):
self.length += 1
new_node = ListNode(value)
if not self.head and not self.tail:
self.head = self.tail = new_node
else:
self.tail.insert_after(value)
self.tail = self.tail.next
"""Removes the List's current tail node, making the
current tail's previous node the new tail of the List.
Returns the value of the removed Node."""
def remove_from_tail(self):
value = self.tail.value
self.delete(self.tail)
return value
"""Removes the input node from its current spot in the
List and inserts it as the new head node of the List."""
def move_to_front(self, node):
self.delete(node)
self.add_to_head(node.value)
"""Removes the input node from its current spot in the
List and inserts it as the new tail node of the List."""
def move_to_end(self, node):
self.delete(node)
self.add_to_tail(node.value)
"""Removes a node from the list and handles cases where
the node was the head or the tail"""
def delete(self, node):
# If LL is empty
if not self.head and not self.tail:
print(f'Error: {node} does not exist')
return False
# If there is only one node
elif self.head == self.tail:
self.head = None
self.tail = None
node.delete()
# If node is the head
elif node == self.head:
self.head = self.head.next
node.delete()
# If node is the tail
elif node == self.tail:
self.tail = self.tail.prev
node.delete()
# Node is in a middle index
else:
node.delete()
self.length -= 1
"""Returns the highest value currently in the list"""
def get_max(self):
# step 1 check for head
if not self.head:
return None
# step 2 make variables
# variable for the value of self.head
var_max = self.head.value
# variable for the current head
var_head = self.head
# step 3 run a loop through all nodes using the head.next feature
# while self.head/var_head is true we just loop through all the nodes
while var_head:
print('var_max', var_max)
print('var_head', var_head.value)
# step 5 check if value of current head is greater than variable.
# when we find a head with a greater value than the original var_max = self.head. We change that variable to the new higher valued node.
if var_head.value > var_max:
# then we update the variable with the new greater value
var_max = var_head.value
# step 4 increment through the head.next
# this code pushes us to the next head while the loop is true
var_head = var_head.next
# step 6 return the node with greatest value
return var_max
|
#Creating two functions to check whether the received values meets the required criteria
def check1():
while True:
try:
n=input("Enter an integer: ")
if int(n)<0 or int(n)>255:
print("Please enter value between 0 and 255.")
else:
break
except:
print("Please enter a whole integer value.")
pass
return int(n)
def check2():
#Different functions were created just to display different queries to the user
while True:
try:
n=input("Enter another integer: ")
if int(n)<0 or int(n)>255:
print("Please enter value between 0 and 255.")
else:
break
except:
print("Please enter a whole integer value.")
pass
return int(n)
|
#import random
from random import randint
player_wins = 0
computer_wins = 0
winning_score = 2
while player_wins < winning_score and computer_wins < winning_score:
print("Player score:{} Computer score: {}".format(player_wins,computer_wins))
print("Rock...")
print("Paper...")
print("Scissors...")
player = input("Player,make your move:").lower()
if player == "quit" or player == "q":
break
#rand_num = random.randint(0,2)
rand_num = randint(0,2)
if rand_num ==0:
computer="rock"
elif rand_num ==1:
computer = "paper"
else:
computer ="scissors"
print("Computer plays {}".format(computer))
if player == computer:
print("It's a tie!")
elif player =="rock":
if computer =="scissors":
print("player wins")
player_wins +=1
elif computer =="paper":
print("computer wins!")
computer_wins +=1
elif player =="paper":
if computer =="rock":
print("player wins!")
player_wins +=1
elif computer=="scissors":
print("computer wins!")
computer_wins +=1
elif player =="scissors":
if computer =="rock":
print("computer wins!")
computer_wins +=1
elif computer =="paper":
print("player wins!")
player_wins +=1
else:
print("Please enter valid move")
if player_wins > computer_wins:
print("CONGRATS, YOU WON..!")
elif player_wins == computer_wins:
print("TIE")
else:
print("OH NO :(THE COMPUTER WON..")
#print("FINAL SCORES...Player score:{} Computer score: {}".format(player_wins,computer_wins)) |
from typing import Sequence
class Helper():
def merge_sort(array: Sequence[str]):
"""merge sort implementation
Base Case: return if the array len is 1 since we can assume this is a sorted array
Recursion: breaks the array down to one
Args:
Array: array that needs sorting .
Returns:
Sorted array
"""
if len(array) == 1:
return array
mid = len(array)//2
L = Helper.merge_sort(array[:mid])
R = Helper.merge_sort(array[mid:])
return Helper.merge(L,R)
def merge(left: Sequence[str],right: Sequence[str]):
"""merge implementation
loop through each array
if the position in one array is smaller than the over
append to the merge array
Args:
Array: array that needs merging
Returns:
Left and right merged
"""
output = []
i = j = 0 #Defines the pointer
while i < len(left) and j < len(right):
if left[i] < right[j]:
output.append(left[i])
i+=1
else:
output.append(right[j])
j+=1
output.extend(left[i:])
output.extend(right[j:])
return output
def searchOutput(foundVideo,search_term):
"""Search videos output
If any videos exist in foundVideo
print the video in the format of x) Title (video_id) [#tags]
return the index of the video they want to play
Args:
Array: foundVideo is the array of video objecst found
String: search_term is the string of the term that was used to search
Returns:
Index of video to play
"""
foundVideo = Helper.videoClean(foundVideo)
if len(foundVideo) == 0:
print("No search results for {}".format(search_term))
return ""
else:
print("Here are the results for {}:".format(search_term))
for x in range(len(foundVideo)):
print(" {}) {}".format(x+1,foundVideo[x]))
print("Would you like to play any of the above? If yes, specify the number of the video.\nIf your answer is not a valid number, we will assume it's a no.")
index = input()
return index
def indexValidaton(index,foundVideo):
"""Validates the index input
Checks if the index is a numeric value and that the index is within range of the array
Args:
Array: foundVideo is the array of video objecst found
Int: index is the index of the array
Returns:
Index of video to play
"""
if index.isnumeric() and int(index)-1 <= len(foundVideo) and int(index) > 0:
return True
def videoClean(videos):
if len(videos) == 0:
return None
videoClean = []
#Remove all videos with flag
for video in videos:
if video.flag == None:
videoClean.append(video)
return videoClean |
# Sa se scrie o functie care primeste un numar nedefinit de parametrii
# si sa se calculeze suma parametrilor care reprezinta numere intregi sau reale
print('-> This is the first exercise: ')
def test_is_number(param):
if not isinstance(param, bool): #am inceput prin a exclude variabilele de tip bool (pentru ca am obsetrvat ca sunt traduse cu 0 si 1)
if isinstance(param, int) or isinstance(param, float):
return True
def my_function(*args, **kwargs):
my_sum = 0
if len(args) == 0:
return my_sum
else:# extra: am continuat functia ca sa fie pretabila pt numere din interiorul unor eventuale liste sau tupluri
for param in args:
if test_is_number(param):
my_sum += param
for param in args: # iteram args pentru a identifica eventuale liste sau tuple
if isinstance(param, list) or isinstance(param, tuple):
for list_item in param:
if test_is_number(list_item):
my_sum += list_item
for key, value in kwargs.items(): # iteram kwargs pentru a evalua valorile cheilor
if test_is_number(value):
my_sum += value
return my_sum
print(my_function(1.5, 5, (1.5, 2, 'a', 3), -3, 'abc', [12, 56, 'cad'],abc=True, a=1, c=10.5))
print(my_function())
print(my_function(2, 4, 'abc', param_1=2, param_2=-10))
# Sa se scrie o functie recursiva care primeste ca parametru un numar intreg si returneaza:
# suma tuturor numerelor de la [0, n]
# suma numerelor pare de la [0, n]
# suma numerelor impare de la [0, n]
print('-> This is the second exercise: ')
sum_odd = 0
sum_even = 0
sum_all = 0
def recursive_sum(n):
global sum_odd
global sum_even
global sum_all
if n > 0:
sum_all = sum_all + n
if n % 2 == 1:
sum_odd = sum_odd + n
elif n % 2 == 0:
sum_even = sum_even + n
recursive_sum(n - 1)
return sum_odd, sum_even, sum_all
v_odd, v_even, v_all = recursive_sum(n=5) ## I unpacked this tuple, to access each variable of function return
print(f'''sum of Odd Elements is: {v_odd},
Sum of Even Elements is: {v_even},
Sum of All Elements is: {v_all}''')
# Sa se scrie o functie care citste de la tastatura si returneaza valoarea daca aceasta este un numar intreg,
# altfel returneaza valoarea 0
print('-> This is the third exercise:')
def ask_number():
user_input = input('Give me a number: ')
try:
user_input = int(user_input)
print('your number', user_input, 'is what we have asked!')
return True
except ValueError as e:
print('Please try again, as the input is not a number (integer) : ', e)
return False
finally:
print('Thank you!')
is_number = False
while not is_number:
is_number = ask_number() |
# Dak Prescott
# Aka: air resistance in two dimensions
import numpy as np
import matplotlib.pyplot as plt
from numpy.core.fromnumeric import argmax
# Parameters to start off
g = 9.81 # m/s**2
v0 = 30 # m/s, initial velocity
theta = 30 # degrees, initial angle
vt = 45 # m/s, terminal velocity of a football
# The variables we'll be using
t = 0 # seconds
x = 0 # meters
y = 1.8 # meters
dt = 0.01
# Create arrays to store data that is calculated
# They start empty, then we append values as they come
t_calculated = np.zeros(0)
x_calculated = np.zeros(0)
y_calculated = np.zeros(0)
angle = np.zeros(0)
max_range = np.zeros(0)
# Define the functions we'll need
def acc_x(v_x: float, v: float) -> float:
"""Acceleration function for x direction."""
global vt
return -g*v_x*v/(vt**2)
def acc_y(v_y: float, v: float) -> float:
"""Acceleration function for y direction."""
global vt
return -g*(1 + v_y*v/(vt**2))
# Methods of Heun's method
def heun_vel_x(v_x: float, v: float) -> float:
"""Function for Heun's method for velocity in x direction."""
global dt
v_x_end = v_x + acc_x(v_x, v)*dt
v_x = v_x + (acc_x(v_x, v) + acc_x(v_x_end, v))*dt/2
return v_x
def heun_vel_y(v_y: float, v: float) -> float:
"""Function for Heun's method for velocity in y direction."""
global dt
v_y_end = v_y + acc_y(v_y, v)*dt
v_y = v_y + (acc_y(v_y, v) + acc_y(v_y_end, v))*dt/2
return v_y
def heun_position(pos: float, vel: float) -> float:
"""Function for the position of the ball, more general function."""
return pos + vel*dt
# Starting velocity components, with radian conversion
v_x = v0 * np.cos(theta * np.pi/180)
v_y = v0 * np.sin(theta * np.pi/180)
v = v0
# Now let's calculate the velocity and the position as it moves
for theta in np.arange(20, 70, 0.5): # Loop over throwing angles in degrees
x = 0
y = 1.8
t = 0
# Starting velocity components, with radian conversion for the angle
v_x = v0 * np.cos(theta * np.pi/180)
v_y = v0 * np.sin(theta * np.pi/180)
v = v0
while y >= 0:
# Update the velocities and positions, in x and y
v_x = heun_vel_x(v_x, v)
x = heun_position(x, v_x)
v_y = heun_vel_y(v_y, v)
y = heun_position(y, v_y)
# Update v
v = np.sqrt(v_x*v_x + v_y*v_y)
# Update the arrays
x_calculated = np.append(x_calculated, x)
y_calculated = np.append(y_calculated, y)
# Update the time and time's array
t = t + dt
t_calculated = np.append(t_calculated, t)
# Add the range we achieved
angle = np.append(angle, theta)
max_range = np.append(max_range, x_calculated[-1])
# Plot the results and figure some things out
plt.xlabel('Angle of throw (degrees)')
plt.ylabel('Horizontal distance of throw (m)')
plt.plot(angle, max_range, 'r', label='')
print(f"Range = {x_calculated[np.argmax(x_calculated)]:0.4f} meters")
# These are two useful lines, argmax gets you the index of the max value in the array
print(f"Max height = {y_calculated[argmax(y_calculated)]:4.2f} meters")
print(f"Time at max height = {t_calculated[argmax(y_calculated)]:4.2f} seconds")
print(f"Time of flight = {t_calculated[-1]:4.2f} seconds")
plt.show()
|
'''
Lyapunov exponent example from class
Measures if a system is chaotic or not.
'''
import numpy as np
import matplotlib.pyplot as plt
# Initial values
dx = 0
sumd = 0
n = 10000
r = np.linspace(0.01, 1.0, 1000)
lamb = np.zeros(r.size)
'''
Lambda > 0: chaos
Lambda < 0: other type of behavior
'''
# Iteratic the logisistic equation and sum terms to get lambda
for index,i in enumerate(r):
x = 0.25
for index2,j in enumerate(np.arange(0, n)):
dx = 4*i*(1 - 2*x)
if j > 5000:
sumd += np.log(abs(dx))
x = 4*i*x*(1 - x)
# Now actually calculate lambda and put it into the array
lamb[index] = sumd/n/np.log(2)
sumd = 0
plt.plot(r, lamb, 'r-')
plt.xlabel("r values")
plt.ylabel("Lambda values")
plt.show()
|
def areYouPlayingBanjo(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not play') + " banjo";
def count_sheeps(sheep):
return sheep.count(True)
array1 = [True, True, True, False,
True, True, True, True ,
True, False, True, False,
True, False, False, True ,
True, True, True, True ,
False, False, True, True ];
print(count_sheeps(array1)) |
#Escribir un programa que pida al usuario una palabra
#y la muestre por pantalla 10 veces.
word=str(input("Ingrese palabra a repetir: "))
for i in range(10):
print(word) |
import numpy as np
import time
from typing import Optional, Tuple, Iterable
# Analysis functions for strategy
class Analysis:
def get_future_ball_array(self):
"""Samples incrementally to return array of future predicted ball positions"""
ball_pos = self._gs.get_ball_position()
# this definition of new_ball_pos guarentees that they are not the same intitally
new_ball_pos = ball_pos - np.array([1, 1])
now = time.time()
t = 0
delta_t = .1
future_ball_array = []
while ((ball_pos != new_ball_pos).any() or t == 0) and self._gs.is_in_play(new_ball_pos):
# here we make the previously generated point the reference
ball_pos = new_ball_pos
new_ball_pos = self._gs.predict_ball_pos(t)
future_ball_array.append((t + now, new_ball_pos))
t += delta_t
return future_ball_array
def intercept_range(self, robot_id: int
) -> Tuple[Tuple[float, float], Tuple[float, float]]:
"""find the range for which a robot can reach the ball in its trajectory
@return position1, position2:
returns the positions between which robots can intercept the ball.
returns None if interception is not possible
"""
# print(f"start time: {datetime.now()}")
# variable at the time when the ball first gets within range.
robot_pos = self._gs.get_robot_position(self._team, robot_id)
delta_t = .1
time = 0
out_of_range = True
while(out_of_range):
interception_pos = self._gs.predict_ball_pos(time)
separation_distance = np.linalg.norm(robot_pos[:2] - interception_pos)
max_speed = self._gs.robot_max_speed(self._team, robot_id)
if separation_distance <= time * max_speed:
first_intercept_point = interception_pos
if not self._gs.is_in_play(first_intercept_point):
return None
out_of_range = False
else:
time += delta_t
while(not out_of_range):
# Starting at the time when the ball first got within range.
interception_pos = self._gs.predict_ball_pos(time)
separation_distance = np.linalg.norm(robot_pos[:2] - interception_pos)
max_speed = self._gs.robot_max_speed(self._team, robot_id)
last_intercept_point = self._gs.predict_ball_pos(time - delta_t)
# Use opposite criteria to find the end of the window
cant_reach = (separation_distance > time * max_speed)
stopped_moving = (last_intercept_point == interception_pos).all()
in_play = self._gs.is_in_play(interception_pos)
if cant_reach or stopped_moving or not in_play:
# we need to subtract delta_t because we found the last
#print(f"end time: {datetime.now()}")
return first_intercept_point, last_intercept_point
else:
time += delta_t
def safest_intercept_point(self, robot_id: int) -> Tuple[float, float]:
"""determine the point in the ball's trajectory that the robot can reach
soonest relative to the ball (even if it's too late)"""
future_ball_array = self.get_future_ball_array()
robot_pos = self._gs.get_robot_position(self._team, robot_id)
max_speed = self._gs.robot_max_speed(self._team, robot_id)
def buffer_time(data):
timestamp, ball_pos = data
ball_travel_time = timestamp - time.time()
distance_robot_needs_to_travel = np.linalg.norm(ball_pos - robot_pos[:2])
robot_travel_time = distance_robot_needs_to_travel / max_speed
return ball_travel_time - robot_travel_time
if len(future_ball_array) > 0:
buffer_time, safest_pos = max(future_ball_array, key=buffer_time)
else:
# if the ball is not visible, return current position
safest_pos = robot_pos
return safest_pos
def best_kick_pos(self, from_pos: Tuple[float, float], to_pos: Tuple[float, float]) -> Tuple[float, float, float]:
"""determine the best robot position to kick in desired direction"""
dx, dy = to_pos[:2] - from_pos[:2]
w = np.arctan2(dy, dx)
return self._gs.dribbler_to_robot_pos(from_pos, w)
# TODO: generalize for building walls and stuff
# TODO: account for attacker orientation?
def block_goal_center_pos(self, max_distance_from_goal: float, ball_pos=None, team=None):
"""Return position between the ball and the goal, at a particular distance from the goal"""
if team is None:
team = self._team
if ball_pos is None:
ball_pos = self._gs.get_ball_position()
if not self._gs.is_in_play(ball_pos):
return np.array([])
goal_top, goal_bottom = self._gs.get_defense_goal(team)
goal_center = (goal_top + goal_bottom) / 2
ball_distance = np.linalg.norm(ball_pos - goal_center)
distance_from_goal = min(max_distance_from_goal, ball_distance - self._gs.ROBOT_RADIUS)
# for now, look at vector from goal center to ball
goal_to_ball = ball_pos - goal_center
if not goal_to_ball.any():
# should never happen, but good to prevent crash, and for debugging
print('ball is exactly on goal center w0t')
return np.array([*goal_center, 0])
angle_to_ball = np.arctan2(goal_to_ball[1], goal_to_ball[0])
norm_to_ball = goal_to_ball / np.linalg.norm(goal_to_ball)
x, y = goal_center + norm_to_ball * distance_from_goal
block_pos = np.array([x, y, angle_to_ball])
# TODO: THIS IS A HACK TO MAKE IT STAY WITHIN CAMERA RANGE
# if block_pos[0] > self._gs.FIELD_MAX_X - self._gs.ROBOT_RADIUS * 3 or block_pos[0] < self._gs.FIELD_MIN_X + self._gs.ROBOT_RADIUS * 3:
# return np.array([])
return block_pos
def is_path_blocked(self, s_pos, g_pos, robot_id, buffer_dist=0):
"incrementally check a linear path for obstacles"
s_pos = np.array(s_pos)[:2]
g_pos = np.array(g_pos)[:2]
if (g_pos == s_pos).all():
return False
# Check endpoint first to avoid worrying about step size in the loop
if not self._gs.is_position_open(g_pos, self._team, robot_id):
return True
path = g_pos - s_pos
norm_path = path / np.linalg.norm(path)
STEP_SIZE = self._gs.ROBOT_RADIUS
# step along the path and check if any points are blocked
steps = int(np.floor(np.linalg.norm(path) / STEP_SIZE))
for i in range(1, steps + 1):
intermediate_pos = s_pos + norm_path * STEP_SIZE * i
np.append(intermediate_pos, 0)
if not self._gs.is_position_open(intermediate_pos, self._team, robot_id, buffer_dist):
return True
return False
# generate RRT waypoints
def RRT_path_find(self, start_pos, goal_pos, robot_id, lim=1000):
goal_pos = np.array(goal_pos)
start_pos = np.array(start_pos)
graph = {tuple(start_pos): []}
prev = {tuple(start_pos): None}
cnt = 0
success = False
for _ in range(lim):
# use gamestate.random_position()
new_pos = np.array(
[np.random.randint(self._gs.FIELD_MIN_X, self._gs.FIELD_MAX_X),
np.random.randint(self._gs.FIELD_MIN_Y, self._gs.FIELD_MAX_Y),
0.0])
if np.random.random() < 0.05:
new_pos = goal_pos
if not self._gs.is_position_open(new_pos, self._team, robot_id, buffer_dist=100) \
or tuple(new_pos) in graph:
continue
nearest_pos = self.get_nearest_pos(graph, tuple(new_pos))
extend_pos = self.extend(nearest_pos, new_pos, robot_id=robot_id)
if extend_pos is None:
continue
graph[tuple(extend_pos)] = [nearest_pos]
graph[nearest_pos].append(tuple(extend_pos))
prev[tuple(extend_pos)] = nearest_pos
if np.linalg.norm(extend_pos[:2] - goal_pos[:2]) < self._gs.ROBOT_RADIUS:
success = True
break
cnt += 1
if not success:
return success
pos = self.get_nearest_pos(graph, goal_pos) # get nearest position to goal in graph
path = []
while not (pos[:2] == start_pos[:2]).all():
path.append(pos)
pos = prev[pos]
path.reverse()
# Smooth path to reduce zig zagging
i = 0
while i < len(path) - 2:
if not self.is_path_blocked(path[i], path[i+2], robot_id):
del path[i+1]
continue
i += 1
# Cut out the "dead-weight" waypoints
for i, pos in enumerate(path):
if not self.is_path_blocked(pos, goal_pos, robot_id):
path = path[:i+1]
break
self.set_waypoints(robot_id, path + [goal_pos])
return success
# RRT helper
def get_nearest_pos(self, graph, new_pos):
rtn = None
min_dist = float('inf')
for pos in graph:
dist = np.sqrt((new_pos[0] - pos[0]) ** 2 + (new_pos[1] - pos[1]) ** 2)
if dist < min_dist:
min_dist = dist
rtn = pos
return rtn
# RRT helper
def extend(self, s_pos, g_pos, robot_id=None):
s_pos = np.array(s_pos)[:2]
g_pos = np.array(g_pos)[:2]
if (g_pos == s_pos).all():
return False
path = g_pos - s_pos
norm_path = path / np.linalg.norm(path)
STEP_SIZE = self._gs.ROBOT_RADIUS
# step along the path and check if any points are blocked
poses = [None]
steps = int(np.floor(np.linalg.norm(path) / STEP_SIZE))
for i in range(1, steps + 1):
intermediate_pos = s_pos + norm_path * STEP_SIZE * i
np.append(intermediate_pos, 0)
if not self._gs.is_position_open(intermediate_pos, self._team, robot_id, buffer_dist=100):
break
if np.linalg.norm(intermediate_pos - s_pos) > 4 * STEP_SIZE:
break
poses.append(intermediate_pos)
return poses[-1]
|
import time
import euler
start_time = time.time()
# The number, 197, is called a circular prime because all rotations of
# the digits: 197, 971, and 719, are themselves prime.
#
# There are thirteen such primes below 100:
# 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#
# How many circular primes are there below one million?
def cycle_numbers(num):
'''Function to cycle a number into all its possible cycle combinations'''
cycle_list = []
num_list = []
cycle_list.append(num)
# Turn the number into a string so we can shuffle it
for i in str(num):
num_list.append(int(i))
for j in range(len(num_list) - 1):
pop = num_list.pop(len(num_list) - 1)
num_list.insert(0, pop)
s = ""
st = ""
for i in num_list:
s = str(i)
st += s
cycle_list.append(int(st))
return cycle_list
def all_one_three_seven_nine(num):
'''Apart from 2 and 5, all prime numbers have to end in 1, 3, 7 or 9 '''
num_list = []
check_list = [1, 3, 7, 9]
in_check_list = True
for i in str(num):
num_list.append(int(i))
for i in num_list:
if i not in check_list:
in_check_list = False
break
return in_check_list
def all_prime(cycle_list):
'''Function to check if all the numbers in a
given list are prime numbers'''
all_primes = True
for i in cycle_list:
if i not in primes:
all_primes = False
break
return all_primes
# create the prime list from the Sieve
primes = euler.read_file(type='primes')
circular_numbers = [2, 5]
for i in primes:
if i < 1000001:
if all_one_three_seven_nine(i):
a = cycle_numbers(i)
if all_prime(a):
circular_numbers.append(i)
print('Problem 35 =', len(circular_numbers))
print("Program took %s seconds to run." % (time.time() - start_time))
|
import time
start_time = time.time()
# In the United Kingdom the currency is made up of pound (£)
# and pence (p). There are eight coins in general circulation:
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).
# It is possible to make £2 in the following way:
# 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
# How many different ways can £2 be made using any number of coins?
def ways(target):
"""
Returns the number of ways to make the target amount of money using any number of coins.
Args:
target: The target amount of money in pence.
Returns:
The number of ways to make the target amount of money.
"""
# Initialize the table of ways to make each amount of money.
ways = [0] * (target + 1)
ways[0] = 1
# Iterate over the coins, and for each coin, add the number of ways to make the target amount of money
# using the coin to the ways to make the target amount of money without the coin.
for coin in [1, 2, 5, 10, 20, 50, 100, 200]:
for i in range(coin, target + 1):
ways[i] += ways[i - coin]
return ways[target]
print('Problem 31 =', ways(200)) #73682
print("Program took %s seconds to run." % (time.time() - start_time))
|
import time
from math import factorial
start_time = time.time()
# n! means n × (n − 1) × ... × 3 × 2 × 1
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
# Find the sum of the digits in the number 100!
total = 0
for x in str(factorial(100)):
total += int(x)
print('Problem 19 =', total) # 648
print("Program took %s seconds to run." % (time.time() - start_time))
|
#!/usr/bin/env python3
""" Complex types - list of floats """
import typing
def sum_list(input_list: typing.List[float]) -> float:
""" function sum_list which takes a list input_list
of floats as argument and returns their sum as a float """
return sum(input_list)
|
# 4. Исправьте класс Word, чтобы указанный ниже код не вызывал ошибки.
class Word:
def __init__(self, text):
self.text = text
class Sentence:
def __init__(self, content):
self.content = content
def show(self, words):
sentence = ''
count = 0
for word_number in self.content:
try:
if (count == 0):
sentence += words[word_number].text.capitalize() + ' '
elif count != len(self.content) - 1:
sentence += words[word_number].text + ' '
else:
sentence += words[word_number].text + '.'
count += 1
except IndexError:
print('Некорректное значение переменной content = ', self.content[count], '(метод show)')
print('В переданном вами списке всего', len(words), 'слов', '- максимальный индекс равен',
len(words) - 1)
print(sentence)
def show_parts(self, words):
parts = ''
count = 0
for word_number in self.content:
try:
parts += words[word_number].part() + ' '
count += 1
except IndexError:
print('Некорректное значение переменной content = ', self.content[count], '(метод show_parts)')
print('В переданном вами списке всего', len(words), 'слов', '- максимальный индекс равен',
len(words) - 1)
print(list(set(parts.split())))
# 1. Создайте новые классы Noun (существительное) и Verb (глагол).
# 2. Настройте наследование новых классов от класса Word.
# 3. Добавьте в новые классы свойство grammar («Грамматические характеристики»).
# Для класса Noun укажите значение по умолчанию «сущ» (сокращение от существительное),
# а для Verb — «гл» (сокращение от глагол). Вспомните про инкапсуляцию и сделайте свойство grammar защищённым.
class Noun(Word):
__grammar = 'сущ'
# 6. Допишите в классы Noun и Verb метод part. Данный метод должен возвращать строку с полным названием части речи.
def part(self):
return 'существительное'
class Verb(Word):
__grammar = 'гл'
# 6. Допишите в классы Noun и Verb метод part. Данный метод должен возвращать строку с полным названием части речи.
def part(self):
return 'глагол'
# пример создания экземпляра нового класса
word_example = Noun('компьютер')
# пример доступа к приватной переменной
try:
print(word_example.__grammar)
except AttributeError:
print('Попытка доступа к приватной переменной!')
words = []
words.append(Noun("собака"))
words.append(Verb("ела"))
words.append(Noun("колбасу"))
words.append(Noun("кот"))
words.append(Verb("ел"))
words.append(Noun("мясо"))
words.append(Noun("кота"))
print('Примеры предложений:')
sentence = Sentence([0, 1, 2])
# 5. Протестируйте работу старого метода show класса Sentence. Если предложения не формируются, исправьте ошибки.
sentence.show(words)
# 7. Протестируйте работу метода show_part класса Sentence. Исправьте ошибки, чтобы метод работал.
sentence.show_parts(words)
sentence = Sentence([3, 4, 5])
sentence.show(words)
sentence.show_parts(words)
sentence = Sentence([0, 1, 6])
sentence.show(words)
sentence.show_parts(words)
|
#!/usr/bin/env python3
# HW06_ch09_ex02.py
# (1)
# Write a function called has_no_e that returns True if the given word doesn't
# have the letter "e" in it.
# - write has_no_e
# (2)
# Modify your program from 9.1 to print only the words that have no "e" and
# compute the percentage of the words in the list have no "e."
# - print each approved word on new line, followed at the end by the %
# - name your function print_no_e
##############################################################################
# Imports
# Body
def has_no_e(word):
#return true is e is in the word
if 'e' in word:
return True
else:
return False
def print_no_e(all_words):
count_words_no_e = 0 # counter for words with 'e'
total = len(all_words) #total number of words
for word in all_words:
if 'e' in word:
pass
else: # is word contains no 'e' print it
count_words_no_e += 1
print(word.strip())
percent = count_words_no_e * 100 / total
print("Percentage of word with no e: " + str(round(percent,2)) + "%")
def read_file(filename):
file_to_read = open(filename, 'r')#open the file for reading
#store the file's contents
file_contents = file_to_read.readlines()
#close the file
file_to_read.close()
return file_contents
def pass_words_to_func(all_words):
#iterate through the list and call the function to check for e
for word in all_words:
print(word.strip(), " contains 'e': ", has_no_e(word))
print_no_e(all_words)
def func_calls(filename):
#read the contents of the file and pass it to the calling function
pass_words_to_func(read_file(filename))
##############################################################################
def main():
func_calls("words.txt")
if __name__ == '__main__':
main()
|
string1 = "taco"
i = ['a', 'b', 'c',]
def missing_char(i):
strin_missing = list()
for i in string1:
string1.replace(i, '')
return "".replace(i, '')
missing_char(i, '') |
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
def powers_of_two(nums):
for numbers in nums:
print(2**numbers)
powers_of_two(nums) |
class parent():
'This gives the declaration of the parent class'
def __init__(self,var1,var2):
self.var1=var1
self.var2=var2
def ope(self):
print "parent class sum : ",self.var1+self.var2
class child(parent):
'This gives the declaration of the parent class'
def __init__(self,var1,var2):
self.var1=var1
self.var2=var2
def ope(self):
print "child class sub : ",self.var1-self.var2
obj_p=parent(100,200)
obj_c=child(300,500)
obj_p.ope()
obj_c.ope()
|
dict={'key':'value','hyd':'sec'}
#not converting to string representation
print "dictionary",dict
dict['abc']='xyz'
#converting to string representation
print "dictionary",str(dict)
|
print "enter var1"
var1=input()
print "enter var2"
var2=input()
print "enter var3"
var3=input()
if(var1>var2 and var1>var3):
print "Max is ", var1
elif(var2>var1 and var2>var3):
print "Maxi is ", var2
else:
print "Max is", var3
|
dict={'key':'value','hyd':'sec'}
dict['abc']='xyz'
print "dictionary length : ",len(dict)
|
list=[6,6,4,3,2,2,5,7,8]
var=0
while(var<len(list)):
print "element",list[var]
var=var+1
|
class a():
'This gives the declaration of the parent class'
def disp(self):
print " class 'a' calling"
class b():
'This gives the declaration of the child class'
def disc(self):
print "class 'b' calling"
class c():
'this is class c'
def calling(self):
obj_p=a()
obj_c=b()
obj_p.disp()
obj_c.disc()
obj=c()
obj.calling()
|
tuple1=(2,5,6,7,1,9,0)
tuple2=(7,5,7,9,3,1,3,5,6,2,5,6,7,1,9,0)
print "all elements",tuple1+tuple2
|
list1=[2,5,6,7,1,9,0]
print "all elements",list1
list1.append(100)
print list1
list=[7,5,3,2,4,6,7,5,4,0]
list1.extend(list)
print list1
list1.insert(10,10)
print list1
list1.pop()
print list1
list1.pop(0)
print list1
print list1.count(6)
print list1.index(10)
list1.sort()
print list1
#print list1.sort() - will not work this way
list1.reverse()
print list1
|
# Python Crash Course 2nd Edition
# Page 173 (Inheritance)
# Section 9-6: Ice Cream Stand
# An ice cream stand is a specific kind of restaurant. Write a class called IceCreamStand that
# inherits from the Restaurant class you wrote in Exercise 9-1 (page 162) or Exercise 9-4
# (page 167). Either version of the class will work; just pick the one you like better. Add an
# attribute called flavors that stores a list of ice cream flavors. Write a method that displays
# these flavors. Crate an instance of IceCreamStand, and call this method.
class Restaurant:
"""A simple class representing restaurant details"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant name and cuisine type attributes"""
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Prints info about the restaurant."""
details = f"{self.restaurant_name} is a {self.cuisine_type} restaurant."
print(f"\n{details}")
def open_restaurant(self):
"""Prints a message statin that the restaurant is open."""
open = f"{self.restaurant_name} is now open."
print(f"\n{open}")
def set_number_served(self, customer_count):
"""Allows updating the number of customers of the restaurant via a method"""
self.number_served = customer_count
def increment_number_served(self, additional_customers):
"""Enables incrementing the number of customers of the restaurant via a method"""
self.number_served += additional_customers
class IceCreamStand(Restaurant):
"""Represents a Ice Cream Stand"""
def __init__(self, restaurant_name, cuisine_type='Ice Cream'):
"""Initialize attributes of parent class and those specific to Ice Cream Stands"""
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
def display_flavors(self):
"""Displays the flavor of ice cream at the Ice Cream Stand"""
print("\nThe following ice cream flavors are available:")
for flavor in self.flavors:
print(f"{flavor.title()}")
icecreamstand1 = IceCreamStand('The Hyppo')
icecreamstand1.flavors = ['horchata', 'coffee', 'caramel', 'dulce de leche', 'thai tea']
icecreamstand1.describe_restaurant()
icecreamstand1.display_flavors()
# Section 9-7: Admin
# An administrator is a special kind of user. Write a class called Admin that inherits from the
# User class you wrote in Exercise 9-3 (page 162) or Exercise 9-5 (page 167). Add an attribute,
# privileges, that stores a list of strings like "can add post", "can delete post",
# "can ban user", and so on. Write a method called show_privileges() that lists the
# administrator's set of privileges. Create an instance of Admin, and call your method.
class User:
"""A class for simulated user profile details"""
def __init__(self, first_name, last_name, email, title):
"""Initializing attributes"""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.email = email
self.title = title.title()
self.login_attempts = 0
def describe_user(self):
print(f"User's Name: {self.first_name} {self.last_name}")
print(f"Email: {self.email}")
print(f"Title: {self.title}")
def greet_user(self):
"""Greets user by username"""
print(f"\nKia ora, {self.first_name}!")
def increment_login_attempts(self):
"""Enables incrementing the number of login attempts by the user via a method"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets login attempts back to zero"""
self.login_attempts = 0
class Admin(User):
"""A class for admin profile attributes"""
def __init__(self, first_name, last_name, email, title):
"""Initializing attributes of parent class and those for Admin"""
super().__init__(first_name, last_name, email, title)
self.privileges = []
def show_privileges(self):
"""Lists the administrator's set of privileges."""
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print(f"- {privilege}")
else:
print("- This user has no privileges.")
admin_user = Admin('Admin', 'Istrator', 'admin@website.co.nz', 'Admin')
admin_user.privileges = ['create user', 'delete user', 'reset password', 'ban user']
admin_user.describe_user()
admin_user.show_privileges()
|
# Python Crash Course 2nd Edition
# Page 127 (While Loops with Lists and Dictionaries)
# Section 7-8: Deli
# Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make
# an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a
# message for each order, such as I made your tuna sandwich. As each sandwich is made, move it to
# the list list of finished sandwiches. After all the sandwiches have been made, print a message
# listing each sandwich that was made.
sandwich_orders = ['dagwood', 'mountaineer', 'popeye']
finished_sandwiches = []
while sandwich_orders:
current_order = sandwich_orders.pop()
print(f"Making order: {current_order.title()}")
finished_sandwiches.append(current_order)
# Displaying finished orders
print("\nThe following sandwich orders have been made:")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title())
# Section 7-9: No Pastrami
# Using the list sandwich_orders from Exercise 7-8, make sure the sandiwch 'pastrami' appears in
# the list at least three times. Add code near the beginning of your program to print a message
# saying the deli has run out of pastrami, and then use a while loop to remove all occurrences of
# 'pastrami' from sandwich_orders. Make sure no pastrami sandwiches end up in finished_sandwiches.
sandwich_orders = ['dagwood', 'mountaineer', 'popeye', 'pastrami', 'pastrami', 'pastrami',]
finished_sandwiches = []
print("\nPlease note: The deli has run out of pastrami.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
# Could just as easily use .pop() and move removed orders into a cancelled_orders list.
print(f"Removing order: Pastrami")
while sandwich_orders:
current_order = sandwich_orders.pop()
print(f"Making order: {current_order.title()}")
finished_sandwiches.append(current_order)
# Displaying finished orders
print("\nThe following sandwich orders have been made:")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title())
# Section 7-10: Dream Vacation
# Write a program that polls users about their dream vacation. Write a prompt similar to if you
# could visit one place in the world, where would you go? Include a block of code that prints the
# results of the poll.
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("If you could visit one place in the world, where would you go? ")
responses[name] = response
repeat = input("Would you like to let another person response? (yes/ no) ")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to go to {response}.") |
# Python Crash Course 2nd Edition
# Page 150 (Arbitrary Number of Arguments)
# Section 8-12: Sandwiches
# Write a function that accepts a list of items a person wants on a sandwich. The function should
# have one parameter that collects as many items as the function call provides, and it should
# print a summary of the sandwich that's being ordered. Call the function three times, using a
# different number of arguments each time.
def make_sandwich(*toppings):
print(toppings)
make_sandwich('bacon', 'lettuce', 'tomato',)
make_sandwich('peanut butter', 'jelly',)
make_sandwich('cheese')
# Section 8-13: User Profiles
# Start with a copy of user_profile.py from page 149. Build a profile of yourself by calling
# build_profile(), using your first and last names and three other key-value pairs that describe
# you.
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('mateo', 'spencer', city='wellington', country='new zealand',
title='lead data scientist')
print(user_profile)
# Section 8-14: Cars
# Write a function that stores information about a car in a dictonary. The function should always
# receive a manufacturer and a model name. It should then accept an arbitrary number of keyword
# arguments. Call the function with the required information and two other name-value pairs, such
# as a color or an option feature. Your function should work for a call like this one:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
# Print the dictionary that's returned to make sure all the information was stored correctly.
def cars(make, model, **options):
car_dict = {
'make': make.title(),
'model': model.title(),
}
for option, value in options.items():
car_dict[option] = value
return car_dict
# Had previously written this, this way. This technically works but when importing, would not
# pick up make, model without calling them make=this, model=that.
#def car_models(make, model, **car_info):
# return car_info
# car_info['manufacturer'] = make
# car_info['model_name'] = model
Tesla = cars('Tesla', 'Model S', color='Black', package='Long Range')
print(Tesla)
|
# Python Crash Course 2nd Edition
# Page 155 (Functions in Modules)
# Section 8-15: Printing Models
# Put the functions for the example printing_models.py in a separate file called
# printing_functions.py. Write an import statement at the top of printing_models.py, and modify
# the file to use the imported functions.
# Per instructions, I've created a printing_models.py and printing_functions.py. Also, placed
# code here to group it with the exercise.
import printing_functions as pf
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
# Section 8-16: Imports
# Using a program you wrote that has one function in it, store that function in a separate file.
# Import the function into your main program file, and call the function using each of these
# approaches:
# * import module_name
# * from module_name import function_name
# * from module_name import function_name as fn
# * import module_name as mn
# * from module_name import *
import cars
tesla = cars.car_info('Tesla', 'Model S', color='Black', package='Long Range')
print(tesla)
from cars import car_info
polestar = car_info('Polestar', '1', color='Silver', package='Performance')
print(polestar)
from cars import car_info as ci
roadster = ci('Tesla', 'Roadster', color='Red', package='SpaceX')
print(roadster)
import cars as c
taycan = c.car_info('Porsche', 'Taycan', color='Silver', package='4S')
print(taycan)
from cars import car_info
etron = car_info('Audi', 'e-Tron', color='Blue', package='A3')
print(etron)
# Section 8-17: Styling Functions
# Choose any three programs you wrote for this chapter, and make sure they follow the styling
# guidelines described in this section.
Complete.
|
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg')
px = img[100,100]
# Display 3 channels of pixel
print px
# accessing only blue pixel
blue = img[100,100,0]
print blue
#You can modify the pixel values the same way
img[100,100] = [255,255,255]
print img[100,100]
img.item(10,10,2)
img.itemset((10,10,2),100)
img.item(10,10,2)
print img.shape
# Image size h*w
print img.size
# data type
print img.dtype
ball = img[10:20, 10:20]
img[80:90, 80:90] = ball
cv2.imshow("ball",img)
#Splitting and Merging Image Channels
b,g,r = cv2.split(img)
img = cv2.merge((b,g,r))
#or
b = img[:,:,0]
#Set all red pixel to 0
img[:,:,2] = 0
#Make border of image
BLUE = [255,0,0]
img1 = cv2.imread('opencv_logo.jpg')
replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show() |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
sess = tf.InteractiveSession()
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
# initial parameters
width = 28
height = 28
flat = width * height
class_output = 10
# input and output
x = tf.placeholder(tf.float32, shape = [None, flat])
y_ = tf.placeholder(tf.float32, shape= [None, class_output])
# converting images to tensor
x_image = tf.reshape(x, [-1,28,28,1])
# First Convolutional Layer
W_conv1 = tf.Variable(tf.truncated_normal([5,5,1,32], stddev = 0.1)) # Kernel of size 5x5 and input channel 1 with 32 features maps
b_conv1 = tf.Variable(tf.constant(0.1, shape=[32])) # for 32 outputs
convolve1 = tf.nn.conv2d(x_image, W_conv1, strides=[1,1,1,1], padding='SAME') + b_conv1
h_conv1 = tf.nn.relu(convolve1) # relu activation function
conv1 = tf.nn.max_pool(h_conv1, ksize = [1,2,2,1], strides = [1,2,2,1], padding= 'SAME') # maxpool 2x2 with no overlapping
''' the output here is a image of dimension 14x14x32 '''
# Second Convolutional Layer
W_conv2 = tf.Variable(tf.truncated_normal([5,5,32,64], stddev = 0.1)) # Kernel size 5x5 and input channel 32 with 64 features maps
b_conv2 = tf.Variable(tf.constant(0.1, shape=[64])) # for 64 outputs
convolve2 = tf.nn.conv2d(conv1, W_conv2, strides = [1,1,1,1], padding= 'SAME') + b_conv2
h_conv2 = tf.nn.relu(convolve2)
conv2 = tf.nn.max_pool(h_conv2, ksize= [1,2,2,1], strides = [1,2,2,1], padding = 'SAME') # maxpool 2x2
''' the output here is 7x7x64 '''
# Fully Connected Layer
flattening_matrix = tf.reshape(conv2, [-1,7*7*64]) # Flattening the second convolution layer
W_fc1 = tf.Variable(tf.truncated_normal([7*7*64, 1024], stddev=0.1)) # fully connected layer weights
b_fc1 = tf.Variable(tf.constant(0.1, shape = [1024])) # need 1024 biases for 1024 outputs
fully_connected_layer = tf.matmul(flattening_matrix, W_fc1) + b_fc1
h_fc1 = tf.nn.relu(fully_connected_layer)
# To reduce overfitting
keep_prob = tf.placeholder(tf.float32)
layer_drop = tf.nn.dropout(h_fc1, keep_prob)
# Softmax layer
W_fc2 = tf.Variable(tf.truncated_normal([1024,10], stddev = 0.1)) # 1024 neurons
b_fc2 = tf.Variable(tf.constant(0.1, shape=[10])) # for 10 outputs
fc = tf.matmul(layer_drop, W_fc2) + b_fc2
y_cnn = tf.nn.softmax(fc)
|
def climbingLeaderboard(scores, alice):
scores = sorted(list(set(scores)))
index = 0
rank_list = []
n = len(scores)
for i in alice:
while (n > index and i >= scores[index]):
index += 1
rank_list.append(n+1-index)
return rank_list
'''
def climbingLeaderboard(scores, alice):
# print(scores)
# print(alice)
maillist = list()
for i in range(len(scores)):
if scores[i] not in maillist:
maillist.append(scores[i])
#print(maillist)
score = list()
for i in range(len(alice)):
val = getposistion(maillist,alice[i],0,len(maillist)-1)
#print(val)
score.append(val)
return (score)
def getposistion(maillist,val,f,l):
if f > l:
return f+1
mid = (f+l)//2
if maillist[mid] == val:
return mid+1
elif maillist[mid] > val:
if mid == len(maillist) -1:
return len(maillist) + 1
elif mid == 0:
return 2
else:
return getposistion(maillist,val,mid+1 ,l)
else:
if mid == 0:
return 1
elif mid == len(maillist) -1 and f == len(maillist) -1 and l == len(maillist) -1:
#return getposistion(maillist, val, f, mid - 1)
return len(maillist)
else:
return getposistion(maillist, val, f, mid -1)
'''
if __name__ == '__main__':
#scores_count = int(input())
scores = list(map(int, input().split()))
#alice_count = int(input())
alice = list(map(int, input().split()))
result = climbingLeaderboard(scores, alice)
print('\n'.join(map(str, result)))
#fptr.write('\n'.join(map(str, result)))
|
import csv
import datetime
import shutil
from tempfile import NamedTemporaryFile #imported class
# these are all built in functions in Python
#figure out the number of rows
def get_length(file_path):
with open("data.csv", "r") as csvfile:
reader = csv.reader(csvfile)
reader_list = list(reader) #lists the contents so the length can be determined
return len(reader_list)
def append_data(file_path, name, email):
fieldnames = ["id", "name", "email"]
#the number of rows?
next_id = get_length(file_path)
with open(file_path, "a", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#writer.writeheader() not needed
writer.writerow({
"id": next_id,
"name": name,
"email": email,
})
#append_data("data.csv", "Larry", "box1@toneangel.com")
# if data.csv is not in the same directory, the whole path is needed above
filename = "data.csv"
temp_file = NamedTemporaryFile(mode='w+', delete=False, newline="")
with open(filename, 'r', newline="") as csvfile, temp_file:
reader = csv.DictReader(csvfile)
fieldnames = ['id', 'name', 'email', 'amount', 'sent', 'date']
writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
#writer.writeheader()
#print(temp_file.name)
for row in reader:
print(row) #to see that each row is a dictionary value
writer.writerow({
"id": row["id"], #can do it this way because the reader reads these from the existing csv file rows
"name": row["name"],
"email": row["email"],
"amount": "1293.23",
"sent": "",
"date": datetime.datetime.now(),
})
shutil.move(temp_file.name, filename) #moves the data to the new file
|
import csv
with open("data.csv", "w+", newline='') as csvfile: #I found newline in documentation to avoid auto add of blank line
... writer = csv.writer(csvfile)
... writer.writerow(["Title", "Description", "Col 3"])
... writer.writerow(["Row 1", "Some Desc", "another"])
... writer.writerow(["Row 1", "Some Desc", "another"])
with open("data.csv", "a", newline="") as csvfile: #appends
... writer = csv.writer(csvfile)
... writer.writerow(["append row", "Some Desc", "another"])
with open("data.csv", "r", newline="") as csvfile: #reads only
reader = csv.reader(csvfile)
for row in reader:
print(row)
""" w+ is a mode that allows read,
write and overwrite of existing file or creates new file
"""
#using a dictonary instead of a list is better-
with open("data.csv", "r", newline="") as csvfile: #reads only
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
with open("data.csv", "a", newline="") as csvfile: #appends
fieldnames = ["id", "title"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({"id":123, "title": "new title"})
#next one will overwrite the file and will add the header row
with open("data.csv", "w", newline="") as csvfile: #appends
fieldnames = ["id", "title"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"id":123, "title": "new title"}) |
__author__ = "Michał Kuśmierczyk (kusm@protonmail.ch)"
__date__ = "29.01.15"
__license__ = "Python"
scales = ("C", "F", "K", "R", "DE", "N", "RE", "RO")
def convert_temp(temp, from_scale, to_scale):
"""Convert temperature to a different scale
possible scale inputs:
"C" for Celsius
"F" for Fahrenheit
"K" for Kelvin
"R" for Rankine
"De" for Delisie
"N" for Newton
"Re" for Réaumur
"Ro" for Rømer
:return converted temp value"""
try:
temp = float(temp)
except ValueError:
return "ValueError: Invalid temperature input. Must be a number."
from_scale = from_scale.upper()
to_scale = to_scale.upper()
if (from_scale not in scales) or (to_scale not in scales):
return 'Invalid scale input. Valid inputs: "C", "F", "K", "R", "De", ' \
'"N", "Re", "Ro".'
if from_scale == to_scale:
return temp
if not from_scale == scales[0]:
temp = convert_to_c(temp, from_scale)
if not to_scale == scales[0]:
temp = convert_from_c(temp, to_scale)
return temp
def convert_from_c(temp, scale):
"""Convert temperature from Celsius to a different scale"""
conversion_from_c = {
scales[1]: temp * (9 / 5) + 32,
scales[2]: temp + 273.15,
scales[3]: (temp + 273.15) * (9 / 5),
scales[4]: (100 - temp) * 3 / 2,
scales[5]: temp * 33 / 100,
scales[6]: temp * 4 / 5,
scales[7]: temp * 21 / 40 + 7.5,
}
return conversion_from_c[scale]
def convert_to_c(temp, scale):
"""Convert temperature to Celsius from a different scale"""
conversion_to_c = {
scales[1]: (temp - 32) * (5 / 9),
scales[2]: temp - 273.15,
scales[3]: (temp - 491.67) * (5 / 9),
scales[4]: 100 - temp * 2 / 3,
scales[5]: temp * 100 / 33,
scales[6]: temp * 5 / 4,
scales[7]: (temp - 7.5) * 40 / 21,
}
return conversion_to_c[scale]
if __name__ == "__main__":
from_scale = input("In what scale is your temperature? "
"C, F, K, R, De, N, Re or Ro >")
to_scale = input("In what scale do you want your temperature to be? "
"C, F, K, R, De, N, Re or Ro >")
temp = input("Temperature in %s >" % from_scale)
print(convert_temp(temp, from_scale, to_scale)) |
__author__ = "Michał Kuśmierczyk (kusm@protonmail.ch)"
__date__ = "30.01.15"
__license__ = "Python"
def encryptor(key, message):
"""Encrypt a message using Ceasar Cipher"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
encrypted_message = []
for letter in message:
if not (letter.lower() in alphabet):
encrypted_message.append(letter)
else:
index = alphabet.index(letter.lower())
index += key
new_letter = alphabet[index % 26]
if letter.isupper():
new_letter = new_letter.upper()
encrypted_message.append(new_letter)
encrypted_message = "".join(encrypted_message)
return encrypted_message
def decryptor(key, message):
"""Decrypt a message using Ceasar Cipher"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
decrypted_message = []
for letter in message:
if not (letter.lower() in alphabet):
decrypted_message.append(letter)
else:
index = alphabet.index(letter.lower())
index -= key
new_letter = alphabet[index % 26]
if letter.isupper():
new_letter = new_letter.upper()
decrypted_message.append(new_letter)
decrypted_message = "".join(decrypted_message)
return decrypted_message
if __name__ == "__main__":
choice = input("'e' to encrypt message, 'd' to decrypt message. ")
input_key = int(input("Key: "))
input_message = input("Message: ")
if choice == 'e':
print(encryptor(input_key, input_message))
elif choice == 'd':
print(decryptor(input_key, input_message))
else:
print("error")
|
#-*- coding: utf-8 -*-
print('Teste de palíndromo')
texto = str(input('Digite um texto: '))#entrada de dados (strings)
texto = texto.replace(" ","")#remove todos os espaços
if texto == texto[::-1]:
print('Esse texto é palíndromo!') # testa se a string X é igual a string X inversa
else:
print('Esse texto não é palíndromo!') |
#importa bibliotecas
from random import randint
#escolhe um número aleatório de 1 a 10
while True:
print('='*50)
print('JOGO DA ADIVINHACAO 3.1')
print('Acerte o numero que o computador escolher')
print('Escolha o tamanho do grupo de numeros para jogar:')
print('[1]facil: 1 ate 10')
print('[2]medio: 1 ate 100')
print('[3]dificil: 1 ate 1000')
print('[4]mais dificil: 1 ate 10000')
print('[5]super dificil: 1 ate 100000')
while True:
try:
limite = int(input('Qual sua escolha?'))
if (limite in [1,2,3,4,5]):
limite = 10 ** limite
break
else:
continue
except:
continue
#define as variáveis
numero = randint(1, limite)
escolha = 0
ultima_escolha = set({})
tentativas = 0
pontos = limite
#mostra os acertos e erros
while True:
escolha = -1
#repete a pergunta
while 1 > escolha or escolha > limite:
escolha = input('\nQual seu palpite de 1 a {0}: '.format(limite))
if escolha == '' or escolha.isnumeric() != True:
escolha = -1
else:
escolha = int(escolha)
if tentativas == pontos-1:
tentativas +=1
break
if escolha == numero:
print('Você acertou!')
if (tentativas > 0):
tentativas += 1
break
else:
if(escolha not in ultima_escolha):
dica_tipo = randint(1,4)
if (dica_tipo == 1):
if(numero %2 ==0):
print('Dica: o numero e par')
else:
print('Dica: o numero e impar')
elif (dica_tipo == 2):
multiplo_aleatorio = randint(2,10)
if (numero % multiplo_aleatorio == 0):
print('Dica: o numero e multiplo de ',multiplo_aleatorio)
else:
print('Dica: o numero nao e multiplo de ',multiplo_aleatorio)
elif (dica_tipo == 3):
soma_numero = sum(list( [ float(c) for c in (str(numero))]))
print('Dica: a soma dos digitos do numero e ', soma_numero)
else:
while True:
escolha_aleatoria = randint(1,limite)
if escolha_aleatoria != numero:
break
else:
continue
if (escolha_aleatoria > numero):
print('Dica: e menor que ',escolha_aleatoria)
else:
print('Dica: e maior que ',escolha_aleatoria)
else:
print('Nao e', escolha, ', tente outro')
ultima_escolha.add(escolha)
tentativas += 1
#define a pontuação
pontos = (1 - ((tentativas) / pontos ))*100
print('Tentativas: {}.\nPontuação: {:.2f}%.'.format(tentativas, pontos))
jogar_de_novo = str(input('Deseja jogar novamente[S/N]?')).strip().upper()
if (jogar_de_novo == 'S'):
continue
else:
break
|
## первая задача
print("Введите длину")
n=float(input())
while(n<0):
print("Введите длину")
n=float(input())
print("Введите ширину")
m=float(input())
while(m<0):
print("Введите ширину")
m=float(input())
if(m>n):
temp=n
n=m
m=temp
print("Введите растояние до от одного из длинных бортиков (не обязательно от ближайшего)")
x=float(input())
while(x<0)or(x>m):
while(x<0):
print("недопустимое значение")
print("Введите растояние до от одного из длинных бортиков (не обязательно от ближайшего)")
x=float(input())
while(x>m):
print("недопустимое значение")
print("Введите растояние до от одного из длинных бортиков (не обязательно от ближайшего)")
x=float(input())
print("Введите растояние до одного из коротких бортиков")
y=float(input())
while(y<0)or(y>n):
while(y<0):
print("недопустимое значение")
print("Введите растояние до одного из коротких бортиков")
y=float(input())
while(y>n):
print("недопустимое значение")
print("Введите растояние до одного из коротких бортиков")
y=float(input())
rez=[]
x1=m-x
x2=m-x1
y1=n-y
y2=n-y1
rez.append(x1)
rez.append(x2)
rez.append(y1)
rez.append(y2)
min=rez[0]
for i in range(1,len(rez)-1,1):
if(rez[i]<min):
min=rez[i]
print("Минимальное расстояние: ",min) |
# 11. Write a Python program to convert a list to a tuple.
def convert (list):
return tuple (list)
list = [1, 2, 3, 4, 5]
print (convert (list))
|
# 5. Write a Python program to add an item in a tuple.
# Jeden sposób:
krotka = (1, 2, 3, 4, 5)
krotka = krotka + (6,)
print (krotka)
# Drugi sposób:
krotka1 = 7
krotka = krotka + (krotka1,)
print (krotka)
|
"""
14. Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
"""
from datetime import date
d1 = date(2019, 9, 11)
d2 = date(2019, 9, 18)
d3 = d2 - d1
print(d3.days)
"""
15. Write a Python program to get the volume of a sphere with radius 6.
volume of a sphere is (4/3)*pi*r*r*r
"""
pi = 3.14
r = int(input("Enter radius value: "))
volume = (4/3)*pi*r*r*r
print("The volume of sphere is: ", volume)
"""
16. Write a Python program to get the difference between a given number and 17,
if the number is greater than 17 return double the absolute difference
"""
x = int(input("Enter an integer: "))
if x <= 17:
print("The difference between the number and 17 is: ",(17 - x))
elif x > 17:
print("The difference is absolute difference: ", 2*(abs(x-17)))
# 2nd type of code:
def difference(n):
if n <= 17:
return 17 - n
else:
return 2*(n - 17)
print(difference(52))
print(difference(16)) |
"""
21. Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user.
"""
x = int(input("Enter the number: "))
if (x % 2) == 0:
print("The number is even")
else:
print("The number is odd")
"""
22. Write a Python program to count the number 4 in a given list
"""
def list_numbers(nums):
count1 = 0
for j in nums:
if j == 4:
count1 = count1+1
print(count1)
list_numbers([1,2,3,4,5,7,4,4,5])
list_numbers([5,1,4,15,14,4,9])
list_numbers([1,2,3,5,6,7,6])
"""
23. Write a Python program to get the n (non-negative integer)
copies of the first 2 characters of a given string.
Return the n copies of the whole string if the length is less than 2.
"""
a = str(input("Enter a string: "))
b = int(input("Enter number of times the letters should be repeated: "))
print("Repeated letters are: ", a[:2] * b)
if len(a) < 2:
print(a*b)
def string_rep(str, v):
if len(str) < 2:
return str * v
else:
return str[:2] * v
print(string_rep('sony', 4))
print(string_rep('R', 4))
"""
24. Write a Python program to test whether a passed letter is a vowel or not
"""
x = str(input("Enter a string character"))
c = ['a','e','i','o','u']
if x in c:
print("is vowel", x)
else:
print("It is not a vowel")
|
# 生成器
L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10))
for n in g:
print(n)
# 斐波拉契数列 Fibonacci
# 如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
def fib(max):
print('begain')
n, a, b = 0, 0, 1
while n < max:
yield(b)
a, b = b, a + b
n += 1
return 'done'
print(fib(10))
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
o = odd()
next(o) |
#Daniel Lu
#07/23/2020
#Converts degrees Fahrenheit to Celsius
f = int(input("Please enter the degrees in Fahrenheit: "))
c = ((f - 32)* 5/9)
print("That is " + str(c) + " degrees Celsius")
|
import math; #diifieHellman
n=int(input("1st prime"))
g=int(input("2nd prime"))
x=int(input("1st private number"))
y=int(input("2nd private number"))
a=pow(n,x)%g #n and g interchangeble
b=pow(n,y)%g
k1=pow(a,x)%g
k2=pow(b,y)%g
if(k1==k2):
print("Successful")
else:
print("unsuccessful")
|
#Write a function named avoids that takes a word and a string of forbidden letters, and that returns
# True if the word doesn’t use any of the forbidden letters.
def avoid(string,forbidden_str):
for i in string:
if forbidden_str in string:
return True
else:
return False
string=str(input('Enter string:'))
forbidden_str=str(input('Enter forbidden string:'))
print(avoid(string,forbidden_str)) |
#Modify the above program to print only the words that have no “e” and compute the percentage of the words
# in the list have no “e.”
def has_no_e(list1):
list2=[]
count=0
for i in list1:
if "e" in i:
list2.append(i)
print((len(list2)/len(list1))*100)
str1=str(input())
list1=str1.split(" ")
has_no_e(list1) |
#Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function
# called is_anagram that takes two strings and returns True if they are anagrams.
def is_anagram(str1,str2):
str1=list(sorted(str1))
str2=list(sorted(str2))
if str1==str2:
return True
else:
return False
str1=str(input('Enter string1:'))
str2=str(input('Enter string2:'))
print(is_anagram(str1,str2)) |
#valume of sphere
'''def vol_sphere(r1):
global pi
return (4/3)*pi*r*r*r
pi=3.142
r=int(input())
print(vol_sphere(r))'''
#Suppose the cover price of a book is Rs.24.95, but bookstores get a 40% discount. Shipping costs
#Rs.3 for the first copy and 0.75p for each additional copy. What is the total wholesale cost for
#60 copies?
'''def wholesale():
bookprice=24.95
discount=(100-40)/100
firstshipcost=3
copies=60
remshipcost=0.75*(copies-1)
totalcost=(bookprice*discount*copies)+firstshipcost+remshipcost
return totalcost
print(wholesale())'''
#If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at
#tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
import math
strtime=((6*60)+52)*60 #hr to min
easypace=((8*60)+15)*2
tempo=((7*60)+12)*3
time=(strtime+easypace+tempo)/(60*60)
time_flo=math.floor(time)
min=(time-time_flo)*60
min_flo=math.floor(min)
sec=(min-min_flo)*60
print(time_flo,":",int(min),":",int(sec))
|
import unittest
from unittest.main import main
from calculate import calc
class TestCalculate(unittest.TestCase):
def test_calculate(self):
case1 = ["Ya", "Ya", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak"]
case2 = ["Tidak", "Tidak", "Tidak", "Ya", "Tidak", "Tidak", "Tidak", "Tidak"]
case3 = ["Tidak", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak"]
case4 = [True, True, True, True, True, True, True, False]
self.assertEqual(calc(case1), "Direkomendasikan")
self.assertEqual(calc(case2), "Direkomendasikan")
self.assertEqual(calc(case3), "Tidak direkomendasikan")
self.assertEqual(calc(case4), "Tidak direkomendasikan")
if __name__ == '__main__':
unittest.main() |
### SCRIPT FOR MULTIPLE PAGES ###
from requests import get
from bs4 import BeautifulSoup
"""We’ll scrape the first 4 pages of each year in the interval 2000-2017. 4 pages for each of the 18
years makes for a total of 72 pages. Each page has 50 movies, so we’ll scrape data for 3600 movies
at most. But not all the movies have a Metascore, so the number will be lower than that. Even so,
we are still very likely to get data for over 2000 movies."""
pages = [str(i) for i in range(1,5)] # Create a list called pages, and populate it with the strings corresponding to the first 4 pages.
years_url = [str(i) for i in range(2000,2018)] # Create a list called years_url and populate it with the strings corresponding to the years 2000-2017.
from time import sleep # Control the loop rate. Will pause the execution for a specified amount of time. So our IP Address does not get banned.
from random import randint # Varies the amount of wait time between requests. Creates a random integer within a specified interval.
from time import time # Set a starting time
from IPython.core.display import clear_output # Clear -- View only the most recent request -- A bit more tidy when scraping multiple web pages.
# Redeclaring the lists in which to store data
names = []
years = []
imdb_ratings = []
metascores = []
votes = []
# Preparing the monitoring of the loop
start_time = time()
requests = 0
# For every year in the interval 2000-2017
for year_url in years_url:
# For every page in the interval 1-4
for page in pages:
# Make a get request
response = get('http://www.imdb.com/search/title?release_date=' + year_url +
'&sort=num_votes,desc&page=' + page, headers = {"Accept-Language": "en-US, en;q=0.5"}) # headers = {"Accept-Language": "en-US, en;q=0.5"} requests that we get all the scraped info in english even if we are over seas.
# Pause the loop
sleep(randint(8,15))
# Monitor the requests
requests += 1
elapsed_time = time() - start_time
print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))
clear_output(wait = True)
# Throw a warning for non-200 status codes
if response.status_code != 200:
warn('Request: {}; Status code: {}'.format(requests, response.status_code))
# Break the loop if the number of requests is greater than expected
if requests > 72:
warn('Number of requests was greater than expected.')
break
# Parse the content of the request with BeautifulSoup
page_html = BeautifulSoup(response.text, 'html.parser')
# Select all the 50 movie containers from a single page
mv_containers = page_html.find_all('div', class_ = 'lister-item mode-advanced')
# For every movie of these 50
for container in mv_containers:
# If the movie has a Metascore, then:
if container.find('div', class_ = 'ratings-metascore') is not None:
# Scrape the name
name = container.h3.a.text
names.append(name)
# Scrape the year
year = container.h3.find('span', class_ = 'lister-item-year').text
years.append(year)
# Scrape the IMDB rating
imdb = float(container.strong.text)
imdb_ratings.append(imdb)
# Scrape the Metascore
m_score = container.find('span', class_ = 'metascore').text
metascores.append(int(m_score))
# Scrape the number of votes
vote = container.find('span', attrs = {'name':'nv'})['data-value']
votes.append(int(vote))
### Examinging the Scraped Data
import pandas as pd
movie_ratings = pd.DataFrame({'movie': names,
'year': years,
'imdb': imdb_ratings,
'metascore': metascores,
'votes': votes
})
print(movie_ratings.info())
movie_ratings.head(10)
movie_ratings.to_csv('movie_ratings.csv')
|
# get current weather data
def k2c(k):
return k-273.15
# Python program to find current
# weather details of any city
# using openweathermap api
# import required modules
import requests, json
# Enter your API key here
api_key = "9a6f64de069cb85d600ee405159a85f3"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
#city_name = input("Dover")
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + 'Dover'
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
# store the value corresponding
# to the "temp" key of y
current_temperature = (y["temp"])
# store the value corresponding
# to the "pressure" key of y
current_pressure = y["pressure"]
# store the value corresponding
# to the "humidity" key of y
current_humidiy = y["humidity"]
# store the value of "weather"
# key in variable z
z = x["weather"]
# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = z[0]["description"]
# print following values
print(" Temperature (in K) = " +
str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " +
str(current_pressure) +
"\n humidity (in percentage) = " +
str(current_humidiy) +
"\n description = " +
str(weather_description))
else:
print(" City Not Found ")
# AI - WIP
import simplejson as json
import math
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets import SupervisedDataSet
from pybrain.tools.xml.networkwriter import NetworkWriter
from pybrain.tools.xml.networkreader import NetworkReader
ds = SupervisedDataSet(9, 3)
data = open("Z:\\sevendata.json", "r").read()
data = json.loads(data)
len = len(data)
for x in range(len):
try:
ds.addSample((data[x]["main"]["temp"],data[x]["main"]["humidity"],data[x]["main"]["pressure"],data[x-1]["main"]["temp"],data[x-1]["main"]["humidity"],data[x-1]["main"]["pressure"],data[x-2]["main"]["temp"],data[x-2]["main"]["humidity"],data[x-2]["main"]["pressure"]),(data[x+24]["main"]["temp"],data[x+48]["main"]["temp"],data[x+72]["main"]["temp"]))
except:
print("nu")
#print(data[x+1]["main"]["temp"])
print("set finished building")
import time
start = time.time()
from pybrain.supervised.trainers import BackpropTrainer
from os import path
if path.exists("Z:\\weights.xml"):
net = NetworkReader.readFrom('Z:\\weights.xml')
print("Resumed Training")
else:
net = buildNetwork(9,10,11,12,13,14,15,16,17,18,19,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3)
print("New Brain Built")
trainer = BackpropTrainer(net, ds, verbose=True)
"""while True:
net = NetworkReader.readFrom('Z:\\weights.xml')
trainer = BackpropTrainer(net, ds, verbose=True)
trainer.trainUntilConvergence(maxEpochs=10, verbose=True)
NetworkWriter.writeToFile(net, 'Z:\\weights.xml')
print("Trained another 10")
done = time.time()
elapsed = done - start
print(str(elapsed))
f = open("Z:\\times.txt", "a")
f.write(str(elapsed))
f.close()
start = time.time()
"""
trainer = BackpropTrainer(net, ds, verbose=True)
trainer.trainUntilConvergence(maxEpochs=512, verbose=True)
NetworkWriter.writeToFile(net, 'Z:\\weights.xml')
|
import dictionary as dict
def encryptor(text):
encrypted_text= ""
for letter in text:
if letter != " ":
encrypted_text= encrypted_text + dict.MORSE_CODE_DICT.get(letter) + " "
else:
encrypted_text += " "
print("The morse code is : ",encrypted_text)
return(encrypted_text) |
import random
def start_game():
import sys
# to invoke sys.exit when player does not want to play another game
print('Welcome to the Number Guessing Game! \nCan you guess the number I have in mind?')
scores = []
while True:
answer = random.randint(1, 100)
# generate random answer for each game, limit possible range to integer 1-100 for playability
attempt_count = 1
while True:
try:
guess = int(input('Pick a number between 1 and 100! \nYour guess: '))
while guess != answer:
if guess > 100:
print('Your guess is outside the answer range! Must be between 1 and 100!')
guess = int(input('Try again! \nYour guess: '))
elif guess > answer:
attempt_count += 1
print("It's lower")
guess = int(input('Try again! \nYour guess: '))
elif guess < answer:
attempt_count += 1
print("It's higher")
guess = int(input('Try again! \nYour guess: '))
print('Got it!This game is over! Your attempt number is {}'.format(attempt_count))
scores.append(attempt_count)
break
except ValueError:
print('Invalid Guess! Must be an integer! Try again!')
continue
# catch ValueError on guess input, allow to correct by asking again without incrementing attempt_count
best_score = min(scores)
# create variable for best score, define it as the lowest number of attempts to win the game
while True:
confirmation = str.upper(input('Would you like to play again? Y/N: '))
if confirmation == 'Y':
print('Best Score is {}'.format(best_score))
break
elif confirmation == 'N':
sys.exit('Bye then!')
else:
print('Don\'t recognize your input!')
continue
# catch input other than Y/N and allow user to correct by asking again
start_game()
|
str = input()
str2 = reversed(str)
if list(str)==list(str2):
print("you inputted a strong string")
else:
print("you inputted a weak string") |
#Author: Maple0
#Github:https://github.com/Maple0
#1st Sep 2016
#print pyramid by using *
def print_pyramid1(rows):
for x in range(0,rows):
print("*"*(x+1))
def print_pyramid2(rows):
i=rows
while i>0:
print("*"*i)
i-=1
def print_pyramid3(rows):
for i in range(0,rows):
print(' '*(rows-i-1) + '*' * (2*i+1))
rows=10
#print_pyramid1(rows)
#print_pyramid2(rows)
print_pyramid3(rows) |
#Author: Maple0
#Github:https://github.com/Maple0
#3st Sep 2016
#convert the decimal number into binary and vise-versa
def decimal_to_binary1(num):
temp=int(num)
remainder=0
binary=0
i=1
while temp >0:
remainder=temp%2
temp=int(temp/2)
binary+=remainder*i
i*=10
print(binary)
def decimal_to_binary2(num):
tmp=[]
while num >0:
tmp.append(num%2 )
num = int(num/2)
start=0
end=len(tmp)-1
while start < end:
temp=tmp[start]
tmp[start]=tmp[end]
tmp[end]=temp
start+=1
end-=1
print(tmp)
def binary_to_decimal(num):
temp=int(num)
remainder=0
decimal=0
i=0
while temp >0:
remainder=temp%10
temp=int(temp/10)
decimal+=remainder*pow(2,i)
i+=1
print(decimal)
decimal=55
binary=110111
#decimal_to_binary1(decimal)
decimal_to_binary2(decimal)
binary_to_decimal(binary)
|
class Node:
"""
Class to represent one node in a parse tree
"""
def __init__(self, tree, tree_id, pos):
self.tree = tree
self.tree_id = tree_id
self.pos = pos
def __str__(self):
string = "id " + str(self.tree_id) + "\n"
string += "pos " + str(self.pos) + "\n"
try:
string += "\nx " + str(self.x) + "\n"
except AttributeError:
return string
try:
string += "m " + str(self.m) + "\n"
string += "h " + str(self.h) + "\n"
except AttributeError:
return string
return string
def __repr__(self):
return self.__str__()
def set_x(self, x):
self.x = x
def set_h(self, m, h):
self.m = m
self.h = h
|
"""
print(2+2)
print('')
x=2
print(x)
print('')
print (x+2)
print('')
print(2+2*3)
"""
"""
print('Spam' == 'Eggs')
print('')
spam = 'Eggs'
print(len(spam))
print('')
x = 2
print(x == 2)
print(type(x))
y = 2.5
print(type(y))
print(x==y)
print(x)
"""
number_of_pupils=16
number_of_sweets=47
number_of_sweets_per_pupil=number_of_sweets/number_of_pupils
number_sweets_left=number_of_sweets-(number_of_pupils*2)
print(round(number_of_sweets_per_pupil))
print(number_sweets_left)
|
#!/usr/bin/python3
""" module that defines a class Base """
from json import dumps, loads
import csv
class Base:
""" class Base definition """
__nb_objects = 0
def __init__(self, id=None):
""" class Base object Constructor"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
@staticmethod
def to_json_string(list_dictionaries):
""" returns the JSON string repr of list_dictionaries """
if not list_dictionaries or list_dictionaries is None:
return "[]"
else:
return dumps(list_dictionaries)
@classmethod
def save_to_file(cls, list_objs):
""" writes the JSON string repr of list_objs to a file """
if list_objs is not None:
list_objs = [objs.to_dictionary() for objs in list_objs]
with open("{}.json".format(cls.__name__), "w", encoding="utf-8") as f:
f.write(cls.to_json_string(list_objs))
@staticmethod
def from_json_string(json_string):
""" returns the list of the JSON string repr json_string """
if json_string is None or not json_string:
return []
return loads(json_string)
@classmethod
def create(cls, **dictionary):
""" returns an instance with all attributes already set """
from models.rectangle import Rectangle
from models.square import Square
if cls is Rectangle:
new = Rectangle(1, 1)
elif cls is Square:
new = Square(1)
else:
new = None
new.update(**dictionary)
return new
@classmethod
def load_from_file(cls):
""" returns a list of instances from a file """
from os import path
filename = "{}.json".format(cls.__name__)
if not path.isfile(filename):
return []
with open(filename, "r", encoding="utf-8") as f:
return [cls.create(**o) for o in cls.from_json_string(f.read())]
@classmethod
def save_to_file_csv(cls, list_objs):
""" serilizes object to csv file"""
from models.rectangle import Rectangle
from models.square import Square
if list_objs is not None:
if cls is Rectangle:
list_objs = [[o.id, o.width, o.height, o.x, o.y]
for o in list_objs]
else:
list_objs = [[o.id, o.size, o.x, o.y]
for o in list_objs]
with open("{}.csv".format(cls.__name__), "w", newline="",
encoding="utf-8") as f:
wr = csv.writer(f)
wr.writerows(list_objs)
@classmethod
def load_from_file_csv(cls):
""" deserilizes object frm csv file """
from models.rectangle import Rectangle
from models.square import Square
list_objs = []
with open("{}.csv".format(cls.__name__), "r", newline="",
encoding="utf-8") as f:
rd = csv.reader(f)
for row in rd:
row = [int(objs) for objs in row]
if cls is Rectangle:
objs = {"id": row[0], "width": row[1], "height": row[2],
"x": row[3], "y": row[4]}
else:
objs = {"id": row[0], "size": row[1], "x": row[2],
"y": row[3]}
list_objs.append(cls.create(**objs))
return list_objs
@staticmethod
def draw(list_rectangles, list_squares):
''' turtle graphics draws all the Rectangles and Squares '''
import turtle
import time
from random import randrange
turtle.Screen().colormode(255)
for item in list_rectangles + list_squares:
img = turtle.Turtle()
img.color((randrange(255), randrange(255), randrange(255)))
img.pensize(1)
img.penup()
img.pendown()
img.setpos((item.x + img.pos()[0], item.y - img.pos()[1]))
img.pensize(10)
for i in range(2):
img.forward(item.width)
img.left(90)
img.forward(item.height)
img.left(90)
img.end_fill()
time.sleep(5)
|
#!/usr/bin/python3
""" function find_peak """
def find_peak(list_of_integers):
'''finds peak'''
if len(list_of_integers) > 0:
list_of_integers.sort()
return list_of_integers[-1]
else:
return None
|
#!/usr/bin/python3
def roman_to_int(roman_string):
numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000}
if type(roman_string) is not str or roman_string is None:
return 0
strg = list(roman_string[::-1].upper())
flag = 1
sum = 0
for l in range(len(strg) - 1):
sum = sum + numerals[strg[l]]*flag
if numerals[strg[l]] <= numerals[strg[l + 1]]:
flag = 1
if numerals[strg[l]] > numerals[strg[l + 1]]:
flag = -1
if flag == 1:
sum = sum + numerals[strg[len(strg) - 1]]
if flag == -1:
sum = sum - numerals[strg[len(strg) - 1]]
return sum
|
#!/usr/bin/python3
""" a module for a function that prints a square with the character #. """
def print_square(size):
""" function that prints a square with the character #.
Args:
size: type int the size of the squares side
Raises:
TypeError: type of ize must be int
ValueError: size must be > 0
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
print(("#" * size + "\n") * size, end="")
if __name__ == "__main__":
import doctest
doctest.testfile("tests/4-print_square.txt")
|
import random
def method1():
diceCount = [0, 0, 0, 0, 0, 0, 0]
throws = 100
diceList = []
for i in range(1, throws+1):
randomThrow = (random.randrange(1,6+1))
diceList.append(randomThrow)
face1 = diceList.count(1)
face2 = diceList.count(2)
face3 = diceList.count(3)
face4 = diceList.count(4)
face5 = diceList.count(5)
face6 = diceList.count(6)
print("Dice\tOccurrence")
print(f"1\t{face1}")
print(f"2\t{face2}")
print(f"3\t{face3}")
print(f"4\t{face4}")
print(f"5\t{face5}")
print(f"6\t{face6}")
print(len(diceList)) #just to make sure there are 100 throws
def method2():
diceCount = [0, 0, 0, 0, 0, 0, 0]
throws = 100
diceList = []
for i in range(1, throws+1):
randomThrow = (random.randrange(1,6+1))
diceList.append(randomThrow)
for i in diceList:
if i == 1:
diceCount[1] += 1
elif i == 2:
diceCount[2] += 1
elif i == 3:
diceCount[3] += 1
elif i == 4:
diceCount[4] += 1
elif i == 5:
diceCount[5] += 1
elif i == 6:
diceCount[6] += 1
else:
pass
print(diceCount)
print("Dice\tOccurrence")
for i in range(7):
print(f"{i}\t{diceCount[i]}")
print(f"Total\t{sum(diceCount)}")
# print(len(diceList)) #just to make sure there are 100 throws
def method3():
# this function simulates throwing of a dice, 100 times
# it keeps tracks of the number of occurences of each face value (1-6).
# it displays the number of occurences after 100 throws.
diceCount = [0]*7 #type in pdf, not *6
#loop 100times
for i in range(100):
num = random.randint(1,6)
#generate a random value (1-6)
diceCount[num]+=1
#update diceCount (increment respective index by 1)
#print summary
print("Dices \tSummary")
print(diceCount)
#print dice values and occurrences
for i in range(1,7):
print(f"{i}\t{diceCount[i]}")
print(f"Total\t{sum(diceCount)}")
method3()
#method3, BEST METHOD, CONCISE & SIMPLE, but takes time to understand |
class BankAccount:
__defaultBalance = 100
def __init__(self, accountId, pin, balance=__defaultBalance):
self._accountId = accountId
self._pin = pin
self._balance = float(balance)
#getter
@property
def accountId(self):
return self._accountId
@property
def pin(self):
return self._pin
@property
def balance(self):
return self._balance
#getter
@pin.setter
def pin(self, pin):
self._pin = pin
@balance.setter
def balance(self, balance):
self._balance = float(balance)
#method
def changePin(self, oldPin, newPin):
if oldPin == self._pin:
self._pin = newPin
return True
return False
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:
self._balance -= amount
return True
return False
def transfer(self, anotherAccount, amount):
if self.withdraw(amount):
anotherAccount.deposit(amount)
return True
return False
def __str__(self):
return f'AccountID: {self._accountId} Balance: ${self._balance:,.2f}'
class Bank:
def __init__(self, name) :
self._name = name
self._accounts = {}
#getter
@property
def name(self): return self._name
#methods
def add(self, account):
self._accounts[account.accountId].append(account) #append to dictionary
def search(self, accountId):
if accountId in self._accounts:
return self._accounts[accountId] #accountId is the key in the dict, returns the object in dict
return None
def remove(self, accountId):
if accountId in self._accounts:
del self._accounts[accountId]
def transfer(self, accountId1, accountId2, amount):
account1 = self.search(accountId1)
account2 = self.search(accountId2)
if account1 and account2 is not None:
return account1.transfer(account2, amount)
return False
def listAll(self):
print(f'Name: {self.name}')
for accountId, account in self._accounts.items():
print(f'Account: {account}')
def main():
pass
|
#PROPERTIES - MORE PYTHONIC WAY LOL
class Student():
def __init__(self, name):
self._name = name
#getter
@property
def name(self):
return self._name
#setter
@name.setter
def name(self, value):
self._name = value
student1 = Student("bali")
print(student1.name)
#why do we it do we this way? : this should applies it in encapsulation principle
#getter and setter method which is the only way we can access it from the outside
|
#POLYMORPHISM
print("START PROGRAM ... ")
print("----------------")
class Student():
def __init__(self, name, age, school, role):
self.name = name
self.age = age
self.school = school
self.role = role
def work(self):
print("I am working as a normal student!")
class SoftwareEngineer(Student): #PLEASE REMEMBER TO TAKE IN THE PARENT CLASS 'Student' INSIDE THIS CLASS FFS
def __init__(self, name, age, school, role, level):
super().__init__(name, age, school, role)
self.role = role
self.level = level
def work(self):
print(f"I am working as a {self.role}")
class Artist(Student):
def __init__(self, name, age, school, role, level):
super().__init__(name, age, school, role)
self.role = role
self.level = level
def work(self):
print(f"I am working as an {self.role}")
student1 = SoftwareEngineer("John", 21, "Computer School", 'Software Engineer', 2)
student2 = Artist("Jake", 25, "Art School", 'Artist', 3)
student3 = Student("Alice", 25, "Art School", "Student")
# print(f"Whats up peeps, my name is {student1.name} and i am {student1.age}. I am currently attending {student1.school} as a {student1.role}")
# print(f"Whats up peeps, my name is {student2.name} and i am {student2.age}. I am currently attending {student2.school} as a {student2.role}")
# print(f"Whats up peeps, my name is {student3.name} and i am {student3.age}. I am currently attending {student3.school} as a {student3.role}")
# student1.work()
# student2.work()
# student3.work()
#POLYMORPHISM
students = [
SoftwareEngineer("John", 21, "Computer School", 'Software Engineer', 2),
Artist("Jake", 25, "Art School", 'Artist', 3),
Student("Alice", 25, "Art School", "Student")
]
def motivate_student(students):
for student in students:
student.work()
motivate_student(students) |
numbers = [6, 10, 2]
a = dict()
for x in numbers:
a[x] = x[0]
a.append((x))
a.sort()
print(a) |
def new_set():
A,p = [],1
while p!=0:
p = int(input('Want to enter a new element? '))
if p == 0: break
x = int(input('Enter a new element. '))
if x not in A: A.append(x)
return A
def union_set(A,B):
C = []
for i in range(len(A)): C.append(A[i])
for i in range(len(B)):
if B[i] not in C: C.append(B[i])
return C
def intersect_set(A,B):
C = []
for i in range(len(A)):
if A[i] in B: C.append(A[i])
return C
def difference(A,B):
C = []
for i in range(len(A)):
if A[i] not in B: C.append(A[i])
return C
def symm_diff(A,B): return union_set(difference(A,B),difference(B,A))
def equality(A,B):
flag = True
flag = flag and len(A) == len(B)
if not flag: return flag
for i in range(len(A)): flag = flag and A[i] in B
return flag
def power_set(A):
B = []
for i in range(2**len(A)):
k,C,D = i,[],[]
for j in range(len(A)):
C.append(k%2)
k = k / 2
for j in range(len(A)):
if C[j] == 1: D.append(A[j])
B.append(D)
return B
def cross_product(A,B):
C = []
for i in A:
for j in B: C.append([i,j])
return C
def equivalence(A,R):
# A = [0,1,2,3,4]
# R = {0:[0,3,4],1:[1],2:[2],3:[0,3,4],4:[0,3,4]}
flag = True
for x in A: flag = flag and (x in R[x])
if not flag: return flag
for x in A:
for y in R[x]: flag = flag and (x in R[y])
if not flag: return flag
for x in A:
for y in R[x]:
for z in R[y]: flag = flag and (z in R[x])
return flag
def main():
print(None)
def contradiction_function():
def f(x): return x+1
def g(x): return x**2
for x in range(40):
print(f(g(x)) ,x**2 + 1, g(f(x)), (x+1)**2)
main() |
import pygame
from SudokuSolver import solve, valid_move
import time
pygame.font.init()
class Grid:
board = [
[8, 0, 9, 3, 0, 1, 0, 0, 0],
[0, 6, 0, 9, 0, 7, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 6, 9],
[3, 0, 5, 6, 0, 0, 0, 1, 4],
[1, 0, 6, 2, 0, 4, 5, 0, 3],
[4, 2, 0, 0, 0, 3, 8, 0, 6],
[5, 7, 8, 0, 0, 0, 0, 0, 0],
[0, 0, 4, 7, 0, 2, 0, 5, 0],
[0, 0, 0, 5, 0, 9, 7, 0, 8]
]
def __init__(self, rows, cols, width, height):
self.rows = rows
self.cols = cols
self.width = width
self.height = height
self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]
self.model = None
self.selected = None
def update_model(self):
"""
update model after insertion
"""
self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)]
def place(self, val):
"""
place value in the cell and check validity of the number
:param val: int
:return: bool
"""
row, col = self.selected
if self.cubes[row][col].value == 0:
self.cubes[row][col].set_value(val)
self.update_model()
if valid_move(self.model, val, (row, col)) and solve(self.model):
return True
else:
self.cubes[row][col].set_value(0)
self.cubes[row][col].set_temp(0)
self.update_model()
return False
def sketch(self, val):
"""
to insert the temp value
:param val: int
"""
row, col = self.selected
self.cubes[row][col].set_temp(val)
def draw(self, win):
"""
Draw grid lines and cubes
:param win: window
"""
# draw grid
gap = self.width // 9
for i in range(self.rows + 1):
if i % 3 == 0 and i != 0:
thick = 4
else:
thick = 1
pygame.draw.line(win, (0, 0, 0), (0, i * gap), (self.width, i * gap), thick)
pygame.draw.line(win, (0, 0, 0), (i * gap, 0), (i * gap, self.width), thick)
# draw cubes
for i in range(self.rows):
for j in range(self.cols):
self.cubes[i][j].draw(win)
def select(self, row, col):
"""
Reset all others
:param row: int
:param col: int
"""
for i in range(self.rows):
for j in range(self.cols):
self.cubes[i][j].selected = False
self.cubes[row][col].selected = True
self.selected = (row, col)
def clear(self):
"""
clear the value in selected cell
"""
row, col = self.selected
if self.cubes[row][col].value == 0:
self.cubes[row][col].set_temp(0)
def click(self, pos):
"""
:param pos: tuple
:return: (row, col)
"""
if pos[0] < self.width and pos[1] < self.height:
gap = self.width / 9
x = pos[0] // gap
y = pos[1] // gap
return (int(y), int(x))
else:
return None
def is_finished(self):
"""
check if all the cells are filled or not
:return: bool
"""
for i in range(self.rows):
for j in range(self.cols):
if self.cubes[i][j].value == 0:
return False
return True
class Cube:
"""
class to create 9x9 cubes for a 3x3 sudoku
"""
rows = 9
cols = 9
def __init__(self, value, rows, cols, width, height):
self.value = value
self.rows = rows
self.cols = cols
self.width = width
self.height = height
self.temp = 0 # temporary value that is inserted with the pencil
self.selected = False
def draw(self, win):
"""
draw window
:param win: window int
"""
font = pygame.font.SysFont("georgia", 30)
gap = self.width // 9
x = self.cols * gap
y = self.rows * gap
if self.temp != 0 and self.value == 0:
txt = font.render(str(self.temp), 1, (128, 128, 128))
win.blit(txt, (x + 5, y + 5))
elif not self.value == 0:
txt = font.render(str(self.value), 1, (0, 0, 0))
win.blit(txt, (x + (gap // 2 - txt.get_width() // 2), y + (gap // 2 - txt.get_height() // 2)))
if self.selected:
pygame.draw.rect(win, (255, 0, 0), (x, y, gap, gap), 3)
def set_value(self, val):
self.value = val
def set_temp(self, val):
self.temp = val
def redraw_window(win, board, playtime, strikes):
"""
redraw window after each insertion
:param win: window
:param board: 2d array
:param playtime: time elapsed
:param strikes: counter keeping count of inserted wrong number
"""
win.fill((250, 250, 250))
# Display time
font = pygame.font.SysFont("georgia", 30)
txt = font.render("Time Elapsed: " + str(format_time(playtime)), 1, (0, 0, 0))
win.blit(txt, (540 - 300, 560))
# Display strikes
txt = font.render("X " * strikes, 1, (255, 0, 0))
win.blit(txt, (10, 560))
# Draw grid lines and board
board.draw(win)
def format_time(secs):
"""
change the time format to hrs:min:sec
:param secs: time in seconds
:return: str, formatted time
"""
sec = secs % 60
min = secs // 60
hrs = min // 60
t = " " + str(hrs) + ":" + str(min) + ":" + str(sec)
return t
def main():
win = pygame.display.set_mode((540, 600))
pygame.display.set_caption("3X3 SUDOKU")
board = Grid(9, 9, 540, 540)
key = None
run = True
start = time.time()
strikes = 0
while run:
playtime = round(time.time() - start)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # game finished
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
key = 1
if event.key == pygame.K_2:
key = 2
if event.key == pygame.K_3:
key = 3
if event.key == pygame.K_4:
key = 4
if event.key == pygame.K_5:
key = 5
if event.key == pygame.K_6:
key = 6
if event.key == pygame.K_7:
key = 7
if event.key == pygame.K_8:
key = 8
if event.key == pygame.K_9:
key = 9
if event.key == pygame.K_DELETE:
board.clear()
key = None
if event.key == pygame.K_RETURN:
i, j = board.selected
if board.cubes[i][j].temp != 0:
if board.place(board.cubes[i][j].temp):
print("Correct")
else:
print("Wrong")
strikes += 1
key = None
if board.is_finished():
print("Game Over")
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
clicked = board.click(pos)
if clicked:
board.select(clicked[0], clicked[1])
key = None
if board.selected and key is not None:
board.sketch(key)
redraw_window(win, board, playtime, strikes)
pygame.display.update()
main()
pygame.quit()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 13:35:55 2019
@author: Mateusz.Jaworski
"""
import random
ints = range(33,127)
password = ''
for i in range(10):
password += chr(random.choice(ints))
print(password) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 18:56:58 2019
@author: Mateusz.Jaworski
"""
i = 10
result = 1
for j in range (1,11):
result *= j
print(i, result)
print('------NEW------')
list_noun = ['dog', 'potato', 'meal', 'icecream', 'car']
list_adj = ['dirty', 'big', 'hot', 'colorful', 'fast']
for x in list_noun:
for y in list_adj:
print(y, x)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 11:36:35 2019
@author: Mateusz.Jaworski
"""
import math
degree1 = 360
radian=pi*degree/180
print("%d degree is %f radians" % (degree1, radian))
degree2 = 45
radian=pi*degree/180
print("%d degree is %f radians" % (degree2, radian))
math.radians(degree1)
math.radians(degree2)
print('%d, %d' % (math.radians(degree1), math.radians(degree2)))
small_pizza_r = 0.22
big_pizza_r = 0.27
family_pizza_r = 0.38
small_pizza_price = 11.5
big_pizza_price = 15.6
family_pizza_price = 22
area_small = pi * pow(small_pizza_r,2)
m_price_small = area_small / small_pizza_r
print('Powierzchnia malej pizzy:', area_small, 'm2.')
print('Cena 1m2 pizzy small wynosi:', m_price_small) |
import math
x = math.radians(float(input("X = ")))
y = math.radians(float(input("Y = ")))
print(math.cos(x))
print(math.sin(y))
if (math.cos(x) - math.sin(y)) == 0:
print("Решений не существует")
elif x*y % math.radians(180) == math.radians(90):
print("Решений не существует")
else:
a = ((math.sin(x) - math.cos(y)) / (math.cos(x) - math.sin(y) )) * math.tan(x*y)
print(a) |
import math
print("Введите высоты")
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
if a <= 0 or b <= 0 or c <= 0:
print("Решений не сушествует")
else:
p = (a+b+c) / 2
s = math.sqrt(p*(p-a)*(p-b)*(p-c))
h1 = 2*s / a
h2 = 2*s / b
h3 = 2*s / c
print("h1 = " + str(h1) + "h2 = " + str(h2) + "h3 = " + str(h3))
|
n = int(input())
count = 2*n - 1
a = 1
for i in range(count):
if i <= n - 1:
print("*"*a)
a += 1
# print("i: ", i)
# print("a: ", a)
else:
a -= 1
print("a: ", a)
print("*"*(a-1))
# print("i: ", i)
# print("a: ", a) |
def divisible(x):
for i in xrange(1, 21):
if x % i != 0:
return False
return True
current = 20
while not divisible(current): current += 20
print current |
def is_palindrome(x):
str_arr = list(str(x))
l = len(str_arr)/2 # int
for i in xrange(l):
if str_arr[i] != str_arr[-1 * (i+1)]: return False
return True
current = 0 # current max
a, b = 999, 999
# Iterate down for a
# When a * b is less than current max, decrement b and reset a to 999
# Finish when b is less than 100
while b > 99:
product = a * b
if product < current:
a, b = 999, b-1
else:
if is_palindrome(product): current = product
a -= 1
print current |
class ListQueueSimple:
def __init__(self):
self._L = []
def enqueue(self, item):
self._L.append(item)
def dequeue(self):
return self._L.pop(0)
def peek(self):
return self._L[0]
def __len__(self):
return len(self._L)
def isempty(self):
return len(self) == 0
class ListQueueFakeDelete:
def __init__(self):
self._head = 0
self._L = []
def enqueue(self, item):
self._L.append(item)
def peek(self):
return self._L[self._head]
def dequeue(self):
item = self.peek()
self._head += 1
return item
def __len__(self):
return len(self._L) - self._head
def isempty(self):
return len(self) == 0
class ListQueue(ListQueueFakeDelete):
def dequeue(self):
item = self._L[self._head]
self._head += 1
if self._head > len(self._L)//2:
self._L = self._L[self._head:]
self._head = 0
return item
|
# 计算每道题每次提交的平均分
import json
f = open('../test_data.json', encoding='utf-8')
res = f.read()
data = json.loads(res)
exc = {}
req = {}
for key in data:
cases = data[key]['cases']
for case in cases:
case_id = case['case_id']
if case_id not in exc:
exc[case_id] = {}
exc[case_id]['sum'] = 0
exc[case_id]['times'] = 0
exc[case_id]['average'] = 0
req[case_id] = {}
req[case_id]['times'] = 0
req[case_id]['average'] = 0
uploads = case['upload_records']
for upload in uploads:
exc[case_id]['sum'] += upload['score']
exc[case_id]['times'] += 1
exc[case_id]['average'] = exc[case_id]['sum'] / exc[case_id]['times']
req[case_id]['times'] = exc[case_id]['times']
req[case_id]['average'] = exc[case_id]['average']
json_str = json.dumps(req)
with open('average.json', 'w') as json_file:
json_file.write(json_str)
print(len(req))
|
# 对5个维度进行pca降维(基于mle)
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.decomposition import PCA
pd_data = pd.read_csv('../matrix/matrix.csv')
temp = pd_data
pd_data = pd_data.iloc[:, 1:6]
pca = PCA(n_components='mle')
pca.fit(pd_data)
print(pca.explained_variance_ratio_)
print(pca.explained_variance_)
print(pca.n_components_)
x_new = pca.transform(pd_data)
plt.scatter(x_new[:, 0], x_new[:, 1])
plt.show()
data_frame = pd.DataFrame(
{'case_id': temp.case_id, 'M1': x_new[:, 0], 'M2': x_new[:, 1], 'M3': x_new[:, 2], 'M4': x_new[:, 3],
'difficulty_index': temp.difficulty_index})
data_frame.to_csv("pca_of_matrix.csv", index=False)
|
# 4
def check_parentheses(expr):
s = []
for i in range(len(expr)):
if expr[i] == '(' or expr[i] == '[' or expr[i] == '{':
s.append(expr[i])
continue
if len(s) == 0:
return False
if expr[i] == ')':
x = s.pop()
if x == '{' or x == '[':
return False
elif expr[i] == '}':
x = s.pop()
if x == '(' or x == '[':
return False
elif x == ']':
x = s.pop()
if x == '(' or x == '{':
return False
if len(s):
return True
else:
return False
if __name__ == "__main__":
expr = "{()}[]"
if check_parentheses(expr):
print("True")
else:
print("False")
# 5 Write a program to convert Integer to Roman String.
num_list = [(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
def num_roman(num):
roman = ''
while num > 0:
for k, v in num_list:
while num >= k:
roman += v
num -= k
return roman
print(num_roman(105))
# 6
'''def count_code_lines(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print("Number of lines in the file: ", count_code_lines("E:\Python-classes\input code"))'''
# 7
import re
def check_password_strength(password):
while True:
if len(password) < 8:
print("Week", ["The password must contain minimum 8 characters"])
break
elif not re.search("[a-z]", password):
print("Week", ["The password must contain lower case alphabets"])
break
elif not re.search("[A-Z]", password):
print("Week", ["The password must contain upper case alphabets"])
break
elif not re.search("[0-9]", password):
print("Week", ["The password must contain a digit"])
break
elif not re.search("[!@#$&]", password):
print("Week", ["The password must contain a special Character"])
break
else:
return "Valid Password"
password = str(input("Enter the password: "))
print(check_password_strength(password))
# 8
def check_sentence(s):
l = len(s)
if s[0] < 'A' or s[0] > 'Z':
return False
if s[l - 1] != '.':
return False
prev_state = 0
curr_state = 0
index = 1
while s[index]:
if 'A' <= s[index] <= 'Z':
curr_state = 0
elif s[index] == ' ':
curr_state = 1
elif 'a' <= s[index] <= 'z':
curr_state = 2
elif s[index] == '.':
curr_state = 3
if prev_state == curr_state and curr_state != 2:
return False
if prev_state == 2 and curr_state == 0:
return False
if curr_state == 3 and prev_state != 1:
return True
index += 1
prev_state = curr_state
return False
s = str(input("Enter the string : "))
print(check_sentence(s))
# 9
def greatest_sub_array(arr,k, n):
vec = []
for i in range(n - k + 1):
temp = []
for j in range(i, i + k):
temp.append(arr[j])
vec.append(temp)
vec = sorted(vec)
return vec[len(vec) - 1]
arr = [1, 4, 3, 2, 5]
k = 4
n = len(arr)
ans = greatest_sub_array(arr, k, n)
print(list(ans))
# 10.Given a list of N integers. The task is to eliminate the minimum number of elements such that in the resulting
# list the sum of any two adjacent values is even.
def adj_sum_even(number):
count = 0
for num in range(len(number)):
if number[num] % 2:
count += 1
return min(count, len(number) - count)
number = [1, 3, 5, 4, 2]
print(adj_sum_even(number))
|
from random import randint
from pygame.locals import K_UP, K_DOWN, K_RIGHT, K_LEFT
class StateMachine:
def __init__(self):
self.states = {}
self.active_state = None
# 为实体添加其会拥有的状态
def add_state(self, state):
self.states[state.name] = state
def think(self, current_time, screen_pos):
if self.active_state is None:
return
bullet = self.active_state.do_actions(current_time, screen_pos)
new_state_name = self.active_state.check_conditions()
if new_state_name is not None:
self.set_state(new_state_name)
if bullet:
return bullet
# 更新状态
def set_state(self, new_state_name):
if self.active_state is not None:
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions()
class State:
def __init__(self,name):
self.name = name
def do_actions(self, current_time):
pass
def check_conditions(self):
pass
def entry_actions(self):
pass
def exit_actions(self):
pass
# 巡逻状态
class StateExploring(State):
def __init__(self, tank):
State.__init__(self, "exploring")
self.tank = tank
def random_direction(self):
c = randint(0, 3)
if c == 0:
self.tank.direction = K_UP
elif c == 1:
self.tank.direction = K_DOWN
elif c == 2:
self.tank.direction = K_LEFT
elif c == 3:
self.tank.direction = K_RIGHT
def do_actions(self, current_time, screen_pos):
if randint(1, 50) == 1:
self.random_direction()
def check_conditions(self):
for enemy in self.tank.enemies:
if self.tank.get_distance(enemy) <= self.tank.view:
self.tank.target = enemy
return "hitting"
if self.tank.is_strike:
self.tank.is_strike = False
return "turning"
return None
def entry_actions(self):
self.random_direction()
# 攻击状态
class StateHitting(State):
def __init__(self, tank):
State.__init__(self, "hitting")
self.tank = tank
def do_actions(self, current_time, screen_pos):
bullet = self.tank.fire(current_time, screen_pos)
return bullet
def check_conditions(self):
if self.tank.is_strike:
self.tank.is_strike = False
return "turning"
if self.tank.get_distance(self.tank.target) > self.tank.view:
self.tank.target = None
return "exploring"
if self.tank.target.is_dead():
return "exploring"
# 转向状态
class StateTurning(State):
def __init__(self, tank):
State.__init__(self, "turning")
self.tank = tank
def do_actions(self, current_time, screen_pos):
self.tank.direction += 1
if self.tank.direction > 276:
self.tank.direction -= 4
def check_conditions(self):
return "exploring"
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 10:18:44 2020
@author: bluem
"""
#import necessary module re
import re
import pandas as pd
#read the file and extract the sequence as strings
file_name1=input("please input the first fasta file name:")
file_name2=input("please input the second fasta file name:")
file1=open(file_name1).read()
file2=open(file_name2).read()
#convert the list to a string
seq1=''.join(re.findall(r">.+?\n([A-Z]+)",file1))
seq2=''.join(re.findall(r">.+?\n([A-Z]+)",file2))
#calculate the hamming distance
edit_distance=0 #set initial distance as zero
for i in range(len(seq1)): #compare each amino acid
if seq1[i]!=seq2[i]:
edit_distance+=1 #add a score 1 if amino acids are different
print('\nthe hamming distance of two sequence is {}\n'.format(edit_distance))
"""
blosum62 source:
https://www.ncbi.nlm.nih.gov/Class/FieldGuide/BLOSUM62.txt
i use the website above to download the .txt file and i use str.repleace(' ',",")
and str.repleace(',,',",") to change it into .csv format
"""
#read the "BLOSUM62 matrix.csv" as a dataframe
blosum62=pd.read_csv("BLOSUM62 matrix.csv")
"""
in the dataframe, the name of amino acid is in column-0,
we should define a function to correspond the amin oacid name to the row number
"""
#check each amino acid name one by one
def find_row_num(aa):
j=0
while True:
if blosum62.iloc[j,0]!=aa:
j+=1
if blosum62.iloc[j,0]==aa:
break
return j
#calculate the blosum score
score=0
alignment=''
for i in range(len(seq1)):
aa1=seq1[i]
aa2=seq2[i]
#retrieve the score by giving 2 amino acid names
score_plus=blosum62.loc[find_row_num(aa2),aa1]#use my function to find the corresponding amino acid row number
#acumulate the score
score+=score_plus
if aa1==aa2:
alignment+=aa1
elif score_plus>=0:
alignment+='+'
else:
alignment+=" "
#print out the result
print('the bolusum62 score is {}\n'.format(score))
print("seq1:{}".format(seq1))
print(" {}".format(alignment))
print("seq2:{}".format(seq2))
|
def divisible_under_20():
reached=lowest=20
i=380
while reached > 0:
if i%reached==0:
reached-=1
if reached < lowest:
lowest=reached
print reached, i, lowest
else:
reached=20
i+=380
return i
divisible_under_20()
|
def anti_vowel(text):
no_vowels=""
print no_vowels
for char in text:
if not isVowel(char):
print char
no_vowels+=char
print no_vowels
return no_vowels
def isVowel(char):
char=char.lower()
if char in ('a' or 'e' or 'i' or 'o' or 'u'):
print True
return True
anti_vowel("Hey look Words!")
|
# Time Complexity : O(N)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#p0 left of p0 should always be 0
p0 = 0
#p2 right of p2 should always be 2
p2 = len(nums) - 1
curr = 0
while curr <= p2:
# check for 0
if nums[curr] == 0:
nums[curr], nums[p0] = nums[p0], nums[curr]
p0 += 1
curr += 1
#check for 2
elif nums[curr] == 2:
nums[curr], nums[p2] = nums[p2], nums[curr]
p2 -= 1
else:
curr += 1
|
# a little program that counts how many times bob is in a string
s = 'azcbobobegghakl'
count = 0
for letter in range(0, len(s)):
if s[letter: letter + 3] == 'bob':
count += 1
print(count)
# same thing just as function count_bob()
def count_bob(st):
count = 0
for letter in range(0, len(st)):
if st[letter: letter + 3] == 'bob':
count += 1
return count
print(count_bob(s))
|
# Escribe un programa que pida notas y los guarde en una lista. Para terminar de introducir notas, escribe una nota que
# no esté entre 0 y 10. El programa termina escribiendo la lista de notas.
lista = []
notas = float(input("Escribe la nota: "))
while notas > 0 and notas < 10:
lista.append(notas)
notas = float(input("Escriba otra nota: "))
print("Sus notas son: ", lista)
|
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
sol = Solution()
print(sol.removeElement([3, 2, 2, 3], 3)) |
from random import randint
game_board = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
winner = None
piece_placed = []
def print_board(board):
display = ''
for i in range(0, len(board)):
for j in range(0, len(board[0])):
if j < 2:
display += board[i][j]+'|'
else:
display += board[i][j]
if i < 2:
display += '\n-+-+-\n'
print(display)
def place_piece(board, location, player):
if player == 'user':
piece = 'X'
else:
piece = 'O'
if location == 1:
board[0][0] = piece
elif location == 2:
board[0][1] = piece
elif location == 3:
board[0][2] = piece
elif location == 4:
board[1][0] = piece
elif location == 5:
board[1][1] = piece
elif location == 6:
board[1][2] = piece
elif location == 7:
board[2][0] = piece
elif location == 8:
board[2][1] = piece
elif location == 9:
board[2][2] = piece
def check_winner(piece):
if piece == 'X':
return 'YOU'
else:
return 'CPU'
def check_win(board):
row1 = board[0][0] == board[0][1] == board[0][2] != ' '
row2 = board[1][0] == board[1][1] == board[1][2] != ' '
row3 = board[2][0] == board[2][1] == board[2][2] != ' '
col1 = board[0][0] == board[1][0] == board[2][0] != ' '
col2 = board[0][1] == board[1][1] == board[2][1] != ' '
col3 = board[0][2] == board[1][2] == board[2][2] != ' '
dia1 = board[0][0] == board[1][1] == board[2][2] != ' '
dia2 = board[0][2] == board[1][1] == board[2][0] != ' '
global winner
if row1:
winner = check_winner(board[0][0])
return True
if row2:
winner = check_winner(board[1][0])
return True
if row3:
winner = check_winner(board[2][0])
return True
if col1:
winner = check_winner(board[0][0])
return True
if col2:
winner = check_winner(board[0][1])
return True
if col3:
winner = check_winner(board[0][2])
return True
if dia1:
winner = check_winner(board[0][0])
return True
if dia2:
winner = check_winner(board[0][2])
return True
return False
print_board(game_board)
while True:
user_choice = None
try:
user_choice = int(input("Choose where to place? (1-9): "))
if user_choice < 0 or user_choice > 9 or user_choice in piece_placed:
raise Exception()
except Exception as e:
print("Invalid input")
continue
place_piece(game_board, user_choice, 'user')
piece_placed.append(user_choice)
print_board(game_board)
if check_win(game_board):
print(winner, "WON!")
break
cpu_choice = randint(1, 9)
while cpu_choice in piece_placed:
cpu_choice = randint(1, 9)
place_piece(game_board, cpu_choice, 'cpu')
piece_placed.append(cpu_choice)
print("CPU has placed:")
print_board(game_board)
if check_win(game_board):
print(winner, "WON!")
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.