blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
7040b3a51e04a8a5956ef2b56fe8f3ef08705323 | IndigoShock/data_structures_and_algorithms | /data_structures/graphs/graph.py | 971 | 3.96875 | 4 | class Vertice:
def __init__(self, value):
self.value = value
self.vertices = []
def __repr__(self):
pass
def __str__(self):
pass
class Graph:
def __init__(self):
self.graph = {}
def __repr__(self):
pass
def __str__(self):
pass
def __len__(self):
pass
def add_vert(self, val):
"""
- use val to create a new Vertice.
- Add verticeto self.graph
- check to see if the vert already exists:
- if so, raise exception
- create helper method
"""
def has_vert(self, val):
"""
checks for a key in the graph
"""
def add_edge(self, v1, v2, weight):
"""
- add a relationship and weight between two verts
- don't forget to validate
"""
def get_neighbors(self, val):
"""
given a val (key), return all adjacent verts
"""
|
693d6e422863cd963e49b729d9e1201d0b75f40d | IndigoShock/data_structures_and_algorithms | /challenges/ll_insertions/linked_list.py | 1,596 | 3.828125 | 4 | from typing import Any
from .node import Node
class LinkedList(object):
def __init__(self, iterable=None):
self.head = None
self._length = 0
if iterable is not None:
try:
for value in iterable:
self.insert(value)
except TypeError:
self.insert(iterable)
def __str__(self):
return f'Head: {self.head} | Length: {self._length}'
def __repr__(self):
return f'<Linked List | Head: {self.head} | Length: {self._length}>'
def __len__(self):
return self._length
def __iter__(self):
if self.head:
self.current = self.head
return self
def __next__(self):
pass
def insert(self, val: Any) -> Any:
self.head = Node(val, self.head)
self._length += 1
return self.head.val
def includes(self, val: Any) -> bool:
current = self.head
while current is not None:
if current.val == val:
return True
current = current._next
return False
def append(self, val):
""" Docstring
"""
current = self.head
while current._next is not None:
current = current._next
# current node is last node in list
new_node = Node(val, _next=None)
current._next = new_node
def insert_before(self, val, target):
""" Docstring
"""
# current = self.head
pass
def insert_after(self, val, target):
""" Docstring
"""
pass
|
642f978df2fdfbd359ddd36c494191dc6527b372 | AndrewSpano/AI-2-Projects | /Project2/Notebooks/network2_utils.py | 7,244 | 3.609375 | 4 | import torch
import nltk
import numpy as np
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
nltk.download('stopwords')
def compute_lengths(X):
""" function used to compute a dictionary that maps:
size of sentence -> number of sentences with this size in X """
# the dictionary to be returned
lengths = {}
# for each sentence in X
for sentence in X:
# get its length
l = len(sentence.split())
# if this is the first time we see it, set the value to 1
if l not in lengths:
lengths[l] = 1
# else increment it by one
else:
lengths[l] += 1
# return the result
return lengths
def pad_up_to_maxlen(split_sentence, maxlen, pad_token="<PAD>"):
""" function used to pad a sentence up to maxlen """
# get its current length
current_len = len(split_sentence)
# calculate how many pad token should be added and add them
remaining_pads = maxlen - current_len
split_sentence.extend([pad_token] * remaining_pads)
# return new sentence
return " ".join(split_sentence)
def truncate_down_to_maxlen(split_sentence, maxlen):
""" function used to truncate a sentence down to maxlen words """
# truncate it
truncated_split_sentence = split_sentence[:maxlen]
# return the rejoined sentence
return " ".join(truncated_split_sentence)
def transform_sentence(sentence, maxlen, pad_token="<PAD>"):
""" function used to invoke one of the above functions """
# split the sentence in order to get its length
split_sentence = sentence.split()
# the sentence to be returned
target_sentence = ""
# check whether the sentence needs to be transformed
if len(split_sentence) < maxlen:
target_sentence = pad_up_to_maxlen(split_sentence, maxlen, pad_token)
elif len(split_sentence) > maxlen:
target_sentence = truncate_down_to_maxlen(split_sentence, maxlen)
else:
target_sentence = sentence
# return the sentence
return target_sentence
def load_word_embeddings(embedding_path, embedding_dimension, pad_token, unknown_token):
""" function used to load word embeddings """
# list of words
words = [pad_token, unknown_token]
# their indices
index_of_word = 2
# dictionary that maps: word -> index
word_to_index_glove = {pad_token: 0, unknown_token: 1}
# vectors with embeddings
pad_vector = np.random.normal(scale=0.6, size=(embedding_dimension, ))
unknown_vector = np.random.normal(scale=0.6, size=(embedding_dimension, ))
vectors_glove = [pad_vector, unknown_vector]
# used to remove stopwords and stem the given words so that they match our vocabulary
stop_words = stopwords.words("english")
stemmer = PorterStemmer()
# finally open the embeddings file
with open(embedding_path, "rb") as emb_file:
# for each line the the embeddings file
for l in emb_file:
# decode the line and split it in space
line = l.decode().split()
# get the word and append it to the word list
word = line[0]
# if some special character is read, then probably the word gets skipped and we
# end up reading the first number of the vector, skip this case
if "0" in word or "1" in word or "2" in word or "3" in word or "4" in word or \
"5" in word or "6" in word or "7" in word or "8" in word or "9" in word:
continue
# check if the word is a stopword. If it is, go to the next word
if word in stop_words:
continue
# stem the word
word = stemmer.stem(word)
# check if this stemmed word has already been added, and if yes proceed
if word in word_to_index_glove:
continue
# now append the word to the words list
words.append(word)
# also update the index dict
word_to_index_glove[word] = index_of_word
index_of_word += 1
# initialize a vector with the values of the vector in this line
vector = np.array(line[1:]).astype(np.float)
vectors_glove.append(vector)
# return the result
return words, word_to_index_glove, vectors_glove
def map_sentences_to_indices_of_vectors(sentences, word_to_index_glove, unknown_token):
""" map senteces to integers that represent the index of each word in the glove vocabulary """
# the list to be returned
mapped_sentences = []
# get the index of the unknown token
unknown_token_index = word_to_index_glove[unknown_token]
# iterate for each sentence
for sentence in sentences:
# get the split sentence
split_sentence = sentence.split()
# map it to the corresponding indices
mapped_sentence = [word_to_index_glove.get(word, unknown_token_index) for word in split_sentence]
# append it to the list
mapped_sentences.append(mapped_sentence)
# return the list
return mapped_sentences
def convert_to_torch_tensors(X_train, y_train, X_test, y_test):
""" Function to quickly convert datasets to pytorch tensors """
# convert training data
_X_train = torch.LongTensor(X_train)
_y_train = torch.FloatTensor(y_train)
# convert test data
_X_test = torch.LongTensor(X_test)
_y_test = torch.FloatTensor(y_test)
# return the tensors
return _X_train, _y_train, _X_test, _y_test
def embed_and_flatten(X_train, X_test, maxlen, embedding_dimension, index_to_vector):
""" Function to embed the training/test sets and flatten them """
# number of training examples
m_train = X_train.shape[0]
# create an empty array
_X_train = torch.zeros((m_train, maxlen, embedding_dimension))
# iterate to gradually start filling this array
for example in range(m_train):
# get all indices to get the embedding of each one
for index in range(maxlen):
# get the value
actual_index = X_train[example][index]
# set the embedding
_X_train[example, index, :] = index_to_vector[actual_index]
# flatten it
_X_train = torch.flatten(_X_train, start_dim=1)
# check if only one dataset is needed
if X_test is None:
return _X_train
# number of testing examples
m_test = X_test.shape[0]
# create an empty array
_X_test = torch.zeros((m_test, maxlen, embedding_dimension))
# iterate to gradually start filling this array
for example in range(m_test):
# get all indices to get the embedding of each one
for index in range(maxlen):
# get the value
actual_index = X_test[example][index]
# set the embedding
_X_test[example, index, :] = index_to_vector[actual_index]
# flatten it
_X_test = torch.flatten(_X_test, start_dim=1)
# return the 2 target vectors
return _X_train, _X_test
|
5c1464de6abbc235483d3e3f4c35d91fa4009fb8 | gulaki/code-timer | /codetimer/codetimer.py | 8,065 | 4.25 | 4 | from time import clock, time
import sys
if sys.platform == 'win32':
timer_func = clock
else:
timer_func = time
UNITS = {'s': 1, 'ms': 1000, 'm': 1/60, 'h': 1/3600}
MUNITS = {'b': 1, 'kb': 1024, 'mb': 1024**2}
class Timer(object):
"""
Timer() is a class to measure time elapsed and count number of passes through code segments using time.clock()
Useful for benchmarking, testing different implementaions for performance.
Run demo_timer.py to see usage and performance characteristics for various implementations of calculating the factorial of a number.
>>> t = Timer() # starts the timer object
...
>>> t.stop() # stops the timer object
>>> t.total # then contains total time between creation and stop() in seconds.
>>> repr(t) # returns time with units as string, so print(t) can be used.
A timer can be started and instructed to wait till start() method is called.
>>> t = Timer(wait=True) # creates timer but doesn't start measuring. wait is False by default. See previous case.
>>> t.start() # begins measuring.
...
>>> t.stop() # stops measuring.
...
>>> t.start() # starts measuring again
...
>>> t.stop() # stops measuring
>>> t.total # now has total time recorded between starts and stops in seconds
>>> t.count # contains number of times the timer was triggered.
This can be used in a loop to measure time per loop or count number of times a function was called.
>>> t = Timer(unit='s') # to define what units to print the time in.
Options are 's' (second), 'ms' (millisecond), 'm' (minute) and 'h' (hour).
By default the unit is 'ms' but in a project the default units can be set before all usages by
>>> Timer.default_unit = 's' # or any unit
"""
default_unit = 'ms'
def __init__(self, wait=False, unit=None):
self._start = 0
self.is_running = False
self.unit = unit or self.default_unit
self.count = 0
self.total = 0
try:
if not wait:
self.start()
except KeyError:
self.start()
def start(self):
if not self.is_running:
self.count += 1
self.is_running = True
self._start = timer_func()
else:
raise RuntimeWarning('Timer already running.')
def stop(self):
if self.is_running:
self.total += timer_func() - self._start
self.is_running = False
else:
raise RuntimeWarning('Check code. Timer is already stopped.')
def reset(self):
self.is_running = False
self.count = 0
self.total = 0
self._start = 0
@staticmethod
def function_timer(func):
"""
Use FunctionTimer as a decorator to measure accumulated time of a function's execution. Invoke the .timer member to get the total time and count
eg:
@Timer.function_timer
def afunction(args):
# do some thing
for i in range(1000):
afunction(args)
t = afunction.timer
print(t.total, t.count)
"""
timer = Timer(wait=True)
def wrapper(*args, **kwargs):
try:
timer.start()
return func(*args, **kwargs)
finally:
timer.stop()
wrapper.timer = timer
return wrapper
def __enter__(self):
self._timer = Timer(wait=True)
self._timer.start()
return self._timer
def __exit__(self, *args):
self._timer.stop()
del self._timer
def __repr__(self):
return str(round(self.total*UNITS[self.unit], 4)) + ' ' + self.unit
class TimerStats(Timer):
"""
TimerStats() extends Timer() by enabling simple statistical analysis on collected time data.
>>> t = TimerStats() # initializes the timer and always waits by default. Units can be specified and default can be set like Timer().
...
>>> for i in range(10000):
... t.start()
... ...
... t.stop()
>>> t.min # minimum lap time (s)
>>> t.max # maximum lap time (s)
>>> t.total # total time (s)
>>> t.count # no. of laps
>>> t.mean # average lap time (s)
>>> t.std # standard deviation (s)
>>> repr(t) # returns total time with units as string
>>> str(t) # 'total=9604.3762 ms, min=90.9867 ms, max=100.9108 ms, mean=96.0438 ms, std=10.0969 ms.'
A call to TimerStats.stop() also returns the lap time. So if required it can be saved as lap data if required.
"""
default_unit = 'ms'
def __init__(self, unit=None):
self.total2 = 0
self.min = 0
self.max = 0
self.lap = 0
Timer.__init__(self, wait=True, unit=unit or self.default_unit)
def stop(self):
if self.is_running:
self.lap = timer_func() - self._start
self.total += self.lap
self.total2 += self.lap ** 2
self.is_running = False
if self.count == 1:
self.min = self.max = self.lap
else:
if self.lap < self.min:
self.min = self.lap
if self.lap > self.max:
self.max = self.lap
else:
raise RuntimeError('Check code. Timer is already stopped.')
@property
def mean(self):
return self.total / self.count
@property
def std(self):
try:
return (self.total2 / (self.count-1) - self.mean ** 2) ** 0.5
except ZeroDivisionError:
return (self.total2 / self.count - self.mean ** 2) ** 0.5
def reset(self):
super().reset()
self.total2 = 0
self.min = 0
self.max = 0
self.lap = 0
@staticmethod
def function_timer(func):
"""
Timerstats.function_timer is similar to Timer.function_timer decorator but enables
statistical analysis on the timing data using TimerStats()
eg:
@Timerstats.function_timer
def afunction(args):
# do something
return something
for i in range(1000):
retval = afunction(args)
lap = afunction.lap # Each lap time can be caught for further analysis
t = afunction.final_stats() # calculates mean and std and can be accessed from the members.
print(t) # Formatted output giving detailed information
"""
timer = TimerStats()
def wrapper(*args, **kwargs):
try:
timer.start()
return func(*args, **kwargs)
finally:
timer.stop()
wrapper.timer = timer
return wrapper
def __str__(self):
template = 'iters={cnt}: total={tot:.4f} {unit}, minm={min:.4f} ' \
'{unit}, maxm={max:.4f} {unit}, mean={mean:.4f} {unit}, ' \
'std={std:.4f} {unit}.'
fact = UNITS[self.unit]
return template.format(
cnt=self.count,
unit=self.unit,
tot=self.total*fact,
min=self.min*fact,
max=self.max*fact,
mean=self.mean*fact,
std=self.std*fact
)
class MemoryTracker(object):
default_unit = 'kb'
def __init__(self, *args):
print(globals())
self.unit = self.default_unit
self.sizes, self.totals, self.times = [], [], []
self.getsize(*args)
def getsize(self, *args):
sizes = [sys.getsizeof(arg)/MUNITS[self.unit] for arg in args]
self.sizes.append(sizes)
self.totals.append(sum(sizes))
self.times.append(timer_func())
def normalize_time(self):
self.times = [times - self.times[0] for times in self.times]
|
e839a7462e1befd6293fbba078feff0f755c51d4 | Swapnil2095/Python | /8.Libraries and Functions/Unicodedata – Unicode Database/unicodedata.category(chr).py | 257 | 3.953125 | 4 | import unicodedata
print (unicodedata.category(u'A'))
print (unicodedata.category(u'b'))
'''
This function returns the general category assigned to the given character as string.
For example, it returns ‘L’ for letter and ‘u’ for uppercase.
'''
|
35c340635b063ecebc478a1ab8d7f527d6fe2f3f | Swapnil2095/Python | /8.Libraries and Functions/copy in Python (Deep Copy and Shallow Copy)/Shallow copy/shallow copy.py | 533 | 4.5625 | 5 | # Python code to demonstrate copy operations
# importing "copy" for copy operations
import copy
# initializing list 1
li1 = [1, 2, [3, 5], 4]
# using copy to shallow copy
li2 = copy.copy(li1)
# original elements of list
print("The original elements before shallow copying")
for i in range(0, len(li1)):
print(li1[i], end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
# checking if change is reflected
print("The original elements after shallow copying")
for i in range(0, len(li1)):
print(li1[i], end=" ")
|
e0a7301220375162a880cad99931126313fe2cd2 | Swapnil2095/Python | /5. Modules/Complex Numbers/asinh.py | 719 | 3.765625 | 4 | # Python code to demonstrate the working of
# asinh(), acosh(), atanh()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x = 1.0
y = 1.0
# converting x and y into complex number z
z = complex(x, y)
# printing inverse hyperbolic sine of the complex number
print("The inverse hyperbolic sine value of complex number is : ", end="")
print(cmath.asinh(z))
# printing inverse hyperbolic cosine of the complex number
print("The inverse hyperbolic cosine value of complex number is : ", end="")
print(cmath.acosh(z))
# printing inverse hyperbolic tangent of the complex number
print("The inverse hyperbolic tangent value of complex number is : ", end="")
print(cmath.atanh(z))
|
e4fddb93c4fb6fe92012f32f1738f2fa1ede48b7 | Swapnil2095/Python | /5. Modules/Mathematical Functions/fact.py | 346 | 4.09375 | 4 | # Python code to demonstrate the working of
# fabs() and factorial()
# importing "math" for mathematical operations
import math
a = -10
b = 5
# returning the absolute value.
print("The absolute value of -10 is : ", end="")
print(math.fabs(a))
# returning the factorial of 5
print("The factorial of 5 is : ", end="")
print(math.factorial(b))
|
b91b8609d687dd362ac271c349fdc3c81ebfe0f3 | Swapnil2095/Python | /8.Libraries and Functions/Regular Expression/findall(d).py | 621 | 4.3125 | 4 | import re
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \d+ will match a group on [0-9], group of one or greater size
p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
'''
\d Matches any decimal digit, this is equivalent
to the set class [0-9].
\D Matches any non-digit character.
\s Matches any whitespace character.
\S Matches any non-whitespace character
\w Matches any alphanumeric character, this is
equivalent to the class [a-zA-Z0-9_].
\W Matches any non-alphanumeric character.
'''
|
077d5e9531b2db59b3fc73655f385935a5a4712e | Swapnil2095/Python | /3.Control Flow/range()/getsize.py | 250 | 3.546875 | 4 | # Python code to demonstrate range()
# on basis of memory
import sys
# initializing a with range()
a = range(1,10000)
# testing the size of a
# range() takes more memory
print ("The size allotted using range() is : ")
print (sys.getsizeof(a))
|
2be154a4143a049477f827c9923ba19198f4a4e3 | Swapnil2095/Python | /8.Libraries and Functions/copyreg — Register pickle support functions/Example.py | 1,312 | 4.46875 | 4 | # Python 3 program to illustrate
# use of copyreg module
import copyreg
import copy
import pickle
class C(object):
def __init__(self, a):
self.a = a
def pickle_c(c):
print("pickling a C instance...")
return C, (c.a, )
copyreg.pickle(C, pickle_c)
c = C(1)
d = copy.copy(c)
print(d)
p = pickle.dumps(c)
print(p)
'''
The copyreg module defines functions which are used by pickling specific objects
while pickling or copying. This module provides configuration information
about object constructors(may be factory functions or class instances)
which are not classes.
copyreg.constructor(object)
This function is used for declaring object as a valid constructor.
An object is not considered as a valid constructor if it is not callable.
This function raises TypeError if the object is not callable.
copyreg.pickle(type, function, constructor=None)
This is used to declare function as a “reduction” function for objects of type type.
function should return either a string or a tuple containing two or three elements.
The constructor parameter is optional. It is a callable object which can be used
to reconstruct the object when called with the tuple of arguments returned by
function at pickling time. TypeError is raised if object is a class or
constructor is not callable.
''' |
6c804224dd0a9bc2544563b958137c1002ac77fc | Swapnil2095/Python | /8.Libraries and Functions/Regular Expression/findall(all).py | 117 | 3.71875 | 4 | import re
# '*' replaces the no. of occurrence of a character.
p = re.compile('ab*')
print(p.findall("ababbaabbb"))
|
3dc8226bfc786cf6bbea43a20a0cf5dbbdeeb72e | Swapnil2095/Python | /5. Modules/Mathematical Functions/sqrt.py | 336 | 4.5625 | 5 | # Python code to demonstrate the working of
# pow() and sqrt()
# importing "math" for mathematical operations
import math
# returning the value of 3**2
print("The value of 3 to the power 2 is : ", end="")
print(math.pow(3, 2))
# returning the square root of 25
print("The value of square root of 25 : ", end="")
print(math.sqrt(25))
|
2d1587bce7ce01c8316ade04b2cf17ee5d300071 | Swapnil2095/Python | /5. Modules/Time Functions/sleep.py | 352 | 3.703125 | 4 | # Python code to demonstrate the working of
# sleep()
# importing "time" module for time operations
import time
# using ctime() to show present time
print ("Start Execution : ",end="")
print (time.ctime())
# using sleep() to hault execution
time.sleep(4)
# using ctime() to show present time
print ("Stop Execution : ",end="")
print (time.ctime())
|
762ff5c6fe386f1bad2c2f304eb6f3460a622eab | Swapnil2095/Python | /2.Operator/Division Operators/Division.py | 434 | 3.984375 | 4 | # A Python 2.7 program to demonstrate use of
# "/" for integers
print (5/2)
print (-5/2)
print("\n------------------------------")
# A Python 2.7 program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
print("\n------------------------------")
# A Python 2.7 program to demonstrate use of
# "//" for both integers and floating points
print (5//2)
print (-5//2)
print (5.0//2)
print (-5.0//2)
|
1ca59efae74f5829e15ced1f428720e696867d9a | Swapnil2095/Python | /2.Operator/Inplace vs Standard/mutable_target.py | 849 | 4.28125 | 4 | # Python code to demonstrate difference between
# Inplace and Normal operators in mutable Targets
# importing operator to handle operator operations
import operator
# Initializing list
a = [1, 2, 4, 5]
# using add() to add the arguments passed
z = operator.add(a,[1, 2, 3])
# printing the modified value
print ("Value after adding using normal operator : ",end="")
print (z)
# printing value of first argument
# value is unchanged
print ("Value of first argument using normal operator : ",end="")
print (a)
# using iadd() to add the arguments passed
# performs a+=[1, 2, 3]
p = operator.iadd(a,[1, 2, 3])
# printing the modified value
print ("Value after adding using Inplace operator : ",end="")
print (p)
# printing value of first argument
# value is changed
print ("Value of first argument using Inplace operator : ",end="")
print (a)
|
7ffe6b1ac7437b0477a969498d66163e4c4e0584 | Swapnil2095/Python | /5. Modules/Time Functions/ctime.py | 450 | 4.15625 | 4 | # Python code to demonstrate the working of
# asctime() and ctime()
# importing "time" module for time operations
import time
# initializing time using gmtime()
ti = time.gmtime()
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print (time.asctime(ti))
# using ctime() to diplay time string using seconds
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())
|
fc98a4b1e6c25c0063a0c5fcacecce1cd1b37f97 | Swapnil2095/Python | /5. Modules/Mathematical Functions/gcd.py | 381 | 3.953125 | 4 | # Python code to demonstrate the working of
# copysign() and gcd()
# importing "math" for mathematical operations
import math
a = -10
b = 5.5
c = 15
d = 5
# returning the copysigned value.
print("The copysigned value of -10 and 5.5 is : ", end="")
print(math.copysign(5.5, -10))
# returning the gcd of 15 and 5
print("The gcd of 5 and 15 is : ", end="")
print(math.gcd(5, 15))
|
40c510c23348cf7cbecc3adad8e318d7aef1df98 | Swapnil2095/Python | /8.Libraries and Functions/NumPy/linalg.solve.py | 263 | 3.515625 | 4 | import numpy as np
'''
Let us assume that we want to solve this linear equation set:
x + 2*y = 8
3*x + 4*y = 18
'''
# coefficients
a = np.array([[1, 2], [3, 4]])
# constants
b = np.array([8, 18])
print("Solution of linear equations:", np.linalg.solve(a, b))
|
9091de76643f812c44e1760f7d73e2a28c19bde6 | Swapnil2095/Python | /8.Libraries and Functions/enum/prop2.py | 724 | 4.59375 | 5 | '''
4. Enumerations are iterable. They can be iterated using loops
5. Enumerations support hashing. Enums can be used in dictionaries or sets.
'''
# Python code to demonstrate enumerations
# iterations and hashing
# importing enum for enumerations
import enum
# creating enumerations using class
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
# printing all enum members using loop
print("All the enum values are : ")
for Anim in (Animal):
print(Anim)
# Hashing enum member as dictionary
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'
# checking if enum values are hashed successfully
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
print("Enum is hashed")
else:
print("Enum is not hashed")
|
f0a0f758c7e274508da794d35c71c52f7da7e0f9 | Swapnil2095/Python | /5. Modules/Calendar Functions/firstweekday.py | 486 | 4.25 | 4 | # Python code to demonstrate the working of
# prmonth() and setfirstweekday()
# importing calendar module for calendar operations
import calendar
# using prmonth() to print calendar of 1997
print("The 4th month of 1997 is : ")
calendar.prmonth(1997, 4, 2, 1)
# using setfirstweekday() to set first week day number
calendar.setfirstweekday(4)
print("\r")
# using firstweekday() to check the changed day
print("The new week day number is : ", end="")
print(calendar.firstweekday())
|
9df048f40e3298108b96ab25b71761875c1a05b3 | Swapnil2095/Python | /4.Function/Function Decorators/func_as_para.py | 488 | 4.03125 | 4 | # A Python program to demonstrate that a function
# can be defined inside another function and a
# function can be passed as parameter.
# Adds a welcome message to the string
def messageWithWelcome(str):
# Nested function
def addWelcome():
return "Welcome to "
# Return concatenation of addWelcome()
# and str.
return addWelcome() + str
# To get site name to which welcome is added
def site(site_name):
return site_name
print (messageWithWelcome(site("GeeksforGeeks")))
|
f60dcd5c7b7cc667b9e0155b722fd637570663ef | Swapnil2095/Python | /8.Libraries and Functions/Decimal Functions/logical.py | 1,341 | 4.65625 | 5 | # Python code to demonstrate the working of
# logical_and(), logical_or(), logical_xor()
# and logical_invert()
# importing "decimal" module to use decimal functions
import decimal
# Initializing decimal number
a = decimal.Decimal(1000)
# Initializing decimal number
b = decimal.Decimal(1110)
# printing logical_and of two numbers
print ("The logical_and() of two numbers is : ",end="")
print (a.logical_and(b))
# printing logical_or of two numbers
print ("The logical_or() of two numbers is : ",end="")
print (a.logical_or(b))
# printing exclusive or of two numbers
print ("The exclusive or of two numbers is : ",end="")
print (a.logical_xor(b))
# printing logical inversion of number
print ("The logical inversion of number is : ",end="")
print (a.logical_invert())
'''
1. logical_and() :- This function computes digit-wise logical “and” operation of the number. Digits can only have the values 0 or 1.
2. logical_or() :- This function computes digit-wise logical “or” operation of the number. Digits can only have the values 0 or 1.
3. logical_xor() :- This function computes digit-wise logical “xor” operation of the number. Digits can only have the values 0 or 1.
4. logical_invert() :- This function computes digit-wise logical “invert” operation of the number. Digits can only have the values 0 or 1.
''' |
489ed9868abd2b5275f7f1c9fac5a817e231c598 | Swapnil2095/Python | /5. Modules/Fraction module/test3.py | 260 | 3.765625 | 4 | from fractions import Fraction
print (Fraction('8/25'))
# returns Fraction(8, 25)
print (Fraction('1.13'))
# returns Fraction(113, 100)
print (Fraction('3/7'))
# returns Fraction(3, 7)
print (Fraction('1.414213 \t\n'))
# returns Fraction(1414213, 1000000)
|
95a5a87944d4bff8b2e1b03a939d0277cd150fe1 | Swapnil2095/Python | /3.Control Flow/Using Iterations/unzip.py | 248 | 4.1875 | 4 | # Python program to demonstrate unzip (reverse
# of zip)using * with zip function
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
('Audi', 'Car Repair'),
('McLaren', 'Dolby sound kit')
])
# Printing unzipped lists
print(l1)
print(l2)
|
06fda82a4d6e2463dfedcb1343b883db03976e0d | Swapnil2095/Python | /5. Modules/Inplace Operators/imod.py | 478 | 3.859375 | 4 | # Python code to demonstrate the working of
# itruediv() and imod()
# importing operator to handle operator operations
import operator
# using itruediv() to divide and assign value
x = operator.itruediv(10, 5)
# printing the modified value
print("The value after dividing and assigning : ", end="")
print(x)
# using imod() to modulus and assign value
x = operator.imod(10, 6)
# printing the modified value
print("The value after modulus and assigning : ", end="")
print(x)
|
9aebe2939010ff4b2eca5edf8f25dfc5362828c6 | Swapnil2095/Python | /5. Modules/Complex Numbers/sin.py | 593 | 4.21875 | 4 | # Python code to demonstrate the working of
# sin(), cos(), tan()
# importing "cmath" for complex number operations
import cmath
# Initializing real numbers
x = 1.0
y = 1.0
# converting x and y into complex number z
z = complex(x, y)
# printing sine of the complex number
print("The sine value of complex number is : ", end="")
print(cmath.sin(z))
# printing cosine of the complex number
print("The cosine value of complex number is : ", end="")
print(cmath.cos(z))
# printing tangent of the complex number
print("The tangent value of complex number is : ", end="")
print(cmath.tan(z))
|
58bd237b612559cd7082821a740ce52963379dd9 | Swapnil2095/Python | /8.Libraries and Functions/pickle — Python object serialization/Functions/pickle.loads.py | 586 | 3.9375 | 4 | # Python program to illustrate
# pickle.loads()
import pickle
import pprint
data1 = [{'a': 'A', 'b': 2, 'c': 3.0}]
print ('BEFORE:',pprint.pprint(data1))
data1_string = pickle.dumps(data1)
data2 = pickle.loads(data1_string)
print ('AFTER:',pprint.pprint(data2))
print ('SAME?:', (data1 is data2))
print ('EQUAL?:', (data1 == data2))
'''
pickle.loads(bytes_object, *, fix_imports = True, encoding = “ASCII”, errors = “strict”)
This function is used to read a pickled object representation from a bytes object
and return the reconstituted object hierarchy specified.
'''
|
519813ef69e8cf4ed6340257705bd963181ed61a | yusraSenem/programlama | /ODEV1_05mart2018.py | 2,551 | 3.921875 | 4 |
##1) KAR HESAPLAMA
def start():
print("İşletme Takip Programı")
print("Kar hesabı için 1 \n OEE için 2 \n Adam Başı Ciro için 3 ü tuşlayınız")
state = int(input("İşlem Numarası Giriniz"))
if(state == 1 ):
kar()
elif(state==2):
oee()
elif(state==3):
abc()
def kar():
finGelir=int(input("finansman geliri:"))
pzrGelir=int(input("pazar geliri:"))
kiraGelir=int(input("kira geliri:"))
toplamGelir=finGelir+pzrGelir+kiraGelir
print("toplam gelir:",toplamGelir)
ucret=int(input("ücret:"))
finGider=int(input("finansman gideri:"))
pzrGider=int(input("pazar gideri:"))
kiraGider=int(input("kira gideri:"))
mhsbGider=int(input("muhasebe gideri:"))
toplamGider=ucret+finGider+pzrGider+kiraGider+mhsbGider
print("toplam gider:",toplamGider)
karZarar=toplamGelir-toplamGider
if karZarar>1000:
print("karlı bir dönem:",karZarar)
elif karZarar==0:
print("başabaş noktasındasınız:",karZarar)
elif karZarar>0:
print("karınız maliyetleri karşılamıyor:")
else:
print("bu dönem zarardasınız:",karZarar)
return karZarar
##2) İŞLETMENİN EKİPMAN KULLANILABİLİRLİK ORANI
def oee():
püs=int(input("planlanmış üretim süresi:"))
pzd=int(input("plansız duruş:"))
kullanilabilirlik=(püs-pzd)/püs
print("kullanılabilirlik oranı:",kullanilabilirlik)
scz=int(input("standart çevrim zamanı:"))
umik=int(input("üretim miktarı:"))
performans=(scz*umik)/(püs-pzd)
print("performans oranı:",performans)
sumik=int(input("sağlam ürün miktarı:"))
tumik=int(input("toplam üretim miktarı:"))
kalite=sumik/tumik
print("kalite oranı:",kalite)
oee=(kullanilabilirlik*performans*kalite)
oeeOran=oee/100
return ("İşletmenin Ekipman Kullanılabilirlik Oranı:",oeeOran)
##3)ADAM BAŞI CİRO HESAPLAMA
def abc():
calisan=25
stmik=int(input("satış miktarını giriniz:"))
bsf=int(input("birim satış fiyatını giriniz:"))
ciro=stmik*bsf
print("döneme ait cironuz:",ciro)
adamBasiCiro=ciro/calisan
return ("Adam Başı Ciro:",adamBasiCiro)
while (True):
try:
start()
except KeyboardInterrupt:
interruptState = input("Çıkmak için e tuşla devam etmek için c : ")
if(interruptState == "e"):
exit()
elif (interruptState == "c" ):
pass
|
f64ba5aae02316163d73b265b7b4e8e3d1d7a015 | JacquesVonHamsterviel/USACO | /10.Dual Palindromes /dualpal.py | 1,249 | 3.53125 | 4 | """
ID: vip_1001
LANG: PYTHON3
TASK: dualpal
"""
def tranverter(n,int):
a=[0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
b=[]
res=0
while True:
s=n//int # 整数-商
y=n%int # 余数
b=b+[y]
if s==0:
break
n=s
b.reverse()
c=""
for i in b:
c=c+str(a[i])
return c
def palindromic(num):
b = num[::-1] # 倒序
if num==b:
res=1
else:
res=0
return res
inputfile = open("dualpal.in", "r").readlines()
outputfile = open("dualpal.out", "w")
outnum=int(inputfile[0].strip()[0:inputfile[0].strip().find(" ")])
startfrom=int(inputfile[0].strip()[inputfile[0].strip().find(" ")+1:len(inputfile[0].strip())])
reslist=[]
i=startfrom+1
while i>startfrom:
k=0
for j in range(2,11):
if palindromic(tranverter(i,j))==1:
k+=1
if k>=2:
reslist.append(i)
break
i+=1
if len(reslist)==outnum:
break
if len(reslist)<outnum:
for i in range(0, len(reslist)):
outputfile.write(str(reslist[i]) + "\n")
else:
for i in range(0, outnum):
outputfile.write(str(reslist[i]) + "\n") |
ca8e34316aad56d028e027b4f54631907829f48d | tdow90/ProjectEuler | /ProjectEuler1.py | 196 | 3.59375 | 4 |
# Problem 1 from projecteuler.net
def Multiple_of_3or5(limit):
sum = 0
for i in range(limit):
if i%3==0 or i%5==0:
sum = i + sum
print(sum)
Multiple_of_3or5(1000) |
cfce81f53ed00bb8421999063dc3e982ac5ffe37 | chengong8225/leetcode_record | /sort/0_bubble_sort.py | 678 | 3.84375 | 4 | # 整体思路:
# 两两对比,调整逆序对的位置。如果没有逆序对,说明排序已经完成,可以跳出排序过程。
nums = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44]
nums_out = [2, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 9, 12, 15, 44, 45, 54, 64]
def bubble_sort(nums):
while 1:
state = 0 # 如果没有逆序对,那就跳出排序过程
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
state = 1
if not state:
break
return nums
print(bubble_sort(nums))
print(nums_out) |
e7d09d8d38f4df4f2221ba3963b53467cef66cfb | bregman-arie/python-exercises | /solutions/lists/running_sum/solution.py | 659 | 4.25 | 4 | #!/usr/bin/env python
from typing import List
def running_sum(nums_li: List[int]) -> List[int]:
"""Returns the running sum of a given list of numbers
Args:
nums_li (list): a list of numbers.
Returns:
list: The running sum list of the given list
[1, 5, 6, 2] would return [1, 6, 12, 14]
Time Complexity: O(n)
Space Complexity: O(n)
"""
for i in range(1, len(nums_li)):
nums_li[i] += nums_li[i - 1]
return nums_li
if __name__ == '__main__':
nums_str = input("Insert numbers (e.g. 1 5 1 6): ")
nums_li = [int(i) for i in nums_str.split()]
print(running_sum(list(nums_li)))
|
2facd54b08dd52181d83631e42b018f0e806c414 | keyehzy/Kattis-problems | /goatrope.py | 1,155 | 3.59375 | 4 | from sys import stdin, stdout
input = iter(stdin.read().splitlines()).__next__
def write(x):
return stdout.write(x)
def euclid(A, B):
from math import sqrt, pow
return sqrt(pow(A[0]-B[0], 2) + pow(A[1]-B[1], 2))
def distance(A, B, C):
from math import sqrt
AB = euclid(A, B)
AC = euclid(A, C)
BC = euclid(B, C)
s = (AB + BC + AC) / 2.
A = sqrt(s*(s-AB)*(s-AC)*(s-BC))
return 2 * A / BC
def goatrope():
# Initial commentary
x, y, x1, y1, x2, y2 = map(int, input().split())
A = (x, y)
d = 0
if x < x1:
if y < y1:
d = euclid(A, (x1, y1))
elif y > y2:
d = euclid(A, (x1, y2))
else:
d = distance(A, (x1, y1), (x1, y2))
elif x > x2:
if y < y1:
d = euclid(A, (x2, y1))
elif y > y2:
d = euclid(A, (x2, y2))
else:
d = distance(A, (x2, y1), (x2, y2))
else:
if y < y1:
d = distance(A, (x1, y1), (x2, y1))
elif y > y2:
d = distance(A, (x1, y2), (x2, y2))
write('%f' % d)
return
if __name__ == '__main__':
goatrope() |
6953a1b7ac04b9953512ff5feb4b64d2cc685ad4 | keyehzy/Kattis-problems | /pot.py | 235 | 3.703125 | 4 | def pot():
n = int(input())
result = 0
for _ in range(n):
s = list(input())
pow = int(s.pop(-1))
result += int(''.join(s))**pow
print(result)
return
if __name__ == '__main__':
pot()
|
7bf365ca3355e386038e2ef186b06d3a31051d1e | keyehzy/Kattis-problems | /planina.py | 163 | 3.71875 | 4 | def planina():
j = int(input())
x = 2
while(j):
x += x - 1
j -= 1
print(x*x)
return
if __name__ == '__main__':
planina()
|
12359883985bb50aeb4279711c06aa118c6cdbe1 | killabayte/codewars | /sort_the_odd_kata/main_my.py | 387 | 3.65625 | 4 | def sort_array(source_array):
even_state = []
new_source_array = []
for one, two in enumerate(source_array):
if two % 2 == 0:
even_state.append((one,two))
else:
new_source_array.append(two)
new_source_array.sort()
for new_even in even_state:
new_source_array.insert(new_even[0], new_even[1])
return new_source_array |
9a3ecfad05a80abe490885249fb761a0ca77afb6 | milenamonteiro/learning-python | /exercises/radiuscircle.py | 225 | 4.28125 | 4 | """Write a Python program which accepts the radius of a circle from the user and compute the area."""
import math
RADIUS = float(input("What's the radius? "))
print("The area is {0}".format(math.pi * math.pow(RADIUS, 2)))
|
2d35b9d5142ed983ef986af641457a21a3e4949d | milenamonteiro/learning-python | /exercises/jokenpo.py | 1,910 | 3.96875 | 4 | """Make a two-player Rock-Paper-Scissors game."""
import os
import time
def cls():
os.system('cls' if os.name=='nt' else 'clear')
def rps(text):
pedra = set(['pedra', 'pe', 'pdra', 'pedr', "1"])
papel = set(['papel', 'pap', "2", 'pape', 'ppel', 'pa', 'papl'])
tesoura = set(['tesoura', 't', "3", 'tsoura', 'tesora'])
while True:
choice = input(text).lower()
if choice in pedra:
input("\nVocê escolheu pedra, boa sorte! Pressione qualquer tecla para continuar.")
return "pedra"
if choice in papel:
input("\nVocê escolheu papel, boa sorte! Pressione qualquer tecla para continuar.")
return "papel"
if choice in tesoura:
input("\nVocê escolheu tesoura, boa sorte! Pressione qualquer tecla para continuar.")
return "tesoura"
print("Por favor, insira o valor correspondente.")
def game(input1, input2):
if input1 == input2:
print("Parece que houve um empate! Ambos jogaram", input1)
elif input1 == "pedra":
if input2 == "tesoura":
ganhador(p1)
else:
ganhador(p2)
elif input1 == "papel":
if input2 == "pedra":
ganhador(p1)
else:
ganhador(p2)
elif input1 == "tesoura":
if input2 == "papel":
ganhador(p1)
else:
ganhador(p2)
def ganhador(p):
print("O jogador {0} jogou {1} e o jogador {2} jogou {3}!\n\nO vencedor é {4}!"
.format(p1, i1, p2, i2, p))
cls()
print("Jokenpô!")
p1 = input("\nInsira o nome do primeiro jogador: ")
p2 = input("\nInsira o nome do segundo jogador: ")
cls()
print("Vamos jogar! Por favor, vire a tela para", p1)
i1 = rps("\nVai jogar com pedra, papel ou tesoura? ")
cls()
print("Agora vire a tela para", p2)
i2 = rps("\nVai jogar com pedra, papel ou tesoura? ")
cls()
p = game(i1, i2)
|
88a268f20d6681db86dcebe9348812f83564a7dc | cbz1902/capturador_tweets | /tweets.py | 984 | 3.890625 | 4 | ######################Clase que nos premite modelar un tweets como un objeto############################################
class tweets:
def __init__(self,tweet,user,mencion,localizacion,hashtag):
"""Inicializador de la clase"""
self.tweet = tweet
self.user = user
self.mencion = mencion
self.localizacion = localizacion
self.hashtag = hashtag
def get_tweet(self):
"""Muestra el texto del tweet"""
return self.tweet
def get_user(self):
"""Muestra el usuario quién realizó el tweet"""
return self.user
def get_mencion(self):
"""Muestra la mención que hay en tweet"""
return self.mencion
def get_localizacion(self):
"""Muestra las coordenadas desde donde se realizó el tweet"""
return self.localizacion
def get_hashtag(self):
"""Muestra los hashtag que se mecionaron en el tweet"""
return self.hashtag
|
332c0b3254b0e565e0056193ab36204421e46aa0 | jundet/jundet.github.io | /2018/10/08/algorithm/cheaper04/maximum_subarray.py | 1,402 | 3.84375 | 4 | # 最大子数组 分治法
import math
import sys
def max_cross_subarray(A, low, mid, high):
left_sum = float("-inf")
sum = 0
max_left = mid
max_right = mid
for i in range(mid-low):
sum = sum + A[mid-i]
if sum > left_sum:
left_sum = sum
max_left = mid - i
right_sum = float("-inf")
sum = 0
for i in range(mid, high):
sum = sum + A[i]
if sum > right_sum:
left_sum = sum
max_right = i
return max_left, max_right, left_sum+right_sum
def max_subarray(A, low, high):
if high == low:
return low, high, A[low]
else:
mid = math.floor((low+high)/2)
left_low, left_high, left_sum = max_subarray(A, low, mid)
right_low, right_high, right_sum = max_subarray(A, mid, high)
cross_low, cross_high, cross_sum = max_cross_subarray(A, low, mid, high)
if left_sum > right_sum and left_sum > cross_sum:
return left_low, left_high, left_sum
elif right_sum > left_sum and right_sum > cross_sum:
return left_low, left_high, left_sum
else:
return cross_low, cross_high, cross_sum
def main():
A = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
low, high, sum = max_subarray(A, 0, len(A)-1)
print(low, ";", high, ";", sum)
if __name__ == "__main__":
main()
|
29cb5bea079b380e867470354ea4e538eb70338b | SSeadog/Algorithm-Practice-Python | /greedy/greedy7.py | 1,244 | 3.625 | 4 | # 만들 수 없는 금액
# 나동빈씨의 해결 방법을 이용
# 동전 개수 n 입력
n = int(input())
# 동전 종류 coin 입력
coin = list(map(int, input().split()))
# coin 오름차순으로 정렬
coin.sort()
# target-1까지 만들 수 있다는 의미를 위해 target 선언
target = 1
# target을 갱신하며 target보다 작은 동전이 없다면 target을 만들 수 없으므로 종료
for c in coin:
if c > target:
break
else: # c가 target보다 작으면 target-1+c까지 금액을 만들 수 있으므로 target에 더해줌
target += c
print(target)
# # 마땅한 방안이 안 떠오름
# # 동전 개수 n 입력
# n = int(input())
# # 동전 종류 coin 입력
# coin = list(map(int, input().split()))
# # coin 내림차순으로 정렬
# coin.sort(reverse=True)
# # coin에 마지막항에 0을 넣음
# coin.append(0)
# # 결과 저장 변수
# result = 0
# print(coin)
# n = 1
# while not result:
# current = n
# for i in coin:
# if i == 0:
# result = n
# if i > n:
# continue
# else:
# current -= i
# if current == 0:
# break
# n += 1
# print(n)
# print(result)
|
6d57b987fa90804134b4b5edbc07ab05bd4a59fa | SSeadog/Algorithm-Practice-Python | /search/bfs.py | 948 | 3.671875 | 4 | # BFS
# 큐를 이용한 bfs
import queue
# bfs 함수 생성
def bfs(graph, start):
# 시작 값을 큐에 넣고 방문 처리
q.put(start)
visited[start] = True
# 큐가 빌때까지 반복
while q.qsize() != 0:
# 큐에서 값을 꺼냄, 출력해서 꺼낸 순서 확인
v = q.get()
print(v, end=" ")
for near_node in graph[v]:
# 방문하지 않은 인접노드들을 큐에 넣음, 방문 처리
if visited[near_node] == False:
q.put(near_node)
visited[near_node] = True
# 그래프를 2차원 리스트(인접 리스트)로 구현
graph = [[], [2, 3, 8], [1, 7], [1, 4, 5],
[3, 5], [3, 4], [7], [2, 6, 8], [1, 7]]
# 방문 확인을 위한 변수 초기화
visited = [False for _ in range(9)]
# bfs 구현을 위한 queue 인스턴스 생성
q = queue.Queue()
# 실행, 결과 확인
bfs(graph, 1)
print(visited)
|
4978aa906cf99b18f54d0f24145eeab60ac967ea | SSeadog/Algorithm-Practice-Python | /simulation/simulation2.py | 888 | 3.578125 | 4 | # 시각
n = input()
# 시계 구현 0번째 인덱스는 시간 1번째 인덱스는 분 2번째 인덱스는 초
clock = [0, 0, 0]
# 결과 저장
result = 0
# 시간이 n보다 작을 때까지만 반복
while clock[0] <= int(n):
# 시분초에 3이 있다면 결과 1증가
if clock[0] % 10 == 3 or int(clock[1] / 10) == 3 or clock[1] % 10 == 3 or int(clock[2] / 10) == 3 or clock[2] % 10 == 3:
result += 1
# 매 반복마다 초를 의미하는 2번째 인덱스에 1추가
clock[2] += 1
# 초가 60초가 되면 초를 0으로 바꾸고 분을 의미하는 1번째 인덱스에 1추가
if clock[2] == 60:
clock[2] = 0
clock[1] += 1
# 분이 60분이 되면 분을 0으로 바꾸고 시를 의미하는 0번째 인덱스에 1추가
if clock[1] == 60:
clock[1] = 0
clock[0] += 1
print(result)
|
f6a3b5a620203e8d05d31b43e5e98efd52a9b5f2 | tricelex/startng-task2 | /user_validate.py | 2,007 | 3.953125 | 4 | import random
import string
def generate_password(fname, lname):
letters = string.ascii_lowercase
randomvars = ''.join(random.choice(letters) for i in range(5))
rand_password = fname[0:2] + lname[0:2] + randomvars
return rand_password
def validate_password(my_password):
new_user_input_password = ''
length = 7
while len(my_password) < length:
new_user_input_password = input(
'Please Enter new password equal or greater than 7 characters: ')
return new_user_input_password
def show_message(new_employee):
print('\nEmployee Information: ')
print("FirstName: " + new_employee['firstName'])
print("LastName: " + new_employee['lastName'])
print("Email: " + new_employee['email'])
print("Password: " + new_employee['password'])
is_running = True
all_employees = []
while is_running:
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
email = input("Enter your email: ")
password = generate_password(first_name, last_name)
satisfied = input(f'Are you satisfied with "{password}" as your password..Enter Y/N: ')
while satisfied != 'y' or 'n':
if satisfied == 'y':
employee = {'firstName': first_name, 'lastName': last_name, 'email': email,
'password': password}
all_employees.append(employee)
show_message(employee)
quit_program = input('\nEnter q to quit or any value to continue: ')
if quit_program == 'q':
is_running = False
break
elif satisfied == 'n':
value = input('\nEnter new password equal or greater than 7 characters: ')
user_input_password = validate_password(value)
employee = {'firstName': first_name, 'lastName': last_name, 'email': email,
'password': user_input_password}
all_employees.append(employee)
show_message(employee)
quit_program = input('Enter q to quit or any value to continue: ')
if quit_program == 'q':
is_running = False
break
else:
satisfied = input('Please Enter either Y or N: ')
for user in all_employees:
print('')
print(user)
|
399a4d526917be7644a04ecd7bc72de480390533 | flyfreejay/Python | /CCC/02/0123456789.py | 2,261 | 3.875 | 4 | '''
Date: 01/06/2019
Author: Jay Lee
Version: 1.0
Purpose: to find the prime numbers from 3 to 100
'''
i = str(input())
def Write0():
print(" * * *")
print("* *")
print("* *")
print("* *")
print("")
print("* *")
print("* *")
print("* *")
print(" * * *")
def Write1():
print(" *")
print(" *")
print(" *")
print("")
print(" *")
print(" *")
print(" *")
def Write2():
print(" * * * ")
print(" *")
print(" *")
print(" *")
print(" * * * ")
print("* ")
print("* ")
print("* ")
print(" * * * ")
def Write3():
print(" * * * ")
print(" *")
print(" *")
print(" *")
print(" * * * ")
print(" *")
print(" *")
print(" *")
print(" * * * ")
def Write4():
print("* *")
print("* *")
print("* *")
print(" * * * ")
print(" *")
print(" *")
print(" *")
def Write5():
print(" * * * ")
print("*")
print("*")
print("*")
print(" * * * ")
print(" *")
print(" *")
print(" * * *")
def Write6():
print(" * * *")
print("* ")
print("* ")
print("* ")
print(" * * *")
print("* *")
print("* *")
print("* *")
print(" * * *")
def Write7():
print(" * * *")
print(" *")
print(" *")
print(" *")
print(" ")
print(" *")
print(" *")
print(" *")
def Write8():
print(" * * *")
print("* *")
print("* *")
print("* *")
print(" * * *")
print("* *")
print("* *")
print("* *")
print(" * * *")
def Write9():
print(" * * *")
print("* *")
print("* *")
print("* *")
print(" * * *")
print(" *")
print(" *")
print(" *")
print(" * * *")
if i =="1":
Write1()
elif i =="2":
Write2()
elif i== "3":
Write3()
elif i == "4":
Write4()
elif i == "5":
Write5()
elif i =="6":
Write6()
elif i == "7":
Write7()
elif i == "8":
Write8()
elif i == "9":
Write9()
else:
Write0() |
4a712daf753218a2fbb46209a38d647640cf0369 | alexramirez106/issue-quiz | /issue-quiz.py | 2,319 | 3.9375 | 4 | userScore = 0
# Question 1 - Barbara Mikulski
question_1 = input("Was Barbara Mikulski the first woman endorsed by EMILY's List? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_1 == "Y":
userScore = userScore + 1
print("Correct! Your score is " + str(userScore) + "!")
else:
print("Sorry! That is incorrect. Your score is " + str(userScore) + ".")
while question_1 == "N":
print("Try again!")
question_1 = input("Was Barbara Mikulski the first woman endorsed by EMILY's List? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_1 == "Y":
userScore = userScore + 1
print("Correct! Your score is " + str(userScore) + "!")
else:
print("Sorry! That is incorrect. Your score is " + str(userScore) + ".")
# Question 2 - Menfolk
question_2 = input("Does EMILY's List endorse or fundraise for pro-choice Democratic men? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_2 == "N":
userScore = int(userScore) + 1
print("Correct! Your score is " + str(userScore) + "!")
else:
print("Sorry! That is incorrect. Your score is " + str(userScore) + ".")
while question_2 == "Y":
print("Try again!")
question_2 = input("Does EMILY's List endorse or fundraise for pro-choice Democratic men? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_2 == "N":
userScore = int(userScore) + 1
print("Correct! Your score is " + str(userScore) + "!")
else:
print("Sorry! That is incorrect. Your score is " + str(userScore) + ".")
# Question 3 - Text 47717
question_3 = input("Does EMILY's List raise money through SMS/text? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_3 == "Y":
userScore = int(userScore) + 1
print("Correct! Text JOIN to 47717! Your final score is " + str(userScore) + "!")
else:
print("Sorry! That is incorrect.")
while question_3 == "N":
print("Try again!")
question_3 = input("Does EMILY's List raise money through SMS/text? If yes, please write 'Y'. If no, please write 'N'. : ")
if question_3 == "Y":
userScore = int(userScore) + 1
print("Correct! Text JOIN to 47717! Your final score is " + str(userScore) + "! Great job!")
else:
print("Sorry! That is incorrect.")
|
eea96998bf055dbadf9735177491c26586698cb9 | ufo9631/pythonApp | /test/for_else.py | 83 | 3.734375 | 4 | nums=[11,22,33,44,55]
for item in nums:
print(item)
else:
print("========") |
ab9c7dbe972d537de2981a7e8de84b9917fbd7fa | ufo9631/pythonApp | /for01.py | 669 | 3.734375 | 4 | age=17
if age<18:
print("去叫家长把,孩纸")
gender="男"
if gender=="女":
print("美女 你好!")
else:
print("吔屎啊你")
#score=input("请输入分数:")
#score=int(score) #字符串转int
#print(score)
#if score>=90:
# print("优秀")
#elif score>80 and score<90:
# print("良")
#python 没有switch-case
'''
for 变量 in 序列:
语句
'''
for name in ['zhangsan','lisi','wangwu']:
print(name)
for i in range(1,11):
print(i)
# for --else
for name in []:
pass #pass占位符 ,什么都不实现用pass站位
else:
print("循环结束")
#循环结束 break,contineu,pass
#break 结束整个循环
|
e5dd6b083b14b15019b04d4056030ac75602ebcf | ufo9631/pythonApp | /variableDemo.py | 8,478 | 4.09375 | 4 | #变量
#全局变量(global):在函数外部定义
#局部变量(local):在函数内部定义
#提升局部变量为全局变量
def fun():
global bl
b1=100
print(bl)
print("I am in fun")
b2=99
print(b2)
#print(b1)
#globals,locals函数
#可以通过globals和locals出局部变量和全局变量
a=1
b=2
def fun(c,d):
e=111
print("Locals={}".format(locals()))
print("Globals={}".format(globals()))
fun(100,200)
#eval()函数 把一个字符串当成一个表达式来执行,返回表达式执行的结果
x=100
y=200
z=eval("x+y")
print(z)
#exec()函数,跟eval()功能相似,但是不返回结果
x=100
y=200
z=exec("x+y")
print(z)
#递归函数
#函数调用自己
#优点:简洁,理解容易
#缺点:对递归深度有限制,消耗资源大
#python对递归深度有限制,超过限制报错
#递归调用深度限制代码
x=0
def fun():
global x
x+=1
print(x)
fun()
#fun()
#内置数据结构(变量类型)
#list,set,dict,tuple
#list(列表) 一组有顺序的数据的组合
l1=[]
print(type(l1))
l2=[100]
print(type(l2),l2)
l3=list()
print(type(l3),l3)
#使用下标(索引)访问列表
l=[3,4,5,9,6,1,3]
print(l[0])
#分片操作,下标值可以为空,如果不写,左边下标值默认为0,右边下标值为最大数加一,即表示取到最后一个数据
print(l[1:3]) #[:] 分片的范围左开右闭
print(l[-2:-1])
print(l[:])
#分片可以控制增长幅度,默认增长幅度为1
print(l[1:6:2]) ## 第二个冒号表示补偿长度 从2到-1 然后隔一个取一个
#下标可以朝出范围,超出后不在考虑多余下标内容
#如果分片一定左边值比右边大,则幅度增长参数需要使用负数
print(l[-2:-4:-1]) #相当于一个逆序的效果
#分片操作是生成一个新的list
#内置函数id,负责显示一个变量或数据的唯一确定编号
#id函数举例
a=100
b=200
print(id(a))
print(id(b))
#list 删除
del l[2]
print(l)
#列表相加
a=[1,2,3,4,5]
b=[6,7,8,9,10]
print(a+b)
#使用乘号操作列表
a=[1,2,3]
b=a*3
print(b)
#成员资格运算,判断一个元素是否在list里边
a=[1,2,3,4,5]
b=8
c=b in a # c是一个布尔值
print(c)
print(b not in a)
#列表的遍历for,while
a=[1,2,3,4,5]
for i in a: # in 后面的变量要求是可以可迭代的内容
print(i)
b=["I love chenweichao"]
for i in b:
print(i)
#一般不用while list
a=[1,2,3,4,5]
length=len(a)
indx=0
while indx<length:
print(a[indx])
indx+=1
#双层列表循环
a=[["one",1],["two",2],["three",3]]
for k,v in a:
print(k,"-",v)
#列表内涵:list content
#for创建
a=['a','b','c']
#用list a创建一个list b
b=[i for i in a]
print(b)
#过滤原来list中的内容放入新列表
a=[x for x in range(1,35)]
b=[m for m in a if m%2==0]
print(b)
#列表生成可以嵌套
a=[i for i in range(1,10)]
print(a)
b =[i for i in range(100,1000) if i%100==0]
print(b)
c=[m+n for m in a for n in b]
print(c)
for m in a:
for n in b:
print(m+n,end=" ")
print()
#列表常用函数
#len:列表长度
a=[x for x in range(1,100)]
print(len(a))
#max 求列表最大值
#min 求列表最小值
print(max(a))
b=['man','film','python']
print(max(b))
#list 函数将格式数据转换成list
a=[1,2,3]
print(list(a))
s="I am chenweichao"
print(list(s))
#传值和传地址的区别
#对于简单的数值,采用传值的操作,即函数内对参数的操作不影响外面的变量
#对于复杂变量,采用传地址操作,此时函数内的参数和外部变量都是同一份,任何地方对此内容更改都影响变量
#关于列表的函数
l=['a','b',"c",45,766,5+7]
a=[i for i in range(1,5)]
print(a)
a.append(100) #在末尾插入
print(a)
a.insert(3,666) #插入的是index的前面
print(a)
#删除
# del删除
#pop ,从对位拿出一个元素,即把最后一个元素取出来
last_ele=a.pop() #拿出最后一个元素
print(last_ele)
#remove:在列表中删除指定的值,要删除的值必须是存在的,否则报错
a.remove(666)
print(a)
#clear:清空
a.clear()
print(a)
#reverse:翻转
a=[1,2,3,4,5,6]
a.reverse()
print(a)
#extend:扩展列表,把两个列表,把一个直接拼接到后一个上
a=[1,2,3,4,5,6]
b=[6,7,8,9,10]
a.extend(b)
print(a)
#count:查找列表中指定值或元素的个数
a_len=a.count(8)
print(a_len)
#copy:拷贝,浅拷贝
#列表类型变量赋值示例
a=[1,2,3,4,5]
b=a.copy()
print(b)
print(id(a))
print(id(b))
#深拷贝跟浅拷贝的区别,对于多层嵌套的列表 浅拷贝只拷贝了一层,深拷贝需要使用特定工具
a=[1,2,3,[10,20,30]]
b=a.copy()
#元组-tuple,元组可以看成是一个不可更改的list
t=()
print(type(t))
#创建一个只有一个值的元组
t=(1,)
print(type(t))
print(t)
t=1,
print(type(t))
#创建多个值的元组
t=(1,2,3,4)
t1=1,2,3,4,5
print(type(t))
print(type(t1))
l=[1,2,3,4,5]
t=tuple(l)
print(type(t))
print(t)
#元组的特定
#是序列表有序
#元组数据可以访问,不能修改
#元素数据可以是任意类型
#总之,list所有特定,除了可修改外,元组都具有
#索引操作
t=(1,2,3,4,5)
print(t[4])
t=(1,2,3,4,5,6)
t1=t[1::2]
print(t1)
#切片可以超标
t2=t[2:100]
print(t2)
#tuple 相加
t=(1,2,3)
t2=(5,6,7)
t1+=t2
print(t1)
#成员检测
t=(1,2,3,4)
if 2 in t:
print("Yes")
else:
print("No")
#元组遍历,一般采用for
#单层元组遍历
t=(1,2,3,4,"i","a","b")
for i in t:
print(i,end=" ")
#双层元组遍历
t=((1,2,3),(2,3,4),('a','b','c'))
for i in t:
print(i)
for k,m ,n in t:
print(k,'---',m,'-----',n)
#关于元组的函数
#len:获取元组的长度
t=(1,2,3,4,5)
print(len(t))
#max ,min 最大最小值,如果列表或元组有多个最大或最小值,则实际打印出哪个
print(max(t))
print(min(t))
#tuple:转化或创建元组
l=[1,2,3,4,5]
t=tuple(l)
print(t)
t=tuple()
print(t)
#元组的函数
# 基本跟list通用
#count: 计算指定数据出现的次数
t=(1,22,2,3,4,4,5,6,6)
print(t.count(3))
#index:找出指定的元素在元组中的索引位置
print(t.index(4))
#元组变量交换法
#变量交换值
a=1
b=3
a,b=b,a
print(a)
print(b)
#集合Set,集合是数据概念
#一堆确定的无序的唯一的数据,集合中每个数据成为一个元素
#集合的定义
s=set()
print(type(s))
s={1,2,3,4,5}
print(type(s)) #大括号定义有值的表示set
print(s)
#如果只是用大括号定义,则定义的是一个dict类型
d={}
print(type(d))
#集合的特征
#集合内数据无序,即无法使用索引和分片
#集合内部数据元素具有唯一性,可以用来排除重复数据
#集合的数据包括可哈希的数据
#集合序列操作,成员检测
s={2,3,4,'a','b','sdfsdfsdfd'}
print(s)
if 2 in s:
print("Yes")
#集合遍历操作
s={2,3,4,'a','b','sdfsdfsdfd'}
for i in s:
print(i,end=" ")
print()
#带有元组的集合遍历
s={(1,2,3),('a','b','c'),(4,6,5)} #不能放集合,集合是不可哈希
for k in s:
print(k)
for k,m ,n in s:
print(k,'---',m,'----',n)
#集合的内涵
#普通的集合内涵,以下集合会自动过滤掉重复的
s={23,1,3,4,5,6,33,7,1,2,3,4,5}
print(s)
ss={i for i in s}
print(ss)
#带条件的集合内涵
sss={i for i in s if i%2==0}
print(sss)
#多循环的集合内涵
s1={1,2,3,4}
s2={'a','b','c'}
s={m*n for m in s1 for n in s2}
print(s)
#集合函数、关于集合的函数
#len,max,min
s={1,2,34,54,34,65,76}
print(len(s))
print(max(s))
print(min(s))
# set 生成一个集合
l=[1,2,3,4,5,6]
s=set(l)
print(s)
#add 向集合内添加元素
s={1}
s.add(234)
print(s)
#clear
s={1}
print(s.clear())
#copy 拷贝
#remove 移除指定的值,如果删除的值不存在 报错
#discard:移除集合指定的值,跟remove一样,但是值不存在的话,不报错
s={12,3,2,4,5}
s.remove(4)
print(s)
s.discard(12)
s.discard(1000)
#pop 随机移除一个元素
s={1,2,3,4,5,6}
d=s.pop()
print(d)
print(s)
#集合函数
#intersection:交集
#difference:差集
#union:并集
#issubset检查一个集合是否为另一个子集
#issuperset:检查一个集合是否为另一个超集
s1={1,2,3,4,5}
s2={3,4,5,6,7}
s_1=s1.intersection(s2)
print(s_1)
s_2=s1.difference(s2)
print(s_2)
s_3=s1.issubset(s2)
print(s_3)
#集合的数学操作
s1={1,2,3,4,5}
s2={3,4,5,6,7}
s_1=s1-s2
print(s_1)
s_2=s1+s2
print(s_2)
#冰冻集合,冰冻和就是不可以进行任何修改的集合,frozenset是一种特殊集合
s=frozenset()
print(type(s))
print(s)
|
eb25947e284a7afc0235865eb1f76818515a0517 | ufo9631/pythonApp | /FunctionProgramming/02.py | 1,661 | 3.90625 | 4 | #函数作为返回值返回
def myF2():
def myF3():
print("In myF3")
return 3
return myF3
f3=myF2()
print(type(f3))
print(f3)
f3()
#返回函数稍微复杂的例子
#args:参数列表
def myF4(*args):
def myF5():
rst=0
for n in args:
rst+=n
return rst
return myF5
f5=myF4(1,23,5,6,7,8)
print(f5())
#闭包 (closure)
#当一个函数在内部定义函数,并且内部的函数应用的函数应用外部函数的参数或者局部变量,当内部函数被当做返回的时候,相关参数和变量保存在返回的函数中,这种结果,叫做闭包
#闭包常见的坑
def count():
#定义列表,列表里存放的是定义的函数
fs=[]
for i in range(1,4):
#定义了一个函数f
#f是一个闭包结构
def f():
return i*i
fs.append(f)
return fs
f1,f2,f3=count()
print(f1())
print(f2())
print(f3())
#出现的问题
#造成上述状况的原因是,返回函数引用了变量i,i并非立即执行,而是等到三个函数都返回的时候才统一使用,此时i已经变成了3,最终调用的结果,都返回的是3*3
#此问题描述:返回闭包时,返回函数不能引用任何循环变量
#解决方案:再创建一个函数,用该函数的参数绑定循环变量的当前值,无论该循环变量以后如何改变,已经绑定的函数参数值不再改变
def count2():
def f(j):
def g():
return j*j
return g()
fs=[]
for i in range(1,4):
fs.append(f(i))
return fs
f1,f2,f3=count2()
print(f1())
print(f2())
print(f3()) |
2b6eae0c835ffaa59af7ff51c99d588a3ff32751 | ufo9631/pythonApp | /test/listOpera.py | 526 | 4.09375 | 4 | #list 增删改查
names=['老王','老李','老刘']
names.append('老赵') #添加到list最后
print(names)
# names.insert(位置,要添加的内容)
names.insert(0,'老陈')
print(names)
names.insert(2,'老汪')
print(names)
names2=['葫芦娃','叮当猫','蜘蛛侠']
names3=names+names2;
print(names3)
names.extend(names3) #将 names3合并到names
print(names)
names.pop() #将最后一个删除 并返回删除的元素
names.remove('老王') #根据内容来删除
del names[0] #删除指定下标的元素 |
e4c083a7a08f3e3f973ecc6ca70d912ea79279fb | ufo9631/pythonApp | /test/strtest.py | 719 | 3.609375 | 4 | l=[1,2,3,4,5]
print(1 in l)
print(1 not in l)
s="hell world{0}{1}".format(1,2)
print(s)
s1='name is %s,age is %d'%('张三',18)
print(s1)
print(s is s1)
print(s is not s1)
i=1
while i<2000:
i=i+1;
print(1,end="|")
if i==10:
break
i=0
while i<10:
print(i,'\n')
i=i+1
else:
print('循环结束')
i=100
print(id(i))
print("hello"+"world")
print(len('abcdefg'))
s="hello world"
print(s[-1])
print(s[-2])
s="abcdefgABCDEFG"
print(s[1:3]) # 字符串切片
print(s[1:-2])
print(s[1:]) #冒号后面没写 就取到最后
print(s[2:-1:2])# 第二个冒号表示补偿长度 从2到-1 然后隔一个取一个
print(s[-1::-1]) #相当于字符串逆序输出 也可以缩写为 s[::-1]
|
39f2f5cb8ca7709e491870793ce0a3923718d3a2 | AfkZa4aem/pong_game | /score.py | 575 | 3.625 | 4 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 40, "normal")
class Score(Turtle):
def __init__(self, position):
super().__init__()
self.color("white")
self.speed("fastest")
self.penup()
self.ht()
self.goto(position)
self.current_score = 0
self.show_score()
def show_score(self):
self.write(f"{self.current_score}", align=ALIGNMENT, font=FONT)
def add_point(self):
self.clear()
self.current_score += 1
self.show_score()
|
7e7c8eb9d88df0ab625913abe74d093ba1ed8a14 | SAMUELVJOSHUA/HeapSort | /HeapSort.py | 319 | 4.0625 | 4 | def heapsort(MyList):
m = len(MyList)
for i in range(m//2, -1, -1):
heapify(MyList, n-1, i)
for i in range(m-1, -1, -1):
# swapping last element with the first element
MyList[i], MyList[0] = MyList[0], MyList[i]
# exclude the last element from the heap
heapify(MyList, i-1, 0)
|
b43b9cbf051659b1fe818de7774cd848e9004020 | foytingo/cs50x | /pset6/mario_less.py | 424 | 3.890625 | 4 | from cs50 import get_int
def main():
height = get_valid_int()
mario_wall(height)
def mario_wall(height):
for i in range(height):
for _ in range(height-i-1):
print(" ", end="")
for _ in range(i+1):
print("#", end="")
print()
def get_valid_int():
while True:
n = get_int("Height: ")
if n <= 8 and n >= 1:
break
return n
main() |
9da34a38cc05d00a5f363595f2d7cd0f1fbb9e14 | deeGraYve/UpennCoursework | /lines/robot.py | 12,443 | 3.65625 | 4 | from robotUtilities import *
from guiHelp import *
import heapq
class PriorityQueue:
def __init__(self):
"""heap: A binomial heap storing [priority,item] lists."""
self.heap = []
self.dict = {}
def setPriority(self,stuff,priority):
"""inserts element into the queue and sets up its priority"""
if stuff in self.dict:
self.dict[stuff][0] = priority
heapq.heapify(self.heap)
else:
pair = [priority,stuff]
heapq.heappush(self.heap,pair)
self.dict[stuff] = pair
def getPriority(self,stuff):
"""returns the priority of a given element in the queue"""
if not stuff in self.dict:
return None
return self.dict[stuff][0]
def dequeue(self):
"""dequeues the element with the highest priority"""
if self.isEmpty():
return None
(priority,stuff) = heapq.heappop(self.heap)
del self.dict[stuff]
return stuff
def isEmpty(self):
"""checks whether or not the queue is empty"""
return len(self.heap) == 0
class Node:
"""Node structure to use for DFS and BFS searches"""
def __init__(self,point):
self.point = point
self.visible = []
self.depth = 0
self.parent = None
def addVis(self,vis):
"""adds visible points to the list"""
self.visible.append(Node(vis))
def setParent(self,node):
"""sets parent of the node"""
self.depth = node.depth + 1
self.parent = node
def getParent(self):
"""returns the parent of the node"""
return self.parent
def __eq__(self, dif):
"""operation of node comparison"""
if self.point == dif.getPoint():
return True
return False
def getPoint(self):
"""returns the point of the node"""
return self.point
def listVis(self):
"""lists all visible nodes"""
return self.visible
def isIn(self,where):
"""checks if node is in some node's array"""
pts = []
for node in where:
pts.append(node.point)
if self.point in pts:
return True
return False
class aStartNode:
"""node structure to be used with A* search (added it late, didn't want to
modify the existing Node structure)"""
def __init__(self, state, parent, pathcost):
self.state = state
self.parent = parent
self.pathcost = pathcost
class navigateSolution:
"""solution class"""
def __init__(self,num):
files = []
files.append('triangle_in_the_middle.test')
files.append('square_in_the_middle.test')
files.append('big_triangles.test')
files.append('tall_triangle_in_the_middle.test')
files.append('mine.test')
self.board = read(files[num])
(self.start, self.end, preobst) = self.board
self.obstacles = []
self.lines = []
self.fringe = []
self.visited = []
self.queue = PriorityQueue()
range = 0
for obstacle in preobst:
if range == 0:
range = 1
else:
self.obstacles.append(obstacle)
self.lines.extend(self.makeLines(obstacle))
def tracepath(self,node):
"""traces path back to the parent"""
if node.parent:
return self.tracepath(node.parent) + [node.state]
else:
return [node.state]
def drawMe(self):
"""draws the board with the obstacles"""
self.root = Tk()
self.mycanvas = Canvas(self.root, width = 600, height = 600)
self.mycanvas.pack()
drawboard(self.mycanvas,self.board)
drawPoint(self.mycanvas,self.start,"red")
drawPoint(self.mycanvas,self.end,"green")
def startDraw(self):
"""starts displaying the canvas"""
self.root.mainloop()
def drawOrigin(self):
"""draws origin"""
drawPoint(self.mycanvas,(0,0),"yellow")
def makeLines(self,obst):
"""returns an array of lines that an obstacle consists of"""
lns = []
for i in range(len(obst)-1):
lns.append((obst[i], obst[i+1]))
lns.append((obst[len(obst)-1], obst[0]))
return lns
def isInsidePoly(self,poly,node):
"""checks if a point is inside of a given polygon"""
cross = 0
pt = node.point
lns = self.makeLines(poly)
ray = ((99.2,101.3),pt) #TODO: check that the line segment doesn't cross the vertex
for ln in lns:
if linesIntersect(ray, ln) == True:
cross += 1
if cross % 2 == 1:
return True
return False
def findVisible(self,curnode):
"""finds nodes visible from a given one"""
for obstacle in self.obstacles:
polylines = self.makeLines(obstacle)
for point in obstacle:
if pathIntersectsAnyLines(curnode.point, point, self.lines) == False:
testnode = Node(self.getMiddle(((curnode.point),(point))))
if self.isInsidePoly(obstacle, testnode) == False:
if Node(point) not in curnode.visible and curnode.point != point:
curnode.addVis(point)
else:
acc = []
for polyline in polylines:
if curnode.point in polyline:
(p1,p2) = polyline
if p1 != curnode.point:
acc.append(p1)
else:
acc.append(p2)
for pt in acc:
if Node(pt) not in curnode.visible and curnode.point != pt:
curnode.addVis(pt)
if pathIntersectsAnyLines(curnode.point, self.end, self.lines) == False:
curnode.addVis(self.end)
return curnode.visible
def getStart(self):
"""returns Node with start point"""
return Node(self.start)
def isGoal(self,node):
"""checks if node is a goal state"""
if node.point == self.end:
return True
return False
def isGoalState(self,pt):
"""checks if point is a goal state"""
if pt == self.end:
return True
return False
def getMiddle(self, line):
"""returns floor of center of line segment"""
((x1, y1), (x2,y2)) = line
(x, y) = (((x1+x2)/2), ((y1+y2)/2))
return (x, y)
def successor(self,node):
"""returns successors of the node"""
succ = []
for vis in self.findVisible(node):
if vis.isIn(self.visited) == False and vis.isIn(self.fringe) == False:
succ.append(vis)
return succ
def dfs(self):
"""DFS search"""
self.fringe.append(self.getStart())
while len(self.fringe) > 0:
node = self.fringe.pop()
if node.getParent() != None:
drawLine(self.mycanvas,node.getParent().point,node.point,"red")
self.visited.append(node)
if self.isGoal(node):
return node
successors = self.successor(node)
for sc in successors:
sc.setParent(node)
self.fringe.extend(successors)
return None
def bfs(self):
"""BFS search"""
self.fringe.append(self.getStart())
while len(self.fringe) > 0:
node = self.fringe.pop(0)
if node.getParent() != None:
drawLine(self.mycanvas,node.getParent().point,node.point,"red")
self.visited.append(node)
if self.isGoal(node):
return node
successors = self.successor(node)
for sc in successors:
sc.setParent(node)
self.fringe.extend(successors)
return None
def h(self,pnt):
"""returns a value of h needed for heuristic function, namely a distance to the end point"""
return distance(pnt,self.end)
def getSuccessors(self,pt):
"""returns node's successors used in A* search(slightly different from successors function)"""
visible = []
for obstacle in self.obstacles:
polylines = self.makeLines(obstacle)
for point in obstacle:
if pathIntersectsAnyLines(pt, point, self.lines) == False:
testnode = Node(self.getMiddle(((pt),(point))))
if self.isInsidePoly(obstacle, testnode) == False:
if point not in visible and pt != point:
visible.append((point,distance(pt,point)))
else:
acc = []
for polyline in polylines:
if pt in polyline:
(p1,p2) = polyline
if p1 != pt:
acc.append(p1)
else:
acc.append(p2)
for pnt in acc:
if pnt not in visible and pt != pnt:
visible.append((pnt,distance(pt,pnt)))
if pathIntersectsAnyLines(pt, self.end, self.lines) == False:
visible.append((self.end,distance(pt,self.end)))
return visible
def aStar(self):
"""A* search"""
fringe = PriorityQueue()
fringe.setPriority(aStartNode(self.getStart().point, None, 0.0), self.h(self.start))
closed = set()
while not fringe.isEmpty():
node = fringe.dequeue()
if self.isGoalState(node.state):
return (self.tracepath(node), node.pathcost)
elif node.state not in closed:
closed.add(node.state)
for (nextstate, nextcost) in self.getSuccessors(node.state):
g = node.pathcost + nextcost
f = self.h(nextstate) + g
fringe.setPriority(aStartNode(nextstate, node, g), f)
return (None, 0.0)
def aStarSolve(self):
"""returns A* solution path"""
(seq, len) = self.aStar()
print "A* solution: ", seq
print "A* solution length: ", len
seq.reverse()
return seq
def aStartDrawPath(self,path):
"""draws A* solution path"""
for i in range(len(path)-1):
drawLine(self.mycanvas,path[i],path[i+1],"green")
drawPoint(self.mycanvas,self.end,"green")
def drawPath(self,res,methodname):
"""draws a path"""
path = []
path.append(res.point)
while res.getParent() != None:
path.append(res.getParent().point)
res = res.getParent()
for i in range(len(path)-1):
drawLine(self.mycanvas,path[i],path[i+1],"green")
drawPoint(self.mycanvas,self.end,"green")
path.reverse()
print methodname, " solution: ", path
return path
class Demo:
"""demo class demonstrating 3 search types"""
def __init__(self,nm):
self.num = nm
def showSolutions(self):
"""displays 3 solutions"""
t = navigateSolution(self.num)
t.drawMe()
t.drawPath(t.bfs(), "BFS")
t.startDraw()
t2 = navigateSolution(self.num)
t2.drawMe()
t2.drawPath(t2.dfs(), "DFS")
t2.startDraw()
t3 = navigateSolution(self.num)
t3.drawMe()
t3.aStartDrawPath(t3.aStarSolve())
t3.startDraw()
"""Enter number from 0 to 4 in Demo(NUMBER)"""
x = Demo(2)
x.showSolutions() |
9e23c4a3830d6d00d9f8a5f06a6b970ba45ae042 | deathgaze/cse1310 | /hw06/hw06_task3.py | 3,298 | 4.3125 | 4 | '''
Kirk Sefchik
UTA ID 1000814472
10/14/13
Description: Task 3 (55 points)
This task will implement the functionality of creating a list from a string that contains numbers separated by commas (with possibly blank space between them). For example the string "1,2,3, 4.5, 6.7, 8" would become the list: [1, 2, 3, 4.5, 6.7, 8]. Write the following functions:
is_numeric() - This function has a string parameter and returns True if all the characters in the string are digits, comma, space, or dot. If there are any other characters, the function should return False.
string_to_list() - This function takes a string parameter and returns the list of the numbers in the string. First it should call the is_numeric() function to check that the string has no bad characters (e.g. letters). If there are any bad characters, it should return the empty list. If there are no bad characters it should try to build the list out of teh data in the string. For this it should look at every substring between two consecutive commas. If there is no dot in that substring, then the substring should be converted to an integer. If there is exactly one dot (no more, no less) it should be converted into a float. If any of the substrings between two consecutive commas can not be converted to an int or a float (e.g. "4.5.8" as it has too many dots), the function should still return the empty list. Hint: the split() method may be useful for this task.
main() - The main() function that will get a string from the user, it will then call the string_to_list() function to build a list out of the user string and then print the resulting list. It will next ask the user if they want to continue. If they want to continue, they should eneter 'y'. In that case the function (main) should repeat the previous steps: ask the user for an input, convert it to a list, ask the user again if they want to continue. And so on until the user does not want to continue, in which case he or she should enter 'n'.
Sample run
>>> ================================ RESTART ================================
>>>
Enter a set of numbers (integers or floats) separated by comma: 1,2,3,a
The list is: []
continue ?( y / n): y
Enter a set of numbers (integers or floats) separated by comma: 1,2,3,4.5.8
The list is: []
continue ?( y / n): y
Enter a set of numbers (integers or floats) separated by comma: 1, 2, 3 , 4.5, 6
The list is: [1, 2, 3, 4.5, 6]
continue ?( y / n): n
>>>
'''
def is_numeric(string):
for character in string:
if not character.isnumeric():
if character == ' ' or character == ',' or character == '.':
continue
else:
return False
return True
def string_to_list(l):
if not is_numeric(l):
return []
l = l.split(',')
num_list = []
for chunk in l:
chunk = chunk.strip()
if chunk.count('.') > 1 or ' ' in chunk:
return []
elif '.' in chunk:
num_list.append(float(chunk))
elif '.' not in chunk:
num_list.append(int(chunk))
return num_list
def main():
''' main program function '''
while True:
string = input("Enter a set of numbers (integers or floats) separated by comma: ")
print("The list is:", string_to_list(string))
cont = ''
while cont.lower() != 'y' and cont.lower() != 'n':
cont = input("continue? (y/n): ")
if cont.lower() == 'n':
quit()
main() |
91f9f66291f74b12ba7cb4820073a520732a1b3e | deathgaze/cse1310 | /hw05/hw05_task3.py | 520 | 3.828125 | 4 | # Kirk Sefchik
# UTA ID 1000814472
# 10/03/13
# Description: Show all the actions and states that the machine (the computer) goes through as it runs the folowing program. You must show the state after each instruction is executed.
L = []
x = 13
count = 0
while x > 0:
if (x % 4) == 0:
x = x // 2
else:
if (x % 3) == 0:
x = x // 3
else:
x = x - 1
print(count, x)
L.append([count,x])
count = count + 1
print(count, x)
print("L: ",L)
print("Bye")
|
df5bf198f20b1d5def054a935af800645fc73faa | deathgaze/cse1310 | /hw02/hw02_task1.py | 508 | 4 | 4 | # Kirk Sefchik
# UTA ID 1000814472
# 09/05/13
# Description: displays the quotient of n and 25. also displays the remainder
# (if any)
# Take inputs and perform operations.
denominator = 25
numerator = int(input("n = "))
remainder = numerator % denominator
quotient = numerator // denominator
# Check for remainder and print results
if remainder == 0:
print(numerator, "/", denominator, "=", quotient)
else:
print(numerator, "/", denominator, "=", quotient, "(remainder: ", remainder, ")") |
7e0a96d8d9ddb9e5e0fa5c33419818766298acd6 | Davies-Career-and-Technical-High-School/unit-1-project-silly-sentences-Alex-Rodrigues22 | /silly_sentences.py | 782 | 3.828125 | 4 | print("Let's play Silly Sentences!")
name1 = input("Enter a name: ")
adj1 = input("Enter an adjective: ")
adj2 = input("Enter an adjective: ")
adverb1 = input("Enter an adverb: ")
food1 = input("Enter a food: ")
food2 = input("Enter a food: ")
noun1 = input("Enter a noun: ")
place1 = input("Enter a place: ")
verb1 = input("Enter a verb: ")
print(name1 + " was planning a dream vacation to " + place1 + ".")
print(name1 + " was especially looking forward to trying the local cuisine, including " + adj1 + " " + food1 + " and " + food2 + ".\n")
print(name1 + " will have to practice the language " + adverb1 + " to make it easier to " + verb1 + " with people.\n")
print(name1 + " has a long list of sights to see, including the " + noun1 + " museum and the " + adj2 + " park.") |
3f9d68c2c48571b411c94567c6e33c4b11090a8d | taosenlin/python_file | /sel/day1/作业.py | 1,532 | 3.515625 | 4 | # Time:2020-02-13 21:49
# Author:TSL
from selenium import webdriver
import time
def get_weathermsg():
driver = webdriver.Chrome("D:\\ruanjiananzhuang\chromedriver.exe")
#创建浏览器实例
driver.get("http://www.weather.com.cn/html/province/jiangsu.shtml")
#搜索天气网址
#取出所有城市的天气信息
city_list = driver.find_element_by_id("forecastID")
print(city_list.text)
city_list1 = city_list.text + "\n" #加回车符方便下面切割
weather_msg = city_list1.split("℃\n") #切割出每个城市对应的温度
# print(weather_msg)
driver.quit()
return weather_msg
def get_lowsetemp(weather_msg):
lowset_temp = None #定义一个变量
cities = [] #定义一个空列表,存放城市名
for msg in weather_msg[:-1]:
city_name = msg.split("\n")[0]
# print(city_name)
temp = msg.split("\n")[1]
# print(temp)
low_temp = min([int(one) for one in temp.split("℃/")])
# print(low_temp)
#第一次还没有获取最低温度或者循环获取的当前温度比已经获取的最低温度还要低
if lowset_temp == None or low_temp < lowset_temp:
lowset_temp = low_temp
cities = [city_name]
elif low_temp == lowset_temp:
cities.append(city_name)
print("最低温度是{}℃,城市有{}".format(lowset_temp,cities))
if __name__ == '__main__':
weather_msg = get_weathermsg()
get_lowsetemp(weather_msg)
|
81f33df9eecce588d9b503cd6e92fadbc727d4df | taosenlin/python_file | /untitled/py_sel/dict/2字典-常见操作.py | 790 | 4 | 4 |
dict = {'name':'赵四','sex':'男'}
# (1)测量字典中,键值对的个数
# len()
# print("字典的长度:",len(dict))
#字典的长度: 2
# (2)返回一个包含字典所有KEY的列表
# keys
# print("字典的所有KEY的列表:",dict.keys())
#字典的所有KEY的列表: dict_keys(['name', 'sex'])
# (3)返回一个包含字典所有value的列表
# values
# print("字典的所有value的列表:",dict.values())
#字典的所有value的列表: dict_values(['赵四', '男'])
# (4)返回一个包含所有(键,值)元组的列表
# items
# print("字典的所有(键,值)元组的列表:",dict.items())
# 字典的所有(键,值)元组的列表: dict_items([('name', '赵四'), ('sex', '男')])
|
eb435a425703fb25430a6522ccdd33cd3bcafa75 | deepak-mandal/code | /parentheses.py | 1,424 | 3.921875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'isBalanced' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
class stack:
def __init__(self):
self.items=[]
def is_empty(self):
return self.items==[]
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
return
return self.items.pop()
def isBalanced(s):
# Write your code here
st=stack()
for ch in s:
if ch in '({[':
st.push(ch)
if ch in ')}]':
if st.is_empty():
return "NO"
else:
char=st.pop()
if not match_parentheses(char, ch):
return "NO"
if st.is_empty():
return "YES"
else:
return "NO"
def match_parentheses(leftPar, rightPar):
if leftPar=='[' and rightPar==']':
return True
if leftPar=='{' and rightPar=='}':
return True
if leftPar=='(' and rightPar==')':
return True
return False
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input().strip())
for t_itr in range(t):
s = input()
result = isBalanced(s)
fptr.write(result + '\n')
fptr.close()
|
58f5d5cfa7b6d569b1e5384b46d94190fbc4f507 | maosa/codecademy | /python/ml/logic_gates.py | 5,830 | 4.5 | 4 | ##### LOGIC GATES - PERCEPTRONS PROJECT
"""
In this project, we will use perceptrons to model the fundamental building blocks of computers — logic gates.
For example, the table below shows the results of an AND gate. Given two inputs, an AND gate will output a 1 only if both inputs are a 1:
Input 1 Input 2 Output
0 0 0
0 1 0
1 0 0
1 1 1
We’ll discuss how an AND gate can be thought of as linearly separable data and train a perceptron to perform AND.
We’ll also investigate an XOR gate — a gate that outputs a 1 only if one (but not both) of the inputs is a 1
We’ll think about why an XOR gate isn’t linearly separable and show how a perceptron fails to learn XOR.
"""
##### To begin, let’s think of an AND gate as a dataset of four points. The four points should be the four possible inputs to the AND gate. For example, the first point in the dataset should be [0, 0].
import sys ##### needed for sys.exit()
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product
data = [[0, 0], [1, 0], [0, 1], [1, 1]]
labels = [0, 0, 0, 1]
plt.scatter([point[0] for point in data], [point[1] for point in data], c = labels)
##### Build a perceptron
##### max_iter sets the number of times the perceptron loops through the training data. The default is 1000, so were cutting the training pretty short! Lets see if our algorithm learns AND even with very little training.
classifier = Perceptron(max_iter = 40, tol = -np.infty)
##### tol = -np.infty is used to avoid some warning messages
classifier.fit(data, labels)
##### Note that it is pretty unusual to train and test on the same dataset. In this case, since there are only four possible inputs to AND, were stuck training on every possible input and testing on those same points.
# print(classifier.score(data, labels))
##### Your perceptron should have 100% accuracy! You just taught it an AND gate!
##### Change labels to those for an XOR logic gate
labels = [0, 1, 1, 0]
classifier.fit(data, labels)
# print(classifier.score(data, labels))
##### Change labels to those for an OR logic gate
labels = [0, 1, 1, 1]
classifier.fit(data, labels)
# print(classifier.score(data, labels))
##### We know the perceptron has been trained correctly, but lets try to visualize what decision boundary it is making. Reset your labels to be representing an AND gate.
labels = [0, 0, 0, 1] # AND
# labels = [0, 1, 1, 1] # OR
# labels = [0, 1, 1, 0] # XOR
labels_choice = input('\nChoose a logic gate (numbers represent the outputs to to following data points: [[0, 0], [1, 0], [0, 1], [1, 1]])\n1) AND: 0, 0, 0, 1]\n2) OR: [0, 1, 1, 1]\n3) XOR: [0, 1, 1, 0]\n\n')
if labels_choice == '1':
labels = [0, 0, 0, 1]
gate = 'AND'
elif labels_choice == '2':
labels = [0, 1, 1, 1]
gate = 'OR'
elif labels_choice == '3':
labels = [0, 1, 1, 0]
gate = 'XOR'
else:
sys.exit('\nError! Invalid input!\n')
classifier.fit(data, labels)
##### We know the perceptron has been trained correctly, but lets try to visualize what decision boundary it is making. Reset your labels to be representing an AND gate. Lets first investigate the classifiers .decision_function() method. Given a list of points, this method returns the distance those points are from the decision boundary. The closer the number is to 0, the closer that point is to the decision boundary.
# print(classifier.decision_function([[0, 0], [1, 1], [0.5, 0.5]]))
##### Is the point [0, 0] or the point [1, 1] closer to the decision boundary? >>>>> [1, 1]
##### Even though an input like [0.5, 0.5] isnt a real input to an AND logic gate, we can still check to see how far it is from the decision boundary. We could also do this to the point [0, 0.1], [0, 0.2] and so on. If we do this for a grid of points, we can make a heat map that reveals the decision boundary. To begin, we need to create a list of the points we want to input to .decision_function().
##### x_values should be a list of 100 evenly spaced decimals between 0 and 1
x_values = np.linspace(0, 1, 100)
y_values = np.linspace(0, 1, 100)
##### We have a list of 100 x values and 100 y values. We now want to find every possible combination of those x and y values. The function product will do this for you.
point_grid = list(product(x_values, y_values))
distances = classifier.decision_function(point_grid)
##### Right now distances stores positive and negative values. We only care about how far away a point is from the boundary we dont care about the sign.
abs_distances = [abs(p) for p in distances]
##### Were almost ready to draw the heat map. Were going to be using Matplotlibs pcolormesh() function. Right now, abs_distances is a list of 10000 numbers. pcolormesh needs a two dimensional list. We need to turn abs_distances into a 100 by 100 two dimensional array.
"""
Numpys reshape function does this for us. The code below turns list lst into a 2 by 2 list.
lst = [1, 2 ,3, 4]
new_lst = np.reshape(lst, (2, 2))
new_lst now looks like this:
[[1, 2],[3, 4]]
"""
distances_matrix = np.reshape(abs_distances, (100, 100))
heatmap = plt.pcolormesh(x_values, y_values, distances_matrix)
##### This will put a legend on the heat map
plt.colorbar(heatmap)
plt.title(gate + " logic gate decision boundary")
##### Make sure plt.show() is always the last line of code
plt.show()
##### Change your labels back to representing an OR gate. Where does the decision boundary go? Change your labels to represent an XOR gate. Remember, this data is not linearly separable. Where does the decision boundary go?
##### Perceptrons cant solve problems that arent linearly separable. However, if you combine multiple perceptrons together, you now have a neural net that can solve these problems!
|
2758434c33b732d60d058fb5a9688e5a41759fe6 | maosa/codecademy | /python/ml/k_means.py | 17,786 | 4.3125 | 4 | ##### K-MEANS CLUSTERING
"""
>>>>> Introduction to Clustering
Often, the data you encounter in the real world won’t have flags attached and won’t provide labeled answers to your question. Finding patterns in this type of data, unlabeled data, is a common theme in many machine learning applications. Unsupervised Learning is how we find patterns and structure in these data.
Clustering is the most well-known unsupervised learning technique. It finds structure in unlabeled data by identifying similar groups, or clusters. Examples of clustering applications are:
1) Recommendation engines: group products to personalize the user experience
2) Search engines: group news topics and search results
3) Market segmentation: group customers based on geography, demography, and behaviors
4) Image segmentation: medical imaging or road scene segmentation on self-driving cars
The goal of clustering is to separate data so that data similar to one another are in the same group, while data different from one another are in different groups. So two questions arise:
- How many groups do we choose?
- How do we define similarity?
K-Means is the most popular and well-known clustering algorithm, and it tries to address these two questions.
The “K” refers to the number of clusters (groups) we expect to find in a dataset.
The “Means” refers to the average distance of data to each cluster center, also known as the centroid, which we are trying to minimize.
It is an iterative approach:
1) Place k random centroids for the initial clusters.
2) Assign data samples to the nearest centroid.
3) Update centroids based on the above-assigned data samples.
Repeat Steps 2 and 3 until convergence (when points don’t move between clusters and centroids stabilize).
Once we are happy with our clusters, we can take a new unlabeled datapoint and quickly assign it to the appropriate cluster.
Before we implement the K-means algorithm, let’s find a dataset. The sklearn package embeds some datasets and sample images. One of them is the Iris dataset.
The Iris dataset consists of measurements of sepals and petals of 3 different plant species:
- Iris setosa
- Iris versicolor
- Iris virginica
The sepal is the part that encases and protects the flower when it is in the bud stage. A petal is a leaflike part that is often colorful.
From sklearn library, import the datasets module:
from sklearn import datasets
To load the Iris dataset:
iris = datasets.load_iris()
We call each piece of data a sample. For example, each flower is one sample.
Each characteristic we are interested in is a feature. For example, petal length is a feature of this dataset.
The features of the dataset are:
Column 0: Sepal length
Column 1: Sepal width
Column 2: Petal length
Column 3: Petal width
The 3 species of Iris plants are what we are going to cluster later in this lesson.
Every dataset from sklearn comes with a bunch of different information (not just the data) and is stored in a similar fashion.
First, let’s take a look at the most important thing, the sample data:
print(iris.data)
Each row is a plant!
Since the datasets in sklearn datasets are used for practice, they come with the answers (target values) in the target key:
Take a look at the target values:
print(iris.target)
The iris.target values give the ground truth for the Iris dataset. Ground truth, in this case, is the number corresponding to the flower that we are trying to learn.
It is always a good idea to read the descriptions of the data:
print(iris.DESCR)
Expand the terminal (right panel):
When was the Iris dataset published?
What is the unit of measurement?
>>>>> Visualize Before K-Means
To get a better sense of the data in the iris.data matrix, let’s visualize it!
With Matplotlib, we can create a 2D scatter plot of the Iris dataset using two of its features (sepal length vs. petal length). The sepal length measurements are stored in column 0 of the matrix, and the petal length measurements are stored in column 2 of the matrix.
But how do we get these values?
Suppose we only want to retrieve the values that are in column 0 of a matrix, we can use the NumPy/Pandas notation [:,0] like so:
matrix[:,0]
[:,0] can be translated to [all_rows , column_0]
Once you have the measurements we need, we can make a scatter plot by:
plt.scatter(x, y)
plt.show()
"""
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
##### Store iris.data
samples = iris.data
##### Create x and y
x = samples[:, 0]
y = samples[:, 1]
##### Plot x and y
plt.scatter(x, y, alpha = 0.5)
##### Show the plot
plt.show()
"""
>>>>> Implementing K-Means: Step 1
The K-Means algorithm:
1) Place k random centroids for the initial clusters.
2) Assign data samples to the nearest centroid.
3) Update centroids based on the above-assigned data samples.
Repeat Steps 2 and 3 until convergence.
After looking at the scatter plot and having a better understanding of the Iris data, let’s start implementing the K-Means algorithm.
In this exercise, we will implement Step 1.
Because we expect there to be three clusters (for the three species of flowers), let’s implement K-Means where the k is 3.
Using the NumPy library, we will create 3 random initial centroids and plot them along with our samples.
Use NumPy’s random.uniform() function to generate random values in two lists:
a centroids_x list that will have k random values between min(x) and max(x)
a centroids_y list that will have k random values between min(y) and max(y)
The random.uniform() function looks like:
np.random.uniform(low, high, size)
The centroids_x will have the x-values for our initial random centroids and the centroids_y will have the y-values for our initial random centroids.
Create an array named centroids and use the zip() function to add centroids_x and centroids_y to it.
The zip() function looks like:
np.array(list(zip(array1, array2)))
Then, print centroids.
The centroids list should now have all the initial centroids.
"""
import numpy as np
##### Number of clusters
k = 3
##### Create x coordinates of k random centroids
centroids_x = np.random.uniform(min(x), max(x), k)
##### Create y coordinates of k random centroids
centroids_y = np.random.uniform(min(y), max(y), k)
##### Create centroids array
centroids = np.array(list(zip(centroids_x, centroids_y)))
print(centroids)
##### Make a scatter plot of x, y
plt.scatter(y, x)
##### Make a scatter plot of the centroids
plt.scatter(centroids_x, centroids_y)
##### Display plot
plt.show()
"""
>>>>> Implementing K-Means: Step 2
Assign data samples to the nearest centroid.
In this exercise, we will implement Step 2.
Now we have the 3 random centroids. Let’s assign data points to their nearest centroids.
To do this we’re going to use the Distance Formula to write a distance() function. Then, we are going to iterate through our data samples and compute the distance from each data point to each of the 3 centroids.
Suppose we have a point and a list of three distances in distances and it looks like [15, 20, 5], then we would want to assign the data point to the 3rd centroid. The argmin(distances) would return the index of the lowest corresponding distance, 2, because the index 2 contains the minimum value.
Create an array called labels that will hold the cluster labels for each data point. Its size should be the length of the data sample.
It should look something like:
[ 0. 0. 0. 0. 0. 0. ... 0.]
Create an array called distances that will hold the distances for each centroid. It should have the size of k.
It should look something like:
[ 0. 0. 0.]
"""
iris = datasets.load_iris()
samples = iris.data
x = samples[:,0]
y = samples[:,1]
sepal_length_width = np.array(list(zip(x, y)))
##### Step 2: Assign samples to nearest centroid
##### Distance formula
def distance(a, b):
one = (a[0] - b[0])**2
two = (a[1] - b[1])**2
distance = (one + two)**0.5
return distance
labels = np.zeros(len(samples))
distances = np.zeros(k)
##### Cluster labels for each point (either 0, 1, or 2)
for i in range(len(samples)):
##### Distances to each centroid
distances[0] = distance(sepal_length_width[i], centroids[0])
distances[1] = distance(sepal_length_width[i], centroids[1])
distances[2] = distance(sepal_length_width[i], centroids[2])
##### Assign to the closest centroid
cluster = np.argmin(distances)
labels[i] = cluster
##### Print labels
print(labels)
"""
>>>>> Implementing K-Means: Step 3
In this exercise, we will implement Step 3.
Find new cluster centers by taking the average of the assigned points. To find the average of the assigned points, we can use the .mean() function.
Save the old centroids value before updating.
Use:
from copy import deepcopy
Store centroids into centroids_old using deepcopy():
centroids_old = deepcopy(centroids)
Then, create a for loop that iterates k times.
Since k = 3, as we are iterating through the forloop each time, we can calculate mean of the points that have the same cluster label.
Inside the for loop, create an array named points where we get all the data points that have the cluster label i.
Then, calculate the mean of those points using .mean() to get the new centroid.
"""
from copy import deepcopy
##### Step 3: Update centroids
centroids_old = deepcopy(centroids)
for i in range(k):
points = [sepal_length_width[j] for j in range(len(sepal_length_width)) if labels[j] == i]
##### OR use a nested for loop
# for n in range(k):
# points = []
# for j in range(len(sepal_length_width)):
# if labels[j] == i:
# points.append(sepal_length_width[j])
##### We need the axis=0 here to specify that we want to compute the means along the rows
centroids[i] = np.mean(points, axis = 0)
print(centroids_old)
print(centroids)
"""
>>>>> Implementing K-Means: Step 4 (Repeat Steps 2 and 3 until convergence)
This is the part of the algorithm where we repeatedly execute Step 2 and 3 until the centroids stabilize (convergence).
We can do this using a while loop. And everything from Step 2 and 3 goes inside the loop.
For the condition of the while loop, we need to create an array named errors. In each error index, we calculate the difference between the updated centroid (centroids) and the old centroid (centroids_old).
The loop ends when all three values in errors are 0.
"""
iris = datasets.load_iris()
samples = iris.data
x = samples[:,0]
y = samples[:,1]
sepal_length_width = np.array(list(zip(x, y)))
##### Step 1: Place K random centroids
k = 3
centroids_x = np.random.uniform(min(x), max(x), size=k)
centroids_y = np.random.uniform(min(y), max(y), size=k)
centroids = np.array(list(zip(centroids_x, centroids_y)))
def distance(a, b):
one = (a[0] - b[0]) ** 2
two = (a[1] - b[1]) ** 2
distance = (one + two) ** 0.5
return distance
##### To store the value of centroids when it updates
centroids_old = np.zeros(centroids.shape)
##### Cluster labeles (either 0, 1, or 2)
labels = np.zeros(len(samples))
distances = np.zeros(3)
##### Initialize error:
#### Use the distance() function to calculate the distance between the updated centroid and the old centroid and put them in error
error = np.zeros(3)
error[0] = distance(centroids[0], centroids_old[0])
error[1] = distance(centroids[1], centroids_old[1])
error[2] = distance(centroids[2], centroids_old[2])
##### Repeat Steps 2 and 3 until convergence:
while error.all() != 0:
##### Step 2: Assign samples to nearest centroid
for i in range(len(samples)):
distances[0] = distance(sepal_length_width[i], centroids[0])
distances[1] = distance(sepal_length_width[i], centroids[1])
distances[2] = distance(sepal_length_width[i], centroids[2])
cluster = np.argmin(distances)
labels[i] = cluster
error = np.zeros(3)
##### Step 3: Update centroids
centroids_old = deepcopy(centroids)
for i in range(3):
points = [sepal_length_width[j] for j in range(len(sepal_length_width)) if labels[j] == i]
centroids[i] = np.mean(points, axis=0)
error[0] = distance(centroids[0], centroids_old[0])
error[1] = distance(centroids[1], centroids_old[1])
error[2] = distance(centroids[2], centroids_old[2])
colors = ['r', 'g', 'b']
for i in range(k):
points = np.array([sepal_length_width[j] for j in range(len(sepal_length_width)) if labels[j] == i])
plt.scatter(points[:, 0], points[:, 1], c = colors[i], alpha = 0.5)
##### Here, we are visualizing all the points in each of the labels a different color
plt.scatter(centroids[:, 0], centroids[:, 1], marker = 'D', s = 150)
plt.xlabel('sepal length (cm)')
plt.ylabel('sepal width (cm)')
plt.show()
"""
>>>>> Implementing K-Means: Scikit-Learn
Instead of implementing K-Means from scratch, the sklearn.cluster module has many methods that can do this for you.
To import KMeans from sklearn.cluster:
from sklearn.cluster import KMeans
For Step 1, use the KMeans() method to build a model that finds k clusters. To specify the number of clusters (k), use the n_clusters keyword argument:
model = KMeans(n_clusters = k)
For Steps 2 and 3, use the .fit() method to compute K-Means clustering:
model.fit(X)
After K-Means, we can now predict the closest cluster each sample in X belongs to. Use the .predict() method to compute cluster centers and predict cluster index for each sample:
model.predict(X)
"""
from sklearn import datasets
##### From sklearn.cluster, import KMeans class
from sklearn.cluster import KMeans
iris = datasets.load_iris()
samples = iris.data
##### Use KMeans() to create a model that finds 3 clusters
model = KMeans(n_clusters = 3)
##### Use .fit() to fit the model to samples
model.fit(samples)
##### Use .predict() to determine the labels of samples
model.predict(samples)
##### Print the labels
print(model.predict(samples))
new_samples = np.array([[5.7, 4.4, 1.5, 0.4], [6.5, 3. , 5.5, 0.4], [5.8, 2.7, 5.1, 1.9]])
print(new_samples)
"""
>>>>> Visualize After K-Means
We have done the following using sklearn library:
- Load the embedded dataset
- Compute K-Means on the dataset (where k is 3)
- Predict the labels of the data samples
And the labels resulted in either 0, 1, or 2.
Let’s finish it by making a scatter plot of the data again!
This time, however, use the labels numbers as the colors.
To edit colors of the scatter plot, we can set c = labels
"""
x = samples[:, 0]
y = samples[:, 1]
plt.scatter(x, y, c = labels, alpha = 0.5)
plt.show()
"""
>>>>> Evaluation
At this point, we have clustered the Iris data into 3 different groups (implemented using Python and using scikit-learn). But do the clusters correspond to the actual species? Let’s find out!
First, remember that the Iris dataset comes with target values:
target = iris.target
It looks like:
[ 0 0 0 0 0 ... 2 2 2]
According to the metadata:
All the 0‘s are Iris-setosa
All the 1‘s are Iris-versicolor
All the 2‘s are Iris-virginica
Let’s change these values into the corresponding species using the following code:
species = np.chararray(target.shape, itemsize=150)
for i in range(len(samples)):
if target[i] == 0:
species[i] = 'setosa'
elif target[i] == 1:
species[i] = 'versicolor'
elif target[i] == 2:
species[i] = 'virginica'
Then we are going to use the Pandas library to perform a cross-tabulation.
Cross-tabulations enable you to examine relationships within the data that might not be readily apparent when analyzing total survey responses.
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.cluster import KMeans
import pandas as pd
iris = datasets.load_iris()
samples = iris.data
target = iris.target
model = KMeans(n_clusters=3)
model.fit(samples)
labels = model.predict(samples)
species = np.chararray(target.shape, itemsize = 150)
for i in range(len(samples)):
if target[i] == 0:
species[i] = 'setosa'
elif target[i] == 1:
species[i] == 'versicolor'
elif target[i] == 2:
species[i] == 'virginica'
df = pd.DataFrame({'labels': labels, 'species': species})
print(df)
##### Use the the crosstab() method to perform cross-tabulation
ct = pd.crosstab(df['labels'], df['species'])
print(ct)
"""
>>>>> The Number of Clusters
At this point, we have grouped the Iris plants into 3 clusters. But suppose we didn’t know there are three species of Iris in the dataset, what is the best number of clusters? And how do we determine that?
Before we answer that, we need to define what is a good cluster?
Good clustering results in tight clusters, meaning that the samples in each cluster are bunched together. How spread out the clusters are is measured by inertia. Inertia is the distance from each sample to the centroid of its cluster. The lower the inertia is, the better our model has done.
You can check the inertia of a model by:
print(model.inertia_)
For the Iris dataset, if we graph all the ks (number of clusters) with their inertias.
Notice how the graph keeps decreasing.
Ultimately, this will always be a trade-off. The goal is to have low inertia and the least number of clusters.
One of the ways to interpret this graph is to use the elbow method: choose an “elbow” in the inertia plot - when inertia begins to decrease more slowly.
In the graph above, 3 is the optimal number of clusters.
"""
num_clusters = list(range(1, 9))
inertias = []
for k in num_clusters:
model = KMeans(n_clusters = k)
model.fit(samples)
inertias.append(model.inertia_)
plt.plot(num_clusters, inertias, '-o')
plt.xlabel('Number of Clusters (k)')
plt.ylabel('Inertia')
plt.show()
|
fd46f768c7d22f46892f7c99f56ec1d5f2b5faa9 | maosa/codecademy | /python/ml/perceptron.py | 13,676 | 4.375 | 4 | ##### PERCEPTRON
"""
>>>>> What is a Perceptron?
Similar to how atoms are the building blocks of matter and how microprocessors are the building blocks of a computer, perceptrons are the building blocks of Neural Networks.
If you look closely, you might notice that the word “perceptron” is a combination of two words:
Perception (noun) the ability to sense something
Neuron (noun) a nerve cell in the human brain that turns sensory input into meaningful information
Therefore, the perceptron is an artificial neuron that simulates the task of a biological neuron to solve problems through its own “sense” of the world.
>>>>> Representing a Perceptron
So the perceptron is an artificial neuron that can make a simple decision. Let’s implement one from scratch in Python!
The perceptron has three main components:
1) Inputs: Each input corresponds to a feature. For example, in the case of a person, features could be age, height, weight, college degree, etc.
2) Weights: Each input also has a weight which assigns a certain amount of importance to the input. If an input’s weight is large, it means this input plays a bigger role in determining the output. For example, a team’s skill level will have a bigger weight than the average age of players in determining the outcome of a match.
3) Output: Finally, the perceptron uses the inputs and weights to produce an output. The type of the output varies depending on the nature of the problem. For example, to predict whether or not it’s going to rain, the output has to be binary — 1 for Yes and 0 for No. However, to predict the temperature for the next day, the range of the output has to be larger — say a number from 70 to 90.
>>>>> Step 1: Weighted Sum
Great! Now that you understand the structure of the perceptron, here’s an important question — how are the inputs and weights magically turned into an output? This is a two-step process, and the first step is finding the weighted sum of the inputs.
>>>>> Step 2: Activation Function
After finding the weighted sum, the second step is to constrain the weighted sum to produce a desired output.
Why is that important? Imagine if a perceptron had inputs in the range of 100-1000 but the goal was to simply predict whether or not something would occur — 1 for “Yes” and 0 for “No”. This would result in a very large weighted sum.
How can the perceptron produce a meaningful output in this case? This is exactly where activation functions come in! These are special functions that transform the weighted sum into a desired and constrained output.
For example, if you want to train a perceptron to detect whether a point is above or below a line (which we will be doing in this lesson!), you might want the output to be a +1 or -1 label. For this task, you can use the “sign activation function” to help the perceptron make the decision:
If weighted sum is positive, return +1
If weighted sum is negative, return -1
In this lesson, we will focus on using the sign activation function because it is the simplest way to get started with perceptrons and eventually visualize one in action.
>>>>> Training the Perceptron
Our perceptron can now make a prediction given inputs, but how do we know if it gets those predictions right?
Right now we expect the perceptron to be very bad because it has random weights. We haven’t taught it anything yet, so we can’t expect it to get classifications correct! The good news is that we can train the perceptron to produce better and better results! In order to do this, we provide the perceptron a training set — a collection of random inputs with correctly predicted outputs.
On the right, you can see a plot of scattered points with positive and negative labels. This is a simple training set.
In the code, the training set has been represented as a dictionary with coordinates as keys and labels as values. For example:
training_set = {(18, 49): -1, (2, 17): 1, (24, 35): -1, (14, 26): 1, (17, 34): -1}
We can measure the perceptron’s actual performance against this training set. By doing so, we get a sense of “how bad” the perceptron is. The goal is to gradually nudge the perceptron — by slightly changing its weights — towards a better version of itself that correctly matches all the input-output pairs in the training set.
We will use these points to train the perceptron to correctly separate the positive labels from the negative labels by visualizing the perceptron as a line. Stay tuned!
>>>>> Training Error
Now that we have our training set, we can start feeding inputs into the perceptron and comparing the actual outputs against the expected labels!
Every time the output mismatches the expected label, we say that the perceptron has made a training error — a quantity that measures “how bad” the perceptron is performing.
As mentioned in the last exercise, the goal is to nudge the perceptron towards zero training error. The training error is calculated by subtracting the predicted label value from the actual label value.
training_error = actual_label - predicted_label
For each point in the training set, the perceptron either produces a +1 or a -1 (as we are using the Sign Activation Function). Since the labels are also a +1 or a -1, there are four different possibilities for the error the perceptron makes:
Actual Predicted Training Error
+1 +1 0
+1 -1 2
-1 -1 0
-1 +1 -2
These training error values will be crucial in improving the perceptron’s performance as we will see in the upcoming exercises.
>>>>> Tweaking the Weights
What do we do once we have the errors for the perceptron? We slowly nudge the perceptron towards a better version of itself that eventually has zero error.
The only way to do that is to change the parameters that define the perceptron. We can’t change the inputs so the only thing that can be tweaked are the weights. As we change the weights, the outputs change as well.
The goal is to find the optimal combination of weights that will produce the correct output for as many points as possible in the dataset.
>>>>> The Perceptron Algorithm
But one question still remains — how do we tweak the weights optimally? We can’t just play around randomly with the weights until the correct combination magically pops up. There needs to be a way to guarantee that the perceptron improves its performance over time.
This is where the Perceptron Algorithm comes in. The math behind why this works is outside the scope of this lesson, so we’ll directly apply the algorithm to optimally tweak the weights and nudge the perceptron towards zero error.
The most important part of the algorithm is the update rule where the weights get updated:
weight = weight + (error * input)
We keep on tweaking the weights until all possible labels are correctly predicted by the perceptron. This means that multiple passes might need to be made through the training_set before the Perceptron Algorithm comes to a halt.
In this exercise, you will continue to work on the .training() method. We have made the following changes to this method from the last exercise:
- foundLine = False (a boolean that indicates whether the perceptron has found a line to separate the positive and negative labels)
- while not foundLine: (a while loop that continues to train the perceptron until the line is found)
- total_error = 0 (to count the total error the perceptron makes in each round)
- total_error += abs(error) (to update the total error the perceptron makes in each round)
>>>>> The Bias Weight
You have understood that the perceptron can be trained to produce correct outputs by tweaking the regular weights.
However, there are times when a minor adjustment is needed for the perceptron to be more accurate. This supporting role is played by the bias weight. It takes a default input value of 1 and some random weight value.
So now the weighted sum equation should look like:
weighted_sum = x1w1 + x2w2 + x3w3 + ... + xnwn + 1w
How does this change the code so far? You only have to consider two small changes:
Add a 1 to the set of inputs (now there are 3 inputs instead of 2)
Add a bias weight to the list of weights (now there are 3 weights instead of 2)
>>>>> Representing a Line
So far so good! The perceptron works as expected, but everything seems to be taking place behind the scenes. What if we could visualize the perceptron’s training process to gain a better understanding of what’s going on?
The weights change throughout the training process so if only we could meaningfully visualize those weights …
Turns out we can! In fact, it gets better. The weights can actually be used to represent a line! This greatly simplifies our visualization.
You might know that a line can be represented using the slope-intercept form. A perceptron’s weights can be used to find the slope and intercept of the line that the perceptron represents.
slope = -self.weights[0]/self.weights[1]
intercept = -self.weights[2]/self.weights[1]
The explanation for these equations is beyond the scope of this lesson, so we’ll just use them to visualize the perceptron for now.
>>>>> Finding a Linear Classifier
Let’s recap what you just learned!
The perceptron has inputs, weights, and an output. The weights are parameters that define the perceptron and they can be used to represent a line. In other words, the perceptron can be visualized as a line.
What does it mean for the perceptron to correctly classify every point in the training set?
Theoretically, it means that the perceptron predicted every label correctly.
Visually, it means that the perceptron found a linear classifier, or a decision boundary, that separates the two distinct set of points in the training set.
"""
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
# from perceptron import Perceptron, lines
def generate_training_set(num_points):
x_coordinates = [random.randint(0, 50) for i in range(num_points)]
y_coordinates = [random.randint(0, 50) for i in range(num_points)]
training_set = dict()
for x, y in zip(x_coordinates, y_coordinates):
if x <= 45-y:
training_set[(x,y,1)] = 1
elif x > 45-y:
training_set[(x,y,1)] = -1
return training_set
training_set = generate_training_set(30)
x_plus = []
y_plus = []
x_minus = []
y_minus = []
for data in training_set:
if training_set[data] == 1:
x_plus.append(data[0])
y_plus.append(data[1])
elif training_set[data] == -1:
x_minus.append(data[0])
y_minus.append(data[1])
##### CUSTOM DEFINITION OF THE PERCEPTRON CLASS
lines = []
class Perceptron:
def __init__(self, num_inputs=3, weights=[1,1,1]):
self.num_inputs = num_inputs
self.weights = weights
def weighted_sum(self, inputs):
weighted_sum = 0
for i in range(self.num_inputs):
weighted_sum += self.weights[i]*inputs[i]
return weighted_sum
def activation(self, weighted_sum):
if weighted_sum >= 0:
return 1
if weighted_sum < 0:
return -1
def training(self, training_set):
foundLine = False
while not foundLine:
total_error = 0
for inputs in training_set:
prediction = self.activation(self.weighted_sum(inputs))
actual = training_set[inputs]
error = actual - prediction
total_error += abs(error)
for i in range(self.num_inputs):
self.weights[i] += error*inputs[i]
slope = -self.weights[0]/self.weights[1]
intercept = -self.weights[2]/self.weights[1]
y1 = (slope * 0) + intercept
y2 = (slope * 50) + intercept
lines.append([[0,50], [y1, y2]])
if total_error == 0:
foundLine = True
cool_perceptron = Perceptron()
perceptron = Perceptron()
perceptron.training(training_set)
fig = plt.figure()
ax = plt.axes(xlim = (-25, 75), ylim=(-25, 75))
line, = ax.plot([], [], lw = 2)
fig.patch.set_facecolor('#ffc107')
plt.scatter(x_plus, y_plus, marker = '+', c = 'green', s = 128, linewidth = 2)
plt.scatter(x_minus, y_minus, marker = '_', c = 'red', s = 128, linewidth = 2)
plt.title('Iteration: 0')
def animate(i):
print(i)
line.set_xdata(lines[i][0]) # update the data
line.set_ydata(lines[i][1]) # update the data
return line,
def init():
line.set_data([], [])
return line,
ani = animation.FuncAnimation(fig, animate, frames = 1, init_func = init, interval = 50, blit = True, repeat = False)
plt.show()
"""
>>>>> What's Next? Neural Networks
Congratulations! You have now built your own perceptron from scratch.
Let’s step back and think about what you just accomplished and see if there are any limits to a single perceptron.
Earlier, the data points in the training set were linearly separable i.e. a single line could easily separate the two dissimilar sets of points.
What would happen if the data points were scattered in such a way that a line could no longer classify the points? A single perceptron with only two inputs wouldn’t work for such a scenario because it cannot represent a non-linear decision boundary.
That’s when more perceptrons and features come into play!
By increasing the number of features and perceptrons, we can give rise to the Multilayer Perceptrons, also known as Neural Networks, which can solve much more complicated problems.
With a solid understanding of perceptrons, you are now ready to dive into the incredible world of Neural Networks!
"""
|
9aa7b00b7246318c9a818b91b155b257c2eed8ed | maosa/codecademy | /python/basics/pandas_part3.py | 6,026 | 4.34375 | 4 | ###################
##### PANDAS PART 3
import pandas as pd
import numpy as np
sales = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/sales.csv')
print(sales)
targets = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/targets.csv')
print(targets)
men_women = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/men_women_sales.csv')
print(men_women)
##### Merge 2 dataframes
df = pd.merge(sales, targets)
print(df)
##### Merge multiple dataframes
all_data = sales.merge(targets).merge(men_women)
print(all_data)
results = all_data[(all_data.revenue > all_data.target) & (all_data.women > all_data.men)]
print(results)
orders = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/orders2.csv')
print(orders)
products = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/products.csv')
print(products)
##### Rename id column to product_id to avoid dataframes being wrongly merged
orders_products = pd.merge(orders, products.rename(columns={'id':'product_id'}))
print(orders_products)
"""
In the example below, the “left” table is the one that comes first (orders), and the “right” table is the one that comes second (customers).
This syntax says that we should match the customer_id from orders to the id in customers.
The new column names id_x and id_y aren’t very helpful for us when we read the table. We can help make them more useful by using the keyword suffixes. We can provide a list of suffixes to use instead of “_x” and “_y”.
pd.merge(
orders,
customers,
left_on='customer_id',
right_on='id',
suffixes=['_order', '_customer']
)
"""
orders_products = pd.merge(
orders,
products,
left_on='product_id',
right_on='id',
suffixes=['_orders', '_products']
)
print(orders_products)
"""
When we merge two DataFrames whose rows don’t match perfectly, we lose the unmatched rows. This type of merge (where we only include matching rows) is called an inner merge.
For an outer merge use: pd.merge(df1, df2, how='outer')
"""
#####
"""
Left Merge
Suppose we want to identify which customers are missing phone information. We would want a list of all customers who have email, but don’t have phone.
We could get this by performing a Left Merge. A Left Merge includes all rows from the first (left) table, but only rows from the second (right) table that match the first table.
For this command, the order of the arguments matters. If the first DataFrame is company_a and we do a left join, we’ll only end up with rows that appear in company_a.
By listing company_a first, we get all customers from Company A, and only customers from Company B who are also customers of Company A.
Use the following command: pd.merge(df1, df2, how='left')
Right merge applies the exact opposite approach.
"""
#####
"""
When we need to reconstruct a single DataFrame from multiple smaller DataFrames, we can use the method pd.concat([df1, df2, df2, ...]). This method only works if all of the columns are the same in all of the DataFrames.
Use the following: pd.concat([df1, df2])
Note that a LIST of dataframes is passed into pd.concat()
"""
#########################################
##### Page Visits Funnel - Pandas Project
visits = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/visits.csv', parse_dates=[1])
cart = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/cart.csv', parse_dates=[1])
checkout = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/checkout.csv', parse_dates=[1])
purchase = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/purchase.csv', parse_dates=[1])
print(visits.head())
print(cart.head())
print(checkout.head())
print(purchase.head())
##### Merge visits and cart
visits_cart = pd.merge(visits, cart, how='left')
print(visits_cart.head())
print(len(visits_cart)) # number of rows
print(len(visits_cart[visits_cart.cart_time.isnull()])) # number of null timestamps
pct_no_t = (len(visits_cart[visits_cart.cart_time.isnull()]) * 100)/len(visits_cart)
print("\n%d%% percent of users who visited the site did not place a t-shirt in their cart\n" % pct_no_t)
##### Merge cart and checkout
cart_checkout = pd.merge(cart, checkout, how='left')
print(cart_checkout.head())
print(len(cart_checkout)) # number of rows
print(len(cart_checkout[cart_checkout.checkout_time.isnull()]))
pct_no_checkout = (len(cart_checkout[cart_checkout.checkout_time.isnull()]) * 100)/len(cart_checkout)
print("\n%d%% percent of users who placed a t-shirt in their cart did not procede to checkout\n" % pct_no_checkout)
##### Merge all using left merges
all_data = visits.merge(cart, how='left').merge(checkout, how='left').merge(purchase, how='left')
print(all_data.head)
print("\nall_data has "+ str(len(all_data)) + " rows\n")
##### Merge checkout and purchase
checkout_purchase = pd.merge(checkout, purchase, how='left')
print(checkout_purchase.head())
print(len(checkout_purchase)) # number of rows
print(len(checkout_purchase[checkout_purchase.purchase_time.isnull()]))
pct_no_purchase = (len(checkout_purchase[checkout_purchase.purchase_time.isnull()]) * 100)/len(checkout_purchase)
print("\n%d%% percent of users who proceded to checkout did not purchase a t-shirt\n" % pct_no_purchase)
#####
print("% of nulls in visit_time: " + str(len(all_data[all_data.visit_time.isnull()]) * 100 / len(all_data)))
print("% of nulls in cart_time: " + str(len(all_data[all_data.cart_time.isnull()]) * 100 / len(all_data)))
print("% of nulls in checkout_time: " + str(len(all_data[all_data.checkout_time.isnull()]) * 100 / len(all_data)))
print("% of nulls in purchase_time: " + str(len(all_data[all_data.purchase_time.isnull()]) * 100 / len(all_data)))
#####
all_data['time_to_purchase'] = all_data.purchase_time - all_data.visit_time
print("\nAverage time from initial visit to purchase: " + str(all_data.time_to_purchase.mean()) + "\n")
|
f8d2873a56e915681c5a4229c9a842626e6f10bd | wonghoifung/learning-python | /r2_5.py | 463 | 3.8125 | 4 | text = 'yes,no,yes,no'
text = text.replace('yes','yep')
print text
text = '11/1/2015, 12/30/2014'
import re
print re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
pat = re.compile(r'(\d+)/(\d+)/(\d+)')
print pat.sub(r'\3:\1:\2', text)
from calendar import month_abbr
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
print pat.sub(change_date, text)
print pat.subn(change_date, text) |
4ad91e1cd661f5b7ce3b6c0960cb022136275e0a | testergitgitowy/calendar-checker | /main.py | 2,618 | 4.15625 | 4 | import datetime
import calendar
def name(decision):
print("Type period of time (in years): ", end = "")
while True:
try:
period = abs(int(input()))
except:
print("Must be an integer (number). Try again: ", end = "")
else:
break
period *= 12
print("Type the day you want to check for (1-Monday, 7-Sunday")
while True:
try:
choosed_day = int(input())
if 1 <= choosed_day <= 7:
break
else:
print("Wrong number. Pass an integer in range (1-7): ", end = "")
except:
print("Must be an integer in range (1-7). Type again: ", end = "")
day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year
startdate=datetime.datetime(year, month, day)
d = startdate
match_amount = 0
month_amount = 0
control = 0
while(period > 0):
period -= 1
if d.weekday() == choosed_day - 1:
if control == 0 and decision == 1:
print("Month's found: ")
control = 1
if control == 0 and decision == 0:
control = 1
match_amount += 1
if decision == 1:
print(calendar.month(d.year,d.month))
if d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
d = d.replace (month = 12, year = year1)
month_amount += 1
diff = abs(d - startdate)
elif d.month != 1:
month1 = d.month - 1
d = d.replace (month = month1)
month_amount += 1
else:
year1 = d.year - 1
month1 = 12
d = d.replace (month = month1, year = year1)
month_amount += 1
if control == 0:
print("No matching were found.\nProbability: 0\nProbability expected: ", 1/7)
else:
print("Number of months found: ", match_amount)
print("Number of months checked: ", month_amount)
print("Number of days: ", diff.days)
print("Probability found: ", match_amount/month_amount)
print("Probability expected: ", 1/7)
if decision == 1:
print("Range of research:\nStarting month:")
print(calendar.month(startdate.year, startdate.month))
print("Final month:",)
print(calendar.month(d.year, d.month))
print("Do you want to print out all of founded months?: [1/y][n/0]", end = " ")
true = ['1','y','Y','yes','YES','YEs','YeS','Yes','ye','Ye','YE']
false = ['0','no','NO','nO','No','n','N']
while True:
decision = input()
if decision in true:
decision = 1
break
elif decision in false:
decision = 0
break
else:
print("Wrong input. Try again: ")
name(decision) |
a485ed23f0437665d6fcaf057b2f961aaa714000 | Kruti235/111 | /main.py | 2,582 | 3.609375 | 4 | import csv
import pandas as pd
import random
import statistics
import plotly.figure_factory as ff
import plotly.graph_objects as go
df= pd.read_csv("studentMarks.csv")
data = df["Math_score"].tolist()
#fig= ff.create_distplot([data],["Math Scores"], show_hist=False)
#fig.show()
mean = statistics.mean(data)
std_deviation = statistics.stdev(data)
print("mean of population=",mean)
print("std_deviation of population=",std_deviation)
def random_set_of_mean(counter):
dataset = []
for i in range(0,counter):
random_index = random.randint(0, len(data)-1)
value = data[random_index]
dataset.append(value)
mean = statistics.mean(dataset)
return mean
mean_list =[]
for i in range(0,1000):
set_of_means = random_set_of_mean(100)
mean_list.append(set_of_means)
std_deviation= statistics.stdev(mean_list)
mean = statistics.mean(mean_list)
print("mean of sampling distribution=",mean)
print("std_deviation of sampling distribution=",std_deviation)
fig = ff.create_distplot([mean_list],["student marks"], show_hist=False)
fig.show()
#finding the mean of the students who iused Math practice App
df= pd.read_csv("School_1_Sample.csv")
data= df["Math_score"].tolist()
mean_of_sample1=statistics.mean(data)
print("mean of sample1=",mean_of_sample1)
fig=ff.create_distplot([mean_list],["students marks"], show_hist= False)
fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode="lines", name="MEAN"))
fig.add_trace(go.Scatter(x=[mean_of_sample1, mean_of_sample1], y=[0, 0.17], mode="lines", name="MEAN OF SAMPLE"))
fig.show()
#second intervention
df= pd.read_csv("School_2_Sample.csv")
data= df["Math_score"].tolist()
mean_of_sample2=statistics.mean(data)
print("mean of sample2=",mean_of_sample2)
fig=ff.create_distplot([mean_list],["students marks"], show_hist= False)
fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode="lines", name="MEAN"))
fig.add_trace(go.Scatter(x=[mean_of_sample2, mean_of_sample2], y=[0, 0.17], mode="lines", name="MEAN OF SAMPLE"))
fig.show()
#third intervention
df= pd.read_csv("School_3_Sample.csv")
data= df["Math_score"].tolist()
mean_of_sample3=statistics.mean(data)
print("mean of sample3=",mean_of_sample3)
fig=ff.create_distplot([mean_list],["students marks"], show_hist= False)
fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode="lines", name="MEAN"))
fig.add_trace(go.Scatter(x=[mean_of_sample3, mean_of_sample3], y=[0, 0.17], mode="lines", name="MEAN OF SAMPLE"))
fig.show()
|
3c8a796bd9e2bbcb6b11e1ba00c3986d40c4982b | DiogoOliveira111/ProjectoTese | /WBMTools/sandbox/data_processing.py | 12,615 | 3.515625 | 4 | import pylab as pl
import pandas as pd
import datetime as dt
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
def survey_results(dir_survey, survey):
""" This function gets the survey scales and put it in a data frame named survey_scales.
This function gets some survey info: person_id, person_ip, start and end time and put it in a data frame named
survey_info.
Parameters
----------
dir_survey: string
the file directory.
survey: int
to get scales indexes
Returns
-------
survey_info: dataframe
indexes: person_id (int), person_ip (int), start_time (string), end_time (string)
survey_scales: dataframe
indexes: max (int), regret (int), neuro (int), neg_affect (int), self_repr (int), satisf (int), dec_diff (int),
alt_search (int)
"""
survey_info = pd.read_csv(dir_survey, sep=';', header=0, index_col=0, skiprows=2)
return survey_info
def filter_subjects(survey_info):
birthday = survey_info['s0_age'].tolist()
ages = []
for i in birthday:
b = dt.datetime.strptime(i, '%d/%m/%Y %H:%M')
t = dt.date.today()
age = t.year - b.year
ages.append(age)
fake_subj = pl.find(pl.array(ages) < 18)
survey_info = survey_info.drop(survey_info.index[fake_subj])
return survey_info, pl.array(ages)[pl.array(ages) >= 18]
def statistical_population(survey_info, ages, survey):
sex = survey_info['s0_sex'].tolist()
scale = survey_info['s0_max'].tolist()
mean_age = pl.mean(ages)
std_age = pl.std(ages)
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(ages)
# Set the ticks to be at the edges of the bins.
ax.set_xticks(bins)
pl.title('Survey ' + str(survey))
# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
# Label the percentages
percent = '%0.0f%%' % (100 * float(count) / counts.sum())
pl.text(x, count+0.5, str(percent), fontsize=12)
pl.text(45, 65, "mean: " + str(mean_age), fontsize=12)
pl.text(45, 60, "std: " + str(std_age), fontsize=12)
# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.15)
plt.show()
pl.title('Survey ' + str(survey))
male = pl.find(pl.array(sex) == 2)
female = pl.find(pl.array(sex) == 1)
cs = mpl.cm.Set1(np.arange(2) / 2.)
pl.pie([len(male)*100/len(sex), len(female)*100/len(sex)], labels=['Male', 'Female'], autopct='%1f%%', shadow=True, startangle=90, colors=['#0489B1', '#FACC2E'])
pl.show()
sns.set(style="whitegrid", color_codes=True)
new_dataframe = pd.DataFrame(columns=('scale', 'value'))
for i in ['s0_max', 's0_regret', 's0_neuro', 's0_neg_affect', 's0_self_repr', 's0_satisf', 's0_dec_diff', 's0_alt_search']:
for j in range(len(survey_info[i].tolist())):
new_dataframe.loc[-1] = [i, survey_info[i].tolist()[j]]
new_dataframe.index = new_dataframe.index + 1 # shifting index
sns.violinplot(x="scale", y="value", data=new_dataframe, inner=None)
sns.swarmplot(x="scale", y="value", data=new_dataframe, color="gray", edgecolor="gray")
pl.show()
def get_person_id(mouse_file, dataset_path, server_info):
""" This function gets the person ID from mouse movements file.
This step is important to relate with the survey results.
Parameters
----------
mouse_file: file
file to analyse.
dataset_path: str
to localize id.
server_info: dataframe
Returns
-------
server_info: dataframe
index: person_ip (string)
"""
mouse_file = open(mouse_file, 'r')
i_start = mouse_file.name.index(dataset_path) + len(dataset_path)
i_end = i_start + mouse_file.name[i_start:].index("_")
server_info['person_ip'] = [mouse_file.name[i_start:i_end]]
return server_info
def get_survey_id(mouse_file, server_info):
""" This function gets the survey ID from mouse movements file.
This step is important to select the survey to analyse.
Parameters
----------
mouse_file: file
file to analyse.
server_info: string
to use index person_ip
the number of the survey appears after the person ip (eg 85.7.249.186_465687)
Returns
-------
server_info: dataframe
new index: survey_id (string)
"""
person_id = server_info['person_ip'][0]
mouse_file = open(mouse_file, 'r')
i_start = mouse_file.name.index(person_id) + len(person_id) + 1
i_end = i_start + 6
server_info['survey_id'] = [mouse_file.name[i_start:i_end]]
return server_info
def get_step(mouse_file, server_info):
""" This function gets the survey's step from mouse movements file.
This step is important to join step in the same group.
Parameters
----------
mouse_file: file
file to analyse.
server_info: dataframe
to use survey_id
the step number appears after the survey id (eg 465687_1)
Returns
-------
server_info: dataframe
new indexes: step (string), time (string)
"""
survey_id = server_info['survey_id'][0]
mouse_file = open(mouse_file, 'r')
i_start = 10+mouse_file.name[10:].index(survey_id) + len(survey_id)
if mouse_file.name[i_start] == "_": # case 465687_1
i_start += 1
i_end = i_start + 1
else: # case 4656871
i_end = i_start + 1
server_info['step'] = [mouse_file.name[i_start:i_end]]
server_info['time'] = [mouse_file.name[i_end + 1:i_end + 1 + mouse_file.name[i_end + 1:].index("_")]]
return server_info
def get_subj_pos(survey_info, server_info):
""" This function returns the subject id based on his ip and time of answer.
Parameters
----------
survey_info: dataframe
to use start_time, end_time, person_ip, person_id
server_info: dataframe
to use time, person_ip
Returns
-------
subj_pos:int
position in survey of subject
"""
start_time = survey_info['s0_start_time'].tolist()
end_time = survey_info['s0_end_time'].tolist()
subj_id = survey_info.index.values.tolist()
survey_ip = survey_info['s0_person_ip'].tolist()
mse_time = server_info['time']
server_ip = server_info['person_ip'][0]
start_time_s = []
end_time_s = []
subj_pos = -1
ref_datetime = dt.datetime.strptime('1969-12-31 16:00', '%Y-%m-%d %H:%M')
for i in start_time:
y = dt.datetime.strptime(i, '%d/%m/%Y %H:%M')
diff_time = y - ref_datetime
start_time_s.append(int(diff_time.total_seconds()))
for i in end_time:
y = dt.datetime.strptime(i, '%d/%m/%Y %H:%M')
diff_time = y - ref_datetime
end_time_s.append(int(diff_time.total_seconds()))
for i in pl.arange(0, len(start_time_s)):
if start_time_s[i] <= int(mse_time) <= end_time_s[i]:
if server_ip == survey_ip[i]:
subj_pos = subj_id[i]
return subj_pos
def reorder_data(data):
""" This function reorder the data from mouse movements file according to the number of frames.
Parameters
----------
data: dataframe
columns of file to order.
Returns
-------
data: dataframe
reorder data.
lost_samples: float
percentage of lost samples
"""
data = data.sort_values(['t', 'x', 'y'])
#print(data)
# print(data)
# index = data[0]
# lost_samples = sum(pl.diff(index) - 1)
# return data, [float(lost_samples) / float(len(index))]
return data
def get_parameters(data):
""" This function gets the parameters of mouse movements from the dataframe
Parameters
----------
data: dataframe
columns of file.
Returns
-------
track_variables: dataframe
indexes: x (int px), y (int px), t (int s), events (int), items (str)
"""
item = data[len(data.columns) - 10]
item = pl.array(item)
x = data[len(data.columns) - 7]
x = pl.array(x)
x = x[~pl.isnan(x)]
y = data[len(data.columns) - 6]
y = pl.array(y)
y = y[~pl.isnan(y)]
t = data[len(data.columns) - 1]
t = pl.array(t)
t = (t - int(t[0])) / 1000. # Absolute to relative time in s
t = t[pl.find(~pl.isnan(x))]
events = data[len(data.columns) - 11] # events all mousemove=0 mousedown=1 mouseup=4
events = pl.array(events)
events = events[pl.find(~pl.isnan(x))]
item = item[pl.find(~pl.isnan(x))]
track_variables = pd.DataFrame({'x': [x],
'y': [y],
't': [t],
'events': [events],
'items': [item]
})
return track_variables
def correct_parameters(track_variables):
""" This function correct x, y, t.
Remove sequential frames with the same position (x,y) and with the same time.
In this case we lose information.
Parameters
----------
track_variables: dataframe
use indexes x, y, t
Returns
-------
track_variables: dataframe
correct the indexes x, y, t
samples_correction: int
Number of samples cut.
"""
x = track_variables['x'][0].tolist()
y = track_variables['y'][0].tolist()
t = track_variables['t'][0].tolist()
total_var = [[x[i], y[i], t[i]] for i in pl.arange(0, len(t))]
total_var = pl.array(total_var)
t_error = pl.find(pl.diff(total_var[:, 2]) == 0)
total_var = pl.delete(total_var, t_error, 0)
x_error = pl.find(pl.diff(total_var[:, 0]) == 0)
y_error = pl.find(pl.diff(total_var[:, 1]) == 0)
xy_error = set(x_error).intersection(y_error)
xy_error = list(xy_error)
samples_correction = len(t_error) + len(xy_error)
total_var = pl.delete(total_var, xy_error, 0)
x = total_var[:, 0]
y = total_var[:, 1]
t = total_var[:, 2]
for i in pl.find(pl.diff(x) == 0):
if i in pl.find(pl.diff(y) == 0):
print("Nr samples with repeated position: ", i)
if len(pl.find(pl.diff(t) == 0)) != 0:
print("Nr samples with repeated time: ", len(pl.find(pl.diff(t) == 0)))
track_variables['x'] = [x]
track_variables['y'] = [y]
track_variables['t'] = [t]
return track_variables, samples_correction
def extract_item_number(track_variables):
""" This function gets the question number and its answer.
Parameters
----------
track_variables: dataframe
string with mouse item. (eg answer465687X11X85SQ64-A2)
Returns
-------
track_variables: dataframe
change index items (int question number (eg 64))
add index answers (int question answer (eg 2))
add t_items (int time where item begins)
"""
t = track_variables['t'][0].tolist()
items = track_variables['items'][0].tolist()
ret_items = pl.zeros(len(items))
ret_answer = pl.zeros(len(items))
t_items = pl.zeros(len(items))
for i, ix in enumerate(items):
if 'SQ' in ix:
# Lime survey notation uses strings such as:
# answer465687X11X85SQ64-A2
# javatbd465687X11X85SQ64
# The relevant items comes after SQ
ret_items[i] = int(ix.split('-')[0].split('SQ')[1])
t_items[i] = t[i]
if len(ix.split('-')) == 2:
ret_answer[i] = int(ix.split('-')[1][1])
else:
ret_answer[i] = -1
else:
ret_items[i] = -1
t_items[i] = t[i]
ret_answer[i] = -1
track_variables['items'] = [ret_items.astype('int')]
track_variables['answers'] = [ret_answer.astype('int')]
track_variables['t_items'] = [t_items]
return track_variables
def get_new_item_ix(track_variables):
""" This function simplify the items analysis giving the items order and removing the items 0.
Parameters
----------
track_variables: dataframe
to use index items
Returns
-------
i: array
int with index of item change.
items_order: array
int with items ordered.
"""
items = track_variables['items'][0].tolist()
items = pl.array(items)
i = pl.find(pl.diff(items) != 0) + 1
items_order = items[i].tolist()
if len(i) > 0:
items_order.insert(0, items[i[0] - 1])
return i, items_order
def count_items(items_order, context_variables, survey):
""" This function count the items in each group and recognize the group.
This step is important to check if the group is complete.
Parameters
----------
items_order: array
int with ordered items.
context_variables: dataframe
to add nr_items and group
survey: int
to identify questions of groups
Returns
-------
context_variables: dataframe
indexes: nr_items (int number of items in group), group (string group name)
"""
item0 = 0
group = None
items_order = list(items_order)
my_dict = {i: items_order.count(i) for i in items_order if i != -1} # item: nr times
nr_items = len(my_dict)
for j in my_dict:
item0 = j
if survey == 465687:
if 0 < item0 < 19:
group = "OldMaximizer"
elif 18 < item0 < 31:
group = "NEO"
elif 30 < item0 < 65:
group = "NewMaximizer"
elif nr_items == 0:
group = "no items"
else:
group = "no group recognized"
if survey == 935959:
if 0 < item0 < 19:
group = "OldMaximizer"
elif 18 < item0 < 79:
group = "NEO"
elif 78 < item0 < 99:
group = "ARES"
elif 98 < item0 < 115:
group = "SPF"
elif 114 < item0 < 142:
group = "HAKEMP"
elif 141 < item0 < 176:
group = "NewMaximizer"
elif nr_items == 0:
group = "no items"
else:
group = "no group recognized"
context_variables['nr_items'] = [nr_items]
context_variables['group'] = [group]
return context_variables |
170368ef9881d616bb55722129a4076855157efc | BREAD5940/Offseason-Croissant | /src/main/python/statespace/LTVDiffDriveController.py | 4,509 | 3.546875 | 4 | #!/usr/bin/env python3
# Avoid needing display if plots aren't being shown
import control as ct
# import control as cnt
# import numpy as np
import math
import numpy as np
import frccontrol as frccnt
def __make_cost_matrix(elems):
"""Creates a cost matrix from the given vector for use with LQR.
The cost matrix is constructed using Bryson's rule. The inverse square
of each element in the input is taken and placed on the cost matrix
diagonal.
Keyword arguments:
elems -- a vector. For a Q matrix, its elements are the maximum allowed
excursions of the states from the reference. For an R matrix,
its elements are the maximum allowed excursions of the control
inputs from no actuation.
Returns:
State excursion or control effort cost matrix
"""
return np.diag(1.0 / np.square(elems))
# The motor used
motor = frccnt.models.MOTOR_CIM
# Number of motors per side
num_motors = 2.0
# Gearing constants and stuff
motor = frccnt.models.gearbox(motor, num_motors)
# High and low gear ratios of differential drive
Glow = 11.832
Ghigh = 6.095
# Drivetrain mass in kg
m = 130 * 0.45
# Radius of wheels in meters
r = 4.0 * 0.0254
# Radius of robot in meters
rb = 26.0 * 0.0254 / 2.0
# Moment of inertia of the differential drive in kg-m^2
J = 6.0
def calcA(v, isHighGear, C1, C3):
if(isHighGear):
G = Ghigh
else:
G = Glow
A = np.array([
[0, 0, 0, 0.5, 0.5],
[0, 0, v, 0, 0],
[0, 0, 0, -1/(2*rb), 1/(2*rb)],
[0, 0, 0, (1/m + rb * rb / J)*C1, (1/m - rb * rb / J)*C3],
[0, 0, 0, (1/m - rb * rb / J)*C1, (1/m + rb * rb / J)*C3]
])
return A
def calcB(v, isHighGear, C2, C4):
if(isHighGear):
G = Ghigh
else:
G = Glow
B = np.array([
[0, 0],
[0, 0],
[0, 0],
[(1/m + rb * rb / J) * C2, (1/m - rb * rb / J) * C4],
[(1/m - rb * rb / J) * C2, (1/m + rb * rb / J) * C4]
])
return B
def calcGains(isHighGear):
qX = 0.12 # allowable linear error
qY = 0.2 # allowable cross track error
qTheta = math.radians(90) # allowable heading error
vMax = 5.0 * 0.3048 # allowable velocity error? (ft/sec to meters per sec)
voltMax = 5.0 # max control effort (from trajectory feedforward?)
# period of the controller
period = 1.0 / 100.0
print("Calculating cost matrix for LTV diff drive controller with costs qX %s qY %s qTheta %s vMax %s at %s volts \n" % (qX, qY, qTheta, vMax, voltMax))
if(isHighGear):
G = Ghigh
gear = "High"
else:
G = Glow
gear = "Low"
C1 = -G ** 2 * motor.Kt / (motor.Kv * motor.R * r ** 2)
C2 = G * motor.Kt / (motor.R * r)
C3 = -G ** 2 * motor.Kt / (motor.Kv * motor.R * r ** 2)
C4 = G * motor.Kt / (motor.R * r)
Q = __make_cost_matrix([qX, qY, qTheta, vMax, vMax])
R = __make_cost_matrix([voltMax, voltMax])
C = np.array([
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]
])
D = np.array([
[0, 0],
[0, 0],
[0, 0]
])
v = 1e-7
A = calcA(v, isHighGear, C1, C3)
B = calcB(v, isHighGear, C2, C4)
sys = ct.StateSpace(A, B, C, D, remove_useless = False)
sysd = sys.sample(period)
K0 = frccnt.lqr(sysd, Q, R)
v = 1.0
A = calcA(v, isHighGear, C1, C3)
B = calcB(v, isHighGear, C2, C4)
sys = ct.StateSpace(A, B, C, D, remove_useless = False)
sysd = sys.sample(period)
K1 = frccnt.lqr(sysd, Q, R)
kx = K0[0, 0]
ky_0 = K0[0, 1]
kvPlus_0 = K0[0, 3]
kVMinus_0 = K0[1, 3]
ky_1 = K1[0, 1]
kTheta_1 = K1[0, 2]
kVPlus_1 = K1[0, 3]
gains = str("%s, %s, %s, %s,\n %s, %s, %s" % (
kx, ky_0, kvPlus_0, kVMinus_0, ky_1, kTheta_1, kVPlus_1
))
# print((gains))
print("LTV Diff Drive CTE Controller gains: \n %s" % gains)
# Save it to a file
fileName = "GeneratedLTVDiffDriveController.kt"
file = open("src/generated/kotlin/statespace/" + fileName, "w")
file.write(
"package statespace\n\n" +
"import edu.wpi.first.wpilibj.kinematics.DifferentialDriveKinematics\n" +
"import org.team5940.pantry.lib.statespace.LTVDiffDriveController\n\n" +
"val generatedLTVDiffDriveController" + gear + "Gear get() = LTVDiffDriveController(\n " +
gains + ",\n DifferentialDriveKinematics(" + str(rb) + ")"+
")\n"
)
|
681e2ef15a450cae0db70cd9994554396ea97916 | glennneiger/git_better | /server/django_server/utils.py | 921 | 3.5 | 4 | from BeautifulSoup import BeautifulSoup
import urllib2
def get_trending_links(language=None, since="daily"):
"""Return a list of trending GitHub repositories for the specified parameters.
Args:
language (None, optional): The programming language. If not set, all languages are included
since (str, optional): One of ['daily', 'weekly', 'monthly']
Returns:
TYPE: List of trending repositories (e.g. ['/rails/rails'])
"""
language_param = "/" + language if language else ""
url = "https://github.com/trending/{language}?since={since}".format(language=language_param, since=since)
html_page = urllib2.urlopen(url)
links = []
soup = BeautifulSoup(html_page)
for link_tag in soup.findAll('a'):
link = link_tag["href"]
if link is not None and link.startswith("/") and len(link.split("/")) == 3:
links.append(link)
return links
|
1d7293afa6c9288a768cb72796c46290bbaf525d | lieta96/30-days-of-python | /day_05/lists.py | 5,598 | 4.3125 | 4 |
# Level 1
#1
empty_list=[]
#2
more_than_five=[0,1,2,3,4,5,6]
#3
lenght_list=len(more_than_five)
#4
middle_index=lenght_list//2
first_item=more_than_five[0]
middle_item=more_than_five[middle_index]
print (middle_item)
last_item=more_than_five[lenght_list-1]
print(last_item)
#5
mixed_data_types=["Julieta",24,1.60,"a quien le importa", "Calle Wallaby 42 Sidney"]
#6
it_companies=["Facebook", "Google", "Microsoft", "Apple", "IBM", "Oracle","Amazon"]
#7
print (it_companies)
#8
print (len(it_companies))
#9
print (f'Primera empresa: {it_companies[0]}')
print (f'Empresa del medio: {it_companies[len(it_companies)//2]}')
print (f'Última compañía: {it_companies[len(it_companies)-1]}')
#10
it_companies[0]="Accenture"
print (it_companies)
#11
it_companies.append('Sony')
print (it_companies)
#12
it_companies.insert(len(it_companies)//2,"ARSAT")
print (it_companies)
#13
it_companies[0]= it_companies[0].upper()
print (it_companies)
#14
print(' # '.join(it_companies))
#15
print (f'"Sony está dentro de la lista?: {"Sony" in it_companies}')
#16
it_companies.sort()
print (it_companies)
#17
it_companies.sort(reverse=True)
print (it_companies)
#18
print(it_companies[3:])
#19
print(it_companies[0:-3])
#20
print(f'Lista completa: \t\t{it_companies}')
it_companies.pop(len(it_companies)//2)
print (f'Lista sin el elemento del medio: {it_companies}')
#21
it_companies.pop(0)
print(it_companies)
#22 igual que 20
#23
it_companies.pop()
print(it_companies)
#24
it_companies.clear()
print(it_companies)
#25 idem anterior
#26
front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']
back_end = ['Node','Express', 'MongoDB']
print (front_end+back_end)
#27
full_stack=front_end.copy()+back_end.copy()
full_stack.append("Python")
full_stack.append("SQL")
print(full_stack)
# Level 2
#1
ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
ages.sort()
min_age=ages[0]
max_age=ages[len(ages)-1]
print(f'Menor edad: {min_age}')
print(f'Mayor edad: {max_age}')
middle_age=ages[len(ages)//2]
print(f'Edad media: {middle_age}')
sum_ages=0
for age in ages:
sum_ages+=age
print (sum_ages)
average_age=sum_ages/len(ages)
print(average_age)
range_ages=max_age-min_age
print(abs(min_age-average_age))
print(abs(max_age-average_age))
# 1 Countries
countries = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe',
]
#Find the middle countries
print(f'La cantidad de países es par? {len(countries)%2==0==True}')
print (len(countries))
middle_countrie_number=len(countries)//2
middle_country=countries[middle_countrie_number]
print(middle_country)
#2
first_countries=countries[0:middle_countrie_number]
last_countries=countries[middle_countrie_number:len(countries)]
print(len(last_countries))
#3
new_countries=['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']
China,Rusiua,USA,*scandic=new_countries
print(scandic)
print(China)
|
72b1efd985e668f70ebc55376f18c57cde06b96e | OlgaFimbresMorales/ProgramacionF | /Producto2/hola.py | 452 | 3.671875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python
import time
print "Hola! Trataré de adivinar un número"
print "Piensa un número entre 1 y 10."
time.sleep( 5 )
print "Ahora multiplícalo por 9."
time.sleep( 5 )
print "Si el número tiene 2 dígitos, súmalos entre si: Ej. 36 -> 3+6=9. Si tu número tiene un solo dígito, súmale 0."
time.sleep( 5 )
print "Al número resultante súmale 4."
time.sleep( 10 )
print "Muy bien. El resultado es 13 :)"
|
c5e0d8fc3cf45e5098827ceba965d581cda6c16f | shankar7042/coding-questions | /binary_tree.py | 6,451 | 3.953125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self) -> str:
return str(self.data)
def levelorder(root):
if root is None:
return
queue = list()
queue.append(root)
queue.append(None) # To verify that the level is end here
while len(queue) != 0:
node = queue.pop(0)
if node is not None:
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
elif len(queue) != 0:
queue.append(None)
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
def preorder(root):
if root is None:
return
print(root.data, end=" ")
preorder(root.left)
preorder(root.right)
def postorder(root):
if root is None:
return
postorder(root.left)
postorder(root.right)
print(root.data, end=" ")
def levelorder2(root):
if root is None:
return
queue = list()
queue.append(root)
queue.append(None) # To verify that the level is end here
level = 0
print(level, '->', end="")
while len(queue) != 0:
node = queue.pop(0)
if node is not None:
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
elif len(queue) != 0:
queue.append(None)
level += 1
print()
print(level, '->', end="")
def kthSum(root, k):
if root is None:
return -1
queue = list()
queue.append(root)
queue.append(None)
level = 0
ans = 0
while len(queue) != 0:
node = queue.pop(0)
if node is not None:
if level == k:
ans += node.data
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
elif len(queue) != 0:
queue.append(None)
level += 1
return ans
def total_nodes(root):
if root is None:
return 0
return total_nodes(root.left)+total_nodes(root.right)+1
def sum_nodes(root):
if root is None:
return 0
return sum_nodes(root.left) + sum_nodes(root.right) + root.data
def heigt(root):
if root is None:
return 0
return max(heigt(root.left), heigt(root.right))+1
def sum_replacement(root):
if root is None:
return
sum_replacement(root.left)
sum_replacement(root.right)
if root.left is not None:
root.data += root.left.data
if root.right is not None:
root.data += root.right.data
def is_balanced(root):
if root is None:
return True
if is_balanced(root.left) is False:
return False
if is_balanced(root.right) is False:
return False
lheight = heigt(root.left)
rheight = heigt(root.right)
if abs(lheight - rheight) <= 1:
return True
else:
return False
def is_balanced_better(root):
if root is None:
return (0, True)
lh, l_balanced = is_balanced_better(root.left)
rh, r_balanced = is_balanced_better(root.right)
return (max(lh, rh) + 1, l_balanced and r_balanced and (abs(lh-rh) <= 1))
def right_view(root: Node):
if root is None:
return
q = list()
q.append(root)
while len(q) != 0:
n = len(q)
for i in range(n):
node = q.pop(0)
if i == n-1:
print(node.data, end="->")
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
def left_view(root):
if root is None:
return
q = list()
q.append(root)
while len(q) != 0:
n = len(q)
for i in range(n):
node = q.pop(0)
if i == 0:
print(node.data, end="->")
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
def get_path(root, n, path):
if root is None:
return False
path.append(root.data)
if root.data == n:
return True
if get_path(root.left, n, path):
return True
if get_path(root.right, n, path):
return True
path.pop(len(path)-1)
return False
def lowest_common_ancestor(root, n1, n2):
path1 = list()
path2 = list()
if (not get_path(root, n1, path1)) or (not get_path(root, n2, path2)):
return
print(path1)
print(path2)
for i in range(min(len(path1), len(path2))):
if path1[i] != path2[i]:
break
return path1[i-1]
def lowest_common_ancester_v2(root, n1, n2):
if root is None:
return None
if root.data == n1 or root.data == n2:
return root
leftLCA = lowest_common_ancester_v2(root.left, n1, n2)
rightLCA = lowest_common_ancester_v2(root.right, n1, n2)
if leftLCA and rightLCA:
return root
if leftLCA is not None:
return leftLCA
if rightLCA is not None:
return rightLCA
return None
def findDist(root, k, dist):
if root is None:
return -1
if root.data == k:
return dist
left = findDist(root.left, k, dist+1)
if left != -1:
return left
return findDist(root.right, k, dist+1)
def shortest_distance_two_nodes(root, n1, n2):
lca = lowest_common_ancester_v2(root, n1, n2)
leftDist = findDist(lca, n1, 0)
rightDist = findDist(lca, n2, 0)
return leftDist + rightDist
def sortedArrayToBST(nums, low=None, high=None):
if low <= high:
mid = (low + high) // 2
root = Node(nums[mid])
root.left = sortedArrayToBST(nums, low, mid-1)
root.right = sortedArrayToBST(nums, mid+1, high)
return root
x = [-10, -3, 0, 5, 9]
root = sortedArrayToBST(x, 0, len(x)-1)
levelorder2(root)
# root = Node(1)
# root.left = Node(2)
# root.right = Node(3)
# root.left.left = Node(4)
# root.left.right = Node(5)
# root.right.left = Node(6)
# root.right.right = Node(7)
# print(shortest_distance_two_nodes(root, 2, 3))
|
32abbab0341942f882ad0a2e9c1a94a9579c9f86 | shankar7042/coding-questions | /binary_search.py | 4,846 | 3.5 | 4 |
def binary_search_asc(arr, key):
start = 0
end = len(arr)-1
while start <= end:
mid = start + ((end-start) // 2)
if arr[mid] == key:
return mid
elif arr[mid] > key:
end = mid-1
else:
start = mid+1
return -1
def binary_search_desc(arr, key):
start = 0
end = len(arr)-1
while start <= end:
mid = start + ((end-start) // 2)
if arr[mid] == key:
return mid
elif arr[mid] < key:
end = mid-1
else:
start = mid+1
return -1
def binary_search_order_not_known(arr, key):
if len(arr) == 1 and arr[0] == key:
return 0
else:
if arr[0] < arr[1]:
return binary_search_asc(arr, key)
else:
return binary_search_desc(arr, key)
def first_occurence(arr, key):
start = 0
end = len(arr)-1
ans = -1
while start <= end:
mid = start + ((end - start) // 2)
if arr[mid] == key:
ans = mid
end = mid - 1
elif arr[mid] > key:
end = mid - 1
else:
start = mid + 1
return ans
def last_occurence(arr, key):
start = 0
end = len(arr) - 1
ans = -1
while start <= end:
mid = start + ((end - start)//2)
if arr[mid] == key:
ans = mid
start = mid + 1
elif arr[mid] > key:
end = mid - 1
else:
start = mid + 1
return ans
def count(arr, key):
return last_occurence(arr, key) - first_occurence(arr, key) + 1
# this funtion can also be used as to find the min_index
def no_of_rotation(arr):
# No roattions happend
if arr[0] < arr[-1]:
return 0
N = len(arr)
start = 0
end = N-1
while start <= end:
if arr[start] <= arr[end]:
return start
mid = start + ((end-start)//2)
next = (mid + 1) % N
prev = (mid - 1 + N) % N
if arr[mid] <= arr[next] and arr[mid] <= arr[prev]:
return mid
elif arr[mid] >= arr[start]: # means left part is sorted we have to go to the right part
start = mid + 1
elif arr[mid] <= arr[end]: # means right part is sorted we have to go to the left part
end = mid - 1
def find_min_index(arr):
start = 0
end = len(arr)-1
while start < end:
mid = (start + end) // 2
if arr[mid] > arr[end]:
start = mid + 1
else:
end = mid
return start
def serach_in_rotated_arr(arr, key):
min_index = no_of_rotation(arr)
ans = binary_search_asc(arr[:min_index], key)
if ans != -1:
return ans
ans = binary_search_asc(arr[min_index:], key)
if ans != -1:
return ans + min_index
return -1
def floor(arr, key):
start = 0
end = len(arr) - 1
ans = -1
while start <= end:
mid = (start + end) // 2
if arr[mid] == key:
return mid
elif arr[mid] < key:
ans = mid
start = mid + 1
else:
end = mid - 1
return ans
def ceil(arr, key):
start = 0
end = len(arr) - 1
ans = -1
while start <= end:
mid = (start + end) // 2
if arr[mid] == key:
return mid
elif arr[mid] < key:
start = mid + 1
else:
ans = mid
end = mid - 1
return ans
def min_diff(arr, key):
start = 0
end = len(arr) - 1
ans = -1
while start <= end:
mid = (start + end) // 2
if arr[mid] == key:
ans = mid
break
elif arr[mid] < key:
ans = mid
start = mid + 1
else:
end = mid - 1
if arr[ans] == key:
return 0
else:
if ans == len(arr) - 1:
return abs(arr[ans] - key)
else:
return min(abs(arr[ans] - key), abs(arr[ans + 1] - key))
def peak_element(arr):
if len(arr) == 1:
return arr[0]
if arr[0] >= arr[1]:
return 0
elif arr[-1] >= arr[-2]:
return len(arr) - 1
start = 1
end = len(arr) - 2
while start <= end:
mid = (start + end) // 2
if arr[mid] >= arr[mid - 1] and arr[mid] >= arr[mid+1]:
return mid
elif arr[mid + 1] >= arr[mid]:
start = mid + 1
elif arr[mid-1] >= arr[mid]:
end = mid - 1
# 4^(1/2) = 2 and 2^(1/2) = 1.414
def mul(n, p):
res = 1
for _ in range(p):
res *= n
return res
def root(num, x):
lo = 1
hi = num
eps = 1e-7
while hi - lo > eps:
mid = (hi+lo)/2
if mul(mid, x) > num:
hi = mid
else:
lo = mid
return lo
print(round(root(144, 3), 5))
print(round(root(2, 3), 5))
|
2080631a6342415fb739524ce136b011d164380f | xuehanshuo/ref-python-numpy | /np_05_矩阵的索引.py | 614 | 3.859375 | 4 | import numpy as np
A = np.arange(3, 15).reshape((3, 4))
print(A)
print("*" * 100)
# 索引某一行/某一列
print(A[2])
print(A[2, :])
print(A[:, 0])
print("*" * 100)
# 索引单个值
print(A[0, 0])
print(A[0][0])
print("*" * 100)
# 索引部分值
print(A[0, 1:3]) # 第0行,[1,3)的所有数
print("*" * 100)
# 迭代每一行
for row in A:
print(row)
print("*" * 100)
# 迭代每一列
for column in A.T:
print(column)
print("*" * 100)
# 迭代每一个元素
for item in A.flat:
print(item)
print(A.flatten()) # 延展出来一行
print("*" * 100)
|
e4a0d20e8f094a49ad535014b0a751bf4e81976d | Cosmo65/Velha-AI | /robodificil.py | 1,958 | 3.53125 | 4 | class RoboDificil(object):
'''Robo bom com MinMax'''
def __init__(self, nome, marca):
self.marca = marca
self.nome = nome
if self.marca == 'X':
self.oponente = 'O'
else:
self.oponente = 'X'
def jogada(self, tabuleiro):
posicao,score = self.maximized_move(tabuleiro)
tabuleiro.marcar(self.marca, posicao)
def maximized_move(self,gameinstance):
''' Find maximized move'''
bestscore = None
bestmove = None
for m in gameinstance.movimentos_disponiveis():
gameinstance.marcar(self.marca, m)
if gameinstance.terminou():
score = self.get_score(gameinstance)
else:
move_position,score = self.minimized_move(gameinstance)
gameinstance.reverter()
if bestscore == None or score > bestscore:
bestscore = score
bestmove = m
return bestmove, bestscore
def minimized_move(self,gameinstance):
''' Find the minimized move'''
bestscore = None
bestmove = None
for m in gameinstance.movimentos_disponiveis():
gameinstance.marcar(self.oponente, m)
if gameinstance.terminou():
score = self.get_score(gameinstance)
else:
move_position,score = self.maximized_move(gameinstance)
gameinstance.reverter()
if bestscore == None or score < bestscore:
bestscore = score
bestmove = m
return bestmove, bestscore
def get_score(self,gameinstance):
if gameinstance.terminou():
if gameinstance.vencedor == self.marca:
return 1 # Won
elif gameinstance.vencedor == self.oponente:
return -1 # Opponent won
return 0 # Draw
|
95ae69a68f37ef7311380514541995a36f7c8686 | golan1202/verilog-parser | /data_from_csv.py | 768 | 3.5 | 4 | import csv
import os
import sys
def parse_from_csv(fname):
if os.path.exists(fname) and os.stat(fname).st_size != 0 and fname.endswith('.csv'):
with open(fname) as f:
data = dict()
try:
reader = csv.reader(f, delimiter=',')
next(reader) # skip the header row
for line in reader:
data[line[0]] = [line[1], line[2]]
return data
except IndexError:
print("\nError in File: '%s'" % fname)
sys.exit("IndexError: Must be in this pattern: port name,port mode,port data_type")
else:
print("\nError in File: '%s'" % fname)
sys.exit("File does not exist OR is empty OR wrong extension")
|
b0a07c7c13f8973b1406df6a06b86710ead5581d | rebetli6/first_project | /data_structures.py | 146 | 3.640625 | 4 | name = ["John Doe", "Jack Doe"]
print(len(name))
print(name[1])
numbers= [11, 24, 55, 12, 21]
s=0
for c in numbers:
s += c
print(c)
print(s) |
67dd8f9a9ace275c3abbe429744e82e558918189 | CesarNaranjo14/selenium_from_scratch | /create_pickles.py | 1,111 | 3.578125 | 4 | """
DESCRIPTION
Create a set of pickle files of neighborhoods.
These files are for the use of giving the crawlers a "memory",
that is, we remove a neighborhood every time a crawler finishes
to scrap it in order to not iterate again.
HOW TO RUN
You have to run inside this directory:
python create_pickle start
"""
# Built-in libraries
import pickle
import os
# Third-party libraries
from flask import Blueprint
# Modules
from src.base.constants import MEMORY_PATH, CRAWLERS_PATH
create_pickles = Blueprint('create_pickles', __name__)
pages = [
"inmuebles24",
"icasas",
"vivanuncios",
"propiedades",
"lamudi",
]
@create_pickles.cli.command('start')
def pickles():
"""Create a set of pickles for every website."""
if not os.path.exists(MEMORY_PATH):
os.makedirs(MEMORY_PATH)
for page in pages:
with open(f"{CRAWLERS_PATH}colonias.txt", "r") as myfile:
colonias = [colonia.lower().strip() for colonia in myfile]
with open(f"{MEMORY_PATH}colonias-{page}.pickle", "wb") as pickle_file:
pickle.dump(colonias, pickle_file)
|
f1579f18820ec92be33bbf194db207d4b8678b89 | nonelikeanyone/Robotics-Automation-QSTP-2021 | /Week_1/exercise.py | 717 | 4.1875 | 4 | import math
def polar2cart(R,theta):
#function for coonverting polar coordinates to cartesian
print('New Coordinates: ', R*math.cos(theta), R*math.sin(theta))
def cart2polar(x,y):
#function for coonverting cartesian coordinates to polar
print('New Coordinates: ', (x**2+y**2)**(0.5), math.atan(y/x))
print('Convert Coordinates')
print('Polar to Cartesian? Put 1. Cartesian to Polar? Put 2.')
ip=int(input('Your wish: ')) #prompt user for input
if ip==1:
#if user enters 1, execute this block
R=int(input('Enter R= '))
theta=(input('Enter theta in radians= '))
polar2cart(R,theta)
else:
#if user does not enter 1, execute this block
x=int(input('Enter x= '))
y=int(input('Enter y= '))
cart2polar(x,y)
|
6c3a9013ec4b575035995144a1239ebc2f2d97ff | yuhaitao10/Language | /python/first-class/first_class_fun.py | 288 | 4.03125 | 4 | #!/usr/bin/python
def square(x):
return x*x
def cube(x):
return x*x*x
def my_map(func,arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1,2,3,4,5,6])
print(squares)
cubes = my_map(cube, [1,2,3,4,5,6])
print(cubes)
|
4f4fddc6e1b35d24a52d7cbf4e3468aab4bca6d2 | yuhaitao10/Language | /python/scripts/data_types.py | 1,486 | 3.984375 | 4 | #!/usr/bin/python
#working on dictionary
print "\nWorking on dictionary"
hosts = {}
hosts['h1'] = '1.2.3.4'
hosts['h2'] = '2.3.4.5'
hosts['h3'] = '3.4.5.6'
for server,ip in hosts.items():
print server, ip
for server,ip in hosts.items():
print ('serer: {} ip: {}'.format(server, ip))
hosts2 = {'h1':'1.2.3.4','h2':'2,3,4,5', 'h3':'3.4.5.6'}
for server,ip in hosts2.items():
print "server: %s" % ip
mylist = []
mytuple = ()
mydictionary = {}
#the only thing we can do to a tuple is to add an element
a = (1,2,3)
a = a + (4,)
book={'Dad':'Bob','Mom':'Lisa','Bro':'Joe'}
book['Dad']
p=book.clear()
print "Dictionary clear() function: %s" % p
#del an dictionary element
del['Dad']
#add a dictionary element
book['Grace'] = 'Sis'
ages={'Dad':'42','Mom':'87'}
tuna=ages.copy()
p = 'Mom' in tuna
print "Dictionary in function: %s" % p
#working on string
print "\nWorking on string:"
seperator='hoss'
sequence=['hey','there', 'bessie','hoss']
glue='hoss'
p=glue.join(sequence)
print "string join() function: %s" % p
randstr="I wich I Had No Sausage"
randstr
p = randstr.lower()
print "string lower() function: %s" % p
truth="I love old women"
p = truth.replace('women', 'men')
print "String replace() function: %s" % p
example="Hey now bessie nice chops"
p = example.find('bessie')
print "String find() function: %s" % p
ratio = '68%'
amt = int(ratio.rstrip('%'))
print "String rstrip() function: %s" % amt
|
eb2fa02366ac7da73b69491e146e50dc6c4f9072 | zhngfrank/notes | /pynotes.py | 3,222 | 4.40625 | 4 | #division normally operates in floating point, to truncate and get integer division use
#// e.g.
print ("3//5 = ", 3//5, "whereas\n3/5 =", 3/5)
#when python is used as a calculator, e.g. through python3 command terminal, the last saved answer
#is stored in the variable "_" (underscore). same as 2nd ans on TI calculator
print('\n','_'*200,'\n')
##round(number, decimalplaces)
print ("round(75.0386, 2)= ", round(75.0386, 2))
#single and double quotes are interchangable, used them as needed to make text readable, e.g.
#if you need quotes in a print statement.
#you can also use \ as an escape sequence to the same effect, this means that the following
#is a character and not something else, e.g. \" will be printed, and will not terminate a print
#statement
print('\n', '_'*200,'\n')
print ("the dog said \"hello\"")
#use r before quotations to force the string to be raw characters. \will be ignored
print('\n', '_'*200,'\n')
print (r"the directory is \user\new, see, no newline")
#make multiline strings with triple quotes. no need to repeat print statements, or use new lines(\n)
#most of the time. python automatically adds a newline, but you can circumvent this by putting a \
#at the end of the line to prevent the EOL"
print('\n', '_'*200,'\n')
print ("""my name is frank\
nice to meet you
this is on the next line
and this is on the third line\
but this isn't""")
#strings can be glued together using the "+" sign or repeated using "*"
print('\n', '_'*200,'\n')
print("my name is frank" + ", nice to meet you" *3)
#side by side string literals can glued together without a + sign, just put em together
#print("yo", " fam")
print('\n', '_'*200,'\n')
#strings are stored c style, e.g. an array of characters. can be accessed via indices
var = "word"
print("word[0] =", var[0],"\nand word[-3] =", var[-3], " (reads from the right)")
print('\n', '_'*200,'\n')
#can slice indices, basically a to statement within the array
print("word[:2] hi word[2:] = " , var[:2], " hi ", var[2:])
print("notice that the first is included and end excluded")
#despite being c string they are immutable, you can't set var[4] = 'j'
print('\n', '_'*200,'\n')
print("len(var)= ", len(var))
#lists in python are like typename vectors, can store any data type and can be added to the end
#format is same as array
print('\n', '_'*200,'\n')
squares = [1, 4, 9, 16]
print("squares[0] = ", squares[0])
#can add to the end using squares.append(literal)
#can be sliced as well. makes it a hell of a lot easier to iterate through them
#creates a shallow copy >> ram usage issues?
print('\n', '_'*200,'\n')
if 3<5 :
print ("do, elif or else won't print")
elif 4>3:
print("this is the same as else if")
else:
print ('this is else')
test_boolean_logic1 = 0;
test_boolean_logic2 = 1;
if test_boolean_logic1:
print("this is 0, should not have printed")
elif test_boolean_logic2:
print("this should have printed, elif with 1 works!")
print('\n', '_'*200,'\n')
#for loop is significantly less explicit
for w in var:
print(w, len(var))
print("so the control variable w, once printed, corresponds to var[i], where i is internal and not",
"explicit")
####
print('\n', '_'*200,'\n', sep='')
|
07fa76c6a9fcbc33d34229f1e62c27e22ec93365 | juanperdomolol/Dominio-python | /ejercicio15.py | 595 | 4.1875 | 4 | #Capitalización compuesta
#Crear una aplicación que trabaje con la ley de capitalización compuesta.
#La capitalización compuesta es una operación financiera que proyecta un capital a un período futuro,
# donde los intereses se van acumulando al capital para los períodos subsiguientes.
capitalInicial= float(input("Cual es el capital dispuesto a Capitalización compuesta "))
interes = float(input("Cual es el interes anual? "))
años = int(input("A cuantos años se proyecta el capital "))
porcentaje= interes/100
resultado = capitalInicial*((1+porcentaje)**años)
print(resultado) |
70d854315f7ccfd8d4a3f46d604991b7a41f82d6 | juanperdomolol/Dominio-python | /ejercicio3.py | 630 | 3.890625 | 4 | #Intervalos
#Generar un número aleatorio entre 1 y 120.
#Decir si se encuentra en el intervalo entre 10 y 50, o bien si es mayor de 50 hasta 100,
# o bien si es mayor de 100, o bien si es menor de 10.
import random
Aleatorio = random.randrange(1, 120)
if (Aleatorio>10 and Aleatorio<50):
print("se encuentra en el intervalo entre 10 y 50")
elif (Aleatorio>50 and Aleatorio<100):
print("se encuentra en el intervalo entre 50 y 100")
elif (Aleatorio>100 and Aleatorio<=120):
print("se encuentra en el intervalo entre 100 y 120")
else:
print("El numero es menor de 10")
print("El numero es: ",Aleatorio) |
3c82383327e8e17cb8b22247916cb89861c50d46 | thouis/plate_normalization | /welltools.py | 377 | 3.5625 | 4 | import re
def extract_row(well):
well = well.upper().strip()
if len(well) > 0 and 'A' <= well[0] <= 'P':
return well[0]
return '(could not parse row from %s)'%(well)
def extract_col(well):
# find the first block of numbers
m = re.match('[^0-9]*([0-9]+)', well)
if m:
return m.group(1)
return '(could not parse col from %s)'%(well)
|
865f27d25b6f07ac8fb8ff2564ad663641104943 | michael-deprospo/OptionsTradingProject | /MultiRegression.py | 1,999 | 3.625 | 4 | from yahoo_fin import stock_info as si
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
#This class pertains to multiple linear regression modeling, with ordinary least squares as the loss function. This class will handle
#data preprocessing, cross validation, train-test split, building loss visualizations, feature engineering. We will be experimenting with L1 and L2
#loss, aka ridge and lasso regression. The final output will be train and test accuracy on the model, as well as inputting a stock and predicting it's
#price daily, weekly, and monthly
class MultiLinearRegression:
def __init__(self, ticker, startdate, enddate):
self.ticker = ticker
self.startdate = startdate
self.enddate = enddate
self.liveprice = None
self.X_train = None
self.Y_train = None
self.X_test = None
self.Y_test = None
self.data = None
def get_curr_price(self):
self.live_price = si.get_live_price(self.ticker)
return self.live_price
def get_historic_data(ticker):
self.data = si.get_data(ticker, start_date=self.startdate, end_date=self.enddate, index_as_date = False)
return self.data
def crossValidation(self):
return 0
def train_test_split(self):
X = get_historic_data(self.ticker)
temp = X
X = X.drop('adjclose')
Y = pd.Series(temp['adjclose'])
self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(X, Y, train_size = .9)
return self.X_train, self.X_test, self.Y_train, self.Y_test
def rmse(self, actual_y, predicted_y):
return np.sqrt(np.mean((actual_y - predicted_y) ** 2))
def customFeatureEngineering(self, self.X):
df =
def buildMultiRegModel(self, ticker):
df = get_historic_data(ticker)
regressor = linear_model.LinearRegression()
|
c8bf6025d729849c121bd1b9ad4702dfae8a3a13 | brobinson124/ai3202 | /Assignment5/assignment5.py | 6,478 | 3.5 | 4 | #Brooke Robinson
#Assignment 5
#Used Assignment 2 as a base
#Worked with Mario Alanis
import sys
class Node:#node represent a grid squard
def __init__(self, locationx, locationy, type_val):
self.x = locationx
self.y = locationy
self.p = None
self.typeN = type_val #0 is free, 1 is mountain, 2 is wall, 3 is a snake, 4 is a barn
if type_val == 0:#awards associated with each type value
self.reward = 0
elif type_val == 1: #Mountain
self.reward = -1
elif type_val == 3: #Snake
self.reward = -2
elif type_val == 4: #Barn
self.reward = 1
elif type_val == 50: #the Apple!
self.reward = 50
else:
self.reward = 0
def setParent(self, parent): #setting the parent
self.p = parent
def getMap(arg):
mymap = []
with open(arg, 'r') as f:
for line in f:
line = line.strip()
if len(line) > 0:
mymap.append(map(int, line.split()))
for x in (range(0,len(mymap))):
for y in range(0,len(mymap[x])):
mymap[x][y] = Node(x,y,int(mymap[x][y]))
#print mymap[x][y].x,mymap[x][y].y, mymap[x][y].reward
return mymap
class MDP:
def __init__(self, mymap):
self.Open = {}
self.Close = {}
self.mymap = mymap
self.length = len(mymap)
self.goal = mymap[0][9]
self.start = mymap[7][0]
self.util_list = {} #a list that stores the utilities for the current
self.prev_util = {} #a list that stores the utilities for the previous
def getAdj(self, n):
#Added for MDP: No cornors
adj_matrix = []
for x in range(n.x-1, n.x+2): #we add +2 because the range does not include the final value
for y in range(n.y-1, n.y+2):
if(x>= 0 and y>=0 and x<len(self.mymap) and y<len(self.mymap[x]) and not (x== n.x and y==n.y)):
if not((x == n.x-1 and y == n.y-1) or (x==n.x+1 and y==n.y+1) or (x==n.x-1 and y ==n.y+1) or (n==n.x+1 and y==n.y-1)):
#we have to make sure it is within bounds(No corners!)
#we also have to make sure we do not add the same node
if(self.mymap[x][y].reward != 2):
adj = mymap[x][y]
adj_matrix.append(adj)
self.u = 0
return adj_matrix
def expect_u(self, e):#e=epsilon, our parameter
#let's initialize all of our map to 0.0 reward
for x in range(0,len(self.mymap)):
for n in self.mymap[x]:
self.util_list[n] = 0.0
self.prev_util[n] = 0.0
d = 1.0#d=delta, a way to measure our parameter
while(d>(e*(1.0-0.9)/0.9)): #our parameters
for x in range(0,len(self.mymap)):
for node in self.mymap[x]:
self.prev_util[node] = self.util_list[node] #add it to our previous to remember value for next loop
max_val = self.MDPfunc(node) #find the policy with the max reward
self.util_list[node] = node.reward +0.9*max_val #0.9 is our living reward
if node.typeN == 2: #cannot be a wall
self.util_list[node] = 0.0
d = 0.0 #reset delta
#we want to loop through the map in order to find if any of the nodes are greater than delta(our parameter tester)
for x in range(0,len(self.mymap)):
for node in self.mymap[x]:
if abs(self.util_list[node] - self.prev_util[node]) > d:
d = abs(self.util_list[node] - self.prev_util[node]) #update our parameters
#print('\n'.join([' '.join(['{0:.2f}'.format(self.util_list[item]) for item in row]) for row in self.mymap]))
#prints the grid of our utilities: I got this specifically from Mario in order to test my code
def MDPfunc(self, n):
#Our policy-finding function
adj = self.getAdj(n)
stored_vals = []
for val in adj:
if val.x == n.x: #have to check up option and down option
if val.y >= 0 and val.y < (len(self.mymap[0])-1):
if self.mymap[val.x][val.y+1] in adj:
node1 = self.mymap[n.x][n.y+1]
else:
node1 = 0.0
if self.mymap[n.x][n.y-1] in adj:
node2 = self.mymap[n.x][n.y-1]
else:
node2 = 0.0
if node1 == 0.0 and node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val])
elif node1 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*(self.prev_util[node2]))
elif node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*(self.prev_util[node1]))
else:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1]+0.1*self.prev_util[node2])
elif val.y == n.y: #check left option and right option
if val.x >= 0 and val.x < (len(self.mymap)-1):
if self.mymap[val.x+1][val.y] in adj:
node1 = self.mymap[n.x+1][n.y]
else:
node1 = 0.0
if self.mymap[n.x-1][n.y] in adj:
node2 = self.mymap[n.x-1][n.y]
else:
node2 = 0.0
if node1 == 0.0 and node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val])
elif node1 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node2])
elif node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1])
else:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1]+0.1*self.prev_util[node2])
return max(stored_vals) #return the best policy
#A* search (Modified)
def starsearch(self):
self.Open[self.start] = self.util_list[self.start] #start our Open list with the reward value stored in util_list
while self.Open != {}:
#find reward that is the LARGEST
max_val_find = max(self.Open, key=self.Open.get)#we want the largest reward, so I changed MIN to MAX
max_val = self.Open[max_val_find]
for value in self.Open:
if self.Open[value] == max_val:
node = value
break
del self.Open[node]
if node.x == self.goal.x and node.y == self.goal.y:
self.time_to_print(node)
break
self.Close[node] = self.util_list[node]
node_adj = self.getAdj(node)
for n in node_adj:
if (n.typeN != 2 and not(n in self.Close)):
if not(n in self.Open) or (self.util_list[n] > self.util_list[node]):
n.setParent(node)
if not(n in self.Open):
self.Open[n] = self.util_list[n]
def time_to_print(self, nextNode):
print "This is my path: "
cost = 0
stringArr = []
while not(nextNode.x == self.start.x and nextNode.y == self.start.y):
stringArr.append(["(", nextNode.x, ",", nextNode.y, ")","Utility: ",self.util_list[nextNode]])
nextNode = nextNode.p
stringArr.append(["(", nextNode.x, ",", nextNode.y, ")", "Utility: ",self.util_list[nextNode]])
for lis in reversed(stringArr):
print lis[0],lis[1],lis[2],lis[3],lis[4],lis[5],lis[6]
mymap = getMap(sys.argv[1])
searched = MDP(mymap)
searched.expect_u(float(sys.argv[2]))
searched.starsearch()
|
baf478cdd62e5bd29bfaaa725f32fa2d041ae191 | louissock/Python-PPA | /ccipher.py | 6,844 | 3.84375 | 4 | """
Filename: ccipher.py
Author: Sang Shin
Date: 09/05/2012
"""
#!/bin/env python
import sys
CONST_ALBET = 'abcdefghijklmnopqrstuvwxyz'
MOD_ALBET = ''
def exit_program():
# Prompt the user with a exiting greet and terminate.
print "Thank you for using the Caesar Cipher Program."
print "Have a nice day."
sys.exit()
def rotate_alphabet(rot, direc):
rot = int(rot)
# For left rotations, we need to adapt for numbers greater than 26
# Rotate the alphabet to the left
if (str(direc).lower() == 'l') or (str(direc).lower() == "left"):
while rot == len(CONST_ALBET) or rot > len(CONST_ALBET):
rot = rot - len(CONST_ALBET)
lowEnd = [CONST_ALBET[i] for i in range(0, rot)]
highEnd = [CONST_ALBET[i] for i in range(rot, len(CONST_ALBET))]
modAlphabetList = highEnd + lowEnd
modAlphabet = "".join(modAlphabetList)
return modAlphabet
# For right rotations, we need to adapt for numbers greater than 26
# Rotate the alpabet to the right
elif (str(direc).lower() == 'r') or (str(direc).lower() == "right"):
while rot == len(CONST_ALBET) or rot > len(CONST_ALBET):
rot = rot - len(CONST_ALBET)
lowEnd = [CONST_ALBET[i] for i in range(len(CONST_ALBET) - rot, len(CONST_ALBET))]
highEnd = [CONST_ALBET[i] for i in range(0, (len(CONST_ALBET) - rot))]
modAlphabetList = lowEnd + highEnd
modAlphabet = "".join(modAlphabetList)
return modAlphabet
else:
print "An error occurred. Exiting."
sys.exit()
def encode_string(userString):
(encodedString, encodedSplitString) = ([],[])
# Check to see if the letter is in the alphabet. If not, add it to the array.
# If the letter is in the alphabet, we need to find the index of it in the
# original alphabet, and find the corresponding letter in the modified alphabet.
for lett in str(userString).lower():
if lett in str(CONST_ALBET):
idx = str(CONST_ALBET).index(lett.lower())
count = 0
for lett_mod in str(MOD_ALBET):
if int(idx) == count:
encodedString.append(lett_mod)
break
else:
count += 1
else:
encodedString.append(lett)
# We have a list that contains only letters. We are going to combine the letters
# to create the word and add it to a list.
encodedString = ''.join(encodedString)
encodedSplitString = encodedString.split()
return encodedSplitString
def encode_procedure():
global MOD_ALBET
userString = raw_input("Enter a string to encode: ")
userRotation = raw_input("Enter a rotation: ")
while True:
userDirection = raw_input("Enter a direction (L or R): ")
# Check for correction direction
if (str(userDirection).lower() == 'l') or \
(str(userDirection).lower() == 'left') or \
(str(userDirection).lower() == 'r') or \
(str(userDirection).lower() == 'right'):
break
else:
print "Invalid input. Try again."
MOD_ALBET = rotate_alphabet(userRotation, userDirection)
encodedUserString = encode_string(userString)
encodedUserString = ' '.join(encodedUserString)
print
print "Encoded String: %s" % encodedUserString
def check_decode_procedure(userString, userWord):
# We want to loop through every possible combination of
# rotations of the alphabet and see if the word provided
# by the user is in the decoded string.
#
# There are two possible outcomes for every decoding method
# for left and right rotations. Since these rotations overlap
# somewhere, we need to find both.
global MOD_ALBET
decodedData = {}
for i in range(1, len(CONST_ALBET) + 1):
MOD_ALBET = rotate_alphabet(i, 'l')
decodedUserString = decode_string(userString)
if userWord in decodedUserString:
decodedData["Left"] = i
break
for i in range(1, len(CONST_ALBET) + 1):
MOD_ALBET = rotate_alphabet(i, 'r')
decodedUserString = decode_string(userString)
if userWord in decodedUserString:
decodedData["Right"] = i
break
return (decodedUserString, decodedData)
def decode_string(userString):
(decodedString, decodedSplitString) = ([],[])
# Check to see if the letter is in the MOD_Alphabet. If not, add it to the array.
# If the letter is in the MOD_Alphabet, we need to find the index of it in the
# MOD_Alphabet, and find the corresponding letter in the original alphabet.
for lett_mod in str(userString).lower():
if lett_mod in str(MOD_ALBET):
idx = str(MOD_ALBET).index(lett_mod.lower())
count = 0
for lett in str(CONST_ALBET):
if int(idx) == count:
decodedString.append(lett)
break
else:
count += 1
else:
decodedString.append(lett_mod)
# We have a list that contains only letters. We are going to combine the letters
# to create the word and add it to a list.
decodedString = ''.join(decodedString)
decodedSplitString = decodedString.split()
return decodedSplitString
def decode_procedure():
global MOD_ALBET
userString = raw_input("Enter a string to decode: ")
userWord = raw_input("Enter a word in the string: ")
(decodedUserString, decodeData) = check_decode_procedure(userString, userWord)
decodedUserString = ' '.join(decodedUserString)
print
print "Decoded String: %s" % decodedUserString
print "Possible Combinations: "
if "Left" in decodeData:
print "\t Direction: Left \t Rotation: %s" % decodeData["Left"]
if "Right" in decodeData:
print "\t Direction: Right \t Rotation: %s" % decodeData["Right"]
else:
print "\t None. Decoding procedure failed."
def main():
print "This is the Caesar Cipher Program."
print "This will either encode or decode a string with the Caesar Algorithm."
while True:
print
print "\t 'e' to ENCODE"
print "\t 'd' to DECODE"
print "\t 'q' to QUIT"
print
userInput = raw_input("\t ---> ")
if (str(userInput).lower() == 'e') or (str(userInput).lower() == 'encode'):
encode_procedure()
elif (str(userInput).lower() == 'd') or (str(userInput).lower() == 'decode'):
decode_procedure()
elif (str(userInput).lower() == 'q') or (str(userInput).lower() == 'quit'):
exit_program()
else:
print "Invalid Input. Try again."
if __name__ == "__main__":
main()
|
fcd42737dc107cd0ddda3a5ea2963abbca0bff55 | louissock/Python-PPA | /gasoline.py | 1,469 | 3.671875 | 4 | """
Filename: gasoline.py
Author: Sang Shin
Date: 08/09/2012
"""
#!/bin/env python
from __future__ import division
CONVERSION_GAL_LITER = 3.7854
CONVERSION_GAL_BARREL = 19.5
CONVERSION_GAL_POUND = 20
CONVERSION_GAL_ENERGY = 115000
CONVERSION_GAL_ENERGY_ETH = 75700
CONVERSION_GAL_DOLLAR = 4.00
def main():
user_input = raw_input("Please enter the number of gallons of gasoline: ")
input_fl = float(user_input)
print "Original number of gallons is: %.2f" % input_fl
print "%.2f gallons is the equivalent of %.2f liters" % (input_fl, \
input_fl * CONVERSION_GAL_LITER)
print "%.2f gallons of gasoline requires %f barrels of oil" % (input_fl, \
input_fl / CONVERSION_GAL_BARREL)
print "%.2f gallons of gasoline produces %.2f pounds of C02" % (input_fl, \
input_fl * CONVERSION_GAL_POUND)
print "%.2f gallons of gasoline is energy equivalent to %.2f gallons of ethanol" % (input_fl, \
(input_fl * CONVERSION_GAL_ENERGY_ETH)/CONVERSION_GAL_ENERGY)
print "%.2f gallons of gasoline requires $%.2f U.S. Dollars" % (input_fl, input_fl * CONVERSION_GAL_DOLLAR)
print
print "Thank you for playing"
if __name__ == "__main__":
main()
|
ff69e17bc700225f4eb40e087d613599d79aedfa | louissock/Python-PPA | /digicount.py | 847 | 3.734375 | 4 | """
Filename: digicount.py
Author: Sang Shin
Date: 08/10/2012
"""
#!/bin/env python
def userInputChecker(diag):
check = 1
while check == 1:
try:
inp_str = raw_input(diag)
inp_int = int(inp_str)
check = 0
except ValueError:
check = 1
print "Please enter a valid number."
return inp_int
def main():
inp_int = userInputChecker("Enter a number: ")
print "The number entered is %d" % inp_int
print
inp_int_digi = userInputChecker("Enter a digit: ")
print "The digit entered is %d" % inp_int_digi
print
digi_arr = [digi for digi in str(inp_int)]
count = digi_arr.count(str(inp_int_digi))
print "The number of %s's in %s is %d" % (str(inp_int_digi), str(inp_int), count)
if __name__ == "__main__":
main()
|
a57504d5e5dd34e53a3e30b2e0987ae6314d6077 | MattCoston/Python | /shoppinglist.py | 298 | 4.15625 | 4 | shopping_list = []
print ("What do you need to get at the store?")
print ("Enter 'DONE' to end the program")
while True:
new_item = input("> ")
shopping_list.append(new_item)
if new_item == 'DONE':
break
print("Here's the list:")
for item in shopping_list:
print(item)
|
5682494536ebd893e233685b4395290391c6c2b2 | VanSC/Lab7 | /Problema6.py | 575 | 3.875 | 4 | pares=0
impares=0
neutro=0
negativos=0
positivos=0
limite=5
for x in range(limite):
number=int(input("ingres el numero "))
if number % 2 == 0:
pares+=1
else:
impares+=1
if x<0:
negativos+=1
else:
positivos+=1
if number == 0:
neutro = 0
print("La cantidad de numeros pares es: ",pares)
print("La cantidad de numeros impares es: ",impares)
print("La cantidad de numeros negativos es: ",negativos)
print("La cantidad de numeros positivos es: ",positivos)
print("El numero neutro es: ",neutro) |
edea61d2217ce4cb2beceb5211bfbd0a844b4a1a | dennisliuu/Coding-365 | /102/003.py | 795 | 3.828125 | 4 | import math
triType = input()
triHeight = int(input())
if triType == '1':
for i in range(1, (triHeight + 1) // 2 + 1):
for j in range(1, i + 1):
print(j, end='')
print()
for i in range(1, (triHeight + 1) // 2):
for j in range(1, (triHeight + 1) // 2 - i + 1):
print(j, end='')
print()
elif triType == '2':
for i in range(1, (triHeight + 1) // 2 + 1):
for j in range(1, (triHeight + 1) // 2 - i + 1):
print('.', end='')
for j in range(i, 0, -1):
print(j, end='')
print()
for i in range(1, (triHeight + 1) // 2):
for j in range(0, i):
print('.', end='')
for j in range((triHeight + 1) // 2 - i, 0, -1):
print(j,end='')
print()
|
5635f384336ab7a9cda34f2217deb0b2aede9388 | dennisliuu/Coding-365 | /101/001.py | 337 | 3.765625 | 4 | name = input("姓名:")
std_id = input("學號:")
score1 = int(input("第一科成績:"))
score2 = int(input("第二科成績:"))
score3 = int(input("第三科成績:"))
total = score1 + score2 + score3
print("Name:" + name + '\n' + "Id:" + std_id + '\n' +
"Total:" + str(total) + '\n' + "Average:" + str(int(total/3))) |
f174320582815cb1397828890720288b72bab536 | dennisliuu/Coding-365 | /103/003.py | 2,800 | 3.75 | 4 | # class poly:
# __a = [0]*20 #存放第一个输入的多项式和运算结果
# __b = [0]*20#存放输入的多项式
# __result = [0]*20#结果
# def __Input(self,f):
# n = input('依序输入二项式的系数和指数(指数小于10):').split()
# for i in range(int(len(n)/2)):
# f[ int(n[2*i+1])] = int(n[2*i])
# print(f, n)
# self.__output(f)
# def __add(self,a,b): #加法函数
# return [a[i]+b[i] for i in range(20)]
# def __minus(self,a,b): #减法函数
# return [a[i]-b[i] for i in range(20)]
# def __mul(self,a,b):
# self.__result = [0]*20
# for i in range(10):#第一个循环:b分别于a[0]到a[9]相乘
# for j in range(10): #第二个循环:b[j]*a[i]
# self.__result[i+j] = int(self.__result[i+j]) + int(a[i]*b[j])
# return self.__result
# def __output(self,a):#输出多项式
# b = ''
# for i in range(20):
# if a[i]> 0:
# b = b+'+'+str(a[i])+'X^'+str(i)
# if a[i]<0:
# b = b+"-"+str(-a[i])+'X^'+str(i)
# print(b[1::])
# def control(self):
# print ("二项式运算:\n")
# self.__Input(self.__a)
# while True:
# operator = input('请输入运算符(结束运算请输入‘#’)')#self.Input(self.a)
# if operator =='#':
# return 0
# else:
# self.__b = [0]*20
# self.__Input(self.__b)
# self.__a = {'+':self.__add(self.__a,self.__b),'-':self.__minus(self.__a,self.__b),'*':self.__mul(self.__a,self.__b)}.get(operator)
# print ('计算结果:',end='')
# self.__output(self.__a)
# POLY = poly() #初始化类
# POLY.control() #通过选取操作符选择相应的运算
# import numpy as np
# # sym = input()
# # 4x^3 - 2x + 3
list1 = []
p1 = input().split(' ')
for i in p1:
list1.append(i)
print(list1)
t = len(list1)
for i in range(len(list1)):
if i == t:
break
if list1[i] == '-':
list1[i:i+2] = [''.join(list1[i:i+2])]
t -= 1
print(list1)
x_times = [s for s in list1 if "x" in s]
print(x_times)
print(
list(set(list1) - set(x_times)).remove('+')
)
coef = []
for i in range(len(x_times)):
coef.append(x_times[i].split('x')[0])
coef.append((x_times[i].split('x')[1]))
for i in range(len(coef)):
if coef[i] == '':
coef[i] = 1
elif coef[i] == '-':
coef[i] = -1
print(coef)
# # p1 = np.poly1d([4, 0, -2, 3])
# # p2 = np.poly1d([-2, 0, -1, 3, -1, -1])
# # if sym == '+':
# # print(p1 + p2)
# # elif sym == '-':
# # print(p1 - p2)
# # elif sym == '*':
# # print(p1 * p2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.