blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
51ea37ffbec00f82af62ecc929f17b7e86c4c504 | teohkenxin/BasicSort | /BasicSort.py | 1,779 | 4.375 | 4 | def selection_sort(array):
for border in range(0, len(array)):
min = border
for pointer in range(border+1, len(array)):
if array[pointer] < array[min]:
min = pointer
array[min],array[border] = array[border],array[min]
return array
def bubble_sort(array):
for i in range(0, len(array)): # repeat 5 times, also provide a number to decrease the number of times of loops for the next for loop.
for number in range (1, len(array)-i): # start from.. (1,4), (1,3), (1,2), (1,1)
if array[number-1] > array[number]: #if the first number is bigger than the second number...
array[number], array[number-1] = array[number-1], array[number] #swap first number and second number.
return array
def insertion_sort(array):
for border in range(1, len(array)): #start from index 1 until the end.
last_index = border-1 #the index of the first number in front of the border
newMember = array[border] #the first number behind the border
while last_index >= 0 and array[last_index] > newMember: #while last_index is not lower than 0 and array[last_index] is bigger than the newMember
array[last_index+1] = array[last_index] #push array[last_index] to array[last_index + 1]
last_index -= 1 #minus tail_index, repeat until it becomes lower than 0 (which breaks the loop)
array[last_index+1] = newMember
return array
unordered = [64, 25, 12, 22, 11]
ordered = selection_sort(unordered.copy())
print("[selection sort result]")
print (ordered,"\n")
ordered = bubble_sort(unordered.copy())
print("[bubble sort result]")
print (ordered,"\n")
ordered = insertion_sort(unordered.copy())
print("[insertion sort result]")
print (ordered) |
66110c655443f265965a3caa2ab4972d676f08df | RAmruthaVignesh/PythonHacks | /DataStructures/linkedlist.py | 4,771 | 4.1875 | 4 | class node(object):
data = None
ptr = None
class LL(object):
head = None
def __init__(self):
pass
def insert(self , position,value):
# Insertion when the linked list is empty
if self.head == None:
mynode = node()
mynode.data = value
mynode.ptr = None
self.head = mynode
else:
sizell=self.size()
#Insertion in the beginning
if position == 0:
mynode = node()
mynode.data=value
mynode.ptr = self.head
self.head = mynode
#insertion when the position is provided
elif position <= sizell:
mynode = node()
prevnode = node()
mynode.data = value
temp=self.traverseposition(position)
mynode.ptr=temp[0]
#print "mynode pointer is" , mynode.ptr.data
#print "position is" , position
temp = self.traverseposition(position-1)
prevnode = temp[0]
#print "prevnode data is" , prevnode.data
prevnode.ptr = mynode
else:
print "Enter the correct postion"
#This function inserts the value at the end of the linkedlist
def insertend(self,value):
mynode = node()
mynode.data= value
mynode.ptr = None
temp= self.traverseposition("full")
lastnode = temp[0]
lastnode.ptr = mynode
#This fuction deletes the value at the end of the linkedlist
def delend(self):
llsize=self.size()
temp = self.traverseposition(llsize-2)
lastnode=temp[0]
lastnode.ptr = None
#This function deletes the node at the given position
def delete(self,position):
sizell = self.size()
if (sizell>0 and position<=sizell and position>=0): #Checks boundary conditions
temp = self.traverseposition(position)
currentnode = temp[0]
if position == 0: #Deleting the first node
temp = self.traverseposition(position+1)
nextnode = temp[0]
self.head = nextnode
elif position >0 :# Function to delete the nodes from 2nd to last
temp = self.traverseposition(position-1)
prevnode = temp[0]
if position <sizell: #Deleting nodes in the middle
temp = self.traverseposition(position+1)
nextnode = temp[0]
prevnode.ptr = nextnode
else: # Deletes last node
prevnode.ptr = None
else:
print "Invalid position"
#This function returns the size of the linkedlist
def size(self):
sizecount = 0
temp = self.traverseposition("full")
size = temp[1]+1
return size
# Function to traverse through the linked list . It takes in position of the node and gives the size and node at the given position
def traverseposition(self,location):
#print "location is" , location
loccount = 0
tempnode = self.head
while (loccount <location and tempnode.ptr !=None): # When the size till the given position is requested
tempnode = tempnode.ptr
loccount = loccount+1
while (loccount == "full" and tempnode.ptr !=None): # When the size of the LL is requested
tempnode = tempnode.ptr
loccount = loccount+1
return [tempnode,loccount]
#This function prints the linked list
def printll(self):
tempnode = self.head
x=[]
def traversenode(tnode):
if tnode.ptr != None:
x.append(tnode.data)
tnode = tnode.ptr
traversenode(tnode)
else:
x.append(tnode.data)
traversenode(tempnode)
print "The Linked list is ",x
newlist = LL()
newlist.insert(0,2)
newlist.insert(0,1)
newlist.insert(1,1.5)
newlist.insertend(3)
newlist.insert(3,2.5)
newlist.printll()
print "The size of the linked list is" , newlist.size()
newlist.delend()
print "The LL after deleting the last node is"
newlist.printll()
print "The size of the linked list after deleting the last node is" , newlist.size()
newlist.delete(2)
print "The LL after deleting node in 2nd position"
newlist.printll()
print "The size of the linked list after deleting node in 2nd position ", newlist.size()
newlist.delete(0)
print "The LL after deleting first node"
newlist.printll()
print "The size of the linked list after deleting 1st node" , newlist.size()
newlist.delete(100)
# print "--------"
# newlist.insert(1,300)
# newlist.printll()
|
e1d9b202869dfbbd3432409c48fc5d1430df7bec | NoraBkh/foodvisor | /Assignment1/database.py | 5,164 | 3.640625 | 4 | #!usr/bin/python
# -*- coding: utf-8 -*-
from collections import defaultdict
class UniqueDict(dict):
'''
a dictionary stucture with specificities:
-> node is added ones
-> structure: (id_node, (id_parent, list_values))
- id_node: represents node id
- id_parent : represents node's id parent
- list_values : list of names(images for exemple) that id_node is attributed to
initial is [] empty list
'''
def __setitem__(self, key, value):
# value is a tuple (parent, name)
# with name as the image name for exemple
if key not in self:
#initialize an array of values
id, _ = value # get id parent
value = (id,[]) # initialize value attribut with an empty list
dict.__setitem__(self, key, value)
else:
# in case the key exist(node is already created)
# i suppose that there is no multi heritage
# add the new value to the existed values
_, val = value
self[key][1].append(val) # [1] to change 'value' attributs
class Database(object):
def __init__(self, root):
# root corresponds to the name
# of the first node
self.graph = UniqueDict()
self.root = root
## Graph initialization
self.add(root, None, None) # None as id, root has no parent
# instantiate an other graph to keep the state of the graph at t <t'
# i prefered to store it as a graph rather then a list because in same
# cases the insertion action may not be executed,
# insertion of the same node multiple times
self.old_graph = self.graph.copy()
# save extract
# my choice was leaned on the backup of extract because in the non-existent
# case it will be difficult to recover this data. the other solution was to
# browse the two graphs afterwards to recover the difference, this solution
# will indeed cost a lot of time and memory space
self.extract = {}
def add(self, id_node, id_parent, value=None):
self.graph[id_node] = (id_parent, value)
def add_nodes(self, insertions):
# Take a list of tuples as input and edit the graph
# store ancient graph
self.old_graph = self.graph.copy()
# add nodes to the graph
for id_node, id_parent in insertions:
self.add(id_node, id_parent) # value at insertion stage is [](to designate a leaf
# which may become an intern node)
def add_extract(self, dict_information ):
# take a dictionary and store the information
# save added nodes
self.extract = dict_information
for key, ids_list in dict_information.items(): # key here is value name
for id in ids_list:
if id in self.graph.keys():
self.graph[id][1].append(key) ## [1] to get 'value' attribut
def get_extract_status(self):
status_dict = {}
# get at first added extract values:{ name, [id_node,id_node]}
for name, list_id in self.extract.items(): # browse added names
# compute added node
diffrence_dict = { k : self.graph[k] for k in set(self.graph) - set(self.old_graph) }
status = "valid"
for id_node in list_id:
## case of invalid node id
if id_node not in self.graph.keys():
status = "invalid"
break
## current node id already exists in the database
else:
# check whether id_node has children in the database
parent_ids = [list(diffrence_dict.values())[i][0] for i in range(len(diffrence_dict.values()) )]
if id_node in parent_ids and status != "coverage_staged":
status = "granularity_staged"
else:
# get parent_id of current node
# again i suppose that there is no
# multiple heritage
parent_id = self.graph[id_node][0] # [0] parent id
# check whether parent_id has an other child other than current node
if parent_id in parent_ids:
status = "coverage_staged"
status_dict[name] = status
return status_dict
|
8e9e182882e176ddd32d6f41675978157ae035d0 | SymmetricChaos/ClassicCrypto | /NGrams/NGramInformation.py | 749 | 3.703125 | 4 | # http://norvig.com/mayzner.html
# Uses Google data
ngrams1 = open('1grams.csv', 'r')
ngrams2 = open('2grams.csv', 'r')
ngrams3 = open('3grams.csv', 'r')
ngrams4 = open('4grams.csv', 'r')
ngrams5 = open('5grams.csv', 'r')
ngrams6 = open('6grams.csv', 'r')
ngrams7 = open('7grams.csv', 'r')
ngrams8 = open('8grams.csv', 'r')
ngrams9 = open('9grams.csv', 'r')
for i in [ngrams2,ngrams3,ngrams4,ngrams5,ngrams6,ngrams7,ngrams8,ngrams9]:
print(str(i.name),"has length",len(i.readlines()))
print()
# If we don't move the cursors back to the beginning of ngrams2 it would
# still be at the end from having read all the lines previously
ngrams1.seek(0)
N = ngrams1.readlines()
letters = [i.split(",")[0] for i in N]
print("".join(letters))
|
62210340aa0f84ea29bbe57f01db3cd5e668775b | kasunramkr/Eduraka | /matplot/matplot.py | 320 | 3.75 | 4 | import matplotlib.pylab as plt
x = [1, 3, 6, 9]
y1 = [i * 3 for i in x]
y2 = [i ** 2 for i in x]
plt.plot(x, y1, label="Plot 1")
plt.plot(x, y2, label="Plot 2")
plt.legend()
plt.grid()
plt.xlim(1, 9)
plt.ylim(1, 81)
plt.xlabel("X - Axis")
plt.ylabel("Y - Axis")
plt.title("My Graph")
plt.savefig("plot.png")
plt.show()
|
16b78efc1a0e12dd32642ea4bf60075bc36e7a45 | luhpazos/Exercicios-Python | /Pacote download/Desafios/38.Comparando Numeros.py | 418 | 3.953125 | 4 | print('\033[32m=-' * 10)
print('COMPARANDO NÚMEROS')
print('\033[32m=-\033[m' * 10)
n = int(input('''Escolha dois números inteiros para avaliar.
Primeiro número:'''))
m = int(input('Segundo número:'))
if n > m:
print('O primeiro valor foi o maior número digitado!')
elif m > n:
print('O segundo valor foi o maior número digitado!')
elif m == n:
print('Não existe valor maior, os dois são iguais!')
|
e10eab3b30ff2cb19bcdb3ed67fbfa9e0cab1730 | BR49/Optimizing-Route-Navigation-in-London | /visualizations.py | 30,466 | 4.59375 | 5 | """CSC111 Final Project, DataClasses
This python module contains several methods for visualizing the different routes plots with the
help of folium library.
The list of possible visualizations are:
- Plot multiple paths between the start and end junctions ( visualize_multiple_path() )
- Plot a path with certain number of stops specific by the user ( visualize_path_specific_stops() )
- Plot the shortest path between the start and end junctions and draw a few paths (maximum of 2) for
comparative purposes ( visualize_shortest_path() )
- Plot the most direct path between the start and end junctions and draw a few paths (maximum of 2)
for comparative purposes ( visualize_direct_path() )
- Plot the path with shortest time taken between the start and end junctions
( visualize_shortest_time_path() )
Copyright and Usage Information
===============================
This file is Copyright (c) 2021 by Aditya Shankar Sarma Peri, Praket Kanaujia,
Aakash Vaithyanathan, and Nazanin Ghazitabatabai.
This module is expected to use data from (with the help of the methods from classes file):
https://data.gov.uk/dataset/208c0e7b-353f-4e2d-8b7a-1a7118467acc/gb-road-traffic-counts.
The GB Road Traffic Counts is produced by the Department for Transport. The Department for Transport
collects traffic data to produce statistics on the level of traffic on roads in Great Britain,
last updated in October 2020.
"""
from typing import Tuple
import random
import folium
import classes
import computations
def visualize_multiple_path(start: str, end: str, n: int) -> None:
"""This method draws multiple routes (up to n such paths) between the start and end junctions.
It returns less than n paths if those many paths do not exists. If no such path exists, the
function simply prints a message indicating no such path exists.
The method saves the map result in a separate file called 'multiple_routes.html' which when
opened shows the visualization.
NOTE: The start and end junctions are marked with beige markers to help identify them.
file_path: 'road.csv'
Preconditions
- start != ''
- end != ''
- start != end
- start and end represent appropriate places on the map
"""
if start == end:
print(' The start and end end junctions are the same! Please re run the program with '
' different start and end junctions.')
return None
dict_junctions = classes.load_dict('road.csv')
end_junc_coord = [dict_junctions[end][0]['latitude'], dict_junctions[end][0]['longitude']]
dict_road_coords = {}
plot_map = folium.Map(location=[51.509865, -0.118092], tiles='cartodbpositron',
zoom_start=12)
# Make marker for end junction.
folium.Marker(location=end_junc_coord, popup='<b>' + end + '</b>',
tooltip='<b>Click here to see junction name</b>',
icon=folium.Icon(color='beige', icon='road')).add_to(plot_map)
graph = classes.load_graph('road.csv')
dict_path = computations.multiple_path(graph, start, end, n)
colours = ['red', 'blue', 'purple', 'green', 'orange', 'gray', 'black', 'pink']
colours_markers = colours.copy()
if dict_path != {}:
list_paths = [dict_path[key] for key in dict_path]
# Plot different markers for all junctions in list_paths.
req_plotting_variables = [colours_markers, end_junc_coord, plot_map]
helper_plot_markers(graph, list_paths, dict_road_coords, start, req_plotting_variables)
# Plot link between different markers
req_road_link_variables = [end_junc_coord, plot_map]
helper_plot_road_links(list_paths, colours, end, dict_road_coords, req_road_link_variables)
print('\n\nHOORAY! A map with the possible multiple paths has been traced and generated. '
'Please open the "multiple_routes.html" file under '
'Plots_Generated folder to view the plot.')
plot_map.save('Plots_Generated/multiple_routes.html')
return None
else:
print(f'\n\nSorry! No multiple paths exists between the {start} and {end} junctions.')
return None
def visualize_path_specific_stops(start: str, end: str, num_stops: int) -> Tuple[bool, float]:
"""This method plots a path between the start and end junctions based on the number of stops
the user would like to make as specified by the parameter.
The method saves the map result in a separate file called 'path_with_specific_stops.html',
which when opened shows the visualization.
The function also returns a Tuple(bool, float) which represents whether we could find such a
path which the given num_stops or not along with the cumulative distance of this path.
These return values are used in the main file appropriately
NOTE: The start and end junctions are marked with green markers and the green road link
represents the shortest path
file_path: 'road.csv'
Preconditions
- start != ''
- end != ''
- start != end
- start and end represent appropriate places on the map
"""
if start == end:
print(' The start and end end junctions are the same! Please re run the program with '
' different start and end junctions.')
return (False, 0.0)
dict_junctions = classes.load_dict('road.csv')
end_junc_coord = [dict_junctions[end][0]['latitude'], dict_junctions[end][0]['longitude']]
dict_road_coords = {}
plot_map = folium.Map(location=[51.509865, -0.118092], tiles='cartodbpositron',
zoom_start=12)
# Make marker for end junction.
folium.Marker(location=end_junc_coord, popup='<b>' + end + '</b>',
tooltip='<b>Click here to see junction name</b>',
icon=folium.Icon(color='green', icon='road')).add_to(plot_map)
graph = classes.load_graph('road.csv')
dict_path = computations.multiple_path(graph, start, end)
if dict_path != {}:
list_paths = [dict_path[key] for key in dict_path]
specific_stops_paths = [path for path in list_paths if len(path) == num_stops + 2]
if specific_stops_paths != []:
specific_stops_path = specific_stops_paths[0]
# Plot different markers for shortest path
req_plotting_variables = [end_junc_coord, plot_map]
helper_plot_specific_marker(graph, specific_stops_path, dict_road_coords, start,
req_plotting_variables)
# Plot link between different markers for shortest path
helper_plot_shortest_road_links(specific_stops_path, end, end_junc_coord,
dict_road_coords, plot_map)
# dist_specific_stop_path = [key for key in dict_path
# if dict_path[key] == specific_stops_path][0]
print('\n\nHOORAY! A map with paths with specific stops has been traced and generated. '
'Please open the "path_with_specific_stops.html" file '
'under Plots_Generated folder to view the plot.')
plot_map.save('Plots_Generated/path_with_specific_stops.html')
return (True, [key for key in dict_path
if dict_path[key] == specific_stops_path][0])
else:
return (False, 0.0)
else:
return (False, 0.0)
def visualize_shortest_path(start: str, end: str) -> bool:
"""This method draws multiple routes between the start and end junctions and colour codes the
shortest path with green colour.
The method saves the map result in a separate file called 'shortest_route.html', which when
opened shows the visualization.
NOTE: The start and end junctions are marked with green markers and the green road link
represents the shortest path
file_path: 'road.csv'
Preconditions
- start != ''
- end != ''
- start != end
- start and end represent appropriate places on the map
"""
if start == end:
print(' The start and end end junctions are the same! Please re run the program with '
' different start and end junctions.')
return False
dict_junctions = classes.load_dict('road.csv')
end_junc_coord = [dict_junctions[end][0]['latitude'], dict_junctions[end][0]['longitude']]
dict_road_coords = {}
plot_map = folium.Map(location=[51.509865, -0.118092], tiles='cartodbpositron',
zoom_start=12)
# Make marker for end junction.
folium.Marker(location=end_junc_coord, popup='<b>' + end + '</b>',
tooltip='<b>Click here to see junction name</b>',
icon=folium.Icon(color='green', icon='road')).add_to(plot_map)
graph = classes.load_graph('road.csv')
dict_path = computations.multiple_path(graph, start, end, 2)
shortest_path = computations.shortest_route(graph, start, end)[0]
colours = ['red', 'blue', 'purple', 'orange', 'gray', 'black', 'pink']
colours_other_markers = colours.copy()
if dict_path != {} and shortest_path != []:
list_paths = [dict_path[key] for key in dict_path]
if shortest_path in list_paths:
list_paths.remove(shortest_path)
# Plot different markers for each junction in path
req_plotting_variables = [colours_other_markers, end_junc_coord, plot_map]
helper_plot_markers(graph, list_paths, dict_road_coords, start, req_plotting_variables)
# Plot different markers for shortest path
req_plotting_variables = [end_junc_coord, plot_map]
helper_plot_shortest_marker(graph, shortest_path, dict_road_coords, start,
req_plotting_variables)
# Plot link between different markers other than shortest path
req_road_link_variables = [end_junc_coord, plot_map]
helper_plot_road_links(list_paths, colours, end, dict_road_coords, req_road_link_variables)
# Plot link between different markers for shortest path
helper_plot_shortest_road_links(shortest_path, end, end_junc_coord, dict_road_coords,
plot_map)
print('\n\nHOORAY! A map with the shortest route has been traced and generated. '
'Please open the "shortest_route.html" file under Plots_Generated folder '
'to view the plot.')
plot_map.save('Plots_Generated/shortest_route.html')
return True
else:
print(f'\n\nSorry! No such shortest path exists between the {start} and {end} junctions.')
return False
def visualize_direct_path(start: str, end: str) -> bool:
"""This method draws a few routes between the start and end junctions and colour codes the
most direct path with green colour between the start and end junctions.
The method saves the map result in a separate file called 'most_direct_route.html', which when
opened shows the visualization.
NOTE: The start and end junctions are marked with green markers and the green road link
represents the shortest path
file_path: 'road.csv'
Preconditions
- start != ''
- end != ''
- start != end
- start and end represent appropriate places on the map
"""
if start == end:
print(' The start and end end junctions are the same! Please re run the program with '
' different start and end junctions.')
return False
dict_junctions = classes.load_dict('road.csv')
end_junc_coord = [dict_junctions[end][0]['latitude'], dict_junctions[end][0]['longitude']]
dict_road_coords = {}
plot_map = folium.Map(location=[51.509865, -0.118092], tiles='cartodbpositron',
zoom_start=12)
# Make marker for end junction.
folium.Marker(location=end_junc_coord, popup='<b>' + end + '</b>',
tooltip='<b>Click here to see junction name</b>',
icon=folium.Icon(color='green', icon='road')).add_to(plot_map)
graph = classes.load_graph('road.csv')
dict_path = computations.multiple_path(graph, start, end, 2)
direct_path = computations.direct_route(graph, start, end)[0]
colours = ['red', 'blue', 'purple', 'orange', 'gray', 'black', 'pink']
colours_other_markers = colours.copy()
if dict_path != {} and direct_path != []:
list_paths = [dict_path[key] for key in dict_path]
if direct_path in list_paths:
list_paths.remove(direct_path)
# Plot different markers for each junction in path
req_plotting_variables = [colours_other_markers, end_junc_coord, plot_map]
helper_plot_markers(graph, list_paths, dict_road_coords, start, req_plotting_variables)
# Plot different markers for shortest path
req_plotting_variables = [end_junc_coord, plot_map]
helper_plot_shortest_marker(graph, direct_path, dict_road_coords, start,
req_plotting_variables)
# Plot link between different markers other than shortest path
req_road_link_variables = [end_junc_coord, plot_map]
helper_plot_road_links(list_paths, colours, end, dict_road_coords, req_road_link_variables)
# Plot link between different markers for shortest path
helper_plot_shortest_road_links(direct_path, end, end_junc_coord, dict_road_coords,
plot_map)
print('\n\nHOORAY! A map with most direct paths has been traced and generated. '
'Please open the "most_direct_route.html" file under Plots_Generated folder '
'to view the plot.')
plot_map.save('Plots_Generated/most_direct_route.html')
return True
else:
print(f'\n\nSorry! No such direct path exists between the {start} and {end} junctions.')
return False
def visualize_shortest_time_path(start: str, end: str, mode: str) -> bool:
"""This method draws multiple routes between the start and end junctions and colour codes the
shortest path with green colour.
The method saves the map result in a separate file called 'shortest_route.html', which when
opened shows the visualization.
NOTE: The start and end junctions are marked with green markers and the green road link
represents the shortest path
file_path: 'road.csv'
Preconditions
- start != ''
- end != ''
- start != end
- start and end represent appropriate places on the map
"""
if start == end:
print(' The start and end end junctions are the same! Please re run the program with '
' different start and end junctions.')
return False
dict_junctions = classes.load_dict('road.csv')
end_junc_coord = [dict_junctions[end][0]['latitude'], dict_junctions[end][0]['longitude']]
dict_road_coords = {}
plot_map = folium.Map(location=[51.509865, -0.118092], tiles='cartodbpositron',
zoom_start=12)
# Make marker for end junction.
folium.Marker(location=end_junc_coord, popup='<b>' + end + '</b>',
tooltip='<b>Click here to see junction name</b>',
icon=folium.Icon(color='green', icon='road')).add_to(plot_map)
graph = classes.load_graph('road.csv')
dict_path = computations.multiple_path(graph, start, end, 2)
if dict_path != {}:
list_paths = [dict_path[key] for key in dict_path]
time_between_juncs = []
shortest_time_path_tuple = computations.path_with_shortest_time(graph, mode, dict_path)
for i in range(len(shortest_time_path_tuple[0]) - 1):
time_between_juncs.append(
graph.time_taken_between_junctions(mode, shortest_time_path_tuple[0][i],
shortest_time_path_tuple[0][i + 1]))
if shortest_time_path_tuple[1] in list_paths:
list_paths.remove(shortest_time_path_tuple[1])
# Plot different markers for shortest_time_path
req_plotting_variables = [end_junc_coord, plot_map]
helper_plot_shortest_marker(graph, shortest_time_path_tuple[0], dict_road_coords, start,
req_plotting_variables)
# Plot link between different markers for shortest_time_path
req_road_link_variables = [end_junc_coord, plot_map]
helper_plot_time_road_links(shortest_time_path_tuple[0], time_between_juncs,
end, dict_road_coords, req_road_link_variables)
print('\n\nHOORAY! A map with the shortest time paths has been traced and generated. '
'Please open the "shortest_route.html" file under Plots_Generated folder '
'to view the plot.')
plot_map.save('Plots_Generated/shortest_time_route.html')
return True
else:
print(f'\n\nSorry! No such shortest time path exists between the {start} '
f'and {end} junctions.')
return False
def helper_plot_markers(graph: classes.RoadSystem(), list_paths: list, dict_road_coords: dict,
start: str, req_plotting_variables: list) -> None:
"""This is a helper method for visualize_multiple_path() method.
The method iterates over the different junctions in a path and makes a marker for it with the
help of the folium library plotting methods."""
end_junc_coord = req_plotting_variables[1]
colours = req_plotting_variables[0]
list_colours = colours.copy()
k = 0
for path in list_paths:
if k >= len(list_colours) and list_colours == []:
colour = random.choice(colours)
else:
colour = colours[k]
for i in range(len(path) - 1):
if path[i] not in dict_road_coords:
if path[i] == start:
coordinates = graph.get_junctions_location(start=path[i], end=path[i + 1])
dict_road_coords[path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='beige', icon='road')
).add_to(req_plotting_variables[2])
else:
coordinates = graph.get_junctions_location(start=path[i], end=path[i + 1])
if coordinates == end_junc_coord:
list_paths.remove(path)
else:
dict_road_coords[path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color=colour, icon='road')
).add_to(req_plotting_variables[2])
k += 1
if list_colours == []:
pass
else:
list_colours.remove(colour)
return None
def helper_plot_specific_marker(graph: classes.RoadSystem(), shortest_path: list,
dict_road_coords: dict, start: str,
req_plotting_variables: list) -> None:
"""This is a helper method for visualize_path_specific_stops() method.
The method iterates over the different junctions in a path and makes a marker for it with the
help of the folium library plotting methods."""
end_junc_coord = req_plotting_variables[0]
for i in range(len(shortest_path) - 1):
if shortest_path[i] not in dict_road_coords:
if shortest_path[i] == start:
coordinates = graph.get_junctions_location(start=shortest_path[i],
end=shortest_path[i + 1])
dict_road_coords[shortest_path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + shortest_path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='green', icon='road')
).add_to(req_plotting_variables[1])
else:
coordinates = graph.get_junctions_location(start=shortest_path[i],
end=shortest_path[i + 1])
if coordinates == end_junc_coord:
return None
else:
dict_road_coords[shortest_path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + shortest_path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='gray', icon='road')
).add_to(req_plotting_variables[1])
return None
def helper_plot_shortest_marker(graph: classes.RoadSystem(), shortest_path: list,
dict_road_coords: dict, start: str,
req_plotting_variables: list) -> None:
"""This is a helper method for visualize_shortest_path() and visualize_direct_path() methods.
The method iterates over the different junctions in a path and makes a marker for it with the
help of the folium library plotting methods."""
end_junc_coord = req_plotting_variables[0]
for i in range(len(shortest_path) - 1):
if shortest_path[i] == start:
if shortest_path[i] not in dict_road_coords:
coordinates = graph.get_junctions_location(start=shortest_path[i],
end=shortest_path[i + 1])
dict_road_coords[shortest_path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + shortest_path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='green', icon='road')
).add_to(req_plotting_variables[1])
if shortest_path[i] not in dict_road_coords:
if shortest_path[i] == start:
coordinates = graph.get_junctions_location(start=shortest_path[i],
end=shortest_path[i + 1])
dict_road_coords[shortest_path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + shortest_path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='green', icon='road')
).add_to(req_plotting_variables[1])
else:
coordinates = graph.get_junctions_location(start=shortest_path[i],
end=shortest_path[i + 1])
if coordinates == end_junc_coord:
return None
else:
dict_road_coords[shortest_path[i]] = coordinates
folium.Marker(location=coordinates, popup='<b>' + shortest_path[i] + '</b>',
tooltip='<b><i>Click here to see junction name</i></b>',
icon=folium.Icon(color='gray', icon='road')
).add_to(req_plotting_variables[1])
return None
def helper_plot_road_links(list_paths: list, colours: list, end: str, dict_road_coords: dict,
req_road_link_variables: list) -> None:
"""This is a helper method for visualize_multiple_path() method.
The method iterates over the different junctions in a path and makes a link between the 2
markers with the help of folium library plotting methods."""
end_junc_coord = req_road_link_variables[0]
j = 0
for path in list_paths:
if j >= len(colours):
colour = random.choice(colours)
else:
colour = colours[j]
for i in range(len(path) - 2):
start_coord = dict_road_coords[path[i]]
end_coord = dict_road_coords[path[i + 1]]
coordinates = [start_coord, end_coord]
if colour == 'pink':
# Draw the link between each marker.
folium.PolyLine(coordinates, tooltip='<b>Path between ' + path[i] + ' and'
' ' + path[i + 1] + '</b>', color=colour, weight=4.5,
opacity=1
).add_to(req_road_link_variables[1])
else:
# Draw the link between each marker.
folium.PolyLine(coordinates, tooltip='<b>Path between ' + path[i] + ' and'
' ' + path[i + 1] + '</b>', color=colour, weight=4.5,
opacity=0.5
).add_to(req_road_link_variables[1])
start_coord = dict_road_coords[path[-2]]
coordinates = [start_coord, end_junc_coord]
if colour == 'pink':
folium.PolyLine(coordinates, popup='<b>Path traced between the 2 roads</b>',
tooltip='<b>Path between ' + path[-2] + ' and ' + end + '</b>',
color=colour, weight=4.5, opacity=1).add_to(req_road_link_variables[1])
else:
folium.PolyLine(coordinates, popup='<b>Path traced between the 2 roads</b>',
tooltip='<b>Path between ' + path[-2] + ' and ' + end + '</b>',
color=colour, weight=4.5, opacity=0.5
).add_to(req_road_link_variables[1])
j += 1
return None
def helper_plot_shortest_road_links(shortest_path: list, end: str, end_junc_coord: list,
dict_road_coords: dict, plot_map: folium) -> None:
"""This is a helper method for visualize_shortest_path(), visualize_direct_path() and
visualize_path_specific_stops() methods.
The method iterates over the different junctions in a path and makes a link between the 2
markers with the help of folium library plotting methods."""
for i in range(len(shortest_path) - 2):
start_coord = dict_road_coords[shortest_path[i]]
end_coord = dict_road_coords[shortest_path[i + 1]]
coordinates = [start_coord, end_coord]
# Draw the link between each marker.
folium.PolyLine(coordinates, popup='<b></b>',
tooltip='<b>Path between ' + shortest_path[i] + ' and'
' ' + shortest_path[i + 1] + '</b>', color='green', weight=4.5,
opacity=0.5).add_to(plot_map)
start_coord = dict_road_coords[shortest_path[-2]]
coordinates = [start_coord, end_junc_coord]
folium.PolyLine(coordinates, popup='<b>Path traced between the 2 roads</b>',
tooltip='<b>Path between ' + shortest_path[-2] + ' and ' + end + '</b>',
color='green', weight=4.5, opacity=0.5).add_to(plot_map)
return None
def helper_plot_time_road_links(shortest_time_path: list, time_between_juncs: list,
end: str, dict_road_coords: dict,
req_road_link_variables: list) -> None:
"""This is a helper method for visualize_shortest_path() and visualize_path_specific_stops()
methods.
The method iterates over the different junctions in a path and makes a link between the 2
markers with the help of folium library plotting methods."""
end_junc_coord = req_road_link_variables[0]
for i in range(len(shortest_time_path) - 2):
start_coord = dict_road_coords[shortest_time_path[i]]
end_coord = dict_road_coords[shortest_time_path[i + 1]]
coordinates = [start_coord, end_coord]
# Draw the link between each marker.
if isinstance(time_between_juncs[i], str):
folium.PolyLine(coordinates, popup='<b>' + str(time_between_juncs[i]) + '</b>',
tooltip='<b>Path between ' + shortest_time_path[i] + ' and'
' ' + shortest_time_path[i + 1] + '</b>', color='green', weight=4.5,
opacity=0.5).add_to(req_road_link_variables[1])
else:
folium.PolyLine(coordinates, popup='<b>' + str(time_between_juncs[i]) + ' hours </b>',
tooltip='<b>Path between ' + shortest_time_path[i] + ' and'
' ' + shortest_time_path[i + 1] + '</b>', color='green', weight=4.5,
opacity=0.5).add_to(req_road_link_variables[1])
start_coord = dict_road_coords[shortest_time_path[-2]]
coordinates = [start_coord, end_junc_coord]
folium.PolyLine(coordinates, popup='<b>' + str(time_between_juncs[-1]) + ' hours </b>',
tooltip='<b>Path between ' + shortest_time_path[-2] + ' and ' + end + '</b>',
color='green', weight=4.5, opacity=0.5).add_to(req_road_link_variables[1])
return None
if __name__ == '__main__':
# Certain visualizations to try for yourself!
# Multiple paths
# visualize_multiple_path('A406', 'LA Boundary', 10)
# visualize_multiple_path('A23', 'LA Boundary', 10)
# visualize_multiple_path('M1 spur', 'A223', 10)
# visualize_multiple_path('LA Boundary', 'M1 spur', 10)
# Shortest paths
# visualize_shortest_path('LA Boundary', 'M1 spur')
# visualize_shortest_path('M1 spur', 'A223')
# visualize_shortest_path('A406', 'LA Boundary')
# visualize_shortest_path('A23', 'LA Boundary')
# Specific stops
# visualize_path_specific_stops('A406', 'LA Boundary', 1)
# Direct paths
# visualize_direct_path('A406', 'LA Boundary')
# Shortest Time Based stops
# visualize_shortest_time_path('A406', 'M1 spur', 'cycle')
# import python_ta.contracts
# python_ta.contracts.check_all_contracts()
import python_ta
python_ta.check_all(config={
'max-line-length': 100,
'disable': ['E9998'],
'extra-imports': ['folium', 'random', 'classes', 'typing', 'computations'],
'allowed-io': ['classes.get_junctions_location', 'classes.load_graph'],
'max-nested-blocks': 5,
})
|
19dea2cf58c7759caf4ff5eb2b2c48b961f11898 | anilmukkoti/N-Grams | /p1.py | 3,672 | 3.671875 | 4 | import sys
import os
from collections import OrderedDict
import collections
#function to genrate 3,5,7 grams respectively from a given file
def generator(threeg,fiveg,seveng,filename):
sevg = {}
for line in open(filename):
line = line.rstrip()
parts = line.split()
le= len(parts) #total numbers in the text file
# to find seven grams
garam = []
for k in range (0,le-6):
if k == le-7 :
gram = parts[k]+" "+parts[k+1]+" "+parts[k+2]+" "+parts[k+3]+" "+parts[k+4]+" "+parts[k+5]+" "+parts[k+6]
garam = gram
if gram in seveng:
seveng[gram] += 1
else:
seveng[gram] = 1
if gram in sevg:
sevg[gram] += 1
else:
sevg[gram] = 1
else :
gram = parts[k]+" "+parts[k+1]+" "+parts[k+2]+" "+parts[k+3]+" "+parts[k+4]+" "+parts[k+5]+" "+parts[k+6]
if gram in seveng:
seveng[gram] += 1
else:
seveng[gram] = 1
if gram in sevg:
sevg[gram] += 1
else:
sevg[gram] = 1
# to find three grams
# z= len(seveng)
# ak =1
# ab=1
for gram in sevg:
city = gram.split()
gm = city[0]+" "+city[1]+" "+city[2]+" "+city[3]+" "+city[4]
if gm in fiveg:
fiveg[gm] += sevg[gram]
else:
fiveg[gm] = sevg[gram]
#ab= ab +1
city = garam.split()
for j in range(2):
gm = city[j+1]+" "+city[j+2]+" "+city[j+3]+" "+city[j+4]+" "+city[j+5]
if gm in fiveg:
fiveg[gm] += 1
else:
fiveg[gm] = 1
for gram in sevg:
flag = gram.split()
gm = flag[0]+" "+flag[1]+" "+flag[2]
if gm in threeg:
threeg[gm] += sevg[gram]
else:
threeg[gm] = sevg[gram]
#ak= ak +1
#flag = garam.split()
for x in range(4):
gm = city[x+1]+" "+city[x+2]+" "+city[x+3]
if gm in threeg:
threeg[gm] += 1
else:
threeg[gm] = 1
testg={}
traing={}
attacks=["Adduser","Hydra_FTP","Hydra_SSH","Java_Meterpreter","Meterpreter","Web_Shell"]
attak=[dict() for j in range(0,8)]
k=0
for j in attacks:
threeg = {}
fiveg = {}
seveng = {}
s=sys.argv[1:][0]+"/"+j
for i in range(1,8):
d=s+"_"+str(i)
for f in os.listdir(d):
generator(threeg,fiveg,seveng,d+"/"+f)
# print len(seveng)
# print len(threeg)
if sys.argv[1:][2]=="3":
attak[k]=threeg
l=len(threeg)
threeg=collections.Counter(threeg).most_common(int(l*0.3))
for gram in threeg:
traing[gram[0]]=1
if sys.argv[1:][2]=="5":
attak[k]=fiveg
l=len(fiveg)
fiveg=collections.Counter(fiveg).most_common(int(l*0.3))
for gram in fiveg:
traing[gram[0]]=1
if sys.argv[1:][2]=="7":
attak[k]=seveng
l=len(seveng)
if j == "Adduser":
print l*0.3
seveng=collections.Counter(seveng).most_common(int(l*0.3))
for gram in seveng:
traing[gram[0]]=1
k=k+1
normal={}
d="ADFA-LD/Training_Data_Master"
for f in os.listdir(d):
threeg = {}
fiveg = {}
seveng = {}
generator(threeg,fiveg,seveng,d+"/"+f)
if sys.argv[1:][2]=="3":
normal=threeg
l=len(threeg)
threeg=collections.Counter(threeg).most_common(int(l*0.3))
for gram in threeg:
traing[gram[0]]=1
if sys.argv[1:][2]=="5":
normal=fiveg
l=len(fiveg)
fiveg=collections.Counter(fiveg).most_common(int(l*0.3))
for gram in fiveg:
traing[gram[0]]=1
if sys.argv[1:][2]=="7":
normal=seveng
l=len(seveng)
seveng=collections.Counter(seveng).most_common(int(l*0.3))
for gram in seveng:
traing[gram[0]]=1
file=open(sys.argv[1:][1]+"_"+str(sys.argv[1:][2]),"w")
for i in range(6):
testg=attak[i]
file.write(attacks[i]+"\n")
for gram in traing:
if gram in testg:
file.write(str(testg[gram])+"\t\t"+gram+"\n")
else:
file.write("0\t\t"+gram+"\n")
testg=normal
file.write("normal\n")
for gram in traing:
if gram in testg:
file.write(str(testg[gram])+"\t\t"+gram+"\n")
else:
file.write("0\t\t"+gram+"\n")
file.close() |
6539a31944533ec5f38a454b4b6b52d6956e689f | 9838dev/coding | /stack/longest_valid_parenthesis.py | 395 | 3.828125 | 4 | # longest valid parenthesis
def longest_valid(s):
st=[-1]
res=0
for i in range(len(s)):
if s[i] == '(':
st.append(i)
else:
if len(st)>0:
st.pop()
if len(st)>0:
res = max(res,i-st[-1])
else:
st.append(i)
print(res)
s = input("Enter any string")
longest_valid(s)
|
0a251292ae4ac80a6fce824f5a35c1d23319ac75 | archerw105/machine-learning | /perceptron.py | 1,769 | 3.65625 | 4 | import numpy as np
class Perceptron:
def __init__(self, input_num):
"""
Parameters
----------
input_num: number of input variables for 1-layer neural network
Notes
-----
0-th index reserved for bias value
"""
self.weights = np.zeros(input_num+1)
def train(self, training_data, l_rate, threshold):
"""Standard gradient descent
Parameters
----------
training_data: input matrix appended by target column vector
l_rate: learning rate
threshold: number of iterations (epochs)
"""
for _ in range(threshold):
sum_error = 0.0
for row in training_data:
input = row[:-1]
target = row[-1]
error = self.predict(input) - target
#cost = 1/2*(error)**2
self.weights[0] -= error*l_rate
for i in range(len(row)-1):
self.weights[i+1] -= error*row[i]*l_rate
return self.weights
def predict(self, input):
"""
Parameters
----------
input: input row vector
"""
activation = np.dot(self.weights[1:], input) + self.weights[0]
if activation >= 0:
return 1
else:
return 0
dataset = [[2.7810836,2.550537003,0],
[1.465489372,2.362125076,0],
[3.396561688,4.400293529,0],
[1.38807019,1.850220317,0],
[3.06407232,3.005305973,0],
[7.627531214,2.759262235,1],
[5.332441248,2.088626775,1],
[6.922596716,1.77106367,1],
[8.675418651,-0.242068655,1],
[7.673756466,3.508563011,1]]
l_rate = 0.1
n_epoch = 5
a = Perceptron(2)
weights = a.train(dataset, l_rate, n_epoch)
print(weights) |
202643e91e884002eeaea357154484831c7c6d0b | eroicaleo/LearningPython | /interview/leet/240_Search_a_2D_Matrix_II.py | 3,019 | 3.578125 | 4 | #!/usr/bin/env python
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
self.count = 0
if len(matrix) > 0 and len(matrix[0]) > 0:
return self.search2DArray(matrix, target, 0, 0, len(matrix)-1, len(matrix[0])-1)
return False
def search2DArray(self, matrix, target, i0, j0, i1, j1):
self.count += 1
if self.count > 50:
return False
print("i0, j0, i1, j1 = ", (i0, j0, i1, j1))
if i0 > i1 or j0 > j1:
return False
midi = (i1+i0)//2
midj = (j0+j1)//2
bot = matrix[i1][midj]
top = matrix[i0][midj]
lft = matrix[midi][j0]
rit = matrix[midi][j1]
mid = matrix[midi][midj]
print('(bot, top, lft, rit, mid) = ', (bot, top, lft, rit, mid))
if target in (bot, top, lft, rit, mid):
print('hit the target: ', (bot, top, lft, rit, mid))
return True
if target > bot:
print('I am in 1')
return self.search2DArray(matrix, target, i0, midj+1, i1, j1)
if target < top:
print('I am in 2')
return self.search2DArray(matrix, target, i0, j0, i1, midj-1)
if target > rit:
print('I am in 3')
return self.search2DArray(matrix, target, midi+1, j0, i1, j1)
if target < lft:
print('I am in 4')
return self.search2DArray(matrix, target, i0, j0, midi-1, j1)
print('I am in region1')
region1 = self.search2DArray(matrix, target, i0, midj, midi, j1)
if region1 == True:
return True
print('I am in region2')
region2 = self.search2DArray(matrix, target, midi, j0, i1, midj)
if region2 == True:
return True
if target < mid:
print('I am in 5')
region3 = self.search2DArray(matrix, target, i0, j0, midi-1, midj-1)
elif target > mid:
print('I am in 6')
region3 = self.search2DArray(matrix, target, midi+1, midj+1, i1, j1)
return region3
sol = Solution()
matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
matrix = [
[ 48, 65, 70, 113, 133, 163, 170, 216, 298, 389],
[ 89, 169, 215, 222, 250, 348, 379, 426, 469, 554],
[178, 202, 253, 294, 367, 392, 428, 434, 499, 651],
[257, 276, 284, 332, 380, 470, 516, 561, 657, 698],
[275, 331, 391, 432, 500, 595, 602, 673, 758, 783],
[357, 365, 412, 450, 556, 642, 690, 752, 801, 887],
[359, 451, 534, 609, 654, 662, 693, 766, 803, 964],
[390, 484, 614, 669, 684, 711, 767, 804, 857,1055],
[400, 515, 683, 732, 812, 834, 880, 930,1012,1130],
[480, 538, 695, 751, 864, 939, 966,1027,1089,1224]]
# print(sol.searchMatrix(matrix, 5))
print(sol.searchMatrix(matrix, 642))
|
f3fbb0f8f59c70cf648f688c45addc4447b3a477 | nguyenhai31096/nguyentronghai-fundamentals-c4e29 | /Session02/homework/Serious_ex04.py | 443 | 4 | 4 | #ex 4a
print(20*"* ")
#ex 4b
n = int(input("enter n: "))
print(n*"* ")
#ex 4c
for i in range(9):
print("X * ", end='')
print("X", end='')
#ex 4e
print()
#ex 4d
n = int(input("enter n: "))
for i in range(n):
print("X * ", end='')
print("X", end='')
#ex_4f
for i in range(3):
print(7*"* ", end='')
print()
#ex_4g
n = int(input("enter n: "))
m = int(input("enter m: "))
for i in range (m):
print(n*"* ")
print() |
d6a4080867317f34c249c701b6010d1a0634cc67 | brunobara/lista1 | /exercicio4.py | 280 | 3.59375 | 4 | """
Exercício 4
Escreva um programa que ache e imprima os números divisíveis por 13 e por 19, entre o ano
de nascimento da sua mãe e 2727.
"""
for i in range(1957,2728):
if (i % 13 == 0):
print(i)
elif (i % 19 == 0):
print(i)
else:
pass
|
6f35a607ec2d8a0abbf3d99f490f9a2ddbbe8951 | jokeefe1/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,204 | 3.90625 | 4 | l = [ 8, 4, 2, 6, 7, 0]
# TO-DO: implement the Insertion Sort function below
def insertion_sort( arr ):
for index in range(1, len(arr)):
while index > 0 and arr[index] < arr[index -1]:
arr[index], arr[index - 1] = arr[index - 1], arr[index]
index -= 1
print(arr)
return arr
# TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
spot_marker = 0
while spot_marker <= len(arr):
for index in range(spot_marker, len(arr)):
if arr[index] < arr[spot_marker]:
arr[index], arr[spot_marker] = arr[spot_marker], arr[index]
print(arr)
spot_marker += 1
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort( arr ):
swap_happened = True
while swap_happened:
swap_happened = False
for index in range(len(arr) -1):
if arr[index] > arr[index + 1]:
swap_happened = True
arr[index], arr[index + 1] = arr[index + 1], arr[index]
print(arr)
return arr
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
return arr
|
37d979504c21cbf250796c97791e33ed2b323255 | JoelWebber/ICTPRG-Python | /Week5 210329/week5quiz1question5.py | 258 | 4.1875 | 4 | inputValue = ""
numberList = []
while (inputValue != 'x'):
inputValue = input("Please enter numbers. If you enter x you will be shown all the numbers you have entered ")
if (inputValue != 'x'):
numberList.append(inputValue)
print(numberList) |
e9c3d8ba0263b88ba6a8092a58e3970338d7dacb | Superbeet/LeetCode | /Word_Search_II.py | 1,656 | 4.03125 | 4 | class TrieNode(object):
def __init__(self, val):
self.val = val
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode("")
def insert(self, val):
node = self.root
for letter in val:
if letter not in node.children:
node.children[letter] = TrieNode(letter)
node = node.children[letter]
node.is_word = True
class Solution(object):
def findWords(self, board, words):
# write your code here
if not board:
return []
h = len(board)
w = len(board[0])
trie = Trie()
for word in words:
trie.insert(word)
result = []
for j in xrange(h):
for i in xrange(w):
self.dfs(board, trie.root, w, h, i, j, "", result)
return sorted(result)
def dfs(self, board, node, m, n, x, y, word, result):
if node.is_word:
result.append(word)
node.is_word = False
if x < 0 or x >= m or y < 0 or y >= n:
return
curr = board[y][x]
if curr == "#":
return
if curr not in node.children:
return
dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for nx, ny in dirs:
dx = x + nx
dy = y + ny
board[y][x] = "#"
self.dfs(board, node.children[curr], m, n, dx, dy, word + curr, result)
board[y][x] = curr
|
812374e52769785e9e779046d7f43a7a69a3eacc | nmoore32/Python-Workbook | /6 Dictionaries/exercise146.py | 1,450 | 3.96875 | 4 | ##
# Creates and displays a random Bingo card (without free space)
#
from random import randrange
NUMS_PER_LETTER = 15
# Creates a random Bingo card
# @return a dictionary containing B I N G O as keys and lists of 5 numbers as values
def createBingo():
# Create empty dictionary
card = {}
# Variables to track the range of values for the current letter
lower = 1
upper = 1 + NUMS_PER_LETTER
# For each of the five letters
for letter in ["B", "I", "N", "G", "O"]:
# Create an empty list to the store the generated values
card[letter] = []
# Generate five unique values and add them to the list
while len(card[letter]) < 5:
next_num = randrange(lower, upper)
if next_num not in card[letter]:
card[letter].append(next_num)
# Update the range values for the next letter
lower += NUMS_PER_LETTER
upper += NUMS_PER_LETTER
# Return the result
return card
# Displays a Bingo card
# @param card the card to display
# @return (None)"""
def displayBingo(card):
for key in card:
print(f" {key}", end=" ")
print()
i = 0
while i < 5:
for value in card.values():
print(f"{value[i]:2d}", end=" ")
print()
i += 1
# Generage a display a random Bingo card
def main():
card = createBingo()
displayBingo(card)
if __name__ == "__main__":
main()
|
51987c189ca48fc49e7761f5be2cb289ed91fc55 | sunbin1993/machine-learning | /MyPython/src/python/hello.py | 734 | 4.4375 | 4 | #!/usr/bin/python3
print("hello world")
# 第一个注释
'''
python 动态语言
数据类型:支持 整数(无大小限制)、浮点数(无大小限制 超过一定范围inf)、字符串、布尔值、空值、
变量:变量名必须是大小写英文、数字和_的组合,且不能用数字开头
常量:
'''
"""
sdfsdf
"""
if True:
print("True")
else:
print("Flase")
'''
字符串
'''
str='Runoob'
print(str)
print(str[0:-1])
print(str[0])
print(str[2:5])
print(str[2:])
print(str * 2,end="") #end="" print不换行
print(str + ' 你好')
print('--------------------------')
print('hello\nrunoob')
print(r'hello\nrunoob')
'''
等待用户输入
'''
input("\n\n按下 enter 键退出")
|
637cedc4a95b9e3e2826d1fa7193e69c1cfe62ae | DZykov/Space-Invaders | /Environment.py | 23,046 | 3.8125 | 4 | import random
from pygame import *
import pygame
import math
import sys
import datetime
class Player(sprite.Sprite):
"""
This is a Player Class which is a subclass of pygame.sprite.Sprite
Player Class creates controllable object
Attributes:
x: An integer represents x coordinate
y: An integer represents y coordinate
size: An integer represents the size of the player
image: An image which is loaded to the memory
rect: The outline of the image; needed for detecting collisions
screen_size: A Tuple(Integer, Integer) represents the screen size
health: An integer represent the health of the player
"""
def __init__(self, screen_size, size, color):
"""
Inits Player class with given attributes
"""
sprite.Sprite.__init__(self)
self.x = screen_size[0] / 2
self.y = screen_size[1] - size - 5
self.size = size
self.color = color + (255,)
self.image = pygame.transform.scale((image.load("Objects/ship.png")),
(size, size))
self.image = pygame.transform.rotate(self.image, 135)
pixels = PixelArray(self.image)
pixels.replace(Color(255, 255, 255, 255), self.color)
del pixels
self.rect = self.image.get_rect(center=(self.x, self.y))
self.screen_size = screen_size
self.health = 10
self.speedx = 5
self.speedy = 5
def move(self, x, y):
"""
Moves Player by given x and y
"""
self.x += x
self.y += y
self.rect = self.rect.move((x, y))
def update(self):
"""
Overrides and calls the update method for this specific sprite
"""
pressed_key = pygame.key.get_pressed()
if pressed_key[pygame.K_LEFT]:
if 0 <= self.x - self.speedx <= self.screen_size[0]:
self.move(-self.speedx, 0)
if pressed_key[pygame.K_RIGHT]:
if 0 <= self.x + self.speedx <= self.screen_size[0]:
self.move(self.speedx, 0)
class Bullet(sprite.Sprite):
"""
This is a Bullet Class which is a subclass of pygame.sprite.Sprite
Bullet Class creates uncontrollable object with specific behaviour
Attributes:
x: An integer represents x coordinate
y: An integer represents y coordinate
image: An image which is loaded to the memory
rect: The outline of the image; needed for detecting collisions
screen_size: A Tuple(Integer, Integer) represents the screen size
speedx: An integer represents the speed of Bullet on x-axis
speedy: An integer represents the speed of Bullet on y-axis
"""
def __init__(self, x, y, speedy, speedx, screen_size, color):
"""
Inits Bullet class with given attributes
"""
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((2, 8))
self.color = color
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.bottom, self.y = y, y
self.rect.centerx, self.x = x, x
self.speedy = speedy
self.speedx = speedx
self.screen_size = screen_size # this part is undone
def update(self):
"""
Overrides and calls the update method for this specific sprite
"""
self.rect.y += self.speedy
self.rect.x += self.speedx
self.y += self.speedy
self.x += self.speedx
if self.y < 0 or self.y > self.screen_size[1] or \
self.x < 0 or self.x > self.screen_size[0]:
self.kill()
class Invader(sprite.Sprite):
"""
This is an Invader Class which is a subclass of pygame.sprite.Sprite
Invader Class creates uncontrollable object
Attributes:
x: An integer represents x coordinate
y: An integer represents y coordinate
size: An integer represents the size of the player
image: An image which is loaded to the memory
rect: The outline of the image; needed for detecting collisions
screen_size: A Tuple(Integer, Integer) represents the screen size
health: An integer represent the health of the player
"""
def __init__(self, screen_size, size, string, x, y):
"""
Inits Invader class with given attributes
"""
sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.size = size
self.image = pygame.transform.scale((image.load(string)),
(size, size))
self.rect = self.image.get_rect(center=(self.x, self.y))
self.screen_size = screen_size
self.health = 1
def move(self, x, y, enemies_left):
"""
Moves Invader by given x and y
"""
if enemies_left > 14:
if 0 <= self.x + x <= self.screen_size[0] and 0 <= self.y + y <= \
self.screen_size[1]:
self.x += x
self.y += y
self.rect = self.rect.move((x, y))
else:
if 0 <= self.x + x <= self.screen_size[0] and 0 <= self.y + self.get_sin(self.x) <= \
self.screen_size[1]:
self.x += x
self.y += self.get_sin(self.x)
self.rect = self.rect.move((x, self.get_sin(self.x)))
elif 0 <= self.x + x <= self.screen_size[0] and self.y + self.get_sin(self.x) >= \
self.screen_size[1]:
self.x += x
self.y -= self.get_sin(self.x)
self.rect = self.rect.move((x, -self.get_sin(self.x)))
def get_sin(self, x) -> float:
"""
Returns the value of sin(<X>) as relative to the screen.
"""
y = -2*math.sin(x/10)
return y
class InvadersGroup(sprite.Group):
"""
This is an InvadersGroup Class which is a subclass of pygame.sprite.Group
InvadersGroup Class is a collection of uncontrollable objects that
subclasses of pygame.sprite.Sprite
Attributes:
screen_size: A Tuple(Integer, Integer) represents the size of a screen
size: An integer represents the size of each member of InvadersGroup
space: An integer represent the space between each member
invaders: A list with every member of InvadersGroup Class
de_way: A string "L" or "R" indicates the direction of movement
died: An integer represents the number of members destroyed
"""
def __init__(self, screen_size, size, space):
"""
Init InvadersGroup with given attributes
"""
sprite.Group.__init__(self)
self.screen_size = screen_size
self.size = size
self.space = space
self.invaders = []
self.de_way = "R"
self.died = 0
def move(self, x, y, health):
"""
Moves each member of InvadersGroup by given x and y
"""
for invader in self.invaders:
invader.move(x, y, len(self.invaders))
def update(self, health):
"""
Calls the update method of every member sprite
Group.update(*args): return None
Calls the update method of every member sprite. All arguments that
were passed to this method are passed to the Sprite update function.
"""
if len(self.invaders) == 0:
pass
elif self.de_way == "L":
self.move(-1, 0, health)
if self.invaders[0].x - self.invaders[-1].size <= 0:
self.de_way = "R"
elif self.de_way == "R":
self.move(1, 0, health)
if self.invaders[-1].x >= \
self.screen_size[0] - self.invaders[-1].size - self.space:
self.de_way = "L"
def add_internal(self, *sprites):
"""
Adds new member to InvadersGroup
"""
super(InvadersGroup, self).add_internal(*sprites)
for s in sprites:
self.invaders.append(s)
def remove_internal(self, *sprites):
"""
Removes and deletes all given sprite from InvadersGroup
"""
super(InvadersGroup, self).remove_internal(*sprites)
for s in sprites:
self.kill(s)
def kill(self, enemy):
"""
Deletes given member of InvadersGroup and deletes given sprite itself
"""
self.died = +1
self.invaders.remove(enemy)
del enemy
def shooter(self):
"""
Chooses random member of InvadersGroup and return its coordinates
"""
if len(self.invaders) > 0:
shoot = pygame.mixer.Sound('Sounds/laser_invader.ogg')
shoot.play()
a = random.choice(self.invaders)
return a.x, a.y
class Barrier(sprite.Sprite):
def __init__(self, screen_size, size, string1, string2, string3, x, y):
sprite.Sprite.__init__(self)
self.health = 10
self.x = x
self.y = y
self.size = size
self.image = pygame.transform.scale((image.load(string1)), (size * 3, size))
self.image2 = pygame.transform.scale((image.load(string2)), (size * 3, size))
self.image3 = pygame.transform.scale((image.load(string3)), (size * 3, size))
self.rect = self.image.get_rect(center=(self.x * 5, self.y))
self.screen_size = screen_size
def move(self, x, y):
if 0 <= self.x + x <= self.screen_size[0] and 0 <= self.y + y <= \
self.screen_size[1]:
self.x += x
self.y += y
self.rect = self.rect.move((x, y))
def update(self):
if 0 < self.health < 7:
self.image = self.image2
if 0 < self.health < 3:
self.image = self.image3
class BarrierGroup(sprite.Group):
def __init__(self, screen_size, size, space):
sprite.Group.__init__(self)
self.screen_size = screen_size
self.size = size
self.space = space
self.barriers = []
self.way = "R"
def move(self, x, y):
for barrier in self.barriers:
barrier.move(x, y)
def move(self, x, y):
for barrier in self.barriers:
barrier.move(x, y)
def update(self):
if len(self.barriers) == 0:
pass
elif self.way == "L":
self.move(-1, 0)
if self.barriers[0].x - self.barriers[-1].size <= 20:
self.way = "R"
elif self.way == "R":
self.move(1, 0)
if self.barriers[-1].x >= \
self.screen_size[0] - 2.5*self.space - self.barriers[-1].size :
self.way = "L"
def add_internal(self, *sprites):
super(BarrierGroup, self).add_internal(*sprites)
for x in sprites:
self.barriers.append(x)
def remove_internal(self, *sprites):
"""
Removes and deletes all given sprite from InvadersGroup
"""
super(BarrierGroup, self).remove_internal(*sprites)
for x in sprites:
self.barriers.remove(x)
del x
class Environment(object):
"""
Creates environment, all objects and 'physics'
"""
def __init__(self, color):
"""
Inits Environment class
"""
pygame.init()
pygame.mixer.music.load('Music/8_bit_song.ogg')
pygame.mixer.music.play(-1)
background = (0, 0, 0)
self.screen_size = (800, 400)
self.size = 30
self.gap = 20
self.color = color
self.max_bullets = 3 # number of bullets allowed
self.bullets = sprite.Group()
self.enemy_bullets = sprite.Group()
self.invaders = self.create_invaders()
self.barriers = self.create_barriers()
self.keys = key.get_pressed()
self.screen = pygame.display.set_mode(
(self.screen_size[0], self.screen_size[1]))
self.play = True
self.clock = pygame.time.Clock()
self.player = Player(self.screen_size, self.size, self.color)
self.all_sprites = sprite.Group()
self.all_sprites.add(self.player)
self.start_time = datetime.datetime.now()
self.ship_hit = False
self.dead = False
pygame.font.init()
default_font = pygame.font.get_default_font()
font_renderer = pygame.font.Font(default_font, 20)
label_lost = font_renderer.render(str("YOU LOST!"), 1, (255, 255, 255))
label_win = font_renderer.render(str("YOU WON!"), 1, (255, 255, 255))
edge_crossed = False
while self.play:
self.clock.tick(60)
self.screen.fill(background)
self.check_control()
self.check_collision()
self.invaders_shoot()
self.all_sprites.update()
self.invaders.update(self.player.health)
self.barriers.update()
self.invaders.draw(self.screen)
self.barriers.draw(self.screen)
self.all_sprites.draw(self.screen)
if self.dead:
self.screen.blit(label_lost, (self.screen_size[0]/2, self.screen_size[1]/3))
self.player.move(0, self.player.speedy)
if len(self.invaders) == 0:
self.screen.blit(label_win, (self.screen_size[0] / 2, self.screen_size[1] / 3))
if self.player.y >= 0:
self.player.move(0, -self.player.speedy)
else:
edge_crossed = True
if edge_crossed:
self.play = False
main()
pygame.display.flip()
def check_control(self):
"""
This method check for keyboard interaction which influences
only Environment
"""
self.keys = key.get_pressed()
for e in event.get():
if e.type == pygame.QUIT:
self.play = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_SPACE:
if len(self.bullets) < self.max_bullets:
shoot = pygame.mixer.Sound('Sounds/laser_ship.ogg')
shoot.play()
bullet = Bullet(self.player.x,
self.player.y - self.player.size, -3, 0,
self.screen_size, (255, 255, 0))
self.bullets.add(bullet)
self.all_sprites.add(self.bullets)
def check_collision(self):
"""
Preconditions: self.invaders, self.bullets, self.enemy_bullets and
self.player are initialized anf none empty
Checks the collision for all objects in the Environment and proceeds
with specific instructions
"""
pygame.font.init()
default_font = pygame.font.get_default_font()
font_renderer = pygame.font.Font(default_font, 14)
hits = pygame.sprite.groupcollide(self.invaders, self.bullets, False,
True)
for hit in hits:
hit.health = hit.health - 1
if hit.health <= 0:
shoot = pygame.mixer.Sound('Sounds/explosion_invader.ogg')
shoot.play()
self.invaders.remove_internal(hit)
pygame.sprite.groupcollide(self.enemy_bullets, self.bullets, True, True)
if pygame.sprite.spritecollide(self.player, self.enemy_bullets, True):
self.ship_hit = True
self.player.health = self.player.health - 1
if self.player.health <= 0:
self.dead = True
shoot = pygame.mixer.Sound('Sounds/ship_explosion.wav')
shoot.play()
self.player.speedx = 0
if self.ship_hit:
label = font_renderer.render(
str(self.player.health), 1, (255, 255, 255))
self.screen.blit(label, (self.player.x + 15, self.player.y - 7))
diff_sec = (datetime.datetime.now() - self.start_time).total_seconds()
if diff_sec > 5:
self.start_time = datetime.datetime.now()
self.ship_hit = False
if self.dead:
self.play = False
main()
hit_barrier = pygame.sprite.groupcollide(self.barriers, self.enemy_bullets, False, True)
for hit in hit_barrier:
hit.health = hit.health - 1
hit.update()
if hit.health <= 0:
shoot = pygame.mixer.Sound('Sounds/barrier_explosion.ogg')
shoot.play()
self.barriers.remove_internal(hit)
def create_invaders(self):
"""
Create all needed Invaders for Environment and returns them as
InvadersGroup
"""
invaders = InvadersGroup(self.screen_size, self.size, self.gap)
n = int(
self.screen_size[0] / 100 * 75 /
(self.size + self.gap))
break_p = self.size + self.gap
for i in range(n):
invader = Invader(self.screen_size, self.size, "Objects/invader1.png",
i * (self.gap + self.size), break_p)
invaders.add(invader)
for i in range(n):
invader = Invader(self.screen_size, self.size, "Objects/invader2.png",
i * (self.gap + self.size), 2 * break_p)
invaders.add(invader)
for i in range(n):
invader = Invader(self.screen_size, self.size, "Objects/invader3.png",
i * (self.gap + self.size), 3 * break_p)
invaders.add(invader)
return invaders
def create_barriers(self):
"""
This method create barriers as pygroup
:return: pygroup
"""
barriers = BarrierGroup(self.screen_size, self.size, self.gap * 10)
n = 3
h = 260
for i in range(n):
barrier = Barrier(self.screen_size, self.size, "Objects/asteroid 1.png", "Objects/asteroid 2.png", "Objects/asteroid 3.png",
i * (self.gap + self.size), h)
barriers.add(barrier)
return barriers
def invaders_shoot(self):
"""
Preconditions: self.invaders is initialized and none empty
Makes randomly chosen Invader to shoot
"""
if len(self.invaders) > 0:
a = random.randint(0, 1000)
if a <= 70:
x, y = self.invaders.shooter()
bullet = Bullet(x, y + self.size, 3, 0, self.screen_size, (255, 0, 0))
self.enemy_bullets.add(bullet)
self.all_sprites.add(self.enemy_bullets)
class Menu(object):
"""
This class creates a main meany at the start.
"""
def __init__(self) -> bool:
self.screen_size = (800, 400)
background = (0, 0, 0)
self.screen = pygame.display.set_mode((self.screen_size[0], self.screen_size[1]))
pygame.display.set_caption('Space Invaders')
self.run = True
self.clock = pygame.time.Clock()
while self.run:
self.screen.fill(background)
TS, TR = text_objects("SPACE INVADERS: The Next Frontier", 40)
TS1, TR1 = text_objects("Press F to Start", 15)
TR.center = (self.screen_size[0] // 2, 100)
TR1.center = (self.screen_size[0] // 2, self.screen_size[1] // 2 + 85)
self.screen.blit(TS, TR)
self.screen.blit(TS1, TR1)
pygame.display.update()
ev = pygame.event.get()
for event in ev:
if event.type == pygame.KEYDOWN and pygame.key.get_pressed()[K_f]:
self.run = False
if event.type == pygame.QUIT:
sys.exit(0)
class CharacterSelect(object):
"""
This class does character selection menu.
"""
def __init__(self):
self.screen_size = (800, 400)
background = (0, 0, 0)
self.screen = pygame.display.set_mode((self.screen_size[0], self.screen_size[1]))
self.run = True
self.clock = pygame.time.Clock()
self.ship_col = 0
while self.run:
self.screen.fill(background)
position = draw_menu(self.screen, 150, 55, 0)
TS, TR = text_objects("DOUBLE CLICK to select ship color", 30)
TR.center = (self.screen_size[0] // 2, 20)
self.screen.blit(TS, TR)
pygame.display.update()
ev = pygame.event.get()
for event in ev:
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in range(len(position)):
if position[i][0] <= pos[0] <= position[i][0] + 150 and position[i][1] <= pos[1] \
<= position[i][1] + 100:
self.ship_col = i
self.run = False
break
break
def text_objects(text, size):
"""
Function returns <textSurface> and the rect surrounding the surface.
"""
pygame.font.init()
BASICFONT = pygame.font.SysFont('Arial', size)
textSurface = BASICFONT.render(text, True, (255, 255, 255))
return textSurface, textSurface.get_rect()
def draw_menu(screen, x, y, row):
"""Draws the necessary menu layout on the screen"""
colors = {0: (255, 6, 80), 1: (218, 165, 32), 2: (107, 142, 35),
3: (64, 224, 208), 4: (153, 255, 204), 5: (111, 90, 255),
6: (169, 169, 169), 7: (240, 230, 140), 8: (255, 64, 255)}
position = []
while row < 3:
color = 0
if row is 0:
for i in range(3):
position.append((x, y))
pygame.draw.rect(screen, colors[color], (x, y, 150, 100))
x += 165
color += 1
elif row is 1:
y += 115
color = 3
for i in range(3):
position.append((x, y))
pygame.draw.rect(screen, colors[color], (x, y, 150, 100))
x += 165
color += 1
else:
y += 230
color = 6
for i in range(3):
position.append((x, y))
pygame.draw.rect(screen, colors[color], (x, y, 150, 100))
x += 165
color += 1
x, y, = 150, 55
row += 1
return position
def main():
Menu()
CharacterSelect()
color = CharacterSelect().ship_col
colors = {0: (255, 6, 80), 1: (218, 165, 32), 2: (107, 142, 35),
3: (64, 224, 208), 4: (153, 255, 204), 5: (111, 90, 255),
6: (169, 169, 169), 7: (240, 230, 140), 8: (255, 64, 255)}
Environment(colors[color])
if __name__ == '__main__':
main()
|
939cd99929188e4251248a229a08d5ce47bd5339 | Randyedu/python | /知识点/04-LiaoXueFeng-master/67-SMTP.py | 9,830 | 3.546875 | 4 | '''
SMTP发送邮件
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
'''
'''
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
'''
from email.mime.text import MIMEText
# 构造一个最简单的纯文本邮件:
# 第一个参数就是邮件正文
# 第二个参数是MIME的subtype,传入'plain'表示纯文本,最终的MIME就是'text/plain'
# 最后一定要用utf-8编码保证多语言兼容性。
msg = MIMEText('hello , send by Python...','plain','utf-8')
# 输入Email地址和口令:
from_addr = '921550356@qq.com'
password = 'balabala'
# 输入收件人地址:
to_addr = 'To:weiyq10580@hundsun.com'
# 输入SMTP服务器地址:
smtp_server = 'smtp.qq.com'
import smtplib
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
仔细观察,发现如下问题:
1、邮件没有主题;
2、收件人的名字没有显示为友好的名字,比如Mr Green <green@example.com>;
3、明明收到了邮件,却提示不在收件人中。
这是因为邮件主题、如何显示发件人、收件人等信息并不是通过SMTP协议发给MTA
而是包含在发给MTA的文本中的.
我们必须把From、To和Subject添加到MIMEText中,才是一封完整的邮件:
'''
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
import smtplib
def _format_addr(s):
name,addr = parseaddr(s)
return formataddr((Header(name,'utf-8').encode(),addr))
msg = MIMEText('Hello,send by Python...','plain','utf-8')
msg['From'] = _format_addr('Python爱好者<%s>' %from_addr)
msg['To'] = _format_addr('管理员<%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候....','utf-8').encode()
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
发送HTML邮件
在构造MIMEText对象时,把HTML字符串传进去,再把第二个参数由plain变为html就可以了:
'''
with open('samples/sina.html','rb') as f:
nine = f.read()
msg = MIMEText(nine,'html','utf-8')
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
发送附件
带附件的邮件可以看做包含若干部分的邮件:文本和各个附件本身.
所以,可以构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象即可:
'''
msg = MIMEMultipart()
msg['From'] = _format_addr('Python爱好者<%s>' %from_addr)
msg['To'] = _format_addr('管理员<%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候....','utf-8').encode()
# 邮件正文是MIMEText:
msg.attach(MIMEText('send with file...','plain','utf-8'))
# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('samples/sample.png','rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image','png',filename='name-sample.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition','attachment',filename='name-sample.png')
mime.add_header('Content-ID','<0>')
mime.add_header('X-Attachment-ID','0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
发送图片
把一个图片嵌入到邮件正文中.
直接在HTML邮件中链接图片地址行不行?答案是,大部分邮件服务商都会自动屏蔽带有外链的图片,因为不知道这些链接是否指向恶意网站。
要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。
如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。
把上面代码加入MIMEMultipart的MIMEText从plain改为html,然后在适当的位置引用图片:
'''
msg = MIMEMultipart()
msg['From'] = _format_addr('Python爱好者<%s>' %from_addr)
msg['To'] = _format_addr('管理员<%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候....','utf-8').encode()
# 邮件正文是MIMEText:
msg.attach(MIMEText('<html><body><h1>hello</h1>'+'<p><img src="cid:0"></p>'+'</body></html>','html','utf-8'))
# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('samples/sample.png','rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image','png',filename='name-sample.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition','attachment',filename='name-sample.png')
mime.add_header('Content-ID','<0>')
mime.add_header('X-Attachment-ID','0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
同时支持HTML和Plain格式
如果我们发送HTML邮件,收件人通过浏览器或者Outlook之类的软件是可以正常浏览邮件内容的,但是,如果收件人使用的设备太古老,查看不了HTML邮件怎么办?
办法是在发送HTML的同时再附加一个纯文本,如果收件人无法查看HTML格式的邮件,就可以自动降级查看纯文本邮件。
利用MIMEMultipart就可以组合一个HTML和Plain,要注意指定subtype是alternative:
'''
msg = MIMEMultipart('alternative')
msg['From'] = _format_addr('Python爱好者<%s>' %from_addr)
msg['To'] = _format_addr('管理员<%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候....','utf-8').encode()
msg.attach(MIMEText('hello','plain','utf-8'))
msg.attach(MIMEText('<html><body><h1>hello</h1></body></html>','html','utf-8'))
if __name__ != '__main__':
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
# 用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
# login()方法用来登录SMTP服务器
server.login(from_addr,password)
# sendmail()方法就是发邮件
# 由于可以一次发给多个人,所以传入一个list
# 邮件正文是一个str,as_string()把MIMEText对象变成str。
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
'''
加密SMTP
使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。
要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件。
'''
'''
某些邮件服务商,例如Gmail,提供的SMTP服务必须要加密传输。我们来看看如何通过Gmail提供的安全SMTP发送邮件。
必须知道,Gmail的SMTP端口是587,因此,修改代码如下:
smtp_server = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 剩下的代码和前面的一模一样:
server.set_debuglevel(1)
...
只需要在创建SMTP对象后,立刻调用starttls()方法,就创建了安全连接。
'''
|
129b8f111c1892590fb2a72df05005545a0d5471 | pepsipepsi/nodebox_opengl_python3 | /examples/Math/HowCurvesWork.py | 1,704 | 3.78125 | 4 | import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
# This boring example demonstrate how curves work, and goes a bit
# into the different parameters for drawing curves on screen.
import math
def draw(canvas):
canvas.clear()
# Setup colors: no fill is needed, and stroke the curves with black.
nofill()
stroke(0)
# Set the initial position
x,y = 50, 50
width = 50
# The dx and dy parameters are the relative control points.
# When using math.pi/2, you actually define the lower half
# of a circle.
dy = width/(math.pi / 2)
# Begin drawing the path. The starting position is on the
# given x and y coordinates.
beginpath(x, y)
# Calculate the control points.
cp1 = (x, y + dy)
cp2 = (x + width, y + dy)
# Draw the curve. The first four parameters are the coordinates
# of the two control curves; the last two parameters are
# the coordinates of the destination point.
curveto(cp1[0], cp1[1], cp2[0], cp2[1], x + width, y)
# End the path; ending the path automatically draws it.
endpath()
# To demonstrate where the control points actually are,
# we draw them using lines.
# The first control point starts at the x,y position.
line(x, y, cp1[0], cp1[1])
# The second control point is the ending point.
line(x + width, y, cp2[0], cp2[1])
# To liven things up just a little bit, little ovals are
# drawn in red on the position of the control points.
nostroke()
fill(1,0,0)
oval(cp1[0] - 2, cp1[1] - 2, 4, 4)
oval(cp2[0] - 2, cp2[1] - 2, 4, 4)
canvas.size = 500,500
canvas.run(draw) |
afc759e8c83496767ae61a3f1d8a27f79c900a58 | chfumero/operationsonfractions | /operationsonfractions/__main__.py | 684 | 3.9375 | 4 | import argparse
from .expression_eval import expression_eval
def main():
parser = argparse.ArgumentParser(
description='This program take operations on fractions as an input and produce a fractional result'
)
parser.add_argument('expression', metavar='expression', type=str, help='Operation on fractions expression')
args = parser.parse_args()
try:
print(str(expression_eval(args.expression)))
except SyntaxError as e:
print('char {}: Syntax error close to "{}"'.format(e.args[0], args.expression[e.args[0]:]))
except:
print('Something went wrong, please review your expression')
if __name__ == "__main__":
main()
|
523b90dbb397c81affbeb96b55e2d0c81bb648d5 | sankeerth/Algorithms | /HashTable/python/leetcode/find_duplicate_file_in_system.py | 5,367 | 4.09375 | 4 | """
609. Find Duplicate File in System
Given a list paths of directory info, including the directory path, and all the files with contents in this directory,
return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
"directory_path/file_name.txt"
Example 1:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Example 2:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Constraints:
1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 105
paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
You may assume no files or directories share the same name in the same directory.
You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
Follow up:
Imagine you are given a real file system, how will you search files? DFS or BFS?
If the file content is very large (GB level), how will you modify your solution?
If you can only read the file by 1kb each time, how will you modify your solution?
What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
How to make sure the duplicated files you find are not false positive?
"""
from typing import List
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
contentToDirectoryPaths = {}
res = []
for path in paths:
dirAndPath = path.split(' ')
rootDir = dirAndPath[0]
for i in range(1, len(dirAndPath)):
name, content = dirAndPath[i].split('(')
content = content.split(')')[0]
if content not in contentToDirectoryPaths:
contentToDirectoryPaths[content] = []
contentToDirectoryPaths[content].append(rootDir + '/' + name)
for content, path in contentToDirectoryPaths.items():
if len(path) > 1:
res.append(path)
return res
sol = Solution()
print(sol.findDuplicate(["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]))
print(sol.findDuplicate(["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]))
"""
Imagine you are given a real file system, how will you search files? DFS or BFS?
DFS. In this case the directory path could be large. DFS can reuse the shared the parent directory before leaving that directory. But BFS cannot.
If the file content is very large (GB level), how will you modify your solution?
In this case, not realistic to match the whole string of the content. So we use file signitures to judge if two files are identical.
Signitures can include file size, as well as sampled contents on the same positions. They could have different file names and time stamps though.
Hashmaps are necessary to store the previous scanned file info. S = O(|keys| + |list(directory)|). The key and the directory strings are the main space consumption.
a. Sample to obtain the sliced indices in the strings stored in the RAM only once and used for all the scanned files. Accessing the strings is on-the-fly.
But transforming them to hashcode used to look up in hashmap and storing the keys and the directories in the hashmap can be time consuming.
The directory string can be compressed to directory id. The keys are hard to compress.
b. Use fast hashing algorithm e.g. MD5 or use SHA256 (no collisions found yet). If no worry about the collision, meaning the hashcode is 1-1.
Thus in the hashmap, the storage consumption on key string can be replaced by key_hashcode, space usage compressed.
If you can only read the file by 1kb each time, how will you modify your solution?
That is the file cannot fit the whole ram. Use a buffer to read controlled by a loop; read until not needed or to the end.
The sampled slices are offset by the times the buffer is called.
What is the time complexity of your modified solution? What is the most time-consuming part and memory consuming part of it? How to optimize?
T = O(|num_files||sample||directory_depth|) + O(|hashmap.keys()|)
How to make sure the duplicated files you find are not false positive?
Add a round of final check which checks the whole string of the content. T = O(|num_output_list||max_list_size||file_size|).
"""
|
e782ce82e6efb40dc24df89b1fe52ead806373aa | Willian-PD/Exercicios-do-Curso-de-programacao-para-leigos-do-basico-ao-avancado | /Exercícios de python/secao-8-parte-6.py | 189 | 3.921875 | 4 | vetor = [1, 2, 3, 4, 5]
code = int(input('Digite um código: '))
if(code == 1):
print(f'{vetor}\n')
elif (code == 2):
vetor.reverse()
print(f'{vetor}')
|
c653c37db0c4a55c7e770c35607a6afb7a4afb6f | Ander-H/LeetCode_Ander | /110_Balanced Binary Tree/solution01.py | 865 | 3.921875 | 4 | """
https://leetcode.com/problems/balanced-binary-tree/discuss/35691/The-bottom-up-O(N)-solution-would-be-better
first solution
the time complexity is O(n^2)
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
left_height = self.depth(root.left)
right_height = self.depth(root.right)
return abs(left_height - right_height) <= 1 and \
self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if root is None:
return 0
return max(self.depth(root.left), self.depth(root.right)) + 1
|
3644112cec12a8e8594c9a694b74dd5d76a9b01b | garybergjr/PythonProjects | /GettingStarted/course_examples/while_loops01.py | 272 | 3.765625 | 4 | #for i in [0, 1, 2, 3, 4]:
# print("Hello " + str(i))
counter = 0
while counter < 5:
print("Hello " + str(counter))
counter = counter + 1
counter = 0
while True:
print("Hello " + str(counter))
counter = counter + 1
if counter >= 5:
break
|
8fe438d8d776c8f065db8ee8bc993fdba68a31f7 | jschnab/leetcode | /math/count_distinct_numbers.py | 891 | 4.03125 | 4 | """
leetcode 2549: count distinct numbers on board
We are given a positive integer n, that is initially placed on a board. Every
day, for 1 billion days, we perform the following procedure:
1. For each number x present on the board, we find all numbers i such that
1 <= i <= n and x % i == 1.
2. We place each number x on the board.
Return the number of distinct integers present on the board after 1 billion
days have elapsed.
"""
def count_numbers(n):
"""
Assuming that n < 1 billion, at least n - 1 satisfies the problem
conditions. Then, all numbers between 1 and n - 1 (inclusive) will
eventually be on the board.
"""
return n - 1
def test1():
assert count_numbers(3) == 2
print("test 1 successful")
def test2():
assert count_numbers(5) == 4
print("test 2 successful")
if __name__ == "__main__":
test1()
test2()
|
95b972b33538fb8b501dc42edfeb20d34fcb3873 | georgedunnery/Spaceship | /spaceship.py | 9,215 | 4.25 | 4 | """
George Dunnery
CS 5001
Homework 5 - Programming #2 - MODULE
11/2/2018
"""
# Turtle module is necessary for visualization
# Random module will help select a random word
import turtle
import random
# Define SHIP to be turtle, since a spaceship is being drawn
SHIP = turtle
# SECTION 1: Functions coordinate the gameplay logic - - - - - - - - - - - - -
def extract(filename):
"""
Paramters: Filename, a .txt file
Does: Reads the file into a list so the information can be accessed,
strips away \n so strings are properly formatted for the game
Returns: List, elements are strings composed of each line in the file.
"""
try:
infile = open(filename, 'r')
raw_data = infile.readlines()
infile.close()
for i in range(len(raw_data)):
raw_data[i] = raw_data[i].strip('\n')
return raw_data
except OSError:
print("Error reading file.")
return []
def choose_word(word_list):
"""
Parameters: List of words to choose from
Does: Chooses a word for the user to guess using a random integer
Returns: String, a word from the wordlist file
"""
try:
return word_list[random.randint(0, len(word_list) - 1)]
except ValueError:
return ''
def validate_guess(user_guess, guess_me):
"""
Parameters: The user's guess, the secret word, strings
Does: Searches the word for the position(s) of the matching letter
Returns: List of positions where the guessed letter is located in the
secret word
"""
positions = []
for i in range(len(guess_me)):
if user_guess.lower() == guess_me[i].lower():
positions.append(i)
return positions
def populate_correct(guess_me):
"""
Parameter: The secret word
Does: Creates a list with empty positions corresponding to the letters
in the secret word. This list will later be updated as the user guesses
correct letters.
Returns: List
"""
correct = []
for i in range(len(guess_me)):
correct.append(" ")
return correct
def victory(correct, guess_me):
"""
Parameters: Correct, list representing how much of the word has been
guessed. Guess_me, string of the secret word iteself
Does: Checks to see if the user has guessed the entire word yet
Returns: Boolean
"""
if len(correct) != len (guess_me):
return False
for letter in range(len(guess_me)):
if guess_me[letter] != correct[letter]:
return False
return True
def defeat(wrong):
"""
Parameter: Wrong, list of wrong guesses
Does: Checks if the player has exceeded the maximum number of wrong guesses
Returns: Boolean
"""
if len(wrong) >= 5:
return True
else:
return False
def compare_scores(leaderboard):
"""
Parameters: List containing the strings of data read from the scores.txt
file by the extract function
Does: Processes the data in the scores file, removing the names to pass
a list of integers to the top_dog function, which then responds with
the highest score from the file
Returns: The highest score from the file
"""
try:
score_list = []
for prev_score in leaderboard:
prev_score = prev_score.split(' ')
score_list.append(int(prev_score[1]))
return top_dog(score_list)
except IndexError:
return 0
def top_dog(score_list):
"""
Parameter: List of scores from the scores file
Does: Seeks the highest score
Returns: Largest integer in the list, or zero if there's an IndexError
"""
try:
if len(score_list) == 1:
return score_list[0]
else:
if score_list[0] > top_dog(score_list[1:]):
return score_list[0]
else:
return top_dog(score_list[1:])
except IndexError:
return 0
def create(cool_name, wins, SCORES):
"""
Parameters: The number of wins the player has, integer. The name of the
scores file, string
Does: Creates the file if it doesn't already exist
Returns: Nothing
"""
outfile = open(str(SCORES), 'w')
outfile.write(str(cool_name) + ' ' + str(wins) + '\n')
outfile.close()
def insert(cool_name, wins, leaderboard, SCORES):
"""
Paremeters: The number of games the player won, integer. The list of
previously saved scores, list. The name of the scores.txt file, string.
Does: Writes the new top score to the beginning of the file, and then
rewrites all of the old scores after the new entry
Returns: Nothing
"""
outfile = open(str(SCORES), 'w')
outfile.write(str(cool_name) + ' ' + str(wins) + '\n')
for prev_score in leaderboard:
outfile.write(prev_score + '\n')
outfile.close()
def pin_tail(cool_name, wins, SCORES):
"""
Parameter: Number of wins the player achieved, integer
Does: Appends the player's name and score to the end of the list, because
if they weren't first, they are last
Returns: Nothing
"""
outfile = open(str(SCORES), 'a')
outfile.write(str(cool_name) + ' ' + str(wins) + '\n')
outfile.close()
def verify_existence(filename):
"""
Parameter: Name of the file, string
Does: Checks if the file exists by trying to open it. Needed to help
determine when to write or append the scores file.
Returns: Boolean
"""
try:
seekfile = open(filename)
seekfile.close()
return True
except OSError:
return False
# SECTION 2: Functions generate visualizations - - - - - - - - - - - -
def letter_lines(guess_me):
"""
Parameter: The secret word, string.
Does: Draws a line for each letter in the secret word. Since it is only
called at the start of each round, it also clears the screen of any
previous round
Returns: Nothing
"""
SHIP.clear()
spaces = ""
for i in range(len(guess_me)):
spaces += '___ '
SHIP.penup()
SHIP.goto(200,0)
SHIP.write(spaces, False, 'left')
SHIP.penup()
SHIP.goto(0,0)
def show_wrong(wrong):
"""
Parameter: The list of incorrect guesses
Does: Displays the incorrect guesses to help the player remember
what they've already guessed
Returns: Nothing
"""
if len(wrong) >= 1:
SHIP.penup()
SHIP.goto((-200 + 15 * len(wrong)),0)
SHIP.write(wrong[-1], False, 'center', ('Times', 12, 'bold'))
SHIP.goto(0,0)
def reveal_correct(correct):
"""
Parameter: List corresponding to the positions of the correctly guessed
letters, with open spaces in unknown locations. Easily generated with the
populate_correct function.
Does: Writes the location(s) of a correct letter, which slowly reveals
the word to the player
Returns: Nothing
"""
SHIP.penup()
for position in range(len(correct)):
SHIP.goto((200 + (25 * position), 5))
SHIP.write(correct[position], False, 'left', ('Times', 12, 'bold'))
SHIP.goto(0,0)
def artist(num_wrong):
"""
Parameter: Number of wrong guesses, integer
Does: Calls other functions to draw ceertain parts of the spaceship
depending on the number of incorrect guesses
Returns: Nothing
"""
SHIP.update()
if num_wrong == 1:
draw_body()
elif num_wrong == 2:
draw_left_rocket()
elif num_wrong == 3:
draw_right_rocket()
elif num_wrong == 4:
draw_left_flame()
else:
draw_right_flame()
def draw_body():
"""
Parameters: None
Does: Draws the body for the first incorrect guess
Returns: Nothing
"""
SHIP.penup()
SHIP.goto(0,175)
SHIP.pendown()
SHIP.goto(-50,100)
SHIP.goto(-50,-100)
SHIP.goto(50,-100)
SHIP.goto(50,100)
SHIP.goto(0,175)
def draw_left_rocket():
"""
Parameters: None
Does: Draws the left rocket for the second incorrect guess
Returns: Nothing
"""
SHIP.penup()
SHIP.goto(-70,-50)
SHIP.pendown()
SHIP.goto(-40,-130)
SHIP.goto(-100,-130)
SHIP.goto(-70,-50)
def draw_right_rocket():
"""
Parameters: None
Does: Draws the right rocket for the second incorrect guess
Returns: Nothing
"""
SHIP.penup()
SHIP.goto(70,-50)
SHIP.pendown()
SHIP.goto(40,-130)
SHIP.goto(100,-130)
SHIP.goto(70,-50)
def draw_left_flame():
"""
Parameters: None
Does: Draws the left flame for the second incorrect guess
Returns: Nothing
"""
SHIP.penup()
SHIP.goto(-100,-130)
SHIP.pendown()
SHIP.goto(-90,-150)
SHIP.goto(-80,-130)
SHIP.goto(-70,-160)
SHIP.goto(-60,-130)
SHIP.goto(-50,-150)
SHIP.goto(-40,-130)
def draw_right_flame():
"""
Parameters: None
Does: Draws the right flame for the second incorrect guess
Returns: Nothing
"""
SHIP.penup()
SHIP.goto(100,-130)
SHIP.pendown()
SHIP.goto(90,-150)
SHIP.goto(80,-130)
SHIP.goto(70,-160)
SHIP.goto(60,-130)
SHIP.goto(50,-150)
SHIP.goto(40,-130)
def bye():
"""
Parameters: None
Does: Gets rid of the turtle screen
Returns: Nothing
"""
SHIP.bye()
|
ac9d5c265190401c2e11d2b144cbf16961da09a2 | snalahi/Python-Basics | /week3_assignment.py | 2,114 | 4.4375 | 4 | # rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches)
# with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of
# rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0.
rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85"
rain_list = rainfall_mi.split(", ")
num_rainy_months = 0
for i in rain_list:
if float(i) > 3.0:
num_rainy_months += 1
# The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter,
# including one-letter words. Store the result in the variable same_letter_count.
sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = 0
sent_list = sentence.split()
for i in sent_list:
if i[0] == i[-1]:
same_letter_count += 1
# Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable
# acc_num.
items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"]
acc_num = 0
for i in items:
if "w" in i:
acc_num += 1
# Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable
# num_a_or_e.
sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems."
sent_list = sentence.split()
num_a_or_e = 0
for i in sent_list:
if "a" in i or "e" in i:
num_a_or_e += 1
# Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem,
# vowels are only a, e, i, o, and u.
s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun"
vowels = ['a','e','i','o','u']
num_vowels = 0
for i in s:
if i in vowels:
num_vowels += 1
|
660b24b3f3c2976548cf1395bccf55b39fde7cb5 | ehsansadeghi1/tsp | /Nearest_Neighbor.py | 1,701 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt
# =============================================================================
# This function takes as input a graph g.
# The function should return the weight of the nearest neighbor heuristic,
# which starts at the vertex number 0,
# and then each time selects a closest vertex.
# =============================================================================
def nearest_neighbors(g):
current_node = 0
path = [current_node]
n = g.number_of_nodes()
# We'll repeat the same routine (n-1) times
for j in range(n - 1):
next_node = None
# The distance to the closest vertex. Initialized with infinity.
min_edge = float("inf")
for v in g.nodes(): # g.nodes() returns nodes of graph g
if (v not in path) and (g[current_node][v]['weight'] < min_edge):
min_edge = g[current_node][v]['weight']
next_node = v
# decide if v is a better candidate than next_node.
# If it is, then update the values of next_node and min_edge
assert next_node is not None
path.append(next_node)
current_node = next_node
weight = sum(g[path[i]][path[i + 1]]['weight'] for i in range(n - 1))
weight += g[path[-1]][path[0]]['weight']
return weight, path
g = nx.Graph()
g.add_edge(0, 1, weight=6)
g.add_edge(1, 2, weight=2)
g.add_edge(2, 3, weight=3)
g.add_edge(3, 0, weight=2)
g.add_edge(0, 2, weight=5)
g.add_edge(1, 3, weight=1)
g.add_edge(0, 4, weight=3)
g.add_edge(1, 4, weight=1)
g.add_edge(2, 4, weight=1)
g.add_edge(3, 4, weight=2)
print(nearest_neighbors(g))
|
1d5a3cd2ea905fe8ef3a9fed41f8de2fa47d80a7 | hrushikeshrv/deep-neural-net-1 | /deep_neural_net_1.py | 15,874 | 4.09375 | 4 | """
Python script to construct a deep neural network.
Needs the architecture of the network, the input data set and the output labels, and a few hyperparameters for you to decide.
Call the 'four_layer_logistic()' or the 'five_layer_logistic()' functions to quickly construct a four layer or a five layer neural network respectively and pass them their required parameters.
Call the 'model()' function to construct a general deep neural network.
Constructs a deep neural network, trains it on the input data set, and returns the parameters along with the error on the dataset.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import time
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def help ():
"""
Returns some helpful information on how to use
"""
print('#'*5 + '-'*100 + '#'*5)
print('\n\n')
print('You will need to decide on the following hyperparameters to initialize your model - \n\n')
print('The architecture of your model. \n\t Decide on the number of layers your network will have, and the number of units in each of these layers. \n')
print('The activation functions to use in each layer. \n\t Most often you will want to use a ReLU activation for the hidden units and a sigmoid or softmax activation for the output.\n')
print('The learning rate alpha of your model. \n\t Use a small number like 0.01, but not too small or gradient descent won\'t converge on the global minima. If you use too big a value, gradient descent can start to diverge.\n')
print('The number of iterations of gradient descent you want to run. \n\t This model currently only supports gradient descent as an optimization algorithm, but I will be adding other optimizers like ADAM, RMS Prop, and Momentum soon.\n')
print('\n')
print('#'*5 + '-'*100 + '#'*5)
print('\n\nIf you\'re working locally, make sure you have numpy and matplotlib installed.')
print('\n')
print('To build a pre-implemented logistic or softmax network, call the \'four_layer_logistic()\' or \'five_layer_logistic()\' functions and pass them the parameters they need.\n\n')
print('To build a general network, simply call the model() function and pass it the parameters it needs. Have your input data and your output labels prepared and formatted how you want before you initialize.')
print('Calling the model() function will begin training your given network on your given dataset for a default of 10,000 iterations\n')
print('It will print the cost and the training accuracy of your model after it is done training.\n\n')
print('#'*5 + '-'*100 + '#'*5)
print('\n')
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def sigmoid (Z):
"""
Takes in a real number or matrix Z and applies the sigmoid function to it.
"""
A = 1/(1+np.exp(-1*Z))
return A
def relu (Z):
"""
Takes in a real number or matrix Z and applies the (leaky) relu function to it.
"""
A = np.zeros(Z.shape)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
if Z[i,j] >= 0:
A[i,j] = Z[i,j]
else:
A[i,j] = 0.001*Z[i,j]
return A
#NOTE TO SELF ---- THIS DEFINITION MIGHT CAUSE BROADCASTING PROBLEMS DURING RUNTIME
#NOTE 2.0 --- fixed it.
def drelu (Z):
"""
Takes in a real number Z and returns the derivative of the relu function at that value or matrix.
Used for back propagation. Z will be the activation value of the last layer before the non-linearity is applied.
"""
A = np.zeros(Z.shape)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
if Z[i,j] >= 0:
A[i,j] = 1
else:
A[i,j] = 0.001
return A
def softmax (Z):
"""
Takes in a vector Z and returns its softmax activation.
"""
temp = np.exp(Z)
factor = np.sum(temp)
A = temp/factor
return A
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def initialize_parameters (architecture = []):
"""
Initializes the parameters of the neural net.
Takes in the architecture of the network as a list.
Structure the list as the number of units in each layer, starting from the number of input features, to the number of output units.
[10, 5, 5, 4, 3] means that there are 10 input features, 3 hidden layers with 5, 5, 4 hidden units respectively, and 3 output units (softmax regression)
Returns a dictionary of keys W(i) for i from 1 to number of layers, and b(i) for the same i.
"""
parameters = {}
number_of_layers = len(architecture) - 1
for i in range(1,number_of_layers+1):
parameters['W' + str(i)] = np.random.randn(architecture[i], architecture[i-1])*0.01
parameters['b' + str(i)] = np.zeros((architecture[i], 1))
return parameters
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def forward_propagation (X, parameters, num_layers, activation_func = []):
"""
Performs forward propagation
Takes in the activations of each layer and the parameters.
activation_func is a list with as many elements (strings - either relu, softmax, or sigmoid) as number of layers (excluding the input layer)
num_layers is the number of layers
parameters is a dictionary containing all the W and b values for all the layers.
X is the input
Returns the final prediction y_hat and all the Z and A values as cache to use for backward propagation.
"""
activations = {'A0': X}
for i in range(1, num_layers+1):
W = parameters['W' + str(i)]
b = parameters['b' + str(i)]
activations['Z' + str(i)] = np.dot(W, activations['A' + str(i-1)]) + b
if activation_func[i-1].lower() == 'relu':
activations['A' + str(i)] = relu(activations['Z' + str(i)])
elif activation_func[i-1].lower() == 'softmax':
activations['A' + str(i)] = softmax(activations['Z' + str(i)])
elif activation_func[i-1].lower() == 'sigmoid':
activations['A' + str(i)] = sigmoid(activations['Z' + str(i)])
activations['W' + str(i)] = W
activations['b' + str(i)] = b
return activations['A' + str(num_layers)], activations
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def calculate_cost (Y, prediction, activation_output = 'sigmoid'):
"""
Calculates the cost.
Takes in the output labels and the prediction from forward propagation, as well as the activation function of the output layer.
Returns the cost.
The inputs will be real numbers or row vectors of the same dimensions if the activation function of the last layer is sigmoid.
The inputs will be row vectors or row matrices of the same dimensions if the activation function of the last layer is softmax.
"""
m = Y.shape[1]
if activation_output.lower() == 'sigmoid':
cost = (-1/m)*np.sum(Y*np.log(prediction) + (1-Y)*np.log(1-prediction))
if activation_output.lower() == 'softmax':
cost = (-1/m)*np.sum(np.sum(Y*np.log(prediction), axis = 0, keepdims = True))
return cost
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def backward_propagation (X, Y, cache, number_of_layers):
"""
Performs backward propagation.
Takes in the inputs X, the corresponding labels Y, and the activation values stored as cache (returned by the second output for forward_propagation)
Returns the gradients of all parameters in the grads dictionary.
The cache is a dictionary containing the Z values and the A values for all layers.
"""
m = Y.shape[1]
last_layer = 'dZ' + str(number_of_layers)
gradients = {last_layer: cache['A'+str(number_of_layers)]-Y}
for i in reversed(range(2,number_of_layers+1)):
gradients['dW' + str(i)] = (1/m)*np.dot(gradients['dZ'+str(i)], cache['A' + str(i-1)].T)
gradients['db' + str(i)] = (1/m)*np.sum(gradients['dZ'+str(i)], axis = 1, keepdims = True)
gradients['dZ' + str(i-1)] = np.dot(cache['W' + str(i)].T, gradients['dZ' + str(i)])*drelu(cache['Z' + str(i-1)])
gradients['dW1'] = (1/m)*np.dot(gradients['dZ'+str(1)], cache['A' + str(0)].T)
gradients['db1'] = (1/m)*np.sum(gradients['dZ'+str(1)], axis = 1, keepdims = True)
return gradients
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def update_parameters (parameters, number_of_layers, gradients, alpha = 0.001):
"""
Updates the parameters.
Takes in the parameters themselves (as the parameters dictionary returned by the initialize_parameters function dictionary),
the gradients (as the gradients dictionary returned by the backward_propagation function), and the learning rate alpha.
Returns the updated parameters.
"""
for i in range(1, number_of_layers+1):
parameters['W' + str(i)] = parameters['W' + str(i)] - alpha*gradients['dW' + str(i)]
parameters['b' + str(i)] = parameters['b' + str(i)] - alpha*gradients['db' + str(i)]
return parameters
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def calculate_accuracy (X, Y, parameters, number_of_layers, activation_functions):
"""
Runs forward propagation on all examples and returns the accuracy of the model
Takes in X and Y, the parameters, number of layers, and the activation functions list. Meant to be run inside the model() function definition.
"""
m = Y.shape[1]
correct_count = 0
pred,_ = forward_propagation(X, parameters, number_of_layers, activation_functions)
for i in range(m):
if (pred[:, i] >= 0.5 and Y[:, i] == 1) or (pred[:,i] < 0.5 and Y[:,i] == 0):
correct_count += 1
accuracy = correct_count*100/m
return accuracy
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def model (X, Y, architecture, activation_functions, learning_rate = 0.001, print_cost = True, number_of_iterations = 10000):
"""
Takes in the training set X, the labels Y, and all the required parameters and trains the defined model for the given number of iterations.
Prints the cost if print_cost is true.
"""
costs = []
number_of_layers = len(architecture) - 1
parameters = initialize_parameters(architecture)
for i in range(number_of_iterations):
prediction, cache = forward_propagation(X, parameters, number_of_layers, activation_functions)
cost = calculate_cost(Y, prediction, activation_functions[-1])
costs.append(cost)
gradients = backward_propagation(X, Y, cache, number_of_layers)
parameters = update_parameters(parameters, number_of_layers, gradients, alpha=0.01)
if print_cost and i%100 == 0:
print(f'Completed {i} iterarions.\n')
print(f'Cost after iteration {i} = {cost}')
plt.plot(costs)
plt.xlabel('Iterations (in hundereds)')
plt.ylabel('Cost')
plt.title(f'Learning rate = {learning_rate}')
plt.show()
costs_df = pd.DataFrame(costs)
sns.set(style = 'whitegrid')
# sns.set_context(context = 'talk')
plt.figure(figsize = (10,5))
sns.lineplot(data = costs_df, palette = 'magma', linewidth = 3)
print(f'Ran {number_of_iterations} iterations. Returning parameters now.')
print(f'The final cost of the model was: {costs[-1]}%')
acc = calculate_accuracy(X, Y, parameters, number_of_layers, activation_functions)
print(f'The training accuracy was: {acc}')
return parameters
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def four_layer_logistic (X, Y, architecture = [10, 5, 5, 1], activation_functions = ['relu', 'relu', 'relu', 'relu', 'sigmoid'], learning_rate = 0.001, print_cost = True, number_of_iterations = 10000):
"""
Predefined function to construct a four layer (logistic) plain neural network.
If you want to override the architecture to construct a four layer softmax network, you can overwrite the values of the default parameters 'architecture' and 'activation_functions'.
Takes in only the input X and the output labels Y.
"""
temp = X.shape[0]
architecture.insert(0, temp)
tic = time.time()
model(X, Y, architecture, activation_functions, learning_rate, print_cost, number_of_iterations)
toc = time.time()
print(f'Took {toc-tic} seconds to train.')
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------#
def five_layer_logistic (X, Y, architecture = [20, 10, 5, 5, 1], activation_functions = ['relu', 'relu', 'relu', 'relu', 'relu', 'sigmoid'], learning_rate = 0.001, print_cost = True, number_of_iterations = 10000):
"""
Predifined function to construct a five layer logistic plain neural network.
If you want to override the architecture to construct a five layer softmax network, you can overwrite the values of the default parameters 'architecture' and 'activation_functions'.
Takes in only the input X and the output labels Y.
"""
temp = X.shape[0]
architecture.insert(0, temp)
tic = time.time()
model(X, Y, architecture, activation_functions, learning_rate, print_cost, number_of_iterations)
toc = time.time()
print(f'Took {toc - tic} seconds to train.')
#-----------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------# |
e3cee24692e97dca3083162fd06db2b3db91abd7 | mmariani/meuler | /019/019.py | 330 | 3.828125 | 4 | #!/usr/bin/env python3
import calendar
import itertools
import operator
def run():
# cheating :)
sundays = sum(calendar.weekday(year, month, 1) == calendar.SUNDAY
for year in range(1901, 2001)
for month in range(1, 13))
print(sundays)
if __name__ == '__main__':
run()
|
2ef722765eed31aeb226c151b8e4261d6dbe2d2f | douglas-hetfield/CURSOS | /Programacao III/Programas/2019_2/CCT0696_1/EXEMPLO_TK/JANELA_TK_2.py | 394 | 3.828125 | 4 | from tkinter import Tk, Label, Button, StringVar
def traduzir():
textoRotulo.set("Alo Mundo")
janelaPrincipal = Tk()
textoRotulo = StringVar()
textoRotulo.set("Hello World")
rotulo1 = Label(master=janelaPrincipal,textvariable=textoRotulo)
botao1 = Button(master=janelaPrincipal,text="Traduzir",command=traduzir)
botao1.pack()
rotulo1.pack()
janelaPrincipal.mainloop()
|
337636f56d93948521b4af99005900f778b8672e | jadenpadua/new-grad-swe-prep | /bst/level-order-traversal.py | 893 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
level_order = []
queue = deque([root])
while len(queue) != 0:
level_len = len(queue)
level_nodes = []
for i in range(level_len):
curr_node = queue.popleft()
level_nodes.append(curr_node.val)
if curr_node.left:
queue.append(curr_node.left)
if curr_node.right:
queue.append(curr_node.right)
level_order.append(level_nodes)
return level_order
|
14a108b48f67d1d195aa2189d2c8e37ae4acf744 | ShaimaAnvar/python-challenge | /Q3.py | 179 | 3.859375 | 4 | def product(a):
if len(a)==0:
return 0
elif len(a)==1:
return a[0]
else:
pro=a[len(a)-1] * a[len(a-2)]
print(pro)
list=[1,2]
product(list) |
364365b3011a83a1693397e638cced53af6687ae | sliwkam/Beginning | /6_list_overlap.py | 233 | 3.6875 | 4 | # library use
import random
# creating random list
a = random.sample(range(100), 15)
b = random.sample(range(100), 10)
c = []
# checking common words
for i in b:
if i in a:
if i not in c:
c.append(i)
print(c)
|
9f39388d18193de2f3691905bb5771e1f6539554 | mehranaman/Intro-to-computing-data-structures-and-algos- | /Assignments/isbn.py | 2,237 | 3.90625 | 4 | # File: ISBN.py
# Description: Algorithm to validate vald ISBN numbers.
# Student Name: Naman Mehra
# Student UT EID: nm26465
# Course Name: CS 303E
# Unique Number: 51850
# Date Created: April 15th, 2017
# Date Last Modified: April 15th, 2017
def is_valid(ISBNno):
#Function to check if ISBN is invalid
if len(ISBNno) != 10:
return False
l = len(ISBNno)
#Check if the first 9 characters are digits from 0-9
for x in range(l-1):
if ord(ISBNno[x]) <48 or ord(ISBNno[x])>57:
return False
#Check if the last character is x or X or a digit from 0-9
if ISBNno[l-1] == 'x' or ISBNno[l-1] == 'X' or (ord(ISBNno[l-1])>48 and ord(ISBNno[l-1])<57):
return True
else:
return False
def makelist(ISBNdigits):
#convert ISBNdigits to list of digits
list_of_numbers = []
for char in ISBNdigits:
#if last character is x or X, it is replaced by 10
if char == 'x' or char == 'X':
char = 10
list_of_numbers.append(int(char))
return list_of_numbers
def partialsums(digits):
#compute partial sums s1 and s2. Return True if the last item in s2 is divisible by 11
#initialize s1 and s2 to calculate partial sums
s1 = [digits[0]]
s2 = [s1[0]]
#loop to calculate partial sums
for x in range(1, len(digits)):
s1.append(s1[x-1] + digits[x])
s2.append(s2[x-1] + s1[x])
#return result
return s2[len(s2)-1]%11 == 0
def main():
#open file to read
readfile = open("ISBN.txt", "r")
#open file to write
write_file = open("isbnOut.txt", "w")
#continue loop until the file reaches the end
for ISBNno in readfile:
#read the ISBN and strip newline character
ISBNno = ISBNno.strip()
#replace hyphens with null character
ISBNdigits = ISBNno.replace("-", "")
#Check if ISBN is valid
if is_valid(ISBNdigits):
#convert ISBN to a list of numbers
digits = makelist(ISBNdigits)
#compute partial sums and return if the ISBN is valid
if partialsums(digits):
#ISBN is valid
output = format(ISBNno, "<13") + " valid\n"
else:
#ISBN is not valid
output = format(ISBNno, "<13") + " invalid\n"
else:
#if ISBN is not valid
output = format(ISBNno, "<13") + " invalid\n"
#write output to file
write_file.write(output)
readfile.close()
write_file.close()
main()
|
7525ff5fdaf2ba1a4400a9c2066c0fbd1792ff50 | arpitpardesi/Advance-Analytics | /Python/Basics/Day2/ArpitPardesi_59128_Assignment(Day2)/Dictionary/Q21.py | 99 | 3.6875 | 4 | d ={'1':['a','b'], '2':['c','d']}
for i in d.get('1'):
for j in d.get('2'):
print(i,j) |
92c5dd51ead269a080f8279ba96d85acc60629a9 | sdyz5210/python | /high/lambdaDemo.py | 200 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def f(x):
return x*x
map1 = map(f,range(1,11))
print map1
#使用匿名函数实现
print '打印匿名函数运行结果',map(lambda x : x*x,range(1,11)) |
bd35ee6b2f7c89ba71080b544262bb88ae71ede5 | AndresMorelos/procesamiento-numerico | /semana9/polynomial_regression.py | 460 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
class Regression:
def __init__(self,x,y, degree):
self.x = x
self.y = y
self.degree = degree
def polynomial(self, xi):
poly_fit = np.poly1d(np.polyfit(self.x,self.y, self.degree))
return poly_fit(18)
regression = Regression([0,5,10,15,20,25,30], [12.9,11.3,10.1,9.03,8.17,7.46,6.85], 3)
print('Regresión Polinomial {0}'.format(regression.polynomial(18))) |
039437b41b48880d95b850c2b7ae11d6552fc6a5 | mubaraqqq/electric-utilities-data-analytics | /Data.py | 1,986 | 4.28125 | 4 | import numpy as np
# #One dimensional array
# a = np.array([1, 2, 3])
# print(type(a))
# print(a.dtype)
# #rank or axis
# print(a.ndim)
# #size attribute for array length
# print(a.size)
# ##shape attribute for shape
# print(a.shape)
# #Two dimensional array
# b = np.array([[1.3, 2.4], [0.3, 4.1]])
# print(b.dtype)
# print(b.ndim)
# print(b.size)
# print(b.shape)
# #itemsize defines the size in bytes of each item in the array
# print(b.itemsize)
# #data is the buffer containing the actual elements of the array
# print(b.data)
# #Creating an array
# c = np.array([[1, 2, 3], [4, 5, 6]])
# print(c)
# d = np.array(((1, 2, 3), (4, 5, 6)))
# print(d)
# e = np.array([(1, 2, 3), [4, 5, 6], (7, 8, 9)])
# print(e)
# print(e.ndim)
# print(e.size)
# print(e.shape)
# #Types of Data
# g = np.array([['a', 'b'], ['c', 'd']])
# print(g)
# print(g.dtype.name)
# #Intrinsic Creation of an array
# #the zeros() function creates an array full of zeroes with dimensions defined by the shape argument
# print (np.zeros((3, 3)))
# #the ones() function creates an array full of ones in a very similar way
# print (np.ones((3,3)))
# #arange() function is used for generating a range of numbers specified as arguments
# print(np.arange(10))
# print(np.arange(2, 8))
# print(np.arange(0, 6, 0.6))
# #use the reshape() function to create two dimensional arrays
# print(np.arange(0, 12).reshape(3, 4))
# #the linspace() function acts like arange but specifies the number of elements the range should be divided into, instead of the number of steps between one element and the next
# print(np.linspace(0, 10, 5))
# #the random function returns random numbers
# print(np.random.random(3))
# print(np.random.random((3, 3)))
#Basic Operations
#Arithmetic Operators
a = np.arange(4)
print(a + 4)
print(a*2)
b = np.arange(4, 8)
print (a + b)
print (a - b)
print (a * b)
print (a * np.sin(b))
print (a * np.sqrt(b))
A = np.arange(9).reshape(3, 3)
B = np.ones((3, 3))
print (A * B)
#The Matrix Product
|
8645ca56ef57b085987d4c360b18e4ccc8f8f686 | JoseGtz/2021_python_selenium | /Module_01/concat_lists.py | 114 | 3.734375 | 4 | list1 = ['hello', 'take']
list2 = ['dear', 'sir']
solution = []
for x in list2:
list1.append(x)
print(list1)
|
96e54896ec2064c1593f1b94d6d89dbb4e92785a | mragarg/loop-exercises-python | /square2.py | 333 | 4.0625 | 4 | user_input = input("How big is the square? ")
try:
user_input = int(user_input)
except:
pass
star_string = ""
star_column = ""
row = 0
column = 0
while(row < user_input):
while(column < user_input):
star_column += "*"
column += 1
star_string += star_column + "\n"
row += 1
print(star_string) |
2f7bc8be0e9cc763e183f448a90eac1574fc4e4f | HoYaStudy/Python_Study | /playground/Literal.py | 2,936 | 3.765625 | 4 | ###############################################################################
# @brief Python3 - Literal.
# @version v1.0
# @author llChameleoNll <hoya128@gmail.com>
# @note
# 2017.07.28 - Created.
###############################################################################
'''
Integer
- Don't start with 0 in Integer.
String
- String is Immutable.
'''
if __name__ == '__main__':
# Integer ----------------------------------------------------------------#
positive = +123 # same as 123
negative = -123
# String -----------------------------------------------------------------#
strLiteral = 'hello'
strLiteral = "world"
strLiteral = "I'm HoYa."
strLiteral = 'I\'m HoYa.'
strLiteral = 'He say, "Melong"'
strLiteral = "He say, \"Melong\""
strLiteral = 'hello' + ' world'
print(strLiteral)
strLiteral = 'hey ' * 3
print(strLiteral)
strLiteral = "hello " "world"
print(strLiteral)
cnt = 5
strLiteral = ''
strLiteral += 'He is '
strLiteral += str(cnt)
strLiteral += ' years old.'
print(strLiteral)
strLiteral = '''Line 1,
Line 2,
Line 3'''
print(strLiteral)
strLiteral = """
Line 11,
Line 12,
Line 13
"""
print(strLiteral)
string = 'abcdefghijklmnopqrstuvwxyz'
print(string[3])
print(string[-2])
# string[50] # Error
# string[0] = 'A' # Error
# slice [start:end:step]
print(string[:])
print(string[5:])
print(string[:7])
print(string[10:15])
print(string[10:20:2])
print(string[::3])
print(string[::-1])
print(len(string))
new_string = string.replace('a', 'A')
print(new_string)
string = 'a,b,c,d,e'
new_string = string.split(',')
print(new_string)
string = 'ab cd ef gh ij'
new_string = string.split()
print(new_string)
new_string = ', '.join(new_string)
print(new_string)
string = 'Lorem ipsum dolor sit amet'
string.startswith('Lorem') # True
string.endswith('ipsum') # False
string.find('dolor') # 12
string.rfind('sit') # 18
string.count('or') # 2
string.isalnum() # True
string = 'lorem ipsum dolor sit amet...'
new_string = string.strip('.')
print(new_string)
new_string = string.capitalize()
print(new_string)
new_string = string.title()
print(new_string)
new_string = string.upper()
print(new_string)
new_string = string.lower()
print(new_string)
new_string = string.swapcase()
print(new_string)
new_string = string.center(50)
print(new_string)
new_string = string.ljust(30)
print(new_string)
new_string = string.rjust(40)
print(new_string)
string = 'apple banana apple orange apple grape'
new_string = string.replace('apple', 'melon')
print(new_string)
new_string = string.replace('apple', 'melon', 2)
print(new_string)
|
4c9a89974fe7eb411b453621a7c4da1ad648873e | alvintanjianjia/MIMOS_Geospatial | /Visualizer.py | 2,788 | 3.71875 | 4 | import pandas as pandas
from matplotlib import pyplot as pyplot
import seaborn as seaborn
class Plot:
"""
Class to handle plot
"""
def __init__(self, argv_width=15, argv_height=10):
"""
Size is in inches
"""
self._figure = pyplot
self._width = argv_width
self._height = argv_height
self._figure.figure(
figsize=(self._width, self._height)
)
def reset(self):
"""
Reset the figure
"""
self._figure = pyplot
self._figure.figure(
figsize=(self._width, self._height)
)
def plot_dist(self, argv_df, argv_x="", argv_show=True):
"""
This is similar to a histogram
Note this would be replaced with displot in a new version which isn't as nice
"""
# plot the distribution
seaborn.distplot(argv_df[argv_x])
# to show it
if argv_show:
self._figure.show()
def plot_barchart(self, argv_df, argv_x="", argv_y="", argv_hue="", argv_show=True):
"""
Bar chart
"""
# plot the boxplot
# if no grouping (hue)
if argv_hue == "":
seaborn.boxplot(
y=argv_df[argv_y],
x=argv_df[argv_x]
)
else:
seaborn.boxplot(
y=argv_df[argv_y],
x=argv_df[argv_x],
hue=argv_df[argv_hue]
)
# to show it or not
if argv_show:
self._figure.show()
def plot_scatter(self, argv_df, argv_x="", argv_y="", argv_hue="", argv_jitter_x=False, argv_jitter_y=False, argv_show=True):
"""
Scatter plot
"""
# plot the scatter
seaborn.lmplot(
data=argv_df,
y=argv_y,
x=argv_x,
hue=argv_hue,
x_jitter=argv_jitter_x,
y_jitter=argv_jitter_y
)
# to show it or not
if argv_show:
self._figure.show()
def plot_cat(self, argv_df, argv_x="", argv_y="", argv_hue="", argv_kind="bar", argv_show=True):
"""
This is similar to a barchart
"""
# if no y, we will use the frequency (count)
if argv_kind == "count":
seaborn.catplot(
data=argv_df,
y=argv_y,
hue=argv_hue,
kind=argv_kind
)
# plot with a y
else:
seaborn.catplot(
data=argv_df,
x=argv_x,
y=argv_y,
hue=argv_hue,
kind=argv_kind
)
# to show it or not
if argv_show:
self._figure.show() |
eabc78b0d6a4e899a076de2787c8083c2bf5696d | sergeichestakov/InterviewPrep | /longestValidParentheses.py | 720 | 3.703125 | 4 | # Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
class Solution:
def longestValidParentheses(self, s: 'str') -> 'int':
longest = 0
stack = []
stack.append(-1)
for index, char in enumerate(s):
if char == '(': # Add to stack and continue
stack.append(index)
elif char == ')': # Find longest by comparing to value in stack
stack.pop()
if not stack:
stack.append(index)
else:
longest = max(longest, index - stack[-1])
return longest
|
26eece00aa97d3c3d1113107f49e32f2c5f84674 | MayuriTambe/Programs | /Programs/BasicPython/Colors.py | 217 | 3.9375 | 4 |
def FisrtLast():
color_list = ["Red","Green","White" ,"Black"]
First=color_list[0]
print("The first color is:",First)
Last=color_list[-1]
print("The Last color is:",Last)
return
FisrtLast()
|
f9baedf1583b17447b3ffab0b6ffeb8850d1f983 | sculzx007/Python-practice | /与孩子一起学编程/设置球的属性.py | 780 | 4.25 | 4 | class Ball:
def bounce(self):
if self.direction == "down":
self.direction = "up"
#这是创建一个类
myBall = Ball() #建立一个类的实例
myBall.direction = "down"
myBall.color = "red"
myBall.size = "small"
#设置了一些属性
print "I just created a ball."
print "My ball is ", myBall.size
print "My ball is ", myBall.color
print "My ball's direction is ", myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce #使用一个方法
print "Now the ball's direction is ", myBall.direction
"""
输出结果:
I just created a ball.
My ball is small
My ball is red
My ball's direction is down
Now I'm going to bounce the ball
Now the ball's direction is down
"""
|
5806ac328d2f07a3489de08f3a83e74ab9a99752 | Alexis-Matheson/CS362_HW4 | /CubeVolume/volume.py | 635 | 4.375 | 4 | #This program calculates the volume of a cube
import math
def Volume(d):
v = d * d * d
print("The volume of the cube is %.2f units squared." %v)
def main():
dimension = input("Enter the size of one side of a cube: ")
try:
float(dimension)
is_float = True
except:
is_float = False
print("The dimension you entered cannot be calculated into a volume.")
if(is_float == True):
d = float(dimension)
if(d > 0):
Volume(d)
else:
print("Cannot get a volume of a negative dimension.")
if __name__ == "__main__":
main() |
05d119e29a76d33d2fed6c844ead1b07e7146214 | rayt579/cake | /greedy_algorithms/shuffle_riffle.py | 3,768 | 4.3125 | 4 | '''
Write a function to tell us if a full deck of cards shuffled_deck
is a single riffle of two other halves half1 and half2
Definition of the Riffle Algorithm
------------------------------------
1) cut the deck into halves half1 and half2
2) take a random number of cards from top of half1 (can be 0) and throw them into the shuffled_deck
3) take a random number of cards from top of half2 (can be 0) and throw them into the shuffled_deck
4) repeat steps 2 and 3 until both halfs are empty
Takeaways:
1) Work with the interviewer to break down the problem to digestable chunks. You need to understand the problem.
- Problems can be reduced to fundamental data structures! This is just an array problem.
2) Avoid using list slicing when necessary because you incur space costs. Keep track of pointers instead.
Bonus:
1) This assumes shuffled_deck contains all 52 cards. What if we can't trust this (e.g. some cards are being secretly removed by the shuffle)?
2) This assumes each number in shuffled_deck is unique. How can we adapt this to rifling lists of random integers with potential repeats?
3) Our solution returns True if you just cut the deck—take one half and put it on top of the other. While that technically meets the definition of a riffle, what if you wanted to ensure that some mixing of the two halves occurred?
'''
# O(n) time, O(n) space
def is_shuffled_with_single_riffle_recursive(shuffled_deck, h1, h2, shuf_index=0, h1_index=0, h2_index=0):
if shuf_index == len(shuffled_deck):
return True
if h1_index < len(h1) and h1[h1_index] == shuffled_deck[shuf_index]:
return is_shuffled_with_single_riffle_recursive(shuffled_deck, h1, h2, shuf_index + 1, h1_index + 1, h2_index)
elif h2_index < len(h2) and h2[h2_index] == shuffled_deck[shuf_index]:
return is_shuffled_with_single_riffle_recursive(shuffled_deck, h1, h2, shuf_index + 1, h1_index, h2_index + 1)
else:
return False
# O(n) time, O(n) space
def is_shuffled_with_single_riffle(shuffled_deck, half1, half2):
h1_index = 0
h2_index = 0
for i in range(len(shuffled_deck)):
if h1_index < len(half1) and shuffled_deck[i] == h1[h1_index]:
h1_index += 1
elif h2_index < len(half2) and shuffled_deck[i] == h2[h2_index]:
h2_index += 1
else:
return False
return True
shuffled_with_riffle = [10, 4, 5, 1]
shuffled_without_riffle = [10, 4, 5, 9]
h1 = [10, 4, 1]
h2 = [5]
print(is_shuffled_with_single_riffle_recursive(shuffled_with_riffle, h1, h2))
print(is_shuffled_with_single_riffle(shuffled_with_riffle, h1, h2))
print(is_shuffled_with_single_riffle_recursive(shuffled_without_riffle, h1, h2))
print(is_shuffled_with_single_riffle(shuffled_without_riffle, h1, h2))
#Solution
'''
def is_single_riffle(half1, half2, shuffled_deck):
half1_index = 0
half2_index = 0
half1_max_index = len(half1) - 1
half2_max_index = len(half2) - 1
for card in shuffled_deck:
# If we still have cards in half1
# and the "top" card in half1 is the same
# as the top card in shuffled_deck
if half1_index <= half1_max_index and card == half1[half1_index]:
half1_index += 1
# If we still have cards in half2
# and the "top" card in half2 is the same
# as the top card in shuffled_deck
elif half2_index <= half2_max_index and card == half2[half2_index]:
half2_index += 1
# If the top card in shuffled_deck doesn't match the top
# card in half1 or half2, this isn't a single riffle.
else:
return False
# All cards in shuffled_deck have been "accounted for"
# so this is a single riffle!
return True
''' |
1eec9005b1d8ecd3969a33eb4103b695c5c3c371 | abdu-zeyad/math-series | /math_series/series.py | 537 | 3.921875 | 4 | def fibonacci(n):
# the formula is : Fn= Fn-1 + Fn-2
if n <= 1:
if n == 0:
return 0
else:
return 1
return fibonacci(n-1) + fibonacci(n-2)
def lucas(n):
if n <= 1:
if n == 0:
return 2
else:
return 1
return lucas(n-1) + lucas(n-2)
def sum_series(n, f=0, s=1):
if n == 0:
return f
elif n == 1:
return s
else:
return sum_series(n - 1, f, s) + sum_series(n - 2, f, s)
print(sum_series(3, 1, 2))
|
87d5c492f448a45c933a82112313c864b435cf3a | sdeva90/Python | /readlineinput.py | 287 | 3.84375 | 4 | # program to understand stdin.readline() function and module system
import sys
def sillyage():
print("how old are you")
age = int(sys.stdin.readline())
if age == 3:
print("i'm child")
elif age == 40:
print("I'm adult")
else:
print("I'm none")
|
742b355baefa55bc874e14ad5eb57961ffd8a5ba | ishantk/PythonSep72018 | /venv/Session26.py | 1,610 | 4.03125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
data = pd.read_csv("advertising.csv")
# print(data)
X = data["TV"].values
Y = data["Sales"].values
print(">>>>>>>>>>>>>>>X><<<<<<<<<<<<<<<")
print(X)
print(">>>>>>>>>>>>>>>>Y<<<<<<<<<<<<<<<")
print(Y)
print(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<")
result = stats.linregress(X,Y)
b1 = result[0]
b0 = result[1]
print("Slope is:",b1)
print("Intercept is:",b0)
# Equation: Y = b0 + b1.X
# Predict Y1 based on equation of line for original values of X
Y1 = []
for x in X:
y = b0 + (b1*x)
Y1.append(y)
print(">>>>>>>>>>>>>>>>Y1<<<<<<<<<<<<<<<")
print(Y1)
print(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
# plt.plot(X,Y,"ro")
plt.plot(X, Y, "o", X, Y1)
# plt.show()
# Calculating MSE will help us to know wether we have correct equation or not to predict
print(">>>>>>>>>>>>>>>>SCI-KIT<<<<<<<<<<<<<<<")
# Let us USE SCIPY to Solve Linear Regression Problem
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Create Object of Linear Regression
regression = LinearRegression()
l = len(X)
X = X.reshape(l,1)
print(l)
print("************")
print(X)
print("************")
# fit is a function which is taking data as input
# this input data is also know as training data
regResult = regression.fit(X, Y)
Y1 = regResult.predict(X)
print("=======================")
print(Y1)
print("=======================")
mse = regResult.score(X,Y)
print("=======================")
print("MSE:",mse)
print("=======================") |
1dbfb4b3a745f2efacf6fd00de51c392afe8ebbd | knnaraghi/MIT-6.00x | /Problem-Set-2/pay_off_debt_bisection_search.py | 697 | 3.859375 | 4 | balance = 431015
annualInterestRate = 0.15
monthlyInterestRate = annualInterestRate / 12.0
minimumpayment = balance / 12.0
maximumpayment = (balance * (1+ monthlyInterestRate)**12) / 12.0
payment = (minimumpayment + maximumpayment) / 2.0
originalbalance = balance
while abs(balance) >= 0.01:
balance = originalbalance
payment = (minimumpayment + maximumpayment) / 2.0
for x in range (1, 13):
balance = (balance - payment) + ((balance - payment) * monthlyInterestRate)
if balance == 0:
break
if balance > 0:
minimumpayment = payment
if balance < 0:
maximumpayment = payment
print "Lowest Payment: " + str(round(minimumpayment, 2))
|
5a7bf067101260fcc1f6e31dae2b25a9fd7533e7 | susanmpu/sph_code | /python-programming/learning_python/factorial.py | 445 | 4.09375 | 4 | #!/usr/bin/env python
# by Samuel Huckins
""" Calculates factorial of the number entered.
"""
def main():
"""
Requests a number, returns its factorial.
"""
num = int(raw_input("What is the number? "))
fact = 1
for factor in range(num, 1, -1):
fact = fact * factor
print "The factorial of %s is %s." % (num, fact)
if __name__ == '__main__':
main()
if raw_input("Press RETURN to exit."):
sys.exit(0)
|
490e2bbfe898da96aa8e25a4a3505b5ba98176ad | bhushanyadav07/coding-quiz-data-track- | /quiz1.py | 646 | 4.375 | 4 | #In this quiz you're going to do some calculations for a tiler. Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long.
#Tiles come in packages of 6.
#1.How many tiles are needed?
#2.You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over?
a = (9*7)+(5*7)
print(a)
#and how many tiles are left
print((17*6)-a)
--->You correctly calculated the number of tiles needed. Nice work!
I calculated my answer like this: 9*7 + 5*7
--->You correctly calculated the number of leftover tiles. Well done!
I calculated my answer like this: (17*6) - (9*7 + 5*7)
|
0f9b60909d2e5830ff7f2d0d810fe4788b66b8f7 | RGMishan/py4e | /mlUdemy/zip.py | 521 | 4.5 | 4 | #zip function
myList= [1,2,3]
urList= [4,5,6]
print(list(zip(myList,urList))) # create a list of tupples
# store one one iterable from both the list or itearable
# prints out [(1, 4), (2, 5), (3, 6)]
myList2= [1,2,3,5,6]
urList2= (4,5,6) #doesnot matter if it is list or tupple need to be iterable
print(list(zip(myList2,urList2))) #prints out same input until it finds out its same iterable
#can be used in database to get info of name and phone number related and create new set
#can add as many iterable you want |
df8a83d7afa0b63654dfe1fbdc54a566f2cd7009 | pornthipkamrisu/AI | /c1.py | 718 | 3.921875 | 4 | Number = input("Please enter 3 integers : ")
num1 = int(Number[0])
num2 = int(Number[2])
num3 = int(Number[4])
if ((num1 > num2) and (num1 > num3) and (num2 > num3)):
Max = num1
Min = num3
elif ((num2 > num1) and (num2 > num3) and (num1 > num3)):
Max = num2
Min = num3
elif ((num1 > num2) and (num1 > num3) and (num3 > num2)):
Max = num1
Min = num2
elif ((num2 > num1) and (num2 > num3) and (num3 > num1)):
Max = num2
Min = num1
elif ((num3 > num2) and (num3 > num2) and (num2 > num1)):
Max = num3
Min = num1
elif ((num3 > num2) and (num3 > num1) and (num1 > num2)):
Max = num3
Min = num1
else:
pass
print("Max is", Max)
print("Min is", Min) |
1c08ddb58a8789f094bc0acd5bd5887ebff6b1fb | learningandgrowing/Data-structures-problems | /satyampwhidden.py | 375 | 3.71875 | 4 |
def extractMaximum(ss):
num, res = 0, 0
# start traversing the given string
for i in range(len(ss)):
if ss[i] >= "0" and ss[i] <= "9":
num = num * 10 + int(int(ss[i]) - 0)
else:
res = max(res, num)
num = 0
return max(res, num)
print(extractMaximum(input()))
|
7bf24bbadb1ef156110b4a206032085c9d4b1863 | bluescience/pythonCode3 | /rootPwr.py | 433 | 4.0625 | 4 | def rootPwr(num):
rt = 0
pwr = 6
while (rt ** pwr) != abs(num):
rt += 1
if rt > num-1: # no root is bigger than its num
pwr -= 1
rt = 0
if pwr < 0:
return("There is no valid solution to this problem.")
return("The solution for int = {} is root = {} and pwr = {}.".format(num, rt, pwr))
print(rootPwr(int(input("Input an integer: ")))) |
dde19ee648772802b167a904584cabd51923bacb | YuriSpiridonov/CodeWars | /add-commas-to-a-number-1.py | 655 | 3.84375 | 4 | # https://www.codewars.com/kata/add-commas-to-a-number-1/train/python
import re
def commas(num):
num = round(num,3)
regex = re.compile(r'(-?\d+)(\.\d+)?')
mo = regex.findall(str(num))
lst = list(mo[0][0])
lencount = len(lst)//3
y = 3
returnNumber = str()
if len(lst)<=3:
returnNumber = ''.join(lst)
else:
for x in range(lencount):
lst.insert(-y,',')
y+=4
if lst[0]==',':
lst.pop(0)
if lst[0]=='-' and lst[1]==',':
lst.pop(1)
returnNumber = ''.join(lst)
if mo[0][1] != '.0':
returnNumber += ''.join(mo[0][1])
return returnNumber
|
0c59f38ff69878a7c7dd237d260aec0a23c8dc8c | Priyanka0502/The_Python_Bible | /cinema_simulator.py | 780 | 4.3125 | 4 | films={
"titanic":{"age_limit":16,"Tickets":2},
"fault in our stars":{"age_limit":14,"Tickets":8},
"little women":{"age_limit":12,"Tickets":5},
"avengers":{"age_limit":8,"Tickets":15},
}
while True:
choice=input("Which film you want to see?").lower()
if choice in films:
age=int(input("how old are you").strip())
if age>=films[choice]["age_limit"]:
num_seats=films[choice]["Tickets"]
if num_seats>0:
print("enjoy the film!!")
films[choice]["Tickets"]=films[choice]["Tickets"]-1
else:
print("Ooops Sorry,We are sold out!!")
else:
print("you are too old to watch the film")
else:
print("we donot have that film....")
|
d78c0c373d89579bea4e9e6c6dd8ce03218a59cc | SnyderMbishai/python_exercises | /list_comprehension3.py | 335 | 4.28125 | 4 | '''Write a program that takes a list of numbers
(for example, a = [5, 10, 15, 20, 25])
and makes a new list of only the first
and last elements of the given list.
For practice, write this code inside a function.'''
a = [2,6,8,10,11,22]
def print_last_and_first(x):
print([x[0], x[len(x)-1]])
print_last_and_first(a) |
b29a78287c486bec6d57ee5707fd2b46a9ea764b | kannor/angry_search | /prac Unit3/loops_on_list.py | 1,117 | 3.921875 | 4 |
list = [1,2,3,4]
i = 0
while i < len(list):
print list[i]
i = i+1
for i in range(len(list)):
print list[i]
i = i + 1
# sum list
def sum_list(list):
sum = 0
for i in list :#' or ' range(len(list)) :
sum = sum+ i # 'or ' list[i]
print 'sum ' , sum
sum_list([1,2,3,4,5])
# Measure udacity
'''
def measure_udacity(list):
for i in range(len(list)):
checker = list[i][0]
#print checker
if checker == 'U':
print list[i]
else:
#print 'does not match'
break
measure_udacity(['Uda','Una','Ama'])
'''
def measure_udacity(list):
count = 0
for e in list:
if e[0]== 'U':
count = count + 1
return count
measure_udacity(['Uda','Una','Ama'])
# 23. find element
def find_element(list , integ):
for e in range(len(list)):
if list[e] == integ:
print e
return '-1'
#find_element([1,2,2],3)
def find_element_index(list,integ):
print list.index(integ)
#find_element_index([1,2,3],3)
def find_element_index_in(list,integ):
checker = integ in list
if checker == True:
print list.index(integ)
return -1
find_element_index_in([1,2,3],3)
|
799b40ac45c622807eb9dd8d7ff93322ecc263cd | iamashu/Data-Camp-exercise-PythonTrack | /part6-import-webdata/No11-Pop-quiz-Exploring-your-JSON.py | 924 | 4.375 | 4 | #Pop quiz: Exploring your JSON
'''
Load the JSON 'a_movie.json' into a variable, which will be a dictionary. Do so by copying, pasting and executing the following code in the IPython Shell:
import json
with open("a_movie.json") as json_file:
json_data = json.load(json_file)
Print the values corresponding to the keys 'Title' and 'Year' and answer the following question about the movie that the JSON describes:
Which of the following statements is true of the movie in question?
#Possible Answers
The title is 'Kung Fu Panda' and the year is 2010.
The title is 'Kung Fu Panda' and the year is 2008.
The title is 'The Social Network' and the year is 2010. correct
The title is 'The Social Network' and the year is 2008.
'''
# Code
import json
with open("a_movie.json") as json_file:
json_data = json.load(json_file)
print(json_data['Title'])
print(json_data['Year'])
'''result
The Social Network
2010
''' |
2dc2788bfd5e2d71ba73cb067e6d8f0a1585b810 | fpavanetti/python_lista_de_exercicios | /aula9_ex023.py | 927 | 4.375 | 4 | '''
Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas
- O nome com todas minúsculas
- Quantas letras ao todo (sem consirar espaços)
- Quantas letras tem o primeiro nome
'''
n = str(input("Digite seu nome completo: "))
print()
print("*" * 40)
print(n)
print("Com todas as letras maiúsculas: {}.".format(n.upper()))
print("Com todas as letras minúsculas: {}.".format(n.lower()))
print("Número de caracteres do nome sem espaços: {}.".format((len(n.replace(" ", "")))))
'''Solução do Guanabara
print("Seu nome tem ao todo {} letras.".format(len(nome) - nome.count(" ")'''
print("Primeiro nome: {[0]}.".format(n.split()))
# solução guanabara
# print("Seu primeiro nome tem {} letras.".format(nome.find(' ')))
# separa = n.split()
# print("Seu primeiro nome é {} e ele {} letras".format(separa[0], len(separa[0])))
print("*" * 40)
|
c0faa0506752612f470a37d11fb0f87acaf8ab55 | guiaugusto/data_structures_examples | /Search_Tree/st_python_binary.py | 713 | 4.03125 | 4 | class Node():
def __init__(self, value):
self.right = None
self.left = None
self.value = value
def add_node(self):
pass
def remove_node(self):
"""
This method have to do this following orders:
1. Have to find the node in Binary Tree
2. If the node was found, it have to remove the following node
3. Have to rebalance the following tree
"""
pass
def search_node(self):
pass
def list_in_order(tree):
if tree:
list_in_order(tree.left)
print('{} '.format(tree.value))
list_in_order(tree.right)
node_2 = Node(2)
node_1 = Node(1)
node_4 = Node(4)
node_2.right = node_4
node_2.left = node_1
list_in_order(node_2)
|
b6f397d2059104aa23c8394242e357b35dbc8154 | ericyishi/HTMLTestRunner_PY3 | /test_case/Test_Calc2.py | 1,257 | 3.90625 | 4 | import unittest
from Calc import Calc
class TestCalc(unittest.TestCase):
'''计算器模块2'''
def setUp(self):
print("测试开始")
self.cal = Calc() # 在这里实例化
def test_add(self):
'''计算器加法模块2'''
self.assertEqual(self.cal.add(1, 2), 3, 'test add1 failed')
self.assertNotEquals(self.cal.add(1, 4), 4, 'test add2 failed')
print("test_add pass")
# @unittest.skip("暂时不测")
def test_minus(self):
'''计算器减法模块2'''
self.assertEqual(self.cal.minus(1, 2), -1, 'test minus1 failed')
self.assertEqual(self.cal.minus(3, 2), 1, 'test minus2 failed')
print("test_minus pass")
def test_divide(self):
"""计算器除法法模块2"""
self.assertEqual(self.cal.divide(6, 2), 3, 'test divide1 failed')
self.assertEqual(self.cal.divide(3, 2), 1, 'test divide2 failed')
def test_multiple(self):
"""计算器乘法模块2"""
self.assertEqual(self.cal.multiple(6, 2), 12, 'test multiple1 failed')
self.assertEqual(self.cal.multiple(3, 2), 6, 'test multiple2 failed')
def tearDown(self):
print("测试结束")
if __name__ == '__main__':
unittest.main()
|
d4c4d13664f28227f9b69e0bf7b166f862abb321 | terylll/LeetCode | /TwoPointer/88_mergeSortedArray.py | 733 | 3.9375 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# Move back to front
i = m - 1
j = n - 1
p = m + n - 1
while(j >= 0):
if (i >= 0 and nums1[i] > nums2[j]):
nums1[p] = nums1[i]
i -= 1
else:
nums1[p] = nums2[j]
j -= 1
p -= 1
# return nums1
nums1 = [1,2,3,0,0,0]
nums2 = [2,5,6]
sol = Solution()
sol.merge(nums1, 3, nums2, 3)
print(nums1) |
5230aa3a2c3b2b2b53719b1b56d033bc8896f176 | algol2302/PythonTricks | /002_functions/fabric_adders.py | 197 | 3.515625 | 4 | def make_adder(n):
def add(x):
return x + n
return add
if __name__ == '__main__':
plus_3 = make_adder(3)
plus_5 = make_adder(5)
print(plus_3(3))
print(plus_5(7))
|
a2aa44a8cb10fc729b324b6927fddb29b18c6637 | BrettMcGregor/udemy-colt-steele | /min_max.py | 562 | 3.71875 | 4 | # def extremes(iterable):
# return min(iterable), max(iterable)
#
#
# print(extremes([1,2,3,5,4,5]))
# print(extremes("alcatrza"))
#
#
# def max_magnitude(num_list):
# return max(abs(n) for n in num_list)
#
#
# print(max_magnitude([1,2,3,54,4,5]))
#
#
# def sum_even_values(args):
# return sum(x for x in args if x % 2 == 0)
#
#
# print(sum_even_values([1,2,3,4,5,6,88]))
#
def sum_floats(*args):
return sum(num for num in args if isinstance(num, float))
print(sum_floats(1.5, 2.4, 'awesome', [], 1)) # 3.9)
print(sum_floats(1,2,3,4,5)) # 0)
|
957fbf7209108eab0bfae3c3a7988952eb6e2a57 | NANDHINIR25/GUVI | /codekata/three numbers can form the sides og=f rite angled triangle.py | 111 | 3.65625 | 4 | ip1,ip2,ip3=map(int,input().split())
a=((ip1**2)+(ip2**2))
if((ip3**2)==a):
print("yes")
else:
print("no")
|
2d379232b526f348d0f3fe14b8d35796dbf80e34 | ikemerrixs/Au2018-Py210B | /students/yushus/session08/Circle.py | 2,871 | 4.125 | 4 | #!/usr/bin/env/python3
"""
Yushu Song
Au2018-Py210B
Circle Class Assignment
"""
from math import pi
class Circle:
def __init__(self, radius):
if radius < 0:
raise ValueError('Radius cannot be < 0')
self.__radius = radius
self.__diameter = 2*self.__radius
@property
def radius(self):
return self.__radius
@property
def diameter(self):
return self.__diameter
@diameter.setter
def diameter(self, value):
self.__init__(value/2)
@property
def area(self):
return pi * self.__radius * self.__radius
@classmethod
def from_diameter(class_object, value):
print(class_object)
return class_object(value/2)
def __str__(self):
return f'Circle with radius: {self.__radius:.6f}'
def __repr__(self):
return f'Circle({self.__radius})'
def __add__(self, other):
if isinstance(other, Circle):
return Circle(self.radius + other.radius)
raise TypeError('{other} has to be a Circle type')
def __mul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
raise TypeError('{other} has to be an int type')
def __rmul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
raise TypeError('{other} has to be an int type')
def __iadd__(self, other):
if isinstance(other, Circle):
return Circle(self.radius + other.radius)
raise TypeError('{other} has to be a Circle type')
def __imul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
raise TypeError('{other} has to be an int type')
def __lt__(self, other):
if isinstance(other, Circle):
return self.radius < other.radius
raise TypeError('{other} has to be a Circle type')
def __le__(self, other):
if isinstance(other, Circle):
return self.radius <= other.radius
raise TypeError('{other} has to be a Circle type')
def __eq__(self, other):
if isinstance(other, Circle):
return self.radius == other.radius
raise TypeError('{other} has to be a Circle type')
def __ne__(self, other):
return not self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class Sphere(Circle):
@property
def area(self):
return pi * super().radius * super().radius * 4
@property
def volume(self):
return pi * super().radius * super().radius* super().radius * 4 / 3
def __str__(self):
return f'Sphere with radius: {super().radius:.6f}'
def __repr__(self):
return f'Sphere({super().radius})' |
0041655ef07e3861ee98fedc5e8467a7aea98135 | crossphd/MIT_Programming_with_Python_6.00._x | /item_order function.py | 1,593 | 3.921875 | 4 |
#w = raw_input("Enter any word: ")
order = "salad water hamburger salad hamburger"
def item_order(order):
global salad, water, hamburger
salad = 0
water = 0
hamburger = 0
s = order
for l in range(len(s)):
#salad count
if s[l] == "s":
if l+1 < len(s) and s[l + 1] == "a":
if l+2 < len(s) and s[l + 2] == "l":
if l+3 < len(s) and s[l + 3] == "a":
if l+4 < len(s) and s[l + 4] == "d":
salad += 1
#water count
elif s[l] == "w":
if l+1 < len(s) and s[l + 1] == "a":
if l+2 < len(s) and s[l + 2] == "t":
if l+3 < len(s) and s[l + 3] == "e":
if l+4 < len(s) and s[l + 4] == "r":
water += 1
#hamburger count
elif s[l] == "h":
if l+1 < len(s) and s[l + 1] == "a":
if l+2 < len(s) and s[l + 2] == "m":
if l+3 < len(s) and s[l + 3] == "b":
if l+4 < len(s) and s[l + 4] == "u":
if l+5 < len(s) and s[l + 5] == "r":
if l+6 < len(s) and s[l + 6] == "g":
if l+7 < len(s) and s[l + 7] == "e":
if l+8 < len(s) and s[l + 8] == "r":
hamburger += 1
return "salad:" + str(salad) + " hamburger:" + str(hamburger) + " water:" +str(water)
a = item_order(order)
print a |
81049a8d911cbec22f0527292e08f8d169be3d6c | gndit/datastructure | /reverselist.py | 909 | 4.40625 | 4 | #python progame to reverse a linked list
class NODE:
def __init__(self,data):
self.data=data
self.next=None
class LINKED:
def __init__(self):
self.head=None
def reverse(self):
prev=None
temp=self.head
while (temp is not None):
next=temp.next
temp.next=prev
prev=temp
temp=next
self.head=prev
def push(self,new_data):
new_node=NODE(new_data)
new_node.next=self.head
self.head=new_node
def print(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
if __name__=='__main__':
lst=LINKED()
print("before reverse list look like this-->")
lst.push(3)
lst.push(9)
lst.push(8)
print(lst.print())
print(" after reverse list look like this-->")
lst.reverse()
print(lst.print())
|
6c89dd46d64b8d5c8b345a4d5d8685ce0b341549 | mikem2314/PythonExercises | /TimeDelta.py | 436 | 3.515625 | 4 | #Written to solve https://www.hackerrank.com/challenges/python-time-delta/problem
import datetime
formatString = "%a %d %b %Y %H:%M:%S %z"
testCases = int(input())
for t in range(testCases):
t1 = str(input())
t2 = str(input())
formatT1 = datetime.datetime.strptime(t1, formatString)
formatT2 = datetime.datetime.strptime(t2, formatString)
diff = formatT2 - formatT1
print (int(abs(diff.total_seconds()))) |
ad3e55d120fc073ec0211a26ac45b72cf639a059 | chenxu0602/LeetCode | /808.soup-servings.py | 2,900 | 3.75 | 4 | #
# @lc app=leetcode id=808 lang=python3
#
# [808] Soup Servings
#
# https://leetcode.com/problems/soup-servings/description/
#
# algorithms
# Medium (38.04%)
# Likes: 102
# Dislikes: 377
# Total Accepted: 6.9K
# Total Submissions: 18.1K
# Testcase Example: '50'
#
# There are two types of soup: type A and type B. Initially we have N ml of
# each type of soup. There are four kinds of operations:
#
#
# Serve 100 ml of soup A and 0 ml of soup B
# Serve 75 ml of soup A and 25 ml of soup B
# Serve 50 ml of soup A and 50 ml of soup B
# Serve 25 ml of soup A and 75 ml of soup B
#
#
# When we serve some soup, we give it to someone and we no longer have it.
# Each turn, we will choose from the four operations with equal probability
# 0.25. If the remaining volume of soup is not enough to complete the
# operation, we will serve as much as we can. We stop once we no longer have
# some quantity of both types of soup.
#
# Note that we do not have the operation where all 100 ml's of soup B are used
# first.
#
# Return the probability that soup A will be empty first, plus half the
# probability that A and B become empty at the same time.
#
#
#
#
# Example:
# Input: N = 50
# Output: 0.625
# Explanation:
# If we choose the first two operations, A will become empty first. For the
# third operation, A and B will become empty at the same time. For the fourth
# operation, B will become empty first. So the total probability of A becoming
# empty first plus half the probability that A and B become empty at the same
# time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
#
#
#
# Notes:
#
#
# 0 <= N <= 10^9.
# Answers within 10^-6 of the true value will be accepted as correct.
#
#
#
from functools import lru_cache
class Solution:
def soupServings(self, N: int) -> float:
# Time complexity: O(1)
# Space complexity: O(1)
# if N > 500 * 25: return 1
# memo = {}
# def dp(n1, n2, memo):
# if n1 <= 0 and n2 <= 0:
# return 0.5
# if n1 <= 0:
# return 1.0
# if n2 <= 0:
# return 0
# if (n1, n2) in memo:
# return memo[(n1, n2)]
# memo[(n1, n2)] = 0.25 * (dp(n1-100, n2, memo) + dp(n1-75, n2-25, memo) + dp(n1-50, n2-50, memo) + dp(n1-25, n2-75, memo))
# return memo[(n1, n2)]
# prob = dp(N, N, memo)
# return round(prob, 5)
if N > 500 * 25: return 1
@lru_cache(None)
def dp(n1, n2):
if n1 <= 0 and n2 <= 0:
return 0.5
if n1 <= 0:
return 1.0
if n2 <= 0:
return 0
return 0.25 * (dp(n1 - 100, n2) + dp(n1 - 75, n2 - 25) + dp(n1 - 50, n2 - 50) + dp(n1 - 25, n2 - 75))
prob = dp(N, N)
return round(prob, 5)
|
eb7baf422562d7e9b7ef952234916f4ad6f117fe | Jordens1/python3-test | /work/python_goon/outer_inner.py | 492 | 3.765625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
def outer(arg): # arg = echo()
def inner():
print("*" * 20)
arg() # echo 原函数
print("*" * 20)
return inner
# @outer #
# def echo():
# print('欢迎来到')
# echo()
def echo():
print('欢迎来到')
echo = outer(echo)
echo()
li = ["hello","world", 'len', 'network']
for idx, item in enumerate(li):
print(idx, item)
for idx, item in enumerate(li, 10):
print(idx, item)
|
12d89d0b176551ca93b42fda41bbda6f1249e245 | 17764591637/jianzhi_offer | /LeetCode/746_minCostClimbingStairs.py | 1,878 | 4 | 4 | '''
数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 1:
输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:
输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
注意:
cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
'''
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
# 思路: 从楼顶分析,比如说10为楼顶,到达楼顶只有两种方式,一种从第八层走两步到达,一种是从第九层走一步到达,因为该10为楼顶其:
# 10为楼顶:F(10)最有子结构为: F(9) 和 F(8)
# F(10) 递推式: F(10)=min(F(9)+cost[9],F(8)+cost[8])
# 边界: F(0)=1 F(1)=100
#
if len(cost)<=1:
return min(cost)
dp=[]
dp.append(cost[0])
dp.append(cost[1])
for i in range(2,len(cost)+1): #楼顶不在cost的范围内,因为对遍历+1
if i==len(cost): #该层为楼顶,没有取值
dp.append(min(dp[i-1],dp[i-2]))
else:
dp.append(min(dp[i-1]+cost[i],dp[i-2]+cost[i]))
return dp[-1] |
a45d7871694012a5064bc07b6e9033f6fcb15457 | guilhermeerosa/Python | /Exercicios-CursoEmVideo/ex019.py | 335 | 3.78125 | 4 | #Escolha aleatória de 4 alunos com biblioteca random/choice
from random import choice
al1 = input('Nome do primeiro aluno? ')
al2 = input('Nome do segundo aluno? ')
al3 = input('Nome do terceiro aluno? ')
al4 = input('Nome do quarto aluno? ')
escolha = choice([al1, al2, al3, al4])
print('O aluno escolhido foi: {}!'.format(escolha))
|
85c506a47d6808b6bd9bef106fb00131bdb2931a | frankcollins3/algorithm | /merge_sort.py | 218 | 3.796875 | 4 | def merge_sort(arr):
if len(arr) < 3:
return array
middle = int(len(arr) / 2)
left, right = merge_sort(arr[:middle]) merge_sort(arr[middle:])
def merge(left, right):
return merge_sort |
a49ce0661ee451c3a3205595da62a820c79a6532 | zingzheng/LeetCode_py | /106Construct Binary Tree from Inorder and Postorder Traversal.py | 772 | 3.9375 | 4 | ##Construct Binary Tree from Inorder and Postorder Traversal
##Given inorder and postorder traversal of a tree, construct the binary tree.
##
##2015年8月13日 21:30:26 AC
##zss
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {integer[]} inorder
# @param {integer[]} postorder
# @return {TreeNode}
def buildTree(self, inorder, postorder):
if not inorder:return None
n = postorder[-1]
i = inorder.index(n)
postorder.remove(n)
root = TreeNode(n)
root.right = self.buildTree(inorder[i+1:],postorder)
root.left = self.buildTree(inorder[:i],postorder)
return root
|
7ff279395092baf994281420aae6a628ebe1fd74 | noltron000-coursework/data-structures | /source/linkedlist.py | 9,835 | 4.1875 | 4 | #!python
class Node(object):
def __init__(self, data):
'''
Initialize this node with the given data.
'''
self.data = data
self.next = None
def __repr__(self):
'''
Return a string representation of this node.
'''
return f'Node({self.data})'
class LinkedList(object):
def __init__(self, iterable=None):
'''
Initialize this linked list.
Append given items, if any.
'''
self.head = None # First node
self.tail = None # Last node
self.size = 0 # Number of nodes
# Append the given items
if iterable is not None:
for item in iterable:
self.append(item)
def __str__(self):
'''
Return a prettified string visualization.
It will represent our linked list.
'''
items = [f'({item})' for item in self.items()]
return f'[{" -> ".join(items)}]'
def __repr__(self):
'''
Return a string representation of this linked list.
'''
return f'LinkedList({self.items()})'
def items(self):
'''
Return a list of all items in this linked list.
---
Best & worst case run time: Θ(n) <theta>
--> to get a list of all items,
we must always visit all n items.
'''
# create an empty list of results.
result = []
# start at the head node.
node = self.head
# loop until the node is None,
# which is one node too far past the tail.
while node is not None: # always O(n); no early exit.
# append this node's data to the results list.
result.append(node.data)
# get the next node.
node = node.next
# now result contains the data from all nodes.
return result # Constant time to return a list.
def is_empty(self):
'''
Return True if this linked list is empty, or False.
'''
return self.head is None
def length(self):
'''
Return the length of this linked list.
This is done by traversing its nodes.
---
Best & worst case run time: O(n) [TODO] <Θ theta?>
--> to get the length of our linked list,
we must always visit all n items.
'''
# node counter initialized to zero.
node_count = 0
# start at the head node.
node = self.head
# loop until the node is None,
# which is one node too far past the tail.
while node is not None:
# count one for this node.
node_count += 1
# get the next node.
node = node.next
# now result contains the number of nodes.
return node_count
def get_at_index(self, index):
'''
Return the item at the given index in this linked list.
Raise ValueError if the given index is out of range.
---
Best case run time: O(1) [TODO] <Ω omega?>
if item is near the head of the list or is not present.
---
Worst case run time: O(n)
if item is near the tail of the list.
'''
# check if the given index is out of range;
# this only happens if index is negative or is massive.
if not (0 <= index < self.size):
raise ValueError(f'List index out of range: {index}')
# index counter initialized to zero.
index_count = 0
# start at the head node.
node = self.head
# loop until the node is None or index item is found.
# note that this while loop will never be false.
while (0 <= index_count < self.size):
# check if condition is met.
if index_count == index:
# will always eventually get here.
return node
# count one for this node.
index_count += 1
# skip to the next node.
node = node.next
else:
raise ValueError('While loop broke unexpectedly.')
def insert_at_index(self, index, item):
'''
Insert the given item at the given index in linked list.
Raise ValueError if the given index is out of range.
---
Best case run time: O(1)
--> method is fastest in one of two cases cases:
1. index is at the head
2. index is not present
---
Worst case run time: O(n)
--> method is slowest if item is at the end of the list,
because it must loop through all n items to find it.
'''
# check if the given index is out of range;
# this only happens if index is negative or is massive.
if not (0 <= index <= self.size):
raise ValueError(f'List index out of range: {index}')
# check if index is head or tail.
elif index == 0:
self.prepend(item)
elif index == self.size:
self.append(item)
# index is in the center of the list.
else:
# get all our important nodes laid out.
prv_node = self.get_at_index(index - 1)
nxt_node = prv_node.next
new_node = Node(item)
# change some pointers around.
new_node.next = nxt_node
prv_node.next = new_node
# finally, update linked list size.
self.size += 1
def append(self, item):
'''
Insert the given item at the tail of this linked list.
---
Best & worst case run time: O(1)
--> reading the tail or head is blazing fast.
the other features in here are constant too.
'''
# Create a new node to hold the given item
new_node = Node(item)
# Check if this linked list is empty
if self.is_empty():
# Assign head to new node
self.head = new_node
else:
# Otherwise insert new node after tail
self.tail.next = new_node
# Update tail to new node regardless
self.tail = new_node
# Finally, update size
self.size += 1
def prepend(self, item):
'''
Insert the given item at the head of this linked list.
---
Best & worst case run time: O(1)
--> reading the tail or head is blazing fast.
the other features in here are constant too.
'''
# Create a new node to hold the given item
new_node = Node(item)
# Check if this linked list is empty
if self.is_empty():
# Assign tail to new node
self.tail = new_node
else:
# Otherwise insert new node before head
new_node.next = self.head
# Update head to new node regardless
self.head = new_node
# Finally, update size
self.size += 1
def find(self, quality):
'''
Search for some data in our linked list.
Do this by using a 'quality' function;
it returns a boolean - true if it is satisfied.
Once found, return the node which encapsulates the data.
---
Best case run time: Ω(1) <omega>
--> if item is near the head of the list.
---
Worst case run time: O(n)
--> if item is near the tail of the list or not present
and we need to loop through all n nodes in the list.
'''
# start at the head node.
node = self.head
# loop until the node is None,
# which is one node too far past the tail.
while node is not None: # O(n) w/ potential early exit.
# does node's data satisfy the quality function?
if quality(node.data):
# quality function is satisfied, return the node.
# note that we exit early when we find a match.
return node
# otherwise skip to the next node.
node = node.next
# quality function was never satisfied...
# meaning there is no matching node that exists to find!
return None
def replace(self, old_data, new_data):
'''
Find the a node with the given old_data.
Update it to contain the given new_data.
Raise ValueError if old_data is not found.
---
Best case run time: Ω(1) <omega>
--> same as the find method
---
Worst case run time: O(n)
--> same as the find method
'''
# used find method to find node.
node = self.find(lambda item: item == old_data)
# check if the node was not found.
if node == None:
raise ValueError(f'Target node was not found: {node}')
# changed node's data with new data.
node.data = new_data
def delete(self, item):
'''
Delete the given item from this linked list.
If for some reason we can't, raise ValueError.
TODO: refactor using find() function.
---
Best case run time: O(1)
--> item is at the head.
---
Worst case run time: O(n)
--> item is at the tail.
'''
# start at the head node.
node = self.head
# keep track of the previous node.
# do this since the list is not doubly-linked.
prv_node = None
# create a flag to track if we found the given item.
found = False
# loop until we find the given item, or reach the tail.
# if the node is None, we have reached the tail.
while not found and node is not None:
# check if the node's data matches the given item.
if node.data == item:
# we found data matching the given item.
found = True
else:
# skip to the next node.
prv_node = node
node = node.next
# check if we found the given item or not.
if found:
# check if we found a node in the middle of this list.
if node is not self.head and node is not self.tail:
# update prv_node to skip around the found node.
prv_node.next = node.next
# unlink the found node from its next node.
node.next = None
# check if we found a node at the head.
if node is self.head:
# update head to the next node.
self.head = node.next
# unlink the found node from the next node.
node.next = None
# check if we found a node at the tail.
if node is self.tail:
# check if there is a node before the found node.
if prv_node is not None:
# unlink the prv_node from the found node.
prv_node.next = None
# update tail to the prv_node regardless.
self.tail = prv_node
# finally, update size.
self.size -= 1
else:
raise ValueError(f'Item not found: {item}')
def test_linked_list():
ll = LinkedList()
print(ll)
print('Appending items:')
ll.append('A')
print(ll)
ll.append('B')
print(ll)
ll.append('C')
print(ll)
print(f'head: {ll.head}')
print(f'tail: {ll.tail}')
print(f'size: {ll.size}')
print(f'length: {ll.length()}')
print('Getting items by index:')
for index in range(ll.size):
item = ll.get_at_index(index).data
print(f'get_at_index({index}): {item}')
print('Deleting items:')
ll.delete('B')
print(ll)
ll.delete('C')
print(ll)
ll.delete('A')
print(ll)
print(f'head: {ll.head}')
print(f'tail: {ll.tail}')
print(f'size: {ll.size}')
print(f'length: {ll.length()}')
if __name__ == '__main__':
test_linked_list()
|
97075196a97faea1f4e6a72383fbd3d6843ddfc9 | JoshRifkin/IS211_Assignment10 | /load_pets.py | 2,026 | 3.671875 | 4 | # Assignment 10
# Load Pets
# By: Joshua Rifkin
import sqlite3 as sql
def createDB(db):
# Delete tables if they already exist, prepping for creation
db.execute("DROP TABLE IF EXISTS person;")
db.execute("DROP TABLE IF EXISTS pet;")
db.execute("DROP TABLE IF EXISTS person_pet;")
# Create Tables
db.execute("CREATE TABLE person (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, age INTEGER);")
db.execute("CREATE TABLE pet (id INTEGER PRIMARY KEY, name TEXT, breed TEXT, age INTEGER, dead INTEGER);")
db.execute("CREATE TABLE person_pet (person_id INTEGER, pet_id INTEGER);")
# Populate person table
db.execute("INSERT INTO person VALUES(1, 'James', 'Smith', 41);")
db.execute("INSERT INTO person VALUES(2, 'Diana', 'Greene', 23);")
db.execute("INSERT INTO person VALUES(3, 'Sara', 'White', 27);")
db.execute("INSERT INTO person VALUES(4, 'William', 'Gibson', 23);")
# populate pet table
db.execute("INSERT INTO pet VALUES(1, 'Rusty', 'Dalmation', 4, 1);")
db.execute("INSERT INTO pet VALUES(2, 'Bella', 'Alaskan Malamute', 3, 0);")
db.execute("INSERT INTO pet VALUES(3, 'Max', 'Cocker Spaniel', 1, 0);")
db.execute("INSERT INTO pet VALUES(4, 'Rocky', 'Beagle', 7, 0);")
db.execute("INSERT INTO pet VALUES(5, 'Rufus', 'Cocker Spaniel', 1, 0);")
db.execute("INSERT INTO pet VALUES(6, 'Spot', 'Bloodhound', 2, 1);")
# populate person_pet table to connect pets to owners with JOIN statements
db.execute("INSERT INTO person_pet VALUES(1, 1);")
db.execute("INSERT INTO person_pet VALUES(1, 2);")
db.execute("INSERT INTO person_pet VALUES(2, 3);")
db.execute("INSERT INTO person_pet VALUES(2, 4);")
db.execute("INSERT INTO person_pet VALUES(3, 5);")
db.execute("INSERT INTO person_pet VALUES(4, 6);")
def main():
conn = sql.connect("pets.db")
db = conn.cursor()
createDB(db)
conn.commit()
conn.close()
if __name__ == "__main__":
main()
|
36e513fb316b70cefe529a73b5485076d719e412 | chandankuiry/image_processing | /threshold.py | 610 | 3.546875 | 4 | import cv2
import numpy as np
img=cv2.imread('image/bookpage.jpg')
grayscale=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
retval,threshold=cv2.threshold(grayscale,12,255,cv2.THRESH_BINARY)
#now we are using adaptive threshold
th=cv2.adaptiveThreshold(grayscale,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,115,1)
#otsu threshold
retval2,threshold2 = cv2.threshold(grayscaled,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow('original image',img)
cv2.imshow('threshold image ', threshold)
cv2.imshow("adaptive threshold",th)
cv2.imshow("otsu threshold",threshold2)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
67b24cffbb5161454b7e60dc0ae5ad0204c94da5 | shlampley/learning | /learn python/testing_args1.py | 621 | 3.8125 | 4 |
name = ""
age = ""
hair_color = ""
eye_color = ""
height = ""
weight = ""
def user_input(query):
while True:
fname = input("What is your {}".format(query))
return fname
def out_put(name, age, hair_color, eye_color, weight):
print("hello " + name + " you are " + age + " years old, you have " + hair_color + " hair, and " + eye_color + " eyes," + " you are " + weight + " lbs." )
name = user_input("Name: ")
age = user_input("Age: ")
hair_color = user_input("Hair color: ")
eye_color = user_input("Eye color: ")
weight = user_input("Weight: ")
out_put(name, age, hair_color, eye_color, weight)
|
d792bbac99a4649247ffb673779199ff06e3fddc | paweldrzal/python_codecademy | /flat_list.py | 239 | 4.0625 | 4 | #flattening a list
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for li in lists:
for m in li:
results.append(m)
return results
print flatten(n)
#output [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
b99fe1e4140914e0948bb29af3d557b87f7312d9 | shreyassk18/MyPyCharmProject | /Basic Programs/Check SubString.py | 318 | 4.3125 | 4 | #The find() method finds the first occurance of a specified value
#find() method returns -1 if string not found
str="Welcome to python programming"
sub_str="python"
check=str.find(sub_str)
if (check==-1):
print("Substring not present in a string")
else:
print("String present at position {}".format(check))
|
8a8b0c0a06c2c307defdbea728683c64b5802ca2 | KailashGanesh/Sudoku-solver | /sudoku-GUI.py | 7,164 | 3.6875 | 4 | import pygame, sys
from sudokuSolver import *
import copy
def isBoardSloved(board):
'''
parm: (sudoku board array)
return: True if no 0 present in board, False if 0 present
'''
for i in range(len(board)):
if 0 in board[i]:
return False
elif i == 8:
return True
def solveBoardViz(board):
'''
parm: sudoku board array
solves the board while also displaying it's working on pygame screen
'''
spot = find_empty_spot(board)
if spot == False:
return True
else:
row, col = spot
for i in range(1,10):
if is_valid_move(board,i,(row,col)):
board[row][col] = i
screen.fill(white)
drawGrid(9,screen,board)
pygame.display.update()
pygame.time.delay(20)
if solveBoardViz(board):
return True
board[row][col] = 0
screen.fill(white)
drawGrid(9,screen,board)
pygame.display.update()
pygame.time.delay(20)
return False
def drawGrid(grid,screen,board):
'''
parm: int - the grid size (for 9*9 give 9), pygame screen, the sudoku board
it draws lines every 3 blocks, grids, and the text of the sudoku board
'''
blockSize = int(size[0]/grid) # width/no. of grids
for x in range(grid):
if x % 3 == 0 and x != 0:
line_width = 5
else:
line_width = 1
pygame.draw.line(screen,black,(0, x*blockSize),(size[0], x*blockSize), line_width)
pygame.draw.line(screen,black,(x*blockSize,0),(x*blockSize, size[0]), line_width)
for y in range(grid):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize,blockSize)
pygame.draw.rect(screen,black,rect,1)
if board[y][x]:
text = myfont.render(str(board[y][x]),True,black)
else:
text = myfont.render(" ",True,black)
screen.blit(text, (x*blockSize+20,y*blockSize+9))
def mouseClick(pos,screen):
'''
parm: click position and screen
return: index of grid click, returns False when not click in grid
how: the grind is drawn using width/no. of cols (here: 540/9 which is 60)
so mouse click pos divided by 60 gives us the grid index which was clicked.
'''
x = int(pos[0]//(size[0]/9))
y = int(pos[1]//(size[0]/9))
if x < 9 and y < 9:
#print(pos,board[y][x])
return y,x
return False
size = width, heigh = 540,600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
boxSelected = False # is any box selected in the grid
val = 0
StatusValue = " " # status text
StatusColor = red
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
boardBackup = copy.deepcopy(board) # makes copy of board, insted of just referance
pygame.font.init()
pygame.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Sudoku")
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
StatusValue = " " # status text
pos = pygame.mouse.get_pos()
index = mouseClick(pos,screen)
if index != False:
y,x = index
boxSelected = True
if event.type == pygame.KEYDOWN:
StatusValue = " " # status text
if event.key == 120: # x key quits app
sys.exit()
if event.key == pygame.K_1:
val = 1
if event.key == pygame.K_2:
val = 2
if event.key == pygame.K_3:
val = 3
if event.key == pygame.K_4:
val = 4
if event.key == pygame.K_5:
val = 5
if event.key == pygame.K_6:
val = 6
if event.key == pygame.K_7:
val = 7
if event.key == pygame.K_8:
val = 8
if event.key == pygame.K_9:
val = 9
if event.key == pygame.K_SPACE: # space key solves full board
board = boardBackup # not at fault
board = copy.deepcopy(boardBackup)
solveBoardViz(board)
boxSelected = False
if isBoardSloved(board):
StatusValue = "Board Solved!"
StatusColor = (0,255,0)
pygame.display.update()
if event.key == pygame.K_LEFT or event.key == 104: # leftkey or h
if boxSelected:
if x == 0: # if can't go left anymore start at right side
x = 8
else:
x-= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_RIGHT or event.key == 108: # rightkey or l
if boxSelected:
if x == 8:
x = 0
else:
x+= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_UP or event.key == 107: # upkey or k
if boxSelected:
if y == 0:
y = 8
else:
y-= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_DOWN or event.key == 106: # downkey or j
if boxSelected:
if y == 8:
y = 0
else:
y += 1
else:
y = 0
x = 0
boxSelected = True
if event.key == 114: # r key to gen new board
boardBackup = make_board()
board = copy.deepcopy(boardBackup)
#boardBackup = board
StatusValue = "New Board!"
StatusColor = (0,0,255)
screen.fill(white)
drawGrid(9,screen,board)
if boxSelected:
#y,x = index
rect = pygame.Rect(x*60,y*60,60,60)
pygame.draw.rect(screen,red,rect,5)
if val:
if board[y][x] == 0:
if is_valid_move(board, val, (y,x)):
board[y][x] = val
if isBoardSloved(board):
StatusValue = "Board Solved!"
StatusColor = (0,255,0)
else:
StatusValue = "WRONG!"
StatusColor = red
val = 0
else:
val = 0
screen.blit(myfont.render(str(StatusValue),True,StatusColor),(0,540))
pygame.display.update()
|
1087b293ded7cebb9454f9491265fd6a63441314 | sabrown89/python-practice-problems | /arrays/left_rotation.py | 698 | 4.40625 | 4 | """
A left rotation operation on an array shifts each of the array's elements 1 unit tot he left. For example, if 2 left rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].
Given an array of n integers and a number, perform the number of rotations on the array. Return the updated array to be printed as a single line of space-separated integers.
"""
# better solution
def left_rotation(array, rotations):
return array[rotations:] + array[:rotations]
# first attempt
def left_rotation_first_attempt(array, rotations):
for rotation in range(rotations):
first_element = array.pop(0)
array.append(first_element)
return array
|
d895ece7e7bc69eeca13ca868073fe31d02f45b0 | maydaypie/recruiting-exercises | /inventory-allocator/src/inventory_allocator.py | 3,173 | 3.765625 | 4 | import unittest
class TestBestShipmentsSolution(unittest.TestCase):
def testCase1(self):
"""
Happy Case, exact inventory match!*
Input: { apple: 1 }, [{ name: owd, inventory: { apple: 1 } }]
Output: [{ owd: { apple: 1 } }]
"""
order = { 'apple': 1 }
inventory_distribution = [{ 'name': 'owd', 'inventory': { 'apple': 1 } }]
output = [{ 'owd': { 'apple': 1 } }]
self.assertEqual(output, BestShipmentsSolution().bestShipments(order, inventory_distribution))
def testCase2(self):
"""
Not enough inventory -> no allocations!
Input: { apple: 1 }, [{ name: owd, inventory: { apple: 0 } }]
Output: []
"""
order = { 'apple': 1 }
inventory_distribution = [{ 'name': 'owd', 'inventory': { 'apple': 0 } }]
output = []
self.assertEqual(output, BestShipmentsSolution().bestShipments(order, inventory_distribution))
def testCase3(self):
"""
Should split an item across warehouses if that is the only way to completely ship an item:
Input: { apple: 10 }, [{ name: owd, inventory: { apple: 5 } }, { name: dm, inventory: { apple: 5 }}]
Output: [{ dm: { apple: 5 }}, { owd: { apple: 5 } }]
"""
order = { 'apple': 10 }
inventory_distribution = [{ 'name': 'owd', 'inventory': { 'apple': 5 } }, { 'name': 'dm', 'inventory': { 'apple': 5 }}]
output = [{'dm': {'apple': 5}}, {'owd': {'apple': 5}}]
self.assertEqual(output, BestShipmentsSolution().bestShipments(order, inventory_distribution))
class BestShipmentsSolution(object):
def bestShipments(self, order, inventory_distribution):
"""
:param order: dict
:param inventory_distribution: List[dict]
:return: List[dict]
"""
output = []
for house_id in range(len(inventory_distribution)):
house_name = inventory_distribution[house_id]['name']
house_inventory = inventory_distribution[house_id]['inventory']
needs_from_the_house = {}
order_item_list = order.keys()
for item in order_item_list:
if item in house_inventory:
# Update order
request_item_amount = order[item]
house_item_amount = house_inventory[item]
if house_item_amount >= request_item_amount:
needs_from_the_house[item] = request_item_amount
del order[item]
else:
needs_from_the_house[item] = house_item_amount
order[item] -= house_item_amount
# Update output
if len(needs_from_the_house) > 0:
output.append({house_name: needs_from_the_house})
# This means the order is empty now, so we can return output
# In order to test our result, we sort the output here
if len(order) == 0:
return sorted(output)
# There is not enough inventory
return []
if __name__ == '__main__':
unittest.main(verbosity = 2)
|
8226335e2da6bf5854e36895e6aca6f51b869d27 | pouyapanahandeh/python3-ref | /pythonW3/elevenn.py | 795 | 3.890625 | 4 | # classes in python
class Employee:
x = 5
# empOne is object for class Eployee ==> in Java ==> NameOfClass object = NameOfClass();
empOne = Employee()
print(empOne.x)
# the __init__() function which is simillar to the Constructor in java
class Honda:
def __init__(self, name, age):
self.name = name
self.age = age
honda = Honda("pooya", 25)
print(honda.name)
print(honda.age)
# class with function
class Person: # instead self we can write what ever we want but it has to be first
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("pooya", 25)
p1.myfunc()
print(p1.age)
# thats how we can delete the element
#del p1.age
#print(p1.age)
# we can remove object like below
#del p1
|
a8d2dc248af5c5cbf3d612b1157735408e5dd57d | kamedono/raspi-camera-research | /opencv/python/sort.py | 120 | 3.5625 | 4 | a = [
[1,7,'z'],
[3,2,'x'],
[1,8,'r'],
[2,2,'s'],
[1,9,'b'],
[2,2,'a']
]
print sorted(a, key=lambda x:x[2])
|
a155badd160d3e6bf427128cf63e8588515495fd | ICS3U-Programming-LiamC/Unit3-06 | /num_guessing_better.py | 2,106 | 4.53125 | 5 | #!/usr/bin/env python3
# Created by: Liam Csiffary
# Created on: May 11, 2021
# This program makes a random number and then has the user guess it
# The user will get score based on their guess
# this is a module that I found to generate random numbers
# found on
# https://www.programiz.com/python-programming/examples/random-number
import random
# this is the fucntion that does everything
def random_number_fun():
# make the random number
random_num = random.randint(0, 9)
random_num = 7
# just as a test to make sure it was working
print(random_num)
# get the users guess
user_num = input("What do you think the number is: ")
# make sure the user inputed an integer
try:
int(user_num)
except ValueError:
print("'{}' is not a number".format(user_num))
random_number_fun()
else:
# FIRST CHECKING #############
user_num = int(user_num)
# check if the user got it right
if (user_num == random_num):
print("\nCongratulations you got it right!")
random_number_fun()
# check if the user got it wrong
if (user_num != random_num):
print("\nSorry you got it wrong")
# ask user if they think their number is bigger or
# smaller than their guess
user_bigger_smaller = input(
"Do you think the random number was bigger or smaller?(b/s): ")
# check if the user_num was bigger or smaller than the random_num
if (user_num < random_num):
bigger_smaller = "b"
else:
bigger_smaller = "s"
# if they guessed right congratulate them
if (bigger_smaller == user_bigger_smaller):
print("\nCongratulations you got it right!")
random_number_fun()
else:
print("\nSorry you got it wrong")
print("The number was {}".format(random_num))
random_number_fun()
# initial bootup of the program
if __name__ == "__main__":
random_number_fun()
|
344244958127bb958c9beba7325e2d58461952ab | Tudor67/Competitive-Programming | /ProjectEuler/#20_FactorialDigitSum_sol2.py | 164 | 3.59375 | 4 | import math
N = 100
N_FACTORIAL = math.factorial(N)
digits = [int(digit) for digit in str(N_FACTORIAL)]
digits_sum = sum(digits)
# 648
print(digits_sum) |
055db6590e709e50656570ab24895ab72bb6cc2b | sivilov-d/HackBulgaria | /week2/3-Simple-Algorithms/divisors.py | 136 | 3.953125 | 4 | n = input("Enter number: ")
n = int(n)
print("Divisors of %s are:" % n)
for i in range(1, n):
if n % i == 0:
print(i)
|
dd771f5544820211eb7da4825dc9b48584bff1bd | chensi06lj/Python_project | /lec01汇率/current_convert_v1.0.py | 370 | 3.671875 | 4 | """
作者:陈思
功能:汇率兑换
版本:1.0
日期:19/03/2019
"""
# 汇率
USD_VS_RMB = 6.77
# 输入人民币
rmb_str_value = input('请输入人民币(CNY)金额:')
# 将字符串转换为数字
rmb_value = eval(rmb_str_value)
# 求兑换美元
usd_value = rmb_value / USD_VS_RMB
print('美元(USD)金额是:', usd_value)
|
4df583f6bb75118fa17da28c1d65bd5a1c31e4e4 | xuyufan936831611/vo_imu | /kitti_eval/print_trajectory.py | 2,282 | 3.734375 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
def quat2mat(q):
''' Calculate rotation matrix corresponding to quaternion
https://afni.nimh.nih.gov/pub/dist/src/pkundu/meica.libs/nibabel/quaternions.py
Parameters
----------
q : 4 element array-like
Returns
-------
M : (3,3) array
Rotation matrix corresponding to input quaternion *q*
Notes
-----
Rotation matrix applies to column vectors, and is applied to the
left of coordinate vectors. The algorithm here allows non-unit
quaternions.
References
----------
Algorithm from
http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
Examples
--------
>>> import numpy as np
>>> M = quat2mat([1, 0, 0, 0]) # Identity quaternion
>>> np.allclose(M, np.eye(3))
True
>>> M = quat2mat([0, 1, 0, 0]) # 180 degree rotn around axis 0
>>> np.allclose(M, np.diag([1, -1, -1]))
True
'''
x, y, z, w = q
Nq = w*w + x*x + y*y + z*z
if Nq < 1e-8:
return np.eye(3)
s = 2.0/(Nq**2)
X = x*s
Y = y*s
Z = z*s
wX = w*X; wY = w*Y; wZ = w*Z
xX = x*X; xY = x*Y; xZ = x*Z
yY = y*Y; yZ = y*Z; zZ = z*Z
return np.array(
[[1.0 - (yY + zZ), xY - wZ, xZ + wY],
[xY + wZ, 1.0 - (xX + zZ), yZ + wX],
[xZ - wY, yZ + wX, 1.0 - (xX + yY)]])
def main():
tra_dir='their_10.txt'
file = open(tra_dir)
contents=file.readlines()
N=len(contents)
full_t = np.zeros((4, N), dtype=np.float32)
pose=[[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]]
for i in range(N):
line=(contents[i]).split()
T = (np.reshape(np.array(line[1:4]).astype(np.float),[3,1]))
q = np.array(line[4:8]).astype(np.float)
R = quat2mat(q)
Tmat = np.concatenate((R, T), axis=1)
hfiller = np.array([0, 0, 0, 1]).reshape((1, 4))
Tmat = np.concatenate((Tmat, hfiller), axis=0)
pose = np.dot(pose,Tmat)
full_t[ :,i] = pose[:,3]
print(pose[:,3])
plt.plot(full_t[0,:], full_t[2,:])
plt.show()
main()
|
d8503d286783dd3ed5e4ed3f03060f9c5bc1e35f | MCornejoDev/Python | /Variables, ES y Operaciones aritméticas/Ejercicio6.py | 401 | 3.78125 | 4 | #Escriba un programa que pida una cantidad de segundos y que escriba cuántos minutos y segundos son.
#1234 segundos son 20 minutos y 34 segundos
#120 segundos son 2 min y 0 segundos
print("CONVERTIDOR DE SEGUNDOS A MINUTOS")
cSegundos = int(input("Escriba una cantidad de segundos: "))
minutos = cSegundos // 60
resto = cSegundos % 60
print(f"{cSegundos} segundos son {minutos} min y {resto} seg") |
8fdb6f8caf9fef4fd1353ce2e4b6ae2a47346e10 | daniel-mcbride/CS1_Files | /Homework/McbrideD_CSCI1470_HW10/McbrideD_CSCI1470_HW10.py | 1,946 | 4.28125 | 4 | #*************** McbrideD_CSCI1470_HW10.py ***************
#
# Name: Daniel McBride
#
# Course: CSCI 1470
#
# Assignment: Homework #10
#
# Algorithm:
# Start
#
#**********************************************************
def checkLength(password):
if len(password) >= 8:
return True
else:
return False
def checkUppercase(password):
for character in password:
if character.isupper():
return True
return False
def checkLowercase(password):
for character in password:
if character.islower():
return True
return False
def checkDigit(password):
for character in password:
if character.isdigit():
return True
return False
print("Let's get your password set up!\n")
password = input("New Password: ")
invalidPassword = True
while invalidPassword:
validLength = checkLength(password)
validUpper = checkUppercase(password)
validLower = checkLowercase(password)
validDigit = checkDigit(password)
if validLength and validUpper and validLower and validDigit:
invalidPassword = False
else:
print("Sorry, your password was invalid")
if not validLength:
print("The password did not meet the 8 character minimum length")
if not validUpper:
print("The password did not contain an uppercase letter")
if not validLower:
print("The password did not contain a lowercase letter")
if not validDigit:
print("The password did not contain a numerical character")
print()
password = input("Please enter a new password: ")
verifyPassword = False
while not verifyPassword:
print()
passwordCheck = input("Please reenter your password: ")
if passwordCheck == password:
verifyPassword = True
else:
print("Verification failed")
print("Verification Succeded! Your new password is now in place!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.