blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
be0b86721d4ad58b52d6bf23c81a13b07231d359
|
nkhuyu/python
|
/projectEuler/ProjectEuler1.py
| 261 | 3.828125 | 4 |
def mutliplesof3and5(n):
if(n%3==0 or n%5==0):
return 1
else:
return 0
def sum(n):
temp=0
for i in range(3,n):# 3:n-1
if(mutliplesof3and5(i)):
temp=temp+i
return temp
##
n=5
sum(n)
|
44b110dcaf1902cc607db2b51cf9dbad11b484d0
|
gnayuy/taocp
|
/python/linkedlists.py
| 5,885 | 4.09375 | 4 |
"""Implementation of the linked list and circular lists algorithms (chapter 2.2.3 and 2.2.4).
"""
import itertools
def topological_sort(relations):
"""Implement algorithm T of chapter 2.2.3.
In this implementation the linked lists are actually replaced by lists.
This does not depart significantly from the spirit of the original as we only use the `pop` and `append` methods.
:param relations: a list of pairs representing the relations between objects
:return: the list of objects in sorted order
:raises:
"""
# step T1 : initialize N, count and top
# as usual, we will keep the 1-indexing from Knuth and ignore the first value of the lists.
n = max([max(e) for e in relations])
N = n
count = [0]*(n+1)
top = []
# Can't use top = [[]]*(n+1) or we would modify all elements every time we push to one of them (shallow copy)
for i in range(n+1):
top.append([])
# step T2 / T3 : ingest relations
for (j,k) in relations:
count[k] += 1
top[j].append(k)
# step T4
qlink = []
for k in range(1, n+1):
if count[k] == 0:
qlink.append(k)
result = []
# loop on queue
while len(qlink) > 0:
# Step T5 + T7
f = qlink.pop()
result.append(f)
N -= 1
# T6 : erase relations
while len(top[f]) > 0:
suc = top[f].pop()
count[suc] -= 1
if count[suc] == 0:
qlink.append(suc)
# step T8
if N == 0:
return result
else:
raise ValueError("Loop in input relations")
def polynomial_addition(p, q):
"""Implement algorithm A of chapter 2.2.4.
This algorithm does not actually make use of circular lists, as each list is traversed only once.
Nonetheless, the implementation uses the `cycle` method from itertools lists to emulate a circular list (this frees
us from the temptation to test for the end of the list to terminate the algorithm, and prepares us for the
multiplication algorithm).
Each polynomial is described as a list of nested tuples of the form (coef, (a, b, c)).
The last element of each polynomial is always (0, (0, 0, -1)).
:param p: the first polynomial to add
:param q: the second polynomial to add
:return: the sum of p and q as a new list (note that this is different from the original algorithm
which adds to q in place.)
"""
result = []
circular_p = itertools.cycle(p)
circular_q = itertools.cycle(q)
# step A1. P and Q are used to denote the value of the current element of p and q
P = next(circular_p)
Q = next(circular_q)
special = (0, 0, -1)
def coef(X):
return X[0]
def abc(X):
return X[1]
# loop over p and q while the special node hasn't been reached (exit case of step A3)
while abc(P) != special or abc(Q) != special :
if abc(P) == abc(Q):
# step A3
c = coef(P) + coef(Q)
if c != 0:
result.append((c, abc(P)))
P = next(circular_p)
Q = next(circular_q)
while abc(P) < abc(Q):
# step A2
result.append(Q)
Q = next(circular_q)
while abc(P) > abc(Q):
# step A5
result.append(P)
P = next(circular_p)
return result + [Q]
def polynomial_multiplication(p, m):
"""Implement algorithm M of chapter 2.2.4.
As for addition, each polynomial is described as a list of nested tuples of the form (coef, (a, b, c)).
The last element of each polynomial is always (0, (0, 0, -1)).
:param p: first polynomial to multiply
:param m: second polynomial to multiply
:return: p*m as a new list (note that this is different from the original algorithm)
"""
special = (0, 0, -1)
result = []
circular_p = itertools.cycle(p)
def coef(X):
return X[0]
def abc(X):
return X[1]
def add_abc(X, Y):
a = abc(X)
b = abc(Y)
return tuple([e1 + e2 for (e1, e2) in zip(a, b)])
# loop for step M1/M2
for M in m:
if abc(M) == (0, 0, -1):
return result + [(0, special)]
# initialize P and Q.
P = next(circular_p)
# poor man's version of circular lists : take the previous iteration's result, use it as a new list and store
circular_q = iter(result.copy() + [(0, special)])
Q = next(circular_q)
result = []
# same algorithm as for addition with a few changes
while abc(P) != special or abc(Q) != special:
if add_abc(P, M) == abc(Q):
# step A3/M2. No need to check that abc(P) > -1 as this is always true in this branch
c = coef(P)*coef(M) + coef(Q)
if c != 0:
result.append((c, abc(Q)))
P = next(circular_p)
Q = next(circular_q)
if abc(P) > special:
while add_abc(P, M) < abc(Q):
# step A2. # The while condition is probably not enough to cover the M2 check
result.append(Q)
Q = next(circular_q)
else:
while abc(Q) > special:
result.append(Q)
Q = next(circular_q)
while abc(P) > special and add_abc(P, M) > abc(Q):
# step A5
X = (coef(P)*coef(M), add_abc(P, M))
result.append(X)
P = next(circular_p)
#result.append((0, special))
if __name__ == '__main__':
relations = [(9, 2), (3, 7), (7, 5), (5, 8), (8, 6), (4, 6), (1, 3), (7, 4), (9, 5), (2, 8)]
#print(topological_sort(relations))
zero = [(0, (0, 0, -1))]
p = [(1, (1, 0, 0)), (1, (0, 1, 0)), (1, (0, 0, 1))] + zero
print(polynomial_addition(p, zero))
|
9e160c2e16ffbaeff98c0d4b96f7f0094af5e86e
|
ivanshukaushik/OpenCV_Projects
|
/drawing_functions_in_python.py
| 685 | 3.609375 | 4 |
import numpy as np
import cv2
img = cv2.imread('lena.jpg', 1)
# img = np.zeros([512, 512, 3], np.uint8) # To make the entire image black
img = cv2.line(img, (0, 0), (255, 255), (255, 0, 0), 5) # BGR
img = cv2.arrowedLine(img, (255, 255), (400, 400), (255, 0, 0), 5) # Arrowed Line
img = cv2.rectangle(img, (50, 50), (200, 200), (100, 100, 100), 5) # Draw Rectangle, Give -1 for filled rectangle
img = cv2.circle(img, (200, 200), 20, (120, 120, 120), 5) # Draw a circle
font = cv2.FONT_HERSHEY_COMPLEX
img = cv2.putText(img, 'Hello world', (10, 500), font, 2, (255, 255, 255), 5, cv2.LINE_AA)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
0321662cfde748244a93de8a0b14f1763b7bf261
|
XaserAcheron/damnums
|
/damfont.py
| 1,070 | 3.796875 | 4 |
import sys
MAX_DIGITS = 5
# [TODO] document this silly thing:
def genfonts(prefix, width, height):
yoffset = height - 2
for charindex in range(10):
char = chr(65 + charindex);
for numdigits in range(2, MAX_DIGITS+1):
spritewidth = width * numdigits
xoffset = int(spritewidth / 2)
for digit in range(1, numdigits+1):
patchwidth = spritewidth - (width * digit)
print ('Sprite "{}{}{}{}0", {}, {} {{ Offset {}, {} Patch "{}11{}0", {}, 0 }}'.format(
prefix
, numdigits
, digit
, char
, spritewidth
, height
, xoffset
, yoffset
, prefix
, char
, patchwidth
))
print ('')
if __name__ == "__main__":
if len(sys.argv) > 3:
try:
prefix = sys.argv[1]
width = int(sys.argv[2])
height = int(sys.argv[3])
if len(prefix) == 2:
genfonts(prefix, width, height)
else:
print ("error: [prefix] must be exactly two characters")
except ValueError:
print ("error: [width] and [height] must be integers")
else:
print ("usage: python damfont.py [prefix] [width] [height]")
|
30a67482cc0693be0074d22cc8672e1b2debf5dc
|
stasvf2278/Rename_Files
|
/Renames_Files.py
| 783 | 3.609375 | 4 |
import os, shutil
def main():
print('Enter input directory path') ## Enter first folder file path here
folder1 = input()
print('Enter New File Prefix')
prefix = input()
print('Enter output directory path') ## Enter second folder file path here
folder2 = input()
os.chdir(folder1)
i = 34
for root, dirs, files in os.walk(folder1):
for file in files:
if not os.path.exists(folder2):
os.makedirs(folder2)
shutil.copy(file, str(folder2+'\\'+prefix+'_'+str(i)+os.path.splitext(file)[1]))
print(folder2+'\\'+prefix+'_'+str(i)+os.path.splitext(file)[1] + ' - Success')
i = i + 1
name = 'main'
if name == "main":
main()
|
c579b12922eb92b1e4cc4f1b28c6c183923b6150
|
uuind/Average_Atomic_Mass-Calculator
|
/Calculator.py
| 359 | 4.03125 | 4 |
def Average_Atomic_Mass():
isotopes = input("How many isotopes?")
average = 0
for x in range(1,int(isotopes) + 1):
mass = input("What is the isotope %s's mass in amu?" % x)
percent = input("How abundant is it in %?")
average += (float(mass)*(float(percent)/100))
print("%s amu" %average)
Average_Atomic_Mass()
|
98b9c79b89cca09f9159031ed04c1a19e71eecea
|
andy12290/Python-Essential-Training--1
|
/Exercise Files/11 Functions/generator.py
| 452 | 3.53125 | 4 |
#!/usr/bin/python3
# generator.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
print("This is the functions.py file.")
for i in inclusive_range(0,25,1):
print(i, end = ' ')
def inclusive_range (start,stop,step):
i = start
while(i < stop):
yield i
i += step
if __name__ == "__main__":
main()
|
93640b1d7b6e00f7a02321e8868723ba2315fb55
|
Tim810306/junyi_test
|
/1.py
| 254 | 3.890625 | 4 |
#第一題a用python:
def reverse(s):
return s[::-1]
#第一題b用python:
def reverse5(s):
s1 = ''
length = len(s) - 1
while length >= 0:
s1 = s1 + s[length]
length = length - 1 #還沒完成順序調整
return s1
|
4f619614442506f1567eb9ecc0de6c989f0c2c21
|
ashburnere/data-science-with-python
|
/python-for-data-science/1-2-Strings.py
| 2,344 | 4.28125 | 4 |
'''Table of Contents
What are Strings?
Indexing
Negative Indexing
Slicing
Stride
Concatenate Strings
Escape Sequences
String Operations
'''
# Use quotation marks for defining string
"Michael Jackson"
# Use single quotation marks for defining string
'Michael Jackson'
# Digitals and spaces in string
'1 2 3 4 5 6 '
# Special characters in string
'@#2_#]&*^%$'
# Assign string to variable
name = "Michael Jackson"
print(name, "length:", len(name))
# Print the first element in the string --> M
print(name[0])
# Print the last element in the string --> n
print(name[len(name)-1])
# Print the element on index 6 in the string --> l
print(name[6])
# Print the element on the 13th index in the string --> o
print(name[13])
# Print the last element in the string by using negativ indexing --> n
print(name[-1])
# Print the first element in the string by using negativ indexing --> M
print(name[-len(name)])
# Take the slice on variable name with only index 0 to index 3 --> Mich
print(name[0:4])
# Take the slice on variable name with only index 8 to index 11 --> Jack
print(name[8:12])
# Stride: Get every second element. The elments on index 0, 2, 4 ...
print(name[::2])
# Stride: Get every second element in the range from index 0 to index 4 --> Mca
print(name[0:5:2])
# Concatenate two strings
statement = name + " is the best"
print(statement)
# Print the string for 3 times
print(3*statement)
# New line escape sequence
print(" Michael Jackson \n is the best" )
# Tab escape sequence
print(" Michael Jackson \t is the best" )
# Include back slash in string
print(" Michael Jackson \\ is the best" )
# r will tell python that string will be display as raw string
print(r" Michael Jackson \ is the best" )
'''
String operations
'''
# Convert all the characters in string to upper case
A = "Thriller is the sixth studio album"
print("before upper:", A)
B = A.upper()
print("After upper:", B)
# Replace the old substring with the new target substring is the segment has been found in the string
A = "Michael Jackson is the best"
B = A.replace('Michael', 'Janet')
# Find the substring in the string. Only the index of the first elment of substring in string will be the output
name = "Michael Jackson" # --> 5
print(name.find('el'))
# If cannot find the substring in the string -> result is -1
print(name.find('Jasdfasdasdf'))
|
d86edccc25b0e5e6aebddb9f876afd3219c58a65
|
ashburnere/data-science-with-python
|
/python-for-data-science/4-3-Loading_Data_and_Viewing_Data_with_Pandas.py
| 2,038 | 4.25 | 4 |
'''Table of Contents
About the Dataset
Viewing Data and Accessing Data with pandas
'''
'''About the Dataset
The table has one row for each album and several columns
artist - Name of the artist
album - Name of the album
released_year - Year the album was released
length_min_sec - Length of the album (hours,minutes,seconds)
genre - Genre of the album
music_recording_sales_millions - Music recording sales (millions in USD) on SONG://DATABASE
claimed_sales_millions - Album's claimed sales (millions in USD) on SONG://DATABASE
date_released - Date on which the album was released
soundtrack - Indicates if the album is the movie soundtrack (Y) or (N)
rating_of_friends - Indicates the rating from your friends from 1 to 10
'''
import pandas as pd
# read from file
csv_path='D:/WORKSPACES/data-science-with-python/resources/data/top_selling_albums.csv'
# read from url
#csv_path='https://ibm.box.com/shared/static/keo2qz0bvh4iu6gf5qjq4vdrkt67bvvb.csv'
df = pd.read_csv(csv_path)
# We can use the method head() to examine the first five rows of a dataframe:
print("top 5 rows\n", df.head())
#We use the path of the excel file and the function read_excel. The result is a data frame as before:
# xlsx_path='https://ibm.box.com/shared/static/mzd4exo31la6m7neva2w45dstxfg5s86.xlsx'
# df = pd.read_excel(xlsx_path)
#df.head()
# We can access the column "Length" and assign it a new dataframe 'x':
x=df[['Length']]
print(x)
'''
Viewing Data and Accessing Data
'''
# You can also assign the value to a series, you can think of a Pandas series as a 1-D dataframe. Just use one bracket:
x=df['Length']
print(type(x))
# You can also assign different columns, for example, we can assign the column 'Artist':
x=df[['Artist']]
print(type(x))
y=df[['Artist','Length','Genre']]
print(type(y))
# print value of first row first column
print(df.iloc[0,0]) # --> Michael Jackson
print(df.loc[0,'Artist']) # --> Michael Jackson
# slicing
print(df.iloc[0:2, 0:3])
print(df.loc[0:2, 'Artist':'Released'])
|
7e13a68d223d69c45253189c3de073873d14ae04
|
zlzlzl002/Python
|
/Hello/test/2월20일DataType.py
| 723 | 3.796875 | 4 |
#-*- coding:utf-8 -*-
# Dict type
mem1={"num":1,"name":"gura","addr":"hong"}
# 삭제하기
del mem1["num"]
# 수정하기
mem1["num"]=2
# tuple type 수정/삭제 불가 list type 속도 빠름
a=(1,2,3,4)
# 여러값 넣기
a,b=10,20
# 1개 생성할때는 , 를 붙여 줘야한다
a=(1,)
# 두변수 상호 교환
isMan="guzn"
isGirl="sang"
isMan, isGirl=isGirl, isMan
print "isMan:",isMan, "isGirl:",isGirl
# list type
int1=[1,2,3,4,5]
# 한개방 참조하기
a=int1[0]
# 삭제하기
del int1[1]
# 추가하기
int1.append(6)
# 정렬
# int1.sort() 오름차순
int1.sort(reverse=True)
# 배열의 방의 갯수
print "len(int1) 갯수:", len(int1)
|
fff0dfba6e768aff3d24c520512ea80566372ff4
|
anucoder/Python-Codes
|
/01_numbers.py
| 203 | 4.09375 | 4 |
#using paranthesis to prioritise
print((2*9)+(10*5))
#reassignment
#dynamic assignment---> no need to declare the type.
a = 5
print(a)
a = a*5
print(a)
#snake casing
two_dogs = 2 #2_dogs is invalid
|
29383e08c12d57b53c61ae628026cb065957f9b7
|
anucoder/Python-Codes
|
/04_dictionaries.py
| 513 | 4.34375 | 4 |
my_stuff = {"key1" : "value1", "key2" : "value2"}
print(my_stuff["key2"])
print(my_stuff) #maintains no order
#multiple datatype with nested dictionaries and lists
my_dict = {"key1" : 123, "key2" : "value2", "key3" : {'123' : [1,2,"grabme"]}}
print(my_dict["key3"]['123'][2]) #accessing grabme
print((my_dict["key3"]['123'][2]).upper())
#reassigning dictionaries
my_diet = {'bfast' : "milk" , "lunch" : "oats"}
my_diet['lunch'] = 'pizza'
print(my_diet)
#appending
my_diet["dinner"] = "salad"
print(my_diet)
|
fee9d9373e1e0f209244e0a6913555313c8bd7ef
|
chiranjibKonwar/intron_dataset
|
/CORRECT_tetra_frequency_calculator_v2.py
| 1,979 | 3.640625 | 4 |
from optparse import OptionParser
import sys, re
from itertools import product
usage= sys.argv[0] + """ -f FASTA_intron_sequence_file"""
parser = None
def createParser():
global parser
epilog = """
This code takes input a FASTA intron sequence and computes overall tetranucleotide frequency for the input intron sequences"""
epilog = re.sub(r'[ \t\f\v]+',' ', epilog)
parser = OptionParser(usage=usage, epilog=epilog)
parser.add_option("-f", "--input_file_intron_sequences", dest="input_file",
help='the input intron sequence fasta file [REQUIRED]')
def main(argv, errorlogger = None, runstatslogger = None):
global parser
(opts, args) = parser.parse_args(argv)
filename=opts.input_file
fh=open(filename,'r')
FASTA=fh.readlines()
count_dict = {}
count =1
for possible_word in product('ATCG', repeat=4):
count_dict["".join(possible_word)] = 0
count_sequences=0
for line in FASTA:
if line.startswith('>'):
count_sequences+=1
else:
line = line.strip()
while len(line)>=4:
word=line[0:4]
if not word in count_dict:
count_dict[word]=count
else:
count_dict[word]+= 1
line=line[1:]
print "total number of sequences = %d" %(count_sequences)
#for key, value in sorted(count_dict.iteritems(), key=lambda (k,v): (v,k)):
#print "%s: %s" % (key, value)
top_scoring_tetra = sorted(count_dict, key=lambda key: count_dict[key], reverse=True)[:16]
print top_scoring_tetra
count_sequences=0
count_sequence_presence=0
dict_fraction = {}
for tetra in top_scoring_tetra:
dict_fraction[tetra]=count_sequence_presence
for sequence in FASTA:
if sequence.startswith('>'):
pass
else:
sequence=sequence.strip()
if tetra in sequence:
dict_fraction[tetra]+=1
for key, value in dict_fraction.items():
print "%s occurs in %s number of sequences" %(key, value)
if __name__=="__main__":
createParser()
main(sys.argv[1:])
|
a33d60ed9f9f9b024cf5304550812e7df316d230
|
BurntSushi/qcsv
|
/qcsv.py
| 15,785 | 3.609375 | 4 |
"""
A small API to read and analyze CSV files by inferring types for
each column of data.
Currently, only int, float and string types are supported.
from collections import namedtuple
"""
from __future__ import absolute_import, division, print_function
from collections import namedtuple
import csv
import numpy as np
__pdoc__ = {}
Table = namedtuple('Table', ['types', 'names', 'rows'])
__pdoc__['Table.types'] = '''
Contains inferred type information for each column in the table
as a dictionary mapping type name to a Python type constructor.
When a type cannot be inferred, it will have type `None`.
'''
__pdoc__['Table.names'] = '''
A list of column names from the header row of the source data.
'''
__pdoc__['Table.rows'] = '''
A list of rows, where each row is a list of data. Each datum
is guaranteed to have type `float`, `int`, `str` or will be the
`None` value.
'''
Column = namedtuple('Column', ['type', 'name', 'cells'])
__pdoc__['Column.type'] = '''
The type of this column as a Python type constructor, or `None`
if the type could not be inferred.
'''
__pdoc__['Column.name'] = '''
The name of this column.
'''
__pdoc__['Column.cells'] = '''
A list of list of all data in this column. Each datum is guaranteed to
have type `float`, `int`, `str` or will be the `None` value.
'''
try:
text_type = basestring
except NameError:
text_type = str
def read(fname, delimiter=',', skip_header=False):
"""
`read` loads cell data, column headers and type information
for each column given a file path to a CSV formatted file. A
`qcsv.Table` namedtuple is returned with fields `qcsv.Table.types`,
`qcsv.Table.names` and `qcsv.Table.rows`.
All cells have left and right whitespace trimmed.
All rows **must** be the same length.
`delimiter` is the string the separates each field in a row.
If `skip_header` is set, then no column headers are read, and
column names are set to their corresponding indices (as strings).
"""
names, rows = _data(fname, delimiter, skip_header)
types = _column_types(names, rows)
return cast(Table(types=types, names=names, rows=rows))
def _data(fname, delimiter=',', skip_header=False):
"""
`_data` loads cell data and column headers, and returns the names
and rows.
All cells have left and right whitespace trimmed.
All rows MUST be the same length.
`delimiter` and `skip_header` are described in `qcsv.read`.
"""
names = []
rows = []
reader = csv.reader(open(fname), delimiter=delimiter)
if not skip_header:
names = list(map(str.strip, next(reader)))
for i, row in enumerate(reader):
# If we haven't discovered names from column headers, then name the
# columns "0", "1", ..., "n-1" where "n" is the number of columns in
# the first row.
if len(names) == 0:
names = list(map(str, range(0, len(row))))
assert len(row) == len(names), \
'The length of row %d is %d, but others rows have length %d' \
% (i, len(row), len(names))
rows.append(list(map(str.strip, row)))
return names, rows
def _column_types(names, rows):
"""
`_column_types` infers type information from the columns in
`rows`. Types are stored as either a Python type constructor (str,
int or float) or as a `None` value. A dictionary of column names to
types is returned.
A column has type `None` if and only if all cells in the column are
empty. (Cells are empty if the length of its value is zero after
left and right whitespace has been trimmed.)
A column has type `float` if and only if all cells in the column
are empty, integers or floats AND at least one value is a float.
A column has type `int` if and only if all cells in the column are
empty or integers AND at least one value is an int.
A column has type `str` in any other case.
"""
types = dict([(name, None) for name in names])
for c in range(len(names)):
# prev_typ is what we believe the type of this column to be up
# until this point.
prev_typ = None
# next_typ is the type of the current cell only. It is compared
# with prev_typ to determine the type of the overall column as
# per the conditions specified in this function's documentation.
next_typ = None
for row in rows:
col = row[c]
# A missing value always has type None.
if len(col) == 0:
next_typ = None
# No need to inspect the type if we've already committed to str.
# (We bail out because it's expensive to inspect types like this.)
elif prev_typ is not str:
# The trick here is to attempt type casting from a stirng to
# an int or a string to a float, and if Python doesn't like it,
# we try something else.
try:
# We try int first, since any integer can be successfully
# converted to a float, but not all floats can converted
# to integers.
int(col)
next_typ = int
except ValueError:
try:
# If we can't convert to float, then we must scale back
# to a string.
float(col)
next_typ = float
except ValueError:
next_typ = str
# If a column contains a string, the column type is always a
# string.
if prev_typ is str or next_typ is str:
prev_typ = str
# A column with floats and ints has type float.
elif next_typ is float and prev_typ is int:
prev_typ = float
# A column with missing values and X has type X.
elif prev_typ is None and next_typ is not None:
prev_typ = next_typ
types[names[c]] = prev_typ
return types
def map_names(table, f):
"""
`map_names` executes `f` on every column header in `table`, with
three arguments, in order: column type, column index, column
name. The result of the function is placed in the corresponding
header location.
A new `qcsv.Table` is returned with the new column names.
"""
new_names = []
for i, name in enumerate(table.names):
new_names.append(f(table.types[name], i, name))
return table._replace(names=new_names)
def map_data(table, f):
"""
`map_data` executes `f` on every cell in `table` with five
arguments, in order: column type, column name, row index, column
index, contents. The result of the function is placed in the
corresponding cell location.
A new `qcsv.Table` is returned with the converted values.
"""
new_rows = [None] * len(table.rows)
for r, row in enumerate(table.rows):
new_row = [None] * len(row)
for c, col in enumerate(row):
name = table.names[c]
typ = table.types[name]
new_row[c] = f(typ, name, r, c, col)
new_rows[r] = new_row
return table._replace(rows=new_rows)
def cast(table):
"""
`cast` type casts all of the values in `table` to their
corresponding types in `qcsv.Table.types`.
The only special case here is missing values or NULL columns. If a
value is missing or a column has type NULL (i.e., all values are
missing), then the value is replaced with `None`.
N.B. cast is idempotent. i.e., `cast(x) = cast(cast(x))`.
"""
def f(typ, name, r, c, cell):
if (isinstance(cell, text_type) and len(cell) == 0) \
or typ is None or cell is None:
return None
return typ(cell)
return map_data(table, f)
def convert_missing_cells(table, dstr="", dint=0, dfloat=0.0):
"""
`convert_missing_cells` changes the values of all NULL cells to the
values specified by `dstr`, `dint` and `dfloat`. For example, all
NULL cells in columns with type `str` will be replaced with the
value given to `dstr`.
"""
def f(typ, name, r, c, cell):
if cell is None and typ is not None:
if typ == str:
return dstr
elif typ == int:
return dint
elif typ == float:
return dfloat
else:
assert False, "Unknown type: %s" % typ
return cell
return map_data(table, f)
def convert_columns(table, **kwargs):
"""
`convert_columns` executes converter functions on specific columns,
where the parameter names for `kwargs` are the column names, and
the parameter values are functions of one parameter that return a
single value.
For example
convert_columns(names, rows, colname=lambda s: s.lower())
would convert all values in the column with name `colname` to
lowercase.
"""
def f(typ, name, r, c, cell):
if name in kwargs:
return kwargs[name](cell)
return cell
return map_data(table, f)
def convert_types(table, fstr=None, fint=None, ffloat=None):
"""
`convert_types` works just like `qcsv.convert_columns`, but on
types instead of specific columns.
"""
def f(typ, name, r, c, cell):
if typ == str and fstr is not None:
return fstr(cell)
elif typ == int and fint is not None:
return fint(cell)
elif typ == float and ffloat is not None:
return ffloat(cell)
return cell
return map_data(table, f)
def column(table, colname):
"""
`column` returns a named tuple `qcsv.Column` of the column in
`table` with name `colname`.
"""
colcells = []
colname = colname.lower()
colindex = -1
for i, name in enumerate(table.names):
if name.lower() == colname.lower():
colindex = i
break
assert colindex > -1, 'Column name %s does not exist' % colname
for row in table.rows:
for i, col in enumerate(row):
if i == colindex:
colcells.append(col)
return Column(type=table.types[table.names[colindex]],
name=table.names[colindex],
cells=np.array(colcells))
def columns(table):
"""
`columns` returns a list of all columns in the data set, where each
column has type `qcsv.Column`.
"""
colcells = []
for _ in table.names:
colcells.append([])
for row in table.rows:
for i, col in enumerate(row):
colcells[i].append(col)
cols = []
for i, name in enumerate(table.names):
col = Column(type=table.types[name],
name=name,
cells=np.array(colcells[i]))
cols.append(col)
return cols
def frequencies(column):
"""
`frequencies` returns a dictionary where the keys are unique values
in the column, and the values correspond to the frequency of each
value in the column.
"""
ukeys = np.unique(column.cells)
bins = np.searchsorted(ukeys, column.cells)
return dict(zip(ukeys, np.bincount(bins)))
def type_str(typ):
"""
`type_str` returns a string representation of a column type.
"""
if typ is None:
return "None"
elif typ is float:
return "float"
elif typ is int:
return "int"
elif typ is str:
return "str"
return "Unknown"
def cell_str(cell_contents):
"""
`cell_str` is a convenience function for converting cell contents
to a string when there are still NULL values.
N.B. If you choose to work with data while keeping NULL values, you
will likely need to write more functions similar to this one.
"""
if cell_contents is None:
return "NULL"
return str(cell_contents)
def print_data_table(table):
"""
`print_data_table` is a convenience function for pretty-printing
the data in tabular format, including header names and type
annotations.
"""
padding = 2
headers = ['%s (%s)' % (n, type_str(table.types[n])) for n in table.names]
maxlens = list(map(len, headers))
for row in table.rows:
for i, col in enumerate(row):
maxlens[i] = max(maxlens[i], len(cell_str(col)))
def padded_cell(i, s):
spaces = maxlens[i] - len(cell_str(s)) + padding
return '%s%s' % (cell_str(s), ' ' * spaces)
line = ""
for i, name in enumerate(headers):
line += padded_cell(i, name)
print(line)
print('-' * (sum(map(len, headers)) + len(headers) * padding))
for row in table.rows:
line = ""
for i, col in enumerate(row):
line += padded_cell(i, cell_str(col))
print(line)
if __name__ == '__main__':
# File name.
f = "sample.csv"
table = read(f)
# Print the table of raw data.
print("# Raw data.")
print_data_table(table)
print('\n')
# Print the table after converting missing values from NULL to concrete
# values. The benefit here is that NULL values are inherently incomputable.
# Whenever they get thrown into a computation on the data, they will always
# provoke a runtime error. This is a Good Thing, because missing values
# SHOULD be given explicit treatment. Inserting values into missing cells
# is making an *assumption* about the data, and should never be implied.
#
# Thus, `convert_missing_cells` is an EXPLICIT way of throwing away NULL
# cells. If you view the output from the previous table, and the output of
# the next table, you'll notice that NULL values have been replaced.
# (String columns get empty strings, integer columns get 0 and float
# columns get 0.0.)
#
# If you want to change what the missing values are replaced with, you can
# use the function's optional parameters:
#
# rows = convert_missing_cells(types, names, rows,
# dstr="-9.99", dfloat=-9.99, dint=-9)
table = convert_missing_cells(table)
print("# Convert missing cells to arbitrary values")
print_data_table(table)
print('\n')
# Now that all of the NULL cells have been removed, we are free to run data
# sanitization functions on the columns of data without worrying about
# seeing those nasty NULL values. For instance, we might want to make all
# strings in the 'string1' column be lowercase. We need only to pass a
# function as an argument, where the function we pass takes a single
# argument (the cell contents) and returns the new cell contents. In this
# case, we tell every cell in the `string1` column to be converted using
# the `str.lower` function.
table = convert_columns(table, string1=str.lower)
print("# Sanitize just one column of data")
print_data_table(table)
print('\n')
# The aforementioned function has limited use, since you typically
# want to be more dynamic than having to give names of columns. Thus, the
# `convert_types` function allows you to convert cells based on their
# *type*. That is, instead of making only a selection of columns lowercase,
# we can specify that *all* string columns should be lowercase.
table = convert_types(table, fstr=str.lower)
print("# Sanitize all cells that have type string")
print_data_table(table)
print('\n')
# Finally, you can traverse your data set by columns like so:
for col in columns(table):
print('(%s, %s) [%s]'
% (col.name, col.type, ', '.join(map(cell_str, col.cells))))
print('\n')
# Or pick out one column in particular:
print(column(table, "mixed"))
|
733046f20c403d8ad93489e1a29f4faf89939851
|
swest06/Hangman
|
/hang.py
| 2,246 | 3.953125 | 4 |
import random
import time
from os import system, name
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux
else:
_ = system('clear')
def game():
words = ["banana", "grape", "orange", "mango", "cherry", "apple", "pear", "peach"]
strikes = int(7)
play = True
while play:
secret = random.choice(words)
g_guess = []
b_guess = []
while len(b_guess) < strikes and len(g_guess) != len(list(secret)):
clear()
print("A random fruit has been chosen.\n"
"Try to guess what it is. \n")
# Prints correct letters and empty spaces
for i in secret:
if i in g_guess:
print(i, end=" ")
else:
print("_", end=" ")
# Get guess
print("strikes: " + str(len(b_guess)) + "/7")
guess = input("Guess a letter: ").lower()
if len(guess) != 1:
print("you can only enter 1 letter")
time.sleep(3)
continue
elif guess in b_guess or guess in g_guess:
print("You've already guessed that letter")
time.sleep(3)
continue
elif not guess.isalpha():
print("You can only guess letters")
time.sleep(3)
continue
# Compare good guesses with word
if guess in secret:
[g_guess.append(guess) for i in secret if i == guess]
if len(g_guess) == len(list(secret)):
print("{}\n"
"You win.".format(secret))
play = False
break
else:
b_guess.append(guess)
else:
print("You lose. The word was {}.".format(secret))
play = False
def main():
play = True
while play:
game()
replay = input("Play again? y/n: ")
if replay[0].lower() == "y":
continue
else:
play = False
print("Goodbye.")
time.sleep(3)
if __name__ == "__main__":
main()
|
2c2f3c5f98ddf31330b03ae761ba95ec1f391778
|
uuind/2018-cc
|
/GCC3.py
| 1,136 | 3.59375 | 4 |
def beg():
b = int(input('how many integers?\n'))
if b == 0:
print("sorry not allowed")
quit()
a = [int(x) for x in input('Please enter the values now\n').split(' ')]
if len(a) == b:
return a
else:
print('incorrect amount of values within sequence')
def groupby(lst):
temp = list()
pos = True
for x in lst:
if x > -1:
if pos == False:
yield temp
pos = True
temp = list()
temp.append(x)
else:
if pos == True:
yield temp
pos = False
temp = list()
temp.append(x)
yield temp
bacon = beg() #Humor is important
b = list(groupby(bacon))
max_seq = [str(x) for x in max(b, key=lambda x: len(x))]
def search_for_pos(max_seq,lst):
for x in max_seq:
for n,y in enumerate(lst):
if int(y)==int(x):
yield str(n)
print('maximal sequence: ' + ' '.join(max_seq),'at positions ' + ', '.join(list(search_for_pos(max_seq,bacon))))
|
f39a2be4092c5f94f3195f0abffa5b11adb45b33
|
kbenedetti9/Mision-TIC-Python
|
/Retos diarios/Reto día 8/reto_dia8.py
| 890 | 3.546875 | 4 |
def reto1(palabra):
cantidad = len(palabra)
i = 0
correcto = 0
num = cantidad
while i<cantidad:
num-=1
if palabra[num] == palabra[i]:
correcto+=1
i+=1
if correcto == cantidad:
result = True
else:
result = False
print(result) # Modifica el codigo para imprimir cada valor
reto1("ojo")
def reto2(numero):
num = str(numero)
cantidad = len(num)
while cantidad != 1:
i = 0
suma = 0
while i<cantidad:
suma += int(num[i])
i+=1
cantidad = len(str(suma))
num = str(suma)
return suma
reto2(347)
def reto3(numero):
i = 1
contador = 0
if numero <= 1:
result = "Error en el numero"
else:
while i<=numero:
if numero % i == 0:
contador+=1
i+=1
if contador == 2:
result = True
else:
result = False
return result
reto3(89)
|
eff50cbd0f7ee774a1d90db6832560189dbdd1fb
|
amaurirg/Tarefas-Macantes
|
/testes/fizzbuzz.py
| 1,127 | 3.765625 | 4 |
from sys import _getframe
import unittest
multiple_of = lambda base, num: num % base == 0
def robot(pos):
say = str(pos)
# mude essa linha de and para or para gerar um erro e ver a saída
if multiple_of(3, pos) and multiple_of(5, pos):
say = 'fizzbuzz'
elif multiple_of(3, pos):
say = 'fizz'
elif multiple_of(5, pos):
say = 'buzz'
return say
"""
def assert_equal(result, expected):
msg = 'Fail: Line {} got {} expecting {}'
if not result == expected:
current = _getframe()
caller = current.f_back
line_no = caller.f_lineno
print(msg.format(line_no, result, expected))
if __name__=='__main__':
assert_equal(robot(1), '1')
assert_equal(robot(2), '2')
assert_equal(robot(4), '4')
assert_equal(robot(3), 'fizz')
assert_equal(robot(6), 'fizz')
assert_equal(robot(9), 'fizz')
assert_equal(robot(5), 'buzz')
assert_equal(robot(10), 'buzz')
assert_equal(robot(20), 'buzz')
assert_equal(robot(15), 'fizzbuzz')
assert_equal(robot(30), 'fizzbuzz')
assert_equal(robot(45), 'fizzbuzz')
"""
|
e027f52eed46b3390499dabf1c19386dcd1101af
|
amaurirg/Tarefas-Macantes
|
/Graficos/scatter_squares.py
| 1,133 | 3.59375 | 4 |
import matplotlib.pyplot as plt
#plt.scatter(2, 4, s=200) # define um ponto específico x=2, y=4 e s=200 (tamanho do ponto)
# x_values = [1, 2, 3, 4, 5]
# y_values = [1, 4, 9, 16, 25]
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
# plt.scatter(x_values, y_values, c='red', edgecolor='none', s=40) # "edgecolor" tira o contorno preto
# # dos pontos e "c" indica a cor da linha.
# plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40) # c em formato RGB com valores de 0 a 1.
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40) # cmap para gradiente.
# Define o título do gráfico e nomeia os eixos
plt.title("Squares Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# Define o tamanho dos rótulos das marcações
# plt.tick_params(axis='both', which='major', labelsize=14)
# Define o intervalo para cada eixo
plt.axis([0, 1100, 0, 1100000])
plt.savefig('squares_plot.png', bbox_inches='tight') # salva o gráfico e tira os espaços em branco.
plt.show() # exibe o gráfico.
|
f340ae17dd37811fc51fb2405c68c71d4fb8acec
|
amaurirg/Tarefas-Macantes
|
/excel(openpyxl)/teste_atualiza.py
| 796 | 3.640625 | 4 |
PRICE_UPDATES = {}
resp = ''
while resp != 'n':
resp = input('\nAtualizar produto? (s para sim ou n para sair): ')
try:
if resp == 's':
produto = input('Digite o produto: ')
preco = input('Digite o valor: ')
# if ',' or '.' not in preco:
# preco = input('Digite um valor válido (ex.: 2,00): ')
if ',' in preco:
valor = preco.replace(',', '.')
PRICE_UPDATES[produto] = float(valor)
else:
PRICE_UPDATES[produto] = float(preco)
else:
print('Digite s para alterar um produto e valor ou n para sair')
except ValueError:
preco = input('Digite um valor válido (ex.: 2,00): ')
if not ValueError:
pass
else:
print('O valor desse produto não será alterado devido ao valor inválido informado.')
print(PRICE_UPDATES)
|
6345660779fa7e35d49ca37642ed793d0a40de4c
|
amaurirg/Tarefas-Macantes
|
/manipulando_arquivos/arquivos_HD/utilizando_pprint.py
| 1,307 | 3.953125 | 4 |
#! python3
#Utilizando o módulo pprint para salvar em um arquivo.py, gerando assim um módulo próprio chamado "myCats.
#Esse trecho comentado cria o módulo que não será necessário ser criado novamente.
'''
import pprint #importa o módulo para salvar de forma mais elegante.
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name':'Pooka', 'desc':'fluffy'}] #cria uma lista com os respectivos valores.
fileObj = open('myCats.py', 'w') #abre o arquivo do tipo texto simples em modo escrita.
fileObj.write('cats = ' + pprint.pformat(cats) + '\n') #salva a lista no arquivo.
fileObj.close() #fecha o arquivo.
'''
import myCats #importa o módulo criado anteriormente.
print(myCats.cats) #exibe a lista completa.
print(myCats.cats[0]) #exibe o índice 0 da lista.
print(myCats.cats[1]) #exibe o índice 1 da lista.
print(myCats.cats[0]['name']) #exibe o nome com índice 0 da lista.
print(myCats.cats[1]['name']) #exibe o nome com índice 1 da lista.
print(myCats.cats[0]['desc']) #exibe o desc com índice 0 da lista.
print(myCats.cats[1]['desc']) #exibe o desc com índice 1 da lista.
|
3fcc4107b7bc8d14674675813d66c6ced891fdb3
|
amaurirg/Tarefas-Macantes
|
/tempo/stopwatch.py
| 718 | 3.859375 | 4 |
#! python3
#Simples cronômetro.
import time
#Exibe as instruções do programa.
print('Pressione ENTER para começar. Depois, pressione ENTER para registrar o tempo no cronômetro. Pressione CTRL+C para sair.')
input()
print('Início da contagem de tempo.')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
print('Rodada %s: %s (%s) %s %s' %(lapNum, totalTime, lapTime, startTime, lastTime), end='')
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
#Trata a excessão de CTRL+C para evitar que sua mensagem de erro seja exibida.
print('\nFIM')
|
7b87c1451cf718b0094d101c26c5d1c82f41efe3
|
amaurirg/Tarefas-Macantes
|
/web_scraping/lucky.py
| 1,736 | 3.703125 | 4 |
#! python 3
#Abre vários resultados de pesquisa no Google.
import requests, sys, webbrowser, bs4 #importa o módulo requests para download da página.
#importa o módulo sys para ler a linha de comando.
#importa o módulo webbrowser para abrir o navegador.
#importa o módulo bs4 para busca mais precisa com BeautifulSoup.
print('Buscando...') #exibe uma mensagem enquanto faz download da página do Google.
res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:])) #faz a pesquisa de acordo com a linha de comando, sem o nome do programa [0]
res.raise_for_status() #verifica se ocorreu algum erro.
soup = bs4.BeautifulSoup(res.text, "html.parser") #Obtém os links dos principais resultados da pesquisa.
linkElems = soup.select('.r a') #seleciona os elementos <a> que estiverem na class="r". Através da inspeção de
#elementos é possível verificar que antes de <a> existe uma class="r".
numOpen = min(5, len(linkElems)) #verifica com a função min() qual valor é menor, ou seja, se encontrou 5 ou se
#o total foi menor que 5. Então armazena em "numOpen" a menor quantidade de
#buscas encontradas. A função max() faz o contrário, verifica qual é maior.
for i in range(numOpen): #faz um loop de acordo com o número armazenado em "numOpen", 5 ou menos.
webbrowser.open('http://google.com' + linkElems[i].get('href')) #abre uma aba do navegador para cada resultado.
#print(linkElems[0].getText()) #exibe somente o texto do elemento 0 sem as tags.
#print(linkElems)
#print(res.text)
#print(len(linkElems))
|
069e6443b63d7b1885a59bd2eaad877127b5cef9
|
amaurirg/Tarefas-Macantes
|
/Graficos/Matplotlib/colormap.py
| 696 | 3.828125 | 4 |
import matplotlib.pyplot as plt
# Valores de x e y
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
# Plota uma linha gradiente azul, sem contorno, e expessura s=40
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues,
edgecolor='none', s=40)
# Define o título do gráfico e nomeia os eixos
plt.title("Square Numbers", fontsize=14)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# Define o intervalo para cada eixo
plt.axis([0, 1100, 0, 1100000])
# Salva o gráfico em um arquivo
# bbox_inches='tight' remove espaços extras em branco podendo ser omitido
plt.savefig('squares_plot.png', bbox_inches='tight')
plt.show()
|
6bf4f21da8abe83fb9749888a2a488a231cdf9a4
|
AlveinTeng/CSC311FinalProject
|
/starter_code/part_a/knn.py
| 4,736 | 3.78125 | 4 |
from sklearn.impute import KNNImputer
from utils import *
import matplotlib.pyplot as plt
def knn_impute_by_user(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
student similarity. Return the accuracy on valid_data.
See https://scikit-learn.org/stable/modules/generated/sklearn.
impute.KNNImputer.html for details.
:param matrix: 2D sparse matrix
:param valid_data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param k: int
:return: float
"""
nbrs = KNNImputer(n_neighbors=k)
# We use NaN-Euclidean distance measure.
mat = nbrs.fit_transform(matrix)
acc = sparse_matrix_evaluate(valid_data, mat)
print("At k={}, Accuracy by student: {}".format(k, acc))
return acc
def knn_impute_by_item(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
question similarity. Return the accuracy on valid_data.
:param matrix: 2D sparse matrix
:param valid_data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param k: int
:return: float
"""
#####################################################################
# TODO: #
# Implement the function as described in the docstring. #
#####################################################################
nbrs = KNNImputer(n_neighbors=k)
# We use NaN-Euclidean distance measure.
mat = nbrs.fit_transform(matrix.transpose())
acc = sparse_matrix_evaluate_item(valid_data, mat)
print("At k={}, Accuracy by item: {}".format(k, acc))
#####################################################################
# END OF YOUR CODE #
#####################################################################
return acc
def sparse_matrix_evaluate_item(data, matrix, threshold=0.5):
""" Given the sparse matrix represent, return the accuracy of the prediction on data.
:param data: A dictionary {user_id: list, question_id: list, is_correct: list}
:param matrix: 2D matrix
:param threshold: float
:return: float
"""
total_prediction = 0
total_accurate = 0
for i in range(len(data["is_correct"])):
cur_user_id = data["user_id"][i]
cur_question_id = data["question_id"][i]
if matrix[cur_question_id, cur_user_id] >= threshold and data["is_correct"][i]:
total_accurate += 1
if matrix[cur_question_id, cur_user_id] < threshold and not data["is_correct"][i]:
total_accurate += 1
total_prediction += 1
return total_accurate / float(total_prediction)
def main():
sparse_matrix = load_train_sparse("../data").toarray()
val_data = load_valid_csv("../data")
test_data = load_public_test_csv("../data")
#####################################################################
# TODO: #
# Compute the validation accuracy for each k. Then pick k* with #
# the best performance and report the test accuracy with the #
# chosen k*. #
#####################################################################
k_value = [1, 6, 11, 16, 21, 26]
# Validation data
results_user = []
results_item = []
for k in k_value:
results_user.append(knn_impute_by_user(sparse_matrix, val_data, k))
results_item.append(knn_impute_by_item(sparse_matrix, val_data, k))
plt.plot(k_value, results_user, color="red", label='student')
plt.plot(k_value, results_item, color='blue', linestyle='--', label='item')
plt.xlabel('k value')
plt.ylabel('validation accuracy')
plt.title('validation accuracy vs k value')
plt.legend(loc='lower right')
plt.show()
# Test performance
user_based = []
item_based = []
for k in k_value:
user_based.append(knn_impute_by_user(sparse_matrix, test_data, k))
item_based.append(knn_impute_by_item(sparse_matrix, test_data, k))
plt.plot(k_value, user_based, color="red", label='student')
plt.plot(k_value, item_based, color='blue', linestyle='--', label='item')
plt.xlabel('k value')
plt.ylabel('Test accuracy')
plt.title('test accuracy vs k value')
plt.legend(loc='lower right')
plt.show()
#####################################################################
# END OF YOUR CODE #
#####################################################################
if __name__ == "__main__":
main()
|
9f67be3ea93dcb4ab9f1d84391cecbb293f408e8
|
Mkath1423/Projects
|
/Projects/Mini Adventure/databaseTools.py
| 4,245 | 4.0625 | 4 |
import sqlite_manager as db
def createNewDB(database, rooms):
'''
This function initializes a new database.
A new gameSave database will be created with the required tables. rooms number of
stock rooms then get inserted into the database. The database name also gets added to the
gameFilePaths.txt file.
Parameters
----------
database : str
This is the name of the database you want to create
rooms : int
this is the number of rooms you want in the new database
Returns
-------
None
'''
# add the new gameSave path to the gameFilePaths.txt file
gameFilePaths = open('GameFiles/gameFilePaths.txt', 'a')
gameFilePaths.write(f',{database}')
gameFilePaths.close()
# set what columns should be in the rooms table and what datatype they contain
rooms_columns = {
'room_name' : 'TEXT',
'room_description ': 'TEXT'
}
# create the rooms table
db.createTable(f'GameFiles/{database}', 'rooms', rooms_columns)
# set what columns should be in the connections table and what datatype they contain
connections_colums = {
'N':'INTEGER',
'E':'INTEGER',
'S':'INTEGER',
'W':'INTEGER'
}
# create the connections table
db.createTable(f'GameFiles/{database}', 'connections', connections_colums)
# insert rooms amount of stock rooms into the tables
for i in range(rooms):
createNewRoom(database)
def createNewRoom(database):
'''
This function inserts a new room in a database.
A new stock room gets made in the specified database. The values for the rooms are:
room_name = newRoomName
room_discripton = newRoomDescription
N = 0
E = 0
S = 0
W = 0
Parameters
----------
database : str
This is the name of the database you want to insert rooms into.
Returns
-------
None
'''
# insert a new row into the rooms table with stock values
db.insert(f'GameFiles/{database}', 'rooms', ['room_name', 'room_description '], [['"newRoomName"', '"newRoomDescription "']])
# insert a new row into the connections table with stock values
db.insert(f'GameFiles/{database}', 'connections', ['N', 'E', 'S', 'W'], [[0, 0, 0, 0]])
def getLevelInfo(database):
'''
This function gets and returns the names and ids of all the rooms in the database.
A dictionary gets created and returned which contains the room ids as key and to room names as values.
Parameters
----------
database : str
This is the name of the database you want to get information from.
Returns
-------
dict<int, str>
A dictionary of all the room ids and names in the database. The ids are keys and the names are values.
'''
levelInfo = {}
# query the database for the room name and id for every row
roomsData = db.select(f'GameFiles/{database}', 'rooms', ['id', 'room_name'], None)
# parse roomsData into a dictionary
for room in roomsData:
levelInfo[room[0]] = room[1]
# add the amount of rooms to dictionary
levelInfo['AmountOfRooms'] = len(levelInfo)
# return the dictionary
return levelInfo
def getRoomData(database, room):
'''
This function gets and returns the data stored for a given room.
The room name, room description and all 4 connections will be returned.
Parameters
----------
database : str
This is the name of the database you want to get information from.
room : int
This is the id of the room you want to get the data of.
Returns
-------
list<list<str>>
All the information for the given room.
Index 0 contains the room_name and the room_description .
Index 1 contains the 4 connections in order [North, East, South, West]
'''
# query the database for the room id name and descripton
room_data = db.select(f'GameFiles/{database}', 'rooms', ['id', 'room_name', 'room_description '], ('id', room))[0]
# query the database for the rooms it connects to
connections_data = db.select(f'GameFiles/{database}', 'connections', ['N', 'E', 'S', 'W'], ('id', room))[0]
# return the collected data
return (room_data, connections_data)
|
a016c597b8fc5f70e2ab5d861b756d347282289d
|
jourdy345/2016spring
|
/dataStructure/2016_03_08/fibonacci.py
| 686 | 4.125 | 4 |
def fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
# In python, the start of a statement is marked by a colon along with an indentation in the next line.
def fastFib(n):
a, b = 0, 1
for k in range(n):
a, b = b, a+b # the 'a' in the RHS is not the one in the RHS. Python distinguishes LHS from RHS and does not mix them up.
return a
# For n = 1, the slower version of fib function is actually faster than the faster one.
# In small values of n, the comparison between two functions is actually not revealing as much as we would expect it to be.
# Thus, we introduce a new concept O(n) ("Big oh"): asymptotic time complexity.
print(fastFib(45))
|
5b4440484b062a79c73b005f2016ad3cd7c49ebf
|
YDrall/laboratory
|
/python/lpthw/loops_and_list.py
| 398 | 3.84375 | 4 |
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1,'pennis',2,'dimes',3,'quarters']
def sperator():
print '-'*20
for number in the_count:
print number
sperator()
for fruit in fruits:
print fruit
sperator()
for i in change:
print i
elements = []
for i in range(0,6):
elements.append(i)
sperator()
for i in elements:
print i
|
951eb2846feac19190916771176ad0621ddf4987
|
YDrall/laboratory
|
/python/lpthw/matrices_testdoc.py
| 454 | 3.609375 | 4 |
def make_matrix(rows, column):
"""
>>> make_matrix(3,5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> make_matrix(4,2)
[[0, 0], [0, 0], [0, 0], [0, 0]]
>>> m = make_matrix(4,2)
>>> m[1][1] = 7
>>> m
[[0, 0], [0, 7], [0, 0], [0, 0]]
"""
matrix = []
for i in range(rows):
matrix += [[0]*column]
return matrix
if __name__ == "__main__":
import doctest
doctest.testmod()
|
be9b1b682cc8b1f6190fead9c3441ce72f512cf4
|
Nathan-Dunne/Twitter-Data-Sentiment-Analysis
|
/DataFrameDisplayFormat.py
| 2,605 | 4.34375 | 4 |
"""
Author: Nathan Dunne
Date last modified: 16/11/2018
Purpose: Create a data frame from a data set, format and sort said data frame and display
data frame as a table.
"""
import pandas # The pandas library is used to create, format and sort a data frame.
# BSD 3-Clause License
# Copyright (c) 2008-2012, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development
from tabulate import tabulate # The tabulate library is used to better display the pandas data frame as a table.
# MIT License Copyright (c) 2018 Sergey Astanin
class DataFrameDisplayFormat:
def __init__(self):
pass # There is nothing to initialise so pass is called here. The pass statement is a null operation.
@staticmethod # Method is static as it alters no values of the self object.
def convertDataSetToDataFrame(data_set):
"""
Convert a data set to a pandas data frame.
"""
data_frame = pandas.DataFrame(data_set) # Convert the data set (List of dictionaries) to a pandas data frame.
return data_frame
@staticmethod # Method is static as it alters no values of the self object.
def formatDataFrame(data_frame):
"""
Format and sort a data frame.
"""
data_frame = data_frame[['favorite_count', # Order and display only these three columns.
'retweet_count',
'text',
]]
print("\nSorting data by 'favorite_count', 'retweet_count', descending.")
# Sort the rows first by favorite count and then by retweet count in descending order.
data_frame = data_frame.sort_values(by=['favorite_count', 'retweet_count'], ascending=False)
return data_frame
@staticmethod # Method is static as it neither accesses nor alters any values or behaviour of the self object.
def displayDataFrame(data_frame, amount_of_rows, show_index):
"""
Display a data frame in table format using tabulate.
"""
# Print out an amount of rows from the data frame, possibly with showing the index, with the headers as the
# data frame headers using the table format of PostgreSQL.
# Tabulate can't display the word "Index" in the index column so it is printed out right before the table.
print("\nIndex")
print(tabulate(data_frame.head(amount_of_rows),
showindex=show_index,
headers=data_frame.columns,
tablefmt="psql"))
|
0d3797cc77e5934de5fae55da24a79d27154ec0f
|
cjp0116/ML
|
/multiple_linear.py
| 4,000 | 3.640625 | 4 |
# Importing the Libaries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""Out of the R&D Spends and Marketing spends, which yields better profit?
With the assumption that the location of the startup hold now significance.
A Caveat to Linear Regressions:
1. Linearity
2. Homoscedasticity
3. Multivariate normality
4. Independence of errors
5. Lack of multi-collinearity
multiple linear equation is.. {y = b0 + x1*b1(R&D) + b2*x2(Admin) + b3+x3(Marketing) + b4*D1 (state)}
as for the state variables, we need to create Dummy Variables
5 methods of building models:
1.) All-in - Throw in all the cases
i. Prior knowledge; OR
ii. You have to; OR
iii. Preparing for Backward Elimination.
2.) Backward Elimination (Stepwise Regression)
i. Select a significance level to stay in the model (e.g. SL(significance level) =0.05)
ii. Fit the full model with all possible predictors.
iii. Consider the predictor with the highest P-value. If P > Significance Level, go to step 4, otherwise go to FIN
ix. Remove the predictor.
X. Fit model without this variable*.
3.) Forward Selection (Stepwise Regression)
i. Select a significance level to enter the model (eg. SL = 0.05)
ii. Fit all simple regression models y + Xn. Select the one with the lowest P-value.
iii. Keep this variable and fit all possible models with one extra predictor added to the one(s) you already have.
Xi. Consider the predictor with the LOWEST P-value. If P < SL, go to STEP3, otherwise go to FIN.
4.) Bidirectional Elimination (Stepwise Regression)
i. Select a significance level to enter and to stay in the model e.g: SLENTER = 0.05, SLSTAY = 0.05
ii. Perform the next step of Forward Selection (new variables must have: P < SLENTER to enter)
iii. Perform ALL steps of Backward Elimination (old variables must have: P < SLSTAY to stay)
iX. No new variables can enter and no old variables can exit.
5.) All Possible Models
i. Select a criterion of goodness of fit (e.g. Akaike criterion).
ii. Construct all possible Regression Models (2**n)-1 total combinations.
iii. Select the one with best criterion.
"""
# Opening the csv to work with
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values # Dependant variables aka profits
y = dataset.iloc[:, 4].values # Independant variables aka: (R&D, Administration, Marketing, State)
# Encoding the state variable (categorical data)
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
labelencoder_y = LabelEncoder()
X[:,3] = labelencoder_y.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features= [3])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the Dummy Variable Trap
X = X[:, 1:]
# Splitting Test Data and Training Data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size= 0.8, test_size= 0.2, random_state= 0)
# Fitting the Mulitple Linear Regression into the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the Test Set Results
y_pred = regressor.predict(X_test)
print(y_pred)
## Building Optimal Model using Backwards Elimination ##
import statsmodels.formula.api as sm
X = np.append(arr = np.ones((50,1)).astype(int), values= X, axis= 1)
# Initialize the independant variable columns
X_opt = X[:, [0,1,2,3,4,5]]
# Fit the full model with possible predictors
regressor_OLS = sm.OLS(endog= y, exog= X_opt).fit()
print(regressor_OLS.summary())
# Remove the ones with the P value > 0.05
X_opt = X[:, [0,3,5]]
regressor_OLS = sm.OLS(endog= y, exog= X_opt).fit()
print(regressor_OLS.summary())
X_opt = X[:, [0,3]]
regressor_OLS = sm.OLS(endog = y, exog= X_opt).fit()
print(regressor_OLS.summary())
|
5fec285125210654cdc334d9d16bebf72c4be2c7
|
benjvdb9/RandNumGenerator
|
/test.py
| 267 | 3.515625 | 4 |
from time import time
times = []
for i in range(10):
times += [time()]
delta = []
old = ""
for elem in times:
print("Time:", elem)
if old == "":
res = "No delta"
else:
res = elem - old
print("Delta:", res)
old = elem
|
8eba1f38d3e13306076467af0694dc65f7d6ed7f
|
englernicolas/ADS
|
/python/aula3-extra.py
| 1,934 | 4.1875 | 4 |
def pesquisar(nome) :
if(nome in listaNome) :
posicao = listaNome.index(nome)
print("------------------------------")
print("Nome: ", listaNome[posicao], listaSobrenome[posicao])
print("Teefone: ",listaFone[posicao])
print("-------------------------")
else:
print("-------------------------")
print("Pessoa não encontrada")
print("-------------------------")
def excluir(nome):
if(nome in listaNome) :
posicao = listaNome.index(nome)
listaNome.pop(posicao)
listaSobrenome.pop(posicao)
listaFone.pop(posicao)
print("Exluido com sucesso!")
else:
print("-----------------------")
print("Pessoa não encontrada")
print("-----------------------")
def listar():
for item in range(0, len(listaNome)):
print("-----------------------")
print( "Nome: ", listaNome[item, listaSobrenome[item]])
print("-----------------------")
listaNome = []
listaSobrenome = []
listaFone = []
while True:
print(" 1 - Cadastrar")
print(" 2 - Pesquisar")
print(" 3 - Excluir")
print(" 4 - Listar todos")
op = int(input("Digide a opção desejada: "))
if(op == 1):
nome = input("Informe o Nome: ")
sobrenome = input("Informe o Sobrenome: ")
fone = input("Informe o Telefone: ")
listaNome.append(nome)
listaSobrenome.append(sobrenome)
listaFone.append(fone)
print("-----------------------")
print("Cadastrado com Sucesso!")
print("-----------------------")
else:
if(op == 2):
pesquisa = input("Informe o nome a pesquisar: ")
pesquisar(pesquisa)
else:
if(op == 3):
pesquisa = input("Informe o nome a excluir: ")
excluir(pesquisa)
else:
if(op == 4):
listar()
|
796e17d9375a3eb2b6fb36232d6beb7cf73adda3
|
lgdelacruz92/LeetCode-Challenges
|
/path-in-grid/path-in-grid.py
| 1,334 | 3.5 | 4 |
def optimal_path(grid):
n = len(grid)
record = []
for i in range(n):
row = []
for j in range(n):
row.append(-1)
record.append(row)
record[0][0] = grid[0][0]
def sum_path(i,j):
if record[i][j] != -1:
return record[i][j]
if i < 0 or i >= n or j < 0 or j >= n:
return 0
val = max(sum_path(i,j-1), sum_path(i-1,j)) + grid[i][j]
record[i][j] = val
return val
return sum_path(n-1,n-1)
def path_solve_dp(grid):
n = len(grid)
dp = []
for i in range(n):
row = []
for j in range(n):
row.append(-1)
dp.append(row)
dp[0][0] = grid[0][0]
for i in range(n):
for j in range(n):
if i-1 < 0 or i >= n:
if j - 1 >= 0:
dp[i][j] = dp[i][j-1] + grid[i][j]
continue
if j-1 < 0 or j >= n:
if i-1 >= 0:
dp[i][j] = dp[i-1][j] + grid[i][j]
continue
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j]
return dp[n-1][n-1]
grid = [
[3,7,9,2,7],
[9,8,3,5,5],
[1,7,9,8,5],
[3,8,6,4,10],
[6,3,9,7,8]
]
import time
start = time.time()
print(path_solve_dp(grid))
print(time.time() - start)
|
3ed7723170138098f9cd9f5032ec00d851b2f7f1
|
lgdelacruz92/LeetCode-Challenges
|
/accounts-merge/disjoint-sets.py
| 1,675 | 3.5 | 4 |
from pprint import PrettyPrinter
pp = PrettyPrinter()
class DisjointSet:
def __init__(self):
self.universe = ['a','b','c','d','e']
self.PARENT = {}
for item in self.universe:
self.PARENT[item] = item
self.PARENT[self.universe[3]] = self.universe[1]
self.GRAPH = []
for item in self.universe:
row = []
for item in self.universe:
row.append(0)
self.GRAPH.append(row)
n = len(self.universe)
for key in self.PARENT.keys():
value = self.PARENT[key]
row_index = self.universe.index(key)
col_index = self.universe.index(value)
self.GRAPH[row_index][col_index] = 1
self.GRAPH[col_index][row_index] = 1
def find(self, item):
if self.PARENT == item:
return item
else:
return self.find(self.PARENT[item])
def union(self, item1, item2):
self.PARENT[item1] = item2
row_index = self.universe.index(item1)
col_index = self.universe.index(item2)
self.GRAPH[row_index][col_index] = 1
self.GRAPH[col_index][row_index] = 1
def print(self, item):
seen = set()
def dfs(item):
print(item)
seen.add(item)
row_index = self.universe.index(item)
for i, col in enumerate(self.GRAPH[row_index]):
if col == 1 and self.universe[i] not in seen:
dfs(self.universe[i])
dfs(item)
s = DisjointSet()
s.union('a', 'b')
s.union('c', 'a')
s.print('d')
s.print('e')
|
9a52ad177df52e01fa357cfc3f620df7e91f46d7
|
lgdelacruz92/LeetCode-Challenges
|
/create-sorted-array-through-instructions/create-sorted-array-through-instructions.py
| 1,088 | 3.875 | 4 |
def b_search(nums, search_item, start, end):
if end < start:
return -1
k = int((end-start)/2) + start
y = search_item
if nums[k] < y and k == end:
return k
elif nums[k] < y and y <= nums[k+1]:
return k
elif y < nums[k]:
return b_search(nums, search_item, start, k-1)
else:
return b_search(nums, search_item, k+1, end)
def binary_search(nums, search_item):
'''
Given an array and search_item give index of where to insert search_item
@nums: List[int]
@search_item: int
'''
return b_search(nums, search_item, start, end)
a = [1,3,3,3,2,4,2,1,2]
min_cost = 0
sorted_a = []
total_cost = 0
for num in a:
index = b_search(sorted_a, num, 0, len(sorted_a)-1)
if index == -1:
sorted_a.append(num)
min_cost = 0
else:
j = index
while j+1 < len(sorted_a) and sorted_a[j+1] == num:
j+=1
sorted_a = sorted_a[:index+1] + [num] + sorted_a[index+1:]
min_cost = min(len(sorted_a) - j, index+1)
total_cost += min_cost
print(total_cost)
|
c89ada8107f353998c9e5c569dbe7e51b5e9889f
|
lgdelacruz92/LeetCode-Challenges
|
/continous_max_subarray/sol1.py
| 905 | 3.828125 | 4 |
from queue import PriorityQueue
def count_subarrays(arr):
n = len(arr)
result = [1] * n
stack = []
for i, v in enumerate(arr):
if not stack:
result[i] += i
else:
while stack and stack[-1][0] < v:
stack.pop()
if stack:
result[i] += i - stack[-1][1]-1
else:
result[i] += i
stack.append((v, i))
arr.reverse()
result.reverse()
stack = []
for i, v in enumerate(arr):
if not stack:
result[i] += i
else:
while stack and stack[-1][0] < v:
stack.pop()
if stack:
result[i] += i - stack[-1][1]-1
else:
result[i] += i
stack.append((v, i))
result.reverse()
return result
if __name__ == '__main__':
count_subarrays([3, 4, 1, 6, 2])
|
a79bbf5a8c8ed5992fe82f9d5409c6d7ad11648f
|
LionStudent/practice
|
/bfs.py
| 808 | 3.90625 | 4 |
class Graph:
def __init__(self):
self.nodes = {}
def __repr__(self):
return str(self.nodes)
def addEdge(self, src, tgt):
self.nodes.setdefault(src,[]).append(tgt)
self.nodes.setdefault(tgt,[]) # add other node but not reverse edge
def bfs(self, root):
queue = [root]
visited = [False] * len(self.nodes)
while queue:
node = queue.pop(0)
if visited[node] == False:
visited[node] = True
print(node, end=" ")
for child in self.nodes[node]:
queue.append(child)
print("")
g = Graph()
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
g.addEdge(3,4)
print(g)
g.bfs(2)
|
86422c92b3f66365832ee47decc1370b789393be
|
ReblochonMasque/spiralofsquares
|
/rectangle.py
| 1,057 | 3.828125 | 4 |
"""
a Rectangle
"""
from anchor import Anchor
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.bbox = None
self.norm_bbox = None
self.calc_bbox(Anchor())
self.normalize_bbox()
def calc_bbox(self, anchor):
x, y = anchor
self.bbox = [Anchor(anchor.x, anchor.y), (x + self.width, y + self.height)]
self.normalize_bbox()
def normalize_bbox(self):
"""
set the anchor point to the top left corner of the bbox
:return:
"""
p0, p1 = self.bbox
x0, y0 = p0
x1, y1 = p1
self.norm_bbox = [Anchor(min(x0, x1), min(y0, y1)), Anchor(max(x0, x1), max(y0, y1))]
def get_center(self):
tl, br = self.bbox
return tl.get_mid(br)
def __str__(self):
res = f'Rectangle of width= {self.width}, height= {self.height}, bbox at: ' \
f'{", ".join(str(elt) for elt in self.bbox)}'
return res
if __name__ == '__main__':
pass
|
2c7d0939e16034bd7e8d9e7c0082ba31a4502042
|
natashahussain/webLnatasha
|
/CO1 pg7(a).py
| 362 | 4 | 4 |
#Enter 2 lists of integers.Check
#(a) Whether list are of same length
list1 = [2, 5, 4, 1, 6]
list2 = [1, 6, 2, 3, 5]
print ("The first list is : "+ str(list1))
print ("The second list is : "+ str(list2))
if len(list1) == len(list2):
print ("Length of the lists are same")
else :
print ("Length of the lists are not same")
|
c6751016634ed6ef77a3be91342ddfd60af0fdae
|
natashahussain/webLnatasha
|
/CO1 Pg12.py
| 118 | 4.03125 | 4 |
#accept a file and print extension
fn=input("enter filename")
f=fn.split(".")
print("extension of file is;"+ f[-1])
|
317bafca9aa622828b3cb835b10d02301372f4ca
|
DeetoMok/CS50
|
/(Pre-July) 3. Flask/sandbox.py
| 1,385 | 3.875 | 4 |
#Taking in an input
#name = input()
from pyclbr import Class
name = "Daryl"
#f is to print in format String. I this case, the variable "name"
print(f"Hello, {name}!")
# initiating a variable does not require u to specify the data type
i = 28
f = 2.8
b = False
n = None
# Conditional statements
x = 28
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
#Python Tuple
coordinates = (10.0,20.0)
#List
# Note items in the list do not have to be of the same type
names = ["Alice", "Bob", "Charlie"]
#Loops
for i in range(5):
print(i)
for name in names:
print(name)
# Set is unordered set
s = set()
s.add(1)
s.add(3)
s.add(5)
s.add(3)
print(s)
# Dictionary is unordered hash map
ages = {"Alice": 22, "Bob": 27}
ages["Charlie"] = 30
ages["Alice"] += 1
print(ages)
#defining a function
def square(x):
return x * x
# older way of format
for i in range(10):
print("{} squared is {}".format(i, square(i)))
print(f"{i}, {square(i)}")
# modules
# from (fileName) import (functionName)
# Separating a main function from other functions so that importing of specific functions
# is possible
def main():
for i in range(10):
print("{} squared is {}".format(i, square(i)))
print(f"{i}, {square(i)}")
if __name__ == "__main__": #if I am currently running this particular file...
main()
|
2f42cd1195a17baddb6f223e470659906aa702cd
|
abdul-malik360/Python_Proj_Week_Prep
|
/numbers.py
| 770 | 3.6875 | 4 |
from tkinter import *
import random
from tkinter import messagebox
root = Tk()
root.geometry("500x500")
root.title("Generate Your Numbers")
numb_ans = StringVar()
numb_ent = StringVar()
mylist = []
mynewlist = [numb_ent]
ent_numb = Entry(root, textvariable=numb_ent)
ent_numb.place(x=50, y=25)
Label(root, textvariable=numb_ans).place(x=50, y=50)
def generate():
for x in range(1, 2):
number = random.randint(1, 2)
mylist.append(number)
numb_ans.set(mylist)
if numb_ans == numb_ent.get():
messagebox.showinfo("you win", "Weldone")
elif numb_ans != numb_ent.get():
messagebox.showinfo("you loose", "try again")
gen_btn = Button(root, text="Generate", command=generate)
gen_btn.place(x=50, y=100)
root.mainloop()
|
bb2c90429b029e33059fa667a3864eb1fdc60808
|
NatanBB/BSI-2_Classes
|
/classes_exec/bola.py
| 1,053 | 3.921875 | 4 |
# Classe Bola: Crie uma classe que modele uma bola:
# Atributos: Cor, circunferência, material
# Métodos: trocaCor e mostraCor
class Ball:
def __init__(self, color="unknown", circunf=0, material="unknown"):
self.color = color
self.circunf = circunf
self.material = material
def trocaCor(self):
troca = input("Deseja mudar a cor atual {}? [sim/nao]".format(self.color))
troca = troca[0].lower()
if troca == "sim":
nova_cor = input("\n> Nova Cor: ")
self.color = nova_cor
else:
print("A cor continua ser {}".format(self.color))
def mostraCor(self):
print("\nA cor atual é {}".format(self.color))
def main():
bola01 = Ball("azul", 5, "metal")
while True:
bola01.mostraCor()
bola01.trocaCor()
continuar = input("Continuar? [sim/nao]")
continuar = continuar[0].lower()
if continuar == "nao":
break
bola01.mostraCor()
main()
|
996998a8d1b2e956b635d0bae93cd0fe49cb454e
|
ambrishrawat/burrows-wheeler
|
/BurrowsWheelerTransform.py
| 1,228 | 4 | 4 |
class BurrowsWheelerTransform:
"""Transforming a string using Burrows-Wheeler Transform"""
def __init__(self):
pass
def bwt(self,f):
"""Applies Burrows-Wheeler transform to input string.
Args:
f (File): The file object where each line is a '0' or '1'.
Returns:
string: transformed string
"""
s = ""
for line in f:
s+=line.strip()
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def invbwt(self,f):
"""Applies inverse Burrows-Wheeler transform.
Args:
r (File): The file object where each line is a '0' or '1'.
Returns:
string: transformed string
"""
r = ""
for line in f:
r+=line.strip()
table = [""] * len(r) # Make empty table
for i in range(len(r)):
table = sorted(r[i] + table[i] for i in range(len(r))) # Add a column of r
s = [row for row in table if row.endswith("\0")][0] # Find the correct row (ending in "\0")
return s.rstrip("\0") # Get rid of trailing null character
|
f5dc8fd74e6bad8bb10b81b98e3ec711dfb9613a
|
lemonad/advent-of-code
|
/2015 (Python)/december03.py
| 2,167 | 3.5625 | 4 |
"""
December 3, Advent of Code 2015 (Jonas Nockert / @lemonad)
"""
from common.puzzlesolver import PuzzleSolver
class Solver(PuzzleSolver):
@classmethod
def make_move(cls, move, pos):
if move == '^':
pos = (pos[0], pos[1] + 1)
elif move == 'v':
pos = (pos[0], pos[1] - 1)
elif move == '>':
pos = (pos[0] + 1, pos[1])
elif move == '<':
pos = (pos[0] - 1, pos[1])
else:
raise RuntimeError('No such move')
return pos
@classmethod
def santa_deliveries(cls, indata):
pos = (0, 0)
grid = {pos: 1}
for move in indata:
pos = cls.make_move(move, pos)
if pos in grid:
grid[pos] = grid[pos] + 1
else:
grid[pos] = 1
return len(grid)
@classmethod
def robo_santa_deliveries(cls, indata):
pos = [(0, 0), (0, 0)]
grid = {pos[0]: 2}
for index, move in enumerate(indata):
p = cls.make_move(move, pos[index % 2])
if p in grid:
grid[p] = grid[p] + 1
else:
grid[p] = 1
pos[index % 2] = p
return len(grid)
def solve_part_one(self):
"""Solution for part one."""
return self.santa_deliveries(self.puzzle_input)
def solve_part_two(self):
"""Solution for part two."""
return self.robo_santa_deliveries(self.puzzle_input)
def solve(self):
return (self.solve_part_one(), self.solve_part_two())
if __name__ == '__main__':
assert(Solver.santa_deliveries('>') == 2)
assert(Solver.santa_deliveries('^>v<') == 4)
assert(Solver.santa_deliveries('^v^v^v^v^v') == 2)
assert(Solver.robo_santa_deliveries('^v') == 3)
assert(Solver.robo_santa_deliveries('^>v<') == 3)
assert(Solver.robo_santa_deliveries('^v^v^v^v^v') == 11)
s = Solver(from_file='input/dec03.in')
(one, two) = s.solve()
print("Houses that received at least one present: %d." % one)
print("Houses that received at least one present: %d." % two)
assert(one == 2081)
assert(two == 2341)
|
a46c37325d7a3efdcf1a50a43dd943b69163a690
|
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
|
/Section 14/Student Resources/Assignment Solution Scripts/01_file_io_phone_book.py
| 3,368 | 3.96875 | 4 |
# File IO - Append
# File
my_file = "my_phone_book.txt"
# Add
def add_entry(first_name, last_name, phone_number):
entry = first_name + "," + last_name + "," + phone_number + "\n"
with open(my_file, "a") as file_handler:
file_handler.write(entry)
# Get list
def get_list_from_file(file_name):
phone_book_list = []
with open(file_name, "r") as file_handler:
for line in file_handler:
phone_book_list.append(line.replace("\n", ""))
return phone_book_list
# Write list to phone book file
def write_list_to_file(phone_book_list, file_name):
phone_book_string = ""
for entry in phone_book_list:
phone_book_string += entry + "\n"
with open(file_name, "w") as file_handler:
file_handler.write(phone_book_string)
# Remove
def remove_entry(first_name, last_name):
phone_book_list = []
entry = first_name + "," + last_name
with open(my_file, "r") as file_handler:
for line in file_handler:
if entry not in line:
phone_book_list.append(line.replace("\n", ""))
write_list_to_file(phone_book_list, my_file)
# Look up
def look_up_name(first_name, last_name):
entry = first_name + "," + last_name
with open(my_file, "r") as file_handler:
for line in file_handler:
if entry in line:
print("*" * 30)
print("Found : ", line.replace("\n", ""))
print("*" * 30)
else:
print("*" * 30)
print("Not Found")
print("*" * 30)
# Update
def update_name():
with open(my_file, "r") as file_handler:
for line in file_handler:
print(line, end="")
# Update
def update_phone_number(first_name, last_name, new_phone_number):
phone_list = get_list_from_file(my_file)
entry_to_search = first_name + "," + last_name
remove_entry(first_name, last_name)
add_entry(first_name, last_name, new_phone_number)
# Main
def main():
while True:
print("-" * 30)
print("Welcome To Phone_Book v1.0")
print("-" * 30)
print("Menu :")
print("1. Add")
print("2. Lookup")
print("3. Update Phone Number")
print("4. Delete")
print("5. Exit")
print()
choice = int(input("Enter your selection : "))
if choice == 1:
first_name = input("Enter First Name : ")
last_name = input("Enter Last Name : ")
phone_number = input("Enter Phone Number : ")
add_entry(first_name, last_name, phone_number)
if choice == 2:
first_name = input("Enter First Name : ")
last_name = input("Enter Last Name : ")
look_up_name(first_name, last_name)
if choice == 3:
first_name = input("Enter First Name : ")
last_name = input("Enter Last Name : ")
new_phone_number = input("Enter New Phone Number : ")
update_phone_number(first_name, last_name, new_phone_number)
if choice == 4:
first_name = input("Enter First Name : ")
last_name = input("Enter Last Name : ")
phone_number = input("Enter Phone Number : ")
remove_entry(first_name, last_name)
if choice == 5:
exit()
if __name__ == "__main__":
main()
|
aa5511e07cc866babfcd2ee3c7f7d6149ba1b740
|
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
|
/Section 6/Student Resources/Assignment Solution Scripts/assignment_lists_02_solution_min_max.py
| 308 | 4.21875 | 4 |
# Lists
# Assignment 2
numbers = [10, 8, 4, 5, 6, 9, 2, 3, 0, 7, 2, 6, 6]
min_item = numbers[0]
max_item = numbers[0]
for num in numbers:
if min_item > num:
min_item = num
if max_item < num:
max_item = num
print("Minimum Number : ", min_item)
print("Maximum Number : ", max_item)
|
e581134dca95d8b5b36dace6546333c01f61b8a7
|
eman19-meet/y2s18-python_review
|
/exercises/functions.py
| 165 | 3.671875 | 4 |
# Write your solution for 1.4 here!
def is_prime(x):
i=1
while i<x:
if x%i==0:
if i!=x and i!=1:
return False
i=i+1
return True
print(is_prime(5191))
|
4de3b01cdf53acec3acf826e69f054234e5d022c
|
Abhinavjha07/Cloud-Computing
|
/Lab1/lab12.py
| 1,598 | 3.65625 | 4 |
import split
import operator
def readFile(fileIn):
content=""
for line in fileIn :
content+=line
return content
def wordCount(contents):
wordcount={}
for word in split.tsplit(contents,(' ','.','!',',','"','\n','?')):
if word != '':
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
return wordcount
def topTenWords(wordcount):
print('\n\nTop 10 words are : ')
wordcountS = sorted(wordcount.items(), key=operator.itemgetter(1),reverse=True)
for x in range(10):
print(wordcountS[x][0],wordcountS[x][1])
def topTenExcept(wordcount):
stop=list(('a','about','above','after','again','against','all','am','an','and','any','are','as','at','be','because','been','be','for','being','below','the','both','but','by','could','did','do','does','doing','down','during','each','few','for','from','further','had','has','have','having','he','she','her','here','of','in','was','to'))
print('\n\nTop 10 words after removing stop words are : ')
wordcountS = sorted(wordcount.items(), key=operator.itemgetter(1),reverse=True)
x=0
c=0
while c < 10 :
if wordcountS[x][0] not in stop:
print(wordcountS[x][0],wordcountS[x][1])
c+=1
x+=1
def main():
fileIn= open("sample.txt", "r")
contents= readFile(fileIn)
wordcount= wordCount(contents)
for key in wordcount :
print(key,wordcount[key])
topTenWords(wordcount)
topTenExcept(wordcount)
if __name__== "__main__":
main()
|
d0ef890c1a36d3daf597b6649dfc11c1ddf4891e
|
BerryRB/Leetcode
|
/leetcode-day3.py
| 999 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 14:57:21 2019
@author: 刘瑞
"""
"""
题目描述:
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
思路:只要把数组中所有的非零元素,按顺序给数组的前段元素位赋值,剩下的全部直接赋值 0
"""
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=[i for i in nums if i != 0]
nums+=[0]*count
return nums
"""
讨论区看到的一行解法
def moveZeroes(self, nums):
nums.sort(key=lambda x: x == 0)
"""
nums=[1,2,3,0,5,0,0,6,0,7]
test=Solution()
test.moveZeroes(nums)
print(nums)
|
7e16b4a55a95d817df09ae851dba7b797ce9a330
|
BerryRB/Leetcode
|
/leetcode-day13.py
| 1,178 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 16:19:46 2019
@author: 刘瑞
"""
"""
题目描述:快乐数
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路:重点是如何判断无限循环,若某一次求平方和的结果重复出现就说明陷入了无限循环。
注意set的添加元素用add函数,列表的添加用append函数
"""
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
ss = set()
while True:
if n == 1:
return True
total = 0
while n:
total += (n % 10) * (n %10)
n = n // 10
if total in ss:
return False
ss.add(total)
n = total
|
325829efc0923bb02e79c044b190855d65baa16e
|
ggradias/real-python-test
|
/fibo.py
| 226 | 3.65625 | 4 |
#Leonardo de Pisa
import sys
def fib(n):
#return the nth fibonacci number
n = int(n)
if n <= 1:
return 1
return fib(n-1)+ fib(n-2)
if __name__ == '__main__':
import pdb; pdb.set_trace()
print(fib(sys.argv[-1]))
|
bfd6a6a1ce1a215bd6e698e732194b26fd0ec7b4
|
tjnelson5/Learn-Python-The-Hard-Way
|
/ex15.py
| 666 | 4.1875 | 4 |
from sys import argv
# Take input from command line and create two string variables
script, filename = argv
# Open the file and create a file object
txt = open(filename)
print "Here's your file %r:" % filename
# read out the contents of the file to stdout. This will read the whole
# file, because the command ends at the EOF character by default
print txt.read()
# always close the file - like gates in a field!
txt.close()
# create a new string variable from the prompt
print "Type the filename again:"
file_again = raw_input("> ")
# Create a new file object for this new file
txt_again = open(file_again)
# Same as above
print txt_again.read()
txt.close()
|
ec8ba8655f455632af649f889421ab136b30bf1d
|
xy008areshsu/Leetcode_complete
|
/python_version/dp_word_break.py
| 1,080 | 4.0625 | 4 |
"""
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
# idea:
# function: f[i] if it can be break for first i+1 elements of s
# update: if s[: i + 1] is in dict, then f[i] is True; else, for j in range(i), if f[j] is True and s[j + 1 : i + 1] is in dict, then is True
# init: f[0] is True if s[0] in dict, else False
# final solution: f[len(s) - 1]
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
f = len(s) * [False]
f[0] = True if s[0] in dict else False
for i in range(1, len(s)):
if s[:i + 1] in dict:
f[i] = True
else:
for j in range(i):
if f[j] and s[j+1: i + 1] in dict:
f[i] = True
break
return f[-1]
|
a3c1730239862bd1d138a800e38288af6e482c67
|
xy008areshsu/Leetcode_complete
|
/python_version/2_sum_3.py
| 991 | 3.96875 | 4 |
"""
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
"""
class TwoSum:
# initialize your data structure here
def __init__(self):
self.h_map = {}
# @return nothing
def add(self, number):
if number in self.h_map:
self.h_map[number] += 1
else:
self.h_map[number] = 1
# @param value, an integer
# @return a Boolean
def find(self, value):
for k in self.h_map.keys():
if value - k in self.h_map:
if value - k != k: # must consider the case of value = 6, k = 3; if h_map[3] > 1 then it is True
return True
elif self.h_map[value - k] > 1:
return True
return False
|
95f95fdcee0ef4b94db756b9528c11a567e5f031
|
xy008areshsu/Leetcode_complete
|
/python_version/single_number.py
| 776 | 3.875 | 4 |
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
res = 0
for n in A:
res = res ^ n
return res
def using_hash_table(self, A): # applies to any kind of single number, with other elements appear any number of times
hash_m = {}
for n in A:
if n in hash_m:
hash_m[n] += 1
else:
hash_m[n] = 1
for n in A:
if hash_m[n] == 1:
return n
return None
|
6b9281109f10fd0d69dfc54ce0aa807f9592109a
|
xy008areshsu/Leetcode_complete
|
/python_version/intervals_insert.py
| 1,267 | 4.125 | 4 |
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert(self, intervals, newInterval):
if len(intervals) == 0:
return [newInterval]
intervals.append(newInterval)
intervals.sort(key=lambda x: x.start)
res = [intervals[0]]
for i in range(1, len(intervals)):
if intervals[i].start <= res[-1].end: # here needs <= instead of <, e.g. [1, 3], and [3, 5] should be merged into [1, 5]
res[-1].end = max(res[-1].end, intervals[i].end)
else:
res.append(intervals[i])
return res
|
a200196530d1911796efd53079b094260a0576e5
|
xy008areshsu/Leetcode_complete
|
/python_version/min_stack.py
| 719 | 3.6875 | 4 |
class stack:
def __init__(self):
self.s = []
def push(self, val):
self.s.append(val)
def pop(self):
return self.s.pop()
def top(self):
return self.s[-1]
class MinStack:
def __init__(self):
self.s = stack()
self.min_s = stack()
def push(self, val):
if len(self.min_s.s) == 0 or val <= self.min_s.top(): # BUG PRONE, Here must use <=, instead of <
self.min_s.push(val)
self.s.push(val)
def pop(self):
if self.s.top() == self.min_s.top():
self.min_s.pop()
return self.s.pop()
def getMin(self):
return self.min_s.top()
def top(self):
return self.s.top()
|
8c4ef949fb0a7b32cd0556da41121ad5b3595054
|
xy008areshsu/Leetcode_complete
|
/python_version/graph_clone.py
| 853 | 3.671875 | 4 |
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if node is None:
return None
new_nodes = {}
parent = {node : None}
self.dfs(node, new_nodes, parent)
for k in parent.keys():
for n in k.neighbors:
new_nodes[k.label].neighbors.append(new_nodes[n.label])
return new_nodes[node.label]
def dfs(self, node, new_nodes, parent):
new_nodes[node.label] = UndirectedGraphNode(node.label)
for n in node.neighbors:
if n not in parent:
parent[n] = node
self.dfs(n, new_nodes, parent)
|
cccd42643b9b7088915328edb06738e2270345e2
|
xy008areshsu/Leetcode_complete
|
/python_version/DFS_factors_of_number.py
| 688 | 3.796875 | 4 |
"""
e.g. 12 : return [ [1, 12], [2, 2, 3], [2, 6], [3, 4] ]
"""
def factors_of_num(num):
res = []
list_aux = []
helper(num, res, list_aux)
return res
def helper(num, res, list_aux):
if num == 1:
if len(list_aux) < 2:
list_aux.append(num)
res.append(list_aux[:])
list_aux.pop()
else:
res.append(list_aux[:])
return
for i in range(2, num + 1):
if num % i == 0:
if (len(list_aux) > 0 and i >= list_aux[-1]) or len(list_aux) == 0:
list_aux.append(i)
helper(num / i, res, list_aux)
list_aux.pop()
print(factors_of_num(6))
|
466622f128194101691bb1a3d11623356560025c
|
xy008areshsu/Leetcode_complete
|
/python_version/longest_substring_with_at_most_two_distinct_chars.py
| 2,663 | 3.78125 | 4 |
"""
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
T is "ece" which its length is 3.
"""
#idea : maintain a h_map, keys are each char, and vals are lists of indices of each char, each val is a sorted list, since the index goes from 0 to len(s) - 1
# scan the string, if the char already in h_map, append the index of that char to the value list.
# else, if len(h_map) still less than 2, add this char into the h_map
# else, find the minimum index and remove it from the value list. If any value list is empty, then delete the corresponding key. Repeat this until the length of
# h_map is less than 2.
# update the longest length at each step of the for loop
import collections
class Solution:
# @param s, a string
# @return an integer
def lengthOfLongestSubstringTwoDistinct(self, s): # More practice,
if s is None:
return 0
if len(s) == 0 or len(s) == 1 or len(s) == 2:
return len(s)
h_map = {}
longest_len = 0
for i, c in enumerate(s):
if c in h_map:
h_map[c].append(i)
else:
if len(h_map) < 2:
h_map[c] = collections.deque()
h_map[c].append(i)
else:
while len(h_map) >= 2:
c_min, indices = min(h_map.items(), key = lambda x:x[1][0]) # list of index are sorted lists
h_map[c_min].popleft()
if len(h_map[c_min]) == 0:
del h_map[c_min]
h_map[c] = collections.deque()
h_map[c].append(i)
c_min, i_min = min(h_map.items(), key = lambda x : x[1][0])
c_max, i_max = max(h_map.items(), key = lambda x : x[1][-1])
i_min = i_min[0]
i_max = i_max[-1]
if i_max - i_min + 1 > longest_len:
longest_len = i_max - i_min + 1
c_min, i_min = min(h_map.items(), key = lambda x : x[1][0])
c_max, i_max = max(h_map.items(), key = lambda x : x[1][-1])
i_min = i_min[0]
i_max = i_max[-1]
if i_max - i_min + 1> longest_len:
longest_len = i_max - i_min + 1
return longest_len
if __name__ == '__main__':
sol = Solution()
print(sol.lengthOfLongestSubstringTwoDistinct('cdaba'))
print(sol.lengthOfLongestSubstringTwoDistinct('ccaabbb'))
print(sol.lengthOfLongestSubstringTwoDistinct('abadc'))
print(sol.lengthOfLongestSubstringTwoDistinct('aac'))
print(sol.lengthOfLongestSubstringTwoDistinct('abacd'))
|
7e3a1b29b321ff31e6e635d825ddcfb1668aeb5c
|
xy008areshsu/Leetcode_complete
|
/python_version/dp_unique_path.py
| 1,531 | 4.15625 | 4 |
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
"""
class Solution:
# @return an integer
def uniquePaths(self, m, n):
unique_paths_number = {}
unique_paths_number[(0, 0)] = 1
unique_paths_number.update({(0, i) : 1 for i in range(n)})
unique_paths_number.update({(i, 0) : 1 for i in range(m)})
return self.solve(unique_paths_number, m - 1, n - 1)
def solve(self, unique_paths_number, m, n):
if m == 0 or n == 0:
unique_paths_number[(m, n)] = 1
return 1
if (m - 1, n) in unique_paths_number:
unique_paths_number_m_1_n = unique_paths_number[(m-1, n)]
else:
unique_paths_number_m_1_n = self.solve(unique_paths_number, m - 1, n)
if (m, n - 1) in unique_paths_number:
unique_paths_number_m_n_1 = unique_paths_number[(m, n - 1)]
else:
unique_paths_number_m_n_1 = self.solve(unique_paths_number, m , n - 1)
unique_paths_number_m_n = unique_paths_number_m_1_n + unique_paths_number_m_n_1
unique_paths_number[(m, n)] = unique_paths_number_m_n
return unique_paths_number_m_n
|
cfbf373d21232629f021e68cee613b716deb32d8
|
xy008areshsu/Leetcode_complete
|
/python_version/dp_distinct_subsequence.py
| 1,225 | 3.796875 | 4 |
"""
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
"""
# function: f[i][j] number of distinct subsequence of first i characters of S S[: i + 1] in first j characters in T T[: j + 1]
# update: f[i][j], f[i][j] must be at least f[i - 1][j]; then if S[i] == T[j], then f[i][j] += f[i-1][j-1]
# init: f[i][0] = 0
# final solution: f[len(S)][len(T)]
class Solution:
# @return an integer
def numDistinct(self, S, T): # more practice
nums = []
for i in range(len(S) + 1):
nums.append((len(T) + 1) * [0])
for i in range(len(S) + 1):
nums[i][0] = 1
for i in range(1, len(S) + 1):
for j in range(1, len(T) + 1):
nums[i][j] = nums[i - 1][j]
if S[i - 1] == T[j - 1]:
nums[i][j] += nums[i - 1][j - 1]
return nums[len(S)][len(T)]
|
5337ae5f30015e142b6b6916ca2b088bcd8d8e72
|
xy008areshsu/Leetcode_complete
|
/python_version/2_sum_2.py
| 906 | 3.90625 | 4 |
"""
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
"""
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
if len(num) == 0 or len(num) == 1:
raise Exception('No solution')
hash_m = {}
for i in range(len(num)):
if (target - num[i]) in hash_m:
return (hash_m[target-num[i]] + 1, i + 1)
hash_m[num[i]] = i
raise Exception('No solution')
|
13741847dbcaee5b10bdf8d23774f8af86a9418b
|
xy008areshsu/Leetcode_complete
|
/python_version/graph_topological_sort.py
| 1,385 | 3.5625 | 4 |
class Graph:
def __init__(self, vertices = [], Adj = {}):
self.vertices = vertices
self.Adj = Adj
def itervertices(self):
return self.vertices
def neighbors(self, v):
return self.Adj[v]
class DFSResult: # More practice
def __init__(self):
self.parent = {}
self.start_time = {}
self.finish_time = {}
self.order = []
self.edges = {}
self.t = 0
def dfs(g):
results = DFSResult()
for v in g.itervertices():
if v not in results.parent:
dfs_visit(g, v, results)
return results
def dfs_visit(g, v, results, parent = None):
results.parent[v] = parent
results.t += 1
results.start_time[v] = results.t
if parent is not None:
results.edge[(parent, v)] = 'tree edge'
for n in g.neighbors(v):
if n not in results.parent:
dfs_visit(g, n, results, v)
elif n not in results.finish_time:
results.edges[(v, n)] = 'back edge'
elif results.start_time[n] < results.start_time[v]:
results.edges[(v, n)] = 'forward edge'
else:
results.edges[(v, n)] = 'cross edge'
results.t += 1
results.finish_time[v] = results.t
results.order.append(v)
def topological_sort(g):
results = dfs(g)
results.order.reverse()
return results.order
|
9af95f8a72a43fb5ff1b9cf8ca24e33abcb83ec3
|
xy008areshsu/Leetcode_complete
|
/python_version/dp_stock_3.py
| 2,009 | 3.84375 | 4 |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
# idea:
# two functions: best_left[i] best profit scanning from left rto right; best_right[i] best profit scanning from right to left. Same as stock_1 to update the two functions
# combine: best_right reverse, then for i in range(len(best_left) - 1) find an i that maximizes best_left[i] + best_right[i]
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices): # more practice
if len(prices) == 0 or len(prices) == 1:
return 0
best_left = [0]
best_right = [0]
#first scan from left to right
min_price = prices[0]
for i in range(1, len(prices)):
if prices[i] < min_price:
min_price = prices[i]
if prices[i] - min_price > best_left[-1]:
best_left.append(prices[i] - min_price)
else:
best_left.append(best_left[-1])
max_price = prices[-1]
for i in range(len(prices) - 2, -1, -1):
if prices[i] > max_price:
max_price = prices[i]
if max_price - prices[i] > best_right[-1]:
best_right.append(max_price - prices[i])
else:
best_right.append(best_right[-1])
max_profit = 0
best_right.reverse()
for i in range(len(best_left) - 1):
max_profit = max(max_profit, best_left[i] + best_right[i + 1]) # these are for exactly two transactions
max_profit = max(max_profit, best_left[-1]) # this is for just one transaction
return max_profit
if __name__ == '__main__':
prices = [3,2,6,5,0,3]
sol = Solution()
print(sol.maxProfit(prices))
|
e48702cf9debf012096411f0f631ca753990fb46
|
xy008areshsu/Leetcode_complete
|
/python_version/binary_search_find_peak_element.py
| 1,043 | 4.03125 | 4 |
"""
A peak element is an element that is greater than its neighbors.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
"""
class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
if len(num) == 0:
return None
if len(num) == 1:
return 0
if len(num) == 2:
if num[0] > num[1]:
return 0
else:
return 1
start = 0
end = len(num) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if num[mid] > num[mid - 1] and num[mid] > num[mid + 1]:
return mid
elif num[mid] > num[mid - 1]:
start = mid
else:
end = mid
if num[start] > num[end]:
return start
else:
return end
if __name__ == '__main__':
sol = Solution()
print(sol.findPeakElement([1, 2, 3]))
|
1c54bfc00aac0e3123c800d0e6dcfaad5a83790d
|
xy008areshsu/Leetcode_complete
|
/python_version/linkedlist_copy_with_random_pointers.py
| 1,038 | 3.921875 | 4 |
"""
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
"""
# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
if head is None:
return None
dummy = RandomListNode(0)
new_cur = dummy
cur = head
h_map = {}
while cur:
new_cur.next = RandomListNode(cur.label)
new_cur = new_cur.next
h_map[cur] = new_cur
cur = cur.next
cur = head
new_cur = h_map[head]
while cur:
if cur.random in h_map:
new_cur.random = h_map[cur.random]
cur = cur.next
new_cur = new_cur.next
return dummy.next
|
d54e443f757c74f225b32e46e24c7a403cf48cc3
|
volkovandr/Snakeee
|
/py/snake.py
| 8,911 | 3.71875 | 4 |
#!/usr/bin/python3
'''
Implementation of the Snake class responsible for movement of the Snake
'''
from time import time
from food import Food
from random import randint
from copy import deepcopy
from exceptions import GameOver
class Snake:
dead = 0
default_speed = 3
default_length = 10
UP, DOWN, LEFT, RIGHT = 'UP', 'DOWN', 'LEFT', 'RIGHT'
deltas = {
UP: (0, -1),
DOWN: (0, 1),
LEFT: (-1, 0),
RIGHT: (1, 0)
}
def random_snake(grid, color):
if grid.borders_occupied():
raise GameOver("GAME OVER: There is no free space at borders "
"to create a new snake")
while True:
side = [Snake.UP, Snake.DOWN, Snake.LEFT, Snake.RIGHT][
randint(0, 3)]
rand_x = randint(0, grid.width - 1)
rand_y = randint(0, grid.height - 1)
if side == Snake.UP:
if not grid.occupied(rand_x, 0):
return Snake(
rand_x, -1, Snake.DOWN, Snake.default_length,
Snake.default_speed, grid, False, color)
elif side == Snake.DOWN:
if not grid.occupied(rand_x, grid.height - 1):
return Snake(
rand_x, grid.height, Snake.UP,
Snake.default_length, Snake.default_speed, grid,
False, color)
elif side == Snake.LEFT:
if not grid.occupied(0, rand_y):
return Snake(
-1, rand_y, Snake.RIGHT, Snake.default_length,
Snake.default_speed, grid, False, color)
else:
if not grid.occupied(grid.width - 1, rand_y):
return Snake(
grid.width, rand_y, Snake.LEFT,
Snake.default_length, Snake.default_speed, grid,
False, color)
def random_robot_snake(grid, color):
snake = Snake.random_snake(grid, color)
snake.robot = True
return snake
def __init__(self, x, y, direction, length,
speed, grid, robot, color):
self.segments = []
self.head_x, self.head_y = x, y
self.direction = direction
self.new_direction = direction
self.speed = speed
self.framestart = None
for seg_no in range(length):
self.segments.append((x - Snake.deltas[direction][0] * seg_no,
y - Snake.deltas[direction][1] * seg_no,
direction))
self.segments.reverse()
self.direction_stack = []
if grid:
grid.add_object(self)
self.grid = grid
self.dead = False
self.frame_position = 0
self.extending = False
self.robot = robot
self.color = color
def length(self):
return len(self.segments)
def set_direction(self, direction):
if len(self.direction_stack) == 0:
if ((self.direction == Snake.UP and direction == Snake.DOWN) or
(self.direction == Snake.DOWN and direction == Snake.UP) or
(self.direction == Snake.RIGHT and direction == Snake.LEFT) or
(self.direction == Snake.LEFT and direction == Snake.RIGHT)):
return
self.direction_stack.append(direction)
# print("Added new direction to the stack:", direction)
def detect_direction(self):
# print("Detecting new direction.")
try:
food = self.grid.find_food()
except:
print("No Food found. Continuing old direction")
return
self.direction_stack = []
path = self.build_path(self.head_x, self.head_y, food.x, food.y)
if not len(path) > 1:
return
if self.head_x > path[1][0]:
return self.set_direction(Snake.LEFT)
if self.head_x < path[1][0]:
return self.set_direction(Snake.RIGHT)
if self.head_y > path[1][1]:
return self.set_direction(Snake.UP)
if self.head_y < path[1][1]:
return self.set_direction(Snake.DOWN)
def eat_food(self, food):
food.eaten = True
self.grid.remove_object(food)
self.extending = True
Food.Food_eaten += 1
print("{} food eaten!".format(Food.Food_eaten))
def move(self):
if self.dead:
return
if not self.framestart:
self.framestart = time()
self.frame_position = (time() - self.framestart) * self.speed
if self.frame_position < 1:
return
# print("Movind the Snake. Old position:")
# self.print()
if len(self.direction_stack):
self.direction = self.direction_stack[0]
del self.direction_stack[0]
self.head_x += Snake.deltas[self.direction][0]
self.head_y += Snake.deltas[self.direction][1]
if not self.grid.within_grid(self.head_x, self.head_y):
return self.die("Out of the grid")
object_at_new_head = self.grid.occupied(self.head_x, self.head_y)
if object_at_new_head:
if type(object_at_new_head) is Food:
self.eat_food(object_at_new_head)
else:
return self.die('Collision with an obstacle of type {}'.format(
type(object_at_new_head).__name__))
self.segments.append((self.head_x, self.head_y, self.direction))
if self.extending:
self.extending = False
else:
del self.segments[0]
if self.robot:
self.detect_direction()
# print("Snake moved. New position:")
# self.print()
if self.frame_position > 1:
self.framestart += 1 / self.speed
self.move()
def print(self):
print([self.segments[i - 1] for i in range(len(self.segments), 0, -1)])
def die(self, reason=None):
self.frame_position = 0
self.dead = True
if reason:
print("I'm dead for the reason: '{}'".format(reason))
Snake.dead += 1
print("{} snakes are dead so far".format(Snake.dead))
def occupied(self, x, y):
for segment in self.segments:
if x == segment[0] and y == segment[1]:
return True
return False
def build_path(self, start_x, start_y, end_x, end_y):
# print("Trying to find a path from ({}, {}) to ({}, {})".format(
# start_x, start_y, end_x, end_y))
if start_x < 0 or start_y < 0 or start_x >= self.grid.width or \
start_y >= self.grid.height:
# print("The start position is out of the grid. Exiting")
return []
grid = deepcopy(self.grid.build2d())
def mark_cell(cell, step, next_search_cells):
x, y = cell
typ = type(grid[x][y])
if typ is Snake or typ is int:
return False
grid[x][y] = step
next_search_cells.append((x, y))
return True
def adjancent_cells(cell, grid):
x, y = cell
if x > 0:
yield (x - 1, y)
if y > 0:
yield (x, y - 1)
if x < len(grid) - 1:
yield (x + 1, y)
if y < len(grid[0]) - 1:
yield (x, y + 1)
search_cells = [(start_x, start_y)]
grid[start_x][start_y] = 0
step = 1
while True:
next_search_cells = []
for search_cell in search_cells:
if search_cell[0] == end_x and search_cell[1] == end_y:
break
for check_cell in adjancent_cells(search_cell, grid):
mark_cell(check_cell, step, next_search_cells)
if not len(next_search_cells):
break
step += 1
search_cells = next_search_cells
# for row in range(len(grid[0])):
# print([column[row] for column in grid])
if type(grid[end_x][end_y]) is not int:
# print("Could not find a path from ({}, {}) to ({}, {})".format(
# start_x, start_y, end_x, end_y))
return []
path = [(end_x, end_y)]
while True:
cur_pos = path[len(path) - 1]
if cur_pos[0] == start_x and cur_pos[1] == start_y:
break
for check_cell in adjancent_cells(cur_pos, grid):
cell = grid[check_cell[0]][check_cell[1]]
if type(cell) is int:
if cell < grid[cur_pos[0]][cur_pos[1]]:
path.append(check_cell)
break
path.reverse()
# print("Found a path: {}".format(path))
return path
|
acf62110c3914a749821a025854092c3971a3e70
|
Cvtq/GridSearch
|
/main.py
| 1,482 | 3.734375 | 4 |
# Вариант 2
cuts = [[-5, 5], [-5, 5], [-5, 5]]
f = "x**2 - 2*x + y**2 + 4*y + z**2 - 8*z + 21"
def findExtr(f, c):
cuts = c
k = len(cuts)
m = 5
d = cuts[0][1] - cuts[0][0]
h = d / m
min = None
e = 0.0001
# Пока шаг сетки больше eps
while (h > e):
# Найдем координаты всех точек сетки
grid = []
for i in range(m):
x = cuts[0][0] + i * h
for j in range(m):
y = cuts[1][0] + j * h
for k in range(m):
z = cuts[2][0] + k * h
grid.append([x, y, z])
# Предположим, что минимум в первых координатах
x = grid[0][0]
y = grid[0][1]
z = grid[0][2]
min = eval(f)
pMinimum = [x, y, z]
# Найдем минимум
for i in range(len(grid) - 1):
x = grid[i + 1][0]
y = grid[i + 1][1]
z = grid[i + 1][2]
point = eval(f)
if point < min:
min = point
pMinimum = [x, y, z]
# Сузим поиск
for i in range(len(cuts)):
cuts[i] = [pMinimum[i] - h, pMinimum[i] + h]
d = cuts[0][1] - cuts[0][0]
h = d / m
print("Min = {}".format(min))
print("At ({}, {}, {})".format(pMinimum[0], pMinimum[1], pMinimum[2]))
findExtr(f, cuts)
|
5b577e98faf5fa8f139b2010122678df321f6436
|
giorgioGunawan/jenga-vs
|
/catkin_ws/src/baldor/src/baldor/transform.py
| 10,909 | 3.515625 | 4 |
#!/usr/bin/env python
"""
Homogeneous Transformation Matrices
"""
import math
import numpy as np
# Local modules
import baldor as br
def are_equal(T1, T2, rtol=1e-5, atol=1e-8):
"""
Returns True if two homogeneous transformation are equal within a tolerance.
Parameters
----------
T1: array_like
First input homogeneous transformation
T2: array_like
Second input homogeneous transformation
rtol: float
The relative tolerance parameter.
atol: float
The absolute tolerance parameter.
Returns
-------
equal : bool
True if `T1` and `T2` are `almost` equal, False otherwise
See Also
--------
numpy.allclose: Contains the details about the tolerance parameters
"""
M1 = np.array(T1, dtype=np.float64, copy=True)
M1 /= M1[3, 3]
M2 = np.array(T2, dtype=np.float64, copy=True)
M2 /= M2[3, 3]
return np.allclose(M1, M2, rtol, atol)
def between_axes(axis_a, axis_b):
"""
Compute the transformation that aligns two vectors/axes.
Parameters
----------
axis_a: array_like
The initial axis
axis_b: array_like
The goal axis
Returns
-------
transform: array_like
The transformation that transforms `axis_a` into `axis_b`
"""
a_unit = br.vector.unit(axis_a)
b_unit = br.vector.unit(axis_b)
c = np.dot(a_unit, b_unit)
angle = np.arccos(c)
if np.isclose(c, -1.0) or np.allclose(a_unit, b_unit):
axis = br.vector.perpendicular(b_unit)
else:
axis = br.vector.unit(np.cross(a_unit, b_unit))
transform = br.axis_angle.to_transform(axis, angle)
return transform
def inverse(transform):
"""
Compute the inverse of an homogeneous transformation.
.. note:: This function is more efficient than :obj:`numpy.linalg.inv` given
the special properties of homogeneous transformations.
Parameters
----------
transform: array_like
The input homogeneous transformation
Returns
-------
inv: array_like
The inverse of the input homogeneous transformation
"""
R = transform[:3, :3].T
p = transform[:3, 3]
inv = np.eye(4)
inv[:3, :3] = R
inv[:3, 3] = np.dot(-R, p)
return inv
def random(max_position=1.):
"""
Generate a random homogeneous transformation.
Parameters
----------
max_position: float, optional
Maximum value for the position components of the transformation
Returns
-------
T: array_like
The random homogeneous transformation
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> T = br.transform.random()
>>> Tinv = br.transform.inverse(T)
>>> np.allclose(np.dot(T, Tinv), np.eye(4))
True
"""
quat = br.quaternion.random()
T = br.quaternion.to_transform(quat)
T[:3, 3] = np.random.rand(3)*max_position
return T
def to_axis_angle(transform):
"""
Return rotation angle and axis from rotation matrix.
Parameters
----------
transform: array_like
The input homogeneous transformation
Returns
-------
axis: array_like
axis around which rotation occurs
angle: float
angle of rotation
point: array_like
point around which the rotation is performed
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> axis = np.random.sample(3) - 0.5
>>> angle = (np.random.sample(1) - 0.5) * (2*np.pi)
>>> point = np.random.sample(3) - 0.5
>>> T0 = br.axis_angle.to_transform(axis, angle, point)
>>> axis, angle, point = br.transform.to_axis_angle(T0)
>>> T1 = br.axis_angle.to_transform(axis, angle, point)
>>> br.transform.are_equal(T0, T1)
True
"""
R = np.array(transform, dtype=np.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = np.linalg.eig(R33.T)
i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
axis = np.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R corresponding to eigenvalue of 1
w, Q = np.linalg.eig(R)
i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = np.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on axis
cosa = (np.trace(R33) - 1.0) / 2.0
if abs(axis[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*axis[0]*axis[1]) / axis[2]
elif abs(axis[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*axis[0]*axis[2]) / axis[1]
else:
sina = (R[2, 1] + (cosa-1.0)*axis[1]*axis[2]) / axis[0]
angle = math.atan2(sina, cosa)
return axis, angle, point
def to_dual_quaternion(transform):
"""
Return quaternion from the rotation part of an homogeneous transformation.
Parameters
----------
transform: array_like
Rotation matrix. It can be (3x3) or (4x4)
isprecise: bool
If True, the input transform is assumed to be a precise rotation matrix and
a faster algorithm is used.
Returns
-------
qr: array_like
Quaternion in w, x, y z (real, then vector) for the rotation component
qt: array_like
Quaternion in w, x, y z (real, then vector) for the translation component
Notes
-----
Some literature prefers to use :math:`q` for the rotation component and
:math:`q'` for the translation component
"""
def cot(x): return 1./np.tan(x)
R = np.eye(4)
R[:3, :3] = transform[:3, :3]
l, theta, _ = to_axis_angle(R)
t = transform[:3, 3]
# Pitch d
d = np.dot(l.reshape(1, 3), t.reshape(3, 1))
# Point c
c = 0.5*(t-d*l) + cot(theta/2.)*np.cross(l, t)
# Moment vector
m = np.cross(c, l)
# Rotation quaternion
qr = np.zeros(4)
qr[0] = np.cos(theta/2.)
qr[1:] = np.sin(theta/2.)*l
# Translation quaternion
qt = np.zeros(4)
qt[0] = -(1/2.)*np.dot(qr[1:], t)
qt[1:] = (1/2.)*(qr[0]*t + np.cross(t, qr[1:]))
return qr, qt
def to_euler(transform, axes='sxyz'):
"""
Return Euler angles from transformation matrix with the specified axis
sequence.
Parameters
----------
transform: array_like
Rotation matrix. It can be (3x3) or (4x4)
axes: str, optional
Axis specification; one of 24 axis sequences as string or encoded tuple
Returns
-------
ai: float
First rotation angle (according to axes).
aj: float
Second rotation angle (according to axes).
ak: float
Third rotation angle (according to axes).
Notes
-----
Many Euler angle triplets can describe the same rotation matrix
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> T0 = br.euler.to_transform(1, 2, 3, 'syxz')
>>> al, be, ga = br.transform.to_euler(T0, 'syxz')
>>> T1 = br.euler.to_transform(al, be, ga, 'syxz')
>>> np.allclose(T0, T1)
True
"""
try:
firstaxis, parity, repetition, frame = br._AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
br._TUPLE2AXES[axes] # validation
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = br._NEXT_AXIS[i+parity]
k = br._NEXT_AXIS[i-parity+1]
M = np.array(transform, dtype=np.float64, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k])
if sy > br._EPS:
ax = math.atan2(M[i, j], M[i, k])
ay = math.atan2(sy, M[i, i])
az = math.atan2(M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i])
if cy > br._EPS:
ax = math.atan2(M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2(M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return ax, ay, az
def to_quaternion(transform, isprecise=False):
"""
Return quaternion from the rotation part of an homogeneous transformation.
Parameters
----------
transform: array_like
Rotation matrix. It can be (3x3) or (4x4)
isprecise: bool
If True, the input transform is assumed to be a precise rotation matrix and
a faster algorithm is used.
Returns
-------
q: array_like
Quaternion in w, x, y z (real, then vector) format
Notes
-----
Quaternions :math:`w + ix + jy + kz` are represented as :math:`[w, x, y, z]`.
Examples
--------
>>> import numpy as np
>>> import baldor as br
>>> q = br.transform.to_quaternion(np.identity(4), isprecise=True)
>>> np.allclose(q, [1, 0, 0, 0])
True
>>> q = br.transform.to_quaternion(np.diag([1, -1, -1, 1]))
>>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
True
>>> T = br.axis_angle.to_transform((1, 2, 3), 0.123)
>>> q = br.transform.to_quaternion(T, True)
>>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
True
"""
M = np.array(transform, dtype=np.float64, copy=False)[:4, :4]
if isprecise:
q = np.empty((4, ))
t = np.trace(M)
if t > M[3, 3]:
q[0] = t
q[3] = M[1, 0] - M[0, 1]
q[2] = M[0, 2] - M[2, 0]
q[1] = M[2, 1] - M[1, 2]
else:
i, j, k = 0, 1, 2
if M[1, 1] > M[0, 0]:
i, j, k = 1, 2, 0
if M[2, 2] > M[i, i]:
i, j, k = 2, 0, 1
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q = q[[3, 0, 1, 2]]
q *= 0.5 / math.sqrt(t * M[3, 3])
else:
m00 = M[0, 0]
m01 = M[0, 1]
m02 = M[0, 2]
m10 = M[1, 0]
m11 = M[1, 1]
m12 = M[1, 2]
m20 = M[2, 0]
m21 = M[2, 1]
m22 = M[2, 2]
# symmetric matrix K
K = np.array([[m00-m11-m22, 0.0, 0.0, 0.0],
[m01+m10, m11-m00-m22, 0.0, 0.0],
[m02+m20, m12+m21, m22-m00-m11, 0.0],
[m21-m12, m02-m20, m10-m01, m00+m11+m22]])
K /= 3.0
# quaternion is eigenvector of K that corresponds to largest eigenvalue
w, V = np.linalg.eigh(K)
q = V[[3, 0, 1, 2], np.argmax(w)]
if q[0] < 0.0:
np.negative(q, q)
return q
|
cc99f3cfb363936e9902969471bda245627e8a46
|
Isetnt2/dice-ploter
|
/main-dice.py
| 976 | 3.5625 | 4 |
import matplotlib.pyplot as plt
from random import randint as rnd
amountOfDice = int(input('Hur många tärningar vill du kasta?'))
amount = int(input('Hur många gånger vill du kasta?'))
amountOfSides = int(input('Hur många sidor ska tärningarna ha?'))
sum = []
frequency = []
plt.plot(sum, frequency[amountOfDice:])
for i in range(amountOfSides*amountOfDice+1):
frequency.append(int('0'))
def throw(diceAmount, diceSides):
sumOfThrow = 0
if len(sum) < amountOfSides*2 - amountOfDice:
for i in range(amountOfDice, amountOfDice*amountOfSides+1):
sum.append(i)
for i in range(diceAmount):
sumOfThrow = sumOfThrow + rnd(1, diceSides)
return sumOfThrow
for i in range(amount):
throws = throw(amountOfDice, amountOfSides)
frequency[throws] = frequency[throws] + 1
plt.clf()
plt.plot(sum, frequency[amountOfDice:])
plt.pause(0.05)
plt.plot(sum, frequency[amountOfDice:], 'g')
plt.show()
|
23b9542d92eb82c369b68d10ff4550af25d33b6b
|
kwaper/iti0201-2018
|
/L2/robot.py
| 1,413 | 3.921875 | 4 |
"""Terminator."""
import rospy
from PiBot import PiBot
robot = PiBot()
count = int()
robot.get_leftmost_line_sensor()
robot.get_rightmost_line_sensor()
def counting(count):
"""Counting."""
if count == 3:
print("Turning Right")
robot.set_right_wheel_speed(-30)
robot.set_left_wheel_speed(0)
rospy.sleep(0.7)
return count
elif count == 2:
print("Going Straight")
robot.set_wheels_speed(-20)
rospy.sleep(0.7)
elif count == 1:
print("Turning Left")
robot.set_right_wheel_speed(0)
robot.set_left_wheel_speed(-30)
rospy.sleep(0.7)
while True:
color_from_left = robot.get_leftmost_line_sensor()
color_from_right = robot.get_rightmost_line_sensor()
if count == 3:
count -= 3
if color_from_right == color_from_left:
robot.set_wheels_speed(-13)
elif color_from_left > color_from_right:
robot.set_left_wheel_speed(-15)
robot.set_right_wheel_speed(15)
if color_from_right > 300:
robot.set_right_wheel_speed(-15)
elif color_from_left < color_from_right:
robot.set_left_wheel_speed(15)
robot.set_right_wheel_speed(-15)
if color_from_left > 300:
robot.set_left_wheel_speed(-15)
if color_from_right < 300 and color_from_left < 300:
count += 1
print(count)
counting(count)
|
d9bfdddb7cdc8dc6ad7a1585f125edfd09ed871d
|
SpamAndEgg/jump_and_run_madness
|
/visualize_convolution.py
| 1,560 | 3.546875 | 4 |
# Here the convoluted frame is produced as output for further use by the neural network or for visualization.
import threading
import numpy as np
import global_var
from math import floor
# This thread visualizes the convolution of the game screen.
class VisualConvolutionThread(threading.Thread):
def run(self):
# Set up the animation window to show the convoluted frame which will be updated every "interval_time"
# milliseconds.
def start_animation():
# "this_conv_frame" is updated in the game loop regularly.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def update(frame):
img.set_data(np.transpose(global_var.this_conv_frame))
plt.setp(title_obj, text='Game score: '+str(floor(global_var.game_score)))
def init():
img.set_data(np.transpose(global_var.this_conv_frame))
fig, ax = plt.subplots(1, 1)
title_obj = plt.title('Game score: 0')
img = ax.imshow(np.transpose(global_var.this_conv_frame), cmap='gist_gray_r', vmin=0, vmax=1)
# Start the animation of the convoluted frame (interval time in milliseconds).
ani = FuncAnimation(fig, update, init_func=init, blit=False, interval=50)
plt.show()
return ani
# Visualize the input convolution.
animation = start_animation()
# Start convolution thread.
visual_convolution = VisualConvolutionThread()
visual_convolution.start()
|
91b56df18751d0c24e4622b5556e95123eb6c68d
|
skimbrel/project-euler
|
/python/p9.py
| 363 | 3.9375 | 4 |
"""Find the 3-tuple (a, b, c) such that a < b < c, a**2 + b**2 == c**2, and sum(a,b,c) = 1000."""
def find_tuple():
for c in xrange(0, 1000):
for b in xrange(0, c):
for a in xrange(0, b):
if a ** 2 + b ** 2 == c ** 2 and sum([a, b, c]) == 1000:
print a * b * c
return
find_tuple()
|
c20802ed076df2adc4c4b430f6761742487d37a7
|
samluyk/Python
|
/GHP17.py
| 900 | 4.46875 | 4 |
# Step 1: Ask for weight in pounds
# Step 2: Record user’s response
weight = input('Enter your weight in pounds: ')
# Step 3: Ask for height in inches
# Step 4: Record user’s input
height = input('Enter your height in inches: ')
# Step 5: Change “string” inputs into a data type float
weight_float = float(weight)
height_float = float(height)
# Step 6: Calculate BMI Imperial (formula: (5734 weight / (height*2.5))
BMI = (5734 * weight_float) / (height_float**2.5)
# Step 7: Display BMI
print("Your BMI is: ", BMI)
# Step 8: Convert weight to kg (formula: pounds * .453592)
weight_kg = weight_float * .453592
# Step 9: Convert height to meters (formula: inches * .0254)
height_meters = height_float * .0254
# Step 10: Calculate BMI Metric (formula: 1.3 * weight / height** 2.5
BMI = 1.3 * weight_kg / height_meters**2.5
# Step 11: Display BMI
print("Your BMI is: ", BMI)
# Step 12: Terminate
|
4b02aaeaf5193eb6df74c199eb4fc563a01441dc
|
HarivigneshN/Harivignesh-N
|
/Converting uppercase to lowercase.py
| 104 | 3.859375 | 4 |
s=input()
a=''
for x in s:
if x.islower():
a=a+x.upper()
elif x.isupper():
a=a+x.lower()
print(a)
|
b26697a86d2fc1058c709d53cb0abbace118653a
|
HarivigneshN/Harivignesh-N
|
/alphabets finder.py
| 196 | 4.1875 | 4 |
a=input()
if((a>='a' and a<='z') or (a>='A' and a<='Z')):
print ("Alphabet")
else:
print("No")
#####Another method#####
#if a.isalpha() == True:
# print("Alphabets")
#else:
# print("No")
|
c4d747c1283007bfd70d81bf8686e448038d7c68
|
HarivigneshN/Harivignesh-N
|
/Encode string by adding 3 in char.py
| 61 | 3.609375 | 4 |
s=input()
a=''
for x in s:
a = a + chr(ord(x) + 3)
print(a)
|
020ba9167844284ef2608e37e6bcb10292330368
|
HarivigneshN/Harivignesh-N
|
/Armstrong number.py
| 111 | 3.625 | 4 |
a=int(input())
b=0
c=a
while (a>0):
d=a%10
b=b+(d**3)
a=a//10
if (b==c):
print ("yes")
else:
print ("no")
|
7c2b8b11f351400e56ea11ee016adadd9cbef2cf
|
HarivigneshN/Harivignesh-N
|
/duplicate remover.py
| 209 | 3.734375 | 4 |
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
---------------------------------------------------------------------------
use set()
ie., a=set(a) but cant sort again.
|
fcec737c20d89968234256445be103b61601a119
|
hed-standard/hed-python
|
/hed/tools/util/io_util.py
| 11,590 | 3.703125 | 4 |
"""Utilities for generating and handling file names."""
import os
import re
from datetime import datetime
from hed.errors.exceptions import HedFileError
TIME_FORMAT = '%Y_%m_%d_T_%H_%M_%S_%f'
def check_filename(test_file, name_prefix=None, name_suffix=None, extensions=None):
""" Return True if correct extension, suffix, and prefix.
Parameters:
test_file (str) : Path of filename to test.
name_prefix (list, str, None): An optional name_prefix or list of prefixes to accept for the base filename.
name_suffix (list, str, None): An optional name_suffix or list of suffixes to accept for the base file name.
extensions (list, str, None): An optional extension or list of extensions to accept for the extensions.
Returns:
bool: True if file has the appropriate format.
Notes:
- Everything is converted to lower case prior to testing so this test should be case insensitive.
- None indicates that all are accepted.
"""
basename = os.path.basename(test_file.lower())
if name_prefix and not get_allowed(basename, allowed_values=name_prefix, starts_with=True):
return False
if extensions:
ext = get_allowed(basename, allowed_values=extensions, starts_with=False)
if not ext:
return False
basename = basename[:-len(ext)]
else:
basename = os.path.splitext(basename)[0]
if name_suffix and not get_allowed(basename, allowed_values=name_suffix, starts_with=False):
return False
return True
def get_allowed(value, allowed_values=None, starts_with=True):
""" Return the portion of the value that matches a value in allowed_values or None if no match.
Parameters:
value (str): value to be matched.
allowed_values (list, str, or None): Values to match.
starts_with (bool): If true match is done at beginning of string, otherwise the end.
Notes:
- match is done in lower case.
"""
if not allowed_values:
return value
elif not isinstance(allowed_values, list):
allowed_values = [allowed_values]
allowed_values = [item.lower() for item in allowed_values]
lower_value = value.lower()
if starts_with:
result = list(filter(lower_value.startswith, allowed_values))
else:
result = list(filter(lower_value.endswith, allowed_values))
if result:
result = result[0]
return result
def extract_suffix_path(path, prefix_path):
""" Return the suffix of path after prefix path has been removed.
Parameters:
path (str) path of the root directory.
prefix_path (str) sub-path relative to the root directory.
Returns:
str: Suffix path.
Notes:
- This function is useful for creating files within BIDS datasets
"""
real_prefix = os.path.normpath(os.path.realpath(prefix_path).lower())
suffix_path = os.path.normpath(os.path.realpath(path).lower())
return_path = os.path.normpath(os.path.realpath(path))
if suffix_path.startswith(real_prefix):
return_path = return_path[len(real_prefix):]
return return_path
def clean_filename(filename):
""" Replaces invalid characters with under-bars
Parameters:
filename (str): source filename
Returns:
str: The filename with anything but alphanumeric, period, hyphens, and under-bars removed.
"""
if not filename:
return ""
out_name = re.sub(r'[^a-zA-Z0-9._-]+', '_', filename)
return out_name
def get_dir_dictionary(dir_path, name_prefix=None, name_suffix=None, extensions=None, skip_empty=True,
exclude_dirs=None):
""" Create dictionary directory paths keys.
Parameters:
dir_path (str): Full path of the directory tree to be traversed (no ending slash).
name_prefix (str, None): An optional name_prefix for the base filename.
name_suffix (str, None): An optional name_suffix for the base file name.
extensions (list, None): An optional list of file extensions.
skip_empty (bool): Do not put entry for directories that have no files.
exclude_dirs (list): List of directories to skip
Returns:
dict: Dictionary with directories as keys and file lists values.
"""
if not exclude_dirs:
exclude_dirs = []
dir_dict = {}
for root, dirs, files in os.walk(dir_path, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude_dirs]
file_list = []
for r_file in files:
if check_filename(r_file, name_prefix, name_suffix, extensions):
file_list.append(os.path.join(os.path.realpath(root), r_file))
if skip_empty and not file_list:
continue
dir_dict[os.path.realpath(root)] = file_list
return dir_dict
def get_filtered_by_element(file_list, elements):
""" Filter a file list by whether the base names have a substring matching any of the members of elements.
Parameters:
file_list (list): List of file paths to be filtered.
elements (list): List of strings to use as filename filters.
Returns:
list: The list only containing file paths whose filenames match a filter.
"""
new_list = [file for file in file_list if any(substring in os.path.basename(file) for substring in elements)]
return new_list
def get_filtered_list(file_list, name_prefix=None, name_suffix=None, extensions=None):
""" Get list of filenames satisfying the criteria.
Everything is converted to lower case prior to testing so this test should be case insensitive.
Parameters:
file_list (list): List of files to test.
name_prefix (str): Optional name_prefix for the base filename.
name_suffix (str): Optional name_suffix for the base filename.
extensions (list): Optional list of file extensions (allows two periods (.tsv.gz)
Returns:
list: The filtered file names.
"""
filtered_files = [file for file in file_list if
check_filename(file, name_prefix=name_prefix, name_suffix=name_suffix, extensions=extensions)]
return filtered_files
def get_file_list(root_path, name_prefix=None, name_suffix=None, extensions=None, exclude_dirs=None):
""" Return paths satisfying various conditions.
Parameters:
root_path (str): Full path of the directory tree to be traversed (no ending slash).
name_prefix (str, None): An optional name_prefix for the base filename.
name_suffix (str, None): The name_suffix of the paths to be extracted.
extensions (list, None): A list of extensions to be selected.
exclude_dirs (list, None): A list of paths to be excluded.
Returns:
list: The full paths.
"""
file_list = []
if not exclude_dirs:
exclude_dirs = []
for root, dirs, files in os.walk(root_path, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude_dirs]
for r_file in files:
if check_filename(r_file, name_prefix, name_suffix, extensions):
file_list.append(os.path.realpath(os.path.join(root, r_file)))
return file_list
def get_path_components(root_path, this_path):
""" Get a list of the remaining components after root path.
Parameters:
root_path (str): A path (no trailing separator)
this_path (str): The path of a file or directory descendant of root_path
Returns:
list or None: A list with the remaining elements directory components to the file.
Notes: this_path must be a descendant of root_path.
"""
base_path = os.path.normpath(os.path.realpath(root_path))
cur_path = os.path.normpath(os.path.realpath(this_path))
common_prefix = os.path.commonprefix([base_path, cur_path])
if not common_prefix:
raise ValueError("NoPathInCommon", f"Paths {base_path} and {cur_path} must have items in common")
common_path = os.path.commonpath([base_path, cur_path])
if common_path != base_path:
return None
rel_path = os.path.relpath(cur_path, base_path)
the_dir = os.path.dirname(rel_path)
if the_dir:
return os.path.normpath(the_dir).split(os.sep)
else:
return []
def get_timestamp():
now = datetime.now()
return now.strftime(TIME_FORMAT)[:-3]
def make_path(root_path, sub_path, filename):
""" Get path for a file, verifying all components exist.
Parameters:
root_path (str): path of the root directory.
sub_path (str): sub-path relative to the root directory.
filename (str): filename of the file.
Returns:
str: A valid realpath for the specified file.
Notes: This function is useful for creating files within BIDS datasets
"""
dir_path = os.path.realpath(os.path.join(root_path, sub_path))
os.makedirs(dir_path, exist_ok=True)
return os.path.realpath(os.path.join(dir_path, filename))
def parse_bids_filename(file_path):
""" Split a filename into BIDS-relevant components.
Parameters:
file_path (str): Path to be parsed.
Returns:
str: BIDS suffix name.
str: File extension (including the .).
dict: Dictionary with key-value pair being (entity type, entity value).
:raises HedFileError:
- If filename does not conform to name-value_suffix format.
Notes:
- splits into BIDS suffix, extension, and a dictionary of entity name-value pairs.
"""
filename = os.path.splitext(os.path.basename(file_path))
ext = filename[1].lower()
basename = filename[0].strip()
entity_dict = {}
if len(basename) == 0:
raise HedFileError("BlankFileName", f"The basename for {file_path} is blank", "")
entity_pieces = basename.split('_')
split_dict = _split_entity(entity_pieces[-1])
if "bad" in split_dict:
raise HedFileError("BadSuffixPiece",
f"The basename for {entity_pieces[-1]} has bad {split_dict['bad']}", "")
if "suffix" in split_dict:
suffix = split_dict["suffix"]
else:
suffix = None
entity_dict[split_dict["key"]] = split_dict["value"]
for pos, entity in reversed(list(enumerate(entity_pieces[:-1]))):
split_dict = _split_entity(entity)
if "key" not in split_dict:
raise HedFileError("BadKeyValue", f"The piece {entity} is not in key-value form", "")
entity_dict[split_dict["key"]] = split_dict["value"]
return suffix, ext, entity_dict
def _split_entity(piece):
"""Splits an piece into an entity or suffix.
Parameters:
piece (str): A string to be parsed.
Returns:
dict: with entities as keys as well as the key "bad" and the key "suffix".
"""
piece = piece.strip()
if not piece:
return {"bad": ""}
split_piece = piece.split('-')
if len(split_piece) == 1:
return {"suffix": piece}
if len(split_piece) == 2:
return {"key": split_piece[0].strip(), "value": split_piece[1].strip()}
else:
return {"bad": piece}
|
fe4e6bf449c1fe5dc2ba80f6102ab13fe10fbeaf
|
hed-standard/hed-python
|
/hed/tools/remodeling/operations/remove_rows_op.py
| 1,988 | 3.640625 | 4 |
""" Remove rows from a tabular file. """
from hed.tools.remodeling.operations.base_op import BaseOp
class RemoveRowsOp(BaseOp):
""" Remove rows from a tabular file.
Required remodeling parameters:
- **column_name** (*str*): The name of column to be tested.
- **remove_values** (*list*): The values to test for row removal.
"""
PARAMS = {
"operation": "remove_rows",
"required_parameters": {
"column_name": str,
"remove_values": list
},
"optional_parameters": {}
}
def __init__(self, parameters):
""" Constructor for remove rows operation.
Parameters:
parameters (dict): Dictionary with the parameter values for required and optional parameters.
:raises KeyError:
- If a required parameter is missing.
- If an unexpected parameter is provided.
:raises TypeError:
- If a parameter has the wrong type.
"""
super().__init__(self.PARAMS, parameters)
self.column_name = parameters["column_name"]
self.remove_values = parameters["remove_values"]
def do_op(self, dispatcher, df, name, sidecar=None):
""" Remove rows with the values indicated in the column.
Parameters:
dispatcher (Dispatcher): Manages the operation I/O.
df (DataFrame): The DataFrame to be remodeled.
name (str): Unique identifier for the dataframe -- often the original file path.
sidecar (Sidecar or file-like): Not needed for this operation.
Returns:
Dataframe: A new dataframe after processing.
"""
df_new = df.copy()
if self.column_name not in df_new.columns:
return df_new
for value in self.remove_values:
df_new = df_new.loc[df_new[self.column_name] != value, :]
return df_new
|
0d28d6b5f6a31a6201a1d728d6a54e40ee339635
|
caderache2014/data_structures
|
/queue.py
| 953 | 3.890625 | 4 |
class queue_item():
def __init__(self):
self.data = None
self.next = None
class queue():
def __init__(self):
self.head= None
def enqueue(self, data):
new_item = queue_item()
new_item.data = data
new_item.next = self.head
self.head = new_item
def dequeue(self):
if self.size() == 0:
raise Exception('Empty Queue!')
remove_item = self.head
if not remove_item.next:
data = remove_item.data
self.head = None
return data
while remove_item.next.next:
remove_item = remove_item.next
data = remove_item.next.data
remove_item.next = None
return data
def size(self):
size = 0
curr_item = self.head
while curr_item:
curr_item = curr_item.next
size += 1
return size
|
2743bd4df557ccc89ab0f3961fa0ca8e2b31697b
|
LstChanceMadrid/digital-crafts-18
|
/tip_calculator.py
| 331 | 3.984375 | 4 |
total_amount = float(input("Enter the total amount: "))
tip_percentage_amount = float(input("Enter the tip percentage amount: "))
def tip_amount(total_amount, tip_percentage_amount):
tip = total_amount * tip_percentage_amount / 100
print("$" + str(tip))
return tip
tip_amount(total_amount, tip_percentage_amount)
|
0d8fbaba74f8471905facad5aa730ae95ba3fb57
|
Robin970822/Ada-IRL
|
/maze_env.py
| 5,705 | 3.5 | 4 |
"""
Created on Tue April 24 21:07 2018
@author: hanxy
"""
import numpy as np
import tkinter as tk
import time
UNIT = 40 # pixels
SQUAR = UNIT * 3 / 8
# create points on canvas
def create_points(point, canvas, fill):
rect_center = UNIT / 2 + point * UNIT
shape = np.shape(rect_center)
assert shape[-1] == 2, 'only build 2d maze'
if len(shape) == 1:
rect = canvas.create_rectangle(
rect_center[0] - SQUAR, rect_center[1] - SQUAR,
rect_center[0] + SQUAR, rect_center[1] + SQUAR,
fill=fill
)
return rect
# transfer rectangle on canvas to point
def transfer_coordinate(rect):
rect_center = np.array([(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2])
point = rect_center / UNIT - 0.5
point = np.array(point, dtype=int)
return point
class Maze(tk.Tk, object):
def __init__(self, col=8, row=8,
hell=np.array([[6, 1], [1, 6], [5, 6], [6, 5]]),
origin=np.array([0, 0]),
terminal=np.array([7, 7])):
super(Maze, self).__init__()
self.action_space = ['w', 's', 'a', 'd']
self.n_actions = len(self.action_space)
self.n_features = 2
self.title('maze')
# col and row for maze
self.col = np.max([col, np.max(hell, axis=0)[1] + 1,
origin[1] + 1, terminal[0] + 1])
self.row = np.max([row, np.max(hell, axis=0)[0] + 1,
origin[0] + 1, terminal[0] + 1])
self.origin = origin # origin coordinate
self.terminal = terminal # terminal coordinate
self.hell = hell # hell coordinate
self.n_hells = np.shape(self.hell)[0] # number of hells
self.geometry('{0}x{1}'.format(self.row * UNIT,
self.col * UNIT))
self.is_encode = True
self._build_maze()
def _build_maze(self):
self.canvas = tk.Canvas(self, bg='white',
height=self.row * UNIT,
width=self.col * UNIT)
# create grids
for c in range(0, self.col * UNIT, UNIT):
x0, y0, x1, y1 = c, 0, c, self.row * UNIT
self.canvas.create_line(x0, y0, x1, y1)
for r in range(0, self.row * UNIT, UNIT):
x0, y0, x1, y1 = 0, r, self.col * UNIT, r
self.canvas.create_line(x0, y0, x1, y1)
# create origin (red)
self.rect = create_points(self.origin, self.canvas, 'red')
# create terminal (yellow)
self.terminal_point = create_points(self.terminal, self.canvas, 'yellow')
# create hell (black)
self.hell_points = np.zeros(self.n_hells, dtype=int)
for i in range(0, self.n_hells):
self.hell_points[i] = create_points(self.hell[i], self.canvas, 'black')
# self.bind("<Key>", self.on_key_pressed)
# pack all
self.canvas.pack()
def reset(self):
self.update()
time.sleep(0.5)
self.canvas.delete(self.rect)
self.rect = create_points(self.origin, self.canvas, 'red')
# return observation
if self.is_encode:
return self._encode(self.origin)
else:
return self.origin
def step(self, action):
s = self.canvas.coords(self.rect)
base_action = np.array([0, 0])
if action == 0: # up 'w'
if s[1] > UNIT:
base_action[1] -= UNIT
elif action == 1: # down 's'
if s[1] < (self.row - 1) * UNIT:
base_action[1] += UNIT
elif action == 2: # left 'a'
if s[0] > UNIT:
base_action[0] -= UNIT
elif action == 3: # right 'd'
if s[0] < (self.col - 1) * UNIT:
base_action[0] += UNIT
# move agent
self.canvas.move(self.rect, base_action[0], base_action[1])
# next state
s_ = self.canvas.coords(self.rect)
# reward function for Reinforcement Learning
done = False
# terminal
if s_ == self.canvas.coords(self.terminal_point):
reward = 1000
done = True
s_ = self.terminal
# s_ = 'terminal'
if self.is_encode:
return self._encode(s_), reward, done
else:
return s_, reward, done
else: # hell
hell_rects = np.zeros((self.n_hells, 4))
for i in range(0, self.n_hells):
hell_rects[i] = self.canvas.coords(self.hell_points[i])
if (s_ == hell_rects[i]).all():
reward = -10
done = True
# s_ = 'hell'
if self.is_encode:
return self._encode(transfer_coordinate(s_)), reward, done
else:
return transfer_coordinate(s_), reward, done
# normal
reward = 0
if self.is_encode:
return self._encode(transfer_coordinate(s_)), reward, done
else:
return transfer_coordinate(s_), reward, done
def render(self):
time.sleep(0.01)
self.update()
# key pressed call back function
def on_key_pressed(self, event):
char = event.char
self.render()
if char in self.action_space:
action = self.action_space.index(char)
s, r, done = self.step(action)
print s
if done:
self.reset()
# encode state
def _encode(self, state):
return state[0] + state[1] * self.col
if __name__ == '__main__':
env = Maze()
env.mainloop()
|
b43f3dc11cc4b367dc7148973fc7f5096d01704c
|
dlapochkin/project.6
|
/main.py
| 6,431 | 3.875 | 4 |
from string import *
from random import *
def main():
"""
Main function
:return: None
"""
board, stats = cleaner(preparation())
table(board, stats)
turn(board, stats)
def preparation():
"""
Creates board pattern and dictionary, containing board values
:return: Shuffled board
"""
pattern = '123456789' \
'456789123' \
'789123456' \
'234567891' \
'567891234' \
'891234567' \
'345678912' \
'678912345' \
'912345678'
clear = dict(zip([(x, y) for x in 'abcdefghi' for y in range(1, 10)], [x for x in pattern]))
return shuffler(clear)
def shuffler(board):
"""
Shuffles board values using random rows and columns swaps and transposition of the board
:param board: dictionary, containing board values
:return: board with shuffled values
"""
shuffling = {0: rows_moving, 1: columns_moving, 2: transposition}
for shuff in range(256):
board = shuffling[randint(0, 2)](board)
return board
def transposition(board):
"""
Swaps rows and columns of the board
:param board: dictionary, containing board values
:return: transposed board
"""
transposed = {}
for (x, y) in board:
transposed[(x, y)] = board[(chr(y + 96), ord(x) - 96)]
return transposed
def rows_moving(board):
"""
Swaps two random rows in one sector
:param board: dictionary, containing board values
:return: board with moved rows
"""
sectors = {0: 'abc', 1: 'def', 2: 'ghi'}
rows = sectors[randint(0, 2)]
x = choice(rows)
rows = rows[:rows.find(x)] + rows[rows.find(x) + 1:]
y = choice(rows)
for z in '123456789':
temp = board[(x, int(z))]
board[(x, int(z))] = board[(y, int(z))]
board[(y, int(z))] = temp
return board
def columns_moving(board):
"""
Swaps two random columns in one sector
:param board: dictionary, containing board values
:return: board with moved columns
"""
sectors = {0: '123', 1: '456', 2: '789'}
columns = sectors[randint(0, 2)]
x = choice(columns)
columns = columns[:columns.find(x)] + columns[columns.find(x) + 1:]
y = choice(columns)
for z in 'abcdefghi':
temp = board[(z, int(x))]
board[(z, int(x))] = board[(z, int(y))]
board[(z, int(y))] = temp
return board
def cleaner(board):
"""
Hides random squares, leaves given amount of hints
:param board: dictionary, containing board values
:return: prepared board, start statistic
"""
stats = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, 'turn': 0}
i = 81 - int(input('Введите число подсказок (рекомендуется использовать числа в диапазоне от 30 до 35): '))
while i > 0:
a, b = choice(list('abcdefghi')), randint(1, 9)
if board[(a, b)] == '0':
continue
stats[board[(a, b)]] += 1
board[(a, b)] = '0'
i -= 1
return board, stats
def table(board, stats):
"""
Prints game board, statistics
:param board: dictionary, containing board values
:param stats: dictionary, containing game statistics
:return: None
"""
tree = board.copy()
for key in tree:
if tree[key] == '0':
tree[key] = ' '
simple = list(tree.values())
print('+---' * 9 + '+', '{: ^9s}'.format(''), '+{:-^7s}+'.format('Числа'))
for x in range(9):
print('|{:^3s}:{:^3s}:{:^3s}|{:^3s}:{:^3s}:{:^3s}|{:^3s}:{:^3s}:{:^3s}|'.format(*simple[x * 9:x * 9 + 9]),
ascii_lowercase[x], '{:^7s}'.format(''), '|{:^7s}|'.format(str(x + 1) + ': ' + str(stats[str(x + 1)])))
if x in [2, 5, 8]:
print('+---' * 9 + '+', '{:^9s}'.format(''), '+{:-^7s}+'.format(''))
else:
print('+...' * 9 + '+', '{:^9s}'.format(''), '+{:-^7s}+'.format(''))
print(' {:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}'.format(*[x for x in range(1, 10)]),
'{:^9s}'.format(''), '{:^9s}'.format('Ход: ' + str(stats['turn'])), '\n')
def turn(board, stats):
"""
Recursive function representing a game move
:param board: dictionary, containing board values
:param stats: dictionary, containing game statistics
:return: None
"""
try:
move = input().split()
key = list(move[0])[0], int(list(move[0])[1])
if len(move) == 1:
if board[key] != '0':
stats[board[key]] += 1
board[key] = '0'
else:
print('Клетка уже пуста. Попробуйте еще раз.')
return turn(board, stats)
else:
value = move[1]
if value not in '123456789':
print('Ошибка ввода. Попробуйте еще раз.')
return turn(board, stats)
if stats[value] == 0 and board[key] != value:
print('Ошибка. Данное число уже использовано 9 раз.')
return turn(board, stats)
if board[key] != '0':
stats[board[key]] += 1
board[key] = value
stats[value] -= 1
stats['turn'] += 1
table(board, stats)
if sum(stats.values()) - stats['turn'] == 0 and checker(board):
print('Поздравляем. Судоку решено за', stats['turn'], 'ходов.')
exit()
except KeyError:
print('Ошибка ввода. Попробуйте еще раз.')
return turn(board, stats)
return turn(board, stats)
def checker(board):
"""
Checks if board filled in correctly (with no repetitions)
:param board: dictionary, containing board values
:return: True or False
"""
lines = {}
for x in 'abcdefghi':
lines[x] = [board[(x, 1)]]
for y in range(2, 10):
lines[x].append(board[(x, y)])
for x in range(1, 10):
lines[x] = [board[('a', x)]]
for y in 'bcdefghi':
lines[x].append(board[(y, x)])
for line in list(lines.values()):
for z in range(1, 10):
if line.count(str(z)) > 1:
return False
return True
if __name__ == '__main__':
main()
|
dd4e4883ebadb8a6623e09f1da4eaafefb75d15c
|
mariomendonca/Solving-problems-python
|
/fibRecursivo.py
| 158 | 3.59375 | 4 |
def fib(n):
print(f'calculando fib de {n}')
if n <= 1:
return n
else:
return fib(n - 2) + fib(n - 1)
print(fib(7))
# fib(10)
# print(fib(100))
|
7d7df2aa2534244e01bc30880c5304bd0e98935a
|
mariomendonca/Solving-problems-python
|
/orientação_a_objetos/aula4.py
| 856 | 3.890625 | 4 |
class Mamifero(object):
def __init__(self, cor_de_pelo, genero, andar):
self.cor_de_pelo = cor_de_pelo
self.genero = genero
self.num_de_patas = andar
def falar(self):
print(f'ola sou um {self.genero} mamifero e sei falar')
def andar(self):
print(f'estou andando sobre {self.num_de_patas}')
def amamentar(self):
if self.genero.lower()[0] == 'm':
print('Machos nao amamentam')
return
print('amamentando meu filhote')
class Pessoa(Mamifero):
def __init__(self, cor_de_pelo, genero, andar, cabelo):
super(Pessoa, self).__init__(cor_de_pelo, genero, andar)
self.cabelo = cabelo
def falar(self):
super().falar()
print('ola sou um maifero sei falar')
# rex = Mamifero('marrom', 'm', 4)
# rex.amamentar()
# rex.andar()
# rex.falar()
julia = Pessoa('preto', 'f', 2, 'loiro')
julia.falar()
|
a68815a2b384a6cc5eff0b8879ce4688a48afd89
|
mariomendonca/Solving-problems-python
|
/expressoes_oo.py
| 1,748 | 3.6875 | 4 |
class No(object):
def __init__(self, dado=None):
self.dado = dado
self._proximo = None
self._anterior = None
def __str__(self):
return str(self.dado)
class Pilha(object):
def __init__(self):
self._inicio = None
self._fim = None
def isVazia(self):
if self._inicio == None:
return True
return False
def buscar_primeiro(self):
i = self._inicio
return i
def buscar(self, x):
i = self._inicio
while i != None:
if x == i._dado:
break
else:
i = i._proximo
return i
def push(self, dado=None):
novo_no = No(dado)
if self.isVazia():
self._fim = novo_no
else:
novo_no._proximo = self._inicio
self._inicio._anterior = novo_no
self._inicio = novo_no
def pop(self):
no = self._inicio
if not self.isVazia():
if no._proximo == None:
self._fim = None
else:
no._proximo._anterior = None
self._inicio = no._proximo
def __str__(self):
s = ''
i = self._inicio
while i != None:
s += f'{i}'
i = i._proximo
return s
n = int(input())
for i in range(n):
string = input()
pilha = Pilha()
for x in string:
if x == '(' or x == '{' or x == '[':
pilha.push(x)
elif x == ')':
if pilha.isVazia():
pilha.push(x)
elif str(pilha.buscar_primeiro()) == '(':
pilha.pop()
elif x == '}':
if pilha.isVazia():
pilha.push(x)
elif str(pilha.buscar_primeiro()) == '{':
pilha.pop()
elif x == ']':
if pilha.isVazia():
pilha.push(x)
elif str(pilha.buscar_primeiro()) == '[':
pilha.pop()
if pilha.isVazia():
print('S')
else:
print('N')
|
d5e0ba6271759bb746c8bef131ba5c8d8c006f17
|
mariomendonca/Solving-problems-python
|
/fatorialRecursivo.py
| 162 | 3.671875 | 4 |
def fatorial(n):
print(f'calculando fatorial de {n}')
if n <= 1:
return 1
else:
return n * fatorial(n - 1)
print(fatorial(1))
print(fatorial(7))
|
4a74596fba5738a6fc1ea4651c8b9b31527a7d99
|
mariomendonca/Solving-problems-python
|
/orientação_a_objetos/aula_professor.py
| 2,140 | 3.546875 | 4 |
class No(object):
def __init__(self, dado=None):
self.dado = dado
self._proximo = None
self._anterior = None
def __str__(self):
# return f'{self.dado}'
return str(self.dado)
class Lista(object):
def __init__(self):
self._inicio = None
self._fim = None
def isVazia(self):
if self._inicio == None:
return True
return False
def inserir_no_final(self, dado=None):
novo_no = No(dado)
if self.isVazia():
self._inicio = self._fim = novo_no
else:
novo_no._anterior = self._fim
self._fim._proximo = novo_no
self._fim = novo_no
def buscar(self, x):
i = self._inicio
while i != None:
if x == i.dado:
break
else:
i = i._proximo
return i
def remover(self, x):
no_encontrado = self.buscar(x)
if no_encontrado != None:
if no_encontrado._anterior != None:
no_encontrado._anterior._proximo = no_encontrado._proximo
else:
self._inicio = no_encontrado._proximo
if no_encontrado._proximo != None:
no_encontrado._proximo._anterior = no_encontrado._anterior
else:
self._fim = no_encontrado._anterior
return no_encontrado
def __str__(self):
s = ''
i = self._inicio
while i != None:
s += f' | {i}'
i = i._proximo
return s
class Pilha(Lista):
def push(self, dado=None):
novo_no = No(dado)
if self.isVazia():
self._fim = novo_no
else:
novo_no._proximo = self._inicio
self._inicio._anterior = novo_no
self._inicio = novo_no
def pop(self):
no = self._inicio
if not self.isVazia():
if no._proximo == None:
self._fim = None
else:
no._proximo._anterior = None
self._inicio = no._proximo
entrada = [4, 7, 17, 89, 2, 10, 99999]
pilha = Pilha()
for i in entrada:
pilha.push(i)
pilha.pop()
print(pilha)
# if __name__ == '__main__':
# minha_lista = Lista()
# for i in entrada:
# minha_lista.inserir_no_final(i)
# print(minha_lista)
# no = minha_lista.buscar(3)
# print(no)
# minha_lista.remover(99999)
# print(minha_lista)
|
5bdcb416f92937e245bd6860d09c119d2eaa1ca1
|
wxhheian/hpip
|
/ch9/ex9_1.py
| 641 | 3.953125 | 4 |
class Dog(): #一般来说类的首字母大写
"""一次模拟小狗的简单测试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令打滚"""
print(self.name.title() + " is rolled over")
my_dog = Dog('willie',6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
|
e40b364e777e48fcd98e4bb30cfdeb4aa55c8641
|
wxhheian/hpip
|
/ch3/ex3_2.py
| 755 | 3.703125 | 4 |
# motorcycles = ['honda','yamaha','suzuki']
# print(motorcycles)
# motorcycles[0] = 'ducati'
# print(motorcycles)
# motorcycles.append('ducati')
# print(motorcycles)
# motorcycles.insert(0,'ducati') #在索引0处插入元素‘ducati’
# print(motorcycles)
# motorcycles.insert(1,'ducati')
# print(motorcycles)
# del motorcycles[0]
# print(motorcycles)
# poped_motorcycle = motorcycles.pop(2) #pop()默认弹出最后一个 pop(2)弹出第3个
# print(motorcycles)
# print(poped_motorcycle)
motorcycles = ['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati') #根据具体的值删除 remove只删除第一个指定的值,如果有多个‘ducati’,需要要循环来删除
print(motorcycles)
|
0448e9274de805b9dec8ae7689071327677a6abb
|
wxhheian/hpip
|
/ch7/ex7_1.py
| 641 | 4.25 | 4 |
# message = input("Tell me something, and I will repeat it back to you: ")
# print(message)
#
# name = input("Please enter your name: ")
# print("Hello, " + name + "!")
# prompt = "If you tell us who you are,we can personalize the messages you see."
# prompt += "\nWhat is your first name? "
#
# name = input(prompt)
# print("\nHello, " + name + "!")
# age = input("How old are you? ")
# print(int(age)>= 18)
number = input("Enter a number, and I'll tell you if it's even or odd:")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even")
else:
print("\nThe number " + str(number) + " is odd.")
|
c017be82d19c5be167dc7d9dd51251756c3076bc
|
JapoDeveloper/think-python
|
/exercises/chapter7/exercise_7_3.py
| 1,405 | 3.9375 | 4 |
"""
Think Python, 2nd Edition
Chapter 7
Exercise 7.3
Description:
The mathematician Srinivasa Ramanujan found an infinite series that can be used
to generate a numerical approximation of 1/π:
https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2Fa1%2Ff5%2F81%2Fa1f581c7dc6c3c581a03902c15327ccb.jpg&f=1&nofb=1
Write a function called estimate_pi that uses this formula to compute and
return an estimate of π. It should use a while loop to compute terms of the
summation until the last term is smaller than 1e-15
(which is Python notation for 10**-15).
You can check the result by comparing it to math.pi.
"""
import math
def factorial(n):
"""calculate the factorial of a non-negative integer number"""
if type(n) is not int or n < 0:
print('Only non-negative integers are accepted.')
return
if n == 0:
return 1
return n * factorial(n-1)
def estimate_pi():
"""compute an approximation of pi"""
k = 0
total = 0
epsilon = 1e-15
factor = 2 * math.sqrt(2) / 9801
while True:
num = factorial(4*k) * (1103 + 26390 * k)
den = factorial(k)**4 * 396**(4*k)
term = factor * num / den
total += term
if term < epsilon:
break
k += 1
return 1 / total
print('Estimation of pi :', estimate_pi())
print('Math module pi value:', math.pi)
|
856461a845a16813718ace33b8d2d5782b0d7914
|
JapoDeveloper/think-python
|
/exercises/chapter6/exercise_6_3.py
| 1,891 | 4.40625 | 4 |
"""
Think Python, 2nd Edition
Chapter 6
Exercise 6.3
Description:
A palindrome is a word that is spelled the same backward and forward,
like “noon” and “redivider”. Recursively, a word is a palindrome if the first
and last letters are the same and the middle is a palindrome.
The following are functions that take a string argument and return the first,
last, and middle letters:
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
We’ll see how they work in Chapter 8.
1) Type these functions into a file named palindrome.py and test them out.
What happens if you call middle with a string with two letters? One letter?
What about the empty string, which is written '' and contains no letters?
2) Write a function called is_palindrome that takes a string argument and returns
True if it is a palindrome and False otherwise. Remember that you can use the
built-in function len to check the length of a string.
"""
from palindrome import *
def is_palindrome(word):
if len(word) <= 1:
return True
elif first(word) == last(word):
return is_palindrome(middle(word))
else:
return False
print(first('Hello')) # H
print(middle('Hello')) # ell
print(last('Hello')) # o
# What happens if you call middle with a string with two letters?
print(middle('ab')) # empty string is returned
# One letter?
print(middle('a')) # empty string is returned
# What about the empty string, which is written '' and contains no letters?
print(middle('')) # empty string is returned
print('Are palindromes?:')
print('noon', is_palindrome('noon')) # Yes
print('redivider', is_palindrome('redivider')) # Yes
print('a', is_palindrome('a')) # Yes
print('empty string', is_palindrome('')) # Yes
print('night', is_palindrome('night')) # No
print('word', is_palindrome('word')) # No
|
12af2132a90d11fbe573827f34f16bfa675402b8
|
JapoDeveloper/think-python
|
/exercises/chapter1/exercise1_2.py
| 986 | 3.96875 | 4 |
"""
Think Python, 2nd Edition
Chapter 1
Exercise 1.2
Description: try math operations and answer the questions
"""
# 1) How many seconds are there in 42 minutes 42 seconds?
print(42 * 60 + 42) # 2,562 seconds
# 2) How many miles are there in 10 kilometers?
# Hint: there are 1.61 kilometers in a mile.
print(10 / 1.61) # 6.21 miles
# 3) If you run a 10 kilometer race in 42 minutes 42 seconds,
# what is your average pace (time per mile in minutes and seconds)?
# What is your average speed in miles per hour?
race_in_miles = 10 / 1.61
race_time_in_sec = (42 * 60 + 42)
total_mile_time_in_sec = race_time_in_sec / race_in_miles
time_per_mile_in_min = int(total_mile_time_in_sec // 60)
time_per_mile_in_sec = total_mile_time_in_sec % 60
print('Average pace: {} minutes {:.2f} seconds'
.format(time_per_mile_in_min, time_per_mile_in_sec))
race_time_in_hr = race_time_in_sec / 3600
speed = race_in_miles / race_time_in_hr
print('Average speed: {:.2f} mi/h'.format(speed))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.