text stringlengths 37 1.41M |
|---|
#development release
def is_prime(number):
'''
Check whether the input number is a prime number
using Fermat's Little Theorem
Please advise...
'''
success = 0
for i in range(1,number):
print((i^(number-1)) % number)
if (((i^(number-1)) % number) == 1):
success += 1
#return chance if number is prime
print(success)
return 1 - (1/(2**success))
|
import random
import turtle
wordList = ['python','programming','university','computer','ganis']
word = list(wordList[random.randint(0,len(wordList) - 1)])
displayWord = list('-' * len(word))
guesses = 6
count = 0
answers = 0
lettersUsed = []
wordFound = False
def initialize():
turtle.left(180)
turtle.forward(100)
turtle.right(90)
turtle.forward(200)
turtle.right(90)
turtle.forward(75)
turtle.right(90)
turtle.forward(20)
turtle.penup()
turtle.home()
turtle.backward(100)
turtle.right(90)
turtle.forward(100)
turtle.left(90)
def checkLetter(a):
isGood = False
while isGood == False:
if a.isalpha() == False:
a = raw_input("not a letter, try again: ")
a = a.lower()
elif len(a) != 1:
a = raw_input("one letter at a time: ")
a = a.lower()
elif a in lettersUsed:
a = raw_input("You already used that letter: ")
a = a.lower()
else:
lettersUsed.append(a)
isGood = True
print
return a
def checkWord(b):
global guesses, count, answers
if b in word:
i = 0
for item in word:
if word[i] == b:
displayWord[i] = b
answers = answers + 1
i = i + 1
print " %d is in the word" % (answers)
else:
print "letter is not in the word"
guesses = guesses - 1
print displayWord
answers = 0
count = count + 1
def hangMan(c):
if c == 5:
turtle.penup()
turtle.goto(-25,180)
turtle.right(180)
turtle.pendown()
turtle.circle(30)
turtle.left(180)
if c == 4:
turtle.penup()
turtle.goto(-25,180)
turtle.right(90)
turtle.forward(60)
turtle.pendown()
turtle.forward(30)
turtle.left(90)
if c == 3:
turtle.penup()
turtle.goto(-25,180)
turtle.right(90)
turtle.forward(70)
turtle.pendown()
turtle.left(90)
turtle.forward(20)
if c == 2:
turtle.penup()
turtle.goto(-25,180)
turtle.right(90)
turtle.forward(70)
turtle.pendown()
turtle.right(90)
turtle.forward(20)
turtle.left(180)
if c == 1:
turtle.penup()
turtle.goto(-25,180)
turtle.right(90)
turtle.forward(90)
turtle.pendown()
turtle.left(45)
turtle.forward(20)
turtle.left(45)
if c == 0:
turtle.penup()
turtle.goto(-25,180)
turtle.right(90)
turtle.forward(90)
turtle.pendown()
turtle.right(45)
turtle.forward(20)
turtle.left(135)
turtle.penup()
turtle.goto(-100,-100)
initialize()
print "Guess A Word"
print "The word is %d letters long and you will have %d guesses ..." % (len(word), guesses)
while wordFound == False and guesses > 0:
print "-" * 50
print "Guess #%d" % (count + 1)
print
turtle.write("Letters Used: " + str(lettersUsed))
turtle.right(90)
turtle.forward(20)
turtle.write("Word: " + str(displayWord))
turtle.backward(20)
turtle.left(90)
letter = raw_input("enter a letter: ")
letter = letter.lower()
checkWord(checkLetter(letter))
for i in range(6):
turtle.undo()
hangMan(guesses)
if '-' not in displayWord:
wordFound = True
if wordFound == True:
print "You found the secret word"
turtle.write("winner",font=(2000))
else:
print "You have ran out of guesses"
turtle.write("You Lost",font=(2000))
turtle.exitonclick()
|
n = int(input('Ingrese un numero entre 1 y 12: '))
if n >0 and n<13:
for x in range(1,13):
print(f'{n} X {x}: {n*x}')
else:
print(f'Numero fuera de rango\n{n} no esta entre 1 y 12')
|
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.data=data
def inorder(temp):
if (not temp):
return
inorder(temp.left)
print(temp.key,end = " ")
inorder(temp.right)
def insert(temp, key):
if not temp:
root= Node(key)
return
queue=[]
queue.append(temp)
while (len(queue)):
temp=queue[0]
queue.pop(0)
if (not temp.left):
temp.left=Node(key)
break
else:
queue.append(temp.left)
if (not temp.right):
temp.right=Node(key)
break
else:
queue.append(temp.right)
def deleteDeepest(root,d_node):
queue=[]
queue.append(root)
while len(queue):
temp=queue.pop(0)
if temp is d_node:
temp=None
return
if temp.right:
if temp.right is d_node:
temp.right=None
else:
queue.append(temp.right)
if temp.left:
if temp.left is d_node:
temp.left=None
else:
queue.append(temp.left)
def deletion(root,key):
if root==None:
return None
if root.left==None and root.right==None:
if root.data==key:
return None
else:
return root
key_node=None
queue=[]
queue.append(root)
while len(queue):
temp=queue.pop(0)
if temp.data==key:
key_node=temp
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
if key_node:
x=temp.data
deleteDeepest(root,temp)
key_node.data=x
return root |
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 10:10:52 2020
@author: tanck
"""
for ix in range(10):
square = ix**2
print(f"Square of {ix:2} is {square:2}")
print("All done and out of the loop; ix is ",ix) |
def initMatrix(height, width, initValue):
"""Initialized a matrix of given size with given values"""
field = []
for y in xrange(height):
field.append([])
for x in xrange(width):
field[y].append(initValue)
return field
def redrawField(field):
"""Dumps the current game field state as psaudographics to the console"""
print(' '+field[0][0]+' | '+field[0][1]+' | '+field[0][2])
print('---+---+---')
print(' '+field[1][0]+' | '+field[1][1]+' | '+field[1][2])
print('---+---+---')
print(' '+field[2][0]+' | '+field[2][1]+' | '+field[2][2])
return
def evaluateField(field):
"""Checks if the game is in a win or lose condition"""
emptyCount = 9
for y in xrange(3):
lineX,lineO = 0,0
for x in xrange(3):
if field[y][x]=='X':
lineX += 1
emptyCount -= 1
if field[y][x]=='O':
lineO += 1
emptyCount -= 1
if lineX == 3:
return 'X has won!'
if lineO == 3:
return 'O has won!'
if emptyCount == 0:
return 'Tie!'
for x in xrange(3):
lineX,lineO = 0,0
for y in xrange(3):
if field[y][x]=='X':
lineX += 1
if field[y][x]=='O':
lineO += 1
if lineX == 3:
return 'X has won!'
if lineO == 3:
return 'O has won!'
diag1X, diag1O,diag2X,diag2O = 0,0,0,0
for i in xrange(3):
if field[i][i] == 'X':
diag1X += 1
if field[i][i] == 'O':
diag1O += 1
if field[i][2-i] == 'X':
diag2X += 1
if field[i][2-i] == 'O':
diag2O += 1
if diag1X == 3 or diag2X == 3:
return 'X has won!'
if diag1O == 3 or diag2O == 3:
return 'O has won!'
return 0 |
for rabbit in range(1+35):
for chicken in range(1+35):
if rabbit + chicken == 35 and rabbit*4+chicken*2==94:
print 'Chicken:%s,Rabbit:%s' %(chicken,rabbit)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
def HouseGuest(Goal):
i = 0
house = []
Goal = int(Goal)
while i < Goal:
print "welcome to our house guest: Mr.%r" % (i)
house.append(i)
print "Now the house have people :",
for x in house:
print "Mr.%s"%(x),
if len(house)-1 == x:
print " "
i += 1
HouseGuest(10) |
from collections import deque
import time
from generate_maze import mazeGenerate
maxFringe=0
nodesNum=0
pts=[]
def matrix2graph(matrix):
# printMap(matrix)
height = len(matrix)
width = len(matrix[0]) if height else 0
graph = {(i, j): [] for j in range(width) for i in range(height) if matrix[i][j] == 1}
for row, col in graph.keys():
if row < height - 1 and matrix[row + 1][col] == 1:
graph[(row, col)].append(("S", (row + 1, col)))
graph[(row + 1, col)].append(("N", (row, col)))
if col < width - 1 and matrix[row][col + 1] == 1:
graph[(row, col)].append(("E", (row, col + 1)))
graph[(row, col + 1)].append(("W", (row, col)))
return graph
# find a path like
# "SSEEENNEEEEESSSSWWWSWWNWWSSSEEEEEENEESSS"
def bfsSearch(maze):
dim = len(maze)
queue = deque([('', (0, 0))])
visited = set()
graph = matrix2graph(maze)
# test graph
# print(graph)
while queue:
path, current = queue.popleft()
if current == (dim - 1, dim - 1):
return path, visited
if current in visited:
continue
visited.add(current)
if graph.get(current,'null') != 'null':
for direction, neighbour in graph[current]:
queue.append((path + direction, neighbour))
return "NO WAY!"
# parse route like "SSEEENNEEEEESSSSWWWSWWNWWSSSEEEEEENEESSS" into a collection of points
def points(route):
pts = []
pts.append((0, 0))
if (route == 'NO WAY'):
return pts
for i in range(0, len(route)):
cur = pts[i]
if route[i] == 'S':
pts.append((cur[0] + 1, cur[1]))
elif route[i] == 'E':
pts.append((cur[0], cur[1] + 1))
elif route[i] == 'N':
pts.append((cur[0] - 1, cur[1]))
else:
pts.append((cur[0], cur[1] - 1))
return pts
# input: dim wall
# output: path length. nodesNum, maxFringe
def bfs(dim, wall):
maze = [[1 for col in range(dim)] for row in range(dim)]
for pt in wall:
maze[pt[0]][pt[1]] = 0
if bfsSearch(maze) == 'NO WAY!':
return [],0,0
route, visited = bfsSearch(maze)
maxFringe = fringe(route)
nodesNum = len(visited)
pts = points(route)
return pts, nodesNum, maxFringe
# parse route like "SSEEENNEEEEESSSSWWWSWWNWWSSSEEEEEENEESSS" into a collection of points with maximum length
def fringe(route):
max = 1
temp = 1
direction = ''
for i in range(0, len(route) - 1):
if route[i] == route[i + 1]:
temp = temp + 1
if temp > max:
max = temp
temp = 1
direction = route[i]
return max
def run_bfs(dim,wall):
path, nodes, fringe = bfs(dim,wall)
if path:
return path, nodes, fringe
return ([(0, 0)], 0, 0)
# unit test
# dim = 10
# p = 0.2
# maze, wall = mazeGenerate(dim, p)
# start = time.clock()
# res = bfs(dim, wall)
# end = time.clock()
# print('runtime = ')
# print(end - start)
# if res != 'NO WAY!':
# pts, nodesNum, maxFringe = res[0], res[1], res[2]
# print(pts) # path
# print(nodesNum) # number of expanded nodes
# print(maxFringe) # maximum of fringe
|
import math
def load_input():
with open("input6.txt") as f:
return f.readlines()
lines = load_input()
def parse(line):
idx = line.index(")")
parent = line[:idx]
child = line[idx + 1:].strip()
return (parent, child)
to_parent = dict()
nodes = set()
for line in lines:
pair = parse(line)
to_parent[pair[1]] = pair[0]
nodes.add(pair[0])
nodes.add(pair[1])
def get_ancestors(node, accumulator):
if node not in to_parent:
return []
parent = to_parent[node]
accumulator.append(parent)
get_ancestors(parent, accumulator)
you_ancestors = []
get_ancestors("YOU", you_ancestors)
san_ancestors = []
get_ancestors("SAN", san_ancestors)
first_common = None
for i in range(0, len(you_ancestors)):
if you_ancestors[i] in san_ancestors:
first_common = you_ancestors[i]
break
if first_common is None:
raise AssertionError("boo, could not find a path!")
first_common_ancestors = []
get_ancestors(first_common, first_common_ancestors)
print(len(you_ancestors) + len(san_ancestors) - 2 * len(first_common_ancestors) - 2)
|
import random
max_num = int(input("Welcome to guess the number.\nPlease enter the maximum number I can think of:"))
secret_number = random.randint(1, max_num)
guess_count = 0
error_count = 0
correct_guess = 0
print("I've thought of a number between 1 and {}".format(max_num))
# print(secret_number)
def guess_calc(s, g):
if g == s:
return "Correct"
elif g < s:
return "Low"
else:
return "High"
while error_count < 5 and correct_guess == 0:
guess = input("Please enter your guess:")
try:
your_guess = int(guess)
except ValueError:
your_guess = 0
if 0 < your_guess < max_num:
guess_count += 1
error_count = 0
guess_status = guess_calc(secret_number, your_guess)
if guess_status == "Correct":
print("Well done you guessed the correct number.\nThis was guess number {}".format(guess_count))
correct_guess = 1
elif guess_status == "Low":
print("Your guess is too low, try again.")
else:
print("Your guess is too high, try again.")
else:
if error_count < 4:
guess_count += 1
print("You don't quite get this do you?.\nGo on try again.\n")
print("Your number must be between 1 and {} inclusive.\n".format(max_num))
else:
print("You are obviously too stupid to play such a simple game - goodbye")
error_count += 1
|
# With a given integral number n, write a program to generate a dictionary
# that contains (i, i*i) such that is an integral number between 1 and n
# (both included). and then the program should print the dictionary.
# Suppose the following input is supplied to the program: 8
# Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
input_num = input("Please enter a number:")
squares = dict()
if(input_num.isdigit()):
input_num=int(input_num)
for i in range(1,input_num+1):
squares[i] = i*i
else:
print("Please enter a positive number")
print(squares)
|
import pygame
from Collider import Collider
from Resources import colors
class Box(Collider):
def __init__(self, x_pos, y_pos, width, height, fill_color=colors.BLACK, border_color=colors.BLACK, border_thickness=0):
self._x_pos = x_pos
self._y_pos = y_pos
self._width = width
self._height = height
self.fill_color = fill_color
self.border_color = border_color
self.border_thickness = border_thickness
def Draw(self, screen):
if (self.border_thickness > 0):
# draws the "border" by drawing a bigger rectangle under the regular rectangle
pygame.draw.rect(screen, # the surface upon which to draw on
self.border_color, # the color of the border rect
(self._x_pos - self.border_thickness, # the x position of the top left corner of the border rect
self._y_pos - self.border_thickness, # the y position of the top left corner of the border rect
self._width + (2 * self.border_thickness), # the width of the border rect
self._height + (2 * self.border_thickness))) # the height of the border rect
pygame.draw.rect(screen, # the surface upon which to draw on
self.fill_color, # the color of the rect
(self._x_pos, # the x position of the top left corner of the rect
self._y_pos, # the y position of the top left corner of the rect
self._width, # the width of the rect
self._height)) # the height of the rect
|
class MiniMax:
"""
class containing implementation of MiniMax Alogrithm
"""
def optimal_move(self, board):
"""
returns the optimal move for the computer
Args:
board (List): 3*3 2D matrix storing selected coordinate for x or o
Returns:
List: coordinate of optimal move
"""
best_score = float("-inf")
best_move = [-1, -1]
for i in range(3):
for j in range(3):
if board[i][j] == 0:
board[i][j] = 2
score = self.minimax(board, False)
board[i][j] = 0
if score > best_score:
best_score = score
best_move = [i, j]
return best_move
def minimax(self, board, is_maximizing):
"""
returns score at each node
Args:
board (List): 3*3 2D matrix storing selected coordinate for x or o
depth (Int): depth of tree
is_maximizing (bool): check whether maximising or not
Returns:
Int: score of each node
"""
result = self.check_win(board)
if result != -2:
return result
if is_maximizing:
best_score = float("-inf")
for i in range(3):
for j in range(3):
# Check for available spot
if board[i][j] == 0:
board[i][j] = 2
score = self.minimax(board, False)
board[i][j] = 0
best_score = max(score, best_score)
return best_score
else:
best_score = float("inf")
for i in range(3):
for j in range(3):
# Check for available spot
if board[i][j] == 0:
board[i][j] = 1
score = self.minimax(board, True)
board[i][j] = 0
best_score = min(score, best_score)
return best_score
def check_win(self, board):
"""
check who wins or draw and return score
Args:
board (List): 3*3 2D matrix storing selected coordinate for x or o
Returns:
Int: score according to who wins or draw
"""
scores = [0, -1, 1] # O for draw, -1 if x wins, 1 if o wins
# Horizontal
for i in range(3):
if board[i][0] != 0 and board[i][0] == board[i][1] == board[i][2]:
return scores[board[i][0]]
# Vertical
for i in range(3):
if board[0][i] != 0 and board[0][i] == board[1][i] == board[2][i]:
return scores[board[0][i]]
# Diagonal
if board[0][0] != 0 and board[0][0] == board[1][1] == board[2][2]:
return scores[board[0][0]]
if board[2][0] != 0 and board[2][0] == board[1][1] == board[0][2]:
return scores[board[2][0]]
# Check for draw
empty_spots = 0
for row in board:
for element in row:
if element == 0:
empty_spots += 1
if empty_spots == 0:
return 0
else:
return -2
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 11 18:51:10 2016
@author: Alexander
"""
"""This program takes in a binary number as a string and returns the equivalent quartenary and its location in the unit square"""
import turtle
import random
def spacefillingfunction(L):
M = (int(max(L))) #guess the type of enerary
if M >= 3 or len(L) % 2 != 0:
return "StringError"
else:
L1 = [L[i:i+2] for i in range(0,len(L),2)] #group the digits into pairs and add them to a list
L2 = [str((M+1)*int(i[0])+int(i[1])) for i in L1] #put each pair through the function
#b1b2 = (2xb1+b2)
L3 = "".join(L2) #put the result back into a single string
if len(L) % 2 != 0: #again, consider the possibility of an odd number of digits.
L4 = "".join([L3[:-2],str(int(L3[-2])+1)]) #if odd, then do the reverse of the above
else:
L4 = L3
return "".join(L4)
turtle.hideturtle()
turtle.speed("fastest")
def draw_4x4_grid(s): #simple program draws 4 squares to make a grid
for i in range(4): #first quadrant
turtle.forward(s)
turtle.left(90)
turtle.penup()
turtle.forward(s)
turtle.pendown()
for i in range(4): #second quadrant
turtle.forward(s)
turtle.left(90)
turtle.penup()
turtle.left(90)
turtle.forward(s)
turtle.right(90)
turtle.pendown()
for i in range(4): #third quadrant
turtle.forward(s)
turtle.left(90)
turtle.penup()
turtle.backward(s)
turtle.pendown()
for i in range(4): #fourth quadrant
turtle.forward(s)
turtle.left(90)
turtle.right(90)
turtle.forward(s)
turtle.left(90)
def binary_to_point(s,L):
draw_4x4_grid(s)
k = spacefillingfunction(L) #convert the binary to a quartenary
for j in range(len(k)):
if k[j] == '0': #determine where to go for a 0 value and repeat at half the scale
if j == len(k)-1: #repeat for all possible values
turtle.begin_fill()
draw_4x4_grid(s/2**(j+1))
if j == len(k)-1:
turtle.end_fill()
elif k[j] == '1':
turtle.penup()
turtle.left(90)
turtle.forward(s/2**(j))
turtle.right(90)
turtle.pendown()
if j == len(k)-1:
turtle.begin_fill()
draw_4x4_grid(s/2**(j+1))
if j == len(k)-1:
turtle.end_fill()
if k[j] == '2':
turtle.penup()
turtle.forward(s/2**j)
turtle.left(90)
turtle.forward(s/2**j)
turtle.right(90)
turtle.pendown()
if j == len(k)-1:
turtle.begin_fill()
draw_4x4_grid(s/2**(j+1))
if j == len(k)-1:
turtle.end_fill()
if k[j] == '3':
turtle.penup()
turtle.forward(s/2**j)
turtle.pendown()
if j == len(k)-1:
turtle.begin_fill()
draw_4x4_grid(s/2**(j+1))
if j == len(k)-1:
turtle.end_fill()
turtle.delay()
turtle.done()
def random_binary(C):
R = []
for i in range(C):
R.append(str(random.randint(0,1)))
S = "".join(R)
return S
#example
X = random_binary(10)
print binary_to_point(150,X)
|
#8. Write a function, is_prime, that takes an integer and returns True
# If the number is prime and False if the number is not prime.
def is_prime(num):
for numbers in range(2,num-1):
if num%(numbers)==0:
return False
else:
return True
print(is_prime(11)) |
#1.Create a variable, paragraph, that has the following content:
# "Python is a great language!", said Fred. "I don't ever rememberhaving this much fun before."
class Pytalk:
def __init__(self,name):
self.name=name
def python_talk(self):
print(''' "Python is a great language!", said {}."I don't ever remember having this much fun before" '''.format(self.name))
talk=Pytalk('Fred')
talk.python_talk() |
import csv as csv
import numpy as np
csv_file_object = csv.reader(open('test.csv', 'rb')) #Load in the csv file
header = csv_file_object.next() #Skip the fist line as it is a header
data=[] #Creat a variable called 'data'
for row in csv_file_object: #Skip through each row in the csv file
data.append(row) #adding each row to the data variable
data = np.array(data) #Then convert from a list to an array
clean_data = np.delete(data,1,1) #remove name
clean_data = np.delete(clean_data,5,1) #remove ticket
clean_data = np.delete(clean_data,6,1) #remove cabin
#pclass(0),sex(1),age(2),sibsp(3),parch(4),fare(5),embarked(6)
clean_data[clean_data[:,1]=='female',1]=0 # 0 for female
clean_data[clean_data[:,1]=='male',1]=1 # 1 for male
clean_data[clean_data[:,6]=='C',6]=0 #0 for C
clean_data[clean_data[:,6]=='Q',6]=1 #1 for Q
clean_data[clean_data[:,6]=='S',6]=2 #2 for S
clean_data[clean_data[:,:]=='',:]=0
#open_file_object = csv.writer(open("clean_data.csv", "wb"))
#All the ages with no data make the median of the data
clean_data[clean_data[:,2]=='',2]=np.median(clean_data[clean_data[0::,2]!= '',2].astype(np.float))
#All missing ebmbarks just make them embark from most common place
clean_data[clean_data[0::,6] == '',6] = np.round(np.mean(clean_data[clean_data[0::,6]!= '',6].astype(np.float)))
#All the missing prices assume median of their respectice class
for i in xrange(np.size(clean_data[0::,0])):
if clean_data[i,5] == '':
clean_data[i,5] = np.median(clean_data[(clean_data[0::,5] != '') &\
(clean_data[0::,0] == clean_data[i,0])\
,5].astype(np.float))
#clean_data[clean_data[:,5]=='',5]=0
#np.savetxt("clean_data.csv", clean_data, delimiter=",")
clean_data = clean_data.astype(np.float)
np.savetxt("clean_test_data.csv", clean_data, delimiter=",",fmt='%.5f') |
str0 = '((((((((((((((2, 3)))))))))))))'
str1 = '((((((((((((((2, 3)))))))))))})'
str2 = '(([{(((((((((((2, 3)))))))))))))'
str3 = '{(((((((((((((2, 3))))))))))))}'
def bal(my_string):
chars = ["{","}","[","]"]
lst = list(my_string)
lst = filter(lambda x: x not in chars, lst)
counter_brackets_one = lst.count("(")
counter_brackets_two = lst.count (")")
#print counter_brackets_one, counter_brackets_two
if counter_brackets_one < counter_brackets_two:
diff_count_right = counter_brackets_two - counter_brackets_one
print "You had {} extra brackets in right.".format(diff_count_right)
lst.insert(0,"("*diff_count_right)
new_string = ''.join(lst)
elif counter_brackets_two < counter_brackets_one:
diff_count_left = counter_brackets_one - counter_brackets_two
print "You had {} extra brackets in left.".format(diff_count_left)
lst.extend(")"*diff_count_left)
new_string = ''.join(lst)
else:
print "Good. You have a balance between brackets."
new_string = ''.join(lst)
print "Your string after balance is %s" %(new_string)
print "For string str0"
bal(str0)
print "For string str1"
bal(str1)
print "For string str2"
bal(str2)
print "For string str3"
bal(str3)
|
print ("How old are you?"),
age = input()
print ("How tall are you?"),
height = input()
print ("How much do you weigh?"),
weight = input()
print ("So, you're '{0}' old, '{1}' tall and '{2}' heavy.".format(age, height, weight))
|
# Using Google text-to-speech(gtts)
from gtts import gTTS
import os
# en=english language
myobj = gTTS(text=input("Enter Text for Text to Speech : "),
lang='en')
# saving the speech as a mp3 file.
myobj.save("name.mp3")
os.system("mgp321 name.mp3")
|
class Node():
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class LinkedList():
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def get_size(self):
return self.length
def is_empty(self):
if self.get_size() == 0: return True
return False
def push_front(self, value):
new_node = Node(value)
if self.is_empty():
self.head = new_node
self.tail = new_node
self.length = self.length + 1
else:
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
self.length = self.length + 1
def push_back(self, value):
new_node = Node(value)
if self.is_empty():
self.head = new_node
self.tail = new_node
self.length = self.length + 1
else:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
self.length = self.length + 1
new_node.next = None
def pop_back(self):
if self.is_empty():
raise Exception('The list is empty')
else:
if self.get_size() == 1:
self.head = None
self.tail = None
self.length -= 1
else:
self.tail.prev.next = None
self.tail = self.tail.prev
self.length -= 1
def print_to_console(self):
if self.is_empty():
print('The list is empty')
else:
list_elem = self.head
list_list = []
for _ in range(self.get_size()):
list_list.append(list_elem.value)
list_elem = list_elem.next
print(list_list)
def search(self, str):
list_elem = self.head
for i in range(0, self.get_size()):
if list_elem.value == str:
return i
list_elem = list_elem.next
return False |
z=[2,1,4,3,7]
x=9
def sum():
for i in range(0,len(z)):
for j in range(0,len(z)):
if z[i]+z[j]==x:
print(i,j)
sum() |
import os
import random
import time
class TicTacToe:
def __init__(self):
self.new_game = True
self.turn = 'X'
self.theBoard = {'1': ' ','2': ' ','3': ' ','4': ' ','5': ' ','6': ' ','7': ' ','8': ' ','9': ' '}
self.players = []
self.game_over = False
def play_again(self):
self.new_game = False
self.theBoard = {'1': ' ','2': ' ','3': ' ','4': ' ','5': ' ','6': ' ','7': ' ','8': ' ','9': ' '}
def help(self):
print("""
WELCOME TO TIC TAC TOE GAME THE COLOMNS AND ROWS ARE DISPLAY LIKE THIS
TAKE A NUMBER FROM 1 - 9 FOR YOUR TURN POSITION
1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9
""")
def is_valid(self, input):
"""
check input:
if it's a number between 1 -9 only
if the field is empty
"""
try:
if self.theBoard[input] != ' ':
print('This field here is not empty.')
return False
except KeyError:
print('Invalid Character!\nYou can only choose from 1 to 9')
return False
return True
def start(self, redo=False, needhelp=True, playwithcomputer=False) -> None:
if needhelp:
self.help()
self.printBoard()
while True:
# take input
# taking input neither computer or player
if playwithcomputer and self.turn == 'O':
sign = f'{random.randint(1, 9)}'
print(f'Computer choosed {sign}')
time.sleep(1)
else:
sign = input(f"It's your turn {self.turn}: ")
if self.is_valid(input=sign) == False:
continue
else:
os.system('cls||clear')
# CHANGING THE POSITION WITH THE TURN USER INPUTED
self.theBoard[sign] = self.turn
# PRINTING THE BOARD
self.printBoard()
# CHECKING THE WINNING MATCH OF ALL SIDES
if self.check_rows() or self.check_columns() or self.check_sides():
os.system('cls||clear')
self.printBoard()
self.players.append(self.turn)
print(f'*** {self.turn} Wins ***')
print('\n\n')
if redo:
self.play_again()
self.printBoard()
continue
next = input('Do you want to start over?: ').upper()
if next in ['Y', 'YES']:
self.play_again()
self.printBoard()
continue
elif next in ['N', 'NO']:
break
# CHANGING THE TURN
self.turn = 'O' if self.turn == 'X' else 'X'
# CHECKING IF ALL FEILDS ARE FILLED UP IF YES GAME OVER WHICH IS DRAW
if ' ' not in self.theBoard.values():
os.system('cls||clear')
self.printBoard()
print('** DROW')
if redo:
self.play_again()
continue
elif input('Do you want to start over?: ').upper() in ['Y', 'YES']:
self.play_again()
continue
else:
break
if self.players:
if self.players.count('X') > self.players.count('O'):
print(f'--- X is the Winner ------')
elif self.players.count('X') < self.players.count('O'):
print(f'--- O is the Winner ------')
elif self.players.count('X') == self.players.count('O'):
print('----- DRAW ------')
else:
print('---- NO WINNER ---')
def printBoard(self) -> None:
"""Display the rows and coloumns of the board"""
print(self.theBoard['1'], ' | ', self.theBoard['2'], ' | ', self.theBoard['3'])
print('---+-----+---')
print(self.theBoard['4'], ' | ', self.theBoard['5'], ' | ', self.theBoard['6'])
print('---+-----+---')
print(self.theBoard['7'], ' | ', self.theBoard['8'], ' | ', self.theBoard['9'])
def check_rows(self, turn=None) -> bool:
"""
return True if any of the three row are matched
1, 2, 3
4, 5, 6
7, 8, 9
"""
if self.theBoard['1'] == self.theBoard['2'] == self.theBoard['3'] != ' ':
return True
elif self.theBoard['4'] == self.theBoard['5'] == self.theBoard['6'] != ' ':
return True
elif self.theBoard['7'] == self.theBoard['8'] == self.theBoard['9'] != ' ':
return True
return False
def check_columns(self, turn=None) -> bool:
"""
return True if any of the three colomns are matched
1, 4, 7
2, 5, 8
3, 6, 9
"""
if self.theBoard['1'] == self.theBoard['4'] == self.theBoard['7'] != ' ':
return True
elif self.theBoard['2'] == self.theBoard['5'] == self.theBoard['8'] != ' ':
return True
elif self.theBoard['3'] == self.theBoard['6'] == self.theBoard['9'] != ' ':
return True
return False
def check_sides(self, turn=None) -> bool:
"""
return True if any of the tow sides are matched
1, 5, 9
3, 5, 7
"""
if self.theBoard['1'] == self.theBoard['5'] == self.theBoard['9'] != ' ':
return True
elif self.theBoard['3'] == self.theBoard['5'] == self.theBoard['7'] != ' ':
return True
return False |
import time #Imports a module to add a pause
#Figuring out how users might respond
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
#Grabbing objects
sword = 0
flower = 0
required = ("\nUse only A, B, or C\n") #Cutting down on duplication
#The story is broken into sections, starting with "intro"
def intro():
print ("After a drunken night out with friends, you awaken the "
"next morning in a thick, dank forest. Head spinning and "
"fighting the urge to vomit, you stand and marvel at your new, "
"unfamiliar setting. The peace quickly fades when you hear a "
"grotesque sound emitting behind you. A slobbering orc is "
"running towards you. You will:")
time.sleep(1)
print (""" A. Grab a nearby rock and throw it at the orc
B. Lie down and wait to be mauled
C. Run""")
choice = input(">>> ") #Here is your first choice.
if choice in answer_A:
option_rock()
elif choice in answer_B:
print ("\nWelp, that was quick. "
"\n\nYou died!")
elif choice in answer_C:
option_run()
else:
print (required)
intro()
def option_rock():
print ("\nThe orc is stunned, but regains control. He begins "
"running towards you again. Will you:")
time.sleep(1)
print(""" A. Run
B. Throw another rock
C. Run towards a nearby cave""")
choice = input(">>> ")
if choice in answer_A:
option_run()
elif choice in answer_B:
print ("\nYou decided to throw another rock, as if the first "
"rock thrown did much damage. The rock flew well over the "
"orcs head. You missed. \n\nYou died!")
elif choice in answer_C:
option_cave()
else:
print (required)
option_rock()
def option_cave():
print ("\nYou were hesitant, since the cave was dark and "
"ominous. Before you fully enter, you notice a shiny sword on "
"the ground. Do you pick up a sword. Y/N?")
choice = input(">>> ")
if choice in yes:#Võtab mõõga
sword = 1 #lisab mõõga
else:
sword = 0
print ("\nWhat do you do next?")
time.sleep(1)
print (""" A. Hide in silence
B. Fight
C. Run""")
if choice in answer_A:
intro()
|
string= input("sisestage string. ")
string.strip()
a = len(string)
b = float(len(string) / 2)
if a>= 7 and (a%2) !=0:
print (string[int(b-1.5):int(b+1.5)])
print("true")
else:
print("false") |
def is_majority(items: list) -> bool:
t,f=0,0
for n in items:
if n:
t+=1
else: f+=1
return t>f
if __name__ == '__main__':
print("Example:")
print(is_majority([True, True, False, True, False]))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_majority([True, True, False, True, False]) == True
assert is_majority([True, True, False]) == True
assert is_majority([True, True, False, False]) == False
assert is_majority([True, True, False, False, False]) == False
assert is_majority([False]) == False
assert is_majority([True]) == True
assert is_majority([]) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
|
import math
#FUNCION
def binario(x):
temp = x
A= []
B=[]
modulo = 0
cociente = 0
while x != 0: # mientras el número de entrada sea diferente de cero
# paso 1: dividimos entre 2
modulo = x % 2
cociente = x // 2
A.append(modulo) # guardamos el módulo calculado
x = cociente # el cociente pasa a ser el número de entrada
while temp!= 0:
# se almacena el módulo en el orden correcto
B.insert(0, temp % 2)
temp //= 2
return B
#DATOS AQUI INGRESA LOS DATOS EL VALOR
parte_entera=0
parte_decimal=0.125
#VARIABLES
signo = 0
modulos_decimal=[]
if(parte_entera == 0):
exponente = 0
modulos =[0]
elif(parte_entera < 0):
print("Numero negativo: s = 1")
signo = 1
parte_entera = abs(parte_entera)
modulos = binario(parte_entera)
exponente = len(modulos)-1
#Pasar la parte decimal a binario
k = 1
r = parte_decimal
while True:
if (2*r >= 1):
d = 1
modulos_decimal.append(d)
else:
d=0
modulos_decimal.append(d)
r = 2*r-d
if(r == 0):
break
k = k + 1
print("El numero en binario es: ")
for i in modulos:
print(i,end="")
print(".",end="")
for i in modulos_decimal:
print(i,end="")
#Calclando exponente sesgado
print("\nAhora calculamos el exponente sesgado: ",end="")
print(exponente," + 127 = ",end="" )
temp = exponente + 127
E = binario(temp)
for h in E:
print(h,end="")
print("\nLa representacion pedida es")
print("Signo\texponente\tmantisa")
print(signo,end="")
print("\t",end="")
for i in E:
print(i,end="")
print("\t",end="")
for i in modulos:
print(i,end="")
for i in modulos_decimal:
print(i,end="")
|
from player import Player;
class Team:
def __init__(self, number_of_players, name):
self.number_of_players = number_of_players;
self.name = name;
self.players = [];
def addPlayer(self, name):
if(len(self.players) < self.number_of_players):
self.players.append(Player(name));
else:
raise ValueError("Team Squad is full!!")
|
string = "ThIsisCoNfUsInG"
substring = 'is'
count = 0
for i in range (0, len(string)):
temp = string[i:i+len(substring)]
if temp == substring:
count += 1
print(count)
|
#!/usr/bin/env python
import sys
def perror(s):
sys.stderr.write(s+'\n')
def label(i):
if i==0:
return 'inicio'
else:
return 'A'+str(i-1)
cities=['Gary', 'Fort_Wayne', 'Evansville', 'Terre_Haute', 'South_Bend']
def label_city(i):
return cities[i]
class Graph:
def __init__(self, V):
self.V = V
self.matrix=[ [0 for i in xrange(V)] for j in xrange(V)]
def set_matrix(self, m):
self.matrix=m;
def dot(self, to_label):
print ('digraph {')
for i in range(0,self.V):
print(' '+to_label(i)+';')
for i in range(0,self.V):
for j in range(0,self.V):
if self.matrix[i][j] != 0:
print(' '+to_label(i)+'->'+to_label(j)+'[label="'+str(self.matrix[i][j])+'"];')
print('}')
def min_distance(self, dist, sptSet):
mindist = sys.maxint
mindex = 0
for i in xrange(self.V):
if sptSet[i]==False and dist[i]<mindist:
mindist = dist[i]
mindex = i
return mindex
def dijkstra(self, src):
self.parent=[-1 for z in xrange(self.V)]
self.dist = [sys.maxint for x in xrange(self.V)]
sptSet = [False for y in xrange(self.V)]
self.dist[src] = 0
for count in xrange(self.V):
u = self.min_distance(self.dist,sptSet)
sptSet[u] = True
for v in xrange(self.V):
if self.matrix[u][v]>0 and sptSet[v] == False and self.dist[v] > self.dist[u]+ self.matrix[u][v]:
self.dist[v] = self.dist[u]+ self.matrix[u][v]
def print_dist(self, to_label):
perror( "Vertice\tdistancia:")
for i in xrange(self.V):
perror( to_label(i)+"\t"+str(self.dist[i]))
g = Graph(5)
g.matrix = [ [ 0, 132, 0, 164, 58],
[ 132, 0, 290, 201, 79],
[ 0, 290, 0, 113, 303],
[ 164, 201, 113, 0, 196],
[ 58, 79, 303, 196, 0]
]
g.dot(label_city)
g.dijkstra(0)
g.print_dist(label_city)
|
# CMSC389O Spring 2020
# HW3: Searching & Sorting -- Implement Natural Logarithm
# Description:
# Implement the ln() function, but don't use the library log functions or integration functions.
# Other library functions are fine
# Solutions should be within 1e-6 of the actual value (i.e. |student_ln(x) - ln(x)| < 1e-6)
# Hints:
# - This is for the sorting and searching section of the course. Don't use integration or bit manipulation.
# - What if you were given a sorted list of values where at least one of them were guaranteed to be acceptable?
# - ln() is (strictly) monotonically increasing -- i.e. for x < y in the domain, ln(x) < ln(y)
# Examples:
# 2.718281828459045 -> 1 (or anything within 1e-6 of 1)
# 20.085536923187668 -> 3 (or anything within 1e-6 of 3)
# Edge cases:
# ln(0) should return the floating point negative infinity float('-inf')
# ln(x) for negative x should raise ValueError (it's an invalid input)
# Running the public tests:
# python3 PublicTests.py
# Submit server notes:
# 2 of the release tests (9 and 10) are performance tests.
# Failing either of the last 2 tests (red box) is probably not due to
# correctness issues if you are passing the other tests.
"""
Zain Bhaila
02/17/2020
Bases cases check for 0 and negative inputs.
Create an initial approximation to center the binary search around using
an identity for the natural log. Approximation is good enough that we only
need to search with a radius of .0015 to find a better approximation. Do a
binary search over all values within the radius, increasing the lower bound if
our approximation is low, and decreasing the upper bound if our approximation
is high. Stop the approximation when our change in values is no longer
significant (when the difference is within the desired accuracy).
Time Complexity: O(1) - Binary search always occurs in a range of .003, so it
executes in constant time. Approximation also occurs in constant time.
Space Complexity: O(1) - No data structures are used.
"""
# needed for 'e' value
import math
# for student use
EPSILON: float = 1e-6
def student_ln(x: float) -> float:
if x == 0: # base cases
return float('-inf')
if x < 0:
raise ValueError("Invalid Input")
n = 99999999 * ((x ** (1/99999999)) - 1) # actual identity is a limit, but this is good start
l = n - .0015 # binary search based algorithm
r = n + .0015
mid = n
previous = -1
while True: # search near the solution until approximation is good
if math.exp(mid) > x: # current value is too large
r = mid
mid = (l+r)/2
else: # current value is too small
l = mid
mid = (l+r)/2
if abs(mid - previous) < EPSILON: # check if approximation is good
break; # stop looping when a close approximation has been found
previous = mid
return mid
|
import webbrowser
import ssl
from webbrowser import Chrome
count = 0
url = input("enter your desired url: ")
tries = 3
while True:
times = input("How many times would you like to open the url: ")
try:
times = int(times)
break
except ValueError:
print("You didnt enter a number you still have:", tries, "tries" )
tries = tries - 1
if tries == -1:
print("no more chances")
print("open the program again")
exit()
continue
times=int(times)
while True:
count=count+1
webbrowser.open_new_tab(url)
if count == times: break
print("count them")
|
t = float(input('Digite a temperatura em graus célcius: '))
f = 9 * (t / 5) + 32
print('{}ºC são {}ºF'.format(t, f))
|
#Faça um programa que leia um número inteiro e mostre na tela
#seu sucessor e seu antecessor
#======================================================
n = int(input('Digite um número: '))
print('O numéro escolhido é {} e seu sucessor é {} e seu antecessor é {}'.format(n,n-1,n+1))
|
#Crie um programa que leia um número real qualquer e mostre sua parte inteira.
from math import trunc
n = float(input('Digite um número com virgula para que o programa mostre sua parte inteira: '))
print('A parte inteira do número é {}'.format(trunc(n))) |
"""Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com SANTO"""
nome = input('Digite o nome de sua cidade: ').strip()
print('Sua cidade começa com o nome Santo? ')
pnome = nome.split()
print('Santo' in pnome[0]) |
def main():
positionsRed = [
['','','','','','',''],
['','','','','','',''],
['red','','','','','',''],
['','red','','','','',''],
['','','red','','','',''],
['','','','red','','','']]
positionsBlue = [
['','','','','','blue',''],
['','','','','blue','',''],
['','','','blue','','',''],
['','','blue','','','',''],
['','','','','','',''],
['','','','','','','']]
if winner(positionsBlue, 4,2, 'blue'):
print(winner(positionsBlue, 4,2, 'blue'), 'is the winner')
def winner(positions, row, col, color):
if checkDownLeft(positions, row, col, color) + checkUpRight(positions, row, col, color) >= 4: #check for the right diagonal
return color
elif checkDownRight(positions, row, col, color) + checkUpLeft(positions, row, col, color) >= 4: #check for the left diagonal
return color
elif checkDown(positions, row, col, color) + checkUp(positions, row, col, color) >= 4: #check for vertical win
return color
elif checkRight(positions, row, col, color) + checkLeft(positions, row, col, color) >=4: #check for horizontal win
return color
else:
return False
def checkDownLeft(positions, row, col, color):
if row > 4 or col < 1: #the cell is out of bounds
return 1
elif positions[row][col] != ' ' and positions[row][col] == positions[row+1][col-1]: #the current cell is not empty and is the same as the next cell in the line
return 1 + checkDownLeft(positions, row+1, col-1, color) #recurse with the next cell
else: #either the current cell is empty or the current cell does not equal the next cell
return 1
def checkUpLeft(positions, row, col, color):
if col < 1 or row < 1:
return 1
elif positions[row][col] == positions[row-1][col-1] and positions[row][col] != ' ':
return 1 + checkUpLeft(positions, row-1, col-1, color)
else:
return 1
def checkUpRight(positions, row, col, color):
if col > 5 or row < 1:
return 1
elif positions[row][col] == positions[row-1][col+1] and positions[row][col] != ' ':
return 1 + checkUpRight(positions, row-1, col+1, color)
else:
return 1
def checkDownRight(positions, row, col, color):
if col > 5 or row > 4:
return 1
elif positions[row][col] == positions[row+1][col+1] and positions[row][col] != ' ':
return 1 + checkDownRight(positions, row+1, col+1, color)
else:
return 1
def checkUp(positions, row, col, color):
if row < 1:
return 1
elif positions[row][col] == positions[row-1][col] and positions[row][col] != ' ':
return 1 + checkUp(positions, row-1, col, color)
else:
return 1
def checkDown(positions, row, col, color):
if row > 4:
return 1
elif positions[row][col] == positions[row+1][col] and positions[row][col] != ' ':
return 1 + checkDown(positions, row+1, col, color)
else:
return 1
def checkRight(positions, row, col, color):
if col > 5:
return 1
elif positions[row][col] == positions[row][col+1] and positions[row][col] != ' ':
return 1 + checkRight(positions, row, col+1, color)
else:
return 1
def checkLeft(positions, row, col, color):
if col < 1:
return 1
elif positions[row][col] == positions[row][col-1] and positions[row][col] != ' ':
return 1 + checkLeft(positions, row, col-1, color)
else:
return 1
main()
|
import sys
def up_from_leaf_to_root_with_calculating_childs_num(arr, num):
abs_num = abs(num)
parent = arr[abs_num][0]
if parent == 0: # 루트 노드
return
my_child_num = arr[abs_num][3]+arr[abs_num][4]+1
if parent < 0: # 부모 노드가 오른쪽에 있을 때
arr[abs(parent)][3] = my_child_num
else: # 부모 노드가 왼쪽에 있을 때
arr[parent][4] = my_child_num
up_from_leaf_to_root_with_calculating_childs_num(arr, parent)
def go_down_from_root_to_leaf_with_calculating_width(arr, width, level, left, right, left_flag, right_flag):
if left == -1 or right == -1:
return width, level
child_width, next_left, next_right = 0, -1, -1
if left != -1:
if not left_flag:
child_width += arr[left][4]+1
else:
child_width -= arr[left][3]+1
if arr[left][1] != -1:
next_left = arr[left][1]
left_flag=False
elif arr[left][2] != -1:
next_left = arr[left][2]
left_flag=True
if right != -1:
if not right_flag:
child_width += arr[right][3]+1
else:
child_width -= arr[right][4]+1
if arr[right][2] != -1:
next_right = arr[right][2]
right_flag=False
elif arr[right][1] != -1:
next_right = arr[right][1]
right_flag=True
next_width = width + child_width
res_width, res_level = go_down_from_root_to_leaf_with_calculating_width(arr, next_width, level+1, next_left, next_right, left_flag, right_flag)
if next_width < res_width:
return res_width, res_level
else:
return next_width, level+1
n = int(sys.stdin.readline())
arr = [[0,0,0,0,0] for _ in range(n+1)]
# [0:parent_num, 1:left_child_num, 2:right_child_num, 3:left_childs_count, 4:right_childs_count]
root_candidate = set(range(1, n+1))
leafs = []
for _ in range(n):
num, c1, c2 = map(int, sys.stdin.readline().split())
arr[num][1], arr[num][2] = c1, c2
if c1 != -1:
arr[c1][0] = -num
root_candidate.remove(c1)
if c2 != -1:
arr[c2][0] = num
root_candidate.remove(c2)
if c1 == c2 == -1:
leafs.append(num)
root = root_candidate.pop()
for leaf_num in leafs:
up_from_leaf_to_root_with_calculating_childs_num(arr, leaf_num)
left_child, right_child = arr[root][1], arr[root][2]
x, y = go_down_from_root_to_leaf_with_calculating_width(arr, 1, 1, left_child, right_child, False, False)
print(y, x)
|
class Node:
"""
A node that consists of a trie.
"""
def __init__(self, key, count=0, data=None):
self.key = key
self.count = count
self.children = {}
class Trie:
def __init__(self):
self.head = Node(None)
"""
트라이에 문자열을 삽입합니다.
"""
def insert(self, string):
curr_node = self.head
for char in string:
if char not in curr_node.children:
curr_node.children[char] = Node(char)
curr_node.count += 1
curr_node = curr_node.children[char]
"""
주어진 단어 string이 트라이에 존재하는지 여부를 반환합니다.
"""
def search(self, string):
curr_node = self.head
for char in string:
if char == '?':
return curr_node.count
if char in curr_node.children:
curr_node = curr_node.children[char]
else:
return 0
def solution(words, queries):
answer = []
front_trie_list = [Trie() for _ in range(100001)]
back_trie_list = [Trie() for _ in range(100001)]
for word in words:
back_trie = back_trie_list[len(word)]
back_trie.insert(word[::-1])
front_trie = front_trie_list[len(word)]
front_trie.insert(word)
for query in queries:
if query[0] == '?':
trie = back_trie_list[len(query)]
count = trie.search(query[::-1])
else:
trie = front_trie_list[len(query)]
count = trie.search(query)
answer.append(count)
return answer
print(solution(
["frodo", "front", "frost", "frozen", "frame", "kakao"], # words
["fro??", "????o", "fr???", "fro???", "pro?"] # queries
)) # result: [3, 2, 4, 1, 0]
print(solution(
["faaaa", "faaab", "faaac", "faaa", "faaaaa", "faaaab"],
["f????"]
))
print(solution(
["f"],
["?"]
)) |
from math import log2
n = int(input())
k = int(log2(n / 3))
stage = [[' '] * n * 2 for _ in range(n)]
def change_for_star(y, x):
stage[y-2][x+2] = '*'
stage[y-1][x+1] = stage[y-1][x+3] = '*'
stage[y][x] = stage[y][x+1] = stage[y][x+2] = stage[y][x+3] = stage[y][x+4] = '*'
def tri(y, x, count):
if count == 0:
change_for_star(y, x)
return
tmp = 3 * 2 ** (count-1)
tri(y - tmp, x + tmp, count-1)
tri(y, x, count-1)
tri(y, x + 2 * tmp, count-1)
tri(n-1, 0, k)
for i in stage:
print(''.join(i)) |
class Node:
def __init__(self, item):
self.item = item
self.count = 0
self.next = []
def insert(node, ch):
if not node.next:
node.next.append(Node(ch))
for i in node.next:
if i.item == ch:
return i
node.next.append(Node(ch))
return node.next[-1]
def insert_word(tree, reverse, word):
wlist = list(word)
# 정방향
head = tree
head.count += 1
for i in wlist:
head = insert(head, i)
head.count += 1
# 역방향
head = reverse
head.count += 1
for i in wlist[::-1]:
head = insert(head, i)
head.count += 1
def find_query(tree, word):
only_word = word.replace('?', '')
head = tree
for i in list(only_word):
if not head.next:
return 0
for j in head.next:
if j.item == i:
head = j
break
return head.count
def solution(words, queries):
answer = []
tree = [Node('0') for _ in range(100000)]
tree_reverse = [Node('0') for _ in range(100000)]
for i in words:
insert_word(tree[len(i) - 1], tree_reverse[len(i) - 1], i)
for i in queries:
if i[0] != '?':
answer.append(find_query(tree[len(i) - 1], i))
else:
answer.append(find_query(tree_reverse[len(i) - 1], i[::-1]))
return answer
if __name__ == "__main__":
# print(solution(["frodo", "front", "frost", "frozen", "frame", "kakao"],
# ["fro??", "????o", "fr???", "fro???", "pro?", "?????", "??????"]))
print(solution(
["frodo", "front", "frost", "frozen", "frame", "kakao"], # words
["fro??", "????o", "fr???", "fro???", "pro?"] # queries
)) # result: [3, 2, 4, 1, 0]
print(solution(
["faaaa", "faaab", "faaac", "faaa", "faaaaa", "faaaab"],
["f????"]
))
print(solution(
["f"],
["?"]
))
print(solution(
["faaaa", "faaab", "faaac", "faaa", "faaaaa", "faaaab"],
["?????"]
))
print(solution(
["faaaa", "faaab", "faaac", "faaa", "faaaaa", "faaaab"],
["????"]
))
|
class Account():
_money = 0
def deposit(self, value):
convertido = 0
try:
convertido = float(value)
except:
raise ValueError("Valor deve ser numerico")
if (convertido < 0 ):
raise ValueError("Valor deve ser positivo")
self._money += convertido
return True
def withdraw(self, value):
if (value == 0):
raise ValueError("Saque deve ser maior que zero")
if (value > self._money):
raise ValueError("Saldo Insuficiente")
self._money -= value
def printStatement(self):
return self._money
|
#!/usr/bin/python3
# encoding: utf-8
'''
FileSort -- Sorts files based on their EXIF data or file date.
FileSort is a Python program to sort files based on their EXIF or
file date.
It defines classes_and_methods
@author: Alexander Hanl (Aalmann)
@copyright: 2018. All rights reserved.
@license: MIT
@deffield updated: Updated
'''
from file_sort.fs_main import main as fs_main, run as fs_run
def run():
# main(sys.argv[1:])
return fs_run()
if __name__ == "__main__":
'''
main
'''
import sys
sys.exit(fs_main())
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main(x,y):
# Use try except to catch specific error instead of the system printing
# out whole list of tracebacks
try:
x = int(x)
y = int(y)
z = x/y
except ValueError:
print("I caught a ValueError")
except ZeroDivisionError:
print("Cannot divide a number by zero")
except: # we can also not specify any error type in try-except
print("Unknown error")
else:
print("Good job")
print("The answer of {} divided by {} is {}".format(x, y, z))
if __name__ == '__main__':
main(200, 500)
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
s = 'This is a long string with a bunch of words in it.'
print(s)
# split a string
l = s.split()
print(l)
# split by a specific character
print(s.split("i"))
# join a list into string
s2 = ":".join(l)
print(s2) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
true_subset_zero.py
Implementing the true subset puzzle.
@author: Luis Martin Gil
@contact: martingil.luis@gmail.com
@website: www.luismartingil.com
@github: https://github.com/luismartingil
'''
import unittest
MIN_RANGE = -65000
MAX_RANGE = 65000
class itemNotRange(Exception):
pass
def subset_zero(array, iterations=None):
""" Receives a list of integers in the range [-65000, 65000] and
returns True if any subset of the list summed is equal to zero.
False otherwise.
Implementation based on a Set.
Taking advantage of the Integer nature of the problem.
"""
# PRE. array is a list of integers
found, myset = False, set([])
for elem in array:
if not (MIN_RANGE < elem < MAX_RANGE):
raise itemNotRange('Found item out of the range. %s' % elem)
# >>> Debugging iterations
if iterations is not None:
iterations.append((elem, list(myset)))
# <<< End debug iterations
# Lets find subsets
if (elem == 0 or (elem * -1) in myset):
found = True
break
else:
map(lambda x : myset.add(x + elem), myset.copy()) # .copy() overhead!
myset.add(elem)
# end for
return found
# Lets work on some unittests
tests_true = [
[0],
[33, -15, 1, 2, 3, 1, -5],
[1, 2, -3],
[7, 3, 4, -1, -1, 2, 7, 8],
[1, 4, 5, 2, -3],
[1, 4, 5, 2, -7],
[10, 40, 5, 2, -60, 5],
[10, 40, 5, 1, -60, 9],
[5, 2, 1, 10, -13],
[-15, 5, 5, 5],
[15, 5, -1, -2, -17, 5, 5, 5, 5, 5, 5, 5, -1, -4],
]
tests_false = [
[],
[1, 2, -5],
[1, 1, 5, 11],
[60, 1, 1, 5, 60],
[10, -1, -3, 6, 10, 6, 10],
]
class Test_Apply(unittest.TestCase):
pass
def test_Function_subset_zero(t, desired):
def test(self):
if desired:
self.assertTrue(subset_zero(t))
else:
self.assertFalse(subset_zero(t))
return test
def attach(where, desc, fun, l, desired):
""" Attaches tests. DRY function helper. """
for a, b in [("test-%s-%.6i" % (desired, l.index(x)), fun(x, desired)) \
for x in l]:
setattr(where, a, b)
def suite():
test_suite = unittest.TestSuite()
attach(Test_Apply,
"test_Function_subset_zero_true",
test_Function_subset_zero,
tests_true,
True)
attach(Test_Apply,
"test_Function_subset_zero_false",
test_Function_subset_zero,
tests_false,
False)
test_suite.addTest(unittest.makeSuite(Test_Apply))
return test_suite
if __name__ == '__main__':
test = True
iterations = True
if test:
mySuit=suite()
runner=unittest.TextTestRunner(verbosity=2)
runner.run(mySuit)
print 'Should be %i tests' % (len(tests_true) + len(tests_false))
print '~' * 60
if iterations:
# Lets get the iterations
array, ite = [1, 1, 2, -10, 8], []
print 'resolving array: %s' % array
result = subset_zero(array, iterations=ite)
print 'result: %s' % (result)
for value, list_status in ite:
print '%10s %s' % (value, list_status)
|
#Accepting the string
s=input("Enter the word ")
#Using dict.get()
r={}
for keys in s:
r[keys]=r.get(keys,0)+1
#printing the result
print("No. of characters in "+s+" is : \n"+str(r))
|
def longest_seq(nums):
numSet = set(nums)
res = 0
for n in nums:
if n+1 in numSet:
currLen = 0
while n+currLen in numSet:
currLen += 1
res = max(res, currLen)
return res
print(longest_seq([100,4,200,2,3,1]))
|
#!/usr/bin/python
"""
Demonstration of Graph functionality.
"""
from sys import argv
from graph import Graph, Node
def main():
graph = Graph() # Instantiate your graph
graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_vertex(4)
graph.add_vertex(5)
graph.add_vertex(6)
graph.add_vertex(7)
graph.add_directed_edge(5, 3)
graph.add_directed_edge(6, 3)
graph.add_directed_edge(7, 1)
graph.add_directed_edge(4, 7)
graph.add_directed_edge(1, 2)
graph.add_directed_edge(7, 6)
graph.add_directed_edge(2, 4)
graph.add_directed_edge(3, 5)
graph.add_directed_edge(2, 3)
graph.add_directed_edge(4, 6)
for node in graph.vertices:
print(node, graph.vertices[node].edges)
print(graph.all_vertices())
main()
|
#find a 3x3 non singular matrix
import numpy as np
# initialize array A and Identity matrix
B= np.array([[2, 0, -1],[0, 2, -1],[-1, 0, 1]])
I= np.identity(3)
A= 3*I - B
print(A) |
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
# Note: try to reduce running time for some extreme cases (long input)
class Solution(object):
""" solution that are not optimized
def twoSum(self, numbers, target):
if (len(numbers) < 2):
return None
for i, x in enumerate(numbers):
for j, y in enumerate(numbers[i+1:]):
if ((x+y) == target):
return i+1, i+1+j+1
if ((x + y) > target):
break
return None
"""
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
# beat 60%
def twoSum(self, numbers, target):
if numbers is None or len(numbers) < 2:
return None
i = 0
j = len(numbers)-1
while i != j:
if numbers[i] + numbers[j] == target:
return i+1, j+1
elif numbers[i] + numbers[j] > target:
j-=1
else:
i+=1
return None
if __name__ == "__main__":
s = Solution()
#numbers = [2,3,4]
#target = 6
numbers = [2, 7, 11, 15]
target = 9
print (s.twoSum(numbers, target)) |
import math
def quadratic(a,b,c):
if not isinstance(a and b and c,(int,float)):
raise TypeError('bad operand type')
drt=b*b-4*a*c
if drt<0:
print("该方程无解")
return None,None
else:
x=(-b+math.sqrt(b*b-4*a*c))/2*a
y=(-b-math.sqrt(b*b-4*a*c))/2*a
return x,y
x1,x2=quadratic (2,2,2)
print(x1,x2)
def product(*numbers):
if numbers==0:
raise TypeError
sum = 1
for n in numbers:
sum=sum*n
return sum
x=product(1,2,3,4,5)
print(x)
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
x=fact(6)
print(x) #递归函数
|
class Student():
name = "dana"
age = 18
def say(self):
self.name = "aaaa"
self.age = 200
print("My name is {0}".format(self.name))
print("My age is {0}".format(self.age))
def sayAgain(s):
print("My name is {0}".format(s.name))
print("My age is {0}".format(s.age))
yueyue = Student()
yueyue.say()
yueyue.sayAgain()
###############################
print("***********************************")
class A():
name = "liuying"
age = 18
def __init__(self):
self.name = "aaa"
self.age = "200"
def say(self):
print(self.name)
print(self.age)
class B():
name = "bbb"
age = 90
a = A()
#a.say()
#A.say(a)
A.say(A)
#A.say(B)
#########################
'''
封装的三个级别:
- 公开:public
- 受保护的:protected
- 私有的:private
私有成员是最高级别的封装 加两个下划线
''' |
# -*- coding: utf-8 -*-
'''
Created on 2019年9月4日
@author: Administrator
'''
from tkinter import *
import math
class MainPage(object):
def __init__(self, master=None):
self.root = master #定义内部变量root
self.root.geometry('%dx%d' % (300, 250)) #设置窗口大小
self.year = IntVar()
self.date = IntVar()
self.instruction=IntVar()
self.salary=IntVar()
self.createPage()
def createPage(self):
self.page = Frame(self.root) #创建Frame
self.page.pack()
Label(self.page,text="年份:").grid(row=0,column=0)
Label(self.page,text="字长:").grid(row=1,column=0)
Label(self.page,text="指令:").grid(row=2,column=0)
Label(self.page,text="工资(美元):").grid(row=3,column=0)
Label(self.page,text="需求(字):").grid(row=4,column=0)
Label(self.page,text="储存器价格(美元):").grid(row=5,column=0)
Label(self.page,text="成本(美元):").grid(row=6,column=0)
self.e1=Entry(self.page,textvariable=self.year)
self.e2=Entry(self.page,textvariable=self.date)
self.e3=Entry(self.page,textvariable=self.instruction)
self.e4=Entry(self.page,textvariable=self.salary)
self.e5=Entry(self.page)
self.e6=Entry(self.page)
self.e7=Entry(self.page)
self.e1.grid(row=0,column=1,padx=10,pady=5)
self.e2.grid(row=1,column=1,padx=10,pady=5)
self.e3.grid(row=2,column=1,padx=10,pady=5)
self.e4.grid(row=3,column=1,padx=10,pady=5)
self.e5.grid(row=4,column=1,padx=10,pady=5)
self.e6.grid(row=5,column=1,padx=10,pady=5)
self.e7.grid(row=6,column=1,padx=10,pady=5)
Button(self.page,text="确定",width=10,command=self.show).grid(row=7,column=0,sticky=W)
Button(self.page,text="退出",width=10,command=self.page.quit).grid(row=7,column=1,sticky=E)
def show(self):
a=self.year.get()
b=self.date.get()
e=self.instruction.get()
f=self.salary.get()
c=math.exp(0.28*(a-1960))*4080
c1=round(c,2)
d=0.003*b*0.72**(a-1974)*c
d1=round(d,2)
g=(f/(e*30))*c1
g1=round(g,2)
self.e5.insert(0,c1)
self.e6.insert(0,d1)
self.e7.insert(0,g1)
|
#!/usr/bin/env python
from __future__ import print_function
import random
import sys
import os
def addnos(fnum, lnum):
"""
function to add 2 numbers together
"""
sumnos = fnum + lnum
return(sumnos)
def main(args):
help(addnos)
#print("add 2 nos together-->", addnos(5,7))
stringnos = addnos(5,7)
print(stringnos)
if __name__ == '__main__':
main(sys.argv[1:])
|
#!/usr/bin/env python
import numpy as np
import sys
def read_unstructured_data():
"""
Read unstructured data, ie. mixed data types
"""
#
# Assign the filename: file
#
filename = "C:\\Users\mdjuk\\repos\\q_python_scripts\\titanic.csv"
data = np.genfromtxt(filename, delimiter=',', names=True, dtype=None)
for i in data['Survived'] :
if i == 1 :
print("data from titanic.csv-->%s" %(i))
def recfromcsv_func():
"""
reading recs from file, via readfromcsv
"""
print("Start of recfromcsv")
filename = "C:\\Users\mdjuk\\repos\\q_python_scripts\\titanic.csv"
#d = np.recfromcsv(filename, delimiter=',', names=True, dtype=None)
d = np.genfromtxt(filename, delimiter=',', names=True, dtype=None)
#
# print first 3 records
#
#print("recs from recfromcsv_func-->%s" %(d[:3]))
for i in d['Survived'] :
if i == 1 :
print("data from titanic.csv-->%s" %(i))
def main(args):
help(read_unstructured_data)
read_unstructured_data()
help(recfromcsv_func)
recfromcsv_func()
if __name__ == '__main__':
main(sys.argv[1:])
###
|
#!/bin/env python
'''
from __future__ import print_function
from datetime import datetime
import os
import sys
import types
def main(args):
pass
if __name__ == '__main__':
print ('Start of XXXX.py at.....', format(str(datetime.now())))
main(sys.argv[1:])
print ('End of XXXX.py at.....', format(str(datetime.now())))
'''
###
from __future__ import print_function
import os
import sys
from datetime import datetime
def main(args):
# reverse a string
a = "markodjukic"
print('1. Reversing a sting-->', a, "-->", a[::-1])
# transposing a matrix
mat = [[1,2,3], [4,5,6]]
print('2. Transposing a matrix-->', mat, "-->", zip(*mat) )
# store all 3 values of the list in 3 new variables
a = [1,2,3]
x, y, z = a
print("x-->", x, "y-->", y, "z-->", z)
# create a single string from all the elements in the list above
a = ["Code", "mentor", "Python", "Developer"]
print (" ".join(a) )
# write python code to print
list1=['a', 'b', 'c', 'd']
list2=['p', 'q', 'r', 's']
for x, y in zip(list1, list2):
print (x,y)
# swap two numbers with one line of code
a = 7
b = 5
print('Before swap-->', 'a-->', a, 'b-->', b)
b, a = a, b
print('After swap-->', 'a-->', a, 'b-->', b)
# print "codecodecodecode mentormentormentormentormentor" without using loops
print("code"*4 +' '+ "mentor"*5)
# Convert the following list to a single list without using any loops
a = [[1,2], [3,4], [5,6]]
# result: [1, 2, 3, 4, 5, 6]
import itertools
print(list(itertools.chain.from_iterable(a)))
# taking a string input - need to run this via REPL, and enter input
result = map(lambda x:int(x) ,raw_input().split())
print(result)
if __name__ == '__main__':
print('Start of script 10PythonTricks-->', format(str(datetime.now())))
main(sys.argv[1:])
print('End of script 10PythonTricks-->', format(str(datetime.now())))
|
#!/usr/bin/env python
from __future__ import print_function
import random
import sys
import os
class Bird:
"""
A base class to define bird properties
"""
count = 0
def __init__(self, chat):
self.sound = chat
Bird.count += 1
def talk(self):
return(self.sound)
"""
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def get_name(self):
return(self.__name)
""" |
from __future__ import print_function # need this to allow print function to work with ()
from datetime import datetime
import os
import sys
import types
def main(args):
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print ("A0-->", A0)
print ("A1-->", A1)
print ("A2-->", A2)
print ("A3-->", A3)
print ("A4-->", A4)
print ("A5-->", A5)
print ("A6-->", A6)
A1 = range(10)
help(zip)
f(2,[]) # [0, 1]
f(3,[3,2,1]) # [3, 2, 1, 0, 1, 4]
f(3) # [0, 1, 4]
f(10) # [0, 1, 4, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Monkey patching - changing the behaviour of a function from what it was initially designed to do
def f(*args,**kwargs):
print(args, kwargs)
l = [1,2,3]
t = (4,5,6)
d = {'a':7,'b':8,'c':9}
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
if __name__ == '__main__':
print ('Start of dict.py at.....', format(str(datetime.now())))
main(sys.argv[1:])
print ('End of dict.py at.....', format(str(datetime.now())))
# Start of dict.py at {}..... 2017-04-24 13:06:03.310000
# A0--> {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
# A1--> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# A2--> []
# A3--> [1, 2, 3, 4, 5]
# A4--> [1, 2, 3, 4, 5]
# A5--> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# A6--> [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
|
#!/usr/bin/env python
from __future__ import print_function
import os, sys
def dataline ():
"""
this will load data as expected
"""
emp_str_1 = '"1","0","3","male","22.0","1","0","A/5 21171","7.25","","S"'
(PassengerId,Survived,Pclass,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked) = emp_str_1.split(',')
print("PassengerId-->", PassengerId)
print("Age-->", Age)
def main(args):
if __name__ == '__main__':
help(dataline)
dataline()
#
# PassengerId,Survived,Pclass,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
if __name__ == '__main__':
main(sys.argv[1:])
|
'''
Obtaining user input.....Page 20-21
the line below was initially 6 lines, and then selecting all lines, then Ctrl+Shift+L, Del at end of first line will
automatically join all of the lines together
days = ["1","2","3","4","5","6"]
'''
import sys
def main(args):
try:
print('Start of input.py.....\n')
user = raw_input("I am Python. What is your name? :")
# output a string and a variable value
print('Welcome', user)
print('\nEnd of input.py.....')
except EOFError:
print('\nEOFError encountered')
try:
text = input('Enter something: ')
print text
except EOFError:
print('\nEOFError')
# output a string and a variable value
if __name__ == "__main__":
main(sys.argv[1:])
|
#!/bin/env python
from __future__ import print_function
import sys
'''
sys.argv is a list of arguments.
So when you execute your script without any arguments this list which you're accessing index 1 of is empty
and accessing an index of an empty list will raise an IndexError.
With your second block of code you're doing a list slice and you're checking if the list slice
from index 1 and forward is not empty then print your that slice of the list.
Why this works is because if you have an empty list and doing a slice on it like this, the slice returns an empty list.
'''
def main(args):
last_list = [1,2,3]
if last_list[1:]:
print('Frist block [1:]', last_list[1:] )
#>> [2,3]
empty_list = []
print('First block [:1]', empty_list[:1] )
#>> []
if __name__ == '__main__':
main(sys.argv[1:])
|
'''
Obtaining user input.....Page 20-21
the line below was initially 6 lines, and then selecting all lines, then Ctrl+Shift+L, Del at end of first line will
automatically join all of the lines together
days = ["1","2","3","4","5","6"]
----------------------------------------------------------------------------------------------------
-- MULTIPLE CURSORS--> CTRL+ALT+UP/DOWN
----------------------------------------------------------------------------------------------------
Return to single selection mode: Esc
Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
Extend selection leftward/rightward at all carets: Shift + Left/Right
Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
Undo the last selection motion: Ctrl + U
Add next occurrence of selected text to selection: Ctrl + D
Add all occurrences of the selected text to the selection: Alt + F3
Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L
'''
import sys
def main(args):
num = 3
print num * 8 + 4
print num * ( 8 + 4 )
# output a string and a variable value
if __name__ == "__main__":
main(sys.argv[1:])
|
import sys
'''
CTRL-S to save the file
CTRL-B to build the file, ie to run it
'''
def main(args):
print("Start of script")
# define 2 varables
a = 8
b = 2
# display th result of adding the variable values
print 'Addition\t', a, "+", b, "=", a + b
# display the result of subtraction th variable values
print 'Subtraction\t', a, '-', b, '=', a - b
# display the result of multiplying the varable names
print 'Multiplication\t', a, '*', b, '=', a * b
# display the result of dividing the variable values
print 'Division\t', a, '/', b, '=', a / b
# display the result of dividing the variabl evalues both with and without the floating-point value
print 'Floor Division\t', a, '/', b, '=', a // b
# display the result of the remainder after dividing the values
print 'Modulus\t', a, '%', b, '=', a % b
# display the result of raising the first operand to the power of the second
print 'Exponent\t', a, '**', b, '=', a ** b
print 'Exponent\t', a, '**', b, '=', a ** b, sep=' '
# NOTE: you can use the sep parameter to explicitly specify the separation between output
print("End of script")
#
# call the main function with arguments passed
#
if __name__ == "__main__" :
main(sys.argv[1:])
|
# python -m unittest anagrams_test.py
import unittest
from assignment2 import Node, BinaryTree, Solution
class TestSolution(unittest.TestCase):
def setUp(self):
# replace this with function construct_binary_tree_from_list
self.binary_tree1 = Node(1)
self.binary_tree1.left = Node(2)
self.binary_tree1.right = Node(3)
self.binary_tree2 = Node(1)
self.binary_tree2.left = Node(2)
self.binary_tree2.right = Node(3)
self.binary_tree2.left.left = Node(4)
self.binary_tree2.left.right = Node(5)
self.binary_tree2.right.left = Node(6)
# binary tree in assignment2 example
self.binary_tree3 = Node(7)
self.binary_tree3.left = Node(3)
self.binary_tree3.right = Node(4)
self.binary_tree3.left.left = Node(2)
self.binary_tree3.left.right = Node(5)
self.binary_tree3.right.right = Node(8)
self.binary_tree3.left.left.left = Node(1)
self.binary_tree3.left.left.right = Node(6)
##########
def test_find_node(self):
self.assertEqual(Solution().find_node(self.binary_tree1, 2), self.binary_tree1.left)
self.assertNotEqual(Solution().find_node(self.binary_tree1, 2), self.binary_tree1.right)
self.assertEqual(Solution().find_node(self.binary_tree1, 10), None)
self.assertEqual(Solution().find_node(None, 10), None)
def test_find_ancestors(self):
self.assertEqual(Solution().find_ancestors(self.binary_tree3, 6), [2, 3, 7])
self.assertNotEqual(Solution().find_ancestors(self.binary_tree3, 6), [2, 3, 10])
self.assertEqual(Solution().find_ancestors(self.binary_tree3, 7), [])
"""
def test_common_ancestor(self):
self.assertEqual(Solution().common_ancestor(self.binary_tree3, self.binary_tree3.left.right, self.binary_tree3.left.left.right), self.binary_tree3.left)
""" |
print "Hello"
peremen1=0
peremen2=0
spisok1 = []
def spisok():
while len(spisok1) in range(15):
s=input("Enter number ")
spisok1.append(s)
return spisok1
spisok()
while peremen2 == 0:
if spisok1[peremen1] == 0:
print " Index is " , spisok1.index(spisok1[peremen1])
peremen2=1
peremen1=peremen1+1
|
print "Hello"
spisok1 = []
peremen1=0
def spisok():
while len(spisok1) in range(15):
s=input("Enter number ")
spisok1.append(s)
return spisok1
spisok()
minimum=spisok1[0]
while peremen1 != 15:
if minimum > spisok1[peremen1]:
minimum=peremen1
peremen1=peremen1+1
elif minimum <= spisok1[peremen1]:
peremen1=peremen1+1
print "Minimum is " , minimum
print "Index is " , spisok1.index(minimum)
|
class Fib(object):
def __init__(self):
self.prev=0
self.curr=1
def __next__(self):
value = self.curr
self.curr+=self.prev
self.prev=value
yield value
def func(n):
for i in range(n):
yield i**2
print(func(5)) |
r= input("doner le rayon de cercle")
m=int(r)
surf = 3.14 * (m**2)
perim = 3.14 * 2 *m
print("la surface du cercle est :",surf ,"et le perimetre est :",perim)
|
#exo11calcul
a=input("veuillez saisir la valeur de a")
a=int(a)
op=input("taper 1 pour l'addition , 2 pour la soustraction , 3 pour la multiplication et 4 pour la division " )
op=int(op)
b=input("veuillez saisir la valeut de b")
b=int(b)
if (op ==1):
print (a+b)
if (op ==2):
print(a-b)
if (op==3):
print(a*b)
if (op ==4):
print(a/b) |
#exo25suitenom
for i in range (1,11):
print(i*[i])
#-----commmit-------
a=int(input("veuillez saisir un entier a"))
div = a//2
if (a == 2 or a==3):
print (a, "est un nombre premier")
div = 0
for i in range (4 , div+1):
div = div + a % i
if (div != 0):
print(a , " est pas premier")
if (div == 0):
print(a , " n'est pas premier") |
# NLP Program to identify dollar amount in the txt file, it will output the dollar amount included in the txt file
# @Author: Yulong He 2020.02.07
# Possible format for identification:
# $500 million/billion/trillion
# $6.57
# 1 dollar and 7 cents
# 5 cent/cents
# one/two/three hundred/hundreds/million/billion... dollar/dollars
import re
import sys
# Open the text file with 16MB buffer to handle larger file
def main():
with open(sys.argv[1], 'r', 16777216) as file:
data = file.read()
# regex word expression:
# ([\d]*\sdollar\sand\s[\d]*\scents)|
# ([\d]*\sdollars\sand\s[\d]*\scents)|
# ([\d]*\sdollar\sand\s[\d]*\scent)|
# ([\d]*\sdollars\sand\s[\d]*\scent)|
# (^\$?[\d]*\smillion)|
# (^\$?[\d]*\sbillion)|
# (^\$?[\d]*\stillion)|
# (^\$?[\d]{0,2}\sdollar)|
# (^\$?[\d]{0,2}\sdollars)|
# (^\$?[\d]*\scents)|
# (^\$?[\d]*\scent)|
# ((\bone\b|\btwo\b|\bthree\b|\bfour\b|\bfive\b|\bsix\b|\bseven\b|\beight\b|\bnine\b)+\s+(hundred|thousand|million|billion|trillion)+\s+(dollars|dollar))
regex_word = r"([\d]*\sdollar\sand\s[\d]*\scents)|([\d]*\sdollars\sand\s[\d]*\scents)|([\d]*\sdollar\sand\s[\d]*\scent)|([\d]*\sdollars\sand\s[\d]*\scent)|(^\$?[\d]*\smillion)|(^\$?[\d]*\sbillion)|(^\$?[\d]*\stillion)|(^\$?[\d]{0,2}\sdollar)|(^\$?[\d]{0,2}\sdollars)|(^\$?[\d]*\scents)|(^\$?[\d]*\scent)|((\bone\b|\btwo\b|\bthree\b|\bfour\b|\bfive\b|\bsix\b|\bseven\b|\beight\b|\bnine\b)+\s+(hundred|thousand|million|billion|trillion)+\s+(dollars|dollar))"
# regex number expression:
regex_numbers = r"(\$\s?([\d]*[,]?){0,}[.]?[\d]{0,2})"
test_str = data
testStrWordEliminatedList = []
dollarNumbersList = []
testStrWordEliminated = test_str
# Match for dollar, dollars, cent, cents, million, billion, trillion
matches_word = re.finditer(regex_word, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches_word, start=1):
testStrWordEliminatedList.append(match.group().strip('.,'))
# Eliminate the noise from previous match
for i in testStrWordEliminatedList:
testStrWordEliminated = testStrWordEliminated.replace(i, '1')
# Find the numeric numbers, including dollar sign.
matches_numbers = re.finditer(regex_numbers, testStrWordEliminated, re.MULTILINE)
for matchNum, match in enumerate(matches_numbers, start=1):
dollarNumbersList.append(match.group().strip('.,'))
# Combine two lists
resultList = testStrWordEliminatedList + dollarNumbersList
# Clean up Invalid results
for i in resultList:
if i == '$':
resultList.remove('$')
if i == '$ ':
resultList.remove('$ ')
if i == '$\n':
resultList.remove('$\n')
# Write list into the file
with open('dollar_output.txt', 'w', 16777216) as writeList:
writeList.writelines("%s\n" % word for word in resultList)
print('Result Exported as dollar_output.txt')
writeList.close()
file.close()
main()
|
import re, math
class Sci:
split = 'e'
sci_format = r'([+-]*\d+\.\d+)e([+-]*\d+)'
__num = 0.0
__exp = 0
def __init__(self, sci, int_size=1, float_size=3):
if isinstance(sci, int) or isinstance(sci, float):
if sci == math.inf: # If incoming Int or Float is too large
raise ValueError("Float number sent is too large, received 'inf'.")
else:
sci_format = '{' + ":.{0}e".format(float_size) + '}' # Construct the format string with float_len
sci = sci_format.format(sci) # Set as string to be processed below
if re.search(self.sci_format, sci): # 1.0e100
groups = re.search(self.sci_format, sci).groups()
self.__num = float(groups[0])
self.__exp = int(groups[1])
self.__fixBase(int_size, float_size)
else:
raise ValueError('Sci number should be in scientific notation: "1.00e100"')
#############################################################################################################
############################################# Operations ####################################################
#############################################################################################################
def __truediv__(self, other):
'''
self / other
'''
if type(other) in (str, int, float):
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
exp = self.__exp - sci_other.exp
num = self.__num / sci_other.num
return Sci(str(num)+'e'+str(exp))
def __rtruediv__(self, other):
'''
other / self
'''
if type(other) in (str, int, float):
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
exp = sci_other.exp - self.__exp
num = sci_other.num / self.__num
return Sci(str(-1*num)+'e'+str(exp))
def __floordiv__(self, other):
'''
self // other
'''
return self.__truediv__(other)
def __rfloordiv__(self, other):
'''
other // self
'''
return self.__rtruediv__(other)
def __mul__(self, other):
'''
self * other
'''
if type(other) in (str, int, float):
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
exp = self.__exp + sci_other.exp
num = self.__num * sci_other.num
return Sci(str(num)+'e'+str(exp))
def __rmul__(self, other):
'''
other * self
'''
if type(other) in (str, int, float):
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
exp = self.__exp + sci_other.exp
num = self.__num * sci_other.num
return Sci(str(num)+'e'+str(exp))
def __add__(self, other):
'''
self + other
'''
if type(other) in [str, int, float]:
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
smll = self if self.exp <= sci_other.exp else sci_other
bigr = self if self.exp > sci_other.exp else sci_other
diff = bigr.exp - smll.exp
exp = smll.exp + diff
num = smll.num / 10**diff
num = num + bigr.num
return Sci(str(num) + 'e' + str(exp))
def __radd__(self, other):
'''
other + self
'''
if type(other) in [str, int, float]:
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
smll = self if self.exp <= sci_other.exp else sci_other
bigr = self if self.exp > sci_other.exp else sci_other
diff = bigr.exp - smll.exp
exp = smll.exp + diff
num = smll.num / 10**diff
num = num + bigr.num
return Sci(str(num) + 'e' + str(exp))
def __sub__(self, other):
'''
self - other
'''
if type(other) in [str, int, float]:
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
smll = self if self.exp <= sci_other.exp else sci_other
bigr = self if self.exp > sci_other.exp else sci_other
diff = bigr.exp - smll.exp
exp = smll.exp + diff
num = smll.num / 10**diff
if smll.exp < 0:
num = bigr.num - num
else:
num = num - bigr.num
return Sci(str(num) + 'e' + str(exp))
def __rsub__(self, other):
'''
other - self
'''
if type(other) in [str, int, float]:
sci_other = Sci(other)
elif isinstance(other, Sci):
sci_other = other
smll = self if self.exp <= sci_other.exp else sci_other
bigr = self if self.exp > sci_other.exp else sci_other
diff = bigr.exp - smll.exp
exp = smll.exp + diff
num = smll.num / 10**diff
if smll.exp < 0:
num = bigr.num - num
else:
num = num - bigr.num
return Sci(str(num) + 'e' + str(exp))
#################################################################################################
#################################################################################################
#################################################################################################
def __str__(self):
return str(self.__num) + 'e' + str(self.__exp)
def __repr__(self):
return str(self.__num) + 'e' + str(self.__exp)
@property
def num(self):
return self.__num
@num.setter
def num(self, val):
self.__num = float(val)
@property
def exp(self):
return self.__exp
@exp.setter
def exp(self, val):
self.__exp = int(val)
def __fixBase(self, int_size =1, float_size=3):
'''
Fix exponential base
'''
int_len = len(str(int(abs(self.__num))))
# Fix Integer part of self.__num
if int_len > int_size:
self.__num = self.__num / (10**(int_len-int_size))
elif int_len < int_size:
self.__num = self.__num * (10**(int_size-int_len))
self.__exp = self.__exp - (int_size-int_len) # Fix EXP part
# Fix Float part of self.__num
self.__num = round(self.__num, float_size)
float_len = len(str(abs(self.__num)).split('.')[1])
if float_size and float_len > float_size:
self.__num = round(self.__num, float_size) |
password = input("Enter a new password: ")
result = []
if len(password) > 8:
result.append(True)
else:
result.append(False)
digit = False
for i in password:
if i.isdigit():
digit = True
result.append(digit)
uppercase = False
for i in password:
if i.isupper():
uppercase = True
result.append(uppercase)
print(result)
if all(result):
print("Strong Password")
else:
print("Weak Password") |
from modules.parsers import parse, convert
feet_inches = input("Enter feet and inches: ")
parsed_feet = parse(feet_inches)['feet']
parsed_inches = parse(feet_inches)['inches']
result = convert(parsed_feet, parsed_inches)
if result < 1:
print("Kid is too small.")
else:
print("Kid can use the slide.")
|
import csv
with open("../files/weather.csv", 'r') as file:
data = list(csv.reader(file))
city = input("Enter a city: ")
for row in data:
if row[0] == city:
print(f"Temparature of {row[0]} is {row[1]}")
|
password = input("Enter a new password: ")
result = {} # define a dictionary
if len(password) > 8:
result["length"] = True # equivalent of result.append(True) for lists
else:
result["length"] = False
digit = False
for i in password:
if i.isdigit():
digit = True
result["digits"] = digit
uppercase = False
for i in password:
if i.isupper():
uppercase = True
result["uppercase"] = uppercase
print(result)
if all(result.values()): # all values to be checked for Truth, not the keys
print("Strong Password")
else:
print("Weak Password") |
password_prompt = "Enter password: "
password = input(password_prompt)
while password != "pass123":
print("Incorrect password!")
password = input(password_prompt)
print("Password is correct!")
|
def parse(feet_inches):
parts = feet_inches.split(" ")
feet = float(parts[0])
inches = float(parts[1])
return {"feet": feet, "inches": inches}
def convert(feet, inches):
meters = feet * 0.3048 + inches * 0.0254
return meters
feet_inches = input("Enter feet and inches: ")
parsed_feet = parse(feet_inches)['feet']
parsed_inches = parse(feet_inches)['inches']
result = convert(parsed_feet, parsed_inches)
if result < 1:
print("Kid is too small.")
else:
print("Kid can use the slide.")
|
import json
"""
json.load(f): Load JSON data from file (or file-like object)
json.loads(s): Load JSON data from a string
json.dump(j, f): Write JSON object to a file (or file-like object)
json.dumps(j): Output JSON object as string
"""
# json_file = open("./test.json", "r")
# movie = json.load(json_file)
# json_file.close()
# print(movie)
# # Dump string value to json
# print(json.dumps(movie, ensure_ascii=False))
"""
Above code is equivalent to:
with open("test.json") as json_file:
movie = json.load(json_file)
print(movie)
"""
###############################################################################
value = """{"title": "Tron: Legacy",
"composer": "Daft Punk",
"release_year": 2010,
"budget": 17000000,
"actors": null,
"won_oscar": false
}"""
tron = json.loads(value)
print(tron)
print("tron title and budget are %s and %s respectively" % (tron["title"], tron["budget"]))
to_json_file = open("tron.json", "w")
json.dump(value, to_json_file, ensure_ascii=False)
to_json_file.close()
###############################################################################
|
vowel = ['A','E','I','O','U','a','e','i','o','u']
isVowel = input("Enter a character between a and z (or A and Z):")
if isVowel in vowel:
print(isVowel,'is a vowel: True')
else:
print(isVowel,'is a vowel: False')
|
inStock = [[],[],[],[],[],[],[],[],[],[]]
gamma = [11,13,15,17]
delta = [3,5,2,6,10,9,7,11,1,8]
from copy import deepcopy
def setZero():
alpha = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
beta = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
print('Alpha after initialization:\n',alpha)
return (alpha,beta)
alpha,beta = setZero()
def inputArray():
alpha = []
print('Enter 20 integers:')
for i in range(1,21):
number = int(input('{}:'.format(i)))
alpha.append(int(number))
return alpha
alpha = inputArray()
def doubleArray(alpha,beta):
beta = []
for i in alpha:
beta.append(i*2)
return beta
def copyGamma(newInStock,gamma):
newInStock[0] = gamma
num1 = gamma[0]
num2 = gamma[1]
num3 = gamma[2]
num4 = gamma[3]
for i in range(1,10):
num1 = num1*3
newInStock[i].append(num1)
num2 = num2*3
newInStock[i].append(num2)
num3 = num3*3
newInStock[i].append(num3)
num4 = num4*3
newInStock[i].append(num4)
return newInStock
def copyAlphaBeta(alpha,beta):
inStock = alpha + beta
return inStock
def printArray(alpha,beta):
print ('\nAlpha after reading 20 numbers:\n',alpha[0:10],'\n',alpha[10:20])
print ('\nBeta after a call to doubleArray:\n',beta[0:10],'\n',beta[10:20])
def setInStock(inStock,delta):
print('\nEnter 10 integers:')
for i in range(10):
num1 = int(input(''))
inStock[i].append(num1)
num2 = (num1*2)-(delta[i])
inStock[i].append(num2)
num3 = (num2*2)-(delta[i])
inStock[i].append(num3)
num4 = (num3*2)-(delta[i])
inStock[i].append(num4)
return inStock
beta = doubleArray(alpha[:],beta[:])
newInStock = deepcopy(inStock)
copyGamma = copyGamma(newInStock,gamma[:])
copyAlphaBeta = copyAlphaBeta(alpha[:],beta[:])
printArray(alpha,beta)
print ('\ninStock after a call to copyGamma:\n',copyGamma,sep=('\n'))
print ('\ninStock after a call to copyAlphaBeta:\n',copyAlphaBeta,)
setInStock = setInStock(inStock[:],delta)
print ('\ninStock after a call to setInStock:\n',setInStock)
|
import argparse
parser = argparse.ArgumentParser(description='Please input the company name')
parser.add_argument('--company', help='give the company name for permutation')
args = parser.parse_args()
company_name = args.company
def read_subdomain_list():
lines = []
with open("subdomains-top1mil-110000.txt", "r") as text_file:
lines = map(lambda x: x.replace('\n', ''), text_file.readlines())
return lines
def generate_permutation(company_name):
with open("permutation-{}.txt".format(company_name), "w") as permutation_file:
for element in read_subdomain_list():
permutation_str = company_name + '-' + element
permutation_file.write(permutation_str + '\n')
if __name__ == "__main__":
# execute only if run as a script
generate_permutation(company_name)
|
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = [0] * n1
R = [0] * n2
# Copy data to temp arrays L[] and R[]
for i in range(n1):
L[i] = arr[l + i]
for j in range(n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of left
j = 0 # Initial index of right
k = l # Initial index of merged
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def merge_sort(arr, l, r):
if l < r:
# if left < right index
# devide list into half
m = (l + r) // 2
# larr = arr[l:m]
# rarr = arr[m+1:r]
# merge_sort the left half
merge_sort(arr, l, m)
# merge_sort the right half
merge_sort(arr, m+1, r)
# merge the left and right
merge(arr, l, m, r)
a = [12, 46, 2, 8, 11, 6, 7, 9, 17]
n = len(a)
merge_sort(a, 0, n-1)
print(a) |
from collections import namedtuple
Car = namedtuple('Car', ['miles', 'color'])
car1 = Car(miles=100, color='red')
print(car1)
car1.miles = 200 # can't set attribute
|
from collections import deque
class MyQueue(object):
def __init__(self):
self.nodes = deque()
# self.head = None
def peek(self):
# print the head data
print(self.nodes[0])
def pop(self):
self.nodes.popleft()
def put(self, value):
if value:
self.nodes.append(value)
if __name__ == "__main__":
queue = MyQueue()
data = [
[1, 42],
[2],
[1, 14],
[3],
[1, 28],
[3],
[1, 60],
[1, 78],
[2],
[2],
]
for value in data:
if value[0] == 1:
queue.put(value[1])
elif value[0] == 2:
queue.pop()
else:
p = queue.peek()
if p:
print(p) |
"""Snake, classic arcade game with different modifications
Sebastin Joya
Maximiliano Carrasco
Gabriel Dichi
30/10/2020
"""
import random
from turtle import *
from random import randrange
from freegames import square, vector
speed=int(input('Please Write a number from 0 to 100 to chosee speed (while closer to the number 0, the speed would increase: '))
food = vector(0,0)
snake = [vector(10, 0)]
colors = ["green","blue","orange","purple","pink","yellow"]
color = random.choice(colors)
color2 = random.choice(colors)
aim = vector(0, -10)
def change(x, y):
"Change snake direction."
aim.x = x
aim.y = y
def inside(head):
"Return True if head inside boundaries."
return -200 < head.x < 190 and -200 < head.y < 190
def move():
"Move snake forward one segment."
head= snake[-1].copy()
head.move(aim)
i=0
if not inside(head) or head in snake:
square(head.x, head.y, 9, 'red')
update()
return
snake.append(head)
if head == food:
print('Snake:', len(snake))
food.x = randrange(-15, 15) * 10
food.y = randrange(-15, 15) * 10
else:
snake.pop(0)
clear()
for body in snake:
square(body.x, body.y, 9, color)
square(food.x, food.y, 9,color2)
update()
ontimer(move, speed)
setup(420, 420, 370,0)
hideturtle()
tracer(False)
listen()
"Snake move with alternative keys"
onkey(lambda: change(10, 0), 'd')
onkey(lambda: change(-10, 0), 'a')
onkey(lambda: change(0, 10), 'w')
onkey(lambda: change(0, -10), 's')
move()
done()
|
# Find the first 10 digits of the sum of the following 100 50-digit numbers:
# (see numbers here: https://projecteuler.net/problem=13)
# Answer: 5537376230
# Answer (the finalSum): 5537376230390876637302048746832985971773659831892672
# Here I wanted to build something robust - the site gives us uniformity but here we build for a sum of any possible numbers.
import sys
# truecount here will help us deal with the Python 'with open' file I'll use to import our numbers
def truecount(s):
return len(s)-s.count('\n')
# We'll define some bases for what I'll call on later
numberFile = "solve13_numberfile.txt"
numberFileLines = 0
maxLen = 0
bigSumCarry = 0
numbersArray = []
numbersLenArray = []
finalSum = ''
# Reads our numbers
with open(numberFile) as f:
numbers = f.readlines()
# Sends our numbers to internal memory for calculation, as well as gives us the largest number we'll be working with
for line in numbers:
numberFileLines += 1
numbersArray.append(line)
if truecount(line) > maxLen:
maxLen = truecount(line)
# These variables will give us the numbers we'll run with for our While loop
summingSize = len(str(sys.maxsize)) - len(str(9*numberFileLines))
summingRun = summingSize
summingRunL = 0
# This is the main function - it essentially teaches Python the way we deal with numbers in primary school
# We do addition in columns here - but we allow Python to use as many numbers as it possibly can
# For the problem we work with 7 columns at a time - and bigSum is the sum of those 7 columns
# We then teach it to carry the remainder on to the next iterations, and repeat until we have our finalSum
# We switch strings and integers here as we progress, so that we can make sure we only use the numbers we need
while (maxLen + summingSize) > summingRun:
bigSum = int(bigSumCarry)
for line in numbersArray:
if truecount(line) >= summingRunL:
endPosition = truecount(line)-summingRunL
startPosition = endPosition - summingSize
if startPosition < 0:
startPosition = 0
bigSum += int(line[startPosition:endPosition])
bigSumLen = len(str(bigSum))
bigSumCarry = str(bigSum)[:bigSumLen-summingSize]
finalSum = str(bigSum)[len(bigSumCarry):] + finalSum
summingRun += summingSize
summingRunL += summingSize
print(finalSum)
|
def solution(enter, leave):
answer = []
room = []
answer = [0] * (len(enter)+1)
i=0
while leave:
if leave[0] in room:
room.remove(leave[0])
leave.pop(0)
# print("if")
else:
# print("else")
for j in room:
answer[j] += 1
# print("answer :",answer)
answer[enter[i]] += len(room)
room.append(enter[i])
# print("room :",room)
i+=1
# print("answer :",answer)
answer.pop(0)
return answer |
'''
Run the application.Then open a browser and type in the URL http://127.0.0.1:5000/ ,
you will receive the string HELLO as a response, this confirms
that your application is successfully running.
The website will also display your HELLO [your name] when you type it in URL(http://127.0.0.1:5000/name)
'''
from flask import Flask #import the Flask object from the flask package
app=Flask(__name__)#creating your Flask application instance with the name app
@app.route("/")#pass '/' to signify that this function respond to main URL
def home():
return "HELLO"#returns string "HELLO"
@app.route("/<name>")#passing parametrs
def user(name):
return f"HELLO {name}"#returns string "HELLO"
if __name__=="__main__":
app.run()#run the development server. |
#!/usr/bin/python3
'''Reddit query using recursion'''
import requests
def recurse(subreddit, hot_list=[], after=''):
'''
Queries the Reddit API and returns a list containing the titles
of all hot articles for a given subreddit. If no results are
found for the given subreddit, the function returns None
'''
url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit)
headers = {'user-agent': 'Python3/requests_library/1'}
redirects = False
if len(hot_list) == 0:
request_subreddit = requests.get(url, headers=headers,
allow_redirects=redirects)
else:
data = {'after': after}
request_subreddit = requests.get(url, headers=headers, params=data,
allow_redirects=redirects)
if request_subreddit.status_code == 200:
subreddit_json = request_subreddit.json()
for children in subreddit_json['data']['children']:
hot_list.append(children)
end_value = subreddit_json['data']['after']
if end_value is None:
return hot_list
return recurse(subreddit, hot_list, end_value)
return None
|
from Player import *
import random
class Board():
def __init__(self,player1,player2,initsit=None):
if initsit==None:
self.players=[player1,player2]
p1Building=[[Building(1,player1),4],[Building(2,player1),3],[Building(3,player1),2],[Building(4,player1),1]]
p2Building=[[Building(1,player2),4],[Building(2,player2),3],[Building(3,player2),2],[Building(4,player2),1]]
self.playerBuildings=[p1Building,p2Building]
self.initGame()
def randomSelect(self):
if self.boards:
r=random.randint(0,len(self.boards)-1)
self.players[self.t].selectedBoard=self.boards[r]
del(self.boards[r])
return None
else:
return "No board left"
def chooseBuilding(self,level):
if self.playerBuildings[self.t][level-1][1]>0:
self.players[self.t].selectedBoard=self.playerBuildings[self.t][level-1][0]
else:
return "no building with that level left"
def putBoard(self,x,y):
if self.players[self.t].selectedBoard.isV==False:
self.playerBuildings[self.t][self.players[self.t].selectedBoard.level-1][1]-=1
self.playboard[x][y]=self.players[self.t].selectedBoard
self.players[self.t].selectedBoard=None
self.t=0 if self.t==1 else 1
def ifFinished(self):
for i in self.playboard:
if None in i:
return False
return True
def initGame(self):
self.boards=[]
self.t=0
for i in self.playerBuildings:
i[0][1]=4
for i in range(1,7):
self.boards.append(ValueBoard(-1*i))
self.boards.append(ValueBoard(i))
self.boards.append(ValueBoard(i))
self.boards.append(ValueBoard(7))
self.boards.append(ValueBoard(7))
self.boards.append(ValueBoard(8))
self.boards.append(ValueBoard(9))
self.boards.append(ValueBoard(10))
self.rowScore=[0 for i in range(5)]
self.colScore=[0 for i in range(6)]
self.playboard=[[None for i in range(6)]for j in range(5)]
#def showBoard(self):
# for i in self.playboard:
# for j in i:
# if j==None:
# print(" ",end=",")
# else:
# print(j.toString(),end=",")
# print()
def checkScore(self):
row=[]
col=[]
#process the witch
for i in range(5):
for j in range(6):
if self.playboard[i][j].value==10:
try:
if self.playboard[i-1][j].isV==False:
self.playboard[i-1][j]=Building(self.playboard[i-1][j].level+1,self.playboard[i-1][j].owner)
except Exception as e:
pass
try:
if self.playboard[i+1][j].isV==False:
self.playboard[i+1][j]=Building(self.playboard[i+1][j].level+1,self.playboard[i+1][j].owner)
except Exception as e:
pass
try:
if self.playboard[i][j-1].isV==False:
self.playboard[i][j-1]=Building(self.playboard[i][j-1].level+1,self.playboard[i][j-1].owner)
except Exception as e:
pass
try:
if self.playboard[i][j+1].isV==False:
self.playboard[i][j+1]=Building(self.playboard[i][j+1].level+1,self.playboard[i][j+1].owner)
except Exception as e:
pass
self.playboard[i][j].value=0
#process the mountain
for i in self.playboard:
smr=[]
for j in i:
if j.value!=7 :
if j.isV==True:
smr.append(j.value)
else:
smr.append(j)
else:
row.append(smr)
smr=[]
row.append(smr)
for i in range(6):
newcol=[]
for j in range(5):
if self.playboard[j][i].value!=7:
if self.playboard[j][i].isV==True:
newcol.append(self.playboard[j][i].value)
else:
newcol.append(self.playboard[j][i])
else:
col.append(newcol)
newcol=[]
col.append(newcol)
final=row+col
#process the dragon
for i in final:
if 8 in i:
for k in range(len(i)):
if isinstance(i[k],int):
if i[k]>0 and i[k]!=9:
i[k]=0
#process the gold
for i in final:
if 9 in i:
for k in range(len(i)):
if isinstance(i[k],int):
if i[k]!=9:
i[k]*=2
else:
i[k]=0
#calculate final score
for i in final:
score=0
l=[0,0]
for j in i:
if isinstance(j,int):
score+=j
# print(j,end="+")
else:
l[self.players.index(j.owner)]+=j.level
#print("="+str(score),end=",")
#print(l)
self.players[0].score+=l[0]*score
self.players[1].score+=l[1]*score
#def toString(self):
|
driving = input ('請問你有沒有開過車?')
if driving != '有' and driving != '沒有':
print('只能輸入 有/沒有 ')
raise SystemExit
age = int(input('請問你的年齡?'))
if driving == '有':
if age >= 18:
print('你通過測驗了')
else:
print('奇怪,你怎麼會開過車')
elif driving == '沒有':
if age >= 18:
print('你可以考駕照了')
else:
print('再幾年就可以去考了') |
#create dummy variables, these are helper functions
import pandas as pd
def cleanGender(x):
"""
This is a helper funciton that will help cleanup the gender variable.
"""
if x in ['female', 'mostly_female']:
return 'female'
if x in ['male', 'mostly_male']:
return 'male'
if x in ['couple'] :
return 'couple'
else:
return 'unknownGender'
def cleanBath(x):
"""
This is a helper function to cleanup the number of bathrooms
"""
#replacing 8+ rooms with 8 rooms
if x == '8+':
return 8
#if the value is less than 8 and is a number keep it!
if float(x) < 8:
return x
#all the other numbers look like garbage values
#replace those with 1 bathroom since that is 90% of all properties
else:
return 1
def cleanBedrooms(x):
"""
This is a helper function to cleanup the number of bedrooms
"""
#All the valid values appear to be <= 6
if float(x) <= 6:
return x
#replace those with 1 bedroom since that is 90% of all properties
else:
return 1
def cleanNumBeds(x):
"""
This is a helper function to cleanup the number of physical beds
"""
#All the valid values appear to be <= 6
if float(x) <= 9:
return x
#replace those with 1 bed since that is 90% of all properties
else:
return 1
def cleanNumBeds(x):
"""
This is a helper function to cleanup the number of physical beds
"""
#All the valid values appear to be <= 6
if float(x) <= 9:
return x
#replace those with 1 bed since that is 90% of all properties
else:
return 1
def cleanRespRate(x):
"""
This is a helper function to cleanup the response rate
"""
val = str(x).replace('%', '').replace('$', '').strip()
if str(x) == 'nan':
return 93.8
else:
return val
def dummyCode(x, cols = ['BookInstantly', 'Cancellation', 'RespTime', 'S_BedType', 'S_PropType', 'SD_PropType',
'HostGender']):
"""
This function turns selected categorical variables into dummy values
and appends the new dummy values onto the dataframe
"""
import pandas as pd
dfCopy = x[:]
dfCopy.RespRate = x.RespRate.apply(cleanRespRate)
dfCopy.Price = x.Price.apply(cleanRespRate)
dfCopy.HostGender = x.HostGender.apply(cleanGender)
dfCopy.S_Bathrooms = x.S_Bathrooms.apply(cleanBath)
dfCopy.S_Bedrooms = x.S_Bedrooms.apply(cleanBedrooms)
dfCopy.S_NumBeds = x.S_NumBeds.apply(cleanNumBeds)
for col in cols:
DC = pd.get_dummies(x[col], col)
dfCopy = pd.concat([dfCopy, DC], axis = 1)
#GitRid Of Columns That Were Dummy Coded
retainedCols = [a for a in dfCopy.columns if a not in cols]
return dfCopy[retainedCols]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PC## - Graffiti
# Howard, Bandoni
# 1/24/20
#
# This code draws Graffiti Spelling HI
#==========================
# -*- coding: utf-8 -*-
from turtle import * #fetches turtle commands
money = Screen() #create one canvas for all of your turtles.
money.screensize(400,600)
money.update()
money.bgcolor('white') #set the canvas color to white
money.bgpic("gradient1.gif") #background image color is pink and purple
money.update() #updates to draw any changes made to the canvas
#Start of drawing
cat = Turtle()
cat.pensize(15)
cat.pencolor("white")
cat.showturtle()
cat.up()
cat.left(180)
cat.down()
cat.up()
cat.forward(180)
cat.down()
cat.hideturtle()
cat.right(90)
cat.forward(180)
cat.showturtle()
cat.down()
cat.backward(90)
cat.right(90)
cat.forward(60)
cat.down()
cat.right(90)
cat.forward(90)
cat.right(180)
cat.forward(180)
cat.right(90)
cat.penup()
cat.forward(90)
cat.right(90)
cat.pendown()
cat.forward(180)
##hi number one white
cat.right(90)
cat.penup()
cat.forward(170)
cat.right(90)
cat.forward(10)
cat.pencolor("pink") #chnages pen color to pink
cat.pendown()
cat.forward(180)
cat.left(180)
cat.forward(90)
cat.left(90)
cat.forward(90)
cat.undo()
cat.left(90)
cat.forward(10)
cat.left(90)
cat.left(180)
cat.forward(60)
cat.right(90)
cat.right(180)
cat.forward(60)
cat.forward(20)
cat.right(180)
cat.forward(180)
cat.penup()
cat.left(90)
cat.forward(90)
cat.right(90)
cat.left(180)
cat.pendown()
cat.forward(180)
cat.hideturtle()
#end of hi number two
done()
|
while(True):
my_string = raw_input("Enter string to remove dups(Blank to terminate): ")
if (my_string == ""):
break;
|
# contains the sorting algorithms for the playlist searches
# 50 most popular
def get_fifty(d):
songs = sorted(d, key=d.get)
top_songs = []
i = 0
# add length methods for dictionaries shorter than 50
while(i < 50):
top_songs.append(songs[i])
i += 1
return top_songs |
"""
Alexander Hay
HW2 - Machine Learning
Learning aim: Motion model
Learning algorithm: Neural Network
Dataset: DS1
+ Training Data: (t, v, w) - odometry
(x, y, theta) - groundtruth
+ Test Data: (t, v, w) - odometry
Part A
1. build training set
2. code learning algorithm
"""
import numpy as np
np.random.seed(1) # for troubleshooting, can reproduce
def sigmoid(x):
"""
args: x - some number
return: some value between 0 and 1 based on sigmoid function
"""
return 1/(1+np.exp(-x))
def sigmoid_derivative(x):
"""
args: x - some number
return: derivative of sigmid given x
"""
x_prime = x*(1-x)
return x_prime
# t, v, w, x, y, dtheta
input = np.loadtxt('training_input.tsv')
# input = np.random.randint(9,size=(10,6)) # data simulating 10 instances of 6-dim input
output = np.zeros([len(input),3])
# x, y, theta
for i in range(len(input)):
"""
Motion Model
"""
time = input[i,0] # time
v = input[i,4] # linear velocity
w = input[i,5] # angular velocity
theta = w*time # dtheta = w*t
delta_x = (v*np.cos(theta)*time) # dx = vt*cos(theta)
delta_y = (v*np.sin(theta)*time) # dy = vt*sin(theta)
output[i,0] = delta_x
output[i,1] = delta_y
output[i,2] = theta
weights = np.random.random([6,3]) # starting weight for each column (synapse)
print "Starting Weights: "
print weights
print
for i in range(20000):
"""
neuron
"""
xw = np.dot(input,weights) # [4x3]*[3*1]=[4x1]
output = sigmoid(xw)
error = output - output
adjustments = error * sigmoid_derivative(output)
weights = weights + np.dot(input.T,adjustments)
print "Weights after training: "
print weights
print
|
"""
Alexander Hay
A* Algorithm
Part A:
1. Build grid cell of 1x1m, ranges x:[-2,5], y:[-6,6].
* Mark cells with landmarks
2. Implement A* Algorithm
3. Use algorithm to plan paths between the following sets of start/goal positions:
A: S=[0.5,-1.5], G=[0.5,1.5]
B: S=[4.5,3.5], G=[4.5-,1.5]
C: S=[-0.5,5.5], G=[1.5,-3.5]
* Display occupied cells
* Display explored cells
* Display planned path
4. Change program so that robot does not have 'a priori' knowledge of obstacles
5. Repeat step 3 with changes in program
6. Decrease cell size to 0.1x0.1m
* inflate size of landmarks to be 0.3m circles
7. Use algorithm to plan paths between the following sets of start/goal positions:
A: S=[2.45,-3.55], G=[0.95,-1.55]
B: S=[4.95,-0.05], G=[2.45,0.25]
C: S=[-0.55,1.45], G=[1.95,3.95]
* Display occupied cells
* Display explored cells
* Display planned path
"""
# a = open_list[0]
# print a.position
# print a.h
# print
import numpy as np
import matplotlib.pyplot as plt
import math
# global variables
barcodes = np.loadtxt('ds1_Barcodes.dat')
groundtruth = np.loadtxt('ds1_Groundtruth.dat') # position data from motion capture (may be taken as known information for filtering)
landmark = np.loadtxt('ds1_Landmark_Groundtruth.dat') # landmark data
measurement = np.loadtxt('ds1_Measurement.dat') # measurement data from robot
odometry = np.loadtxt('ds1_Odometry.dat') # time, forward v, angular v, measured from robot
class Node(object):
"""
creates attributes for each node in grid environment
Parameters:
parent --- tuple (x,y) of parent node, starting node has no parent
position - tuple (x,y) of itself
Attributes:
self.parent = parent node
self.position = (x,y)
self.g = distance from node to start
self.h = distance from node to goal (heuristic)
self.f = g + h (cost function)
"""
def __init__(self, parent=None, position=None):
self.parent = parent # set of coordinates
self.position = position # set of coordinates
self.g = 0
self.h = 0
self.f = self.g + self.h
class Grid(object):
"""
sets grid_map size and node cost
Parameters:
node size ----- float of the size of the node in meters
start --------- tuple (x,y) of start node
goal ---------- tuple (x,y) of goal node
Attributes:
start --------- starting node in grid coordinates
goal ---------- goal node in grid coordinates
landmark_list - list of landmarks (used for debugging)
xedges -------- an array of the x coordinates for nodes the grid_map is built of
yedges -------- an array of the y coordinates for nodes the grid_map is built of
node_cost ----- the cost of entering that node
Functions:
set_node ------ determines how many nodes to populate world with and their size
landmarks ----- converts landmark point to a node, sets node_cost of landmark node to 1000
world_to_grid - converts world points to their nodes points
"""
def __init__(self, size, start, goal):
# self.landmark_list = []
self.set_node(size)
self.start=self.world_to_grid(start)
self.goal=self.world_to_grid(goal)
def set_node(self, size):
"""
determines how many nodes to populate world with and their size
"""
self.xedges = np.arange(-2,5,size)
self.yedges = np.arange(-6,6,size)
self.node_cost = np.ones([len(self.xedges),len(self.yedges)]) # initiaizes each cell cost to be one
self.landmarks()
def landmarks(self):
"""
defines landmarks and their node cost
"""
inflate = 0.3 # Relevant for Part A #6 of HW1
for k in range(len(landmark)):
# print k
for i in range(len(self.xedges)): # row index
# print i
if landmark[k,1] >= self.xedges[i] and landmark[k,1] <= self.xedges[i]+1:
x = i
for j in range(len(self.yedges)): # col index
if landmark[k,2] >= self.yedges[j] and landmark[k,2] <= self.yedges[j]+1:
y = j
self.node_cost[x][y] = 1000 # cost of landmark
def world_to_grid(self, position): # world to grid
"""
translate world x,y to grid_map i,j
"""
for i in range(len(self.xedges)): # row index
if position[0] >= self.xedges[i] and position[0] <= self.xedges[i]+1:
x = self.xedges[i]
for j in range(len(self.yedges)): # col index
if position[1] >= self.yedges[j] and position[1] <= self.yedges[j]+1:
y = self.yedges[j]
return (x, y)
class Astar(object): #start, goal, grid_map):
"""
A* algorithm
Parameters:
start ------ raw start location
goal ------- raw goal location
grid_map --- map created by Grid class
Attributes:
start ------ start location relative to the grip map
goal ------- goal location relative to the grip map
Fuctions:
heuristic -- calculates the minimum cost from node location to goal
children --- returns a list of potential node children
validation - vets children against open and closed lists with their f and h values, returns updated open list sorted by f values
"""
def __init__(self, start, goal, grid_map):
# initiatialize costs
self.start = grid_map.world_to_grid(start)
self.goal = grid_map.world_to_grid(goal)
# print self.goal
start_node = Node(None,self.start)
goal_node = Node(None,self.goal)
start_node.g = 0 # distance from node to start
start_node.h = self.heuristic(start_node.position,goal_node.position) # distance from node to goal
start_node.f = start_node.g + start_node.h # cost function
open_list = [] # all generated nodes
closed_list = [] # all expanded nodes
open_list.append(start_node)
while open_list[0] != goal_node:
q = open_list[0]
if q.position == goal_node.position:
path = []
trace = q
while trace is not None:
path.append(trace.position)
trace = trace.parent
self.path=path
return #path
open_list.pop(0)
closed_list.append(q)
child_list = self.children(q, goal_node, grid_map)
open_list = self.validation(child_list, closed_list, open_list)
def heuristic(self, position, goal):
"""
calculates minimum cost from node to goal
transistion_cost is defined by Grid.node, but I don't know how to access that info, so it's redefined here
hypotenuse is the straight line distance to goal
cost is the hypotenuse times the transition cost
"""
transition_cost = 1 #grid.node_cost this should be defined by Grid.node cost I think but I don't know how to access that information
hypotenuse = (0.5) * math.sqrt((position[0] - goal[0])**2 + (position[1] - goal[1])**2)
cost = hypotenuse * transition_cost
# corner_cut = min(abs(position[0] - goal[0]), abs(position[1] - goal[1])) # returns x difference or y difference, whichever is shorter
# straight_dist = max(abs(position[0] - goal[0]), abs(position[1] - goal[1]))
# cost = (straight_dist + corner_cut) * transition_cost # cutting corners does not affect cost. moving diagonal=1, moving udlr=1
# # print "cost: " + str(cost)
return cost
def children(self, node, goal, grid_map):
"""
returns list of possible node children
"""
child_list = []
index = 0
for i in range(-1,2):
for j in range(-1,2):
position = (node.position[0] + i, node.position[1] + j)
# index = index + 1
child = Node(parent=node, position=position)
# print "child #: " + str(index)
# print "child position: " + str(child.position)
# print position
# print grid_map.node_cost
child.g = grid_map.node_cost[position[0]][position[1]] + child.parent.g
child.h = self.heuristic(child.position, goal.position)
child.f = child.g + child.h
if child.position == node.position:
continue
elif child.position[0] < grid_map.xedges[0] or child.position[0] > grid_map.xedges[-1]:
continue
elif child.position[1] < grid_map.yedges[0] or child.position[1] > grid_map.yedges[-1]:
continue
else:
child_list.append(child)
child_list.sort(key=lambda x: x.f)
# for i in range(len(child_list)):
# print "Child " + str(i) + ": " + str(child_list[i].position)
# print child_list[i].f
# print
return child_list
def validation(self, child_list, closed_list, open_list):
for i in range(len(child_list)):
# checks if child is in closed list
if (child_list[i] in closed_list):
for j in range(len(closed_list)):
# if child IS in closed list, checks if child.f is greater than closed.f
# if it IS greater, child is removed from the child_list
if child_list[i].f > closed_list[j].f:
# print yes
child_list.remove(child_list[i])
# if child IS in closed list, and if child.f EQUALS closed.f
# compares h values
# if child.h IS greater, child is removed from child list
elif child_list[i].f == closed_list[j].f:
if child_list[i].h > closed_list[j].h:
child_list.remove(child_list[i])
# if child IS NOT in closed list
# checks if child is in open list
if (child_list[i] in open_list):
for k in range(len(open_list)):
# if child IS in open list, checks if child.f is greater than open.f
# if it IS greater, child is removed from the child_list
if child_list[i].f > open_list[k].f:
child_list.remove(child_list[i])
# if child IS in open list, and if child.f EQUALS open.f
# compares h values
# if child.h IS greater, child is removed from child list
elif child_list[i].f == open_list[k].f:
if child_list[i].h > open_list[k].h:
child_list.remove(child_list[i])
# if child list passes all that, child is added to open list
# list is sorted by f
open_list.append(child_list[i])
open_list.sort(key=lambda x: x.f)
# a = open_list[0]
# print a.position
# print a.h
# print
return open_list
class Astar_online(object): #start, goal, grid_map):
"""
A* algorithm
Parameters:
start ------ raw start location
goal ------- raw goal location
grid_map --- map created by Grid class
Attributes:
start ------ start location relative to the grip map
goal ------- goal location relative to the grip map
Fuctions:
heuristic -- calculates the minimum cost from node location to goal
children --- returns a list of potential node children
"""
def __init__(self, start, goal, grid_map):
# initiatialize costs
self.start = grid_map.world_to_grid(start)
self.goal = grid_map.world_to_grid(goal)
start_node = Node(None,self.start)
goal_node = Node(None,self.goal)
start_node.g = 0 # distance from node to start
start_node.h = self.heuristic(start_node.position,goal_node.position) # distance from node to goal
start_node.f = start_node.g + start_node.h
open_list = [] # all generated nodes
open_list.append(start_node)
while open_list != goal_node:
q = open_list[0]
if q.position == goal_node.position:
path = []
trace = q
while trace is not None:
path.append(trace.position)
trace = trace.parent
self.path=path
return #path
open_list.pop(0)
child_list = self.children(q, goal_node, grid_map)
open_list = child_list
def heuristic(self, position, goal):
"""
calculates minimum cost from node to goal
transistion_cost is defined by Grid.node, but I don't know how to access that info, so it's redefined here
hypotenuse is the straight line distance to goal
cost is the hypotenuse times the transition cost
"""
transition_cost = 1 #grid.node_cost this should be defined by Grid.node cost I think but I don't know how to access that information
hypotenuse = (0.5) * math.sqrt((position[0] - goal[0])**2 + (position[1] - goal[1])**2)
cost = hypotenuse * transition_cost
# # print "cost: " + str(cost)
return cost
def children(self, node, goal, grid_map):
"""
returns list of possible node children
"""
child_list = []
index = 0
for i in range(-1,2):
for j in range(-1,2):
position = (node.position[0] + i, node.position[1] + j)
# index = index + 1
parent = node
child = Node(parent=parent, position=position)
# print "child #: " + str(index)
# print "child position: " + str(child.position)
child.g = grid_map.node_cost[position[0]][position[1]] + child.parent.g
child.h = self.heuristic(child.position, goal.position)
child.f = child.g + child.h
if child.position == node.position:
continue
elif child.position[0] < grid_map.xedges[0] or child.position[0] > grid_map.xedges[-1]:
continue
elif child.position[1] < grid_map.yedges[0] or child.position[1] > grid_map.yedges[-1]:
continue
else:
child_list.append(child)
child_list.sort(key=lambda x: x.f)
# for i in range(len(child_list)):
# print "Child " + str(i) + ": " + str(child_list[i].position)
# print child_list[i].f
# print
return child_list
def plot(grid,path,start,goal,num,method):
"""
plots grid_map information
"""
plt.imshow(grid.node_cost.T,origin='lower',extent=[-2,5,-6,6])
plt.plot(grid.start[0],grid.start[1],'go',label="Start Node")
plt.plot(grid.goal[0],grid.goal[1],'bo',label="Goal Node")
for i in range(len(path)):
dot = path[i]
plt.plot(dot[0],dot[1],'rx',label="Route")
ax = plt.gca();
ax.set_xticks(grid.xedges)
ax.set_yticks(grid.yedges)
plt.title('Figure ' + str(num) + ", " + method)
plt.xlabel("x position (m)")
plt.ylabel("y position (m)")
plt.grid(which='major',axis='both')
ax.legend()
plt.show()
def main():
"""
executes the assignment
Fuctions:
do_hw - automates inputs and parameters for hw questions.
"""
start_list1 = [(0.5,-1.5),(4.5,3.5),(-0.5,5.5)]
goal_list1 = [(0.5,1.5),(4.5,-1.5),(1.5,-3.5)]
start_list2 = [(2.45,-3.55),(4.95,-0.05),(-0.55,1.45)]
goal_list2 = [(0.95,-1.55),(2.45,0.25),(1.95,3.95)]
def do_hw(start,goal,i,method,size):
"""
Automates HW
Parameters:
start -- start location defined by hw problem
goal --- goal location defined by hw problem
i ------ iterator for figures
method - runs the algorithm offline or online, defined by hw problem
size --- sets the node size, defined by hw problem
"""
print "Set " + str(i) + ": "
if method == "Offline":
grid_map = Grid(size,start,goal)
astar = Astar(start, goal, grid_map)
print "Start Node: " + str(start)
print "Goal Node: " + str(goal)
print "Path: " + str(astar.path)
plot(grid_map,astar.path,start,goal,i,method)
elif method == "Online":
grid_map = Grid(size,start,goal)
astar = Astar_online(start, goal, grid_map)
print "Start Node: " + str(start)
print "Goal Node: " + str(goal)
print "Path: " + str(astar.path)
plot(grid_map,astar.path,start,goal,i+3,method)
print
print "Part A, #3"
for i in range(3):
do_hw(start_list1[i],goal_list1[i],i+1,"Offline",1)
print
print "Part A, #5"
for i in range(3):
do_hw(start_list1[i],goal_list1[i],i+1,"Online",1)
print
# print "Part A, #7"
# for i in range(3):
# do_hw(start_list2[i],goal_list2[i],i+1,"Offline",10)
# print
# print "Part A, #7*"
# for i in range(2):
# do_hw(start_list2[i],goal_list2[i],i+7,"Offline",10)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.