blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c32d0f7b44749e6ae0ecec14ed2a2002e9b8bb7b | rootme254/Python-Projects | /shop.py | 3,154 | 4.21875 | 4 | '''
This is a shopping list like ile inatumiwa in jumia the online shopping
Create a class called ShoppingCart.
Create a constructor that has no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.
Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of these items from the current total and also update the items dict accordingly. If the quantity of items to be removed exceeds current quantity in cart, assume that all entries of that item are to be removed.
Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return Cash paid not enough.
Create a class called Shop that has a constructor which initializes an attribute called quantity at 100.
Make sure Shop inherits from ShoppingCart.
In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.
'''
class ShoppingCart (object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self,item_name ,quantity ,price):
self.total =self.total + price
self.items[item_name]=quantity
def remove_item(self,item_name ,quantity,price):
del self.items[item_name]
self.total = self.total - price
value=0
for k,v in self.items.items():
value += v
if (quantity > value ):
self.items.clearAll()
def checkout(self,cash_paid):
if (cash_paid < self.total):
print ("Cash paid not enough ")
else:
self.balance= cash_paid - self.total
print ("Total amount for the goods below ",self.total)
print (self.items)
print ("The arrears after payment is ",self.balance)
def show_details(self):
print (self.items)
class Shop(ShoppingCart):
'''If you wanted the constructor to be handled by the ->>
super constructor
super.(ShoppingCart,self).__init__(item_name ,quantity ,price)
'''
def __init__(self):
self.quantity=100
#Overriding the remove_item
def remove_item(self):
self.quantity =- 1
sh=ShoppingCart()
sh.add_item("Cars",30,3452.34)
sh.add_item("Computer",20,3452.34)
sh.add_item("Movies",20,34523.34)
sh.add_item("Papers",10,1000)
sh.remove_item("Papers",10,1000)
sh.show_details()
sh.checkout(80000)
|
e604fb50261893929a57a9377d7e7b0e11a9b851 | georgeyjm/Sorting-Tests | /sort.py | 2,686 | 4.34375 | 4 | def someSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i+1,length):
comparisons += 1
if array[i] > array[j]:
accesses += 1
array[i], array[j] = array[j], array[i]
return array, comparisons, accesses
def insertionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i):
comparisons += 1
if array[j] > array[i]:
accesses += 1
array.insert(j,array[i])
del array[i+1]
return array, comparisons, accesses
def selectionSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
min = i
for j in range(i+1,length):
comparisons += 1
if array[j] < array[min]:
accesses += 1
min = j
array[i], array[min] = array[min], array[i]
return array, comparisons, accesses
def bubbleSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length-1):
for j in range(length-1,i,-1):
comparisons += 1
if array[j] < array[j-1]:
accesses += 1
array[j], array[j-1] = array[j-1], array[j]
return array, comparisons, accesses
def mergeSort(array,comparisons=0,accesses=0):
'''Or is it quick sort??'''
if len(array) == 1: return array, comparisons, accesses
result = []
middle = len(array) // 2
left, comparisons, accesses = mergeSort(array[:middle],comparisons,accesses)
right, comparisons, accesses = mergeSort(array[middle:],comparisons,accesses)
leftIndex, rightIndex = 0,0
while leftIndex < len(left) and rightIndex < len(right):
comparisons += 1
if left[leftIndex] > right[rightIndex]:
result.append(right[rightIndex])
rightIndex += 1
else:
result.append(left[leftIndex])
leftIndex += 1
result += left[leftIndex:] + right[rightIndex:]
return result, comparisons, accesses
def bogoSort(array):
'''Time Complexity: O(1) (best), O(∞) (worst)'''
from random import shuffle
comparisons, accesses = 0,0
while True:
for i in range(1, len(array)):
comparisons += 1
if array[i] < array[i-1]: break
else:
break
shuffle(array)
accesses += 1
return array, comparisons, accesses
|
c444e7a76a76479c82d08818bcdb38b51cfe073e | 4dasha45/COM411 | /basics/data_visuialisation/function/ascii_code.py | 238 | 4.09375 | 4 | print("program started")
print("Please enter a standard character:")
word=input()
if (len(word)==1):
print("th ascii code for {}is {}".format(word,ord(word)))
else:
print("A single character was expected")
print("end the program") |
4f4431799d2dc9cf46e296cf132e3f77bdeffc3d | asiskc/python_assignment_jan5 | /student.py | 1,030 | 3.875 | 4 | class CheckError():
def __init__(self,roll):
if(roll>24):
raise NameError()
dict = {
1: "student1",
2: "student2"
}
choice = 1
while (choice==1):
try:
choice = int(input("choose an option"))
if (choice == 1):
roll = int(input("roll no:"))
name = input("name: ")
CheckError(roll)
dict.update({roll: name})
elif (choice == 2):
roll = int(input("roll no.: "))
print(dict[roll])
elif (choice == 3):
del dict
except KeyError:
print("Roll no. does not exist")
except NameError:
print("cannot accomadate more than 24 students")
except ValueError:
print("enter an ingteger roll no.")
except TypeError:
print("students list doesnot exist")
else:
print("Error occured")
finally:
loop = input("would you like to continue? (yes/no)")
if(loop == "yes"):
choice=1
else:
choice=0
|
7c314615e75b8f7f02f68c040f50f854bcb8e1cb | jilljenn/tryalgo | /tryalgo/knapsack.py | 3,210 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Knapsack
jill-jênn vie et christoph dürr - 2015-2019
"""
# snip{
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, list of item indexes in solution
:complexity: O(n * cmax), for n = number of items
"""
n = len(p)
opt = [[0] * (cmax + 1) for _ in range(n + 1)]
sel = [[False] * (cmax + 1) for _ in range(n + 1)]
# --- basic case
for cap in range(p[0], cmax + 1):
opt[0][cap] = v[0]
sel[0][cap] = True
# --- induction case
for i in range(1, n):
for cap in range(cmax + 1):
if cap >= p[i] and opt[i-1][cap - p[i]] + v[i] > opt[i-1][cap]:
opt[i][cap] = opt[i-1][cap - p[i]] + v[i]
sel[i][cap] = True
else:
opt[i][cap] = opt[i-1][cap]
sel[i][cap] = False
# --- reading solution
cap = cmax
solution = []
for i in range(n-1, -1, -1):
if sel[i][cap]:
solution.append(i)
cap -= p[i]
return (opt[n - 1][cmax], solution)
# snip}
def knapsack2(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity.
alternative implementation with same behavior.
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, list of item indexes in solution
:complexity: O(n * cmax), for n = number of items
"""
n = len(p)
# Plus grande valeur obtenable avec objets ≤ i et capacité c
pgv = [[0] * (cmax + 1) for _ in range(n)]
for c in range(cmax + 1): # Initialisation
pgv[0][c] = v[0] if c >= p[0] else 0
pred = {} # Prédécesseurs pour mémoriser les choix faits
for i in range(1, n):
for c in range(cmax + 1):
pgv[i][c] = pgv[i - 1][c] # Si on ne prend pas l'objet i
pred[(i, c)] = (i - 1, c)
# Est-ce que prendre l'objet i est préférable ?
if c >= p[i] and pgv[i - 1][c - p[i]] + v[i] > pgv[i][c]:
pgv[i][c] = pgv[i - 1][c - p[i]] + v[i]
pred[(i, c)] = (i - 1, c - p[i]) # On marque le prédécesseur
# On pourrait s'arrêter là, mais si on veut un sous-ensemble d'objets
# optimal, il faut remonter les marquages
cursor = (n - 1, cmax)
chosen = []
while cursor in pred:
# Si la case prédécesseur a une capacité inférieure
if pred[cursor][1] < cursor[1]:
# C'est qu'on a ramassé l'objet sur le chemin
chosen.append(cursor[0])
cursor = pred[cursor]
if cursor[1] > 0: # A-t-on pris le premier objet ?
# (La première ligne n'a pas de prédécesseur.)
chosen.append(cursor[0])
return pgv[n - 1][cmax], chosen
|
5f5e2d3f7bf5b6e1553e8c10d331d5d4143346af | jilljenn/tryalgo | /tryalgo/gauss_jordan.py | 2,290 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Linear equation system Ax=b by Gauss-Jordan
jill-jenn vie et christoph durr - 2014-2018
"""
__all__ = ["gauss_jordan", "GJ_ZERO_SOLUTIONS", "GJ_SINGLE_SOLUTION",
"GJ_SEVERAL_SOLUTIONS"]
# snip{
# pylint: disable=chained-comparison
def is_zero(x): # tolerance
"""error tolerant zero test
"""
return -1e-6 < x and x < 1e-6
# replace with x == 0 si we are handling Fraction elements
GJ_ZERO_SOLUTIONS = 0
GJ_SINGLE_SOLUTION = 1
GJ_SEVERAL_SOLUTIONS = 2
def gauss_jordan(A, x, b):
"""Linear equation system Ax=b by Gauss-Jordan
:param A: m by n matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique,
2 otherwise
:complexity: :math:`O(n^2m)`
"""
n = len(x)
m = len(b)
assert len(A) == m and len(A[0]) == n
S = [] # put linear system in a single matrix S
for i in range(m):
S.append(A[i][:] + [b[i]])
S.append(list(range(n))) # indices in x
k = diagonalize(S, n, m)
if k < m:
for i in range(k, m):
if not is_zero(S[i][n]):
return GJ_ZERO_SOLUTIONS
for j in range(k):
x[S[m][j]] = S[j][n]
if k < n:
for j in range(k, n):
x[S[m][j]] = 0
return GJ_SEVERAL_SOLUTIONS
return GJ_SINGLE_SOLUTION
def diagonalize(S, n, m):
"""diagonalize """
for k in range(min(n, m)):
val, i, j = max((abs(S[i][j]), i, j)
for i in range(k, m) for j in range(k, n))
if is_zero(val):
return k
S[i], S[k] = S[k], S[i] # swap lines k, i
for r in range(m + 1): # swap columns k, j
S[r][j], S[r][k] = S[r][k], S[r][j]
pivot = float(S[k][k]) # without float if Fraction elements
for j in range(k, n + 1):
S[k][j] /= pivot # divide line k by pivot
for i in range(m): # remove line k scaled by line i
if i != k:
fact = S[i][k]
for j in range(k, n + 1):
S[i][j] -= fact * S[k][j]
return min(n, m)
# snip}
|
1204ef8366837b66f591ff142e663df7302c87b5 | jilljenn/tryalgo | /tryalgo/graph01.py | 1,275 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest path in a 0,1 weighted graph
jill-jenn vie et christoph durr - 2014-2018
"""
from collections import deque
# snip{
def dist01(graph, weight, source=0, target=None):
"""Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is found
:returns: distance table, predecessor table
:complexity: `O(|V|+|E|)`
"""
n = len(graph)
dist = [float('inf')] * n
prec = [None] * n
black = [False] * n
dist[source] = 0
gray = deque([source])
while gray:
node = gray.pop()
if black[node]:
continue
black[node] = True
if node == target:
break
for neighbor in graph[node]:
ell = dist[node] + weight[node][neighbor]
if black[neighbor] or dist[neighbor] <= ell:
continue
dist[neighbor] = ell
prec[neighbor] = node
if weight[node][neighbor] == 0:
gray.append(neighbor)
else:
gray.appendleft(neighbor)
return dist, prec
# snip}
|
322e307335af2bdf4474d2f78117c867668243ef | jilljenn/tryalgo | /tryalgo/levenshtein.py | 817 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Levenshtein edit distance
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def levenshtein(x, y):
"""Levenshtein edit distance
:param x:
:param y: strings
:returns: distance
:complexity: `O(|x|*|y|)`
"""
n = len(x)
m = len(y)
# Create the table A
# Row 0 and column 0 are initialized as required
# The remaining entries will be overwritten during the computation
A = [[i + j for j in range(m + 1)] for i in range(n + 1)]
for i in range(n):
for j in range(m):
A[i + 1][j + 1] = min(A[i][j + 1] + 1, # insert
A[i + 1][j] + 1, # delete
A[i][j] + int(x[i] != y[j])) # subst.
return A[n][m]
# snip}
|
eea13b5f1c5f7a88cbba2d5a56e5101de59a96dd | jilljenn/tryalgo | /tryalgo/dijkstra.py | 2,886 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest paths by Dijkstra
jill-jênn vie et christoph dürr - 2015-2018
"""
# pylint: disable=wrong-import-position
from heapq import heappop, heappush
from tryalgo.our_heap import OurHeap
# snip{
def dijkstra(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
:param graph: directed graph in listlist or listdict format
:param weight: in matrix format or same listdict graph
:assumes: weights are non-negative
:param source: source vertex
:type source: int
:param target: if given, stops once distance to target found
:type target: int
:returns: distance table, precedence table
:complexity: `O(|V| + |E|log|V|)`
"""
n = len(graph)
assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u])
prec = [None] * n
black = [False] * n
dist = [float('inf')] * n
dist[source] = 0
heap = [(0, source)]
while heap:
dist_node, node = heappop(heap) # Closest node from source
if not black[node]:
black[node] = True
if node == target:
break
for neighbor in graph[node]:
dist_neighbor = dist_node + weight[node][neighbor]
if dist_neighbor < dist[neighbor]:
dist[neighbor] = dist_neighbor
prec[neighbor] = node
heappush(heap, (dist_neighbor, neighbor))
return dist, prec
# snip}
# snip{ dijkstra_update_heap
# snip}
# snip{ dijkstra_update_heap
def dijkstra_update_heap(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
with a heap implementing item updates
:param graph: adjacency list or adjacency dictionary of a directed graph
:param weight: matrix or adjacency dictionary
:assumes: weights are non-negatif and weights are infinite for non edges
:param source: source vertex
:type source: int
:param target: if given, stops once distance to target found
:type target: int
:returns: distance table, precedence table
:complexity: `O(|V| + |E|log|V|)`
"""
n = len(graph)
assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u])
prec = [None] * n
dist = [float('inf')] * n
dist[source] = 0
heap = OurHeap([(dist[node], node) for node in range(n)])
while heap:
dist_node, node = heap.pop() # Closest node from source
if node == target:
break
for neighbor in graph[node]:
old = dist[neighbor]
new = dist_node + weight[node][neighbor]
if new < old:
dist[neighbor] = new
prec[neighbor] = node
heap.update((old, neighbor), (new, neighbor))
return dist, prec
# snip}
|
1f90271814c98307cdfb0dc1111f011c619498ba | eliaskousk/example-code-2e | /24-class-metaprog/setattr/example_from_leo.py | 340 | 3.71875 | 4 | #!/usr/bin/env python3
class Foo:
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = value
def __setattr__(self, name, value):
print(f'setting {name!r} to {value!r}')
super().__setattr__(name, value)
o = Foo()
o.bar = 8
print(o.bar)
print(o._bar)
|
a82eb08a4de5bab1c90099a414eda670219aeb95 | eliaskousk/example-code-2e | /21-async/mojifinder/charindex.py | 2,445 | 4.15625 | 4 | #!/usr/bin/env python
"""
Class ``InvertedIndex`` builds an inverted index mapping each word to
the set of Unicode characters which contain that word in their names.
Optional arguments to the constructor are ``first`` and ``last+1``
character codes to index, to make testing easier. In the examples
below, only the ASCII range was indexed.
The `entries` attribute is a `defaultdict` with uppercased single
words as keys::
>>> idx = InvertedIndex(32, 128)
>>> idx.entries['DOLLAR']
{'$'}
>>> sorted(idx.entries['SIGN'])
['#', '$', '%', '+', '<', '=', '>']
>>> idx.entries['A'] & idx.entries['SMALL']
{'a'}
>>> idx.entries['BRILLIG']
set()
The `.search()` method takes a string, uppercases it, splits it into
words, and returns the intersection of the entries for each word::
>>> idx.search('capital a')
{'A'}
"""
import sys
import unicodedata
from collections import defaultdict
from collections.abc import Iterator
STOP_CODE: int = sys.maxunicode + 1
Char = str
Index = defaultdict[str, set[Char]]
def tokenize(text: str) -> Iterator[str]:
"""return iterator of uppercased words"""
for word in text.upper().replace('-', ' ').split():
yield word
class InvertedIndex:
entries: Index
def __init__(self, start: int = 32, stop: int = STOP_CODE):
entries: Index = defaultdict(set)
for char in (chr(i) for i in range(start, stop)):
name = unicodedata.name(char, '')
if name:
for word in tokenize(name):
entries[word].add(char)
self.entries = entries
def search(self, query: str) -> set[Char]:
if words := list(tokenize(query)):
found = self.entries[words[0]]
return found.intersection(*(self.entries[w] for w in words[1:]))
else:
return set()
def format_results(chars: set[Char]) -> Iterator[str]:
for char in sorted(chars):
name = unicodedata.name(char)
code = ord(char)
yield f'U+{code:04X}\t{char}\t{name}'
def main(words: list[str]) -> None:
if not words:
print('Please give one or more words to search.')
sys.exit(2) # command line usage error
index = InvertedIndex()
chars = index.search(' '.join(words))
for line in format_results(chars):
print(line)
print('─' * 66, f'{len(chars)} found')
if __name__ == '__main__':
main(sys.argv[1:])
|
a04924cd0fc7da072413c4062f8a2a1258f58e32 | eliaskousk/example-code-2e | /05-data-classes/dataclass/coordinates.py | 512 | 3.5625 | 4 | """
``Coordinate``: simple class decorated with ``dataclass`` and a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from dataclasses import dataclass
@dataclass(frozen=True)
class Coordinate:
lat: float
lon: float
def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.lon >= 0 else 'W'
return f'{abs(self.lat):.1f}°{ns}, {abs(self.lon):.1f}°{we}'
# end::COORDINATE[]
|
f23ba5514189ed232eeaaf3cd6a4ea8fb799864e | eliaskousk/example-code-2e | /20-executors/getflags/slow_server.py | 3,986 | 3.515625 | 4 | #!/usr/bin/env python3
"""Slow HTTP server class.
This module implements a ThreadingHTTPServer using a custom
SimpleHTTPRequestHandler subclass that introduces delays to all
GET responses, and optionally returns errors to a fraction of
the requests if given the --error_rate command-line argument.
"""
import contextlib
import os
import socket
import time
from functools import partial
from http import server, HTTPStatus
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from random import random, uniform
MIN_DELAY = 0.5 # minimum delay for do_GET (seconds)
MAX_DELAY = 5.0 # maximum delay for do_GET (seconds)
class SlowHTTPRequestHandler(SimpleHTTPRequestHandler):
"""SlowHTTPRequestHandler adds delays and errors to test HTTP clients.
The optional error_rate argument determines how often GET requests
receive a 418 status code, "I'm a teapot".
If error_rate is .15, there's a 15% probability of each GET request
getting that error.
When the server believes it is a teapot, it refuses requests to serve files.
See: https://tools.ietf.org/html/rfc2324#section-2.3.2
"""
def __init__(self, *args, error_rate=0.0, **kwargs):
self.error_rate = error_rate
super().__init__(*args, **kwargs)
def do_GET(self):
"""Serve a GET request."""
delay = uniform(MIN_DELAY, MAX_DELAY)
cc = self.path[-6:-4].upper()
print(f'{cc} delay: {delay:0.2}s')
time.sleep(delay)
if random() < self.error_rate:
# HTTPStatus.IM_A_TEAPOT requires Python >= 3.9
try:
self.send_error(HTTPStatus.IM_A_TEAPOT, "I'm a Teapot")
except BrokenPipeError as exc:
print(f'{cc} *** BrokenPipeError: client closed')
else:
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
except BrokenPipeError as exc:
print(f'{cc} *** BrokenPipeError: client closed')
finally:
f.close()
# The code in the `if` block below, including comments, was copied
# and adapted from the `http.server` module of Python 3.9
# https://github.com/python/cpython/blob/master/Lib/http/server.py
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('--error-rate', '-e', metavar='PROBABILITY',
default=0.0, type=float,
help='Error rate; e.g. use .25 for 25%% probability '
'[default:0.0]')
parser.add_argument('port', action='store',
default=8001, type=int,
nargs='?',
help='Specify alternate port [default: 8001]')
args = parser.parse_args()
handler_class = partial(SlowHTTPRequestHandler,
directory=args.directory,
error_rate=args.error_rate)
# ensure dual-stack is not disabled; ref #38907
class DualStackServer(ThreadingHTTPServer):
def server_bind(self):
# suppress exception when protocol is IPv4
with contextlib.suppress(Exception):
self.socket.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
return super().server_bind()
# test is a top-level function in http.server omitted from __all__
server.test( # type: ignore
HandlerClass=handler_class,
ServerClass=DualStackServer,
port=args.port,
bind=args.bind,
)
|
d2977b7a63a6f0bebe59544ccaf8fc1763570d1c | eliaskousk/example-code-2e | /05-data-classes/typing_namedtuple/coordinates.py | 487 | 3.765625 | 4 | """
``Coordinate``: a simple ``NamedTuple`` subclass with a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from typing import NamedTuple
class Coordinate(NamedTuple):
lat: float
lon: float
def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.lon >= 0 else 'W'
return f'{abs(self.lat):.1f}°{ns}, {abs(self.lon):.1f}°{we}'
# end::COORDINATE[]
|
06b96c803dcc6f53a2db59b8ba48e68c47e4df33 | anqi117/py-study | /namecard-func.py | 2,341 | 3.703125 | 4 | card_infor = []
def print_menu():
print("="*50)
print(" 名片系统 v1.0")
print("1. add a new card")
print("2. delete a card")
print("3. update a card")
print("4. search a card")
print("5. show all of cards")
print("6. exit")
print("="*50)
def add_new_card_info():
new_name = input("name: ")
new_qq = input("qq: ")
new_wechat = input("wechat: ")
new_addr = input("addr: ")
new_infor = {}
new_infor['name'] = new_name
new_infor['qq'] = new_qq
new_infor['wechat'] = new_wechat
new_infor['addr'] = new_addr
# 将一个字典添加到列表中
global card_infor
card_infor.append(new_infor)
print(card_infor)
def delete_card():
flag = 0
target_card_name = input("please input the name you want to delete:")
for i, card in enumerate(card_infor):
if card['name'] == target_card_name:
del card_infor[i]
print(card_infor)
flag = 1
if flag == 0:
print("Card can not be found")
def update_card_info():
flag = 0
target_card_name = input("please input the name you want to update:")
for card in card_infor:
if card['name'] == target_card_name:
card['qq'] = input("please input a new qq: ")
card['wechat'] = input("please input a new wechat: ")
card['addr'] = input("please input a new addr: ")
flag = 1
print("update successd!\n")
print("%s\t%s\t%s\t%s"%(card['name'], card['qq'], card['wechat'], card['addr']))
break
if flag == 0:
print("Card can not be found.")
def search_card():
"""search a card by name"""
search_name = input("name: ")
global card_infor
for card in card_infor:
if card['name'] == search_name:
print(card)
break
else:
print("There is not a data about %s."%search_name)
def show_all_card():
print("%s\t%s\t%s\t%s"%("name", "qq", "wechat", "addr"))
global card_infor
for card in card_infor:
print("%s\t%s\t%s\t%s"%(card['name'],card['qq'],card['wechat'],card['addr']))
def main():
#1 打印功能提示
print_menu()
while True:
#2 获取用户输入
num = int(input("Please input a function number: "))
#3 根据用户的数据执行相对应的功能
if num==1:
add_new_card_info()
elif num==2:
delete_card()
elif num==3:
update_card_info()
elif num==4:
search_card()
elif num==5:
show_all_card()
elif num==6:
break
else:
print("Please input correct number.")
print("")
main()
|
50dc5fc8bf4ec94682c5d984b9e57cb46b35fc28 | hcmMichaelTu/python | /lesson08/sqrt_cal2.py | 793 | 3.859375 | 4 | import math
def Newton_sqrt(x):
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
def cal_sqrt(method, method_name):
print(f"Tính căn bằng phương pháp {method_name}:")
print(f"a) Căn của 0.0196 là {method(0.0196):.9f}")
print(f"b) Căn của 1.21 là {method(1.21):.9f}")
print(f"c) Căn của 2 là {method(2):.9f}")
print(f"d) Căn của 3 là {method(3):.9f}")
print(f"e) Căn của 4 là {method(4):.9f}")
print(f"f) Căn của {225/256} là {method(225/256):.9f}")
cal_sqrt(math.sqrt, "math’s sqrt")
cal_sqrt(lambda x: pow(x, 0.5), "built-in pow")
cal_sqrt(lambda x: math.pow(x, 0.5), "math’s pow")
cal_sqrt(lambda x: x ** 0.5, "exponentiation operator")
cal_sqrt(Newton_sqrt, "Newton’s sqrt")
|
dd7145fa02abd11c3490fa783f40f8b696c8261e | hcmMichaelTu/python | /lesson12/turtle_draw.py | 336 | 3.78125 | 4 | import turtle as t
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while ins := input("Nhập chuỗi lệnh cho con rùa (L, R, U, D): "):
for act in ins:
if act in actions:
t.setheading(actions[act])
else:
continue
t.forward(d)
print("Done!")
|
01b471090a34326b7c1c1a898ec5a25a9dbb0164 | hcmMichaelTu/python | /lesson04/string_format.py | 165 | 3.640625 | 4 | import math
r = float(input("Nhập bán kính: "))
c = 2 * math.pi * r
s = math.pi * r**2
print("Chu vi là: %.2f" % c)
print("Diện tích là: %.2f" % s)
|
87b04bf978a40493536c104be127f2ff83c55f74 | hcmMichaelTu/python | /lesson18/Sierpinski_carpet.py | 684 | 3.71875 | 4 | import pygame
def Sierpinski(x0, y0, w, level):
if level == stop_level:
return
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
pygame.draw.rect(screen, WHITE, (x0 + w//3, y0 + w//3, w//3, w//3))
else:
Sierpinski(x0 + i*w//3, y0 + j*w//3, w//3, level + 1)
width = 600
stop_level = 5
WHITE = (255, 255, 255)
PINK = (255, 192, 203)
pygame.init()
screen = pygame.display.set_mode((width, width))
pygame.display.set_caption("Sierpinski carpet")
screen.fill(PINK)
Sierpinski(0, 0, width, 0)
pygame.display.update()
input("Press Enter to quit. ")
pygame.quit()
|
71fb5ab35539839f8d8810bbd26003f5ba605ee2 | hcmMichaelTu/python | /lesson12/turtle_escape.py | 328 | 3.828125 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while (abs(t.xcor()) < t.window_width()/2 and
abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
t.setheading(actions[direction])
t.forward(d)
print("Congratulations!")
|
9a171f9585f56bb701ddbf6d88c6437c5123eca2 | hcmMichaelTu/python | /lesson14/tri_color_wheel.py | 1,797 | 3.6875 | 4 | import turtle as t
import time
import math
class TriColorWheel:
def __init__(self, omega, center=(0, 0), radius=100,
colors=("red", "green", "blue"),
up_key=None, down_key=None):
self.center = center
self.radius = radius
self.colors = colors
self.omega = omega # vận tốc góc độ/giây (+, 0, -)
self.angle = 0 # góc điểm chốt A
if up_key: t.onkeypress(self.speed_up, up_key)
if down_key: t.onkeypress(self.speed_down, down_key)
def speed_up(self): self.omega += 2
def speed_down(self): self.omega -= 2
def rotate(self, dt):
self.angle += self.omega * dt
A = self.angle; B = A + 120; C = B + 120
t.up(); t.goto(self.center); t.down()
for angle, color in zip((A, B, C), self.colors):
t.color(color)
t.begin_fill()
t.setheading(angle); t.forward(self.radius); t.left(90)
t.circle(self.radius, 120); t.goto(self.center)
t.end_fill()
def contain(self, point):
return math.dist(point, self.center) <= self.radius
if __name__ == "__main__":
def run():
global tm
t.clear()
tcw1.rotate(time.time() - tm)
tcw2.rotate(time.time() - tm)
t.update()
tm = time.time()
t.ontimer(run, 1000//24) # 24 fps
tcw1 = TriColorWheel(180, center=(100, 0),
up_key="Left", down_key="Right")
tcw2 = TriColorWheel(-180, center=(-100, 0),
colors=("cyan", "magenta", "yellow"),
up_key="a", down_key="d")
t.tracer(False); t.hideturtle(); t.listen()
tm = time.time(); run(); t.exitonclick()
|
db6bca60ff9d43d14f893a5d2afaf0dcb825091b | hcmMichaelTu/python | /lesson08/Newton_sqrt2.py | 166 | 3.75 | 4 | def Newton_sqrt(x):
if x < 0:
return
if x == 0:
return 0
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
|
a4fbc2deb5430e99feeeafc0af267677f4e957fc | hcmMichaelTu/python | /lesson05/square.py | 192 | 3.71875 | 4 | import turtle as t
t.shape("turtle")
d = int(input("Kích thước hình vuông? "))
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
|
2d17aba920279d5c521fcd5646ef53b844dde294 | hcmMichaelTu/python | /lesson06/exam.py | 191 | 3.65625 | 4 | điểm_thi = float(input("Bạn thi được bao nhiêu điểm? "))
if điểm_thi < 5:
print("Chúc mừng! Bạn đã rớt.")
else:
print("Chia buồn! Bạn đã đậu.")
|
113c8f8c95c6b98f181af8c197305be9729c853e | hcmMichaelTu/python | /lesson15/turtle_escape.py | 552 | 3.65625 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
try:
while (abs(t.xcor()) < t.window_width()/2
and abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
if direction == "L":
t.setheading(180)
elif direction == "R":
t.setheading(0)
elif direction == "U":
t.setheading(90)
else: # direction == "D"
t.setheading(270)
t.forward(d)
print("Congratulations!")
except t.Terminator:
pass
|
30ab7ff7d01d2d2ac154a8a1643169059633d8a8 | hcmMichaelTu/python | /lesson12/turtle_draw2.py | 349 | 3.625 | 4 | import turtle as t
def forward(deg):
def _forward():
t.setheading(deg)
t.forward(d)
return _forward
t.shape("turtle")
d = 20
actions = {"Left": 180, "Right": 0, "Up": 90, "Down": 270}
for act in actions:
t.onkey(forward(actions[act]), act)
t.onkey(t.bye, "Escape")
t.listen()
t.mainloop()
|
f7627d984bb9d995801c88ebe76baffac933ebca | hcmMichaelTu/python | /lesson17/triangle.py | 271 | 3.5 | 4 | import sys
char = input("Nhập kí hiệu vẽ: ")
n = int(input("Nhập chiều cao: "))
stdout = sys.stdout
with open("triangle.txt", "wt") as f:
sys.stdout = f
for i in range(1, n + 1):
print(char * i)
sys.stdout = stdout
print("Done!")
|
5d437d6e804b72f26526c22418c8f2cb719ed1d6 | hcmMichaelTu/python | /lesson18/guess_number2.py | 872 | 3.765625 | 4 | import random
def binary_guess():
if left <= right:
return (left + right) // 2
else:
return None
def hint(n, msg):
global left, right
if msg == "less":
left = n + 1
else:
right = n - 1
max = 1000
print("Trò chơi đoán số!")
print(f"Bạn đoán một con số nguyên trong phạm vi 1-{max}.")
left, right = 1, max
secret = random.randint(1, max)
count = 0
while True:
count += 1
input("Press Enter to guess.")
n = binary_guess()
print(f"Đoán lần {count} số {n}")
if n < secret:
print("Số bạn đoán nhỏ quá!")
hint(n, "less")
elif n > secret:
print("Số bạn đoán lớn quá!")
hint(n, "greater")
else:
print(f"Bạn đoán đúng số {secret} sau {count} lần.")
break
|
4de83b6bff15ac23aa0a775e068a487b51c771e4 | mikemeko/6.01_Tools | /src/core/math/line_segments.py | 2,443 | 3.671875 | 4 | """
Utility for line segments.
(1) Check whether two line segments intersect. Credit to: http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
(2) Translate segments.
"""
__author__ = 'mikemeko@mit.edu (Michael Mekonnen)'
from core.util.util import overlap
from math import atan2
from math import cos
from math import pi
from math import sin
def _cross(V, W):
"""
Returns the magnitude of the cross product of vectors |V| and |W|.
"""
vx, vy = V
wx, wy = W
return vx * wy - vy * wx
def intersect(segment1, segment2):
"""
If |segment1| or |segment2| has 0 length, returns False.
If |segment1| and |segment2| intersect and are colliniar, returns 'collinear'.
Otherwise, if |segment1| and |segment2| intersect at exactly one point,
returns that point.
Otherwise, returns False.
Segments should be given in the form ((x0, y0), (x1, y1)).
"""
(x00, y00), (x01, y01) = segment1
x00, y00, x01, y01 = float(x00), float(y00), float(x01), float(y01)
R = (x01 - x00, y01 - y00)
if R == (0, 0):
return False
(x10, y10), (x11, y11) = segment2
x10, y10, x11, y11 = float(x10), float(y10), float(x11), float(y11)
S = (x11 - x10, y11 - y10)
if S == (0, 0):
return False
QmP = (x10 - x00, y10 - y00)
RcS = float(_cross(R, S))
QmPcS = _cross(QmP, S)
QmPcR = _cross(QmP, R)
if RcS == 0:
# segments are parallel
if QmPcR == 0:
# segments are collinear
if R[0] == 0:
return 'collinear' if overlap((min(y00, y01), max(y00, y01)), (min(y10,
y11), max(y10, y11))) else False
else:
for (x, vx, xs) in [(x00, R[0], (x10, x11)), (x10, S[0], (x00, x01))]:
for ox in xs:
if 0 <= (ox - x) / vx <= 1:
return 'collinear'
return False
else:
return False
t = QmPcS / RcS
if t < 0 or t > 1:
return False
u = QmPcR / RcS
if u < 0 or u > 1:
return False
return (x00 + t * R[0], y00 + t * R[1])
def translate(segment, d):
"""
Returns a new segment that corresponds to the given |segment| translated
perpendicularly by |d| units.
Segment should be given and is returned in the form ((x1, y1), (x2, y2)).
"""
(x1, y1), (x2, y2) = segment
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
phi = atan2(y2 - y1, x2 - x1)
theta = pi / 2 - phi
dx = d * cos(theta)
dy = d * sin(theta)
return ((x1 - dx, y1 - dy), (x2 - dx, y2 - dy))
|
fe5ece5986e3f29e5f82a7512ea54746f2efa9bc | guimesmo/python-demo | /frase_do_dia_typed.py | 1,260 | 3.578125 | 4 | import random
import typing
class Frase:
def __init__(self, conjunto: str, idioma_padrao: str = "pt"):
self.conjunto = conjunto
self.idioma_padrao = idioma_padrao
self.output = dict()
self.parse()
def __str__(self):
return self.output.get(self.idioma_padrao, "Não definido")
def parse(self) -> None:
conjunto = self.conjunto.split("\n")
for frase in conjunto:
if frase: # previne linha em branco
idioma, frase = frase.split("|")
self.output[idioma] = frase
def gerador_de_frase_i18n(idioma: str = "pt") -> str:
with open("frases-i18n.txt", "r") as arquivo:
conjuntos = arquivo.read().split("\n\n")
frases = []
for conjunto in conjuntos:
frase_instancia = Frase(conjunto)
frases.append(frase_instancia)
frase = random.choice(frases)
return frase.output.get(idioma)
def gerador_de_frase() -> str:
with open("frases.txt", "r") as arquivo:
frases = list(arquivo.readlines())
return random.choice(frases)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
idioma = sys.argv[1]
else:
idioma = "pt"
print(gerador_de_frase_i18n(idioma))
|
62bb6e65edf4da3a18f8f681413b99518182631f | lokeki/python | /ZadSrdZaw/wykladI/Zad8EnumerateZip.py | 1,292 | 3.71875 | 4 | #wyk/enumerate/zip
'''
workDays = [19, 21, 22, 21, 20, 22]
print(workDays)
print(workDays[2])
enumerateDays = list(enumerate(workDays))
print(enumerateDays)
#enumerate - numerujemy kazdy element z listy i tworza sie tumple
for pos, value in enumerateDays:
print("Pos:", pos, "Value:", value)
month = ['I', 'II', 'III', 'IV', 'V', 'VI']
#zip - laczymy dwie tablice i tworza sie yumple(pary)
monthDay = list(zip(month,workDays))
print(monthDay)
for mon, day in monthDay:
print('Month:', mon, 'Day:', day)
for pos, (mon, day) in enumerate(zip(month, workDays)):
print('Pos:', pos, 'Month:', mon, 'Day:', day)
print('{} - {} - {}'.format(pos, mon, day)
'''
projects = ['Brexit', 'Nord Stream', 'US Mexico Border']
leaders = ['Theresa May', 'Wladimir Putin', 'Donald Trump and Bill Clinton', 'cosik']
for project, leader in zip(projects, leaders):
print('The leader of {} is {}'.format(project, leader))
print('')
dates = ['2016-06-23', '2016-08-29', '1994-01-01']
for project, data, leader in zip(projects, dates, leaders):
print('The leader of {} started {} is {}'.format(project, data, leader))
print('')
for position, (project, data, leader) in enumerate(zip(projects, dates, leaders)):
print('{} The leader of {} started {} is {}'.format(position + 1, project, data, leader))
|
14547f40099598502bbadfea46a328fb21330128 | lokeki/python | /ZadSrdZaw/wykladI/Zad11Generator.py | 1,645 | 3.671875 | 4 | #generator zazwyczaj się używa kiedy jest duza baza danych
'''
listA = list(range(6))
listaB = list(range(6))
print(listA, listaB)
product = []
for a in listA:
for b in listA:
product.append((a,b))
print(product)
#skrocona wersja z ifem (lista)
product = [(a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0]
print(product)
#wersja ze slownikiem, zmiana nawiasow kawadratowych na klamrowe, zmiana w zapisie danych
#zamiast (a,b), to a:b
product = { a:b for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0}
#klucz (a) zosal a dane (b) sie zmienialy
print(product)
print('-' * 30)
#generator nie zajmuje pamięci jak lista, nie jest to gotowa np lista, nie przechowuje danych,
# przechowuje raczej metode, sposob na wygenerowanie tych danych
gen = ((a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0)
print(gen)
print('-' * 30)
#zwraca i usuwa
print(next(gen))
print(next(gen))
print('-' * 30)
for x in gen:
print(x)
print('-' * 30)
gen = ((a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0)
#wyłapanie konca generatora poprzez try/except
while True:
try:
print(next(gen))
except StopIteration:
print("All values have been generated")
break
'''
ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ',
'LUZ', 'BZG', 'LCJ', 'SZY', 'IEG', 'RDO']
routes = ((port1, port2) for port1 in ports for port2 in ports if port1 < port2)
line = 0
while True:
try:
print(next(routes))
line += 1
except StopIteration:
print("All values have been generated. It have been", line)
break |
a0556b957eaf8394c0277e7830d7b347319bb402 | lokeki/python | /ZadSrdZaw/wykladI/Zad18FunkcjaArgumentemFunkcji.py | 969 | 3.53125 | 4 | # Funkcja jako argument funkcji
'''
def Bake (what):
print("Baking:", what)
def Add (what):
print("Adding:",what)
def Mix (what):
print("Mixing:", what)
cookBook = [(Add, "milk"), (Add, "eggs"), (Add, "flour"), (Add, "sugar"), (Mix, "ingerdients"), (Bake, "cookies")]
for activity, obj in cookBook:
activity(obj)
print("-" * 40)
def Cook(activity, obj):
activity(obj)
for activity, obj in cookBook:
Cook(activity, obj)
'''
def double(x):
return 2 * x
def root(x):
return x ** 2
def negative(x):
return -x
def div2(x):
return x / 2
def generateValues(nameFunctoin, parametrs):
listWithResult = []
for parametr in parametrs:
listWithResult.append(nameFunctoin(parametr))
return listWithResult
x_table = list(range(11))
print(type(x_table))
print(generateValues(double, x_table))
print(generateValues(root, x_table))
print(generateValues(negative, x_table))
print(generateValues(div2, x_table))
|
dc30adb10fb9d8482e0f4febadf412dd4524bc80 | lokeki/python | /ZadSrdZaw/wykladI/Zad24OptymalizacjaFunkcjiCache.py | 737 | 3.5625 | 4 | #Optymalizacja funkcji przez cache# musi byc deterministyczna, miec zawsze takie
# same argumenty i taki rezultat
'''
import time
import functools
@functools.lru_cache()
def Factorial (n):
time.sleep(0.1)
if n == 1:
return 1
else:
return n * Factorial(n - 1)
start = time.time()
for i in range(1,11):
print('{}! = {}'.format(i, Factorial(i)))
stop = time.time()
print("Time:", stop - start)
print(Factorial.cache_info())
'''
import time
import functools
@functools.lru_cache()
def fib(n):
if n <= 2:
result = n
else:
result = fib(n - 1) + fib(n - 2)
return result
start = time.time()
for i in range(1, 33):
print(fib(i))
stop = time.time()
print(stop - start) |
30532ca431def7eaaba8588814e5b22873ff8017 | lokeki/python | /ZadSrdZaw/wykladI/Zad19FunkcjaZwracaFunkcje.py | 1,208 | 3.53125 | 4 | # Zwaracanie funkcji
#
# def Calculate ( kind = "+", *args):
# result = 0
#
# if kind == "+":
#
# for a in args:
# result += a
#
# elif kind == '-':
#
# for a in args:
# result -= a
#
# return result
#
# def CreateFunction(kind = "+"):
# source = '''
# def f(*args):
# result = 0
# for a in args:
# result {}= a
# return result
# '''.format(kind)
# exec(source, globals())
#
# return f
#
# fAdd = CreateFunction("+")
# print(fAdd(1,2,3,4))
# fSubs = CreateFunction("-")
# print(fSubs(1,2,3,4))
import datetime
def TimeFunk(timeF = 'm' ):
if timeF == 'm':
sec = 60
elif timeF == 'h':
sec = 3600
elif timeF == 'd':
sec = 86400
source = '''
def f(start, end):
temp = end - start
tempSec = temp.total_seconds()
return divmod(tempSec, {})[0]
'''.format(sec)
exec(source, globals())
return f
TimeFunk()
f_minutes = TimeFunk('m')
f_hours = TimeFunk('h')
f_days = TimeFunk('d')
start = datetime.datetime(2019, 12, 10, 0, 0, 0)
end = datetime.datetime(2020, 12, 10, 0, 0, 0)
print(f_minutes(start, end))
print(f_hours(start, end))
print(f_days(start, end)) |
8a23940de2d48ab3b767e90e2e3a3e55836daffd | andyreagan/2018-advent-of-code | /2019-mm-month-of-python/13-manselmi/bruteforce.py | 489 | 3.953125 | 4 | import sys
def collatz_f(i: int) -> int:
if i % 2 == 0:
return int(i / 2)
else:
return int(3*i + 1)
def get_path_length(i: int) -> int:
# print(i)
l = 1
while i != 1:
i = collatz_f(i)
l += 1
# print(i, l)
return l
def main(n):
all_path_lengths = [get_path_length(i+1) for i in range(n)]
m = max(all_path_lengths)
print(m, all_path_lengths.index(m)+1)
if __name__ == '__main__':
main(int(sys.argv[1]))
|
8122e6d19531fc76d06288aaf9dfb1590aca10d7 | webclinic017/StockPredictor-1 | /CAP4621_Stock_Prediction_Project.py | 15,684 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Dhruv's Section
# In[ ]:
get_ipython().system('pip install matplotlib')
get_ipython().system('pip install seaborn')
get_ipython().system('pip install yfinance')
import platform
import yfinance as yf
import datetime
import matplotlib.pyplot as plt
import seaborn
# prints the ticker's close form the most recent, and its change from the day before
def getTickerData(tickerSymbol):
tickerData = yf.Ticker(tickerSymbol)
tickerInfo = tickerData.info
companyName = tickerInfo['shortName']
print('Company Name: ' + companyName)
today = datetime.datetime.today().isoformat()
# tickerOF = tickerData.history(period='1d', start='2020-10-1', end=today[:10])
# tickerOF = tickerData.history(period='1d', start='2018-5-1', end='2018-6-1')
tickerOF = tickerData.history(period='1d', start='2020-10-1', end='2020-10-20')
priceLast = tickerOF['Close'].iloc[-1]
priceYest = tickerOF['Close'].iloc[-2]
change = priceLast - priceYest
print(companyName + ' last price is: ' + str(priceLast))
print('Price change = ' + str(change))
# Gives a chart of the last 10 days
def getChart(tickerSymbol):
tickerData = yf.Ticker(tickerSymbol)
hist = tickerData.history(period="30d", start='2020-9-21', end='2020-10-20')
# hist = tickerData.history(period='1d', start='2020-10-1', end=today[:10])
# Plot everything by leveraging the very powerful matplotlib package
hist['Close'].plot(figsize=(16, 9))
# Calling the functions
getTickerData('MSFT')
getChart('MSFT')
# # Andres's Section
# In[ ]:
pip install quandl
# In[ ]:
import quandl
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
# In[ ]:
# Get stock data
df = quandl.get("WIKI/FB")
# Print Data
print(df.tail())
# In[ ]:
# Get Close Price
df = df[['Adj. Close']]
# Print it
print(df.head())
# In[ ]:
# Var for predicting 'n' days out into the future
forecast_out = 30
# Create another column (the target or dependent variable) shifted 'n' units up
df['Prediction'] = df[['Adj. Close']].shift(-2)
# Print new dataset
print(df.tail())
# In[ ]:
# Create independent Data set (X)
# Convert dataframe to numpy array
X = np.array(df.drop(['Prediction'], 1))
# Remove the last 'n' rows
X = X[:-2]
print(X)
# In[ ]:
# Create dependent data set (y)
# Convert the dataframe to numpy array (All of the values including NaN's)
y = np.array(df['Prediction'])
# Get all of the y values except the last n rows
y = y[:-2]
print(y)
# In[ ]:
# Split the data into 80% training and 20& testing
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# In[ ]:
# Create and train the Support Vector Machine (Regressor)
svr_rbf = SVR(kernel="rbf", C=1e3, gamma=0.1)
svr_rbf.fit(x_train, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
svm_confidence = svr_rbf.score(x_test, y_test)
print("svm confidence: ", svm_confidence)
# In[ ]:
# Create and train the Linear Regression Model
lr = LinearRegression()
# Train the Model
lr.fit(x_train, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
lr_confidence = lr.score(x_test, y_test)
print("lr confidence: ", lr_confidence)
# In[ ]:
# Set x_forecast equal to the last 2 rows of the original data set from Adj. Close column
x_forecast = np.array(df.drop(['Prediction'],1))[-2:]
print(x_forecast)
# In[ ]:
# Print linear regression model predictions for the next n days
lr_prediction = lr.predict(x_forecast)
print(lr_prediction)
# Print SVR model predictions
svm_prediction = svr_rbf.predict(x_forecast)
print(svm_prediction)
# Backtesting with Zipline
# In[ ]:
get_ipython().system('pip install backtrader')
# In[ ]:
from zipline.api import order_target, record, symbol
import matplotlib.pyplot as plt
def initialize(context):
context.i = 0
context.asset = symbol('AAPL')
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# data.history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()
# Trading logic
if short_mavg > long_mavg:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(context.asset, 100)
elif short_mavg < long_mavg:
order_target(context.asset, 0)
# Save values for later inspection
record(AAPL=data.current(context.asset, 'price'),
short_mavg=short_mavg,
long_mavg=long_mavg)
def analyze(context, perf):
fig = plt.figure()
ax1 = fig.add_subplot(211)
perf.portfolio_value.plot(ax=ax1)
ax1.set_ylabel('portfolio value in $')
ax2 = fig.add_subplot(212)
perf['AAPL'].plot(ax=ax2)
perf[['short_mavg', 'long_mavg']].plot(ax=ax2)
perf_trans = perf.ix[[t != [] for t in perf.transactions]]
buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
sells = perf_trans.ix[
[t[0]['amount'] < 0 for t in perf_trans.transactions]]
ax2.plot(buys.index, perf.short_mavg.ix[buys.index],
'^', markersize=10, color='m')
ax2.plot(sells.index, perf.short_mavg.ix[sells.index],
'v', markersize=10, color='k')
ax2.set_ylabel('price in $')
plt.legend(loc=0)
plt.show()
# # Abhinay's Section
# In[ ]:
get_ipython().system('pip install stocknews')
# In[ ]:
from stocknews import StockNews
# In[ ]:
# In[ ]:
scraper.find('div', {'class', 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
# In[ ]:
# # John and Dhruv's Section
# In[ ]:
from google.colab import drive
drive.mount('/content/drive')
# In[ ]:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import os
# plt.style.use('fivethirtyeight')
# In[ ]:
# df = pd.read_csv('/content/drive/My Drive/AI Stock Predictor Project Group/data/aapl.csv', sep = ',', header = 0)
df = pd.read_csv('aapl.csv',sep = ',', header = 0)
#print(df.tail())
# In[ ]:
df.shape
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
# In[ ]:
print(df.tail())
# In[ ]:
# Create independent Data set (X)
# Convert dataframe to numpy array
# X = np.array(df)
# X = df['Close']
# converting list to array
X = np.array(df['Close'])
X = np.reshape(X, (-1, 1))
# print(Temp)
# Remove the last 'n' rows
# X = X[:-forecast_out]
print(X)
# In[ ]:
# Create dependent data set (y)
# Convert the dataframe to numpy array (All of the values including NaN's)
y = np.array(df['Prediction'])
# Get all of the y values except the last n rows
# y = y[:-forecast_out]
print(y)
# In[ ]:
# Split the data into 80% training and 20& testing
# x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.2)
# x_train1 = np.array(x_train.drop(['Sentiment','Date', 'Prediction'], axis=1))
# x_test1 = np.array(x_test.drop(['Sentiment','Date', 'Prediction'], axis=1))
x_train1 = np.array(df.drop(['Date', 'Prediction'],1))[:-40]
x_test1 = np.array(df.drop(['Date', 'Prediction'],1))[-40:]
# Split the data into training/testing sets
x_train = X[:-40]
x_test = X[-40:]
# Split the targets into training/testing sets
y_train = y[:-40]
y_test = y[-40:]
print(x_train)
print(x_test)
print(y_train)
print(y_test)
# In[ ]:
# # Create and train the Support Vector Machine (Regressor)
# svr_rbf = SVR(kernel="rbf", C=1e3, gamma=0.1)
# svr_rbf.fit(x_train, y_train)
# In[ ]:
# # Test Model: Score returns the coefficient of determination R^2 of the prediction
# # # The best possible score is 1.0
# svm_confidence = svr_rbf.score(x_test, y_test)
# print("svm confidence: ", svm_confidence)
# In[ ]:
# Create and train the Linear Regression Model
lr = LinearRegression()
# Train the Model
lr.fit(x_train1, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
lr_confidence = lr.score(x_test1, y_test)
print("lr confidence: ", lr_confidence)
# In[ ]:
# # Print linear regression model predictions for the next n days
# lr_prediction = lr.predict(x_test)
# print(lr_prediction)
# CODE #####################################################################################
# Make predictions using the testing set
# x_forecast is the last row of the data, which we ant to predict
x_forecast = np.array(df.drop(['Date', 'Prediction'],1))[-1:]
print(x_forecast)
lr_prediction = lr.predict(x_forecast)
print('Prediction for the 1 day out:', lr_prediction)
# Print SVR model predictions
# svm_prediction = svr_rbf.predict(x_forecast)
# print(svm_prediction)
# In[ ]:
lr_prediction = lr.predict(x_test1)
print(lr_prediction)
# lr_prediction = scalar.inverse_transform(lr_prediction)
# train = df[:x_train1]
# valid = df[x_train1:]
train = x_train1
valid = df.drop(['Date', 'Prediction'],1)[-40:]
valid['Predictions'] = lr_prediction
# Visulaize the date
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(df['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'])
plt.show()
# In[ ]:
lr_prediction = lr.predict(x_test1)
print(lr_prediction)
# The coefficients
print('Coefficients: \n', lr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(y_test, lr_prediction))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(y_test, lr_prediction))
# Prediction is black line, actual is blue dot
plt.plot(x_test['Date'], lr_prediction, color='black')
plt.plot_date(x_test['Date'], x_test['Close'], color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
# In[ ]:
# Set x_forecast equal to the last n row of the original data set from Close column
x_forecast = np.array(df.drop(['Sentiment', 'Date', 'Prediction'],1))[-1:]
print(x_forecast)
# # John's Section
# In[ ]:
import urllib.request, json
with urllib.request.urlopen('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AMZN&apikey=RKHOCKAPF9H87FQQ') as response:
data = json.loads(response.read())
meta=data["Meta Data"]
data=data["Time Series (Daily)"]
print(meta)
print(data)
# In[ ]:
# # Dhruv's Section
# In[ ]:
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# In[ ]:
# Get the stock quote
#df = pd.read_csv('aapl.csv',sep = ',', header = 0)
# print(type(df))
# print(df.tail())
n = 60
#df = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2019-12-17')
# df
# In[ ]:
# Visualize the data
# df.shape
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
# In[ ]:
#Create a new Dataframe
df = web.DataReader('AAPL', data_source = 'yahoo', start = '2015-01-01', end = '2020-10-01')
data = df[['Close']]
print(data.values)
#print(data.values)
#print(len(data))
# print(type(data))
#Convert to numpy array
dataset = np.array(data.values)
dataset = np.reshape(dataset, (-1, 1))
#print(dataset)
#print(dataset)
#Get the number of rows to train the model
training_data_len = math.ceil(len(data) * .8)
# In[ ]:
#Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
print(scaled_data)
# In[ ]:
#Create the scaled training data set
train_data = scaled_data[0:training_data_len, :]
#Split the data into x_train and y_train
x_train = []
y_train = []
for i in range(n, len(train_data)):
x_train.append(train_data[i-n:i, 0])
y_train.append(train_data[i, 0])
# In[ ]:
#Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshape the data
# (#samples, timesteps, and features)
#x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
#x_train.shape
# In[ ]:
#Build the LSTM model
model = Sequential()
# 50 neurons, (timesteps, features)
model.add(LSTM(50, return_sequences = True, input_shape = (x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences = False))
#model.add(LSTM(50))
model.add(Dense(25))
model.add(Dense(1))
# In[ ]:
model.compile(optimizer = 'adam', loss = 'mean_squared_error')
# In[ ]:
#Train the model
model.fit(x_train, y_train, batch_size = 1, epochs = 5)
# In[ ]:
#Create the testing dataset
#Create a new array containing scaled values from index size-n to size
# [last n values, all the columns]
test_data = scaled_data[training_data_len - n:, :]
#Create the datasets x_test, y_test
x_test = []
# 61st values
y_test = dataset[training_data_len:, :]
for i in range(n, len(test_data)):
# Past n values
x_test.append(test_data[i-n:i, 0])
# In[ ]:
#convert to numpy array
x_test = np.array(x_test)
print(x_test.shape)
# In[ ]:
#Reshape the data for the LSTM model to 3-D
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# In[ ]:
#Get the models predicted price and values
print(x_test[0])
#predictions = model.predict(x_test)
#print(predictions)
# We want predictions to contain the same values as y_test dataset
#predictions = scaler.inverse_transform(predictions)
#print(predictions)
# print(type(predictions))
# In[ ]:
#Get the root mean squred error (RMSE) - lower the better
rmse = np.sqrt(np.mean(predictions - y_test)**2)
print(rmse)
# In[ ]:
#Plot the data
#print(data[:56])
train = data[:training_data_len]
valid = data[training_data_len:]
#train = data.loc[:'2020-09-01']
#valid = data.loc['2020-09-01':]
#print(data.loc[:'2020-09-01'])
valid['Predictions'] = predictions
#print(type(train))
#print(type(valid))
#predictions_series = []
#indices = list(range(162, 202))
#for prediction in predictions:
# predictions_series.append(prediction)
#predictions = pd.Series(predictions_series, index = indices)
# Visulaize the date
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid['Close'])
plt.plot(valid['Predictions'])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
plt.show()
# In[ ]:
print(valid[[180]], predictions[[180]])
# In[ ]:
#Get the quote
# apple_quote = web.DataReader('AAPL', data_source="yahoo", start)
stock_quote = pd.read_csv('/content/aapl.csv',sep = ',', header = 0)
new_df = stock_quote.filter(['Close'])
last_n_days = new_df[-n:].values
last_n_days_scaled = scaler.transform(last_n_days)
X_test = []
X_test.append(last_n_days_scaled)
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
pred_price = model.predict(X_test)
pred_price = scaler.inverse_transform(pred_price)
print(pred_price)
|
02960d761aec2401238739d0c6cee1a6a5b54571 | Wowol/Blackjack-Reinforcement-Learning | /game/card.py | 333 | 3.875 | 4 | from random import randint
class Card:
"""Generate one card and store its number in value field
"""
value = 0
def __init__(self):
number = randint(1, 13)
if number == 1:
self.value = 11
elif number > 10:
self.value = 10
else:
self.value = number
|
d81541f0bfae3d2a5323f517300afa9501bdf685 | ntshcalleia/Listas_AlgGraf_2017_2 | /lista2/questao5.py | 1,868 | 3.734375 | 4 | import math
def troco(T):
moedas = {
1: 0,
5: 0,
10: 0,
25: 0,
50: 0,
100: 0
}
while(T > 0): # Criterio guloso: escolher maior moeda possivel. Colocar quantas der dela
if T >= 100:
moedas[100] = int(math.floor(T/100))
T = T % 100
elif T >= 50:
moedas[50] = int(math.floor(T/50))
T = T % 50
elif T >= 25:
moedas[25] = int(math.floor(T/25))
T = T % 25
elif T >= 10:
moedas[10] = int(math.floor(T/10))
T = T % 10
elif T >= 5:
moedas[5] = int(math.floor(T/5))
T = T % 5
elif T >= 1:
moedas[1] = T
T = 0
return moedas
def main():
T = int(input("T = "))
moedas = troco(T)
print("{} pode ser representado por:".format(T))
if moedas[1] != 0:
if moedas[1] == 1:
print("1 moeda de 1")
else:
print("{} moedas de 1".format(moedas[1]))
if moedas[5] != 0:
if moedas[5] == 1:
print("1 moeda de 5")
else:
print("{} moedas de 5".format(moedas[5]))
if moedas[10] != 0:
if moedas[10] == 1:
print("1 moeda de 10")
else:
print("{} moedas de 10".format(moedas[10]))
if moedas[25] != 0:
if moedas[25] == 1:
print("1 moeda de 25")
else:
print("{} moedas de 25".format(moedas[25]))
if moedas[50] != 0:
if moedas[50] == 1:
print("1 moeda de 50")
else:
print("{} moedas de 50".format(moedas[50]))
if moedas[100] != 0:
if moedas[100] == 1:
print("1 moeda de 100")
else:
print("{} moedas de 100".format(moedas[100]))
if __name__ == '__main__':
main() |
f8576b094f7f0676433b035d8630f2a64477eb85 | Huitzoo/Rosalind_Bioinformatics | /rabbits.py | 299 | 3.671875 | 4 | def main():
months = int(input('Enter the months'))
litters = int(input('Enter the number of litters'))
fibo = [1,1]
if months <= 2:
print('1')
else:
for i in range(2,months):
fibo.append(litters*fibo[i-2]+fibo[i-1])
print(fibo)
main()
|
e9f2417dd3507d88cfb24b12c8c927c259e7fc91 | halesahinn/Searching-Reverse-Complement-of-DNA-Motif | /Project1_150114063_150116841_150114077.py | 2,536 | 3.5625 | 4 | #Büşra YAŞAR-150114063
#Emine Feyza MEMİŞ-150114077
#Hale ŞAHİN-150116841
import operator
import re
import os
import sys
from os import path
#print("Please enter the input file path :")
#path = input()
def reverse(s):
str = ""
for i in s:
str = i + str
return str
def readFile(file_path):
path2 = path.relpath(file_path)
with open(path2) as f:
text = f.read()
printText(text)
def printText(text):
# Extract your code into a function and print header for current kmer
#print("%s\n################################" %name)
kmers = {}
for i in range(len(text) - k + 1):
kmer = text[i:i+k]
if kmer in kmers:
kmers[kmer] += 1
else:
kmers[kmer] = 1
print ('Inputs: k=%d,x=%d' % (k,x))
print ('Outputs:')
print ('%d-mer:\t' % (k))
i = 0
occuredKmers = {}
passAmount = 0
for kmer, count in kmers.items():
if count >= x:
print (kmer)
occuredKmers[i] = kmer
i = i + 1
passAmount = passAmount + 1
if passAmount == 0:
print('There is no such %d-mer which appears more than %d times for the input DNA string.' % (k,x))
print ('Reverse Complement: ')
j = 0
reverseComplement = ""
noReverse = 0
occurence = 0
while j < len(occuredKmers):
kmer = occuredKmers[j]
reverseKmer = reverse(kmer)
for base in reverseKmer:
if base == 'A':
base = 'T'
elif base == 'T':
base = 'A'
elif base == 'G':
base = 'C'
elif base == 'C':
base = 'G'
reverseComplement = reverseComplement + base
for i in range(len(text) - k + 1):
kmer = text[i:i+k]
if reverseComplement == kmer:
occurence = occurence +1
if occurence > 0:
print (reverseComplement + ' appearing' + ' %d times' % (occurence))
noReverse = noReverse + 1
j = j + 1
occurence = 0
reverseComplement=""
if noReverse == 0:
print ('There is no reverse complement %d-mers in DNA string.' % (k))
if __name__ == "__main__":
print("Please enter the k value: ")
k =int(input())
print("Please enter the x value: ")
x =int(input())
print("Please enter the input file path:")
file_path = input()
readFile(file_path)
|
235a6863fd259e561c92567af98b6ccf29a7fee0 | optimizely/pycon2019 | /lambda_calculus_seminar/pylambda1.py | 202 | 4.09375 | 4 | '''
'''
f = lambda x: 3*x + 1
f(2) # eli5 - you replace the x with the 2
f(4)
'''
def f(x):
return x
def f(x):
return x(x)
'''
def f(x):
def g(y):
return x(y)
return g
|
314411a03d4703ed284d6f12d7f1c356eab8a094 | pandast3ph4n/password-generator | /passgen.py | 1,071 | 3.5625 | 4 | import random
import string
import tkinter as tk
pool = string.ascii_letters + string.digits + string.punctuation
def generate_password(length=12, random_length=False):
if random_length:
length = random.randrange(10, 16)
if length < 4:
print('hey din dust.... ikke noe tull')
return False
elif length > 1000:
print('yo, for langt... thats what she said!')
return False
while True:
password = random.choices(pool, k=length)
password = ''.join(password)
if not any(character in string.digits for character in password):
continue
if not any(character in string.punctuation for character in password):
continue
if not any(character in string.ascii_lowercase for character in password):
continue
if not any(character in string.ascii_uppercase for character in password):
continue
break
return password
if __name__ == "__main__":
password = generate_password()
print(generate_password())
|
8a5bb6ad81f3f444da59c72d9c3f3f4dbaf9cfa3 | ccmien/Fundamentals-of-Computing-Projects | /Word Wrangler.py | 4,042 | 4.0625 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
if len(list1) == 0:
return list1
if len(list1) == 1:
return [list1[0]]
elif list1[len(list1)/2 -1] == list1[len(list1)/2]:
return remove_duplicates(list1[:len(list1)/2]) + remove_duplicates(list1[len(list1)/2 + 1:])
else:
return remove_duplicates(list1[:len(list1)/2]) + remove_duplicates(list1[len(list1)/2:])
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
if len(list1) == 0 or len(list2) == 0:
return []
index1 = 0
index2 = 0
intersect_list = []
while index1 < len(list1) and index2 < len(list2):
if list1[index1] == list2[index2]:
intersect_list.append(list1[index1])
index1 += 1;
index2 += 1;
elif list1[index1]<list2[index2]:
index1 += 1
else:
index2 += 1
return intersect_list
# Functions to perform merge sort
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in either list1 and list2.
This function can be iterative.
"""
merged_list = list2
index_add = 0
for (index1, item1) in enumerate(list1):
for index2 in range(index_add, len(list2)):
if index2 == len(list2) - 1 and item1 >= list2[index2]:
merged_list = merged_list + [item1]
if item1 < list2[index2]:
merged_list = merged_list[:(index2+index1)] + [item1] + merged_list[(index2+index1):]
index_add = index2
break
return merged_list
def merge_sort(list1):
"""
Sort the elements of list1.
Return a new sorted list with the same elements as list1.
This function should be recursive.
"""
if len(list1) < 2:
return list1
if len(list1) == 2:
return merge([list1[0]], [list1[1]])
else:
return merge(merge_sort(list1[:len(list1)/2]), merge_sort(list1[len(list1)/2:]))
# Function to generate all strings for the word wrangler game
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if len(word) == 0:
return [""]
if len(word) == 1:
return ["", word]
else:
first = word[0]
rest = word[1:]
rest_strings = gen_all_strings(rest)
new_strings = []
for string in rest_strings:
for index_s in range(len(string) + 1):
new_strings.append(str(string[:index_s]) + first + str(string[index_s:]))
return new_strings + rest_strings
# Function to load words from a file
def load_words(filename):
"""
Load word list from the file named filename.
Returns a list of strings.
"""
res = []
url = codeskulptor.file2url(filename)
netfile = urllib2.urlopen(url)
for line in netfile.readlines():
res.append(line[:-1])
return res
def run():
"""
Run game.
"""
words = load_words(WORDFILE)
wrangler = provided.WordWrangler(words, remove_duplicates,
intersect, merge_sort,
gen_all_strings)
provided.run_game(wrangler)
# Uncomment when you are ready to try the game
run() |
ae97a6da42d85c675d029aacdd0991f18ec08c6c | SofiaDaniela/Mision_02 | /extraGalletas.py | 446 | 3.890625 | 4 | # Autor: Sofía Daniela Méndez Sandoval, A01242259
# Descripción: Cantidad de Ingredientes para # de Galletas
cantidad = int(input("¿Cuántas galletas realizará?: "))
azucar = (cantidad*1.5)/48
mantequilla = cantidad/48
harina = (cantidad*2.75)/48
print("Para realizar el determinado número de galletas, necesitará: ")
print("Azúcar: ", "%.2f" % azucar, "tazas")
print("Mantequilla: ", "%.2f" % mantequilla, "tazas")
print("Harina: ", "%.2f" % harina, "tazas")
|
c4061364eb081676fcaa1c2720decd4187d1eef9 | vamsikvs1994/Web_crawler | /word_counter.py | 3,854 | 4.09375 | 4 | '''
Author: Venkata Sai Vamsi Komaravolu
Date: 30th December 2017
File Name: word_counter.py
Description:
This python program performs the word count in a web-page given the URL. It makes use of certain
methods and packages available in python.
The working of this program classified as mentioned below:
1. Open the given URL
2. Read the web-page and using the utf-8 format decoding
3. Remove the tags in the web page
4. Remove all the non-alphanumeric characters in the word string
5. Count the words and form a dictionary
6. Finally sorting and displaying the top 5 most used words in the web-page
'''
import re #regular expression package
from urllib.request import urlopen #urlopen is used to open the web-page using the given URL
def main(url):
opened_url = urlopen(url) #open the given web-page from the given url
decoded_url = opened_url.read().decode('utf-8') #read the web-page and decode according to utf-8 format
text = remove_tags(decoded_url).lower() #remove the tags in the webpage and lower() makes all case-based characters lowercased
words = remove_non_alp_num(text) #remove all non-alphanumeric characters
dict = word_counter(words) #creates a dictionary with the words and their count
sorted_words = sort_counter(dict) #sorts the dictionary and returns the words and their count in descending order
count=0
for s in sorted_words: #displays the 5 top most used words in the given web-page
if(count<5):
print(str(s))
count+=1
return
def remove_tags(page_info): #method to remove the tags in the the given web-page
start = page_info.find("</a>")
end = page_info.rfind("</li>") #rfind() returns the last index where the substring is found
page_info = page_info[start:end]
ins = 0
word_form = ''
for char in page_info: # creating a word form from the characters
if char == '<': # word string is between the < and > characters
ins = 1
elif (ins == 1 and char == '>'):
ins = 0
elif ins == 1:
continue
else:
word_form += char
return word_form
def remove_non_alp_num(text): #method for removing all non-alphanumeric characters using UNICODE definition
return re.compile(r'\W+', re.UNICODE).split(text) #re.compile() is used to compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods
def word_counter(words): #method for creating a Python dictionary with words and their respective count
wordfreq = [words.count(p) for p in words]
return dict(zip(words,wordfreq))
def sort_counter(dict): #method for sorting and displaying the words with their count in descending order
out = [(dict[key], key) for key in dict]
out.sort()
out.reverse()
return out
|
2aefeb397fb1ea15bc2519fa34be929718bf4a9a | agoldh20/exercism | /python/pangram/pangram.py | 249 | 3.609375 | 4 | import re
def is_pangram(sentence):
sentence = sentence.lower()
sentence = re.sub(r'([^a-z])', "", sentence)
if len(list(set(sentence))) < 26:
return False
elif len(list(set(sentence))) == 26:
return True
pass
|
3eb68789808cd0ae37f3509e941521452b9141f7 | IlkoAng/Python-OOP-Softuni | /exercise1-first-steps-oop/04-cup.py | 407 | 3.59375 | 4 | class Cup:
def __init__(self, size, quantity):
self.size = size
self.quantity = quantity
def fill(self, mil):
if self.size >= self.quantity + mil:
self.quantity += mil
def status(self):
result = self.size - self.quantity
return result
cup = Cup(100, 50)
print(cup.status())
cup.fill(40)
cup.fill(20)
print(cup.status())
|
cbc85235c505b37df1c409b2a9b9a070ae497e42 | liu-creator/python__basic | /Py_mysql/一次插入多条数据.py | 1,135 | 3.59375 | 4 | '''插入100条数据到数据库(一次插入多条)'''
import pymysql
import string,random
#打开数据库连接
conn=pymysql.connect('localhost','root','123456')
conn.select_db('testdb')
#获取游标
cur=conn.cursor()
#创建user表
cur.execute('drop table if exists user')
sql="""CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
cur.execute(sql)
#修改前查询所有数据
cur.execute("select * from user;")
print('修改前的数据为:')
for res in cur.fetchall():
print (res)
print ('*'*40)
#循环插入数据
words=list(string.ascii_letters)
sql="insert into user values(%s,%s,%s)"
random.shuffle(words)#打乱顺序
cur.executemany(sql,[(i+1,"".join(words[:5]),random.randint(0,80)) for i in range(100) ])
#插入100条后查询所有数据
cur.execute("select * from user;")
print('修改后的数据为:')
for res in cur.fetchall():
print (res)
print ('*'*40)
cur.close()
conn.commit()
conn.close()
print('sql执行成功')
|
54873a969653a53afa1be805c1c8b96dcd77daa3 | MattBJ/Radar_Object_Detection_System | /Data_Simulations/Sampled_Frequency_Data_out.py | 9,078 | 3.5 | 4 | # Matthew Bailey
# Simulation python code:
# Purpose: Generate 3 sampled frequency data sets that represent a moving ordinance and 2 stationary objects in a 3D Area
# Secondary purpose: Ditch the stationary objects (explain how it would've worked) - Use only x,x',y, and y' and assume stationary Z, as everything would've been stationary
# Vision: We have 1 transmitting radar, and 3 receivers. The receivers are set up in an equilateral triangle configuration, with the transmitter in the center.
# There, hopefully, 2 objects that are stationary (represented as single points), that will contribute constant frequency information
# There will be an ordinance traveling from the near edge of the field to a close point next to the radar dish
# Important information: Bandwidth is 100 MHz, the chirp is 100 microseconds (10 KHz)
# Chirp waveform: Triangulat (so from 0 modulation to 100 MHz is 50uS)
# Delta Frequency = 600 GHz
# Time per freq. change = 1.666 pico seconds
# Arbitrary distance constraint: 6 meters --> Roughly 25KHz difference (there and back = 12 meters)
# Constraints: C (Speed of light) = 3e8
# Arbitrary distance max = 6 meters (from any receiver)
# The distance to any object to any receiver is calculated by the following:
# D_TX = sqrt((TX_x - Obj_x)^2 + (TX_y - Obj_y)^2 + (TX_z - Obj_z)^2)
# D_RXn = sqrt((RX_x - Obj_x)^2 + (RX_y - Obj_y)^2 + (RX_z - Obj_z)^2)
# D_Tot = D_TX + D_RXn
# Converting distance to frequency information:
# (D_tot / c) * 600 GHz = Frequency_Data
# For the stationary objects, this can simply be calculated over the entirety of the large sample set
# For the ordinance, the distance will be dynamically changing
# For each sample in time, a new distance must be calculated and thus the corresponding frequency changes (should steadily get lower)
# Each data set will be represented by a vector of scalars which are set equal to the 3 CURRENT frequency components multiplied by time
# FIRST CHALLENGE: Create a varying frequency dataset (1 HZ to 1KHz, changes once per ____ samples)
# make the sampling extremely high frequency (1 nanosecond)
# figure out how to change frequencies dynamically over time WITHOUT jumping around
# after 1000 samples, change frequency
# np.cos() requires an array of data (time set), then outputs an array of equal size. will always take that last element and append it
import numpy as np
import matplotlib.pyplot as plt
import copy
def freq_data(freq,sampling_freq,sample_num): # Takes the frequency, sampling frequency, and the time instance of the data required
# t = np.arange(0,(sample_num+1)+(1/sampling_freq),(1/sampling_freq))
# print(t)
out = np.cos(2*(np.pi)*(freq)*(sample_num / sampling_freq))
# print(out)
# return out[(sample_num)*(sampling_freq)] # the last element
return out
# THE CODE BELOW WAS ME TESTING DYNAMICALLY CHANGING FREQUENCY OF A SIGNAL AS THE SIGNAL IS BEING SAMPLED
# frequency_jumps = np.arange(50,151)
# print(frequency_jumps.shape)
# print(frequency_jumps)
# print(frequency_jumps[999])
# j = 0
# data_buffer = []
# sampling_freq = 1000 # 1ksps
# N = 2224
# freq_jump_prev = 0
# freq_jump_next = (2/50) * 1000
# print(int(52.6))
# for i in range(N):
# print(i)
# if(freq_jump_next == i):
# j += 1
# freq_jump_prev = freq_jump_next
# freq_jump_next = freq_jump_prev + (2/frequency_jumps[j]) * 1000
# freq_jump_next = int((freq_jump_next + 0.5))
# print(int(freq_jump_next))
# print('Frequency: ',frequency_jumps[j])
# data_buffer.append(freq_data(frequency_jumps[j],1000,i))
# data_buffer = np.array(data_buffer)
# Now display the sinusoids over the time
# fig = plt.figure()
# ax = fig.add_subplot(1, 1, 1)
# plt.plot(np.arange(0,N),data_buffer,'r')
# plt.show()
# First attempt, all 1's...
# Generate the 2 object frequencies for the 3 receivers --> Will probably get rid of it
# For now let's just do the ordinance frequencies
# nf_pos = 0.1
TX_pos = np.array([0,1,0])
RX1_pos = np.array([0,1,0])
RX2_pos = np.array([0,0,((4/3)**(1/2))/2])
RX3_pos = np.array([0,0,-((4/3)**(1/2))/2])
x_0 = 4
x_f = 1
sampling_freq = 100000
samples = int(sampling_freq*.9)
print(samples)
# dt = 0.0000001 # let's make it real as possible --> 10 Msps
dt = 1/sampling_freq
dx_0 = (x_f - x_0)/(dt*samples)
y_0 = 5
y_f = 3
# dt = 1/sampling_freq
dy_0 = 2.18777777777 # per second
def generate_y_data(y_0, v_0, nf_pos, nf_vel,dt,samples): # count is in milliseconds
# time step will be 1 millisecond
a = -9.8 # meters per second
# a = -9.8e-3 # per milisecond
v_0_mili = copy.copy(v_0)
v_0_mili = v_0_mili/1000
# v_0_mili *= 1e-3 # get in velocity per milisecond
count = (-2*v_0)/a # count is in MILISECONDS
count = int(round(count*1000))
# return np.array([np.random.randn()*nf_pos + y_0 + v_0*i/1000 + (1/2)*a*((i/1000)**2) for i in range(count)]), count, np.array([y_0 + v_0*i/1000 + (1/2)*a*((i/1000)**2) for i in range(count)]), np.array([np.random.randn()*nf_vel + v_0 + (a)*(i/1000) for i in range(count)]), np.array([v_0 + (a)*(i/1000) for i in range(count)])
return np.array([y_0 + v_0 * (i*dt) + (1/2)*a*((i*dt)**2) for i in range(samples)])
actual_x = np.array([x_0 + (dx_0)*(i*dt) for i in range(samples)])
actual_y = generate_y_data(y_0,dy_0,0,0,dt,samples)
# actual_x = np.ones(samples) * x_0
# actual_y = np.ones(samples) * y_0 # let's just keep it stationary
# Try and work with the generation using stationary object!
print(actual_x.shape)
print(actual_y.shape)
TX_x = np.ones(samples) * 0
TX_y = np.ones(samples) * 0.5
RX1_x = RX1_pos[0] * np.ones(samples)
RX1_y = RX1_pos[1] * np.ones(samples)
RX2_x = RX2_pos[0] * np.ones(samples)
RX2_y = RX2_pos[1] * np.ones(samples)
RX3_x = RX3_pos[0] * np.ones(samples)
RX3_y = RX3_pos[1] * np.ones(samples)
dist_TX = ((TX_x - actual_x)**2+(TX_y - actual_y)**2)**(1/2)
dist_RX1 = ((RX1_x - actual_x)**2 + (RX1_y - actual_x)**2)**(1/2)
dist_RX2 = ((RX2_x - actual_x)**2 + (RX2_y - actual_x)**2)**(1/2)
dist_RX3 = ((RX3_x - actual_x)**2 + (RX3_y - actual_x)**2)**(1/2)
# Now have all the distance information from the separate RX's
# Now convert the 3 buffers to frequency data! --> Total distance * the frequency rate change
F_1 = (dist_TX + dist_RX1)/(3e8) * 6e11
F_2 = (dist_TX + dist_RX2)/(3e8) * 6e11
F_3 = (dist_TX + dist_RX3)/(3e8) * 6e11
# print(D_1)
# Turn the 3 buffers from frequency data into an actual signal
print(int(1/dt))
k = 0 # Responsible for 'batch programming'
print('total samples: ',samples)
print('sampling freq: ',sampling_freq)
# PROBLEM: running out of RAM space with these 900K - 64-bit (double precision) floating point arrays of frequency information
# Solution: Somehow, call these routines as FUNCTIONS (subroutines), upon return the STACK is cleared (RAM)
# 'Garbage collection doesn't happen in line' --> Need to create a function and call it (kinda like a stack!)
# With this function, return 2 things:
# 1) Return the string to append to the original string
# 2) Return the ITERATION to continue the calculation!
text_file_buf1 = open("RX1_buffer.txt","w")
text_file_buf2 = open("RX2_buffer.txt","w")
text_file_buf3 = open("RX3_buffer.txt","w")
# samples_calc = 100 # just do batches of 100
# s_sampled_1 = 'float32_t sampled_RX1[] = {'
# s_sampled_2 = 'float32_t sampled_RX2[] = {'
# s_sampled_3 = 'float32_t sampled_RX3[] = {'
s_sampled_1 = ''
s_sampled_2 = ''
s_sampled_3 = ''
# text_file_buf1.write(s_sampled_1)
# text_file_buf2.write(s_sampled_2)
# text_file_buf3.write(s_sampled_3)
def calc_write(text_file,freq,sampling_freq,sample_num):
sample_value = freq_data(freq,sampling_freq,sample_num)
s = str(sample_value) + '\n'
text_file.write(s)
for q in range(samples):
print('text_file writing, iteration: ', q, 'Frequency at q: ', F_1[q])
calc_write(text_file_buf1,F_1[q],sampling_freq,q)
calc_write(text_file_buf2,F_2[q],sampling_freq,q)
calc_write(text_file_buf3,F_3[q],sampling_freq,q)
sample_size = 512 # or 2024
true_RX1Dist_fname = "RX1_TruDist.txt"
file_true = open(true_RX1Dist_fname,'w')
for x in range(int(samples/sample_size)):
print(F_1[x*sample_size]/(6e11))
for x in range(samples):
s = str(F_1[x]/(6e11)) + '\n'
file_true.write(s)
file_true.close()
print('final x value of ordinance: ',actual_x[-1])
print('final y value of ordinance: ',actual_y[-1])
# text_file_buf1.close()
# Write a function that does the computation AND creates the string, THEN appends it to the text files
# somehow, for the last 3 files delete the last ',' then write '};' and be done!
# write the large datasets to txt files
# text_file_buf1.write()
text_file_buf1.close()
# text_file_buf2.write()
text_file_buf2.close()
# text_file_buf3.write()
text_file_buf3.close()
print(s_sampled_1)
# {number,number,number,number,....,number,number, + '};'... get rid of LAST ','
|
0a6ff68dfe1aa589b13e7baeddc216e2780ca7ec | ngantonio/DataScience-Analysis | /practicas con bases de datos/coutingDomains.py | 1,457 | 3.59375 | 4 | """ cuenta el número total de dominios de emails
y los almacena en una base de datos
"""
import sqlite3 as sql
# Iniciamos las variables de conexión, y creamos la base de datos.
connection = sql.connect('domaindb.sqlite')
cur = connection.cursor()
# Verificamos si la tabla existe, si no, la creamos.
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts (org TEXT, count INTEGER)')
file = input('Enter file name: ')
if len(file) < 1:
file = 'mbox.txt'
fh = open(file)
# Por cada linea...
for line in fh:
# Obtenemos solo las lineas que comiencen por "From: "
if not line.startswith('From: '): continue
pieces = line.split()
# Obtenemos el email
email = pieces[1]
# Para obtener el dominio del email, separamos el string por el caracter '@'
# para: marquard@uct.ac.za el dominio se encuentra en la pos. 1
email = email.split('@')
domain = email[1]
# Almacenamos el dominio y Preguntamos si ya existe en la DB,
# si es asi, actualiza el contador
cur.execute('SELECT count FROM Counts WHERE org = ?', (domain,))
row = cur.fetchone()
if row is None:
cur.execute('INSERT INTO Counts (org, count) VALUES(?,1)',(domain,))
else:
cur.execute('UPDATE Counts SET count = count+1 WHERE org = ?',(domain,))
connection.commit()
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
for row in cur.execute(sqlstr):
print(str(row[0]),row[1])
cur.close() |
492009c5e453bbcd947240576e7741225109328e | Tachone/PythonCode | /countline0007/countline0007.py | 1,154 | 3.640625 | 4 | #!/usr/bin/env python
#coding=utf-8
# 统计目录下文件的代码行数
import os
def walk_dir(path):
file_path=[]
for root,dirs,files in os.walk(path):
for f in files:
if f.lower().endswith('py'):
file_path.append(os.path.join(root,f))
return file_path
def count_codeline(path):
file_name=os.path.basename(path)
line_num=0
empty_line_num=0
note_num=0
note_flag=False
with open(path) as f:
for line in f.readlines():
line_num+=1
if line.strip().startswith('\"\"\"') and not note_flag:
note_num+=1
note_flag=True
continue
if line.strip().startswith('\"\"\"'):
note_flag=False
note_num+=1
if line.strip().startswith('#') or note_flag:
note_num+=1
if line.strip()=='':
empty_line_num+=1
print u"在%s中,共有%d行代码,其中有%d空行,有%d行注释" %(file_name,line_num,empty_line_num,note_num)
if __name__ =='__main__':
for f in walk_dir('.'):
count_codeline(f)
|
8f2417a4bd242c6372d79c5244b5af3be83ca9a2 | MahadiRahman262523/Python_Code_Part-2 | /formatted string.py | 198 | 3.875 | 4 | '''
num1 = 20
num2 = 30
print("sum is = ",num1 + num2)
'''
'''
num1 = 20
num2 = 30
print(f"{num1} + {num2} = {num1 + num2} ")
'''
print("mahadi rahman", end = " ")
print("01301442265")
|
4ee6c5e0690d7c0302b76dbebff6751bbf507c1e | MahadiRahman262523/Python_Code_Part-2 | /factorial.py | 119 | 3.953125 | 4 | n = int(input("enter any positive number = "))
fact = 1
for i in range(n) :
fact = fact*(i+1)
print(fact) |
67293e2d186feadeafd7db8ea20284a37e3b93bd | MahadiRahman262523/Python_Code_Part-2 | /sum of n number.py | 130 | 3.9375 | 4 |
n = int(input("enter any integer value = "))
sum = 0
i = 1
while i <= n :
sum = sum + i
i = i + 1
print(sum)
|
ad0b647a1611a07369624c42e3cea0484b7afd4c | flaherty-kr/DS2000HW | /conv.py | 247 | 3.96875 | 4 | # Kristen Flaherty
# Sec 01
#key parameters
#input
km = float(input('Please enter the number of kilometers:\n'))
#km to miles conversion
conv = .621
full_miles = int(km * conv)
#print full miles statement
print("The number of full miles is:", full_miles)
|
77019b16ce59e91dc2f26b3a73a6f353873b9b6c | cbstudent/Exercises | /4. Sorting/mergeSort.py | 606 | 4.03125 | 4 | def mergeSort(array):
_mergeSort(array, 0, len(array) - 1)
return array
def _mergeSort(array, lo, hi):
if lo >= hi:
return
mid = (lo + hi) // 2 + 1
_mergeSort(array, lo, mid - 1)
_mergeSort(array, mid, hi)
merge(array, lo, mid, hi)
def merge(array, lo, mid, hi):
copy = array[:]
p1 = lo
p2 = mid
cur = lo
while cur <= hi:
if p1 < mid and p2 <= hi:
if copy[p1] < copy[p2]:
array[cur] = copy[p1]
p1 += 1
else:
array[cur] = copy[p2]
p2 += 1
elif p1 < mid:
array[cur] = copy[p1]
p1 += 1
else:
array[cur] = copy[p2]
p2 += 1
cur += 1
|
837e845a9c83a16b34c9581c2bad17b55eda0102 | cbstudent/Exercises | /3. Arrays/threeNumberSum.py | 599 | 3.96875 | 4 | def threeNumberSum(array, targetSum):
# Sort the array (can be sorted in place, because we don't care about the original indices)
array.sort()
res = []
# Use two pointers, one starting from the left, and one starting from the right
for idx, curr in enumerate(array):
i = idx + 1
j = len(array) - 1
while i < j:
currSum = curr + array[i] + array[j]
if currSum < targetSum:
i += 1
elif currSum > targetSum:
j -= 1
elif currSum == targetSum:
ares = sorted([curr, array[i], array[j]])
res.append(ares)
i += 1
j -= 1
return sorted(res)
|
9c5cd49ac894af1653d42d202d98446ac5814a77 | cbstudent/Exercises | /7. Graphs/hasSingleCycle.py | 441 | 3.71875 | 4 | def hasSingleCycle(array):
# Write your code here.
idx = 0
counter = 0
while counter < len(array):
# If we've jumped more than once and we find ourselves back at the starting index, we haven't visited each element
if counter > 0 and idx == 0:
return False
jump = array[idx]
idx = (idx + jump) % len(array)
if idx < 0:
idx = idx + len(array)
counter += 1
if idx == 0:
return True
else:
return False
|
19dcfff0b8fc4eaa073e604d83e2519e862d5353 | SteventsStuff/ElementaryTasks | /tests/t3_triangles_test.py | 1,728 | 3.578125 | 4 | #!/usr/bin/env python3
import unittest
import tasks.t3_triangles as triang
from tasks.t3_triangles import Triangle
class TestTriangle(unittest.TestCase):
def setUp(self) -> None:
self.triangle_1 = Triangle("tr1", 12, 15, 14)
self.triangle_2 = Triangle("tr2", 10.5, 13.5, 12.5)
self.triangle_3 = Triangle("tr3", 2, 5, 4)
self.triangle_4 = Triangle("test_1", 7, 10.3, 9)
# testing Triangle class
def test_Triangle_constructor(self):
self.assertEqual(("test_1", 7, 10.3, 9),
(self.triangle_4._name, self.triangle_4.a_size,
self.triangle_4.b_size, self.triangle_4.c_size))
def test_validate_triangle_size_perfect_input(self):
self.assertEqual(None, self.triangle_4.validate_triangle_size())
# idk
# def test_validate_triangle_size_incorrect_input(self):
# self.assertRaises(ValueError, Triangle("test_error", 7, 1, 9))
def test_get_area(self):
self.assertEqual(78.92678569408487, self.triangle_1.get_area())
def test_get_name(self):
self.assertEqual("tr3", self.triangle_3.get_name())
# testing print func
def test_print_triangles_empty_list(self):
expected = "There are no triangles in this list!"
self.assertEqual(expected, triang.print_triangles([]))
def test_print_triangles_perfect_list(self):
triangle_list = [self.triangle_1, self.triangle_2,
self.triangle_3, self.triangle_4]
expected = """1. [tr1]: 78.93cm
2. [tr2]: 62.15cm
3. [test_1]: 30.93cm
4. [tr3]: 3.80cm
"""
self.assertEqual(expected, triang.print_triangles(triangle_list))
if __name__ == "__main__":
unittest.main()
|
bb3e8df598c01c38d5982158ec26c99f8e77fb3c | blaise594/PythonPuzzles | /printStatements.py | 687 | 4.09375 | 4 | #The Purpose of this program is to demonstrate print statements
# Print full name
print("My name is Daniel Rogers")
# Print the name of the function that converts a string to a floating point number
print("The float() function can convert strings to a float")
# Print the symbol used to start a Python comment
print("The symbol used to start a comment in Python is the pound symbol \'#\' ")
# Print the name of Python data type for numbers without decimals
print("The Python data type used for numbers is the integer type, whole numbers only")
# Print the purpose of the \t escape character
print ('The backslash-t escape character is used to insert TAB spaces into outputs\tlike\tthis')
|
639d50d4d0579ee239adf72a08d7b4d78d9b91b6 | blaise594/PythonPuzzles | /weightConverter.py | 424 | 4.21875 | 4 | #The purpose of this program is to convert weight in pounds to weight in kilos
#Get user input
#Convert pounds to kilograms
#Display result in kilograms rounded to one decimal place
#Get user weight in pounds
weightInPounds=float(input('Enter your weight in pounds. '))
#One pound equals 2.2046226218 kilograms
weightInKilos=weightInPounds/2.2046226218
print('Your weight in kilograms is: '+format(weightInKilos, '.1f'))
|
2b32c38f8df34e7624b993aba7ba38a88059dcbb | i-djurdjevic/BioinformaticsCourseBook | /poglavlja/9/kodovi/SuffixArrayMultiple.py | 1,715 | 3.8125 | 4 | #Formiranje sufiksnog niza na osnovu niza niski strings
def suffix_array_construction(strings):
suffix_array = []
for s in range(len(strings)):
string = strings[s] + '$'
for i in range(len(string)):
suffix_array.append((string[i:],s, i))
suffix_array.sort()
return suffix_array
#Funkcija vraca pozicije na kojima se niska pattern pojavljuje u svakoj pojedinacnoj niski, u "okolini" pozicije mid
def find_neighborhood(suffix_array, mid, pattern):
up = mid
down = mid
while up >= 0 and len(suffix_array[up][0]) > len(pattern) and suffix_array[up][0][:len(pattern)] == pattern:
up -= 1
while down < len(suffix_array) and len(suffix_array[down][0]) > len(pattern) and suffix_array[down][0][:len(pattern)] == pattern:
down += 1
positions = []
for i in range(up+1, down):
positions.append((suffix_array[i][1], suffix_array[i][2]))
positions.sort()
print(positions)
return positions
#Trazenje pozicija na kojima se pojavljuje niska pattern u svakoj pojedinacnoj niski koja je ucestvovala u formiranju suffix_array-a
def pattern_matching_with_suffix_array(suffix_array, pattern):
top = 0
bottom = len(suffix_array)-1
while top <= bottom:
mid = (top + bottom) // 2
if len(suffix_array[mid][0]) > len(pattern):
if suffix_array[mid][0][:len(pattern)] == pattern:
return find_neighborhood(suffix_array, mid, pattern)
if pattern < suffix_array[mid][0]:
bottom = mid - 1
else:
top = mid + 1
def main():
strings = ['ananas', 'and', 'antenna', 'banana', 'bandana', 'nab', 'nana', 'pan']
suffix_array = suffix_array_construction(strings)
pattern = 'an'
print(pattern_matching_with_suffix_array(suffix_array, pattern))
if __name__ == "__main__":
main()
|
f25285c2cc809eeb16fd3696bbfa60ddc341e9e9 | juliali/ClassicAlgorithms | /undirected_graph/ugraph_circle.py | 1,159 | 3.59375 | 4 | import queue
import os
import csv
def is_undirected_graph_circled(adj_matrix):
n = len(adj_matrix)
degrees = [0] * n
visited = []
q = queue.Queue()
for i in range(0, n):
degrees[i] = sum([int(value) for value in adj_matrix[i]])
if degrees[i] <= 1:
q.put(i)
visited.append(i)
while not q.empty():
i = q.get()
for j in range(0, n):
if int(adj_matrix[i][j]) == 1:
degrees[j] -= 1
if degrees[j] == 1:
q.put(j)
visited.append(j)
if len(visited) == n:
return False
else:
return True
def processFile(file_name):
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, file_name)
data = list(csv.reader(open(file_path)))
result = is_undirected_graph_circled(data)
if result:
print("YES. It contains circle(s): " + file_path)
else:
print("NO. It doesn't contain circle(s): " + file_path)
return
processFile("graph1.csv")
processFile("graph2.csv") |
9d2a6aa7b90925def161452c31235a27d5af40ca | bushidosds/MeteorTears | /lib/utils/fp.py | 979 | 3.625 | 4 | # -*- coding:utf-8 -*-
import os
def iter_files(path: str, otype='path') -> list:
r"""
Returns a list of all files in the file directory path.
:param path: file path, str object.
:param otype: out params type, str object default path.
:return: files path list.
:rtype: list object
"""
filename = []
def iterate_files(path):
path_rest = path if not isinstance(path, bytes) else path.decode()
abspath = os.path.abspath(path_rest)
try:
all_files = os.listdir(abspath)
for items in all_files:
files = os.path.join(path, items)
if os.path.isfile(files):
filename.append(files) if otype == 'path' else filename.append(items)
else:
iterate_files(files)
except (FileNotFoundError, AttributeError, BytesWarning, IOError, FileExistsError):
pass
iterate_files(path)
return filename
|
b858cea86ba5635c86653bcc25a02aa9319d3104 | rdauncey/CS50_problem_set_solutions | /pset6/credit.py | 2,025 | 4 | 4 | from cs50 import get_string
from sys import exit
def main():
# Get input from user
number = get_string("Number: ")
digits = len(number)
# Check length is valid
if digits < 13 or digits > 16 or digits == 14:
print("INVALID")
exit(1)
# Luhn's algorithm
if luhns(number) is False:
print("INVALID")
exit(1)
# VISA or MASTERCARD
if digits == 13 or digits == 16:
# Use the number at the beginning to determine the type
if number[0] == "4":
print("VISA")
exit(0)
elif (int(number[:2]) > 50) and (int(number[:2]) < 56):
print("MASTERCARD")
exit(0)
else:
print("INVALID")
exit(0)
# AMEX
elif digits == 15:
# Check the beginning of the number is correct
if number[:2] == "34" or number[:2] == "37":
print("AMEX")
exit(0)
else:
print("INVALID")
exit(1)
# Function takes the number (as a string) as an input, and returns a boolean value
# which indicates whether the number is or is not a valid credit card number
def luhns(number):
even_digits = []
odd_digits = []
for i in range(len(number)):
# If even, append digit in int form to odds list
if i % 2 == 0:
odd_digits.append(int(number[len(number) - i - 1]))
# If not, append to evens list
else:
even_digits.append(int(number[len(number) - i - 1]))
# Multiply all entries in even_digits by 2
even_digits = [i * 2 for i in even_digits]
# If we have a two digit number, preemptively sum the digits
for k in range(len(even_digits)):
# Can be at most two digits
if even_digits[k] > 9:
even_digits[k] = 1 + (even_digits[k] - 10)
# Now we can just sum over the two lists
output = sum(even_digits) + sum(odd_digits)
if output % 10 == 0:
return True
else:
return False
main()
|
abe6d35e9add0faca38e2eb800fef850dee91aed | paperbackdragon/python-300 | /project/dbhelper.py | 2,907 | 3.875 | 4 | """
Database Helper
Author: Heather Hoaglund-Biron
"""
import sqlite3
class DatabaseHelper:
"""
A DatabaseHelper reads and writes MP3 metadata to an SQLite database. It is
necessary to close the connection to the database when finished with the
close() method.
"""
def __init__(self):
"""
Initializes the MP3 metadata database.
"""
self.conn = sqlite3.connect('tags.db')
self.c = self.conn.cursor()
#Create table
self.c.execute("""CREATE TABLE IF NOT EXISTS songs
(title TEXT NOT NULL,
album TEXT NOT NULL,
artist TEXT,
track INTEGER,
length TEXT,
PRIMARY KEY (title, album))""")
#Commit changes
self.conn.commit()
def write(self, data):
"""
Takes the given song and writes it to the database, returning the
primary key. Song title and album name are required.
"""
insert_text = "INSERT into songs (title, album"
columns = ['title', 'album', 'artist', 'track', 'length']
used = ['title', 'album']
primary_key = {}
#See which tags are in the dictionary (title and album aren't optional)
for column in columns[2:]:
if column in data:
insert_text += ", " + column
used.append(column)
insert_text += ") values ("
#Prepare values
values = []
for column in used:
if column == "track":
values.append(data[column])
else:
values.append("\"" + data[column] + "\"")
if column == "title" or column == "album":
primary_key[column] = data[column]
insert_text += ", ".join(values)
insert_text += ")"
#Execute command(s) and commit
try:
self.c.execute(insert_text)
self.conn.commit()
print "Writing tag: %s" % data
except sqlite3.IntegrityError:
primary_key = {}
print "Item already exists in database."
return primary_key
def read(self, key):
"""
Reads the information given in the query, grabs the specified data from
the database, and returns it.
"""
select_text = "SELECT * from songs WHERE title is \"%s\" AND album is "\
"\"%s\" ORDER BY artist, album, track" % (key["title"], key["album"])
self.c.execute(select_text)
rows = []
for row in self.c.fetchall():
rows.append(row)
print "Reading tag: %s" % rows
return rows
def close(self):
self.conn.close()
|
3f04d5bef7608689c343a5eddb61c3ac1939a3e8 | boconganh/algorithm | /python/merge-sort.py | 418 | 3.609375 | 4 | def merge(A,p,q,r):
n1=q-p+1
n2=r-q
L=A[p:p+n1]+[float("inf")]
R=A[q+1:q+1+n2]+[float("inf")]
#print A[p:r+1],L,R
i=0
j=0
for k in range(p,r+1):
if L[i]<=R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
def merge_sort(A,p,r):
if p<r:
q=(p+r)//2
merge_sort(A,p,q)
merge_sort(A,q+1,r)
merge(A,p,q,r)
A=[1,2,4,2,4,32,45,6]
print A
merge_sort(A,0,len(A)-1)
print A
|
a2dad7fea5ec6e42767c6ab36c4658c857d5548c | boconganh/algorithm | /python/find-max-subarray.py | 997 | 3.59375 | 4 |
def find_max_cross_subarray(A,low,mid,high):
left_sum=float("-inf")
sum=0
for i in range(mid,low-1,-1):
sum+=A[i]
if sum>left_sum:
left_sum=sum
max_left=i
right_sum=float("-inf")
sum=0
for j in range(mid+1,high+1):
sum+=A[j]
if sum>right_sum:
right_sum=sum
max_right=j
return (max_left,max_right,left_sum+right_sum)
def find_max_subarray(A,low,high):
if low==high:
return (low,high,A[low])
else:
mid=(low+high)//2
left_low,left_high,left_sum=find_max_subarray(A,low,mid)
right_low,right_high,right_sum=find_max_subarray(A,mid+1,high)
cross_low,cross_high,cross_sum=find_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 (right_low,right_high,right_sum)
else:
return (cross_low,cross_high,cross_sum)
A=[11,-2,-4,3,-4,23,-145,345,23]
print A
print find_max_subarray(A,0,len(A)-1) |
ac8ff352c058b7b1e3885d3bca7611f29437f2b4 | SaeedTaghavi/MonteCarloIntegration | /test.py | 1,391 | 3.640625 | 4 | import numpy as np
import random
def calc_pi(N):
inCircle = 0
for i in range(N):
point = (random.random() , random.random())
r = point[0]*point[0] + point[1]*point[1]
if r < 1.0 :
inCircle = inCircle +1
# plt.plot(point[0], point[1], 'r.')
# else:
# plt.plot(point[0], point[1], 'b.')
res = float(inCircle)/float(N)
res = 4.0*res
return res
def pi_diff(temp_pi):
return np.pi-temp_pi
def calc_pi_array(num_array):
res_array = []
for num in num_array:
res_array = res_array + [calc_pi(num)]
return res_array
Numbers = []
for i in range(2,7):
Numbers = Numbers + [int(10.0**i)]
Numbers = Numbers + [int(3.0 * 10.0 ** i)]
Numbers = Numbers + [int(6.0 * 10.0 ** i)]
import matplotlib.pyplot as plt
for i in range(1,5):
pis = calc_pi_array(Numbers)
pi_diff_array = []
for pi in pis:
pi_diff_array = pi_diff_array + [pi_diff(pi)]
print(Numbers)
print(pis)
print(pi_diff_array)
plt.plot(Numbers,pi_diff_array,'-s')
plt.xscale('log')
plt.xlabel('N')
plt.ylabel('pi_calc - pi')
plt.savefig('PiDeviationFromTheExactValue.png')
plt.show()
#
# def double(x):
# return 2.0*x
#
# def sinSquare(x):
# return np.sin(x)*np.sin(x)
#
# print(double(3.0))
# print(sinSquare(np.pi/6.0))
|
eac27c0231a6e7acfd305620cff56fd69e3f6d3e | apan64/basic-data-structures | /Lab_11.py | 1,194 | 3.703125 | 4 | import math
class AdjMatrixGraph:
def __init__ (self, n):
self.n = n
self.array = []
for x in range(n):
q = []
for y in range(n):
q.append(int(0))
self.array.append(q)
def display (self):
for x in range (self.n):
for y in range (self.n):
print ("{0:2}".format(self.array[x][y]), end=" ")
print( )
print( )
def insert (self, x, y, w):
self.array[x][y] = int(w)
def floyd (self):
for i in range(0, self.n):
for r in range(0, self.n):
for c in range(0, self.n):
self.array[r][c] = min(self.array[r][c], self.array[r][i] + self.array[i][c])
def main( ):
n = eval(input("Enter number of vertices: "))
G = AdjMatrixGraph(n)
G.display( )
k = math.ceil(math.sqrt(n))
for x in range(n):
for y in range(n):
if x!=y:
weight = (x%k-y%k)**2 + (x//k-y//k)**2 + 1
G.insert(x, y, weight)
G.display( )
G.floyd( )
G.display( )
if __name__ == '__main__':
main( )
|
ab96fe2f94f539e7535d8110c3dafcd2f35cf097 | apan64/basic-data-structures | /Lab_6.py | 2,569 | 3.921875 | 4 |
class Node:
def __init__ (self, x, q):
self.data = x
self.next = q
class Stack:
def __init__ (self):
self.top = None
def isEmpty (self):
return self.top == None
def push (self, x):
self.top = Node (x, self.top)
def pop (self):
if self.isEmpty( ):
raise KeyError ("Stack is empty.")
x = self.top.data
self.top = self.top.next
return x
class List:
def __init__ (self):
self.head = None
def build_list (self):
str = input ("Enter strings separated by blanks: ")
for x in str.split (" "):
if self.head == None:
self.head = Node (x, None)
curr = self.head
else:
curr.next = Node (x, None)
curr = curr.next
def display (self):
curr = self.head
while curr != None:
print (curr.data, end=" ")
curr = curr.next
print( )
def reverse_display_1 (self):
st = Stack()
curr = self.head
while curr != None:
st.push(curr.data)
curr = curr.next
while (not(st.isEmpty())):
print(st.pop(), end = " ")
print( )
def recur(self, q):
if q.next != None:
self.recur(q.next)
print(q.data, end = " ")
def reverse_display_2 (self):
self.recur(self.head)
print( )
def reverse_display_3 (self):
w = self.head
curr = self.head
head = self.head
head = head.next
curr.next = None
while head != None:
curr = head
head = head.next
curr.next = w
w = curr
head = curr.next
while curr != None:
print (curr.data, end=" ")
curr = curr.next
print( )
curr = w
curr.next = None
while head != None:
curr = head
head = head.next
curr.next = w
w = curr
def main( ):
L = List( )
L.build_list( )
print ("Forward: ", end="\t")
L.display( )
print ("Backward: ", end="\t")
L.reverse_display_1( )
print ("Backward: ", end="\t")
L.reverse_display_2( )
print ("Backward: ", end="\t")
L.reverse_display_3( )
print ("Forward: ", end="\t")
L.display( )
if __name__ == '__main__':
main( )
|
02856d56ce1a0c1a834220d6e0eb7d259010e53d | naitiknakrani/Machine-Learning-algorithms | /1.3-polynomial-regression.py | 3,466 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 11 17:42:30 2021
@author: naitik
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
df = pd.read_csv("FuelConsumptionCo2.csv")
df.head() # show data
df.describe() #summarize data
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] # select few samples
cdf.iloc[5:7,:] # select specific row and column
cdf.head(9) # give first 9 rows data
# Training starts from here
# Let's split our dataset into train and test sets.
# 80% of the entire dataset will be used for training and 20% for testing.
# We create a mask to select random rows using np.random.rand() function:
msk = np.random.rand(len(df)) < 0.8
train = cdf[msk]
test = cdf[~msk]
# Build a Model of Linear Regression
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
test_x = np.asanyarray(test[['ENGINESIZE']])
test_y = np.asanyarray(test[['CO2EMISSIONS']])
poly = PolynomialFeatures(degree=2)
train_x_poly = poly.fit_transform(train_x) # convert Train_x into 1 x x^2
train_x_poly
# Now we can use same linear model for polynomial data
regr = linear_model.LinearRegression()
regr.fit (train_x_poly, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
# plot the data and non-linear regression line
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
XX = np.arange(0.0, 10.0, 0.1) # generate sample sequence like for XX=0:0.1:10
yy = regr.intercept_[0]+ regr.coef_[0][1]*XX+ regr.coef_[0][2]*np.power(XX, 2)
plt.plot(XX, yy, '-r' )
plt.xlabel("Engine size")
plt.ylabel("Emission")
#Evaluation matrix
from sklearn.metrics import r2_score
test_x_poly=poly.fit_transform(test_x)
test_y_ = regr.predict(test_x_poly)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y , test_y_) )
print('Variance score: %.2f' % regr.score(test_x_poly, test_y))
# regression with cubic polynomial
poly = PolynomialFeatures(degree=3)
train_x_poly = poly.fit_transform(train_x) # convert Train_x into 1 x x^2
train_x_poly
# Now we can use same linear model for polynomial data
regr = linear_model.LinearRegression()
regr.fit (train_x_poly, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
# plot the data and non-linear regression line
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
XX = np.arange(0.0, 10.0, 0.1) # generate sample sequence like for XX=0:0.1:10
yy = regr.intercept_[0]+ regr.coef_[0][1]*XX+ regr.coef_[0][2]*np.power(XX, 2)+regr.coef_[0][3]*np.power(XX, 3)
plt.plot(XX, yy, '-r' )
plt.xlabel("Engine size")
plt.ylabel("Emission")
#Evaluation matrix
from sklearn.metrics import r2_score
test_x_poly=poly.fit_transform(test_x)
test_y_ = regr.predict(test_x_poly)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y , test_y_) )
print('Variance score: %.2f' % regr.score(test_x_poly, test_y)) |
7ebafa063d92a5960289cba76c3043e18990810e | IqbalHadiSubekti/Factorial | /factorial.py | 462 | 4.0625 | 4 | count = 0
while count == 0:
def factorial(n):
if 1 <= n <= 2:
return n
elif 3 <= n <= 5:
return n + 1
elif 6 <= n <= 8:
return n + 2
elif 9 <= n <= 11:
return n + 3
else:
print("Input Salah")
n = int(input("Input: "))
print("Output:",factorial(n))
ulangi = str(input("Hitung ulang? ya/tidak: "))
if ulangi == "ya":
pass
elif ulangi == 'tidak':
break
|
5e238d1bc97635963bcb15b615c9e94fbf7c7b5f | dharanpreethi/Text-Minining_Indian-English-Liteature | /Text_mining/Corpus_tm.py | 2,458 | 3.890625 | 4 | # Corpus of text analysis
# Now, we can mine the corpus of texts using little more advanced methods of Python.
#1.Install glob using pip and import the module
#2. Import other necessary modules which we already installed in our previous analysis
#3. Asterisk mark will import all plain text files in the corpus
#4. Create a corpus of text files and call them using glob
#5. Store the stopwords of nltk in a variable
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import glob
corpus = glob.glob("E:\Medium Blog\Text_mining\*.txt")
stop_words = set(stopwords.words('english'))
# Pre-processing and analysis
# We will call the corpus using for loop and then read the texts and convert them into lowercase. We extract the content for analysis, apply stopwords list and tokenization as we did for the single text, but everything should be in the for loop as in the below code.
for i in range(len(corpus)):
text_file = open(corpus[i], "r", encoding = "UTF-8")
lines = []
lines = text_file.read().lower()
extract1 =lines.find("start of this project")
extract2 = lines.rfind("end of this project")
lines = lines[extract1:extract2]
tokenizer = RegexpTokenizer('\w+') # extracting words
tokens = tokenizer.tokenize(lines) # tokenize the text
new_stopwords = ("could", "would", "also", "us") # add few more words to the list of stopwords
stop_words = stopwords.words('english')
for i in new_stopwords:
stop_words.append(i) # adding new stopwords to the list of existing stopwords"""
words_list = [w for w in tokens if not w in stop_words]
filtered_words = []
for w in tokens:
if w not in stop_words:
filtered_words.append(w)
fre_word_list = nltk.FreqDist(filtered_words) #extracting frequently appeared words
print(fre_word_list.most_common(5)) # check the most common frequent words
fre_word_list.plot(25) #create a plot for the output
pos = nltk.pos_tag(filtered_words, tagset = 'universal') # applying parts of speech (pos) tag for further analysis
p = []
y = ['NOUN'] # change the pos here to store them separately
for j in pos:
for l in y:
if l in j:
p.append(j)
noun = nltk.FreqDist(p)# check the frequency of each pos
noun.plot(20)# creating a plot for pos
|
8160b104778db2c44617989b4a58d2f9873fa57c | AYBUcode/CENG113fall2020 | /Week3p.py | 141 | 3.828125 | 4 | a=3.556; b=4; c="abc"
print('{0}+{1}={2}'.format(a,b,a+b))
print("the value of a:%10.0f!!"%(a))
x = int(input("Enter a value: "))
print(x*2) |
24a70d398de181471d15d36d995c8585b1c35ea7 | quentinb28/problem-solving-challenges | /codility/flags.py | 1,694 | 3.6875 | 4 | def solution(A):
# initialize list of peaks indexes in between peaks
peaks = [0] * len(A)
# last item should be index outside of peaks length
next_peak = len(A)
peaks[-1] = next_peak
# stops at 0 because we want to avoid index out of range within if statement
for i in range(len(A) - 2, 0, -1):
# if height greater than point before and after then save peak index
if (A[i] > A[i - 1]) and (A[i] > A[i + 1]):
next_peak = i
# keep saving peak index until next peak occurs
peaks[i] = next_peak
# cannot be within loop for index out of bound reasons
peaks[0] = next_peak
current_guess = 0
next_guess = 0
# iterate through flags counts until it breaks
while can_place_flags(peaks, next_guess):
# saves last working flags count
current_guess = next_guess
next_guess += 1
return current_guess
def can_place_flags(peaks, flags_to_place):
# to land on index 1 after first iteration (cannot land on index 0)
current_position = 1 - flags_to_place
# iterates through each flag and add the relevant number of places to next position
for i in range(flags_to_place):
# if next flag falls outside of peaks index range
if current_position + flags_to_place > len(peaks) - 1:
return False
# current position moves to current position + flags places
current_position = peaks[current_position + flags_to_place]
# if last current position within peaks size then return True
return current_position < len(peaks)
if __name__ == '__main__':
A = [1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]
solution(A)
|
4c22ce72238761ce47b68c340174df50866a6a35 | quentinb28/problem-solving-challenges | /sherlock-and-anagrams/sherlock-and-anagrams-exercise.py | 1,063 | 3.890625 | 4 | from collections import Counter
from itertools import combinations
s = 'ifailuhkqq'
def sherlockAndAnagrams(s):
# Variable to store all possible combinations
all_combinations = []
# Iterate through substrings starting points
for i in range(0, len(s) + 1):
# Iterate through substrings ending points
for j in range(1, len(s) + 1):
# Append substring to list of combinations
all_combinations.append(s[i:j])
# Sort all substrings so the anagrams can be counted
all_combinations = [''.join(sorted(c)) for c in all_combinations]
# Filter out all empty strings
all_combinations = list(filter(None, all_combinations))
result = 0
# Get the values from the counter and compute all the possible anagram pairs
# (i.e. if v = 4 then the options are 1-2 1-3 1-4 2-3 2-4 3-4 = 6)
for k, v in Counter(all_combinations).items():
result += len(list(combinations(range(v), 2)))
return result
if __name__ == '__main__':
r = sherlockAndAnagrams(s)
print(r)
|
39347b2b248bd565b8a1df9753681900855e88d0 | quentinb28/problem-solving-challenges | /new-year-chaos/new-year-chaos-exercise.py | 585 | 3.578125 | 4 | q = [2, 1, 5, 3, 4]
def minimumBribes(q):
# Initiate total number of bribes
total_bribes = 0
# Iterate through each runner backward
for i in range(len(q) - 1, -1, -1):
# Stop execution if a runner bribes more than two runners
if q[i] - (i + 1) > 2:
print('Too chaotic')
return
# Add the number of runners behind current runner that were bribed
else:
total_bribes += len(list(filter(lambda x: x < q[i], q[i + 1:])))
print(total_bribes)
if __name__ == '__main__':
minimumBribes(q)
|
79fb67bd7592371aaf3861d4e0f9dc84f3a94fdd | y001003/PythonStudy | /_class/class_overriding_1.py | 2,318 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
.format(self.name,location,self.speed))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
Flyable.__init__(self, flying_speed)
# 메서드 오버라이딩 move로 fly 기동하도록 메서드 move 재정의
def move(self, location):
print("[공중 유닛 이동]")
self.fly(self.name, location)
# 벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐",80,10,20)
# 배틀크루저 : 공중 유닛, 체력, 공격력 좋지만 느림
battlecruiser = FlayableAttackUnit("배틀크루저", 500, 25, 3)
vulture.move("11시")
#battlecruiser.fly(battlecruiser.name,"9시")
battlecruiser.move("9시")
|
2c8446bcdebf09395972b1f4fc94eecc00a29fde | y001003/PythonStudy | /_class/class_super_1.py | 2,233 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
.format(self.name,location,self.speed))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
Flyable.__init__(self, flying_speed)
# 메서드 오버라이딩 move로 fly 기동하도록 메서드 move 재정의
def move(self, location):
print("[공중 유닛 이동]")
self.fly(self.name, location)
#건물
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
#Unit.__init__(self, name, hp, 0)
super().__init__(name, hp, 0) # 자신이 상속받는 부모클래스 초기화
self.location = location
|
36b67db6ed6e02eb188301bea8a878aa34166ad6 | y001003/PythonStudy | /_file/input_output_1.py | 856 | 3.765625 | 4 |
# print("Python","Java","JavaScript", sep=" vs ", end="?")
# print("무엇이 더 재미있을까요?")
# import sys
# print("Python","Java", file=sys.stdout)
# print("Python","Java", file=sys.stderr)
# dictionary
# scores = {"수학":0, "영어":50, "코딩":100}
# for subject, score in scores.items():# items() : key와 value 쌍으로 보내줌
# #print(subject,score)
# #왼쪽정렬 8공간 오른쪽 정렬 4개공간
# print(subject.ljust(8), str(score).rjust(4), sep=":")
#은행 대기순번표
# 001, 002, 003, ...
# for num in range(1,21):
# print("대기번호 : " + str(num).zfill(3))
# 표준 입력
answer = input("아무 값이나 입력하세요 : ")
print(type(answer)) # 무조건 String 문자열형태로 기억된다.
# print("입력하신 값은 " + answer + "입니다.")
|
3bdb316174a1c4996567dd5bb66fd25ab8891b57 | y001003/PythonStudy | /_for,while/for_2.py | 519 | 3.671875 | 4 | # 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102,103,104.
# students = [1,2,3,4,5]
# print(students)
# students = [i+100 for i in students]#students 값을 i에 대입해서 각 i +100
# print(students)
# 학생 이름을 길이로 변환
# students = ["Iron man", "Thor", "I am groot"]
# students = [len(i) for i in students]
# print(students)
# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students) |
c0287f0659be8e9c8b945efbeb98e648caf565a9 | y001003/PythonStudy | /_class/class_heritage_1.py | 1,683 | 3.6875 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp):
self.name = name
self.hp = hp
print("{0} 유닛이 생성되었습니다.".format(self.name))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, damage)
Flyable.__init__(self, flying_speed)
# 발키리 : 공중 공격 유닛, 한번에 14발 미사일 발사
valkyrie = FlayableAttackUnit("발키리",200,6,5)
valkyrie.fly(valkyrie.name,"3시")
|
c3a23f4391d29250c7ff9ee4fa0ad9cd133abbe7 | priancho/nlp100 | /05.py | 900 | 4.3125 | 4 | #usage example:
#python3 05.py 2 "This is a pen."
import re
import sys
# extract character n-grams and calculate n-gram frequency
def char_n_gram(n, str):
ngramList = {}
n=int(n)
str = str.lower()
wordList=re.findall("[a-z]+",str)
for word in wordList:
if len(word) >= n:
for i in range(len(word)-n+1):
if word[i:i+n] in ngramList:
ngramList[word[i:i+n]]+=1
else:
ngramList[word[i:i+n]]=1
return ngramList
# extract character n-grams and calculate n-gram frequency
def word_n_gram(n, str):
next
if __name__ == '__main__':
if len(sys.argv) != 3:
print "Usage: %s <n> <sentence>" % (sys.argv[0])
print " <n>: n for n-gram."
print " <sentence>: input sentence to generate n-grams"
print ""
print " e.g., %s 2 \"This is a pen.\"" % (sys.argv[0])
exit(1)
print (char_n_gram(sys.argv[1],sys.argv[2]))
print (word_n_gram(sys.argv[1],sys.argv[2]))
|
af416cceefc1c63424869b66e5fbbaccf9e1f4a5 | silvaniodc/python | /Aulas Python/E_hoje.py | 1,049 | 3.546875 | 4 | # -*- coding: UTF-8 -*-
# O que Silvanio vai fazer no Domingo?
def hoje_e_o_dia():
from datetime import date
hj = date.today()
dias = ('Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado', 'Domingo')
dia = int(hj.weekday())
if dia == 3 :
print 'Hoje é %s e Silvânio vai continuar Estudando insanamente...!' % (dias[hj.weekday()])
if dia == 1 :
print 'Hoje é %s e Silvânio vai na Ubercom ver se o HD SSD ja chegou!' % (dias[hj.weekday()])
if dia == 6 :
print 'Hoje é %s e com certeza Silvânio vai pescar :) ' % (dias[hj.weekday()])
if dia == 5 :
print 'Hoje é %s e Silvânio vai levar Janaina pra tomar Açai!' % (dias[hj.weekday()])
if dia == 2 :
print 'Hoje é %s e Silvânio vai estudar Inglês igual um a louco!' % (dias[hj.weekday()])
if dia == 0 :
print 'Hoje é %s e Silvânio vai faze um Churrasco de Picanha au au!' % (dias[hj.weekday()])
if dia == 4 :
print 'Hoje é %s e Silvânio vai assistir Family Guy na Netflix!' % (dias[hj.weekday()])
hoje_e_o_dia() |
fee0f545fe5e9ec8758ef45e2411e1a2e76801c4 | rustikk/OpenCV-Basics | /opencv-getting-setting/gett_setting_code_along.py | 1,990 | 3.546875 | 4 | import argparse
import cv2
#construct the argument parser
ap = argparse.ArgumentParser()
#if no argument is passed, "adrian.png" is used
ap.add_argument("-i", "--image", type=str, default="adrian.png",
help="path to input image")
#vars stores the arguments in a dictionary
args = vars(ap.parse_args())
#load the image, grab it spacial dimensions (width and height),
#and then display the original image to our screen
#reads the image from the argument passed at the command line,
#the input path to the image being manipulated
image = cv2.imread(args["image"])
#grabs the width and height
(h, w) = image.shape[:2]
#shows the image with a title of Original
cv2.imshow("Original", image)
#keeps the image open til a key is pressed, then it closes
#cv2.waitKey(0)
#rgb values at (0, 0)
(b, g, r) = image[0, 0]
print("Pixel at (0, 0) - Red: {}, Green: {}, Blue {}".format(r, g, b))
# access the pixel located at x=50, y=20
(b, g, r) = image[20, 50]
print("Pixel at (50, 20) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# update the pixel at (50, 20) and set it to red
image[20, 50] = (0, 0, 255)
#y values first then x values as images are numpy arrays
#and you access rows before columns in numpy arrays
(b, g, r) = image[20, 50]
print("Pixel at (50, 20) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# compute the center of the image, which is simply the width and height
# divided by two
cX, cY = (w // 2, h // 2)
# since we are using NumPy arrays, we can apply array slicing to grab
# large chunks/regions of interest from the image -- here we grab the
# top-left corner of the image
tl = image[0:cY, 0:cX]
tr = image[0:cY, cX:w]
br = image[cY:h, cX:w]
bl = image[cY:h, 0:cX]
cv2.imshow("Top-Left Corner", tl)
cv2.imshow("Top-Right Corner", tr)
cv2.imshow("Bottom-Right Corner", br)
cv2.imshow("Bottom-left Corner", bl)
#set the top left corner of the original image to be green
image[0:cY, 0:cX] = (255, 0, 255)
#show updated image
cv2.imshow("Updated", image)
cv2.waitKey(0) |
bc44e991bdb4525bbca5a93fe4e6db50947fe225 | kerroggu/AtCoderLibrary | /src/UnionFind.py | 1,325 | 3.609375 | 4 | ## Tested by ABC264-E
## https://atcoder.jp/contests/abc264/tasks/abc264_e
## Tested by ABC120-D
## https://atcoder.jp/contests/abc120/tasks/abc120_d
class UnionFind:
def __init__(self,n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.parent=[-1]*n
# 連結成分の個数を管理
self._size=[1]*n
def root(self,x):
if self.parent[x]<0:
return x
else:
# 経路の圧縮
self.parent[x]=self.root(self.parent[x])
return self.parent[x]
def same(self,x,y):
return self.root(x)==self.root(y)
def union(self,x,y):
r1=self.root(x)
r2=self.root(y)
if r1==r2:
return
# ランクの取得
d1=self.parent[r1]
d2=self.parent[r2]
if d1<=d2:
self.parent[r2]=r1
self._size[r1]+=self._size[r2]
if d1==d2:
self.parent[r1]-=1
else:
self.parent[r1]=r2
self._size[r2]+=self._size[r1]
def size(self,x):
return self._size[self.root(x)]
def __str__(self):
rt=[i if j<0 else j for i,j in enumerate(self.parent)]
return str(rt)
|
053d941b6d0539e9510961fd68a4a70123ff0cc7 | DouglasCremonese/Uri | /1042.py | 266 | 3.734375 | 4 | # Exercício 1042 Uri Online Judge
# Programador: Douglas Garcia Cremonese
lista = list()
a, b, c = map(int, input().strip().split(" "))
lista.append(a)
lista.append(b)
lista.append(c)
lista.sort()
for i in range(3):
print(lista[i])
print()
print(a)
print(b)
print(c) |
8a56d576c3c6be23f5fdbb3ad70965befbac04f7 | juancebarberis/algo1 | /practica/7-10.py | 898 | 4.3125 | 4 | #Ejercicio 7.10. Matrices.
#a) Escribir una función que reciba dos matrices y devuelva la suma.
#b) Escribir una función que reciba dos matrices y devuelva el producto.
#c) ⋆ Escribir una función que opere sobre una matriz y mediante eliminación gaussiana de-
#vuelva una matriz triangular superior.
#d) ⋆ Escribir una función que indique si un grupo de vectores, recibidos mediante una
#lista, son linealmente independientes o no.
A = [(2,1), (4,1)]
B = [(4,0), (2,8)]
def sumarMatrices(A, B):
""""""
resultado = []
for i in range(len(A)):
nuevaFila = []
for e in range(len(A[i])):
nuevaFila.append(A[i][e] + B[i][e])
resultado.append(nuevaFila)
return resultado
print('A')
for fila in A:
print(fila)
print('B')
for fila in B:
print(fila)
print('Resultado!:')
res = sumarMatrices(A, B)
print(f"{res[0]}")
print(f"{res[1]}")
|
49ff1527a9468412bde79ed0664bdbf5ebbdac99 | juancebarberis/algo1 | /tp2/modulos/input.py | 2,558 | 3.625 | 4 | #Este módulo contiene funciones del tipo input que intervienen en la jugabilidad
#y el movimiento de Snake.
from modulos.terminal import timed_input
def inputJugada(movimiento, variables, _ESPECIALES, snake):
"""
Comprueba lo ingresado por el usuario desde el teclado.
Evalúa si pertenece a un movimiento, un especial, o a un cierre del juego.
"""
entrada = timed_input(float(variables['SPEED']))
#Condicionales de 'salir del juego'.
if entrada.isspace(): #Para salir del juego, presiona <SPACE>
return False, variables, snake, _ESPECIALES
#Condicionales de movimiento
if entrada == 'w' and not movimiento == 's':
return entrada, variables, snake, _ESPECIALES
elif entrada == 'a' and not movimiento == 'd':
return entrada, variables, snake, _ESPECIALES
elif entrada == 's' and not movimiento == 'w':
return entrada, variables, snake, _ESPECIALES
elif entrada == 'd' and not movimiento == 'a':
return entrada, variables, snake, _ESPECIALES
#Condicionales de especiales
especiales = variables['SPECIALS']
if especiales == [] or especiales[0] == '':
return movimiento, variables, snake, _ESPECIALES
for i in range(len(especiales)):
if entrada == _ESPECIALES[especiales[i]]['E_KEY'] and int(_ESPECIALES[especiales[i]]['E_CANT']) > 0:
if _ESPECIALES[especiales[i]]['E_TYPE'] == 'VELOCIDAD':
velocidad = float(variables['SPEED'])
velocidad += float(_ESPECIALES[especiales[i]]['E_VALUE'])
variables['SPEED'] = str(velocidad)
_ESPECIALES[especiales[i]]['E_CANT'] = int(_ESPECIALES[especiales[i]]['E_CANT'])-1
break
if _ESPECIALES[especiales[i]]['E_TYPE'] == 'LARGO':
if len(snake) == 1:
break
if int(_ESPECIALES[especiales[i]]['E_VALUE']) == -1:
snake.pop(-1)
if int(_ESPECIALES[especiales[i]]['E_VALUE']) == 1:
if movimiento == 'w': snake.insert(0, (snake[0][0] - 1, snake[0][1]))
if movimiento == 's': snake.insert(0, (snake[0][0] + 1, snake[0][1]))
if movimiento == 'a': snake.insert(0, (snake[0][0], snake[0][1] - 1))
if movimiento == 'd': snake.insert(0, (snake[0][0], snake[0][1] + 1))
_ESPECIALES[especiales[i]]['E_CANT'] = int(_ESPECIALES[especiales[i]]['E_CANT'])-1
break
return movimiento, variables, snake, _ESPECIALES |
aa85396997537a23bda51f9247ef62426ba564a3 | juancebarberis/algo1 | /practica/mapEnClase.py | 182 | 3.609375 | 4 | def map(seq, funcion):
res = []
for elem in seq:
res.append(funcion(elem))
return res
def por_2(n): return n * 2
seq = [1,2,3,4,5,6,7,8]
print(map(seq, por_2)) |
51956c3e996f59440be71017a4160422f79b320b | juancebarberis/algo1 | /pre-parcialito/parcialito_3.py | 2,155 | 3.734375 | 4 | '''
1. Escribir una funci´on reemplazar que tome una Pila, un valor nuevo y un valor viejo y
reemplace en la Pila todas las ocurrencias de valor viejo por valor nuevo. Considerar que la
Pila tiene las primitivas apilar(dato), desapilar() y esta vacia().
'''
def reemplazar(pila, nuevo, viejo):
pilaAuxiliar = Pila()
#Recorro pila hasta vaciarla
while not pila.esta_vacia():
valor = pila.desapilar()
if valor == viejo:
valor = nuevo
pilaAuxiliar.apilar(valor)
#Muevo los valor de la pila auxiliar a la pila original
while not pilaAuxiliar.esta_vacia():
pila.apilar(pilaAuxiliar.desapilar())
'''
2. Escribir un m´etodo que invierta una ListaEnlazada utilizando una Pila como estructura
auxiliar y considerando que lista solo tiene una referencia al primer nodo.
'''
import enlazadas
import pilas
import colas
def invertir_lista_enlazada(self):
''''''
pila = Pila()
#Apilo todos los elementos en pila
actual = self.prim
while actual:
pila.apilar(actual)
actual = self.prox
#Vuelvo a enlistar los datos en la lista de manera invertida
primero = self.prim
proximo = self.prox
while not pila.esta_vacia():
primero = pila.desapilar()
proximo = None
'''
3. Escribir una funci´on que reciba una pila de n´umeros y elimine de la misma los elementos
consecutivos que est´an repetidos. Se pueden usar estructuras auxiliares. La funci´on no devuelve
nada, simplemente modifica los elementos de la pila que recibe por par´ametro.
Por ejemplo: remover duplicados consecutivos(Pila([2, 8, 8, 8, 3, 3, 2, 3, 3, 3, 1, 7]))
Genera: Pila([2, 8, 3, 2, 3, 1, 7]).
'''
def limpiar_repetidos_pila(pila):
''''''
pilaAuxiliar = Pila()
while not pila.esta_vacia():
valor = pila.desencolar()
if not pila.esta_vacia():
siguiente = pila.ver_tope()
elif valor == siguiente:
continue
pilaAuxiliar.apilar(valor)
while not pilaAuxiliar.esta_vacia():
pila.apilar(pilaAuxiliar.desapilar())
'''
6. Escribir una funci´on que reciba una cola y la cantidad de elementos en la misma,
y devuelva True si los elementos forman un pal´ındromo o False si no.
Por ejemplo:
es palindromo([n, e, u, q, u, e,n], 7) − > True
'''
|
ef2adcd35cf3050024eaad85e20cfa17d87d6132 | juancebarberis/algo1 | /practica/6-1.py | 1,072 | 4.03125 | 4 | #Ejercicio 6.1. Escribir funciones que dada una cadena de caracteres:
#a) Imprima los dos primeros caracteres.
#b) Imprima los tres últimos caracteres.
#c) Imprima dicha cadena cada dos caracteres. Ej.: 'recta' debería imprimir 'rca'
#d) Dicha cadena en sentido inverso. Ej.: 'hola mundo!' debe imprimir '!odnum aloh'
#e) Imprima la cadena en un sentido y en sentido inverso. Ej: 'reflejo' imprime
#'reflejoojelfer' .
def imprimirDosPrimerosCaracteres(s):
print('Primeros dos: ' + s[:2])
def imprimirTresUltimosCaracteres(s):
print('Tres ultimos caracteres: ' + s[-3:])
def imprimirCadaDosCaracteres(s):
print('Cada dos caracteres: ' + s[::2])
def imprimirCadenaInversa(s):
print('Inversa: ' + s[::-1])
def imprimirCadenaEInversa(s):
print('Cadena e Inversa: ' + s + s[::-1])
entrada = input('Ingrese una secuencia: ')
aReturn = imprimirDosPrimerosCaracteres(entrada)
bReturn = imprimirTresUltimosCaracteres(entrada)
cReturn = imprimirCadaDosCaracteres(entrada)
dReturn = imprimirCadenaInversa(entrada)
eReturn = imprimirCadenaEInversa(entrada) |
04dcc88ad0fb461fa9aafe3e290ab9addb03c08e | juancebarberis/algo1 | /practica/5-4.py | 1,135 | 4.125 | 4 | #Ejercicio 5.4. Utilizando la función randrange del módulo random , escribir un programa que
#obtenga un número aleatorio secreto, y luego permita al usuario ingresar números y le indique
#si son menores o mayores que el número a adivinar, hasta que el usuario ingrese el número
#correcto.
from random import randrange
def adivinarNumeroAleatorio():
""""""
numeroSecreto = randrange(start= 0, stop=100)
print('Adivine el número entre 0 y 100.')
while True:
entrada = input('Ingrese el candidato:')
if not entrada.isnumeric():
print('Por favor, ingrese un número válido.')
continue
else:
entrada = int(entrada)
if entrada == numeroSecreto:
break
if entrada > numeroSecreto:
print(f'El número {entrada} es mayor que el número a adivinar.')
continue
if entrada < numeroSecreto:
print(f'El número {entrada} es menor que el número a adivinar.')
continue
print('¡Genial, adivinaste! El número era ' + str(numeroSecreto))
adivinarNumeroAleatorio() |
e08f787de4a2297aa6884dbb013e92f612423cc5 | juancebarberis/algo1 | /practica/7-7.py | 877 | 4.21875 | 4 | #Ejercicio 7.7. Escribir una función que reciba una lista de tuplas (Apellido, Nombre, Ini-
#cial_segundo_nombre) y devuelva una lista de cadenas donde cada una contenga primero el
#nombre, luego la inicial con un punto, y luego el apellido.
data = [
('Viviana', 'Tupac', 'R'),
('Francisco', 'Tupac', 'M'),
('Raquel', 'Barquez', 'H'),
('Mocca', 'Tupac Barquez', 'D'),
('Lara', 'Tupac Barquez', 'P')
]
def tuplaACadena(lista):
"""
Esta función recibe una lista de tuplas con (Nombre, Apellido, Inicial segundo nombre)
y devuelve una lista con cadenas, donde cada una representa "Nombre Inicial. Apellido).
"""
resultante = []
for persona in lista:
cadenaIndividual = ""
cadenaIndividual += f"{persona[1]} {persona[2]}. {persona[0]}"
resultante.append(cadenaIndividual)
return resultante
print(tuplaACadena(data)) |
f9209f14d346695a6956bdc5180624ca6144b176 | juancebarberis/algo1 | /ej1/norma.py | 694 | 3.515625 | 4 | # NOMBRE_Y_APELLIDO = JUAN CELESTINO BARBERIS
# PADRÓN = 105147
# MATERIA = 7540 Algoritmos y Programación 1, curso Essaya
# Ejercicio 1 de entrega obligatoria
def norma(x, y, z):
"""Recibe un vector en R3 y devuelve su norma"""
return (x**2 + y**2 + z**2) ** 0.5
assert norma(-60, -60, -70) == 110.0
assert norma(26, 94, -17) == 99.0
assert norma(34, 18, -69) == 79.0
assert norma(-34, 63, -42) == 83.0
assert norma(0, 35, 84) == 91.0
assert norma(6, -7, 6) == 11.0
assert norma(94, -3, -42) == 103.0
assert norma(0, 42, -40) == 58.0
assert norma(48, -33, 24) == 63.0
assert norma(0, 0, 0) == 0
#Con z = 85, la igualdad de cumple. (Vale también para -85).
z = 85
assert norma(-70, 14, z) == 111.0 |
ce044a40bf93a96235b26cbd956382cbdb23c054 | stavanmehta/image-test | /image_helper/shortest_sequence.py | 458 | 3.75 | 4 |
def solution(N):
# write your code in Python 3.6
commands = list()
L = 0
R = 1
def getL():
return 2 * L - R
def getR():
return 2 * R - L
print L
if N < 0:
L = getL()
commands.append(L)
while L >= N:
L = getL()
if L + R - N == 0:
R = getR()
commands.append(L)
print commands
if __name__ == '__main__':
solution(-11) |
52bd4fcad10f017b48d79ab42a97e75fa9c7b7f4 | AshleySetter/LearningTravis | /UnecessaryMath.py | 139 | 3.71875 | 4 | def multiply(a, b):
"""
multiplies 2 python objects,
a and b and returns the result
"""
result = a*b
return result
|
7926f12749d7c6331283b2b5c7006ecddd3a88e0 | frollo/AdvancedProgramming | /Lab-7/es1.py | 783 | 3.609375 | 4 | import sys
from re import sub
def isMinor(word):
return (word == "the") or (word == "and") or (len(word) <= 2)
if __name__ == '__main__':
kwicindex = list()
counter = 0
titles = dict()
with open(sys.argv[1], "r") as file:
for line in file:
counter += 1
line = sub("[^a-zA-Z0-9\s]", " ", line)
line = sub("\s+", " ", line.strip())
kwicindex += [(x, counter) for x in line.lower().split() if not isMinor(x)]
titles[counter] = line
for (kwic, c ) in sorted(kwicindex, key = lambda x: x[0]):
title = titles[c]
position = title.lower().find(kwic)
print("{0:>5d}\t{1:>33s}{2:<40s}.".format(c, title[0:position if position < 33 else 33], title[position:40 + position:]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.