text stringlengths 37 1.41M |
|---|
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
def __init__(self, suits, ranks):
self.suits = suits
self.ranks = ranks
self.values = values[ranks]
def __str__(self):
return self.ranks + ' of ' + self.suits
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
created_card = Card(suit, rank)
self.all_cards.append(created_card)
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.all_player_cards = []
def add_card(self, new_card):
self.all_player_cards.append(new_card)
player_human = Player('Player')
player_bot = Player('Bot')
new_deck = Deck()
new_deck.shuffle()
game_on = True
bot_cards_value = 0
player_cards_value = 0
player_human.add_card(new_deck.deal_one())
player_human.add_card(new_deck.deal_one())
player_bot.add_card(new_deck.deal_one())
player_bot.add_card(new_deck.deal_one())
def bot_cards():
print('\nBot cards: ')
value = 0
for i in player_bot.all_player_cards[:-1]:
print(i)
value += i.values
print('And one card is hidden!')
print(f'Of value: {value} (without hidden card!)\n')
def player_cards():
print('\nYour cards: ')
value = 0
for i in player_human.all_player_cards:
print(i)
value += i.values
print(f'Of value: {value}\n')
ace = False
def counting_values():
global bot_cards_value
global player_cards_value
player_cards_value = 0
bot_cards_value = 0
for i in player_bot.all_player_cards:
bot_cards_value += i.values
for i in player_human.all_player_cards:
player_cards_value += i.values
if ace == True:
player_cards_value -= 10
x = 0
decision_on = True
def decision():
global x
global decision_on
print('\nWhay you want to do: ')
print('1 - hit (take one more card)')
print('2 - stay (computer makes a move)')
while True:
x = input('Choose number: ')
if x == '1' or x == '2':
if x == '2':
decision_on = False
return x
else:
return x
else:
print('Wrong number!')
def game():
print('\n')
bot_cards()
player_cards()
counting_values()
while game_on:
game()
decision()
while decision_on:
if x == '1':
if new_deck.all_cards[-1].values == 11:
print('Choose card value: ')
print('1 - 1 point')
print('2 - 11 points')
y = input()
if y == '1':
player_human.add_card(new_deck.deal_one())
player_cards_value -= 10
ace = True
game()
else:
print('Wrong number!')
else:
player_human.add_card(new_deck.deal_one())
game()
if player_cards_value > 21:
print(f'Values of bot cards: {bot_cards_value}')
print(f'Values of player cards: {player_cards_value}\n')
print('Game over! You have over 21 points! Bot wins!')
game_on = False
break
else:
decision()
else:
decision_on = False
break
while not decision_on:
if bot_cards_value == 21 and player_cards_value != 21:
print(f'Values of bot cards: {bot_cards_value}')
print(f'Values of player cards: {player_cards_value}\n')
print('Game over! Bot have 21 points! Bot wins!')
break
elif bot_cards_value == 21 and player_cards_value == 21:
print(f'Values of bot cards: {bot_cards_value}')
print(f'Values of player cards: {player_cards_value}\n')
print('Game over! You bot have 21 points! Tie!')
break
elif bot_cards_value < 21 and bot_cards_value > player_cards_value:
print(f'Values of bot cards: {bot_cards_value}')
print(f'Values of player cards: {player_cards_value}\n')
print('Game over! Bot have more points than you! Bot wins!')
break
elif bot_cards_value > 21:
print(f'Values of bot cards: {bot_cards_value}')
print(f'Values of player cards: {player_cards_value}\n')
print('Game over! Bot have over 21 points! You win!')
break
elif bot_cards_value < 21 and bot_cards_value < player_cards_value:
player_bot.add_card(new_deck.deal_one())
bot_cards()
counting_values()
continue
break |
def test():
print "bloodCalc OK!"
def main(x):
print "Valid signs are Aries, Taurus, Gemini, Cancer, Leo, Virgo,\n Libra, Scorpio, Sagittarius, Capricorn, Aquarius,and Pisces."
sun = raw_input("Enter Sun sign: ")
moon = raw_input("Enter Moon sign:")
if x == False:
print "Your blood color is " + find(sun, moon) + "."
else:
return find(sun, moon)
def calculate(sign):
data = sign.upper()
x = 0
if data == "ARIES":
x = x + 1
return x
elif data == "TAURUS":
x = x + 2
return x
elif data == "GEMINI":
x = x + 3
return x
elif data == "CANCER":
x = x + 4
return x
elif data == "LEO":
x = x + 5
return x
elif data == "VIRGO":
x = x + 6
return x
elif data == "LIBRA":
x = x + 7
return x
elif data == "SCORPIO":
x = x + 8
return x
elif data == "SAGITTARIUS":
x = x + 9
elif data == "CAPRICORN":
x = x + 10
elif data == "AQUARIUS":
x = x + 11
elif data == "PISCES":
x = x + 12
else:
return 4
def find(sign1, sign2):
data = calculate(sign1) + calculate(sign2)
if data == 2 or data == 3:
return "Burgundy"
elif data == 4 or data == 5:
return "Brown"
elif data == 6 or data == 7:
return "Yellow"
elif data == 8:
return "Mutant/Candy Red"
elif data == 9:
return "Lime"
elif data == 10 or data == 11 or data == 13:
return "Green"
elif data == 12:
return "Jade"
elif data == 14 or data == 15:
return "Teal"
elif data == 16 or data == 17:
return "Cerulean"
elif data == 18 or data == 19:
return "Indigo"
elif data == 20 or data == 21:
return "Purple"
elif data == 22 or data == 23:
return "Violet"
elif data == 24:
return "Fuchsia"
|
sentence = input("Enter a sentence : ")
def reverse():
p = sentence[::-1] # Reversing the given sentence and storing it in 'p'
q = p.split()
r = []
x = len(q) - 1 # Splitted sentence obtained then reduced it's length
while x >= 0:
r.append(q[x]) # putting x words into r
x = x - 1
y = " ".join(r)
print('the reversed words obtained are : ', y)
reverse()
|
'''
PyBank challenge
Your task is to create a Python script that analyzes the records to calculate
each of the following:
-The total number of months included in the dataset
-The net total amount of "Profit/Losses" over the entire period
-The average of the changes in "Profit/Losses" over the entire period
-The greatest increase in profits (date and amount) over the entire period
-The greatest decrease in losses (date and amount) over the entire period
In addition, your final script should both print the analysis to the terminal
and export a text file with the results.
'''
import csv
# Create lists to capture the spreadsheet columns and the changes derived from them
months = []
profloss = []
changes = []
# Open the csv file
budgetdatacsv = "budget_data.csv"
with open(budgetdatacsv,newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter =",")
# Skip the header row to make it easier to run operations on the values later
csv_header = next(csvreader)
# Fill the lists with the data from the sheet
for row in csvreader:
months.append(row[0])
profloss.append(int(row[1]))
# Calculate the number of months
nomonths = len(months)
# Calculate the difference between this and last month's profit/loss
# Start with row 2 (index = 1), since the first row doesn't have a row to compare.
for val in range(1,nomonths):
change=int(profloss[val])-int(profloss[val-1])
# Append calculated value to the changes list
changes.append(change)
'''
Now that we have all the lists, analyse the data in them to obtain
the information for the report
'''
# Calculate the sum of profit/loss
totalprofloss=sum(profloss)
# Calculate the average of the changes
avgchange = sum(changes)/len(changes)
# Find the greatest increase in profits (date and amount) over the entire period
greatestinc = max(changes)
greatestincmo = months[(changes.index(greatestinc))+1]
# Find the greatest decrease in losses (date and amount) over the entire period
greatestdec = min(changes)
greatestdecmo = months[(changes.index(greatestdec))+1]
# Build the analysis report lines
line1=(" Financial Analysis")
line2=("--------------------")
line3=("Total Months: " + str(nomonths))
line4=("Total P/L: $" + str(totalprofloss))
line5=("Average Change: ${:.2f}".format(avgchange))
line6=("Greatest Increase in Profits: " + str(greatestincmo) + " ($" + str(greatestinc)+")")
line7=("Greatest Decrease in Profits: " + str(greatestdecmo) + " ($" + str(greatestdec)+")")
#output to a file
with open("Financial_Analysis.txt","w") as report:
for i in range(1,8):
report.write(eval("line"+ "%d" %i))
report.write("\n")
#print to screen
print(eval("line"+ "%d" %i))
|
def count_positives_sum_negatives(arr):
if arr == []: return []
first = 0
second = 0
for i in arr:
if i > 0:
first += 1
if i < 0:
second += i
return [first, second]
|
import re
def is_valid(email):
pattern = re.compile(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\.-]+\.[a-zA-Z]*$")
if re.match(pattern,email):
return "Email is valid"
else:
raise ValueError("Email is not valid")
def valid_email(email):
try:
return is_valid(email)
except ValueError as e:
return e |
def compare(a, b):
"""This function returns the largest number of two numbers"""
if a > b:
return a
return b
value_1 = 45
value_2 = 20
print(compare(value_1, value_2)) |
import re
m = input("Please enter your password: ")
x = True
while x:
if (len(m)<6 or len(m)>16):
break
elif not re.search("[a-z]",m):
break
elif not re.search("[A-Z]",m):
break
elif not re.search("[0-9]",m):
break
elif not re.search("[$#@]",m):
break
else:
print("valid password")
x = False
break
if x:
print("Not a valid password") |
class Vertex:
def __init__(self, num):
self.empty = True
self.num = 0
self.connected_edge = []
self.connected_distance = []
self.num = num
self.reached = False
self.square = 0
self.x = 0
self.y = 0
self.back_pointer = None
self.gx = None
self.close = False
empty = False
def add_edge(self, end, distance):
if not self.connected_edge:
self.connected_edge.append(end)
self.connected_distance.append(distance)
else:
flag = False
for i in range(0, len(self.connected_edge)):
if distance < self.connected_distance[i]:
self.connected_edge.insert(i, end)
self.connected_distance.insert(i, distance)
flag = True
break
if flag is False:
self.connected_edge.append(end)
self.connected_distance.append(distance)
def get_distance_to(self, vertex_num):
distance = -1
i = 0
for edge in self.connected_edge:
if edge == vertex_num:
distance = self.connected_distance[i]
else:
i += 1
return distance
def get_connected_edge(self):
return self.connected_edge
def get_connected_distance(self):
return self.connected_distance
def get_ver_num(self):
return self.num
def is_empty(self):
return self.empty
def is_reached(self):
return self.reached
def set_reached(self):
self.reached = True
def set_not_reached(self):
self.reached = False
def set_square(self, square):
self.square = square
def get_square(self):
return self.square
def get_square_pos(self):
x = (self.square - 1) % 10
y = 9 - int((self.square - 1) / 10)
return x, y
def set_pos(self, x, y):
self.x = x
self.y = y
def get_pos(self):
return self.x, self.y
def set_back_pointer(self, vertex):
self.back_pointer = vertex
def get_back_pointer(self):
return self.back_pointer
def set_gx(self, x):
self.gx = x
def get_gx(self):
return self.gx
def is_closed(self):
return self.close
def set_closed(self):
self.close = True
def set_not_closed(self):
self.close = False |
"""
Запишите букву 'A' (латинскую, заглавную) 100 раз подряд.
Сдайте на проверку программу, которая выводит эту строчку
(только буквы, без кавычек или пробелов).
"""
a = 'A'
print(a * 100)
|
#####
# Python Examples:
# linked_list.py
#
# Linked list implementation in Python.
#
# Xavier Torrent Gorjon
#####
class Element(object):
"""Class that represents nodes on the linked list."""
def __init__(self, data):
"""Class constructor. Sets the data variable."""
self.__data = data
self.__next = None
# Getters and setters.
def set_data(self, data):
self.__data = data
def set_next(self, next_element):
self.__next = next_element
def get_data(self):
return self.__data
def get_next(self):
return self.__next
# Function overloads.
def __str__(self):
return str(self.__data)
class LinkedList(object):
"""Class that represents a linked list of elements."""
def __init__(self):
"""Class constructor. List starts with no elements."""
self.__list = None
self.__length = 0
def add(self, data, add_pos=None):
"""
Adds a new element to the list on the add_pos position.
If no value is provided for add_pos, it appends the element to the last one.
"""
node = Element(data)
if add_pos is None:
add_pos = self.__length
if self.__list is None:
self.__list = node
else:
if add_pos == 0:
node.set_next(self.__list)
self.__list = node
else:
current = self.__list
current_pos = 1
while current.get_next() is not None and current_pos < add_pos:
current = current.get_next()
current_pos += 1
node.set_next(current.get_next())
current.set_next(node)
self.__length += 1
def delete(self, del_pos=None):
"""
Deletes the element of the list on the del_pos position.
If no value is provided for del_pos, it deletes the last one.
"""
if del_pos is None:
del_pos = self.__length
if self.__list is None:
print "Nothing to remove."
else:
if del_pos == 0:
self.__list = self.__list.get_next()
else:
prior = self.__list
current = self.__list.get_next()
current_pos = 1
while current.get_next() is not None and current_pos < del_pos:
prior = current
current = current.get_next()
current_pos += 1
prior.set_next(current.get_next())
self.__length -= 1
# Function overloads.
def __iter__(self):
current = self.__list
while current is not None:
yield current
current = current.get_next()
def __str__(self):
string = "{"
count = 0
for element in self:
string += str(element)
count += 1
if count < self.get_length():
string += ","
string += "}"
return "Number of elements: " + str(self.__length) + ", Values: " + string
# Getters and setters.
def get_length(self):
return self.__length
if __name__ == "__main__":
n = LinkedList()
n.add("aaa")
n.add("bbb")
n.add("ccc")
n.add("333")
n.add("666")
n.add("999")
n.add("1")
n.delete(3)
print n
|
# Fibonacci starting at 0
def fib_at_zero(n):
if n < 2:
return n
return fib_at_zero(n-1) + fib_at_zero(n-2)
# Fibonacci starting at 1
def fib_at_one(n):
if n == 1:
return 0
elif n == 2:
return 1
return fib_at_one(n-1) + fib_at_one(n-2)
print(fib_at_zero(0))
print(fib_at_zero(1))
print(fib_at_zero(2))
print(fib_at_zero(3))
print(fib_at_zero(4))
print("*"*80)
print(fib_at_one(1))
print(fib_at_one(2))
print(fib_at_one(3))
print(fib_at_one(4))
print(fib_at_one(5))
|
import sys
def collatz(number):
if (number%2==0):
print(str(number//2))
return number//2
elif (number%2==1):
print(str(3*number+1))
return 3*number+1
while True:
try:
num=int(input('imput a number pleease:'))
break
except ValueError:
print('u should input a integer')
continue
while True:
bak = collatz(num)
if bak == 1:
break
else:
num=collatz(bak)
|
from typing import List
from typing import Dict
"""expliquez pourquoi un des Modifier marche et un ne marche pas"""
def step1():
class Modifier1:
def __init__(self, liste: List, otherListe: List):
self.liste = liste
self.otherListe = otherListe
def changeArray(self):
self.liste.extend(self.otherListe)
liste = [1, 2, 3]
otherListe = [4, 5, 6]
modifier = Modifier1(liste, otherListe)
modifier.changeArray()
print(liste)
def step2():
class Modifier2:
def __init__(self, liste:List, otherListe:List):
self.liste = liste
self.otherListe=otherListe
def changeArray(self):
self.liste = self.liste+self.otherListe
liste = [1, 2, 3]
otherListe=[4,5,6]
modifier = Modifier2(liste, otherListe)
modifier.changeArray()
print(liste)
|
import random
from time import sleep
snakes = {32:10, 36:6, 48:26, 62:18, 88:24, 95:56, 97:78}
ladders = {1:38, 4:14, 8:30, 21:42, 28:76, 50:67, 71:92, 80:99}
def roll_dice():
return random.randint(1,6)
win = 100
player = 0
counter = 0
while True:
steps = roll_dice()
print("You Got:", steps)
if player + steps == 100:
break
if (player + steps) > 100:
player = player
elif (player+steps) in ladders:
print(f"LADDER ^ {player+steps} To {ladders[(player+steps)]}")
player = ladders[(player+steps)]
elif (player+steps) in snakes:
print(f"SNAKE ~~ {player+steps} To {snakes[(player+steps)]}")
player = snakes[(player+steps)]
else:
player += steps
counter += 1
print("Current Position:", player)
print("***************\n")
print(f"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"~~~~~~~ Congratulations !!! You won in {counter} steps ~~~~~~~".rjust(58))
print(f"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
import csv
import numpy as np
import pandas as pd
##########################old logic to be reomoved ###################
#file_name = sys.argv[1]
#fp = open(file_name)
#contents = fp.read()
#f = open('data.csv')
#f is instance of file being opened
#csv_f = csv.reader(f)
# we are trying to loop over every row
# every row is a list of three elemets, if you see closely
for row in contents:
print row[0]
f.close() |
#Uses python3
#Pierce Lovesee
#July 2nd, 2021
#Good job! (Max time used: 0.27/10.00, max memory used: 39157760/536870912.)
import sys
def toposort(adj, visitedNodes):
postOrdering = [] #keep track of the post ordering of the graph
def explore(v):
if visitedNodes[v]: #if the vertex has been visted, don't explore it
return
for i in adj[v]: #explore all adjacent verticies to 'v'
explore(i)
visitedNodes[v] = True #mark as visited when adjacent verticies explored
postOrdering.append(v) #append vertex to post ordering record
def DFS(): #perform DFS on graph to determine post ordering
for v in range(len(visitedNodes)): #explore all verticies in the graph
explore(v)
return(postOrdering) #once complete, return te post ordering of graph
return(DFS())
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
visitedNodes = [False for _ in range(n)]
order = toposort(adj, visitedNodes)
for _ in range(n):
print(order.pop() + 1, end=' ')
|
#python3
#Pierce Lovesee
#June 22nd, 2021
import sys
def number_of_components(adj, nodeTruth):
"""
Input: Takes a graph adjacency list as input with a truth table to track what
nodes have been visited.
Output: Returns the number of seperetly connected components in the graph
(i.e. if the graph is continuous, returns 1; if the graph has dead zones,
returns > 1; if the graph is empty, returns 0)
"""
def explore(v, CC):
nonlocal nodeTruth
nodeTruth[(v)][0] = True #mark the node as visited
nodeTruth[(v)][1] = CC #note what group of connected components
for i in adj[v]: #for every connected node to v in the adj list
if not nodeTruth[(i)][0]: #if that node has not been visited
explore(i, CC) #then visit it; come on, really do it.
def DFS():
nonlocal nodeTruth
CC = 0 # base case, empty graph would have zero components
for v in range(len(nodeTruth)): #loop through all verticies in the graph
if not nodeTruth[v][0]: #if the node has not been visited
CC += 1
explore(v, CC) #call explore on it (recursive)
#move to next cc group after all nodes connected to v are found
#CC = connected components (groups of connected nodes)
return(CC)
#iteratively and recursively explore all verticies and edges
return(DFS())
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split())) #stores user input
n, m = data[0:2] #stores 'n' verticies and 'm' edges at start of user input
data = data[2:] #defines the graph data as all other user input
#isolates the list of edges for later iteration
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)] #creates a list of 'n' empty lists
#loop to create adjacency list representation of graph
for (a, b) in edges:
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
nodeTruth = [[False, 0] for _ in range(n)] #[(is visited), (connectivity)]
print(number_of_components(adj, nodeTruth))
|
#Uses python3
#Pierce Lovesee
#July 3rd, 2021
#Good job! (Max time used: 0.37/10.00, max memory used: 46055424/536870912.)
import sys
import queue
def distance(adj, s, t, dist, prev):
"""
Input: adjacency list, start node int, target node int, distance list, and
prev node list.
Output: (int) the shortest distance between 's' and 't'
"""
def BFS(): #helper function to perform breadth-first search on graph
dist[s] = 0 #set start node's dist to zero
Q = [s] #initialize queue with start node
while bool(Q): #perform the following while Queue is not empty:
u = Q.pop(0) #dequeue the next element, let it be 'u'
for i in adj[u]: #for each adjacent node to 'u'
if dist[i] == float('inf'): #if it has not been discovered
Q.append(i) #add it to the queue
dist[i] = dist[u] + 1 #set it's dist to dist[u] + 1
prev[i] = u #mark 'u' as its previous node
BFS() #envoke the breadth first search on the graph
if dist[t] == float('inf'): #if the target node was never discovered in BFS
return -1 #return error since it cannot be reached from start node
return dist[t] #otherwise, return the memoized distance to the target
def reconPath(s, t, prev):
"""
Input: start node, target node, list of each node's previous shortest path
node.
Output: list of nodes to traverse the shortest path from start node to
target node
"""
if prev[t] == -1: #if a previous node was not recorded for the target
#then return error message, no path from 's' to 't'
return ("No Such Path Exists (" + str(s + 1) + ", " + str(t + 1) + ")")
reconPathList = [] #list for storing the reconstructed path F/'t' T/'s'
reversedPathList = [s + 1] #list for storing reversed path F/'s' T/'t'
def constructPath(s, t): #helper function to reconstruct the path
if t == s: #once 't' is 's', break recursion
return
reconPathList.append(t + 1) #add 't' to the path
constructPath(s, prev[t]) #then recurs on 't's previous node
def reversePath(): #helper to reverse the ordering of the list
for _ in range(len(reconPathList)):
reversedPathList.append(reconPathList.pop())
constructPath(s, t) #reconstruct the path F/'s' T/'t'
reversePath() #then reverse the path
return(reversedPathList) #return the reversed path
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
# Test Data Sets with Results Commented
# data = [5, 4, 5, 2, 1, 3, 3, 4, 1, 4, 3, 5] # -1
# data = [4, 4, 1, 2, 4, 1, 2, 3, 3, 1, 2, 4] # 2
# data = [5, 4, 5, 2, 4, 2, 3, 4, 1, 4, 4, 3] # 3
n, m = data[0:2] #n - nodes | m - endges
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) # list edges (u, v)
adj = [[] for _ in range(n)] # undirected adjacency list
for (a, b) in edges: #populate undrected adjacency list
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
s, t = data[2 * m] - 1, data[2 * m + 1] - 1 #s - source | t - target
dist = [float('inf') for _ in range(n)] #initialize distance list to infinity
prev = [-1 for _ in range(n)] #initialize prev. node array to -1 (no such node)
print(distance(adj, s, t, dist, prev))
print(reconPath(s, t, prev)) # Uncommenting displays the node path
|
#python3
# Pierce Lovesee
# Janurary 2nd, 2021
import sys
class StackWithMax():
def __init__(self):
self.__stack = [] # two stacks need to be maintained; one as stack
self.MaxStack = [] # and one to keep track of how many elemts can
# be removed and have the current max stay the
# max of the stack
def __str__(self): # print definintion for StackWithMax
return(str(self.__stack)) # object
def Push(self, a): # handles new items being pushed to the stack
self.__stack.append(a) # appends new item to end of stack
# if the MaxStack is empty, or if new element is larger than current
# max, then append to end of MaxStack list
if (not bool(self.MaxStack)) or (self.MaxStack[-1] <= a):
self.MaxStack.append(a)
# otherwise, the last element of the MaxStack is appened again
# conceptually this means that if there are say 5 copies of the
# same max element in a row, then 5 elements can be popped from
# the stack while maintaining the same max
else:
max = self.MaxStack[-1]
self.MaxStack.append(max)
def Pop(self): # pops elements from both stacks
assert(len(self.__stack))
self.__stack.pop()
# as elements are popped from the main stack, the current maximum
# is tracked with the MaxStack stack.
self.MaxStack.pop()
def Max(self): # returns the last element of MaxStack
return(self.MaxStack[-1])
if __name__ == '__main__':
stack = StackWithMax()
num_queries = int(sys.stdin.readline())
for _ in range(num_queries):
query = sys.stdin.readline().split()
if query[0] == "push":
stack.Push(int(query[1]))
elif query[0] == "pop":
stack.Pop()
elif query[0] == "max":
print(stack.Max())
elif query[0] == "print":
print(stack)
else:
assert(0)
|
class Car:
"""Классификатор легковых автомобилей"""
def __init__(self, brand, year, volume, price, mileage):
""""Инициализация атрибутов класса Car"""
self.brand = brand # марка авто
self.year = year # год выпуска
self.volume = volume # объем двигателя
self.price = price # цена
self.mileage = mileage # пробег
self.wheels = 4 # кол-во колес
self.tip = 'легковой'
print('Новый автомобиль добавлен:', self.brand, self.year, 'г.в.')
def get_info(self):
"""Вывод информации о экземпляре"""
car_info = 'Поступил новый ' + self.tip + ' автомобиль: марки ' + self.brand + ' ' + str(self.year) + ' г.в.' + \
', двигатель объемомом: ' + str(self.volume) + ' л.' + ', цена: ' + str(self.price) + ' руб., пробег: ' \
+ str(self.mileage) + ' км.'
return car_info
def update_price(self, price):
"""Изменение цены авто"""
self.price = price
class Truck(Car):
"""Классификатор грузовых автомобилей"""
def __init__(self, brand, year, volume, price, mileage):
"""Инициализация атрибутов класса Truck"""
super().__init__(brand, year, volume, price, mileage)
self.tip = 'грузовой'
self.wheels = 8
car_1 = Car('Audi', 1999, 1.8, 400000, 120000)
car_1.update_price(100)
car_2 = Truck('Man', 2000, 5, 20000, 1000000)
car_2.update_price(5000)
print('У авто ' + str(car_1.brand) + ' ' + str(car_1.wheels) + ' колес(а)')
print(car_1.get_info())
print(car_2.get_info())
|
# a = 10
# while a > 1:
# a -= 1
# print(a * '*')
#
# for i in range(10):
# print(i**2)
a = int(input())
while a >= 0:
print(a)
a -= 1
|
# @Time : 20190704
# @Author : lzh
def counting_sort(nums):
min_value = min(nums)
max_value = max(nums)
counting_arr_len = max_value - min_value + 1
counting_arr = [0] * counting_arr_len
for num in nums:
counting_arr[num-min_value] += 1
sorted_index = 0
for j in range(counting_arr_len):
while counting_arr[j] > 0:
nums[sorted_index] = j + min_value
counting_arr[j] -= 1
sorted_index += 1
return nums
if __name__ == "__main__":
test_data = [49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22]
print(sorted(test_data))
counting_sort(test_data)
print(test_data) |
# @Time : 20190704
# @Author : lzh
def heap_sort(nums):
global length
length = len(nums)
build_max_heap(nums)
for i in range(len(nums)-1, 0, -1):
nums[0], nums[i] = nums[i], nums[0]
length -= 1
heapify(nums, 0)
return nums
def heapify(nums, i):
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < length and nums[left] > nums[largest]:
largest = left
if right < length and nums[right] > nums[largest]:
largest = right
if i != largest:
nums[i], nums[largest] = nums[largest], nums[i]
heapify(nums, largest)
def build_max_heap(nums):
for i in range(len(nums)//2, -1, -1):
heapify(nums, i)
if __name__ == "__main__":
test_data = [49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22]
print(sorted(test_data))
test_data = heap_sort(test_data)
print(test_data)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import collections
import math
import bitarray
def solveIt(inputData):
# Modify this code to run your optimization algorithm
# parse the input
lines = inputData.split('\n')
firstLine = lines[0].split()
items = int(firstLine[0])
capacity = int(firstLine[1])
values = []
weights = []
for i in range(1, items+1):
line = lines[i]
parts = line.split()
values.append(int(parts[0]))
weights.append(int(parts[1]))
# value, weight, taken = naive(weights, values, capacity)
# value, weight, taken = dynamic(weights, values, capacity)
# value, weight, taken = dynamic_optimized(weights, values, capacity)
value, weight, taken = bb(weights, values, capacity)
verify(taken, value, values, weight, weights)
# prepare the solution in the specified output format
outputData = str(value) + ' ' + str(0) + '\n'
outputData += ' '.join(map(str, taken))
return outputData
def verify(taken, objective, values, weight, weights):
"""
"""
import itertools
taken_value_sum = sum(itertools.compress(values, taken))
taken_weight_sum = sum(itertools.compress(weights, taken))
if objective != taken_value_sum:
print 'objective {} does not match taken_value_sum: {}, taken: {}'.format(objective, taken_value_sum, taken)
if weight != taken_weight_sum:
print 'weight {} does not match taken_weight_sum: {}, taken: {}'.format(weight, taken_weight_sum, taken)
def naive(weights, values, capacity):
# a trivial greedy algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
items = len(values)
value = 0
weight = 0
taken = []
for i in range(0, items):
if weight + weights[i] <= capacity:
taken.append(1)
value += values[i]
weight += weights[i]
else:
taken.append(0)
return (value, weight, taken)
def dynamic(weights, values, capacity):
table = [[0 for y in range(len(weights))] for x in xrange(0,capacity+1)]
maxi = maxj = 0
for i in xrange(capacity+1):
for j in range(len(weights)):
if j == 0 and i >= weights[j]:
table[i][j] = values[j]
continue
if (i >= weights[j]):
if (table[i-weights[j]][j-1] + values[j] > table[i][j-1]):
table[i][j] = table[i-weights[j]][j-1] + values[j]
else:
table[i][j] = table[i][j-1]
else:
table[i][j] = table[i][j-1]
taken = []; weight = 0;
i = capacity; j = len(weights)-1
value = table[i][j]
while i > 0 and j >= 0:
if (table[i][j] != table[i][j-1]):
taken.insert(0, 1)
weight += weights[j]
i -= weights[j]
else:
taken.insert(0,0)
j -= 1
return (value, weight, taken)
def dynamic_optimized(weights, values, capacity):
"""
"""
import bitarray
table = [[{'value': 0, 'pre':bitarray.bitarray()} for y in range(2)] for x in xrange(0,capacity+1)]
for j in range(len(weights)):
for i in xrange(capacity+1):
if j == 0 and i >= weights[j]:
table[i][j&1] = {'value':values[j],'pre':bitarray.bitarray(1)}
continue
if (i >= weights[j]):
if (table[i-weights[j]][~j&1]['value'] + values[j] > table[i][~j&1]['value']):
table[i][j&1] = {'value':table[i-weights[j]][~j&1]['value'] + values[j],
'pre': bitarray.bitarray(table[i-weights[j]][~j&1]['pre'])}
table[i][j&1]['pre'].append(1)
else:
table[i][j&1] = {'value':table[i][~j&1]['value'], 'pre': bitarray.bitarray(table[i][~j&1]['pre'])}
table[i][j&1]['pre'].append(0)
else:
table[i][j&1] = {'value':table[i][~j&1]['value'], 'pre': bitarray.bitarray(table[i][~j&1]['pre'])}
table[i][j&1]['pre'].append(0)
maxj = max(enumerate(table[capacity]), key=lambda x: x[1]['value'])[0]
taken = [[0,1][x] for x in table[capacity][maxj]['pre'].tolist()]
weight = sum([weights[i] if ex else 0 for i,ex in enumerate(taken)])
value = table[capacity][maxj]['value']
return (value, weight, taken)
def bb(weights, values, capacity):
# re-order items in ascending value/weight order
ratio_order = sorted([ i for i in range(len(weights))], key=lambda x: (values[x]/float(weights[x]), -x))
weights = [weights[x] for x in ratio_order]
values = [values[x] for x in ratio_order]
sys.setrecursionlimit(10100)
feasible = {'value':0, 'path': None}
do_bb(depth=0, path=[], accumulated=0, leftover=capacity,
estimate=do_estimate(0, weights, values, capacity, initial=0),
feasible=feasible,
weights=weights,
values=values)
if (feasible['path']):
value = sum([values[i] for i in feasible['path']])
weight = sum([weights[i] for i in feasible['path']])
taken = [1 if x in feasible['path'] else 0 for x in range(len(weights))]
taken = [taken[x] for x in ratio_order]
return (value, weight, taken)
else:
return (None, None, None)
def do_bb(depth, path, accumulated, leftover, estimate, feasible, weights, values):
assert len(values) == len(weights)
# print 'weights: {}'.format(weights)
# print 'values: {}'.format(values)
# print 'depth: {}'.format(depth)
# print 'path: {}'.format(path)
# print 'accumulated: {}'.format(accumulated)
# print 'leftover: {}'.format(leftover)
# print 'estimate: {}'.format(estimate)
# print 'feasible:{}'.format(feasible)
if leftover >= 0 and accumulated > feasible['value']:
feasible['value'] = accumulated
feasible['path'] = path;
if len(weights) == depth or leftover < 0 or estimate < feasible['value']:
return;
node_weight = weights[depth]; node_value = values[depth]
do_bb(depth + 1, path, accumulated, leftover, do_estimate(depth + 1, weights, values, leftover, initial=accumulated), feasible, weights, values)
do_bb(depth + 1, append_path(path, depth), accumulated + node_value, leftover - node_weight, estimate, feasible, weights, values)
return
def append_path(path, num):
ret = list(path);
ret.append(num)
return ret
def do_estimate(depth, weights, values, capacity, initial):
assert len(weights) == len(values)
acc_value = 0
acc_weight = 0
i = len(weights)-1;
# whole items
while i >= depth and acc_weight + weights[i] <= capacity:
acc_value += values[i]
acc_weight += weights[i]
i -= 1
# last fractional item
if acc_weight < capacity and depth <= i < len(weights):
acc_value += ((values[i]/float(weights[i])) * (capacity-acc_weight))
# print initial + math.ceil(acc_value)
return initial + math.ceil(acc_value)
import sys
if __name__ == '__main__':
if len(sys.argv) > 1:
fileLocation = sys.argv[1].strip()
inputDataFile = open(fileLocation, 'r')
inputData = ''.join(inputDataFile.readlines())
inputDataFile.close()
print solveIt(inputData)
else:
print 'This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)'
|
# define a function with the name favorite city that will print out
# "One of my favorite cities is" + name of that city at least 3 different times!
def favorite_city(name):
print("One of my favorite cities is", name)
favorite_city("Ashburn, Virginia")
favorite_city("Overland Park, Kansas")
favorite_city("Plano, Texas")
|
from Array import remove_element
def test_remove_element():
arr = [1, 1, 3, 2]
assert 3 == remove_element.remove_element(arr, 3)
assert arr[0:3] == [1, 1, 2]
arr = [1, 2, 2, 1, 3, 4, 3, 5]
assert 6 == remove_element.remove_element(arr, 3)
assert arr[0:6] == [1, 2, 2, 1, 4, 5] |
def search_insert_position(arr, value):
left = 0
right = len(arr) - 1
if value > arr[right]:
return right + 1
if value < arr[left]:
return left
return _search_binary_search(arr, value, left, right)
def _search_binary_search(arr, value, low, high):
if high - low <= 0:
return low
mid = low + int((high - low) / 2)
if value < arr[mid]:
return _search_binary_search(arr, value, low, mid)
elif value > arr[mid]:
return _search_binary_search(arr, value, mid + 1, high)
return mid |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def convert(head: ListNode):
if head is None:
return None
length = get_length(head)
left = 0
right = length - 1
root = build_bst(head, left, right)
return root[1]
def build_bst(head, left, right):
if right - left == 1:
# right is root, left is left child
root = TreeNode(head.next.val)
root.left = TreeNode(head.val)
return [head.next, root]
if right == left:
# return leaf
root = TreeNode(head.val)
return [head, root]
# at least 3 elements
mid = left + (right - left) // 2
left_children = build_bst(head, left, mid - 1)
left_head = left_children[0]
left_root = left_children[1]
# moving head
head = left_head.next
root = TreeNode(head.val)
root.left = left_root
right_children = build_bst(head.next, mid + 1, right)
right_head = right_children[0]
right_root = right_children[1]
root.right = right_root
return [right_head, root]
def get_length(head):
count = 0
while head is not None:
count += 1
head = head.next
return count |
# a palindrome reads the same from left to right
# convert into a string
# use 2 pointers left, right
# false if pointers dont match
def is_palindrome(num):
if num < 0:
return False
num_str = str(num)
left = 0
right = len(num_str) - 1
while left < right:
if num_str[left] != num_str[right]:
return False
left += 1
right -= 1
return True
# divide the number by each digit's divisor
# 232 for example
# divide 232/100 and 232%10 and compare the result
def is_palindrome_int(num):
if num < 0:
return False
if num < 10:
return True
divisor = 10
while num / divisor > 10:
divisor *= 10
left_divisor = divisor
right_divisor = 10
print(left_divisor, right_divisor)
i = 0
while left_divisor >= right_divisor:
# modulo of 10 to get the last digit
left = int(num / left_divisor) % 10
# divide by the same length of power of 10 to get the desired digit
# ex divide 213 by 100 to get 2
# divide 13 by 10 to get 1
right = int((num % right_divisor) / pow(10, i))
print(left_divisor, right_divisor, left, right)
if left != right:
return False
left_divisor = int(left_divisor / 10)
right_divisor = right_divisor * 10
i += 1
return True |
def find_element(sorted_arr, el):
low = 0
high = len(sorted_arr) - 1
if len(sorted_arr) == 0:
return -1
while low >= 0 and high <= len(sorted_arr) and low <= high:
mid = low + int((high - low) / 2)
if sorted_arr[mid] > el:
# search in lower half
high = mid - 1
elif sorted_arr[mid] < el:
# search in higher half
low = mid + 1
else:
return mid
return -1 |
from Number import roman_to_int
def test_roman_to_int():
num = 'MCMXCIV'
assert 1994 == roman_to_int.convert_roman_to_int(num)
num = 'XXVII'
assert 27 == roman_to_int.convert_roman_to_int(num)
num = 'LVIII'
assert 58 == roman_to_int.convert_roman_to_int(num)
num = 'MDCCCXC'
assert 1890 == roman_to_int.convert_roman_to_int(num) |
def string_to_integer(str):
str_arr = list(str)
right = len(str) - 1
sum = 0
while right > 0:
num = convert_string_to_integer(str_arr, right)
print(num)
sum = sum + num
right -= 1
char = convert_string_to_integer(str_arr, 0)
if char == '-':
sum *= -1
else:
sum += char
return sum
def convert_string_to_integer(str_arr, index):
if str_arr[index] != '-':
return int(str_arr[index]) * pow(10, len(str_arr) - index - 1)
return str_arr[index] |
from String import first_occurence_substr
def test_find_first_occurrence():
str = 'hello'
needle = 'll'
assert 2 == first_occurence_substr.find_first_occurrence_substr(str, needle)
haystack = "aaaaa"
needle = "bba"
assert -1 == first_occurence_substr.find_first_occurrence_substr(str, needle)
str = 'q'
needle = 'q'
assert 0 == first_occurence_substr.find_first_occurrence_substr(str, needle)
|
def one_away(str1, str2):
# same length or abs(diff(length1, length2)) <= 1
diff = abs(len(str2) - len(str1))
length = len(str1)
if len(str1) > len(str2):
length = len(str2)
if diff > 1:
return False
odd = False
index1 = 0
index2 = 0
for i in range(length):
if index1 >= len(str1) or index2 >= len(str2):
return True
if str1[index1] != str2[index2]:
if str1[index1 + 1] == str2[index2]:
index1 += 1
if str1[index1] == str2[index2 + 1]:
index2 += 1
if odd is False:
odd = True
else:
return False
index1 += 1
index2 += 1
return True |
from String import is_unique
def test_is_unique():
str = 'excuse moi'
assert is_unique.is_unique(str) == False
str = 'excus moi'
assert is_unique.is_unique(str) == True
str = 'e'
assert is_unique.is_unique(str) == True
str = 'EXCUSe moi'
assert is_unique.is_unique(str) == False
def test_is_unique_sort():
str = 'excuse moi'
assert is_unique.is_unique_sort(str) == False
str = 'excus moi'
assert is_unique.is_unique_sort(str) == True
str = 'e'
assert is_unique.is_unique_sort(str) == True
str = 'EXCUSe moi'
assert is_unique.is_unique_sort(str) == False |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sorted_array_to_bst(arr):
return bst(arr, 0, len(arr) - 1)
def bst(arr, low, high):
if high - low == 1:
root = TreeNode(arr[high])
root.left = TreeNode(arr[low])
return root
if low == high:
return TreeNode(arr[low])
mid = low + (high - low) // 2
root = TreeNode(arr[mid])
root.left = bst(arr, low, mid - 1)
root.right = bst(arr, mid + 1, high)
return root |
# evaluate each roman char
# add left with right
# if left is less, then subtraction
def convert_roman_to_int(roman_num):
sum = 0
roman_int_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
return convert_seq(sum, 0, 1, roman_num, roman_int_dict)
def convert_seq(sum, left, right, roman_num, roman_int_dict):
if right > len(roman_num):
return sum
if right > len(roman_num) - 1:
sum += roman_int_dict[roman_num[left]]
return sum
value = roman_int_dict[roman_num[left]]
next_value = roman_int_dict[roman_num[right]]
if value < next_value:
sum = sum + (next_value - value)
return convert_seq(sum, right + 1, right + 2, roman_num, roman_int_dict)
else:
sum += value
return convert_seq(sum, left + 1, right + 1, roman_num, roman_int_dict) |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def is_same_tree(root1, root2):
if root1 is None and root2 is None:
return True
if not root1 or not root2 or root1.val != root2.val:
return False
return is_same_tree(root1.left, root2.left) and is_same_tree(root1.right, root2.right) |
from Tree import delete_node_bst
def test_delete_bst():
five = delete_node_bst.TreeNode(5)
two = delete_node_bst.TreeNode(2)
five.left = two
three = delete_node_bst.TreeNode(3)
two.right = three
four = delete_node_bst.TreeNode(4)
two.left = four
root = delete_node_bst.delete(five, 5)
assert root.val == 2
def test_delete_root_bst():
five = delete_node_bst.TreeNode(5)
two = delete_node_bst.TreeNode(2)
eight = delete_node_bst.TreeNode(8)
five.left = two
five.right = eight
three = delete_node_bst.TreeNode(3)
two.right = three
four = delete_node_bst.TreeNode(4)
two.left = four
nine = delete_node_bst.TreeNode(9)
eight.right = nine
six = delete_node_bst.TreeNode(6)
eight.left = six
seven = delete_node_bst.TreeNode(7)
six.right = seven
root = delete_node_bst.delete(five, 5)
assert root.val == 6
assert eight.left.val == 7
assert root.right == eight
def test_delete_leaf():
five = delete_node_bst.TreeNode(5)
two = delete_node_bst.TreeNode(2)
eight = delete_node_bst.TreeNode(8)
five.left = two
five.right = eight
three = delete_node_bst.TreeNode(3)
two.right = three
one = delete_node_bst.TreeNode(1)
two.left = one
nine = delete_node_bst.TreeNode(9)
eight.right = nine
six = delete_node_bst.TreeNode(6)
eight.left = six
seven = delete_node_bst.TreeNode(7)
six.right = seven
root = delete_node_bst.delete(five, 4)
assert root.val == 5
root = delete_node_bst.delete(five, 1)
assert root.val == 5
assert two.left is None
root = delete_node_bst.delete(five, 9)
assert root.val == 5
assert eight.right is None
root = delete_node_bst.delete(five, 3)
assert root.val == 5
assert two.right is None
def test_delete_parent_node():
five = delete_node_bst.TreeNode(5)
two = delete_node_bst.TreeNode(2)
eight = delete_node_bst.TreeNode(8)
five.left = two
five.right = eight
three = delete_node_bst.TreeNode(3)
two.right = three
one = delete_node_bst.TreeNode(1)
two.left = one
nine = delete_node_bst.TreeNode(9)
eight.right = nine
six = delete_node_bst.TreeNode(6)
eight.left = six
seven = delete_node_bst.TreeNode(7)
six.right = seven
root = delete_node_bst.delete(five, 6)
assert root.val == 5
assert eight.left == seven
root = delete_node_bst.delete(five, 2)
assert root.val == 5
assert root.left == one
assert one.right == three
root = delete_node_bst.delete(five, 8)
assert root.val == 5
assert root.left.val == seven.val
assert seven.right.val == nine.val
def test_delete():
one = delete_node_bst.TreeNode(1)
two = delete_node_bst.TreeNode(2)
one.right = two
root = delete_node_bst.delete(one, 1)
assert root.val == 2 |
class telephone_util:
def __init__(self):
self.keys = {
0: [],
1: [],
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y']
}
def get_char_key(self, key, place):
if key not in self.keys or place > 3 or place < 1:
return ''
letters = self.keys[key]
if len(letters) == 0:
return ''
return letters[place - 1] |
from String import longest_common_prefix_binary_search
def test_longest_common_prefix():
input = ['flower', 'flo', 'flow', 'flock']
assert 'flo' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
input = ['flower', 'flo', 'flow', 'flock', 'flight']
assert 'fl' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
input = ['flower', 'flo', 'flow', 'flock', 'manager']
assert '' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
input = []
assert '' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
input = ['', 'flower', 'flo', 'flow', 'flock', 'manager']
assert '' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
input = ['flowerdress', 'flowermaid', 'flowier', 'flowing', 'flockbird', 'flightattendant']
assert 'fl' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input)
|
i = 1
j = 2
while j <= 12:
print("\n multiple of ",j,"\n")
i=1
while i<=12:
print (i," x ",j," = ",i*j)
i +=1
j += 1
|
#Area of a Square
"""lenght=input("Enter the lenght of the square\n")
lenght=int(lenght)
area=lenght*lenght
print(area)"""
#Area of a Triangle
"""base=input("Enter the base of the triangle")
height=input("Enter the height of the triangle")
base=int(base)
height=int(height)
area=(base/2*height)
print(area)"""
"""base=int(input("Enter the base of the triangle"))
height=int(input("Enter the height opf the triangle"))
area=base*height/2
print(area)"""
#Area of a Circle
"""import math
radius=int(input("enter the radius of the circle"))
area=radius*radius*math.pi
area=round(area ,2)
print(area)"""
#AreaCalculator
"""import math
print("Welcome to the Area calculator designed by Omikunle Okiki Joshua")
menu=int(input("Please Select the Shape \n1) Triangle\n2) Square\n3) Circle\n"))
if menu==1:
print("You have selected Triangle")
base=int(input("Enter the base of the triangle\n"))
height=int(input("Enter the height opf the triangle\n"))
area=base*height/2
print(area)
elif menu==2:
print("You have selected Square")
lenght=input("Enter the lenght of the square\n")
lenght=int(lenght)
area=lenght*lenght
print(area)
elif menu==3:
print("You have selected Circle")
radius=int(input("enter the radius of the circle\n"))
area=radius*radius*math.pi
print(area)
else:
print("Invalid Option")
print("Run the program again and select an option from 1 - 3")"""
|
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
from prime import primes
def p7():
return primes(150000)[10000]
print p7() |
import http.client
import json
from urllib import parse
from urllib import request
from uszipcode import SearchEngine
KEY="d417eac4aaa24bc082c1581ef13783ea&api"
def get_stores_list():
"""
Queries Wegman's api for the information on their stores and reads the response
:return: list of wegmans stores and their data
"""
web_respone=request.urlopen("https://api.wegmans.io/stores?Subscription-Key=%s-version=2018-10-18" % KEY)
store_json=http.client.HTTPResponse.read(web_respone)
return json.loads(store_json)["stores"]
def build_stores_dict(list):
"""
Takes a list of stores and build a dictionary of store numbers based on zipcodes
:param list:(List) list of all the stores and their data
:return: store_dict(dict): a dictionary of all the store numbers indexed by zipcodes
"""
store_dict={}
for store in list:
lat=store["latitude"]
long=store["longitude"]
number=store["number"]
zipcodes=clean_zip_codes(SearchEngine().by_coordinates(lat, long, returns=1))
for entry in zipcodes:
if entry not in store_dict.keys():
store_dict[entry]=[number]
else:
store_dict[entry].append(number)
return store_dict
def get_product(product):
"""
Finds products matching the users search that wegmans sells
:param product:(String) the name of the product we are looking for
:return:(list) a list of tuples containing the products name and sku respectively
"""
try:
product=parse.quote(product)
web_respone = request.urlopen\
("https://api.wegmans.io/products/search?query=%s&api-version=2018-10-18&subscription-key=%s" % (product, KEY))
product_json = http.client.HTTPResponse.read(web_respone)
except:
return None
return make_product(json.loads(product_json)["results"])
def make_product(list):
"""
takes a list of matching products and makes a tuple of the products name and sku for each product
:param list:(list) list of product data
:return:(list) list of tuples of the products
"""
available_products=[]
for entry in list:
available_products.append((entry['name'], entry['sku']))
return available_products
def clean_zip_codes(list):
"""
takes the list of all the zip objects and just returns a list of the zipcodes
:param list:(list) the list of zipcode objects
:return:(list) the list of only zipcodes
"""
zip_codes=[]
for entry in list:
zip_codes.append(entry.zipcode)
return zip_codes
def locate_nearest_stores(dic, location):
"""
collects zipcodes near you location and checks the dictionary for wegmans in those locations. If no wegmans are
found it checks again with a larger radius (25, 50, 75, 100). If no stores are found in an 100 mile radius it gives
up
:param dic:(dict) the dictionary of store locations
:param location:(dict) the users latitude and longitude
:return:(set) returns the set of stores in the area, -1 if nothing within 100 miles
"""
for i in range(1, 5):
zips=clean_zip_codes(SearchEngine().by_coordinates(location["lat"], location["lng"], radius=25*i, returns=1000))
stores=locate_helper(zips, dic)
if len(stores)>0:
return stores
return -1
def locate_helper(list, dic):
"""
compares list of zipcodes to entries in the dictionary
:param list:(list) the list of all the zipcodes near the use
:param dic:(dict) the dictionary of store locations
:return: the set of stores within the users area
"""
stores=[]
for zip in list:
if zip in dic.keys():
stores.extend(dic[zip])
return stores
def shelf_location(store_num, sku):
"""
Gets the items shelf location from the store number and sku
:param store_num:(String) the stores number
:param sku:(String) the sku number of the product
:return: the shelf location of the product
"""
try:
web_respone = request.urlopen(
"https://api.wegmans.io/products/%s/locations/%s?api-version=2018-10-18&subscription-key=%s" % (sku, store_num, KEY))
location=http.client.HTTPResponse.read(web_respone)
except:
return None
if len(json.loads(location)["locations"]) > 0:
return json.loads(location)["locations"][0]["name"]
else:
return None
def get_price(store_num, sku):
"""
gets the products price from its sku and store number
:param store_num:(String) the stores number
:param sku:(String) the sku number of the product
:return: the price of the product
"""
try:
web_respone = request.urlopen(
"https://api.wegmans.io/products/%s/prices/%s?api-version=2018-10-18&subscription-key=%s" % (sku, store_num, KEY))
location = http.client.HTTPResponse.read(web_respone)
except:
return None
return json.loads(location)["price"]
def get_image(sku):
"""
Returns a list of images for a given sku.
:param sku: The sku number of a product
:return: An image link if available, else None
"""
try:
web_response = request.urlopen(
"https://api.wegmans.io/products/%s?api-version=2018-10-18&subscription-key=%s" % (sku, KEY))
location = http.client.HTTPResponse.read(web_response)
images = json.loads(location)["tradeIdentifiers"]
except:
return None
if len(images) > 0:
return images[0]
else:
return None
|
d = {'a':3, 'b':6, 'c':2, 'd':32, 'e':21, 'f':2}
def replace_dict_value(d, bad_value, good_value):
for key,value in d.items():
if value == bad_value:
d[key] = good_value
return d
def main():
print(replace_dict_value(d, 2, 7))
if __name__ == "__main__":
main() |
num_list = []
while True:
num = input(f"Ievadiet skaitli: ")
if num == 'q' or num == 'Q':
break
else:
num = float(num)
num_list += [num]
print(num_list)
print(f"Top 3 min numbers are: {sorted(num_list)[:3]}")
print(f"Top 3 max numbers are: {sorted(num_list, reverse=True)[:3]}")
print(num_list)
print(f"Top 3 min numbers are: {sorted(num_list)[:3]}")
print(f"Top 3 max numbers are: {sorted(num_list, reverse=True)[:3]}")
|
def number(num):
is_number = isinstance(num, int)
print(isnumber)
# if is_number == False:
# print("False")
# num = input("Number?")
# number(num)
# else:
# print("Skaitlis " + num + " ir ok.")
num = input("Number?")
number(num) |
class Rotinas(object):
@staticmethod
def add(a, b):
print("add: ", a, "+", b, "=", a + b)
return a + b
@staticmethod
def subtract(a, b):
print("subtract: ", a, "-", b, "=", a - b)
return a - b
@staticmethod
def multiply(a, b):
print("multiply: ", a, "x", b, "=", a * b)
return int(a * b)
@staticmethod
def divide(a, b):
print("divide: ", a, ":", b, "=", a / b)
return int(a / b)
@staticmethod
def jump(endereco):
print("jump: ", endereco)
return endereco
@staticmethod
def subroutine_call(pc, endereco, memoria):
memoria[endereco] = ('%04x' % (pc + 2))[0:2]
memoria[endereco+1] = ('%04x' % (pc + 2))[2:]
print("subroutine_call end:", endereco)
return endereco + 2
@staticmethod
def return_from_subroutine(pc, endereco, memoria):
print("return_from_subroutine: ", endereco)
return int("0x"+memoria[endereco]+memoria[endereco+1], 0)
@staticmethod
def jump_if_zero(acumulador, endereco, pc):
print("acumulador: ", acumulador)
if acumulador == 0:
print("jump_if_zero: true pc:", endereco)
return endereco
print("jump_if_zero: false pc:", pc+2)
return pc + 2
@staticmethod
def jump_if_negative(acumulador, endereco, pc):
if acumulador < 0:
print("jump_if_negative: true pc:", endereco)
return endereco
print("jump_if_negative: false pc:", pc+2)
return pc + 2
@staticmethod
def load_value(memory, endereco, value):
print("load_value: ", value)
return value
@staticmethod
def load_from_memory(memory, endereco, value):
value = int("0x"+memory[endereco]+memory[endereco+1], 0)
print("load_from_memory: ", value)
return value
@staticmethod
def move_to_memory(acumulador, endereco, memoria):
memoria[endereco] = ('%04x' % acumulador)[0:2]
memoria[endereco + 1] = ('%04x' % acumulador)[2:]
print("move_to_memory end:", endereco, "value: ", memoria[endereco]+memoria[endereco+1])
@staticmethod
def get_data():
input_value = input("---------> get_data: ")
value = int("0x"+input_value, 0)
print("get_data value: ", value)
return value
@staticmethod
def put_data(acumulador):
print("---------> put_data: ", acumulador)
@staticmethod
def halt_machine(operando):
print("halt_machine end: ", operando)
return operando
|
class Node:
#constructor to initalize the node object
def __init__(self, data=None, next=None):
self.data = data
self.next = None
class LinkedList:
#function to initialize the head
def __init__(self):
self.head = None
#function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
#function to insert new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
#Utility function to print the LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
#Driver program to run the
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print ("Given Linked List")
llist.printList()
llist.reverse()
print ("\nNow the reversed Linked List is ")
llist.printList() |
# paresoimpares.py
print("Calcular si un número es par o impar")
print("José Moya -- GDS0151 \n")
def main():
numero_1 = int(input("Escriba un número entero: "))
if numero_1 % 2 == 0:
print("El número es par.")
else:
print("El número es impar.")
if __name__ == "__main__":
main()
|
import unittest
class animal:
def __init__(self, vivo):
self.vivo = vivo
def esta_vivo(self):
print("Esta vivo: " + self.vivo)
class gato(animal):
def correr(self):
print("El gato esta corriendo")
def dormir(self):
print("ZZZZzzzzz ZZZZZZzzzzz")
def ronronear(self):
print("RRRR RRRRR RRRRR RRRRR")
garfield = gato("si")
garfield.esta_vivo()
garfield.ronronear()
garfield.dormir()
garfield.correr()
class TestResult(unittest.TestCase):
def test_vivo(self):
self.assertEqual(garfield.vivo, "si")
|
print('''=== AGENDA TELEFONICA ===''')
cont = 1
agenda = {}
while cont == 1:
opcao = int(input("[1] - INSERIR\n[2] - REMOVER\n[3] - PESQUISAR\n[4] - SAIR\nDigite a opção desejada:\n"))
if opcao == 1:
nome = input("nome:\n")
email = input("email:\n")
telefone = int(input("telefone:\n"))
endereco = input("endereço:\n")
agenda[nome] = [email, telefone, endereco]
elif opcao == 2:
nome = input("Digite o nome do contato que deseja apagar:\n")
del agenda[nome]
elif opcao == 3:
nome = input("Digite o nome do contato:\n")
if nome in agenda:
print(nome)
c = 0
for i in agenda[nome]:
if c == 0:
print("E-mail: ", i)
elif c == 1:
print("Telefone: ", i)
elif c == 2:
print("Endereco: ", i)
c += 1
else:
print("Contato nao encontrado.")
elif opcao == 4:
print("Fim da Ação.")
break
else:
print("Opcao invalida.") |
'''
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
'''
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
l,r = 0, len(s)-1
while l < r:
s[l],s[r] = s[r],s[l]
l += 1
r -= 1
return " ".join(s) |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import neighbors, metrics
from sklearn.preprocessing import LabelEncoder
# reading dataset
df = pd.read_csv('car.data')
# extracting columns and attributes
x = df[['buying', 'maint', 'safety']].values
# extracting the classification column
y = df[['class']]
# turning x from string to number
Le = LabelEncoder()
for i in range(len(x[0])):
x[:, i] = Le.fit_transform(x[:, i])
# turning classes in numbers
label_maping = {
'unacc': 0,
'acc': 1,
'good': 2,
'vgood': 3
}
y['class'] = y['class'].map(label_maping)
y = np.array(y)
# generating model
knn = neighbors.KNeighborsClassifier(n_neighbors=25, weights='uniform')
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
knn.fit(x_train, y_train)
prediction = knn.predict(x_test)
accuracy = metrics.accuracy_score(y_test, prediction)
print("predictions: ", prediction)
print("accuracy: ", accuracy)
|
# B_R_R
# M_S_A_W
"""
It stores and retrieves books from the JSON file.
Format of JSON file:
[
{
"name": 'Clean Code',
"author": "Robert",
'read': True
}
]
"""
from typing import List, Dict, Union
from .database_connection import DatabaseConnection
Book=Dict(str, Union(str, int))
books_file="books.json"
def create_book_table():
with DatabaseConnection('data.db') as connection:
cursor=connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS books(name text primary key,author text,read integer)")
def add_book(name:str, author:str) -> None:
with DatabaseConnection('data.db') as connection:
cursor=connection.cursor()
cursor.execute('INSERT INTO books VALUES(?,?,0)',(name,author))
def get_all_books()->List[Book]:
with DatabaseConnection('data.db') as connection:
cursor=connection.cursor()
cursor.execute("SELECT * FROM books")
books=[{"name":row[0],"author":row[1],"read":row[2]} for row in cursor.fetchall()]
return books
def mark_book_as_read(name:str) ->:
with DatabaseConnection('data.db') as connection:
cursor=connection.cursor()
cursor.execute('UPDATE books SET read=1 WHERE name=?',(name,))
def delete_book(name:str):
with DatabaseConnection('data.db') as connection:
cursor=connection.cursor()
cursor.execute('DELETE from books WHERE name=?', (name,))
|
# B_R_R
# M_S_A_W
"""
Coding Problem on Regular expressions:
In order to work with regular expressions or we can say regex too,
we have to import its module which is called re
Specifically we use findall method of regex library
findall returns a list containing all matches
"""
import re
email='abdumaliksharipov@gmail.com'
expression='[a-z]+'
matches=re.findall(expression,email)
print(matches)
name=matches[0]
domain=f'{matches[1]}.{matches[2]}'
print(name)
print(domain)
print()
print()
print()
print()
# Let's change it a bit
# So we amend expression whereby it takes in dot as well
# Now there are 2 matches to meet the the expression
email2='somebody@company.net'
expression2='[a-z\.]+'
matches2=re.findall(expression2, email2)
nam=matches2[0]
dom=matches2[1]
print(matches2)
print(nam)
print(dom)
print()
print()
print()
print()
# We can make it simpler by using split method too
email3='name@company.us'
parts=email3.split('@')
nam2=parts[0]
dom2=parts[1]
print(parts)
print(nam2)
print(dom2)
|
# B_R_R
# M_S_A_W
"""
It stores and retrieves books from the CSV file.
Format of CSV file:
name,author,read\n
name,author,read\n
name,author,read\n
name,author,read\n
# comma would not be good idea to separate if comma is part of the name of the book
"""
books_file="books.txt"
def create_book_table():
with open(books_file, 'w')as file:
pass
def add_book(name, author):
with open(books_file, 'a') as file:
file.write(f'{name}, {author}, 0\n')
def get_all_books():
with open(books_file, 'r')as file:
lines=[line.strip().split(',') for line in file.readlines()]
return[
{'name':line[0], 'author':line[1], 'read':line[2]}
for line in lines
]
def mark_book_as_read(name):
books=get_all_books()
for book in books:
if book['name']==name:
book['read']="1"
_save_all_books(books)
def _save_all_books(books):
with open(books_file, 'w')as file:
for book in books:
file.write(f"{book['name']}, {book['author']},{book['read']}\n")
def delete_book(name):
books = get_all_books()
books=[book for book in books if book['name']!=name]
_save_all_books(books)
|
"""
So this would be program for movie collection, which has several functions
such as adding new movies to the existing collection, listing all
movies in the collection, finding some specific movie with details,
and finally exiting from the programm.
"""
# Still working on it. Need to fully grasp lambda function in order to take it in independently.
movies=list()
def menu():
user_input=input("Press 'a' to add movie, 's' to show movies, 'f' to find, and 'q' to quit \n")
while user_input!='q':
if user_input=="a":
add_movie()
elif user_input=="s":
show_movie()
elif user_input=="f":
find_movie()
else:
print("Unknown command. Please try again")
user_input=input("\nPress 'a' to add, 's' to show, 'f' to find, 'q' to quit \n")
def add_movie():
name=input("What is the name of the movie: ")
director=input("Who is the director of the movie: ")
year=int(input("When is the release of the movie: "))
"""
movie=[
{'name': "name",
'director':"director",
"year":'year"}
]"""
movies.append({"name":name,
"director":director,
"year": year})
def show_movie():
for item in movies:
show_movie_details(item)
def show_movie_details(movie):
print(f"{movie['name']}")
print(f"{movie['director']}")
print(f"{movie['year']}")
def find_movie():
find_by=input("With what property of movie are you looking for: ")
lookin_for=input(f"What item are you looking for which is associated with '{find_by}' ")
found_movies=find_by_attribute(movies,lookin_for, lambda x:x[find_by] )
def find_by_attribute(items,expected,finder):
found=list()
for i in items:
if finder(i)==expected:
found.append(i)
return found
menu()
|
oldlist = [1,2,3,4,2,12,3,14,3,2,12,3,14,3,21,2,2,3,4111,22,3333,4]
newlist = []
for i in oldlist:
if i not in newlist:
newlist.append(i)
print newlist
|
d = {'k1':'v1','k2':'v2','k3':'v3'}
l = []
for i in d:
l.append(i)
print l
|
while True:
year = raw_input('input the year: ')
if not year:
print 'bye'
break
elif int(year) % 100 == 0:
if int(year) % 400 == 0:
print '%s is runnian' % year
else:
print '%s is not runnian' % year
elif int(year) % 4 == 0:
print '%s is runnian' % year
else:
print '%s is not runnian' % year
|
mylist = [65555,1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,45,33,45]
least = mylist[0]
for l in mylist:
if l < least:
least = l
first = second = least
for element in mylist:
if element >= first:
second = first
first = element
print 'the max num %s,the second num %s' % (first,second)
|
#!/usr/bin/python
#########################
# python script 17
########################
#defining a class
class Class_name():
def function1(self):
name = lambda a: a+5
print(name(10))
#creating a object
class_object = Class_name()
#calling a def in class
class_object.function1()
|
print("what is ur name")
nameUser = input()
print("How pld r u?")
ageUser = input()
print("Where r u live?")
cityUser = input()
print("This is {0}.".format(nameUser))
print("It is {0}.".format(ageUser))
print("(S)He live in {0}.".format(cityUser)) |
#!/usr/bin/python
#
# Simple XOR brute-force Key recovery script - given a cipher text, plain text and key length
# it searches for proper key that could decrypt cipher into text.
#
# Mariusz Banach, 2016
#
import sys
def xorstring(s, k):
out = [0 for c in range(len(s))]
key = []
if type(k) == type(int):
key = [k,]
else:
key = [ki for ki in k]
for i in range(len(key)):
for j in range(i, len(s), len(key)):
out[j] = chr(ord(s[j]) ^ key[i])
return ''.join(out)
def brute(input_xored, expected_output, key_len):
key = []
if len(input_xored) != len(expected_output):
print '[!] Input xored and expected output lengths not match!'
return False
for i in range(key_len):
cipher_letters = [ input_xored[x] for x in range(i, len(input_xored), key_len)]
plaintext_letters = [ expected_output[x] for x in range(i, len(input_xored), key_len)]
found = False
for k in range(256):
found = True
for j in range(key_len):
if chr(ord(cipher_letters[j]) ^ k) != plaintext_letters[j]:
found = False
break
if found:
key.append(k)
break
found = False
if not found:
print '[!] Could not found partial key value.'
break
return key, xorstring(input_xored, key) == expected_output
def main(argv):
if len(argv) < 4:
print 'Usage: %s <cipher> <plain> <key-len>'
return False
cipher = argv[1]
plain = argv[2]
keylen = int(argv[3])
if len(cipher) != len(plain):
print '[!] Cipher text and plain text must be of same length!'
return False
if len(cipher) % keylen != 0:
print '[!] Cipher text and plain text lengths must be divisble by keylen!'
return False
print "Cipher text:\t%s" % cipher
print "Plain text:\t%s" % plain
print "Key length:\t%d" % keylen
key, status = brute(cipher, plain, keylen)
if status:
print '[+] Key recovered!'
print '\tKey:\t\t\t', str(key)
print '\tDecrypted string:\t' + xorstring(cipher, key)
else:
print '[!] Key not found.'
if __name__ == '__main__':
main(sys.argv)
|
'''Write a recursive function to count the number of times the integer n appears in the input array
ex 1. n = 2 [2, 34, 54, 2, 3] should return 2
ex 2. n = 2 [12, 34, 54, 21, 3]
'''
def count(arr, n):
if len(arr) < 1:
return 0
if arr[0] == n:
return 1 + count(arr[1:], n)
else:
return 0 + count(arr[1:], n)
arr1 = [2, 34, 54, 2, 3]
arr2 = [12, 2, 2, 2]
arr3 = [12, 34, 54, 21, 3]
arr4 = []
print(count(arr1, 2))
print(count(arr2, 2))
print(count(arr3, 2))
print(count(arr4, 2)) |
import math
import mathutils
class _Point:
def __init__(self, x, y):
self.x = x
self.y = y
def dist(self, other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
def dx2(self, other):
return (self.x - other.x)**2
def dy2(self, other):
return (self.y - other.y)**2
def __str__(self):
return "Point(x={}, y={})".format(self.x, self.y)
class Waypoint(_Point):
def __init__(self, x, y, heading):
super().__init__(x, y)
self.heading = heading
def __str__(self):
return "Waypoint(x={}, y={}, theta={})".format(self.x, self.y, self.heading)
def _calc(point1, knot1, knot2, point2):
# Chris made this in desmos. I don't know how it works. Don't ask me.
# https://www.desmos.com/calculator/yri3mwz7kn
sgn_theta1 = -mathutils.sgn((knot2.y - knot1.y)/(knot2.x - knot1.x) * (point1.x - knot1.x) + knot1.y - point1.y)
num = knot2.dx2(point1) + knot2.dy2(point1) - knot1.dx2(point1) - knot1.dy2(point1) - knot1.dx2(knot2) - \
knot1.dy2(knot2)
angle_theta1 = math.acos(num / (-2 * knot1.dist(knot2) * knot1.dist(point1)))
theta1 = sgn_theta1 * angle_theta1
sgn_theta2 = -mathutils.sgn((knot2.y - knot1.y) / (knot2.x - knot1.x) * (point2.x - knot2.x) + knot2.y - point2.y)
num = knot1.dx2(point2) + knot1.dy2(point2) - knot2.dx2(point2) - knot2.dy2(point2) - knot1.dx2(knot2) - \
knot1.dy2(knot2)
print(num / (-2 * knot1.dist(knot2) * knot1.dist(point1)))
angle_theta2 = math.acos(num / (-2 * knot1.dist(knot2) * knot2.dist(point2))) - math.pi
theta2 = sgn_theta2 * angle_theta2
d = knot1.dist(knot2)
print(mathutils.normalize_angle(theta1))
print(mathutils.normalize_angle(theta2))
return mathutils.normalize_angle(theta1), d, mathutils.normalize_angle(theta2)
def navigate(waypoint1, waypoint2):
"""
Calculate a path between two points.
:param waypoint1:
:param waypoint2:
:return: (Angle of first turn, distance, angle of second turn)
"""
r_point1 = _Point(waypoint1.x + math.tan(waypoint1.heading), waypoint1.y + 1)
r_point2 = _Point(waypoint2.x + math.tan(waypoint2.heading), waypoint2.y + 1)
return _calc(r_point1, waypoint1, waypoint2, r_point2)
class TrajectoryPoint:
def __init__(self, time, pos, vel, acc):
self.time = time
self.pos = pos
self.vel = vel
self.acc = acc
def __str__(self):
return "{}\t{}\t{}\t{}".format(self.time, self.pos, self.vel, self.acc)
def straight_trajectory(dist, cruise_speed, acc, frequency=100):
# https://www.desmos.com/calculator/ponjr7cwze
ramp_time = cruise_speed / acc
ramp_dist = acc * ramp_time**2 / 2
cruise_dist = dist - 2 * ramp_dist
cruise_time = cruise_dist / cruise_speed
if cruise_dist < 0:
# All ramp, no cruise. Fix parameters to match
cruise_time = 0
cruise_dist = 0
ramp_time = (dist / acc)**0.5
ramp_dist = dist / 2
time = cruise_time + 2 * ramp_time
def get_pos(t):
if t <= ramp_time:
return acc * t**2 / 2
elif t <= ramp_time + cruise_time:
return ramp_dist + (t - ramp_time) * get_vel(ramp_time)
else:
tp = (t - ramp_time - cruise_time)
return ramp_dist + cruise_dist + get_vel(ramp_time + cruise_time) * tp - acc * tp**2 / 2
def get_vel(t):
if t <= ramp_time:
return get_acc(t) * t
elif t <= ramp_time + cruise_time:
return cruise_speed
else:
tp = (t - ramp_time - cruise_time)
return get_vel(ramp_time + cruise_time) - acc * tp
def get_acc(t):
if t <= ramp_time:
return acc
elif t <= ramp_time + cruise_time:
return 0
else:
return -acc
points = []
for i in range(int(time * frequency) + 1):
t = i / frequency
points.append(TrajectoryPoint(t, get_pos(t), get_vel(t), get_acc(t)))
return points, time, 1 / frequency
def radius_trajectory(radius, angle, track_width, cruise_speed, acc, frequency=100):
D = track_width / 2
ratio = (radius - D) / (radius + D)
outer_dist = (radius + D) * angle
inner_dist = (radius - D) * angle
outer_speed = cruise_speed
inner_speed = cruise_speed * ratio
outer_acc = acc
inner_acc = acc * ratio
outer_points, total_time, _ = straight_trajectory(outer_dist, outer_speed, outer_acc, frequency=frequency)
inner_points, _, _ = straight_trajectory(inner_dist, inner_speed, inner_acc, frequency=frequency)
return outer_points, inner_points, total_time, 1/frequency
|
def main():
emails_dict = {}
email_lengths = []
name_lengths = []
new_email = str(input("Email: "))
while new_email != "":
name = get_name_from_email(new_email)
emails_dict[new_email] = name
name_lengths.append(len(name))
email_lengths.append(len(new_email))
new_email = str(input("Enter another email: "))
# Prints sorted email list
for item in emails_dict.items():
print(f"{item[1]:<{max(name_lengths)}} ({item[0]:<{max(email_lengths)}})")
def get_name_from_email(new_email):
email_split_by_dots = new_email.split(".")
email_further_split_by_ats = email_split_by_dots[1].split("@")
name = email_split_by_dots[0].title() + " " + email_further_split_by_ats[0].title()
is_name = str(input("Is your name {}? (y/n): ".format(name)))
if is_name == "n":
name = str(input("Name: "))
return name
main() |
import sys
sys.stdin = open("input.txt")
T = int(input())
for tc in range(1, T+1):
string = input()
bracket = ['(', ')', '{', '}']
stack = []
# 스트링에서 하나하나꺼내와서
for s in string:
# 괄호만 간추린다
if s in bracket:
# 스택에 있으면
if stack:
# 아스키 코드 표를 보면
# '(' 에서 -1 값이 ')' 가 된다.
# '{' 에서 -2 값이 '}' 가 된다.
if ord(stack[-1]) == ord(s)-2 or ord(stack[-1]) == ord(s)-1:
stack.pop()
else:
stack.append(s)
# 스택에 없으면 일단 추가
else:
stack.append(s)
result = 0 if stack else 1
print("#{} {}".format(tc, result))
|
# a = [[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]
#
# for i in range(len(a)):
# for j in range(len(a[0])):
# if i > j :
# a[i][j],a[j][i] = a[j][i],a[i][j]
#
# print(a)
a = [1, 2, 3, 4]
for i in range(1<<len(a)):
print('******',i,end='\n')
for j in range(len(a)):
if i & (1 << j):
print(a[j],end=' ')
print()
|
__author__ = 'xyang'
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def loop(self, root):
if self.max is None:
self.max = root.val
l = 0
r = 0
if root.left:
l = self.loop(root.left)
if root.right:
r = self.loop(root.right)
nodeSum = root.val + l + r
nodePathMax = max(root.val, root.val + l, root.val + r)
self.max = max(nodeSum, self.max, nodePathMax)
return nodePathMax
def maxPathSum(self, root):
self.max = None
if root is None:
return 0
self.loop(root)
return self.max
|
def insertion_sort(arr):
"""
算法思想: 每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。
时间复杂度: O(n²)
空间复杂度: O(1)
稳定性: 稳定
:param arr: List[int]
:return: arr
"""
n = len(arr)
for i in range(1, n):
element = arr[i]
pos = i
while pos >= 1 and arr[pos - 1] > element:
arr[pos] = arr[pos - 1]
pos -= 1
arr[pos] = element
return arr
if __name__ == "__main__":
test_arr = [8, 5, 10, 12, 7, 6, 15, 9, 11, 3]
print(insertion_sort(test_arr))
|
def fib(N):
"""
问题描述:斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。
该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N,计算 F(N)。
解决思路: 可使用递归, 但运行时间长。使用下面这种方法可大大减少时间复杂度
:param N:
:return:
"""
a, b = 0, 1
for _ in range(N):
a, b = b, a + b
return a
if __name__ == "__main__":
test_N = 4
print(fib(test_N))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def maxDepth1(root):
"""
问题描述:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到
最远叶子节点的最长路径上的节点数。
解决思路:借助栈实现DFS
说明: 叶子节点是指没有子节点的节点。
:param root:TreeNode
:return:int
"""
if not root:
return 0
max_depth = 0
node_stack = [root]
value_stack = [1]
while node_stack:
node = node_stack.pop()
value = value_stack.pop()
max_depth = max(max_depth, value)
if node.right:
node_stack.append(node.right)
value_stack.append(value + 1)
if node.left:
node_stack.append(node.left)
value_stack.append(value + 1)
return max_depth
def maxDepth2(root):
"""
借助队列实现BFS
:param root: TreeNode
:return: int
"""
if not root:
return 0
depth = 0
from collections import deque
queue = deque([root])
while not queue:
depth += 1
n = len(queue)
while n > 0:
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
n -= 1
return depth
|
def singleNumber(nums):
"""
问题描述:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均
出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
解决思路:使用异或运算符,对于^异或运算来说,有以下几个规则
0 ^ N = N
N ^ N = 0
N1^N2^N3 = N1^N3^N2=N2^N3^N1=N2^N1^N3
所以,N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N = N
:param nums:List[int]
:return:int
"""
result = 0
for num in nums:
result ^= num
return result
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 1 21:07:55 2020
@author: viktor
"""
def contar_digito (a):
"""
"""
m=0
while a>0:
b=a%10
a=a//10
if b==7:
m=m+1
return (m)
a=int(input(""))
m=contar_digito (a)
print(m) |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 10 21:23:10 2020
@author: vikto
"""
a=int(input())
b=int(input())
count=0
c=1
while count!=b:
c=c*a
count=count+1
print(c) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 17:41:17 2020
@author: viktor
"""
a=float(input(""))
b=float(input(""))
c=float(input(""))
if a<b<c:
print("True")
else:
print(False)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 19:26:53 2020
@author: viktor
"""
a=int(input(""))
if a>100 and a<1000:
primero=a%10
a=a-primero
a=a/10
segundo=a%10
tercero=(a-segundo)/10
suma=primero+segundo+tercero
if (suma%5==0):
print("True")
else:
print("False")
else:
print("False")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 18:23:16 2020
@author: viktor
"""
a=int(input(""))
n=a
c=0
if n<=0:
print("False")
else:
while (c+2)<n:
c=c+2
print(c) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 22:57:08 2020
@author: viktor
"""
n=int(input(""))
x=1
c=1
print(1)
if n>1:
while x<n:
b=c+x+1
c=b
x=x+1
print(b) |
__author__ = 'Michael Isik'
from numpy import Infinity
class Population:
""" Abstract template for a minimal Population.
Implement just the methods you need.
"""
def __init__(self):pass
def getIndividuals(self):
""" Should return a shallow copy of the individuals container, so that
individuals can be manipulated, but not the set of individuals itself.
For removing or appending individuals to the population, use methods
like removeIndividual() or addIndividual().
"""
raise NotImplementedError()
def addIndividual(self, individual):
""" Should add an individual to the individual container.
"""
raise NotImplementedError()
def addIndividuals(self, individuals):
""" Should add a set of individuals.
"""
raise NotImplementedError()
def removeIndividual(self, individual):
""" Should remove an individual from the individual container.
"""
raise NotImplementedError()
def removeIndividuals(self, individuals):
""" Should remove a set of individuals.
"""
raise NotImplementedError()
def setIndividualFitness(self, individual, fitness):
""" Should associate the fitness value to the specified individual.
"""
raise NotImplementedError()
def getIndividualFitness(self, individual):
""" Should return the associated fitness value of the specified individual.
"""
raise NotImplementedError()
class SimplePopulation(Population):
""" A simple implementation of the abstract Population class.
Sets are used as individual container. The fitness values are
stored in a separate dictionary, which maps individuals to fitness values.
For descriptions of the methods please refer to the Population documentation.
"""
def __init__(self):
self._individuals = set()
# self._fitness = collections.defaultdict( lambda: 0. )
# self._fitness = collections.defaultdict( lambda: -Infinity )
self._fitness = {}
def getIndividuals(self):
return self._individuals.copy()
def addIndividual(self, individual):
self._individuals.add(individual)
self._fitness[individual] = -Infinity
def addIndividuals(self, individuals):
for individual in individuals:
self.addIndividual(individual)
# self._individuals = self._individuals.union(set(individuals))
def removeIndividual(self, individual):
self._individuals.discard(individual)
del self._fitness[individual]
# self._fitness[individual] = -Infinity
# if self._fitness.has_key(individual):
# self._fitness[individual] = -Infinity
# del self._fitness[individual]
def removeIndividuals(self, individuals):
for individual in individuals:
self.removeIndividual(individual)
# self._individuals.difference_update(set(individuals))
def setIndividualFitness(self, individual, fitness):
self._fitness[individual] = fitness
def getIndividualFitness(self, individual):
# assert self._fitness.has_key(individual)
return self._fitness[individual]
def clearFitness(self):
""" Clears all stored fitness values """
for (ind, _) in self._fitness.items():
self._fitness[ind] = -Infinity
# self._fitness.clear()
def getFitnessMap(self):
""" Returns the fitness dictionary """
return self._fitness.copy()
def getMaxFitness(self):
""" Returns the maximal fitness value """
return self.getIndividualFitness(self.getBestIndividuals(1))
def getBestIndividuals(self, n):
""" Returns n individuals with the highest fitness ranking.
If n is greater than the number of individuals inside the population
all individuals are returned.
"""
return set(self.getBestIndividualsSorted(n))
def getBestIndividualsSorted(self, n):
return self.getSortedIndividualList()[:n]
def getWorstIndividuals(self, n):
""" Returns the n individuals with the lowest fitness ranking.
If n is greater than the number of individuals inside the population
all individuals are returned.
"""
return set(self.getSortedIndividualList()[-n:])
def removeWorstIndividuals(self, n):
""" Removes the n individuals with the lowest fitness ranking.
If n is greater than the number of individuals inside the population
all individuals are removed.
"""
inds = self.getWorstIndividuals(n)
self.removeIndividuals(inds)
def getSortedIndividualList(self):
""" Returns a sorted list of all individuals with descending fitness values. """
fitness = self._fitness
return sorted(iter(fitness.keys()), key=lambda k:-fitness[k])
def getIndividualsN(self):
""" Returns the number of individuals inside the population """
return len(self._individuals)
def getAverageFitness(self):
return sum(self._fitness.values()) / float(len(self._fitness))
|
import numpy as np
LEFT =1
RIGHT = 2
STRAIGHT = 0
ACCELERATE =3
BRAKE = 4
RIGHT_AND_BRAKE = 5
RIGHT_AND_ACC = 6
LEFT_AND_BRAKE = 7
LEFT_AND_ACC = 8
def one_hot(labels):
"""
this creates a one hot encoding from a flat vector:
i.e. given y = [0,2,1]
it creates y_one_hot = [[1,0,0], [0,0,1], [0,1,0]]
"""
classes = np.unique(labels)
n_classes = classes.size
one_hot_labels = np.zeros(labels.shape + (n_classes,))
for c in classes:
one_hot_labels[labels == c, c] = 1.0
return one_hot_labels
def rgb2gray(rgb):
"""
this method converts rgb images to grayscale.
"""
gray = np.dot(rgb[...,:3], [0.2125, 0.7154, 0.0721])
gray = 2 * gray.astype('float32') - 1
return gray
def id_to_action(id):
if id == LEFT:
return np.array([-1.0, 0.0, 0.0])
elif id == RIGHT:
return np.array([1.0, 0.0, 0.0])
elif id == ACCELERATE:
return np.array([0.0, 1.0, 0.0])
elif id == BRAKE:
return np.array([0.0, 0.0, np.float32(0.2)])
else:
return np.array([0.0, 0.0, 0.0])
def action_to_id(a):
"""
this method discretizes actions
"""
if all(a == [-1.0, 0.0, 0.0]):
return LEFT
elif all(a == [1.0, 0.0, 0.0]):
return RIGHT
elif all(a == [0.0, 1.0, 0.0]):
return ACCELERATE
elif all(a == [0.0, 0.0, np.float32(0.2)]):
return BRAKE
elif all(a == [1.0, 0.0, np.float32(0.2)]):
# I am oversimplifiyng my action inputs to make everything easier
return RIGHT #return RIGHT_AND_BRAKE
elif all(a == [1.0, 1.0, 0.0]):
return RIGHT #return RIGHT_AND_ACC
elif all(a == [-1.0, 0.0, np.float32(0.2)]):
return LEFT #return LEFT_AND_BRAKE
elif all(a == [-1.0, 1.0, 0.0]):
return LEFT #return LEFT_AND_ACC
else:
return STRAIGHT # STRAIGHT = 0
def preprocessing_y(y_batch):
# create two empty lists in order to store the discretized actions
y_new = []
# use the action_to_id function in loop to discretize the labels
for i in range(y_batch.shape[0]):
y_new.append(action_to_id(y_batch[i]))
# cast the lists to np arrays
y_new = np.array(y_new)
# one hot encode the labels for easier classification
return one_hot(y_new)
def preprocessing_x(X_batch):
return rgb2gray(X_batch)
class Uniform_Sampling:
def __init__(self, y_train_preprocessed):
unique, index, counts = np.unique(y_train_preprocessed, axis=0, return_index=True, return_counts=True)
self.indx_four = []
self.indx_three = []
self.indx_two = []
self.indx_one = []
self.indx_zero = []
for i in range(y_train_preprocessed.shape[0]):
if all(y_train_preprocessed[i] == unique[0]):
self.indx_four.append(i)
elif all(y_train_preprocessed[i] == unique[1]):
self.indx_three.append(i)
elif all(y_train_preprocessed[i] == unique[2]):
self.indx_two.append(i)
elif all(y_train_preprocessed[i] == unique[3]):
self.indx_one.append(i)
elif all(y_train_preprocessed[i] == unique[4]):
self.indx_zero.append(i)
def produce_random_batch(self, X_train, y_train_p, batch_size):
indx_batch = np.random.randint(0,4+1,batch_size)
y_indx = []
for i in range(indx_batch.shape[0]):
if indx_batch[i] == 0:
new_indx = np.random.randint(0,len(self.indx_zero))
y_indx.append(self.indx_zero[new_indx])
elif indx_batch[i] == 1:
new_indx = np.random.randint(0,len(self.indx_one))
y_indx.append(self.indx_one[new_indx])
elif indx_batch[i] == 2:
new_indx = np.random.randint(0,len(self.indx_two))
y_indx.append(self.indx_two[new_indx])
elif indx_batch[i] == 3:
new_indx = np.random.randint(0,len(self.indx_three))
y_indx.append(self.indx_three[new_indx])
elif indx_batch[i] == 4:
new_indx = np.random.randint(0,len(self.indx_four))
y_indx.append(self.indx_four[new_indx])
X_return = preprocessing_x(X_train[y_indx])
return X_return, y_train_p[y_indx]
def produce_random_batch_history(self, X_train, y_train_p, batch_size, history):
indx_batch = np.random.randint(0,4+1,batch_size)
y_indx = []
X_indx = []
for i in range(indx_batch.shape[0]):
if indx_batch[i] == 0:
new_indx = np.random.randint(history,len(self.indx_zero))
y_indx.append(self.indx_zero[new_indx])
for i in range(history):
X_indx.append(self.indx_zero[new_indx] - i)
elif indx_batch[i] == 1:
new_indx = np.random.randint(history,len(self.indx_one))
y_indx.append(self.indx_one[new_indx])
for i in range(history):
X_indx.append(self.indx_one[new_indx]-i)
elif indx_batch[i] == 2:
new_indx = np.random.randint(history,len(self.indx_two))
y_indx.append(self.indx_two[new_indx])
for i in range(history):
X_indx.append(self.indx_two[new_indx] -i)
elif indx_batch[i] == 3:
new_indx = np.random.randint(history,len(self.indx_three))
y_indx.append(self.indx_three[new_indx])
for i in range(history):
X_indx.append(self.indx_three[new_indx]-i)
elif indx_batch[i] == 4:
new_indx = np.random.randint(history,len(self.indx_four))
y_indx.append(self.indx_four[new_indx])
for i in range(history):
X_indx.append(self.indx_four[new_indx]-i)
X_return = preprocessing_x(X_train[X_indx])
X_return = np.reshape(X_return, [-1,96,96,history])
return X_return, y_train_p[y_indx] |
array = [10, 3, 16, 99, 22, 100, 44, 22, -12, 33, 21]
def for_uneven_item(array):
if len(array) == 0:
return None, 'Short array. Try again'
for index, item in enumerate(array):
if index % 2 != 0:
print(item, end = ' ')
return True, None
list_of_array, error = for_even_item(array)
if error != None:
print(error)
if error == None:
print(list_of_array)
def while_odd_item(array):
if len(array) == 0:
return None, 'Short array. Try again'
index = 1
while index < len(array):
print(array[index])
index += 1
return array, None
list_of_array, error = while_even_item(array)
if error != None:
print(error)
if error == None:
print(list_of_array)
def main(array):
if len(array) == 0:
return None, 'Short array. Try again'
def rec_func(array):
if len(array) == 0:
return ''
if array[0] % 2 != 0:
print(array[0], end=' ')
return rec_func(array[1:])
result = rec_func(array)
return result, None
result, error = main(array)
if error != None:
print(error)
|
array = [10, 3, 16, 99, 22, 100, 44, 22, -12, 33, 21]
def array_with_even_items(array):
if len(array) == 0:
return None, 'Short array. Try again'
B = []
for index, item in enumerate(array):
if index % 2 != 0:
B.append(item)
return B, None
result, error = array_with_even_items(array)
if error != None:
print(error)
else:
print(result)
def array_with_even_items(array):
if len(array) == 0:
return None, 'Short array. Try again'
B = []
index = 0
while index < len(array):
if index % 2 != 0:
B.append(array[index])
index += 1
return B, None
result, error = array_with_even_items(array)
if error != None:
print(error)
else:
print(result)
def array_with_even_items(array):
if len(array) == 0:
return None, 'Short array. Try again'
B = []
def rec_array(array, B):
if len(array) == 0 or len(array) == 1:
return B
B.append(array[1])
return rec_array(array[1:], B)
result = rec_array(array, B)
return result, None
result, error = array_with_even_items(array)
if error != None:
print(error)
else:
print(result) |
def Quick_sort(list,low,high):
if low >= high:
return
pivot = partition(list,low,high)
Quick_sort(list,low,pivot-1)
Quick_sort(list,pivot+1,high)
return list
def partition(list,low,high):
pivot = (low + high) // 2
swap(list,pivot,high)
i = low
for j in range(low,high,1):
if list[j] <= list[high]:
swap(list,i,j)
i = i+1
swap(list,i,high)
return i
def swap(list,i,j):
list[i],list[j] = list[j],list[i]
list = [2, 5, 1, 6, 7, 3, 7, 8, 10]
print(Quick_sort(list,0,len(list)-1)) |
n1 = input()
n2 = input()
list1 = list(n1)
list1.sort()
list2 = list(n2)
list2.sort()
if list1 == list2:
print("Anagram")
else:
print("Not")
|
####Percentiles in PY###
import numpy as np
import matplotlib.pyplot as plt
ages = [5, 31, 43, 48, 50, 41, 7, 11, 15, 39, 80, 82, 32, 2, 8, 6, 25, 36, 27, 61, 31]
x = np.percentile(ages, 75)
y = np.percentile(ages, 90)
# get the percentile value of the ages which are lower than the 75 % or 90%
print(x)
print(x)
# plt.hist(x, 10)
# plt.show()
# plt.hist(y, 2)
# plt.show()
|
def volume(r):
return 4/3*3.14*r*r*r
r=int(input('Enter the radius of sphere : '))
print("Volume of Sphere : ",volume(r))
|
#David Justice
#9-29-16
#Bubble Sort
#Defines function called bubbleSort
def bubbleSort(myList):
#Creates counter variable to count number of comparisons
counter = 0
#Creates boolean moreSwaps to contorl while loop runs
moreSwaps = True
#while loop checks to see if variable moreSwaps is True
while moreSwaps:
#Sets moreSwaps to False
moreSwaps = False
#for loop runs until length of myList is reached
for element in range(len(myList) - 1):
#for every run of for loop, adds one to counter variable
counter = counter + 1
#if statment checks if each 2 items needs to be swapped
if myList[element] > myList[element + 1]:
#sets moreSwaps to True to continue running
moreSwaps = True
#Variable temp saves item to be over written
temp = myList[element]
#swap is preformed by deleting number to be over written
#then adding the temp after in the list
myList[element] = myList[element + 1]
myList[element + 1] = temp
#returns the results of the swap in the list and the counts done to complete
return myList, counter
#Defines function called testBubbleSort
def testBubbleSort():
#creates myList list
myList = [12,5,7,18,11,6,12,4,17,1]
#creates two variables, sortedList and counter, that call function bubbleSort and
#store the returned list and count values.
sortedList, counter = bubbleSort(myList)
#prints sorted list
print(sortedList)
#prints the returned number of comparisons done
print("Counts = " + str(counter))
#Calls function testBubbleSort
testBubbleSort()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import copy
import itertools
def get_maximums(numbers):
result = [max(l) for l in numbers]
return result
def join_integers(numbers):
return int("".join([str(n) for n in numbers]))
def generate_prime_numbers(limit):
primes = []
nombre = [i for i in range(2, limit+1)]
while len(nombre) != 0:
primes.append(nombre[0])
nombre = [elem for elem in nombre if elem % nombre[0] != 0]
return primes
def combine_strings_and_numbers(strings, num_combinations, excluded_multiples):
#for i in range(1, num_combinations + 1):
#for s in strings:
#if excluded_multiples is None or i % excluded_multiples != 0:
#result.append(s + str(i))
return [s + str(i) for i in range(1, num_combinations + 1) for s in strings if excluded_multiples is None or i % excluded_multiples != 0]
if __name__ == "__main__":
print(get_maximums([[1,2,3], [6,5,4], [10,11,12], [8,9,7]]))
print("")
print(join_integers([111, 222, 333]))
print(join_integers([69, 420]))
print("")
print(generate_prime_numbers(17))
print("")
print(combine_strings_and_numbers(["A", "B"], 2, None))
print(combine_strings_and_numbers(["A", "B"], 5, 2))
|
#AUTHOR: BABATUNDE IDAHOR
#COURSE: CS133
#TERM : FALL 2015
#DATE : 11/3/2015
#This program checks if two user input strings are anagrams of each other.
print('Project_3: Q1')
print('----------------------------------------------')
print('----------------------------------------------')
#Input values
word1 = str(input('Please enter first word: '))
word2 = str(input('Please enter secord word: '))
# Go through the list and check if word1 matches word2.
word1a = word1.lower() # converts the string to a lower case
word2b = word2.lower()
#convert to a list
word1_list = list(word1a)
word2_list = list(word2b)
#Sorts the existing list
word1_list.sort()
word2_list.sort()
#Loop removes the white spaces from the sorted list.
while ' ' in word1_list:
word1_list.remove(' ')
while ' ' in word2_list:
word2_list.remove(' ')
# checks for anagrams
if word1_list == word2_list:
print( '\n'+ "Yes it's an Anagram!")
print('\n' + '------------------------PROOF------------------')
print(word1_list)
print(word2_list)
else:
print( 'hmm!! - No, they are not Anagrams' )
print(word1_list)
print(word2_list)
print('------------------------All Done!----------------')
|
#Rakshith Raghu(rrde)
code = str(input("Enter your cipher text:")).lower()
decoded = ""
regular = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",".",
"!", "?", "0","1","2","3","4","5","6","7","8","9", " ","@","#","$","%","&",",","/",";",":","(",")"]
caesar = ["d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a","b","c",".",
"!", "?", "0","1","2","3","4","5","6","7","8","9", " ","@","#","$","%","&",",","/",";",":","(",")"]
length = len(code)
for i in range(length):
for z in range(0, 51): #51
if(code[i] == caesar[z]):
decoded = decoded + regular[z]
else:
z=z
print("The decoded phrase is:", decoded) |
"""
Module for time conversion
"""
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = ['oeb2utc']
def oeb2utc(systime_array, seconds_of_gps_delay=6):
"""Converts 6-byte system time (AKA gondola time) to UTC during the flight. Note that the
detectors report a higher-precision "event" time that must first be divided by 10 to convert
to system time.
Parameters
----------
systime_array : `~numpy.ndarray`
Array of system times (normally `~numpy.int64`)
seconds_of_gps_delay : int
Lag in seconds between GPS measurement and GPS recording (default: 6 seconds)
Returns
-------
utc_array : `~numpy.ndarray`
Array of UTC times `~numpy.datetime64`
Notes
-----
This conversion function works as intended for only system times during the flight.
The flight computer was restarted on 2016 Jan 25, which leads to a discontinuity in system
times, and this discontinuity is taken into account by the function.
"""
# Best-fit parameters provided by Pascal on 2016 Mar 30
ref1_datetime64 = np.datetime64('2016-01-18T18:27:54.4375Z')
ref1_fit = (948121319866971.46, 0.99999868346236354)
ref2_datetime64 = np.datetime64('2016-01-25T08:25:04.59375Z')
ref2_fit = (359386220206.81140, 0.99999774862264112)
# System time converted from 100-ns steps to nominal 1-ns steps
arr = (np.array(systime_array) * 100)
# Convert the system time to UTC using the best-fit parameters
# There are some type manipulations to avoid unnecessary element-wise mapping
utc_array = np.empty_like(arr, np.dtype('<M8[ns]'))
utc_array[arr >= 6e14] = ref1_datetime64 +\
((arr[arr >= 6e14] - ref1_fit[0]) / ref1_fit[1]).astype(np.int64).view(np.dtype('<m8[ns]'))
utc_array[arr < 6e14] = ref2_datetime64 +\
((arr[arr < 6e14] - ref2_fit[0]) / ref2_fit[1]).astype(np.int64).view(np.dtype('<m8[ns]'))
return utc_array + np.timedelta64(seconds_of_gps_delay, 's')
|
#!/usr/bin/env python3
import os
this_dir = os.path.dirname(__file__)
with open(this_dir + "/input", mode='r') as file:
input_ = [line.strip() for line in file.readlines() if line]
length = len(input_[0])
height = len(input_)
slopes = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2)
]
def count_trees(slope):
right = slope[0]
down = slope[1]
i = 0
j = 0
tree_count = 0
while True:
j += right
j = j % length
i += down
if i >= height:
break
char = input_[i][j]
if char == "#":
tree_count += 1
return tree_count
counts = [count_trees(slope) for slope in slopes]
product = 1
for count in counts:
product *= count
print(counts)
print(product)
|
from vehicle import Vehicle
class Car(Vehicle):
default_tire = 'tire'
def __init__(self, engine, tires=[], distance_traveled=0, unit='miles', **kwargs):
print(f'__init__ from Car with distance_traveled: {distance_traveled} and {unit}')
#pass values to parent constructor
super().__init__(distance_traveled=distance_traveled, unit=unit, **kwargs)
self.engine = engine
self.tires = [self.default_tire, self.default_tire, self.default_tire, self.default_tire]
def drive(self, distance):
self.distance_traveled += distance |
class Vehicle:
'''
Vehicle models with tyres and engine
'''
default_tire = 'tire' #class level variable
def __init__(self,engine, tires):
'''
Vehcile class default constructor
'''
self.engine = engine
self.tires = tires
@classmethod
def bicycle(cls, tires=None):
if not tires:
tires = [cls.default_tire, cls.default_tire]
return cls(None, tires)
def description(self):
print(f'Car with engin: {self.engine} and tires: {self.tires}')
|
#-*-coding:utf-8-*-
class Solution(object):
'''
题意:求数列中三个数之和为0的三元组有多少个,需去重
暴力枚举三个数复杂度为O(N^3)
先考虑2Sum的做法,假设升序数列a,对于一组解ai,aj, 另一组解ak,al
必然满足 i<k j>l 或 i>k j<l, 因此我们可以用两个指针,初始时指向数列两端
指向数之和大于目标值时,右指针向左移使得总和减小,反之左指针向右移
由此可以用O(N)的复杂度解决2Sum问题,3Sum则枚举第一个数O(N^2)
使用有序数列的好处是,在枚举和移动指针时值相等的数可以跳过,省去去重部分
'''
def threeSum(self,nums):
nums.sort()
res=[]
length=len(nums)
for i in range(0,length-2):
if i and nums[i]==nums[i-1]:
continue
target=nums[i]*-1
left,right=i+1,length-1
while left<right:
if nums[left]+nums[right]==target:
res.append([nums[i],nums[left],nums[right]])
right-=1
left+=1
while left<right and nums[left]==nums[left-1]:
left+=1
while left<right and nums[right]==nums[right+1]:
right-=1
elif nums[left]+nums[right]>target:
right-=1
else:
left+=1
return res
if __name__=='__main__':
nums=[-1, 0, 1, 2, -1, -4]
print Solution().threeSum(nums)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.