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 |
|---|---|---|---|---|---|---|
e5ce39c12304f06f6abc8433752593ce3b611381 | hungair0925/note-toy-program | /TerminalBookShelf/book_shelf.py | 1,390 | 3.8125 | 4 | class BookShelf:
def __init__(self, name):
self.bk_sh = {}
self.name = name
def __str__(self):
message = "本棚[{0}]".format(self.name)
return message
def add_book(self, title, author):
self.bk_sh[title] = author
print("追加したよ( ̄・ω・ ̄)")
def list_book(self):
if len(self.bk_sh) == 0:
print("棚には何も追加されていません")
else:
print("{0:<10}| {1:<15}".format("Title", "Author"))
print("{0}".format("-"*25))
for title, author in self.bk_sh.items():
print("{0}| {1}".format(title, author))
print("{0}".format("-"*25))
def remove_book(self, title):
del_flag = int(input("削除していいの(´・ω・`)?[0:NG/1:OK]"))
if del_flag:
rm_book_author = self.bk_sh.pop(title)
print("{0}(著):{1}を削除しました".format(rm_book_author, title))
else:
pass
#インスタンス
shelf = BookShelf("お気に入り") #インスタンスしたオブジェクトの名前
print(shelf) #追加
shelf.add_book("論語と算盤", "渋沢栄一")
shelf.add_book("脳・心・人工知能", "甘利俊一")
shelf.add_book("留魂録", "吉田松陰") #一覧表示
shelf.list_book() #削除
shelf.remove_book("留魂録")
|
47d3da207a88d5a2da4b9048427e0ae04c7f1f37 | benwhale/word-squares | /word_squares/solver/recursive_solver.py | 9,218 | 3.8125 | 4 | from word_squares.solver.solver_util import SolverUtil
class RecursiveSolver:
"""Recursive solver class which traverses the grid and builds a solution"""
def __init__(self, dimension, letters, dawg, grid):
self.dimension = dimension
self.letters = letters
self.dawg = dawg
self.grid = grid
def generate_solution(self):
"""
Makes the initial call to solve to kick off the recursive solving process.
:return: Populated numpy array or False
"""
return self.solve(
word_no=0,
letter_no=0,
remaining_letters=self.letters,
grid=self.grid.copy(),
)
def solve(self, word_no, letter_no, remaining_letters, grid):
"""
Recursive solving function to traverse the grid.
Retrieves the prefixes for which go through this space on the grid.
Iterates through the available letter choices and retrieves valid words combining the prefixes with the letter
If there are valid words on both the vertical and horizontal axes, attempt to place the letters and move to the
next space in the solution if successful. Returns False if there are no valid letters which can be placed at all
or returns the result of the recursive calls to solved.
"""
horizontal_prefix = self.get_horizontal_prefix(word_no, grid)
vertical_prefix = self.get_vertical_prefix(letter_no, grid)
search_letters = self.get_unique_letters(remaining_letters)
for letter in search_letters:
# Candidate for refactoring into child method
# Find potential words starting with the prefixes
# which can be made by the letters available
horiz_words, vert_words = self.find_valid_words(
letter, horizontal_prefix, vertical_prefix
)
if len(horiz_words) == 0 or len(vert_words) == 0:
# Exit iteration - no valid words in either the horizontal or vertical for this letter choice
continue
try:
# Attempt to place letters in grid, raising an error when we do not have enough of the letter to place
updated_grid, solution_remaining_letters = self.place_letter(
word_no, letter_no, letter, remaining_letters, grid.copy()
)
except ValueError:
# Exit iteration - We have tried to place more of a letter than there are remaining
continue
# proceed to next recursive solution stage
solution = self.proceed_with_solution(
letter_no, word_no, solution_remaining_letters, updated_grid
)
if solution is False:
continue # Exit iteration - No solution down this route, so back up a step
else:
return solution # Solution has been found, so bubble it up
return False # We have reached the end of the letter iteration and there are no valid letters
def proceed_with_solution(
self, letter_no, word_no, solution_remaining_letters, updated_grid
):
"""
Checks which letter we are on and works out which letter to solve for next.
If we are mid way through a word, we try and complete that word with the next letter
If we have completed a word, we move to the next word where there is one, and start at
the first unfinished letter.
Otherwise, we have filled in every slot and can return our solution up the chain.
"""
if letter_no < self.dimension - 1:
# Attempt to complete a given word first
return self.solve(
word_no,
letter_no + 1,
solution_remaining_letters,
updated_grid.copy(),
)
elif word_no < self.dimension - 1:
# Move onto the next word
return self.solve(
word_no + 1,
word_no + 1,
solution_remaining_letters,
updated_grid.copy(),
)
elif word_no == self.dimension - 1 and letter_no == self.dimension - 1:
# We have successfully completed the final letter
return updated_grid # Return the final numpy array
def find_valid_words(self, letter, horizontal_prefix, vertical_prefix):
"""
Gets words matching both the horizontal and vertical prefixes, and filters to only include words which can be
made by the remaining letters.
:param letter: the character to add to the prefix
:param horizontal_prefix: the horizontal prefix representing the letters placed in a row so far
:param vertical_prefix: the vertical prefix representing the letters placed in a column so far
:return: a tuple containing two lists with the matching horizontal and vertical words in them.
"""
horiz_words = SolverUtil.get_words_matching_prefix(
self.dawg, (horizontal_prefix + letter)
)
vert_words = SolverUtil.get_words_matching_prefix(
self.dawg, (vertical_prefix + letter)
)
# TODO is there is a better approach which passes in the remaining letters and current prefix
horiz_words = list(self.filter_words_to_contain_letters(horiz_words))
vert_words = list(self.filter_words_to_contain_letters(vert_words))
return horiz_words, vert_words
def place_letter(self, word_no, letter_no, letter, remaining_letters, grid):
"""
Attempts to place letters in the current slot, and in it's mirror on the diagonal axis.
If it is the diagonal axis then we only place the one. Placed letters are removed from the list.
If this fails due to there not being enough letters to remove, we raise the ValueError onwards so
that the parent method can handle it
:param word_no: The current word number we are solving
:param letter_no: The current letter number we are solving
:param letter: The letter we are trying to place
:param remaining_letters: The remaining letters available to place
:param grid: The grid to place letters into
:return: Updated grid and remaining letters if successful, raised ValueError if not
"""
if word_no == letter_no:
# We are on the diagonal axis, so there will only be one letter placed
grid[word_no, letter_no] = letter
try:
letter_list = list(remaining_letters)
letter_list.remove(letter)
new_remaining_letters = "".join(letter_list)
except ValueError:
raise
else:
grid[word_no, letter_no] = letter
grid[letter_no, word_no] = letter
try:
letter_list = list(remaining_letters)
letter_list.remove(letter)
letter_list.remove(letter)
new_remaining_letters = "".join(letter_list)
except ValueError:
raise
return grid, new_remaining_letters
def filter_words_to_contain_letters(self, word_list):
"""
First cut of a generator function to reduce the number of options to eliminate words
which don't exist in the letter set.
Will miss lots of invalid ones, but it's a start.
Could do with a refactor to use the prefixes / remaining letters
"""
for word in word_list:
sorted_letters = sorted(self.letters)
# Copy of letters string in list form
for letter in word:
try:
sorted_letters.remove(letter)
except ValueError:
break
else:
# Runs when the loop is complete without breaking out
yield word
def get_horizontal_prefix(self, row_no, grid):
"""
TODO - move to util
Retrieves the currently generated prefix by joining the values in the specified row
:param row_no: the row number to retrieve the prefix from
:param grid: the grid to retrieve from
:return: string containing the generated prefix
"""
row = grid[row_no]
return "".join(row)
def get_vertical_prefix(self, col_no, grid):
"""
TODO - move to util
Retrieves the currently generated prefix by joining the values in the specified row
:param col_no: the column number to retrieve the prefix from
:param grid: the grid to retrieve from
:return: string containing the generated prefix
"""
col = grid[:, col_no]
return "".join(col)
def get_unique_letters(self, letters):
"""
TODO - move to util
Turns a string into an alphabetically sorted list with a single instance of each character.
To be used for the letter iteration as we only want to try each letter once per iteration.
Putting it back into a sorted list allows for more predictability
"""
return sorted(list(set(letters)))
|
0ff2709b707158fcad9441d591b13a5964abeac5 | naveens33/python_tutorials | /strings/example3.py | 198 | 3.546875 | 4 | # split function extended behaviour
name = "MS Dhoni"
print(name.split())
print(name.split(' '))
# if you are not provided anything inside the split, then it will split according to any whitespace,
|
1f711a10d7b490fe9fb1fb838c86ffe6ec65baee | naveens33/python_tutorials | /Misc/assert_statement.py | 166 | 3.671875 | 4 | # Assertion vs Verification
'''
age = 15
if age == 18:
print("Yes")
print("Thanks for using code")
'''
age = 15
assert age == 18
print("Thanks for using code")
|
a912bca81664abc29b5a09b287d8dffab28478bd | naveens33/python_tutorials | /conditional_statements/ifelse_statement.py | 148 | 3.53125 | 4 | if __name__=='__main__':
age = int(input("Enter the age: "))
if age >= 18:
print("Eligible")
else:
print("Not Eligible") |
763643acc64451c58fd791f3618c6e3dbb9a865e | naveens33/python_tutorials | /strings/example2.py | 454 | 3.734375 | 4 | # Swap Case without using method
text = "Process Finished With Exit Code 0"
result = ""
for i in range(len(text)):
if text[i].isupper():
result += text[i].lower()
elif text[i].islower():
result += text[i].upper()
else:
result += text[i]
print(result)
name = "Mr. Karthick BA. BL."
#print(name.swapcase())
ans = ""
for c in name:
if c.isupper():
ans = ans+c.lower()
else:
ans = ans+c.upper()
print(ans) |
db5d5360c56a47f44c1b9615e1cc389c144d5fe5 | naveens33/python_tutorials | /list_tuple_set_dict/dict_functions.py | 295 | 3.578125 | 4 | d={"Name":"John","Class":2,"Rank":1,"FeeStatus":["paid","paid","paid"]}
#get
print(d.get("FeeStatus"))
print(d["FeeStatus"])
#dict item related fucntions
print(d.keys())
print(d.values())
print(d.items())
#popitem pop del
d.popitem()
print(d)
d.pop("Class")
print(d)
del(d["Name"])
print(d) |
0f5f7eac09fdeaecee1f50e3a4422e78f546fceb | naveens33/python_tutorials | /looping_statements/exmaple6.py | 273 | 3.9375 | 4 | #Triangle pattern *
if __name__=='__main__':
n=6
for i in range(1,n):
for k in range(i,n-1):
print(' ',end="")
for j in range(i):
print('*',end="")
for j in range(i-1):
print('*',end="")
print()
|
4c6c163680bf31b7f34dce1957a1b458315578a3 | naveens33/python_tutorials | /list_comprehension/example1.py | 187 | 3.9375 | 4 | sentence = "amazing"
#print(list(sentence))
'''
li = []
for c in sentence:
li.append(c)
print(li)
'''
#Syntax
#[expression for item in items]
li = [c for c in sentence]
print(li)
|
76e3e82c3817f367155bfc53d2257e2a8a2c24ae | naveens33/python_tutorials | /list_comprehension/example6.py | 104 | 3.921875 | 4 | # Find the cube of numbers in a list
li = [5, 3, 6, 8, 2, 0, 7, 1]
li = [i ** 3 for i in li]
print(li)
|
8f1f43ea4e81107852b2e40178d2a4978bb20c09 | estineali/RISC_V_Simulation | /LabWeek7/Lab04/Task1/randomBitGen.py | 654 | 3.53125 | 4 | import random
array_name = "Registers" ##Name of array of registers
register_len = 64 ##size of each register in that array
file_len = 32 ## Number of registers in the array
number_systems = {2 : ["'b", 2], 8 : ["'o", 8], 10 : ["'d", 10], 16 : ["'h", 16]} ##Work in progress
selected_base = 2 ## a part of the work in progrss.
##Dont Bother with the Code Below.
for i in range(file_len):
x = array_name + "[" + str(i) + "] <= " + str(register_len) + number_systems[selected_base][0]
for j in range(register_len):
temp = random.randint(0, 1000) % number_systems[selected_base][1]
if i == 0:
temp = 0
x += str(temp)
x += ";"
print(x)
|
efe78ea947d5f580d38c9684d67349b3ce4abeee | victoire4/Introductory-Programming-with-Python | /Exercise5.py | 370 | 3.671875 | 4 | import math as m
S=2117519.73
xo=2000
EV=m.sqrt(S)
Xn=1/2*(xo+(S/xo))
n=0
print("S=",S)
print("The exact answer to square root of S is",EV)
print("When we use Hero's method, we have:")
while EV!=Xn :
Xn=1/2*(Xn+(S/Xn))
n+=1
print("X",n,"=",Xn)
print("For the number S, the answer is the same that the exact answer after",n,"compute by the Hero's method.")
|
044227e03794710c8377b8e77a8699d12f35cbcc | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-1/EXs/EX014.py | 137 | 3.859375 | 4 | c = float(input('Informe a temperatura em °C: '))
f = ((9*c)/5) + 32
print('A temperatura correspondente a {}°C é {}°F'.format(c, f)) |
956348c08220ff07108152d7a8b76618ad9a03a2 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-2/EXs/EX038.py | 272 | 4 | 4 | num1 = int(input('Digite o 1º número: '))
num2 = int(input('Digite o 2º número: '))
if num1 > num2:
print('O {} é maior que {}'.format(num1, num2))
elif num1 < num2:
print('O {} é maior que4 {}'.format(num2, num1))
else:
print('Os números são iguais')
|
6dec8ea622eaa11c427254df9a7ce44d5d5241a2 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-2/EXs/EX061.py | 215 | 3.796875 | 4 | termo = int(input('Primeiro termo: '))
razão = int(input('Razão: '))
cont = 0
while cont < 10:
print('{}'.format(termo), end='')
print(' >> ' if cont < 9 else '', end='')
cont += 1
termo += razão
|
bcf0ea0073f1ff6635e224542e025db935224de2 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-3/EXs/EX079.py | 413 | 4.15625 | 4 | numeros = []
while True:
num = int(input('Digite um número: '))
if num in numeros:
print(f'O número {num} já existe na lista, portanto não será adicionado')
else:
numeros.append(num)
continuar = str(input('Quer adicionar mais um número na lista? S/N ')).upper()
if continuar == 'N':
break
numeros.sort()
print(f'Os números adicionado a lista foram: {numeros}')
|
f97586be28e08bfc87a74a7a28c0b3e60764c999 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-1/EXs/EX004.py | 390 | 4 | 4 | algo = input('Digite algo: ')
print('''O tipo primitivo do que foi digitado é {},
Só tem espaço? {};
É um número? {};
É alfabético? {};
É alfanumérico? {};
Está em letras maiúsculas? {};
Está em letras minusculas? {};
Está capitalizada? {}.'''.format(type(algo), algo.isspace(), algo.isnumeric(), algo.isalpha(), algo.isalnum(), algo.isupper(), algo.islower(), algo.istitle())) |
df0974adbb3ceadeaabb40abcc0ef8409a2fa27b | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-3/EXs/EX085.py | 377 | 3.875 | 4 | numeros = [[], []]
for n in range(0, 7):
num = int(input(f'Digite o {n+1}º número: '))
if num % 2 == 0:
numeros[0].append(num)
else:
numeros[1].append(num)
print(f'Números adicionados à lista: {numeros}')
print(f'Números pares adicionados à lista: {numeros[0]}')
print(f'Números impares adicionados à lista: {numeros[1]}')
|
da100cf4a30bed21264a673ed585ce508ca89115 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-2/EXs/EX037.py | 579 | 4.1875 | 4 | num = int(input('Digite um número inteiro qualquer: '))
print('''Escolha uma base de conversão:
[1] Converter para Binário
[2] Converter para Octal
[3] Converter para Hexadecimal''')
escolha = int(input('Converter para: '))
if escolha == 1:
print('{} convertido para Binário é igual a {}'.format(num, bin(num) [2:]))
elif escolha == 2:
print('{} convertido para Octal é igual a {}'.format(num, oct(num)[2:]))
elif escolha == 3:
print('{} convertido para Hexadecimal é igual a {}'.format(num, hex(num)[2:]))
else:
print('Escolha invalida, tente novamente!') |
e8df8f6730c4083dc53a4ccd472ff26b85e89e01 | victor-da-costa/Aprendendo-Python | /Curso-Em-Video-Python/Mundo-2/EXs/EX054.py | 335 | 3.84375 | 4 | from datetime import date
atual = date.today().year
maior = 0
menor = 0
for nasc in range(1, 8):
ano = int(input('Em que ano a {}º nasceu? '.format(nasc)))
idade = atual - ano
if idade >= 18:
maior += 1
else:
menor += 1
print('{} pessoas são de menor e {} são maiores de idade!'.format(menor, maior)) |
c409417437ec4b8179f981f20b731c3c06199435 | Vslamer/1_DL_CV_Book | /1_python_tutorial/5.function.py | 1,788 | 4.09375 | 4 | def say_hello():
print("hello chenyong")
def greetings(x='good morning'):
print(x)
say_hello()
greetings()
greetings("cao ni")
a=greetings()
def create_a_list(x,y=2,z=3):
return [x,y,z]
b=create_a_list(1)
c=create_a_list(3,3)
d=create_a_list(6,7,8)
print(b,'\n',c,'\n',d)
#*args是可变参数,args接收的是一个tuple,
#可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple
def traverse_args(*args):
for arg in args:
print(arg)
traverse_args(1,2,3)
traverse_args('a','b','v','d')
def traverse_kargs(**kwargs):
#for i,j in kwargs.items():
print(kwargs)
for i,j in kwargs.items():
print(i,j)
traverse_kargs(x=3,y=4,z=5)
traverse_kargs(fig='f',f2='r')
def foo(x,y,*args,**kwargs):
print(x,y)
print(args)
print(kwargs)
foo(1,2,3,4,5,a=6,b='bar')
#有些情况下函数也可以当成一个变量使用
moves=['up','left','down','right']
coord=[0,0]
for move in moves:
if move=='up':
coord[1]+=1
print(coord)
elif move=='down':
coord[1]-=1
print(coord)
elif move=='right':
coord[0]+=1
print(coord)
elif move =='left':
coord[0]-=1
print(coord)
else:
pass
print(coord)
def move_up(x):
x[1]+=1
def move_down(x):
x[1]-=1
def move_left(x):
x[0]-=1
def move_right(x):
x[0]+=1
actions={'up':move_up,'down':move_down,'left':move_left,'right':move_right}
coord=[0,0]
for move in moves:
actions[move](coord)
print('函数版本:\n',coord)
def get_val_at_pos_1(x):
return x[1]
heros=[('superman',99),('bataman',100),('jker',95)]
#d=sorted(a.iteritems(),key=itemgetter(1)) 字典
sorted_pairs0=sorted(heros,key=get_val_at_pos_1)
sorted_pairs1=sorted(heros,key=lambda x: x[1])
print(sorted_pairs0)
print(sorted_pairs1)
som_ops=lambda x,y: x+y+x*y+x**y
result=som_ops(2,3)
print(result) |
15c14dc1cb66a93e1374f7deaeed40b558242142 | Vslamer/1_DL_CV_Book | /1_python_tutorial/13.plt.py | 798 | 3.78125 | 4 | import numpy.random as random
random.seed(42)
n_tests=10000
winning_doors=random.randint(0,3,n_tests)
change_mind_wins=0
insist_wins=0
for winning_door in winning_doors:
first_try=random.randint(0,3)
remaining_choices=[i for i in range(3) if i!=first_try]
wrong_choices=[i for i in range(3) if i!=winning_door]
if first_try in wrong_choices:
wrong_choices.remove(first_try)
screened_out=random.choice(wrong_choices)
remaining_choices.remove(screened_out)
changed_mind_try=remaining_choices[0]
change_mind_wins+=1 if changed_mind_try==winning_door else 0
insist_wins+=1 if first_try==winning_door else 0
print('you win {1} out of {0} tests if you changed your mind \n '
'you win {2} out of {0} tsts if you insist on the initial choice'.format
(n_tests,change_mind_wins,insist_wins)) |
62e30686d10a88934fce06bbc457f08e5390152e | sramirezh/Corona_crawler | /Covid_19_v2.py | 4,490 | 3.578125 | 4 | #!/Users/simon/opt/anaconda3/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 11:51:27 2020
Code based on:
https://towardsdatascience.com/web-scraping-html-tables-with-python-c9baba21059
@author: simon
"""
import requests
import lxml.html as lh
import pandas as pd
import numpy as np
def get_main_table(url):
"""
Gets a table from url
Args:
url of the website containing the table
Return:
df pandas dataframe
"""
global tr_elements,doc,page
#Create a handle, page, to handle the contents of the website
page = requests.get(url)
#Store the contents of the website under doc
doc = lh.fromstring(page.content)
#Parse data that are stored between <tr>..</tr> of HTML
tr_elements = doc.xpath('//tr')
# =============================================================================
# Getting the header
# =============================================================================
# parse the first row as our header.
#Create empty list
col=[]
i=0
#For each row, store each first element (header) and an empty list
for t in tr_elements[0]:
i+=1
name = t.text_content()
col.append((name,[]))
# =============================================================================
# Creating Pandas data frame
# =============================================================================
#Since out first row is the header, data is stored on the second row onwards
for j in range(1,len(tr_elements)):
#T is our j'th row
T = tr_elements[j]
# #If row is not of size 10, the //tr data is not from our table
# if len(T)!=10:
# break
#
#i is the index of our column
i=0
#Iterate through each element of the row
for t in T.iterchildren():
data = t.text_content()
#Check if row is empty
if i>0:
#Convert any numerical value to integers
try:
data=int(data)
except:
pass
#Append the data to the empty list of the i'th column
col[i][1].append(data)
#Increment i for the next column
i+=1
Dict={title:column for (title,column) in col}
df=pd.DataFrame(Dict)
return df
def longest_per_column(table, header):
"""
returns the length of the longest string in the column
"""
total = []
for i,name in enumerate(header):
lengths = []
column = table[:,i]
for row in column:
lengths.append(len(str(row)))
lengths.append(len(name))
total.append(np.max(lengths))
return total
df = get_main_table('https://www.worldometers.info/coronavirus/')
header = df.columns[:4]
# Dummy column to sort
df[header[1]] = df[header[1]].astype(str) # to be able to use next line
df['sort_column'] = df[header[1]].str.replace(',','', regex=True)
table = df.values
#TODO df has twice the same table, check the tr_elements
index = np.where(table == header[0])[0][0] # The table repeats itself here
table = table[:index,:]
table[:,-1] = table[:,-1].astype(float)
df2 = pd.DataFrame(table)
# Sorting the table based on the total cases
table = table[table[:,-1].argsort()][::-1]
# Working on the top 10
lengths = longest_per_column(table[:11,:4],header)
target_country = 'Colombia'
ind_target = np.where(table[:,0] == target_country)[0][0]
print ("\u001b[1m C-19\n") #http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html
# Getting the longest string
print(f"{header[0]:<{lengths[0]}}\t{header[1]:<{lengths[1]}}\t{header[2]:<{lengths[2]}}\t{header[3]:<{lengths[3]}}") #https://stackoverflow.com/questions/8234445/python-format-output-string-right-alignment
print (f"{table[1][0]:<{lengths[0]}}\t{table[1][1]:<{lengths[1]}}\t{table[1][2]:<{lengths[2]}}\t{table[1][3]:<{lengths[3]}}")
print("---")
for i in range(2,11):
print (f"{table[i][0]:<{lengths[0]}}\t{table[i][1]:<{lengths[1]}}\t{table[i][2]:<{lengths[2]}}\t{table[i][3]:<{lengths[3]}}") #https://realpython.com/python-f-strings/
print("---")
i = ind_target
print (f"{table[i][0]:<{lengths[0]}}\t{table[i][1]:<{lengths[1]}}\t{table[i][2]:<{lengths[2]}}\t{table[i][3]:<{lengths[3]}}| color=orange")
|
d6e4880fd81231918ca9c02a03b622a1f1d43151 | GitSmurff/LABA-2-Python | /laba8/laba2.py | 238 | 3.953125 | 4 | import datetime
day = int(input("Введите день "))
month = int(input("Введите месяц "))
year = int(input("Введите год "))
d = datetime.date(year, month, day)
print(d.day, d.month, d.year)
|
9a16c181418ba0fb5d6118d89d95a179942b7f05 | GitSmurff/LABA-2-Python | /laba6/laba1.py | 1,002 | 4.21875 | 4 | import abc
class Abstract(abc.ABC):
@abc.abstractmethod
def __init__(self, x):
self.x = 0
class Queen(Abstract):
def __init__(self):
self.x = int(input('Введите число от 1 до 9: '))
if self.x >= 1 and self.x <= 3:
s =str(input("Введите строку: "))
n = int(input("Введите число повторов строки: "))
i = 0
while i < n:
print (s)
i += 1
elif self.x >= 4 and self.x <= 6:
m = int(input("Введите степень, в которую следует возвести число: "))
print(self.x**m)
elif self.x >= 7 and self.x <= 9:
i = 0
while i < 10:
self.x += 1
i += 1
print(self.x)
else:
print("Ошибка ввода!")
return self.x
x = Queen()
|
eb2672431ec79ee7a316806869318e8a586a5635 | GitSmurff/LABA-2-Python | /Laba4/mathpack/gg1.py | 306 | 3.65625 | 4 | def gg1():
x = int(input("Введите число от 4 до 6: "))
if x >= 4 and x <= 6:
m = int(input("Введите степень, в которую следует возвести число: "))
print(x**m)
else:
print("Ошибка ввода!")
|
5a80d705ec034b8139ca4c32beefff2f2852bf7c | pymatix/pyhton | /display logarithmic values for user input.py | 128 | 3.734375 | 4 | import math
x=int(input("enter a numeric value to find log:"))
print (math.log(x))
print (math.log(x,10))
print (math.log10(x))
|
8ad193780c081b95b0ff9129ec6c43b1c8b8d0a7 | jlglearn/Code | /heap.py | 2,058 | 3.71875 | 4 | HeapLeft = lambda i : i*2;
HeapRight = lambda i : i*2+1;
HeapParent = lambda i : i//2;
class Heap:
def __init__(self):
self.A = [];
self.nElements = 0;
def Value(self, i):
assert((i > 0) and (i <= self.nElements));
return self.A[i-1]['key'];
def Swap(self, i, j):
assert((i > 0) and (i <= self.nElements) and (j > 0) and (j <= self.nElements));
t = self.A[i-1];
self.A[i-1] = self.A[j-1];
self.A[j-1] = t;
def HeapifyDown(self, i):
l = HeapLeft(i);
r = HeapRight(i);
m = i;
if ((l <= self.nElements) and (self.Value(l) < self.Value(i))):
m = l;
if ((r <= self.nElements) and (self.Value(r) < self.Value(m))):
m = r;
if m == i: return;
self.Swap(m, i);
self.HeapifyDown(m);
def HeapifyUp(self, i):
if i == 1:
return;
p = HeapParent(i);
l = HeapLeft(p);
r = HeapRight(p);
m = p;
if ((l <= self.nElements) and (self.Value(l) < self.Value(p))):
m = l;
if ((r <= self.nElements) and (self.Value(r) < self.Value(m))):
m = r;
if m == p:
#parent strictly less than children, done
return;
self.Swap(m, p);
self.HeapifyUp(p);
def Element(self, i):
return self.A[i-1];
def Insert(self, key, data):
self.A.append({'key':key, 'data':data});
self.nElements += 1;
self.HeapifyUp(self.nElements);
def Empty(self):
return self.nElements == 0;
def Pop(self):
assert(self.nElements > 0);
x = self.Element(1);
self.Swap(1, self.nElements);
del self.A[self.nElements-1];
self.nElements -= 1;
self.HeapifyDown(1);
return x;
|
2a265aa3683301252b6193920c57da2eb8ef943d | Amel294/amel | /ml/sddsds/ml5.py | 569 | 3.578125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
data=pd.read_csv("/home/ai31/Desktop/common/ML/Day3/Questions/city.csv")
#print(data)
#print(data.head())
data=data.as_matrix()
x=data[:,[2,3,4,5]]
y=data[:,[-2]]
print(x)
print(y)
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
lr=LinearRegression()
lr.fit(x_train,y_train)
p=lr.predict(x_test)
plt.scatter(y_test,p)
plt.show()
|
16d142413e3b150cc842b9efe5032a44076eb3c3 | Amel294/amel | /nlp/ass2/q1.py | 180 | 3.578125 | 4 | #!/usr/bin/python
from textblob import Word
theword = Word("watch")
print(theword.pluralize())
from textblob import Word
theword = Word("watches")
print(theword.singularize())
|
37f3a5d3adbb3eda568f72b34bd44e8264e59fb8 | Amel294/amel | /python/bank.py | 369 | 3.65625 | 4 | class bank:
def add(self):
us=1
a=self.acno=input('\n Enter account number:\t')
b=self.acbal=input('\n Enter account bal\t')
c=self.acno=raw_input('\n Enter account type:\t')
d=self.noac=input('\n number of accounts:\t')
e=self.aname=raw_input('\n name:\t')
f=self.addre=raw_input('\n address:\t')
li=[us,a,b,c,d,e,f]
print li
x=bank()
x.add()
|
159fe63cfca5b1d83c6a412528be3abdd77371f5 | Amel294/amel | /python/day9/q1.py | 285 | 3.71875 | 4 | #!/usr/bin/python
class vect:
def __init__(self,px,py):
self.x=px
self.y=py
def dispv(self):
print"(%f,%f)"%(self.x,self.y)
def __add__(self,a):
newx=self.x+a.x
newy=self.y+a.y
return vect(newx,newy)
v1=vect(10,5)
v2=vect(5,10)
v3=v1+v2
v1.dispv()
v2.dispv()
v3.dispv()
|
afe5c40fa2cd2030009b7f5a211b21516a8b19a3 | kaiyaprovost/algobio_scripts_python | /prob21_mergeSort_full.py | 1,074 | 3.734375 | 4 | def mergeSort(n,array):
x = ""
if n > 1:
mid = n//2
left = array[:mid]
right = array[mid:]
mergeSort(len(left),left)
mergeSort(len(right),right)
i=0
j=0
k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k]=left[i]
i += 1
else:
array[k]=right[j]
j += 1
k += 1
while i < len(left):
array[k]=left[i]
i += 1
k += 1
while j < len(right):
array[k]=right[j]
j += 1
k += 1
infile = open("C:/Users/Kaiya/Desktop/rosalind_inv.txt","rU")
n = infile.readline()
array = infile.readline()
infile.close()
n = int(n.strip())
array = array.split()
array = [int(x) for x in array]
mergeSort(n,array)
#print array
outfile = open("C:/Users/Kaiya/Desktop/rosalind_inv_ans.txt","w")
for i in array:
print >>outfile, i,
outfile.close()
|
0f626ce09d8e57b18275baa874f0917abdc21c97 | kaiyaprovost/algobio_scripts_python | /prob27_rootedtrees.py | 501 | 4 | 4 | import math
## num rooted trees:
## (2n - 3)!!
## =
## (2n - 3)! / (n-2)! * 2^(n-2)
## math.factorial(2n - 4)
## /
## math.factorial(n-2) * math.pow(2,(n-2))
n = int(input("number of leaves: "))
def rootTreeCalc(n):
num = int(math.factorial(2*n - 3))
den = int(math.factorial(n-2)) * int(math.pow(2,(n-2)))
root = num/den
return root
print rootTreeCalc(n) % 1000000
print "---"
##for n in range(2,18):
## ans = rootTreeCalc(n) % 1000000
## print ans
|
3ed6e13c885c7e666fd318e32e3b20278581df18 | kaiyaprovost/algobio_scripts_python | /windChill.py | 1,076 | 4.1875 | 4 | import random
import math
def welcome():
print("This program computes wind chill for temps 20 to -25 degF")
print("in intervals of 5, and for winds 5 to 50mph in intervals of 5")
def computeWindChill(temp,wind):
## input the formula, replacing T with temp and W with wind
wchill = 35.74 + 0.6215*temp - 35.75*(wind**0.16) + 0.4275*temp*(wind**0.16)
return(wchill)
def main():
welcome() #Print a message that explains what your program does
#Print table headings:
for temp in range(20, -25, -5):
print "\t",str(temp),
print
#Print table:
for wind in range(5,55,5): #For wind speeds between 5 and 50 mph
print wind,"\t", #Print row label
for temp in range(20, -25, -5): #For temperatures between 20 and -20 degrees
wchill = computeWindChill(temp, wind)
print wchill,"\t", #Print the wind chill, separated by tabs
print #Start a new line for each temp
main()
|
dc12be1a75d335fbc764bee2ae11f759b7f22697 | kaiyaprovost/algobio_scripts_python | /dna_to_rna.py | 87 | 3.671875 | 4 | dna = str(input("dna string to convert"))
rna = dna.replace("T","U")
print(rna)
|
89a6afcaabb168d3cf9988733987e7ec003d49ba | kaiyaprovost/algobio_scripts_python | /prob7_rosalind_substring.py | 136 | 3.640625 | 4 | string = "NbCEJ9e2QcLPf2JUmXNztSDlgpFGlmsJSci2gX04MHLhzKtyMV1TnoZV0rCFZ3dPSLtfnOPterinochilusMoqaDWpWejUhi2tjCLjNn8mYAdWKuPA3V6QRjpmyHwzmsalamandraTVy77qBxVLoKtWTnj2DdgTL9MjT8HCOGQe."
print(len(string))
a=70
b=82
c=127
d=136
sub1 = string[a:(b+1)]
sub2 = string[c:(d+1)]
print sub1,sub2
|
811057a34fb5b59acf1f123ad850dafd421b010e | kaiyaprovost/algobio_scripts_python | /prob11_searchforsubstring.py | 225 | 3.5 | 4 | full = str(input("full string "))
motif = str(input("motif "))
## wants 1 based numbers
counti = 1
for i in range(len(full)):
if full[i:i+len(motif)] == motif:
print counti,
counti = counti + 1
|
42b3e8b6194acad8057c5f10d1b2144887c5744a | Ekimkuznetsov/My_projects | /ex_11.py | 296 | 3.90625 | 4 | import re
file = input("Enter the file: ")
read = open(file)
summ = 0
for line in read:
num = re.findall("[0-9]+", line) #list of numbers in the line
for elem in num: #sum by adding elements inside of each line
elem = int(elem)
summ = summ + elem
print(summ)
|
7f5e66623babc6919733bec982bbd4d4baa10176 | Ojhowribeiro/PythonProjects | /exercicios/PycharmProjects/exepython/ex014.py | 315 | 4.125 | 4 | c = float(input('Qual a temperatura em c°:'))
f = float((c*1.8)+32)
k = float(c+273)
print('{}°C é igual a {:.2f}°F e {:.2f}°K'.format(c, f, k))
'''c = float (input('qual o valor em °c: '))
f = float (((9*c) /5 ) + 32)
k = float (c + 273)
print('{}°C é igual a {:.2f}°F e {:.2f}°K'.format(c, f, k))''' |
cd9a5d6b6ed0f9df3733fcec8eced83f7c949e08 | Ojhowribeiro/PythonProjects | /exercicios/PycharmProjects/exepython/ex040.py | 477 | 3.828125 | 4 | nome_aluno = str(input('Nome do aluno: '))
nota_1 = float(input('Qual foi sua primeira nota? '))
nota_2 = float(input("Qual foi sua segunda nota? "))
media = float((nota_1 + nota_2) / 2)
if media < 5.0:
status = 'REPROVADO'
elif media >= 5.0 and media <= 6.9:
status = 'RECUPERAÇÂO'
elif media >= 7.0:
status = 'APROVADO'
else:
print('ERRO NO SISTEMA, DIGITE NOVAMENTE')
print('O aluno(a) {} está {}, sua media foi {:.1f}'.format(nome_aluno, status, media))
|
f929c42ac31f25d0783f58cd158fd7d3730a4251 | Ojhowribeiro/PythonProjects | /exercicios/PycharmProjects/exepython/ex044.py | 877 | 3.84375 | 4 | preco_compras = float(input('Preço das compras: '))
print('''----Forma de Pagamento----
[1] á vista dinheiro/pix
[2] á vista no cartão
[3] 2x no cartão
[4] 3x ou mais no cartão''')
opcao = int(input('Qual sua opção? '))
if opcao == 1:
s = preco_compras - (preco_compras * 0.10)
elif opcao == 2:
s = preco_compras - (preco_compras * 0.05)
elif opcao == 3:
s = preco_compras
parcela = s / 2
print('Sua compra sera parcelada em 2x de R${}'.format(parcela))
elif opcao == 4:
s = preco_compras + (preco_compras * 0.20)
totalpar = int(input('Quantas parcelas? '))
parcela = s / totalpar
print('Sua compra sera parcelada em {}x de R${:.2f} com juros'.format(totalpar,parcela ))
else:
s = preco_compras
print('Opção invalida!!!')
print('Sua compra de R${} vai custar {} no final'.format(preco_compras, s))
|
0369b41812b9cdd3bd66f2dacbd728497b6525c8 | Ojhowribeiro/PythonProjects | /exercicios/PycharmProjects/exepython/ex006.py | 370 | 4.15625 | 4 | n = int(input('digite um numero: '))
dobro = int(n*2)
triplo = int(n*3)
raiz = float(n**(1/2))
print('O dobro de {} é {}, o triplo é {} e a raiz é {:.2f}'.format(n, dobro, triplo, raiz))
'''n = int(input('digite um numero: '))
mul = n*2
tri = n*3
rai = n**(1/2)
print('o dobro de {} é {}, o triplo é {} e a raiz quadrada é {:.3f}'.format(n, mul, tri, rai))'''
|
d5db4d147d1a96ba1713d98198e9c596b6d9e84c | Ojhowribeiro/PythonProjects | /exercicios/PycharmProjects/exepython/ex008.py | 396 | 4.21875 | 4 | medida = float(input('Qual o valor em metros: '))
cm = float(medida*100)
mm = float(medida*1000)
km = float(medida/1000)
print('{} metros: \n{:.3f} cm \n{:.3f} mm\n{:.3f} km'.format(medida, cm, mm, km))
'''medida = float(input('qual a distancia em metros:'))
cm = medida * 100
mm = medida * 1000
km = medida / 1000
print('{} metros igual:\ncm: {}\nmm: {}\nkm: {}'.format(medida, cm, mm, km))''' |
71d253977476a26224ca7786de9883dc05ebe1c0 | leyap/python3-tutorial | /Python3Tutorial/tuple.py | 157 | 4.15625 | 4 |
tuple1 = ()
tuple2 = 'tuple',
print(tuple2)
tuple3 = 'a','b','c'
print(tuple3)
a,b,c = tuple3
print(b)
a,b = '1','2'
print(a,b)
a,b = b,a
print(a,b)
|
1dc781ac4bc168a9409b2ce2cfbc135987c0b061 | leyap/python3-tutorial | /Python3Tutorial/logic.py | 567 | 3.96875 | 4 | # if, else, elif
'''
False:
False
None
0
0.0
''
[]
()
{}
set()
others is True
'''
'''
==
!=
<
<=
>
>=
in ...
'''
a = 1
b = 2
if a>b:
print("a大于b")
else:
print("a小于b")
# \
print("hello \
world")
if (a > b):
print("a大于b")
elif (a == b):
print("a等于b")
else:
print("a小于b")
really = True
if really:
print("really")
# run break, will pass else
while True:
if (1 < 2):
break
else:
print('ok')
for i in range(0, 4):
print(i)
print()
for i in range(0, 10, 2):
print(i)
print()
for i in range(2, -1, -1):
print(i)
print()
|
27ebd0caa32448dbf96bf0414c337a4d8d31eef4 | DanDits/Masterarbeit | /polynomial_chaos/poly.py | 12,980 | 3.671875 | 4 | from functools import lru_cache
import numpy as np
import numpy.polynomial.polynomial as npoly
import math
# Pretty general implementation for a recursively defined polynomial basis in function form, so it is not optimized
# as terms that cancel out are still calculated and may lead to inaccuracies.
# For higher accuracy (for low order terms) use more hand
# calculated polynomials for "polys_start"
from util.analysis import rising_factorial
def _poly_function_basis_recursive(polys_start, recursion_factors):
"""
Factory function for a basis of polynomials p(x) for a single double variable x.
The returned function takes a non negative integer n and returns a polynomial of degree n
which is the n-th basis polynomial. The first basis polynomials are given as function by polys_start.
The following polynomials are defined by the recursion factors f as follows:
p_n(x) = f_0(n,x) * p_(n-1)(x) + f_1(n,x) * p_(n-2)(x) + ...
:param polys_start: The m starting polynomials.
:param recursion_factors: factors as functions from degree n and position x,
defining the recursion for higher order polynomials.
:return: A function that takes an order n and returns a polynomial p mapping a double to a double.
Polynomials are cached internally but not mathematically simplified and not optimized.
"""
@lru_cache(maxsize=None)
def poly(n):
if 0 <= n < len(polys_start):
return polys_start[n]
elif n >= len(polys_start):
return lambda x: sum(f_a(n, x) * poly(n - 1 - i)(x) for i, f_a in enumerate(recursion_factors))
else:
raise ValueError("Illegal degree n={} for polynomial basis function.".format(n))
return poly
# Pretty general implementation for a recursively defined polynomial basis in numpy's polynomial coefficient form,
# which is optimized to use Horner's scheme for evaluation and can be extended more easily for multi dimensionality.
def _poly_basis_recursive(polys_start_coeff, recursive_poly_functions):
"""
:param polys_start_coeff: List of coefficients as 1d numpy arrays for starting polynomials.
:param recursive_poly_functions: List of tuples of an integer and a function. The integer indicates which previous
polynomials coefficients to apply on, 0 for the previous, 1 for the one before the previous,...
The function takes the degree n and the previous coefficients and returns new coefficients which are summed up to
make the new polynomial's coefficients.
:return: A function taking a degree n and returning a function which evaluates the n-th polynomial at the point x.
"""
@lru_cache(maxsize=None)
def poly_coeff(n):
if 0 <= n < len(polys_start_coeff):
return polys_start_coeff[n]
elif n >= len(polys_start_coeff):
coeff = np.array([0.])
for i, func in recursive_poly_functions:
if i < 0 or i >= n:
raise ValueError("Can't apply on not yet calculated polynomial! i={}, n={}".format(i, n))
coeff = npoly.polyadd(coeff, func(n, poly_coeff(n - i - 1)))
return coeff
else:
raise ValueError("Illegal degree n={} for polynomial coefficients.".format(n))
@lru_cache(maxsize=None)
def poly(n):
coeff = poly_coeff(n)
return lambda x: npoly.polyval(x, coeff)
return poly
# HINT: hermite (so hermite-gauss chaos) and laguerre (so laguerre-gamma chaos)
# nodes are becoming wrong for degree >= 15 when using the recurrence correlation
# as the image becomes very big (but also if normalized very small (O(10^-16))), orthonormal basis are correct!
# the nodes are also correct, the problem is that the polynomial evaluation becomes increasingly bad for these
# types of basis because of cancellation and round off errors. Therefore use definition by roots.
def poly_by_roots(roots, leading_coefficient):
"""
Returns the polynom that is defined by:
p(x)=leading_coefficient * (x-r1)*(x-r2)*...*(x-r_n)
if n roots are given. The leading factor is the factor between the monic version and the normal
version of the polynomials.
:param roots: The roots of the polynomial.
:param leading_coefficient: The leading coefficient in front of the highest power.
:return: A polynomial function which can be evaluated at an array-like parameter.
"""
def poly(x):
prod = leading_coefficient
for root in roots:
prod *= (x - root)
return prod
return poly
# to get the traditional weights for gauss-laguerre multiply by gamma(alpha),
# to get the traditional weights for gauss legendre multiply by 2
def calculate_nodes_and_weights(alphas, betas):
if len(alphas) <= 0 and len(betas) <= 0:
return [], []
# The Golub-Welsch algorithm in symmetrized form
# see https://en.wikipedia.org/wiki/Gaussian_quadrature#Computation_of_Gaussian_quadrature_rules
# or see http://dlmf.nist.gov/3.5#vi for calculation of nodes = zeros of polynomial
# p_k(x)=(x-alpha_(k-1))*p_(k-1)(x)-beta_(k-1)p_(k-2)(x) # the monic recurrence correlation of the polynomials
beta_sqrt = np.sqrt(betas)
trimat = (np.diag(alphas)
+ np.diag(beta_sqrt, 1) + np.diag(beta_sqrt, -1))
nodes, vectors = np.linalg.eigh(trimat)
# nodes are the roots of the n-th polynom which are the eigenvalues of this matrix
# the weights are the squares of the first entry of the corresponding eigenvectors
return nodes, np.reshape(vectors[0, :] ** 2, (len(nodes),))
# Polynomial basis: http://dlmf.nist.gov/18.3
# Recurrence correlations: http://dlmf.nist.gov/18.9#i
# when returned 'amount' of nodes is fixed (no matter the degree),
# then using 'amount' nodes gives stable and converging results up to degree<2*amount for collocation
class PolyBasis:
def __init__(self, name, polys, nodes_and_weights, params=()):
self.name = name
self.params = params
self.polys = polys
self.nodes_and_weights = None
if nodes_and_weights is not None:
self.nodes_and_weights = lru_cache(maxsize=None)(nodes_and_weights)
def make_hermite():
# Hermite polynomials, recursion p_n(x)=x*p_(n-1)(x)-(n-1)*p_(n-2), p_0(x)=1, p_1(x)=x
# _poly_function_basis_recursive((lambda x: 1, lambda x: x), (lambda n, x: x, lambda n, x: 1 - n)) # as example
basis = PolyBasis("Hermite",
_poly_basis_recursive([np.array([1.]), np.array([0., 1.])], # starting values
[(0, lambda n, c: npoly.polymulx(c)),
(1, lambda n, c: c * (1. - n))]),
lambda degree: calculate_nodes_and_weights(np.zeros(degree), np.arange(1, degree)))
basis.polys = lambda degree: poly_by_roots(basis.nodes_and_weights(degree)[0], 1)
return basis
def make_laguerre(alpha):
assert alpha > 0
# normalized recurrence relation: q_n=xq_(n-1) - (2(n-1) + alpha)q_(n-1) - (n-1)(n - 2 + alpha)q_(n-2)
# to obtain the regular polynomials multiply by (-1)^n / n!
basis = PolyBasis("Laguerre",
_poly_basis_recursive([np.array([1.]), np.array([alpha, -1.])],
[(0, lambda n, c: npoly.polyadd(c * (2 * (n - 1) + alpha) / n,
- npoly.polymulx(c) / n)),
(1, lambda n, c: -(n - 1 + alpha - 1) / n * c)]),
lambda degree: calculate_nodes_and_weights(2 * np.arange(0, degree) + alpha,
np.arange(1, degree) * (
np.arange(1, degree) - 1 + alpha)),
params=(alpha,))
basis.polys = lambda degree: poly_by_roots(basis.nodes_and_weights(degree)[0],
(1, -1)[degree % 2] / math.sqrt(rising_factorial(alpha, degree))
/ math.sqrt(math.factorial(degree))) # (-1)^n/n!
return basis
def make_legendre():
# Legendre polynomials, interval assumed to be [-1,1], recursion p_n(x)=x(2n-1)/n * p_(n-1)(x)-(n-1)/n*p_(n-2)(x)
# http://math.stackexchange.com/questions/12160/roots-of-legendre-polynomial gives the monic version of the legendre
# polynomials: p_n(x)=x*p_(n-1)(x)-(n-1)^2/(4(n-1)^2-1)p_(n-2), to get the normal polynomial divide by
# (n!)^2 * 2^n / (2n)!
basis = PolyBasis("Legendre",
_poly_basis_recursive([np.array([1.]), np.array([0., 1.])], # starting values
[(0, lambda n, c: (2. * n - 1) / n * npoly.polymulx(c)),
(1, lambda n, c: (1. - n) / n * c)]),
lambda degree: calculate_nodes_and_weights(np.zeros(degree), np.arange(1, degree) ** 2
/ (4 * (np.arange(1, degree) ** 2) - 1)))
return basis
def make_jacobi(alpha, beta):
assert alpha > -1
assert beta > -1
# jacobi polynomial basis (belongs to beta distribution on (-1,1))
def jacobi_basis():
def get_factor(n):
return (2 * n + alpha + beta - 1) * (2 * n + alpha + beta) / (2 * n * (n + alpha + beta))
# this doesn't even look nice on paper
return _poly_basis_recursive([np.array([1.]),
np.array([0.5 * (alpha - beta), 0.5 * (alpha + beta + 2)])], # starting values
[(0, lambda n, c: npoly.polyadd(npoly.polymulx(c) * get_factor(n),
-c * get_factor(n) * (beta ** 2 - alpha ** 2)
/ ((2 * n + alpha + beta - 2)
* (2 * n + alpha + beta)))),
(1, lambda n, c: c * (-2 * get_factor(n) * (n + alpha - 1) * (n + beta - 1) / (
(2 * n + alpha + beta - 2) * (2 * n + alpha + beta - 1))))])
def jacobi_nodes_and_weights(degree):
# handle special cases to avoid division by zero
if np.allclose([alpha, beta], np.zeros(2)):
# uniform distribution so legendre nodes and weights
return calculate_nodes_and_weights(np.zeros(degree), np.arange(1, degree) ** 2
/ (4 * (np.arange(1, degree) ** 2) - 1))
if np.allclose([alpha + beta], [0.]):
first_term = np.append((beta - alpha) / 2, np.zeros(degree - 1))
else:
first_term = ((beta ** 2 - alpha ** 2) / ((2 * np.arange(degree) + alpha + beta)
* (2 * np.arange(degree) + 2 + alpha + beta)))
if np.allclose([alpha + beta], [-1.]): # second term would have division by zero in second term for n=1
# for (alpha,beta)==(-0.5,-0.5) the arcsine distribution
temp = np.arange(2, degree)
second_temp = (4 * temp * (temp + alpha) * (temp + beta) * (temp + alpha + beta)
/ ((2 * temp + alpha + beta - 1) * ((2 * temp + alpha + beta) ** 2)
* (2 * temp + alpha + beta + 1)))
second_temp = np.append((np.array([(4 * 1 * (1 + alpha) * (1 + beta)
/ (((2 * 1 + alpha + beta) ** 2) * (
2 * 1 + alpha + beta + 1)))])),
second_temp)
return calculate_nodes_and_weights(first_term, np.array([]) if degree <= 1 else second_temp)
# (alpha,beta)==(0.5,0.5): Wigner semicircle distribution; nodes are chebychev nodes of the second kind
temp = np.arange(1, degree)
second_term = (4 * temp * (temp + alpha) * (temp + beta) * (temp + alpha + beta)
/ ((2 * temp + alpha + beta - 1) * ((2 * temp + alpha + beta) ** 2)
* (2 * temp + alpha + beta + 1)))
return calculate_nodes_and_weights(first_term, second_term)
basis = PolyBasis("Jacobi",
jacobi_basis(),
jacobi_nodes_and_weights,
params=(alpha, beta))
return basis
# legendre nodes are the same, weights are off by factor 2 due to our scaling by distribution weight
# laguerre nodes are the same, weights are off by factor gamma(alpha) due to our scaling by distribution weight
# hermite nodes are off by a factor sqrt(2) as we use e^(x^2/2) instead of e^(x^2), weights are off by factor sqrt(pi)
# jacobi nodes are same except for EW 0, because we shifted domain from (0,1) to (-1,1)? |
9de3fd928aecb53938eb1ced384dfb9deeb3a5b9 | lzaugg/giphy-streamer | /scroll.py | 1,426 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Console Text Scroller
~~~~~~~~~~~~~~~~~~~~~
Scroll a text on the console.
Don't forget to play with the modifier arguments!
:Copyright: 2007-2008 Jochen Kupperschmidt
:Date: 31-Aug-2008
:License: MIT_
.. _MIT: http://www.opensource.org/licenses/mit-license.php
"""
from itertools import cycle
from sys import stdout
from time import sleep
def stepper(limit, step_size, loop, backward, bounce):
"""Generate step indices sequence."""
steps = range(0, limit + 1, step_size)
if backward:
steps.reverse()
if bounce:
list(steps).extend(reversed(steps))
if loop:
steps = cycle(steps)
return iter(steps)
def display(string):
"""Instantly write to standard output."""
stdout.write('\r' + string)
stdout.flush()
def scroll(message, window, backward=False, bounce=True,
loop=True, step_size=1, delay=0.1, template='[%s]'):
"""Scroll a message."""
string = ''.join((' ' * window, message, ' ' * window))
limit = window + len(message)
steps = stepper(limit, step_size, loop, backward, bounce)
try:
for step in steps:
display(template % string[step:window + step])
sleep(delay)
except KeyboardInterrupt:
pass
finally:
# Clean up.
display((' ' * (window + len(template) - 2)) + '\r')
if __name__ == '__main__':
scroll('Hello Sam!', 20) |
f8f775245f38f0553c139bf3253c449e7bf851d8 | judeinno/CodeInterview | /test/test_Piglatin.py | 941 | 4.15625 | 4 | import unittest
from app.Piglatin import PigLatinConverter
""" These tests are for the piglatin converter"""
class TestConverter(unittest.TestCase):
"""This test makes sure that once the first letters are not vowels they are moved to the end"""
def test_for_none_vowel(self):
self.pig = PigLatinConverter(args='jude')
result = self.pig.pig_latin()
self.assertEqual(result, 'udejay')
"""This test makes sure that once the first letter is a vowel the word way is added to the end of the word"""
def test_for_vowel(self):
self.pig = PigLatinConverter(args='andela')
self.assertEqual(self.pig.pig_latin(), 'andelaway')
"""This test makes sure that an integer is not entered"""
def test_for_integers(self):
self.pig = PigLatinConverter(args= str(55))
self.assertEqual(self.pig.pig_latin(), 'Please enter a word')
if __name__ == '__main__':
unittest.main() |
b4ed1b7eb05ab6da331e525a39a51ddd196cc6b1 | aliwo/swblog | /_drafts/number_baseball.py | 3,274 | 3.578125 | 4 |
# 가설 1: 0 스트라이크 0 볼이 나오면 제대로 계산하지 못한다.
# -> 반론: 모든 질문이 0스트라이크 0볼이 아닌 이상 xxx 는 소거 된다.
# 가설 2: 설마 질문에는 0이 들어갈까?
# -> 0 없애도록 했는데 역시 오답...
# 사실은 111 처럼 중복이 가능하다? -> 문제에 명시되어 있다. 중복은 없어.
def strikes(elem):
if elem[1] == 0:
return ['xxx']
question = str(elem[0])
if elem[1] == 1:
return [f'{question[0]}xx', f'x{question[1]}x', f'xx{question[2]}']
if elem[1] == 2:
return [f'{question[0]}{question[1]}x', f'x{question[1]}{question[2]}', f'{question[0]}x{question[2]}']
return [question]
def balls(elem):
if elem[2] == 0:
return ['xxx']
question = str(elem[0])
if elem[2] == 1:
return [f'x{question[0]}x', f'xx{question[0]}', f'{question[1]}xx', f'xx{question[1]}',
f'{question[2]}xx', f'x{question[2]}x']
if elem[2] == 2:
return [
f'{question[1]}{question[0]}x', f'{question[1]}x{question[0]}', f'x{question[0]}{question[1]}'
,f'{question[1]}{question[2]}x', f'x{question[2]}{question[1]}', f'{question[2]}x{question[1]}'
,f'{question[2]}x{question[0]}', f'{question[2]}{question[0]}x', f'x{question[2]}{question[0]}'
]
return [f'{question[1]}{question[2]}{question[0]}', f'{question[2]}{question[0]}{question[1]}']
def intersect(poss1, poss2):
'''
배열 poss1 과 poss2 를 비교했을 때 가능한 모든 조합을 리턴합니다.
'''
possibilities = []
for elem in poss1:
for elem2 in poss2:
temp = []
for ch1, ch2 in zip(elem, elem2):
if ch1 == '0' or ch2 == '0':
break
if ch1 == 'x' and ch2 == 'x':
temp.append('x')
elif ch1 == 'x' and ch2 not in temp:
temp.append(ch2)
elif ch2 == 'x' and ch1 not in temp:
temp.append(ch1)
elif ch1 == ch2 and ch1 not in temp:
temp.append(ch1)
else:
break
else:
possibilities.append(''.join(temp))
return possibilities
def form_possibilities(poss):
'''
주어진 숫자와, 스트라이크, 볼의 수로 가능한 모든 조합을 리턴합니다.
스트라이크로 얻을 수 있는 모든 조합과, 볼로 얻을수 있는 모든 조합을 인터섹트 하면 나옵니다.
'''
return intersect(strikes(poss), balls(poss))
def solution(baseball):
# 첫번째 질문으로 possibilities 생성
possibilities = form_possibilities(baseball[0])
for elem in baseball[1:]:
possibilities = intersect(possibilities, form_possibilities(elem))
return len(set(possibilities))
# print(solution([[123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]]))
# print(solution([[156, 0, 0], [123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]]))
print(solution([[156, 0, 0], [123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1], [624, 2, 0]])) # 답이 하나로 줄음... 무섭도록 완벽하게 동작하네
print(solution([[127, 3, 0]])) # 789
|
ee93ccbf1d7a2333fb1d2c1f69c055d0a5d6a2df | aliwo/swblog | /_drafts/kakao_2019_11/crain.py | 644 | 3.71875 | 4 |
def pick_doll(board, stk, pick):
for layer in board:
if layer[pick] != 0:
stk.append(layer[pick])
layer[pick] = 0
return
def solution(board, moves):
answer = 0
stk = []
for pick in moves:
pick_doll(board, stk, pick-1)
if len(stk) >= 2:
if stk[-1] == stk[-2]:
stk.pop()
stk.pop()
answer += 2
return answer
board1 = [
[0,0,0,0,0],
[0,0,1,0,3],
[0,2,5,0,1],
[4,2,4,4,2],
[3,5,1,3,1]
]
moves = [1,5,3,5,1,2,1,4]
# 4 3 1 1 터짐
# 3 터짐
# 2 0 4
print(solution(board1, moves))
|
90f0633a3a87aa291b56512cd6699dbde07985d9 | aliwo/swblog | /_drafts/copy_test.py | 593 | 4 | 4 | from copy import deepcopy
class Num:
def __init__(self, num):
self.num = num
def __repr__(self):
return str(self.num)
a = [1, 2, 3]
b = [Num(1), Num(2), Num(3)]
# 할당
a1 = a
b1 = b
print('할당')
a1.append(4)
print(a)
b1.append(Num(4))
print(b)
print()
# 얕은 복사
print('얕은 복사')
a2 = a[:]
b2 = b[:]
a2.append(5)
print(a)
print(a2)
b2.append(Num(5))
print(b)
print(b2)
print('얕은 복사와 mutable')
b2[0].num = 999
print(b)
print(b2)
print()
# 깊은 복사
print('깊은 복사')
b3 = deepcopy(b)
b3[0].num = 1
print(b)
print(b3)
|
00e5fa463d5a47ac891a6ce478dca0169e1c642c | aliwo/swblog | /_drafts/algo_expert_medium/three_number_sum.py | 1,514 | 3.640625 | 4 | from collections import defaultdict
# def threeNumberSum(array, targetSum):
# '''
# 정렬하고 탐색을 시작하나
# 아니면 정렬 없이 답을 만들까.
#
# two number sum 이면 딕셔너리 만들면 된다.
# three number sum 이면 이중 루프 돌면서 딕셔너리를 look up 하면 되나?
#
# '''
# array.sort()
# cache = {x: {y: True for y in array[i+1:]} for i, x in enumerate(array)}
# result = []
# for i in array:
# for j in array[i:]:
# if targetSum - (i + j) in cache[j]:
# result.append(sorted([i, j, targetSum - (i + j)]))
#
# return result
def threeNumberSum(array, targetSum):
'''
정렬하고 탐색을 시작하나
아니면 정렬 없이 답을 만들까.
two number sum 이면 딕셔너리 만들면 된다.
three number sum 이면 이중 루프 돌면서 딕셔너리를 look up 하면 되나?
'''
array.sort()
cache = defaultdict(lambda: defaultdict(dict))
result = []
for i in range(len(array)):
for j in range(i+1, len(array)):
for k in range(j+1, len(array)):
cache[array[i]][array[j]][array[k]] = True
for x, cache_2 in cache.items():
for y, cache_3 in cache_2.items():
if targetSum - (x + y) in cache_3:
result.append(sorted([x, y, targetSum - (x + y)]))
return result
print(threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
# print(threeNumberSum([1, 2, 3], 6))
|
4fddb352f78666322a54f60acf257705c02a540b | aliwo/swblog | /_drafts/skt_2022_11_26/the_great_merchant.py | 3,918 | 3.65625 | 4 | from typing import List, Any
class Branch:
"""
상인이 하루에 선택할 수 있는 경우의 수 입니다.
상인은 매일...
- 구매
- 가만히 있거
- 판매
를 할 수 있습니다.
"""
def __init__(self, money: int, stone: int):
self.money = money
self.stone = stone
def buy(self, price: int) -> "Branch":
"""
하루에 1 개만 살 수 있습니다.
예외: 돈이 모자랄 경우 stay 합니다.
"""
if self.money >= price:
return Branch(
money=self.money - price,
stone=self.stone + 1,
)
return self.stay(price)
def stay(self, price: int) -> "Branch":
"""
사지 않고 가만히 있습니다.
예외: 시세가 0원이라고요? 그러면 가만히 있을 수 없죠!
"""
if price == 0:
return self.buy(price)
return self
def sell(self, price: int, stone: int) -> "Branch":
"""
price 가격에 stone 개수 만큼 판매 합니다.
예외:
- 가격이 0원인 경우 팔지 않고 바로 삽니다.
- 돌이 부족한 경우 가만히 있습니다.
"""
if price == 0:
return self.buy(price)
if self.stone >= stone:
return Branch(
money=self.money + (price * stone),
stone=self.stone - stone,
)
return self.stay(price)
def __hash__(self) -> int:
return hash(f'{self.money}_{self.stone}')
def __eq__(self, other: Any) -> bool:
return isinstance(other, Branch) and self.money == other.money and self.stone == other.stone
def __gt__(self, other) -> bool:
return isinstance(other, Branch) and self.money > other.money
def __ge__(self, other) -> bool:
return isinstance(other, Branch) and self.money >= other.money
def __lt__(self, other) -> bool:
return isinstance(other, Branch) and self.money < other.money
def __le__(self, other) -> bool:
return isinstance(other, Branch) and self.money <= other.money
def solution(n: int, price: List[int]) -> int:
"""
branches 는 상인이 하루 동안 취할 수 있는 행동의 모든 경우의 수를 담고 있습니다.
for loop 한 번 회전이 곧 하루를 의미 합니다.
하루 동안 상인은
- branch.stay() 가만하 있거나
- branch,buy() 돌을 사거나
- 아니면 자신이 가지고 있는 돌 만큼 range(1, branch.stone + 1)
판매를 할 수 있습니다.
"""
branches = [
Branch(money=0, stone=0)
]
for i in range(price.index(0), len(price)):
new_branches = []
while branches:
branch = branches.pop()
branch_set = {branch.stay(price[i]), branch.buy(price[i])}
for stone in range(1, branch.stone + 1):
branch_set.add(branch.sell(price[i], stone))
for branch in branch_set:
new_branches.append(branch)
branches = new_branches
return max(branches).money
print(solution(2, [0,1,2]) == 2)
print(solution(2, [0,0,3,1,1,1,9]) == 36)
print(solution(2, [1,0,0]) == 0)
print(solution(2, [0,0,1,1,9]) == 18)
# 시세가 0인 날에 처음 으로 돌을 1개 살 수 있음.
# 그 다음 시세가 0이 아닌 날에 팔 수 있음.
# 매 번 다음의 선택지가 존재
# 가만히 있는다.
# 산다. (돈이 있을 때)
# 판다. (돌이 있을 때)
# 0원에 사서 9원에 팔고 가만히 있는다.
# [0, 9, 1, 1, 1] -> 9
# [0, 1, 1, 1, 9] -> 9
# 0원에 사고 9원에 팔고, 나머지는 가만히 있는다.
# 가장 시세가 비싼 날에 팔면 안 되는 경우
# [0, 9, 9, 1, 8, 1, 8]
# 리스트 길이는 100... 완전 탐색해도 되겠는데?
|
6772a12b4837a3d7fa63a6eba3764c719d15983a | rzamoramx/data_science_exercises | /statistics/variance.py | 604 | 4 | 4 | """ Base functions for computes variances """
import math
from typing import List
from linear_algebra.vectors import sum_of_squares
from statistics.central_tendencies import de_mean
def standard_deviation(xs: List[float]) -> float:
""" The standard deviation is the square root of the variance """
return math.sqrt(variance(xs))
def variance(xs: List[float]) -> float:
""" Almost the average squared deviation from the mean """
assert len(xs) >= 2, "variance requires at least two elements"
n = len(xs)
deviations = de_mean(xs)
return sum_of_squares(deviations) / (n - 1) |
82649213d5ab8211c2da37b4f0db2aaef5f2829c | jaeglee94/allHomework | /03 Python Homework/PyBank/main.py | 2,007 | 3.65625 | 4 | #Import Libraries
import os
import csv
from statistics import mean
#Initialize Variables
file = os.path.join("budget_data.csv")
dataSet=[]
PL = []
plChange = []
months = 0
netTotal = 0
average = 0.0
#Read CSV to list variable
with open(file,"r",newline = "") as csvfile:
csvreader = csv.reader(csvfile,delimiter =",")
for lines in csvreader:
dataSet.append(lines)
#Close file and create separate list just for P/L
for lines in dataSet[1:]:
PL.append(int(lines[1]))
#determine months and netTotal through loop
months += 1
netTotal = netTotal + int(lines[1])
i = 1
for i in range(len(PL)):
plChange.append(PL[i]-PL[i-1])
plChange = plChange[1:]
#Determine average, max, min and initialize max profit/loss month variables
average = round(mean(plChange),2)
maxProfit = max(PL)
maxLoss = min(PL)
maxProfitMonth = ""
maxLossMonth = ""
#Search in list for max profit or max loss value, return month associated with value
for lines in dataSet[1:]:
if lines[1] == str(maxProfit):
maxProfitMonth = lines[0]
elif lines[1] == str(maxLoss):
maxLossMonth = lines[0]
#Initialize formatted currency variables
netTotalFormatted = "{:,}".format(netTotal)
averageFormatted = "{:,}".format(average)
maxProfitFormatted = "{:,}".format(maxProfit)
maxLossFormatted = "{:,}".format(maxLoss)
#Print variables to console with block string
Result = (f"Financial Analysis\n"
f"----------------------------\n"
f"Total months: {months}\n"
f"Total: ${netTotalFormatted}\n"
f"Average Change: ${averageFormatted}\n"
f"Greatest Increase in Profits: {maxProfitMonth} (${maxProfitFormatted}) \n"
f"Greatest Decrease in Profits: {maxLossMonth} (${maxLossFormatted}) \n")
#Print Result to Terminal
print(Result)
#Set Output Text Pathway and file name
output_path = os.path.join("result.txt")
#Write to text file the result
with open(output_path,"w",newline="") as textfile:
textfile.write(Result)
|
e8ee5820f5c7b6e7a83f797c3077fd7015b92671 | KoYeJoon/python_basic | /ch4/exercise4/exer2.py | 459 | 3.625 | 4 | """
f=open("sample.txt",'r')
sum=0
count=0
while True:
line=f.readline()
if not line : break
count=count+1
result=int(line)
sum=sum+result
print(sum)
average=sum/count
f.close()
f=open("result.txt",'w')
f.write(str(average))
f.close()
"""
f=open("sample.txt")
lines=f.readlines()
f.close()
total=0
for line in lines :
score = int(line)
total += score
average=total/len(lines)
print(total)
f=open("result.txt",'w')
f.write(str(average))
f.close()
|
19e270416749b68d0334062ec0051001a30dfe35 | ssegota/Complex-System-Engineering-Exercises | /vj5.py | 2,370 | 3.65625 | 4 | import numpy as np
from Values import *
import math
#maximum allowed cost(budget)
#used if useCostLimit = True
costLimit = 8000
#if set to true it will use the predefined cost limit (which might be higher than first solution cost)
#otherwise it will generate solution that has a better cost then the first random solution - algorithm tends to not find a better solution in this case
useCostLimit = True
breakValue = 0
#coolingStrategy = "linear" or "geometric" or anything for basic
coolingStrategy = "linear"
if coolingStrategy == "geometric":
breakValue = 0.03#smallest possible without dumping a mathOverflow when using exp
#generate a random solution
sol = np.random.randint(2, size=20)
print(sol)
#calculate fitness
#Fitness = [cost][Satisfaction]
Fitness = calculateCost(sol, True)
k = 1
m = 0.5
tk = m*20**2
t0 = tk
Mk = 2000
if not useCostLimit:
costLimit = Fitness[0]
else:
print("maximum cost(budget) fixed and set to: ", costLimit)
while tk>breakValue:
k+=1
print("tk=",tk,"in iteration:",k)
for m in range(Mk):
randPos=np.random.randint(20)
newSol = list(sol)
if newSol[randPos] == 0:
newSol[randPos] = 1
else:
newSol[randPos] = 0
newSolutionFitness = calculateCost(newSol)
delta = Fitness[1] - newSolutionFitness[1]
#cost prohibitive?
if newSolutionFitness[0]>costLimit:
continue
if delta < 0:
#print(newSolutionFitness[1],">",Fitness[1])
#print(newSol)
sol = list(newSol)
Fitness = newSolutionFitness
else:
probability = math.exp(delta/tk)
#print(probability)
if np.random.uniform(0,1,1) < (1-probability):
sol = list(newSol)
Fitness = newSolutionFitness
if coolingStrategy == "linear":
#pass
#beta = (t0 - tk)/(k-1)
beta = 0.8
tk = t0 - beta*k
elif coolingStrategy == "geometric":
pass
#alpha = (tk/t0)**(1/(k-1))
alpha = 0.5
tk = alpha**k * t0
else:
tk-=0.9
if tk <= 0:
break;
print("\n\nBest solution found:")
print(sol)
calculateCost(sol, True) |
1503231991538ae5b8dcda3e9e758a93956d01dd | chloebee102/Dunkin-Dash | /tiles.py | 15,554 | 3.59375 | 4 |
# coding: utf-8
# In[56]:
#needed to define the plane in which the player moves
import items, enemies, actions, world
#import pdb
class MapTile():
def __init__(self, x, y):
self.x = x
self.y = y
def intro_text(self): #display info when entering the tile
raise NotImplementedError()
def modify_player(self, the_player):
raise NotImplementedError()
def adjacent_moves(self):
#default actions a player can do
moves = []
#pdb.set_trace()
if world.tile_exists(self.x + 1, self.y):
moves.append(actions.MoveRight())
if world.tile_exists(self.x - 1, self.y):
moves.append(actions.MoveLeft())
if world.tile_exists(self.x, self.y - 1):
moves.append(actions.MoveUp())
if world.tile_exists(self.x, self.y + 1):
moves.append(actions.MoveDown())
return moves
def available_actions(self):
#Sets up available actions based on room
moves = self.adjacent_moves()
moves.append(actions.ViewInventory())
return moves
class BoylstonSt(MapTile):
def intro_text(self):
return """
You find yourself stranded on the sidewalk of Boylston St.
You can make out the alleyway and Walker Building further down the street.
"""
def modify_player(self, the_player):
pass
#defining a room that provides items
class ItemRoom(MapTile):
def __init__(self, x, y, item):
self.item = item
super().__init__(x, y)
def add_loot(self, the_player):
the_player.inventory.append(self.item)
def modify_player(self, the_player):
self.add_loot(the_player)
#defining a room that holds enemies
class EnemyRoom(MapTile):
def __init__(self, x, y, enemy):
self.enemy = enemy
super().__init__(x, y)
#prevent enemies from respawning
def modify_player(self, the_player):
if self.enemy.is_alive():
the_player.hp = the_player.hp - self.enemy.damage
print("Enemy does {} damage. You have {} HP remaining.".format(self.enemy.damage, the_player.hp))
def available_actions(self): #make non-default actions available
if self.enemy.is_alive():
return [actions.Flee(tile=self), actions.Attack(enemy=self.enemy)]
else:
return self.adjacent_moves()
class CopyCenter(ItemRoom):
def __init__(self, x , y):
super().__init__(x, y, items.Dollar(1))
def intro_text(self):
return """
As you walk by the Print and Copy Center, you notice something sticking out of the nearby mailbox.
It's a dollar! You put it in your wallet.
"""
class ColonialTheater(MapTile):
def intro_text(self):
return """
Another unremarkable part of Emerson's Campus. Still closed to the public, neat.
"""
def modify_player(self, the_player):
pass
class Colo(ItemRoom):
def __init__(self, x ,y):
super().__init__(x, y, items.Dollar(1))
def intro_text(self):
return """
As you pass by Colonial, you decide to pop into the mailroom.
You have one package to pickup.
Inside, from your grandma, is a single dollar bill.
Well at least it's not socks."""
class Sidewalk(MapTile):
def intro_text(self):
return """
Another unremarkable part of Boylston St."""
def modify_player(self, the_player):
pass
class BostonCommon(MapTile):
def intro_text(self):
return """
You walk all the way to the Boston Commons.
There's no Dunkin' near here.
You turn around."""
def modify_player(self, the_player):
pass
class BarnesandNoble(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Dollar(1))
def intro_text(self):
return """
You pass by the Barnes and Noble. Inside, overpriced apparel rots.
You decide to go in. Once inside, you purchase a lanyard.
The store is so grateful for a customer, they pay you.
You pocket one dollar.
"""
class TextbookStore(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Textbook())
def intro_text(self):
return """
You walk into the Tufte Textbook Store. It's quiet, as usual.
The clerk at the desk hands you something.
It's a textbook. You put it away for now.
"""
class PianoRow(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Coupon())
def intro_text(self):
return """
You walk into Piano Row. The securitas guard's eyes are glazed over.
Over on the table are a stack of flyers and coupons.
You take a coupon, maybe it works at Dunkin'.
"""
class ECPD(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Mace())
def intro_text(self):
return """
You walk up the ramp into the ECPD Office. There is a faint sound of crickets.
As you pass by the window, a can of Mace sit unattended.
You pocket the Mace.
"""
class Dunkin(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Creamer())
def intro_text(self):
return """
Finally, you walk into the Dunkin' Donuts. The line is massive.
So very, very massive.
As you wait in line, a coffee creamer rolls along the floor.
You pick up and pocket the coffee creamer.
"""
class Lockers(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Backpack())
def intro_text(self):
return """
As you walk up the stairs of the Campus Center, you end up in the hallway near the Max.
To the left of this hallway is a row of Grad Student lockers.
Sitting forlornly near one is a blue backpack. You pick it up.
"""
class Sidewalk2(ItemRoom):
def __init__(self, x, y):
print("Sidewalk2 init")
super().__init__(x, y, items.Purse())
def intro_text(self):
return """
As you walk along the sidewalk, you notice a bag at your feet.
It's your purse! Whoops, how did that get here?"""
class WalkerB(MapTile):
def intro_text(self):
return """
As you leave the alley and enter the basement of Walker, the securitas guard stares.
You rummage through your pockets for your ID. It's not there.
You dejectedly turn around and leave Walker.
"""
def modify_player(self, the_player):
pass
class Alley(MapTile):
def intro_text(self):
return """
The sidewalk ends and turns to brick. You look to your left and see the alleyway.
Down at the end of the alleyway, lies City Place.
"""
def modify_player(self, the_player):
pass
class Alley2(MapTile):
def intro_text(self):
return """
Another uneven, brick pathway in the alleyway.
"""
def modify_player(self, the_player):
pass
class CampusCenter(MapTile):
def intro_text(self):
return """
You pass through the hallway of Piano Row and head up the flight of stairs to the Campus Center.
Watch out for the spilled mozzarella sticks on the stairs!
"""
def modify_player(self, the_player):
pass
class Tufte(MapTile):
def intro_text(self):
return """
You swing open the large doors to the Tufte Building.
You walk inside.
"""
def modify_player(self, the_player):
pass
class Doorway(MapTile):
def intro_text(self):
return """
You go to open the doorway to City Place. You have to use both hands.
The doors are heavy and you are weak.
"""
def modify_player(self, the_player):
pass
class Foodcourt(MapTile):
def intro_text(self):
return """
Another greasy part of the City Place foodcourt.
"""
def modify_player(self, the_player):
pass
class Doorway2(MapTile):
def intro_text(self):
return """
You go to leave City Place. You can't.
The Dunkin' is literally right there.
Try again, kid.
"""
def modify_player(self, the_player):
pass
class DiningCenter(MapTile):
def intro_text(self):
return """
You go to enter the Dining Center. A sodexo employee stops you.
You don't live on campus.
You're out of meal swipes.
You shall not pass.
"""
def modify_player(self, the_player):
pass
#
#class Sidewalk2(ItemRoom):
# def __init__(self, x, y, item):
# super().__init__(x, y, items.Purse())
#
# def intro_text(self):
# return """
# As you walk along the sidewalk, you notice a bag at your feet.
# It's your purse! Whoops, how did that get here?
# """
class VisitorCenter(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.TourGuide())
def intro_text(self):
if self.enemy.is_alive():
return """
An Emerson Tour Guide blocks your path. They brace themselves with their weapon of overexaggerated facts.
"""
else:
return """
The last remaining Tour Guide cowers behind the counter.
"""
class WhiskeySaigon(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Clubgoer())
def intro_text(self):
if self.enemy.is_alive():
return """
From the doors of Whiskey Saigon busts out an obnoxious, drunk club goer looking for a fight.
"""
else:
return """
The club goer has now resorted to smoking heavily outside the club. You're not sure if this is much better than before.
"""
class Walker(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Securitas())
def intro_text(self):
if self.enemy.is_alive():
return """
Before you can step into the Walker elevators, a lethargic Securitas guard says "ID please."
"""
else:
return """
The Securitas agent is now fast asleep.
"""
class Griddlers(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.GriddlerEmployee())
def intro_text(self):
if self.enemy.is_alive():
return """
Before you can hurry along the sidewalk, a Griddlers employee stops you.
They make eye contact.
They have a flyer in their hand.
Oh god no.
"""
else:
return """
The corpse of a dead Griddler's employee rots along the sidewalk.
"""
class CenterStage(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Sodexo())
def intro_text(self):
if self.enemy.is_alive():
return """
You decide to stop for mozzarella sticks.
But when the Sodexo Employee hands you the box, there's 2 less than usual.
You can't allow this.
"""
else:
return """
The Sodexo employee is nowhere to be found. Students are looting for mozzarella sticks.
All is right with the world.
"""
class Tufte2(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Stairs())
def intro_text(self):
if self.enemy.is_alive():
return """
As you enter Tufte, you spot your longtime menace.
Two fights of stairs.
"""
else:
return """
The stairs will forever be here in Tufte.
But at least you have now conquered them.
"""
class Alley3(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Pidgeon())
def intro_text(self):
if self.enemy.is_alive():
return """
Suddenly, you stop in your tracks.
There in the alleyway, staring at you with its beady, little eyes...
A Pidgeon!
"""
else:
return """
The Pidgeon still sits in the alleyway. But no longer does he stare at you with contempt, but instead with respect.
"""
class Starbucks(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Starbucks())
def intro_text(self):
if self.enemy.is_alive():
return """
You walk into the Starbucks. The scent of coffee bitch slaps you in the face.
"Have you tried our new frappucino?" asks the tired barista.
"""
else:
return """
The barista is still there and still tired, but no longer do they offer you the new frappucino.
You have won.
"""
class FoodCourt2(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Baby())
def intro_text(self):
if self.enemy.is_alive():
return """
A mother carlessly pushing her baby in a stroller walks by.
As the stroller passes, the baby reaches out and smacks your leg.
Not today, baby.
"""
else:
return """
There are no strollers to be seen. This is your territory now.
"""
class Dunkin2(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Dunkin())
def intro_text(self):
if self.enemy.is_alive():
return """
Finally! At last! You've reached the end of the line.
But there before you stands the ultimate and most powerful enemy of your journey.
The Dunkin' Donuts barista.
Prepare for battle! (And coffee)
"""
else:
return """
The entire Dunkin' Donuts is on fire. You've defeated them once and for all.
You may run on Dunkin', but Dunkin' got ran over by you.
"""
class SevenEleven(EnemyRoom):
def __init__(self, x, y):
super().__init__(x, y, enemies.Pelton())
def intro_text(self):
if self.enemy.is_alive():
return """
You waltz into the 7/11.
Who is there, but the one and only Prezzy P?
He's eyeing the last Big Gulp cup.
Oh no you don't, Lee.
"""
else:
return """
Lee Pelton is no longer here, but you still smell the faint scent of tuition money.
"""
class TwoB(ItemRoom):
def __init__(self, x, y):
super().__init__(x, y, items.Dollar(1))
def intro_text(self):
return """
You walk into the lobby of 2B.
A dollar bill flutters down from the ceiling.
Woah, this place is literally made of money.
You pocket the dollar.
"""
class Dunkin3(MapTile):
def intro_text(self):
return """
You see a bright light in the distance...
... can it be?
It is!
Your morning coffee!
Victory is yours!
"""
def modify_player(self, player):
player.victory = True
|
cfed7dd7c7a90f60de005c1f1c02124bfc4f6ef1 | srinivasarao2468/Python | /class/class_variables.py | 1,031 | 3.96875 | 4 | class Employee:
amount_increment=1.04
def __init__(self, fname, lname, salary):
self.fname = fname
self.lname = lname
self.salary = salary
self.email = fname+"."+lname+"@gamil.com"
def fullname(self):
return "{} {}".format(self.fname, self.lname)
def amount_rise(self):
increment=self.salary*self.amount_increment
return increment
emp1 = Employee("Sri", "alluri", 50000)
emp2 = Employee("Hari", "kammana", 60000)
#amount increment of all the class and instances are same
print(emp1.amount_increment)
print(emp2.amount_increment)
print(Employee.amount_increment)
print(emp1.amount_rise())
#increment ammount only for perticular
emp1.amount_increment=1.05
print(emp1.amount_increment)
print(emp2.amount_increment)
print(Employee.amount_increment)
#increment to class variable again it changes all the values of instances
Employee.amount_increment=1.06
print(emp1.__dict__)
print(emp1.amount_increment)
print(emp2.amount_increment)
print(Employee.amount_increment)
|
96dc9f04059696a4f6b9af6233ee9de2cd73b927 | srinivasarao2468/Python | /Excercises/currentdata.py | 157 | 3.703125 | 4 | from datetime import datetime
print("current datetime ", datetime.now())
now = datetime.now()
print("current datetime\n", now.strftime("%Y-%m-%d %H:%M:%S"))
|
2a64573bd720f3a1634f1e31855f76116eb72d2d | lancelote/testing_python_book | /test/unit/calculator_app/calculate_test.py | 1,586 | 3.84375 | 4 | import unittest
from calculator_app.calculate import Calculate
class TestCalculate(unittest.TestCase):
def setUp(self):
self.calc = Calculate()
def test_add_method_returns_correct_result(self):
self.assertEqual(4, self.calc.add(2, 2))
def test_add_method_raises_typeerror_if_not_ints(self):
self.assertRaises(TypeError, self.calc.add, "Hello", "World")
def test_subtract_method_returns_correct_result(self):
self.assertEqual(4, self.calc.subtract(6, 2))
self.assertEqual(-2, self.calc.subtract(0, 2))
def test_subtract_method_raises_typeerror_if_not_ints(self):
self.assertRaises(TypeError, self.calc.subtract, "Hello", "World")
def test_multiply_method_returns_correct_result(self):
self.assertEqual(8, self.calc.multiply(4, 2))
self.assertEqual(0, self.calc.multiply(0, 2))
self.assertEqual(-4, self.calc.multiply(4, -1))
def test_multiply_method_raises_typeerror_if_not_ints(self):
self.assertRaises(TypeError, self.calc.multiply, "Hello", "World")
def test_divide_method_returns_correct_result(self):
self.assertEqual(4, self.calc.divide(8, 2))
self.assertEqual(0, self.calc.divide(0, 2))
self.assertEqual(-2, self.calc.divide(4, -2))
def test_divide_method_raises_typeerror(self):
self.assertRaises(TypeError, self.calc.divide, "Hello", "World")
def test_divide_method_raises_zerodivisionerror(self):
self.assertRaises(ZeroDivisionError, self.calc.divide, 1, 0)
if __name__ == '__main__':
unittest.main() |
39d9b6de8c992a3e3e9ce1594b45527b29f62634 | kelvinlegolas3/python-practice | /06-ObjectOrientedProgrammingv2.py | 1,097 | 3.9375 | 4 | # Assessment 6 : Object Oriented Programming v2
# Link : https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/05-Object%20Oriented%20Programming/04-OOP%20Challenge.ipynb
# 1.
print("Exercise # 1:")
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def __str__(self):
return f"Account owner: {self.owner} \nAccount balance: ${self.balance}"
def deposit(self, amount):
self.balance += amount
return f"Deposit Accepted. Your balance now is: {self.balance}"
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return f"Withdrawal Accepted. Your balance now is {self.balance}"
else:
return f"Attempted withdraw amount is: {amount}. Your remaning balance is only {self.balance}"
account1 = Account("Jose", 100)
print(account1.owner)
print(account1.balance)
print(account1)
print(account1.deposit(200))
print(account1.withdraw(300))
print(account1.withdraw(300)) |
059d0ddd6b41ff375c1296f092ed4a93ce77df7f | ahmad225/LeetCode | /Easy/Python/reverseInteger.py | 282 | 3.75 | 4 | def reverse(x: int) -> int:
reversed = 0
while x != 0:
temp = reversed * 10 + x % 10
if temp / 10 != reversed:
return 0 #overflow of integer
reversed = temp
x /= 10
return reversed
i = 2**40
print(9646324351 > 2 ** 31 - 1)
|
758a310ed0ad0ba45b24b35b75702f85f1aa61bc | TimIainMarsh/Project-Euler | /Problem1.py | 300 | 3.828125 | 4 | # list1 = []
# for i in range(1000):
# # i%3 will produce zero if i is divisable by 3 - zero is seen as false that is why
# # it is not(i%3)
# if not(i%3) or not(i%5):
# list1.append(i)
# sum = 0
# for i in list1:
# sum += i
# print(sum)
for i in range(20,0,-1):
print(i) |
3efa7e30fb15bcf535e23fed76bbc3f2b6071625 | Kontetsu/pythonProject | /example6.py | 160 | 3.921875 | 4 | # Comparison operators
john_1 = "John"
john_2 = "John"
print(john_1 == john_2)
print(1 != 1)
print(99 < 1.1)
print(99 > 1.1)
print(-32 >= -33)
print(123 <= 123) |
9a187a02324ff8272baffd64344857c219549ef3 | Kontetsu/pythonProject | /example40.py | 241 | 3.703125 | 4 | # Exceptions
# Divide smth by zero
a = 1
b = [1, 2, 3, 0, 0, "string", "hello"]
for element in b:
try:
print(a / element)
except (ZeroDivisionError, TypeError) as error:
print("This is an exception {}".format(error)) |
5b2887021b660dfb5bca37a6b395b121759fed0a | Kontetsu/pythonProject | /example24.py | 659 | 4.375 | 4 | import sys
total = len(sys.argv) - 1 # because we put 3 args
print("Total number of args {}".format(total))
if total > 2:
print("Too many arguments")
elif total < 2:
print("Too less arguments")
elif total == 2:
print("It's correct")
arg1 = int(sys.argv[1])
arg2 = int(sys.argv[2])
if arg1 > arg2:
print("Arg 1 is bigger")
elif arg1 < arg2:
print("Arg 1 is smaller")
else:
print("Arg 1 and 2 are equal!")
# some methods how to check the user input pattern
print("string".isalpha())
print("string1".isalnum())
print("string".isdigit())
print("string".startswith('s'))
print("string".endswith('g')) |
e8310a33a0ee94dfa39dc00ff5027d61c74e6d94 | Kontetsu/pythonProject | /example27.py | 748 | 4.28125 | 4 | animals = ["Dog", "Cat", "Fish"]
lower_animal = []
fruits = ("apple", "pinnaple", "peach")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#for anima in animals:
# lower_animal.append(anima.lower())
print("List of animals ", animals)
for animal in animals:
fave_animal = input("Enter yor favorite animal from the list: ")
#print("Animals {}".format(animal))
if animal == fave_animal:
print("Your favorite animal Catis :", animal)
break
#for fruit in fruits:
# print("Fruits {}".format(fruit))
#for vehicles in thisdict.items():
# print("Vehicles {} {}".format(vehicles[0], vehicles[1]))
#for k, v in thisdict.items(): # is better
# print("Vehicles {} {}".format(k, v)) |
7b53f5e59aaa660a1e5c8be1541a55f888966e1c | hfw6310/LeetCode-Method | /206. 反转链表.py | 1,003 | 4 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 递归
if head == None or head.next == None:
return head
p = self.reverseList(head.next)
# 交换当前head 和 head.next
head.next.next = head
head.next = None
return p
'''
#解题思路:新建一个头结点,将所有的原链表节点从头到尾逐一取下,采用头插法插入整个链表到新建节点之前,则完成了链表逆序的目的。
new_head = None
while head :
tmp = head.next # 备份原来head节点的next地址
head.next = new_head
new_head = head
head = tmp
return new_head
''' |
2f206911f23fee3c39bdfc19824907c366146a3b | hfw6310/LeetCode-Method | /234. 回文链表.py | 1,106 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# 堆栈
stack = []
# step1: push
curr = head
while (curr):
stack.append(curr)
curr = curr.next
# step2: pop and compare
node1 = head
while (stack):
node2 = stack.pop()
if node1.val != node2.val:
return False
node1 = node1.next
return True
'''
#递归
self.front_pointer = head
def recursively_check(current_node=head):
if current_node is not None:
if not recursively_check(current_node.next):
return False
if self.front_pointer.val != current_node.val:
return False
self.front_pointer = self.front_pointer.next
return True
return recursively_check()
''' |
9e9bd791108484ce6835338381726b17dbc52d83 | littlet1968/div_scripts | /matchDate.py | 2,476 | 3.75 | 4 | from datetime import datetime
def match_date(myDate):
try:
# we only have a date?
if len(myDate.split(' ')) == 1:
try:
myDObj = datetime.strptime(myDate, '%d-%b-%Y')
# return date object in form "DD-MM-YYY"
return(myDObj)
except Exception as ie:
print("Error dateonly :", ie)
print("For date only please provide date in the format 'DD-Mon-YYYY'")
return(False)
elif len(myDate.split(' ')) == 2:
try:
# try to split the time based on the : (string -1 to remove a may ending : e.g.: 04: = 04)
if len(myDate.split(' ')[1][:-1].split(':')) == 1:
# return date object in form "DD-MM-YYY HH24"
try:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H')
except ValueError:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H:')
return(myDObj)
elif len(myDate.split(' ')[1][:-1].split(':')) == 2:
# return date object in form "DD-MM-YYY HH24:MI"
try:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H:%M')
except ValueError:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H:%M:')
return(myDObj)
elif len(myDate.split(' ')[1][:-1].split(':')) == 3:
# return date object in form "DD-MM-YYY HH24:MI:SS"
try:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H:%M:%S')
except ValueError:
myDObj = datetime.strptime(myDate, '%d-%b-%Y %H:%M:%S:')
return(myDObj)
except Exception as ie:
print("Error date-time :", ie)
print("Date-Time format should be in the format:")
print(" -> 'DD-Mon-YYYY HH24'")
print(" -> 'DD-Mon-YYYY HH24:MI'")
print(" -> 'DD-Mon-YYYY HH24:MI:SS'")
return(False)
else:
print("Date not recognized")
return(False)
except Exception as oe:
print("No date string given I suppose:", oe)
return(False)
print(match_date('17-Oct-2020 13:9:1'))
|
2c7b93cc1861afa5516f966e22e45c0a7e47f701 | LauraSiobhan/beginning_python_jan2020 | /students/ryan/exercise_14_2.py | 209 | 3.796875 | 4 | card_list = [(3, 'diamonds'), (8, 'clubs')]
total = 0
for item in card_list:
number = item[0]
suit = item[1]
print(f'{number} of {suit}')
total += number
print(f'My total number of points is {total}')
|
d210715994b35fe9e77948473c5ad580111f1e8a | LauraSiobhan/beginning_python_jan2020 | /examples/blackjack.py | 3,887 | 3.96875 | 4 | """ This is a simple implementation of a blackjack game. The basic rules are:
the dealer deals you cards, starting with two, then adding one if you "hit".
Your goal is to reach, but not exceed, 21 points. If the dealer has more
points than you without going over 21, they win. If you have more points than
the dealer without going over 21, you win. """
import random
# my_deck = [('2', 'hearts'), ('3', 'hearts'), ('4', 'hearts')...]
VALUES = [(str(num), num) for num in range(2,11)]
VALUES.extend([('J', 10), ('Q', 10), ('K', 10), ('A', 11)])
SUITS = ['diamonds', 'hearts', 'spades', 'clubs']
def make_deck():
""" return a deck of card tuples """
this_deck = []
for suit in SUITS:
for value in VALUES:
this_card = (value[0], suit)
this_deck.append(this_card)
return this_deck
def deal_cards(deck, player1, player2):
""" deal cards from the deck list, out to each of the players. no return
value """
for _ in range(2):
for player in (player1, player2):
deal_card(deck, player)
def deal_card(deck, player_hand):
""" deal a single card. no return value. """
this_card = deck[-1]
player_hand.append(this_card)
del(deck[-1])
def get_player_input(deck, hand):
""" let the player hit as many times as they want """
# show the player their hand
answer = ''
while answer != 's':
print('Your cards:')
points = get_hand_value(hand)
for card in hand:
print(card)
print(f'You have {points} points')
if points > 21:
print('Bust!')
return
answer = input('Hit or stay? (h or s) ')
if answer == 'h':
deal_card(deck, hand)
print('Your final hand:')
for card in hand:
print(card)
def get_dealer_hand(deck, hand):
""" figure out the dealer's hand """
while True:
points = get_hand_value(hand)
if points < 19:
deal_card(deck, hand)
elif points > 21:
return "Bust"
else:
break
def get_hand_value(hand):
""" determine the value of a hand """
points = 0
for card in hand:
points += get_points(card)
return points
def get_points(card):
""" pass in a card tuple (value, suit), and return the number of points
it's worth """
value = card[0]
for item in VALUES:
if item[0] == value:
return item[1]
def main():
""" run the game """
my_deck = make_deck()
random.shuffle(my_deck)
player_hand = []
dealer_hand = []
deal_cards(my_deck, player_hand, dealer_hand)
# now, player and dealer each have two cards
get_player_input(my_deck, player_hand)
dealer_result = get_dealer_hand(my_deck, dealer_hand)
print("Dealer's hand:")
for card in dealer_hand:
print(card)
player_points = get_hand_value(player_hand)
dealer_points = get_hand_value(dealer_hand)
print(f"Dealer has {dealer_points} points")
if dealer_result == "Bust":
print("Dealer busts, you win!")
else:
if dealer_points > player_points:
print("Dealer wins!")
else:
print("You win!")
def test_deal_cards():
print('testing the deal_cards function')
my_deck = make_deck()
expected_player1 = []
expected_player2 = []
expected_player1.append(my_deck[-1])
expected_player2.append(my_deck[-2])
expected_player1.append(my_deck[-3])
expected_player2.append(my_deck[-4])
player1 = []
player2 = []
deal_cards(my_deck, player1, player2)
print('checking assertions')
assert(expected_player1[0] == player1[0])
assert(expected_player1[1] == player1[1])
assert(expected_player2[0] == player2[0])
assert(expected_player2[1] == player2[1])
if __name__ == '__main__':
main()
#test_deal_cards()
|
089268b059eb6f71a886c24ed1e6ed55fa6a58e9 | mabauer/aoc2020 | /src/day09.py | 2,710 | 4.09375 | 4 | #!/usr/bin/env python3
import re
import os
import sys
from typing import List
from utils import read_inputfile
# Convert input into list of ints
def read_numbers(input: List[str]) -> List[int]:
result = [ int(line) for line in input ]
return result
# Verify if number equals to the sum of some pair in to_consider
def verify_number(number: int, to_consider: List[int]) -> bool:
# print("%d -> %s" % (number, to_consider))
for first in to_consider:
for second in to_consider:
if first != second:
if number == first + second:
# print("%d %d" % (first, second))
return True
return False
# Find the weakness in a list of ints, i.e. a number that cannot be reproduced by the sum of
# some pair of numbers in a rolling window of numbers previously read
# Consider a sliding/rolling window of window_size.
def find_weakness(input: List[int], window_size: int) -> int:
if len(input) <= window_size + 1:
raise ValueError("Input too short")
# Prefill window
sliding_window = input[:window_size]
input = input[window_size:]
while len(input) > 0:
# "Pop" the next item from the input
next = input[0]
input = input[1:]
if not verify_number(next, sliding_window):
return next
# Move sliding window by 1
sliding_window.append(next)
sliding_window = sliding_window[1:]
raise ValueError("No weakness found")
# Find a contiguous block of numbers whose sum equals weakness
def find_contiguous_block(input: List[int], weakness: int) -> List[int]:
block : List[int] = []
i = 0
sum = 0
while i < len(input):
j = i
# Try building a block starting from position j
sum = 0
block = []
while j < len(input) and sum < weakness:
next = input[j]
sum += next
block.append(next)
if sum == weakness:
return block
j += 1
i += 1
return block
def part1(input, window_size=25):
return find_weakness(read_numbers(input), window_size)
def part2(input, window_size=25):
numbers = read_numbers(input)
weakness = find_weakness(numbers, window_size)
block = find_contiguous_block(numbers, weakness)
first = min(block)
second = max(block)
result = first + second
return result
def main():
# Official input
input = read_inputfile("input09.txt")
print("The solution for part 1 on the official input is %d" % (part1(input)))
print("The solution for part 2 on the official input is %d" % (part2(input)))
if __name__ == "__main__":
main()
|
309858fc891519e6fd7b4f9913ec9b759215f034 | mabauer/aoc2020 | /src/day10.py | 4,552 | 3.765625 | 4 | #!/usr/bin/env python3
import re
import os
import sys
from typing import List
from typing import Tuple
from typing import Dict
from utils import read_inputfile
# Convert input into list of ints
def read_numbers(input: List[str]) -> List[int]:
result = [ int(line) for line in input ]
return result
# Count the 1- and 3-step joltage jumps for part 1
def find_differences_in_adapter_chain(adapters: List[int]) -> Tuple[int, int]:
adapters.sort()
i = 0
prev = 0
ones = 0
threes = 0
while i < len(adapters):
next = adapters[i]
if next - prev == 1:
ones += 1
else:
if next -prev == 3:
threes += 1
else:
raise ValueError("Difference != 0 or 3")
prev = next
i += 1
threes += 1
return (ones, threes)
# Compute all possible varinats of adapter chains
# This does not terminate for longer inputs!!!
def find_adapter_chains(start: int, adapters: List[int], chain=None) -> List[List[int]]:
if chain == None:
chain = []
current = adapters[start]
chain.append(current)
# print("%s, -- %d" % (chain, current))
if start == len(adapters)-1:
return [chain]
chains: List[List[int]] = []
pos = start + 1
while pos < len(adapters):
next = adapters[pos]
difference = next - current
if difference > 3:
break
if difference <= 3 :
chains = chains + find_adapter_chains(pos, adapters, chain.copy())
pos += 1
return chains
# Count the number of all possible varinats of adapter chains using dynamic programming
# By memorizing previously computed partial results this implementation works for larger inputs!
def count_adapter_chains(start: int, adapters: List[int], memo: Dict[int, int]=None) -> int:
if memo == None:
memo = {}
current = adapters[start]
if start == len(adapters)-1:
return 1
if memo is not None and start in memo:
return memo[start]
chains = 0
pos = start + 1
while pos < len(adapters):
next = adapters[pos]
difference = next - current
if difference > 3:
break
if difference <= 3 :
chains = chains + count_adapter_chains(pos, adapters, memo)
pos += 1
if memo is not None:
memo[start] = chains
return chains
def count_adapter_chains_iterative(adapters: List[int]) -> int:
# maybe_skipped[i] will contain a list of all adapters that can possibly omitted
# while building an adapter chain starting from adapter with joltage i
maybe_skipped : Dict[int, List[int]] = {}
for adapter in adapters:
maybe_skipped[adapter] = []
for adapter in adapters:
for difference in [1, 2, 3]:
next = adapter + difference
if next in adapters:
maybe_skipped[adapter].append(next)
# Count the number of possible chains backwards:
# For the last adapter, there is only one possibility of building a chain
# For earlier ones, it is the sum of all possibilities of those that we have previously computed.
# For [0, 1, 3, 4]:
# skippable[0] = [1, 3], skippable[1] = [3, 4], skippable[3] = [4], skippable[4]=[]
# chains[4] = 1,
# chains[3] = chains[4] = 1
# chains[1] = chains[3] + chains[4] = 1 + 1 = 2
# chains[0] = chains[1] + chains[3] = 2 + 1 = 3 <= There are 3 possible chains
chains : Dict[int, int] = {}
chains[adapters[len(adapters)-1]] = 1
for adapter in reversed(adapters[0:len(adapters)-1]):
sum = 0
# print("%d: %s" % (adapter, maybe_skipped[adapter]))
for next in maybe_skipped[adapter]:
sum += chains[next]
chains[adapter] = sum
return chains[0]
def part1(input):
adapters = read_numbers(input)
(ones, threes) = find_differences_in_adapter_chain(adapters)
result = ones * threes
return result
def part2(input):
adapters = read_numbers(input)
adapters.append(0)
device = max(adapters) + 3
adapters.append(device)
adapters.sort()
# chains = count_adapter_chains(0, adapters, {})
chains = count_adapter_chains_iterative(adapters)
return chains
def main():
# Official input
input = read_inputfile("input10.txt")
print("The solution for part 1 on the official input is %d" % (part1(input)))
print("The solution for part 2 on the official input is %d" % (part2(input)))
if __name__ == "__main__":
main()
|
a2e7daef49e13c888bac2502866972f7d7c8598e | mabauer/aoc2020 | /src/utils.py | 199 | 3.5625 | 4 | from typing import List
import os
def read_inputfile(filename: str) -> List[str]:
with open("input" + os.path.sep + filename) as f:
input = [line.strip() for line in f]
return input |
1688c93855bda769c0e21a5cbfb463cfe3cc0299 | JimVargas5/LC101-Crypto | /caesar.py | 798 | 4.25 | 4 | #Jim Vargas caesar
import string
from helpers import rotate_character, alphabet_position
from sys import argv, exit
def encrypt(text, rot):
'''Encrypts a text based on a pseudo ord circle caesar style'''
NewString = ""
for character in text:
NewChar = rotate_character(character, rot)
NewString = NewString + NewChar
return NewString
def main(rot):
if rot.isdigit():
text = input("Type the message that you would like to encrypt: ")
#rot = int(input(Rotate by:))
rot = int(rot)
print(encrypt(text, rot))
else:
print("You need to enter an integer argument.")
exit()
if __name__ == '__main__':
if len(argv) <=1:
print("You need to enter an integer argument.")
exit()
else:
main(argv[1]) |
98b83cd4a9300252b7a6f5c9f8ab63aba966c33b | deyoung1028/Python | /classwork7_15.py | 1,090 | 4 | 4 | #json
# int, float, bool, dictionary, array
#array of int, array of dictionary, array of bool, etc.
import json
from os import name
# write json
#with open("car.json", "w") as file
#car = {"make":"Honda", "model": "Accord", "noOfCylinders":2}
#json.dump(object you want to write, file object)
# json.dump(car,file)
users = []
while True: #loop
with open("users.json", "w") as file: #setup for writing a json file
json.dump(users,file) # command to write a json file
name = input("Please enter your name:")
age = int(input("please enter age:"))
user = {"name": name, "age": age} # dictionary format for array
users.append(user) #adds a new user to the array
choice = input("Q to quit")
if choice =="q":
break
#read JSON
with open("users.json") as file: #setup for reading a json file
person = json.load(file) # command to create a json that you can read
for user in users: #loop to display users and user ages
print(user["name"])
print(user["age"])
|
b211b888702bbb1ebed8b6ee2b21fec7329a7b59 | deyoung1028/Python | /to_do_list.py | 1,738 | 4.625 | 5 | #In this assignment you are going to create a TODO app. When the app starts it should present user with the following menu:
#Press 1 to add task
#Press 2 to delete task (HARD MODE)
#Press 3 to view all tasks
#Press q to quit
#The user should only be allowed to quit when they press 'q'.
#Add Task:
#Ask the user for the 'title' and 'priority' of the task. Priority can be high, medium and low.
#Delete Task: (HARD MODE)
#Show user all the tasks along with the index number of each task. User can then enter the index number of the task to delete the task.
#View all tasks:
#Allow the user to view all the tasks in the following format:
#1 - Wash the car - high
#2 - Mow the lawn - low
#Store each task in a dictionary and use 'title' and 'priority' as keys of the dictionary.
#Store each dictionary inside an array. Array will represent list of tasks.
#** HINT **
#tasks = [] # global array
#input("Enter your option")
tasks = [] #global array
def view_tasks():
print(tasks)
while True:
print("Please make a choice from the following menu:")
print("1 - Add Task")
print("2 - Delete Task")
print("3 - View all tasks ")
print("q to quit")
choice = input("Enter Choice:")
if choice == "q":
break
if choice == "1":
title = input("Please enter a task title:")
priority = input("Please enter priority : high, medium or low - ")
task = {"title": title, "priority": priority}
tasks.append(task)
if choice == "2":
view_tasks()
del_task = int(input("Chose a task to delete:" ))
del tasks[del_task - 1]
view_tasks()
if choice == "3":
view_tasks()
print(tasks) |
e41796d392658024498869143c8b8879a7916968 | deyoung1028/Python | /dictionary.py | 487 | 4.21875 | 4 | #Take inputs for firstname and lastname and then create a dictionary with your first and last name.
#Finally, print out the contents of the dictionary on the screen in the following format.
users=[]
while True:
first = input("Enter first name:")
last = input("Enter last name:")
user = {"first" : first, "last": last}
users.append(user)
choice = input("Enter q to quit or any key to continue:")
if choice == "q":
break
print(users)
|
210c1ad4af6f4f8e6d59be5997cfd4af820a60e1 | jhonatacaiob/EXERCICIOS-DE-REPETI-AO-DE-LOGICA | /QUESTÃO 7.py | 687 | 3.78125 | 4 | primeira=[]
segundo=[]
terceiro=[]
quarto=[]
quinto=[]
def preguiça(x):
print("Nessa lista, existem", len(x), "pessoas")
for i in range (1,16,1):
idades = int(input("QUAL SUA IDADE?: "))
if idades<=0:
print("Você não é um recém nascido")
elif idades <= 15:
primeira += [idades]
elif idades >= 16 and idades <= 30:
segundo += [idades]
elif idades >= 31 and idades <= 45:
terceiro += [idades]
elif idades >= 46 and idades <= 60:
quarto += [idades]
elif idades > 60:
quinto += [idades]
preguiça(primeira)
preguiça(segundo)
preguiça(terceiro)
preguiça(quarto)
preguiça(quinto) |
b4b7af57d632857f823abddf5385ed1d8f802c6b | hieast/PlayGround | /MOOC/Rice/AIIPP(An Introduction to Interactive Programming in Python)/Stopwatch The Game.py | 1,870 | 3.5625 | 4 | #"Stopwatch: The Game"
import simplegui
# define global variables
width = 300
hight = 200
font_size = 48
seconds = 0
success = 0
stoped = 0
running = False
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
if t >= 6000:
return "Boommmmmm!"
d = t%10
remains = t//10
bc = remains%60
a = remains//60
if bc < 10:
string = string = str(a) + ":0" + str(bc) + "." + str(d)
else:
string = str(a) + ":" + str(bc) + "." + str(d)
return string
# define event handlers for buttons; "Start", "Stop", "Reset"
def start():
global running
running = True
timer.start()
def stop():
global running, success, stoped
if running:
success += (seconds%10) == 0
stoped += 1
running = False
timer.stop()
def reset():
global seconds, running, success, stoped
seconds = 0
success = 0
stoped = 0
if running:
running = False
timer.stop()
# define event handler for timer with 0.1 sec interval
def tick():
global seconds
seconds += 1
# define draw handler
def draw(canvas):
canvas.draw_text(format(seconds),
[0.5 * width - 1.5 * font_size, 0.5 * (hight + font_size)],
font_size, "White")
canvas.draw_text( str(success) + "/" + str(stoped),
[width - font_size, 0.75 * font_size],
font_size/2, "Red")
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", width, hight)
# register event handlers
frame.add_button("Start", start, 200)
frame.add_button("Stop", stop, 200)
frame.add_button("Reset", reset, 200)
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100,tick)
# start frame
frame.start()
# Please remember to review the grading rubric
|
47a0012507170ee674d6b2096d69059606842e2d | AnanditaGuha/Chapter4Anandita_Hunter | /fiveb.py | 273 | 3.734375 | 4 | import turtle
def draw_spiral(t,n,sz,ang):
for i in range(n):
t.right(ang)
t.forward(sz)
sz = sz + 5
wn = turtle.Screen()
tess = turtle.Turtle()
wn.bgcolor("lightgreen")
tess.color("blue")
tess.pensize(3)
draw_spiral(tess,99,5,89)
tess.right(90) |
63d5e945c98414589b8511ac360b670e836d9eaa | KritikRawal/Lab_Exercise-all | /2.11.py | 96 | 3.921875 | 4 | """What is the result of 10**3?"""
print("The result of 10**3 is: ")
print(10 ** 3)
print() |
74dee8921f4db66c458a0c53cd08cb54a2d1ba63 | KritikRawal/Lab_Exercise-all | /4.l.2.py | 322 | 4.21875 | 4 | """ Write a Python program to multiplies all the items in a list"""
total=1
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total * list1[ele]
# printing total value
print("product of all elements in given list: ", total) |
d71d9e8c02f405e55e493d1955451c12d50f7b9b | KritikRawal/Lab_Exercise-all | /3.11.py | 220 | 4.28125 | 4 | """ find the factorial of a number using functions"""
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input('enter the number'))
print(factorial)
|
53b8278af9a4a98b4de820d91054d80e9f1247f4 | KritikRawal/Lab_Exercise-all | /3.8.py | 393 | 4.125 | 4 | """takes a number as a parameter and check the number is prime or not"""
def is_prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
print('Start')
val = int(input('Enter the number to check prime:\n'))
ans = is_prime(val)
if ans:
print(val, 'Is a prime number:')
else:
print(val, 'Is not a prime number:')
|
1f611b99273d9a3b4f8cf798e9c6834868a8dded | KritikRawal/Lab_Exercise-all | /4.8.py | 192 | 3.84375 | 4 | """display the Fibonacci series between 0 and 50"""
disp = 0
a = 1
series = []
while disp <= 50:
series.append(disp)
temp = disp
disp = disp + a
a = temp
print(series) |
9bd2b639bea460194c13fea4a4964f0ee94e1fc8 | KritikRawal/Lab_Exercise-all | /4.l.4.py | 176 | 3.984375 | 4 | """Write a Python program to get the smallest number from a list."""
list1 = [10, 20, 4, 45, 99]
# printing the minimum element
print("smallest element is:", min(list1)) |
ae6ae8cfe7e655b1ffc9617eb8d87480a97e8f27 | KritikRawal/Lab_Exercise-all | /4.2.py | 635 | 4.4375 | 4 | """. Write a Python program to convert temperatures to and from celsius,
fahrenheit.
C = (5/9) * (F - 32)"""
print("Choose the conversion: ")
print(" [c] for celsius to fahrenheit")
print(" [f] for fahrenheit to celsius")
ans = input()
conversion = 0
cs = ""
if ans == "c":
ans = "Celsius"
elif ans == "f":
ans = "Fahrenheit"
print(f"Enter your temperature in {ans}")
temp = int(input())
if ans == "Celsius":
conversion = temp * (9 / 5) + 32
cs = "Fahrenheit"
elif ans == "Fahrenheit":
conversion = (5 / 9) * (temp - 32)
cs = "Celsius"
print(f"{temp} ({ans}) is {conv} ({cs})")
print() |
b9e75d0b9d9605330c54818d1dd643cc764032cf | KritikRawal/Lab_Exercise-all | /2.5.py | 277 | 4.21875 | 4 | """For given integer x,
print ‘True’ if it is positive,
print ‘False’ if it is negative and
print ‘zero’ if it is 0"""
x = int(input("Enter a number: "))
if x > 0:
print('positive')
elif x<0:
print('negative')
else:
print('zero') |
e76c314a76e8dfbab059db55880212321501f8e6 | dmccuk/the_python_mega_course | /String_Manuipulation/stock_v_writers.py | 576 | 3.5625 | 4 | o = 790
h = 6
names_rating = {"Lucy": 18, "Mary": 12, "Henry": 10, "Stacey": 11, "Loulou": 5}
print("")
print("Hours to comlete %s orders" % o)
for i in names_rating.values():
x = o / i
print(round(x,1))
print("")
print("Hours taken for everyone working together to complete %s order" % o)
print(o / sum(names_rating.values()))
print("")
print("Ornaments completed in %s hours - per Person" % h)
for i in names_rating:
print(i, names_rating[i] * h)
print("")
print("Ornements Per Hour with eveyone working")
print(h / h * sum(names_rating.values()))
print("") |
f7026478851e7f253d9786928bdd2f65d1b7098b | dmccuk/the_python_mega_course | /User_input/string_formatting uppercase.py | 153 | 3.953125 | 4 | def name(value):
first = value.capitalize()
message = "Hi %s" % (first)
return message
name1 = input("Enter your name: ")
print(name(name1)) |
815dfb869742fe6053bc5edbca8760044a00cdda | pniedzwiedzinski/cpp-cuda-linear-regression | /scripts/linear_regression.py | 1,116 | 4.03125 | 4 | """
This module contains python implementation of linear regression algorithm,
that I will be then implement in CUDA. I will be using data generated from
`generate_data.py`, which generates data of function `y = 3x + 2`.
The model will is of form `y = X * W` where `X` is a vector of features and
`W` is a vector of weights.
"""
import numpy as np
from generate_data import generate_data
def mse(true_y: "np.array", pred_y: "np.array") -> float:
"""
This function calculates the mean squared error (MSE) of the model
based on its predictions (`pred_y`) on true labels (`true_y`).
"""
return np.mean((true_y - pred_y)**2)
def calculate_weights(X, y):
return np.linalg.inv(X.transpose() @ X) @ X.transpose() @ y
if __name__ == "__main__":
data_x, data_y = generate_data(1000000)
X = np.array(data_x).reshape(len(data_x), 1)
y = np.array(data_y)
X = np.insert(X, 0, 1, axis=1)
weights = calculate_weights(X, y)
pred = X @ weights
print(f"mse: {mse(y, pred)}")
print(f"predicted: y = {weights[1]} * x + {weights[0]}")
print("true: y = 3 * x + 2")
|
0ec3619cec0dc520dabfe5fe4317acc9f95312fb | bugxiaoc/spider-Demo | /spider_Demo/tools/stringu.py | 808 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
"""
String Util
"""
def checkURI(str):
if re.search('',str,re.S):
return 1
else:
return 0
def delete_space(obj):
while '' in obj:
obj.remove('')
return obj
def fromat_list(obj):
temp = []
for x in obj:
temp.append(x.strip().replace("\n", "").replace(" ", ""))
return temp
def toString(result,result1):
ls1 = delete_space(fromat_list(result))
ls2 = delete_space(fromat_list(result1))
for i in range(0,len(ls1)):
print ls1[i],ls2[i]
def toString(result,result1,result2):
ls1 = delete_space(fromat_list(result))
ls2 = delete_space(fromat_list(result1))
ls3 = delete_space(fromat_list(result2))
for i in range(0,len(ls1)):
print ls1[i],ls2[i],ls3[i] |
3de052724e3e39f88b6cdeaf03793aaeab0eafd8 | DJMedhaug/mad_libs | /madlib.py | 523 | 4 | 4 | animal = input('Enter an animal ')
madlib = animal
madlib += ' can be found running wild in '
madlib += input(' Enter a city... ')
madlib += ' causing distruction at every turn, when he turned '
madlib += input('Enter a color ')
madlib += ' he gained strength and speed, {} tried to run from the people. '.format(animal)
madlib += 'When he changed color the people ran the other way and jumped into a '
madlib += input('Enter a car ')
madlib += ' and took off, from there he was free to do as he pleased. '
print (madlib)
|
336721b955f93d2642cb854994909e450d6d15c1 | Anas321/single_stone_task | /spark_sql.py | 1,505 | 3.5 | 4 | """Start a spark session to generate the required document."""
from pyspark.sql import SparkSession
import config
def generate_json_report(input_files, report_file_name=config.OUTPUT_FILE):
"""Generate a json report by starting a spark session.
Args:
- input_files: input files names.
- report_file_name: name of the output json file.
Returns:
- There are no to direct returns from this function.
"""
# Start the spark session
spark = (SparkSession
.builder
.appName('SparkApplication')
.getOrCreate())
# Loop through the input files
for file in input_files:
file_format = file.split('.')[1]
table_name = file.split('.')[0]
(spark.read.format(file_format)
.option("inferSchema", "true")
.option("header", "true")
.load(file)
.select('fname', 'lname', 'cid')).createOrReplaceTempView(table_name)
# SQL query to join the two tables
((spark.sql("""
SELECT concat(st.fname, ' ', st.lname) as `student name`,
concat(te.fname, ' ', te.lname) as `teacher name`,
st.cid as `class ID`
FROM {0} as st
JOIN {1} as te
ON st.cid = te.cid
""".format(input_files[0].split('.')[0],
input_files[1].split('.')[0])))
.toPandas()
.to_json(report_file_name))
# Stop the spark session
spark.stop()
|
d3271b426ac5456f44d241952152409ed5acb612 | erick-guerra/python-oop-learning | /Python Beyond the Basics - Object-Oriented Programming - Working Files/Chapter 3/1_classes.py | 448 | 3.9375 | 4 |
class MyClass(object):
var = 10
# this_obj is a MyClass instance or MyClass Object
this_obj = MyClass()
# created second instance to show different hex cod (memory address)
that_obj = MyClass()
print(this_obj)
print(that_obj)
print(this_obj.var) # Instance access variable from the class; 10
print(that_obj.var)
class Joe(object):
def callme(self):
print('Calling "Call me" method instance: ')
thisjoe = Joe()
thisjoe.callme()
|
379041e760fc23eadd2de54d6a67c3bcf1cec6df | erick-guerra/python-oop-learning | /Python Beyond the Basics - Object-Oriented Programming - Working Files/Chapter 5/scratch_dir/scratch.py | 663 | 3.53125 | 4 | import os
class DictConfig(dict):
def __init__(self, filename):
self._file_name = filename
if os.path.isfile(self._file_name):
with open(self._file_name, 'a') as fh:
fh.writelines("{key}={value}\n".format(key=key, value=value))
def __setitem__(self, key, value):
print("Set Item")
dict.__setitem__(self, key, value)
def __getitem__(self, item):
print("Getting dictionary")
with open('config_file.txt') as fh:
for line in fh:
line = line.split('=')
self.dict[line[0]] = line[1]
return dict.__getitem__(self, item)
# def __getitem__(self, item):
a = DictConfig("config_text.txt")
print(a)
a['B'] = '3'
a['C'] = '1'
a['B'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.