blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4d1c1f7fde435cb6512b1c7bc60bc6207f424a7c | subodhss23/python_small_problems | /hard_problems/sort_by_letters.py | 577 | 4.1875 | 4 | ''' Write a function that sorts each string in a list by the letter in alphabetic ascending order(a-z)'''
def sort_by_letter(lst):
new_lst = []
new_obj = {}
list_two = []
for i in lst:
for j in i:
if j.isalpha():
new_obj[j] = i
sorted_lst = sorted(new_obj)
for i in sorted_lst:
list_two.append(new_obj[i])
return list_two
print(sort_by_letter(["932c", "832u32", "2344b"]))
print(sort_by_letter(["99a", "78b", "c2345", "11d"]))
print(sort_by_letter(["572z", "5y5", "304q2"]))
print(sort_by_letter([])) |
ad8d2cf3cf60563ebce447aa82c60e293cc1c144 | magonzalezo/aprender_python | /08-Funciones/predefinidas.py | 1,136 | 4.375 | 4 | """
Funciones que ya trae consigo Python
"""
nombre = "Miguel Gonzalez"
##### Generales
# Imprimir por pantalla
print(nombre)
# Indicar tipo de variable
print("")
print(type(nombre))
# Detectar tipo
print("")
comprobar = isinstance(nombre, str)
if comprobar:
print("La variable es un String")
else:
print("La variable no es un String")
# Limpiar espacios
print("")
frase = " cadena que contiene espacios a los lados "
print(frase)
print(frase.strip())
# Borrar variables
print("")
variable = "Texto con lo que sea"
print(variable)
del variable
#print(variable)
# Comprobar variable vacia
print("")
texto = " texto"
if len(texto) <= 0:
print("La variable esta vacia")
else:
print("La variable tiene contenido:", len(texto))
# Encontar caracteres
print("")
frase = "La belleza esta en el ojo del observador"
print(frase.find("esta"))
# Reemplazar palabras en un String
print("")
frase_original = "Los dioses estan locos"
nueva_frase = frase_original.replace("locos", "gordos")
print(frase_original)
print(nueva_frase)
# Mayusculas y Minusculas
print("")
print("MaYusCuLa".upper())
print("MiNuScUlA".lower()) |
0b633068e5bc4ed118e3d469313bf615c2972c95 | ArenS2/LeetC0D3 | /code/ID905.py | 336 | 3.546875 | 4 | class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
result = []
for i in range(len(A)):
if((A[i] & 1) == 1):
result.append(A[i])
else:
result.insert(0, A[i])
return result |
97c807c8e0fed131814e485729b493b55ea14582 | NickLennonLiu/cpp | /dsa/PA/PA2a/2-5/testcases/generator.py | 145 | 3.546875 | 4 | import random
n = 10
print(n)
for i in range(0,n):
x = random.randint(-5,5)
y = random.randint(-5,5)
t = random.randint(0,100)
print(x,y,t)
|
4d9cd322a5728877940901ce926ee9a954e7ce49 | daniel-reich/ubiquitous-fiesta | /Ddmh9KYg7xA4m9uE7_3.py | 170 | 3.515625 | 4 |
def convert_binary(string):
ret_str = ""
for c in string.lower():
if c in "abcdefghijklm":
ret_str += "0"
else:
ret_str += "1"
return ret_str
|
f6e623ac686f65ab2983624b9fea9ccf3cb11fae | varshachary/MyPracticeProblems | /odd_length_subarrays.py | 906 | 4.03125 | 4 | """
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr.
# source Leetcode
# refrence links- https://www.youtube.com/watch?v=J5IIH35EBVE
#reference link 2 -https://www.geeksforgeeks.org/sum-of-all-odd-length-subarrays/
"""
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
result=0
n=len(arr)
for i in range(0,n):
result=result +(((((n-i)*(i+1))+1)//2)*arr[i])
return result
"""
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
"""
|
7ef03f1fef43c27f9defad304e17ac7df712d5e0 | yordanivh/intro_to_cs_w_python | /chapter05/Convert _temp.py | 1,076 | 3.796875 | 4 | def convert_temperatures(t: float,source: str,target: str) -> float:
if source == 'Celsius':
celsius = t
elif source == 'Kelvin':
celsius = t - 273.15
elif source == 'Fahrenheit':
celsius = (t - 32) * 5/9
elif source == 'Rankine':
celsius = (t -491.67) * 5/9
elif source == 'Delisle':
celsius = 100 - t * 2/3
elif source == 'Newton':
celsius = t * 100/33
elif source == 'Reaumur':
celsius = t * 5/4
elif source == 'Romer':
celsius = (t - 7.5) * 40/21
if target == 'Celsius':
return celsius
elif target == 'Kelvin':
return celsius + 273.15
elif target == 'Fahrenheit':
return celsius * 5/9 + 32
elif target == 'Rankine':
return (celsius + 273.15) * 9/5
elif target == 'Delisle':
return (100 - celsius) * 3/2
elif target == 'Newton':
return celsius * 33 /100
elif target == 'Reamur':
return celsius * 4/5
elif target == 'Romer':
return celsius * 21 /40 + 7.5
|
bd4414c1e6a8627ad1aa40acdde528f75afd0df8 | saxenasamarth/BootCamp_PythonLearning | /generator2.py | 598 | 4.09375 | 4 | '''Write a generator which gives the time user takes to call the function from previous call
(Time between current next() call and previous next() call).
Store a local variable to reference previous time, calculate current time at every next call on generator and yield their difference.
Update previous time before return for next call'''
import time
prevtime = time.time()
def timecalc():
global prevtime
print("printing")
while(True):
currenttime=time.time()
x=prevtime
prevtime=currenttime
yield currenttime-x
b=timecalc()
print(next(b))
time.sleep(5)
print(next(b))
|
7ab3814abe2a278b11df2248369fb2857dd2c332 | DanielBarcenas97/Python | /1.PythonBasico/4.ControlDeFlujo/break.py | 514 | 3.578125 | 4 | """
Created by Edgar Daniel Barcenas Martinez
Proteco Gen 34. FI UNAM
Diciembre 28, 2017
"Break"
"""
#Sentencia break
#Se utiliza en ciclos for y while con el fin de terminar el bucle actual
#Se ejecuta el codigo siguiente al bucle
for i in range(1, 50):
if(i == 20):
break
print(i)
print("Sali del bucle")
print()
#Sentencia continue
#Termina la iteracion actual y continua con la siguiente
for i in "Python":
if(i == "h"):
continue
print(i)
print()
x = 2
while(x < 20):
if(x == 10):
break
print(x)
x += 1 # x = x + 1
|
12fb0c1f36ae1ce113b3edffc0d2be7deeeb234a | Nilcelso/exercicios-python | /ex059.py | 1,166 | 3.921875 | 4 | from time import sleep
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
opçao = 0
while opçao !=5:
print(''' [ 1 ] SOMAR
[ 2 ] MUTIPLICAR
[ 3 ] MAIOR
[ 4 ] NOVOS NUMEROS
[ 5 ] SAIR DO PROGRAMA''')
opçao = int(input('>>>>>>>> Qual a sua opção? '))
if opçao == 1:
soma = n1 + n2
print('A soma entre {} e {} é {}.'.format(n1, n2, soma))
elif opçao == 2:
mult = n1 * n2
print('A multimplicaçao entre {} e {} é {}'.format(n1, n2, mult))
elif opçao == 3:
if n1 > n2:
print('O maior numero entre {} e {} é {}.'.format(n1, n2, n1))
elif n2 > n1:
print('O maior numero entre {} e {} é {}.'.format(n1, n2, n2))
else:
print('Os numeros digitados são iguais.')
elif opçao == 4:
print('Informe os números novamente:')
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
elif opçao == 5:
print('finalizando.....')
else:
print('Opção inválida. Tente novamente.')
print('=-=' * 10)
sleep(2)
print('Fim do programa! Vote sempre!')
|
246e1e4021b1161445aa7ea448886acc6dab9a3b | TengXu/CS-2015 | /CS 111/ps2pr3.py | 1,747 | 3.84375 | 4 | #
# ps2pr3.py - Problem Set 2, Problem 3
#
# Indexing and slicing puzzles
#
# name: teng xu
# email: xt@bu.edu
# 1
def mult(n, m):
""" takes two integers n and m as inputs and returns the product
of those integers
"""
if n == 0:
return 0
elif n < 0:
return -mult(-n, m)
else :
rest = mult(n-1,m)
return m + rest
# 2
def dot(l1, l2):
""" takes as inputs two lists of numbers, l1 andl2, and returns
the dot product of those lists
"""
if len(l1) != len(l2):
return 0.0
elif l1 == [] or l2 == []:
return 0.0
else:
rest = dot(l1[1:],l2[1:])
return l1[0]*l2[0] + rest
# 3
def letter_score(letter):
""" takes a lowercase letter as input and returns the value of
that letter as a scrabble tile.
"""
if letter in ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',]:
if letter in ['a','n','o','i','e','l','r','s','t','u']:
return 1
elif letter in ['d','g']:
return 2
elif letter in ['b','c','m','p']:
return 3
elif letter in ['f','v','w','y','h']:
return 4
elif letter in ['k']:
return 5
elif letter in ['j','x',]:
return 8
elif letter in ['q','z']:
return 10
else:
return 0
# 4
def scrabble_score(word):
""" takes as input a string word containing only lowercase letters and
returns the scrabble score of that string
"""
if word == '':
return 0
else:
rest = scrabble_score(word[1:])
return letter_score(word[0]) + rest
|
f92f126f2c172b2f35008d1b095610aec8b4f935 | Sihaiyinan/leetcode-record | /python/26. 删除排序数组中的重复项/leetcode.py | 318 | 3.578125 | 4 | from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if nums.__len__() == 0: return 0
j = 0
for i in range(1, nums.__len__()):
if nums[j] != nums[i]:
j += 1
nums[j] = nums[i]
return j + 1
nums = [0,0,1,1,1,2,2,3,3,4]
print(Solution().removeDuplicates(nums)) |
b719ede584f6dd16ed7e44811ebbed3c2d0604d0 | aabele/hoverfly-random-response-data | /tests.py | 2,807 | 3.625 | 4 | #!/usr/bin/env python
import unittest
import six
from randomize_response_data import randomizer
class RandomizeTestCase(unittest.TestCase):
def setUp(self):
self.string_data = 'sdfgsdfgsdfgsdfg'
self.string_response = randomizer(self.string_data)
self.integer_data = 1234567890
self.integer_response = randomizer(self.integer_data)
self.boolean_data = False
self.boolean_response = randomizer(self.boolean_data)
def test_string_response_type(self):
""" Response (string) should have the same type as input """
self.assertIsInstance(self.string_response, six.string_types)
def test_string_response_length(self):
""" Response (string) should have the same length as input """
self.assertEqual(len(self.string_response), len(self.string_data))
def test_integer_response_type(self):
""" Response (integer) should have the same type as input """
self.assertIsInstance(self.integer_response, six.integer_types)
def test_integer_response_length(self):
""" Response (integer) should have the same length as input """
def _(i):
# Support for the case if the integer starts with zeroes
return len(str(i))
self.assertEqual(_(self.integer_response), _(self.integer_data))
def test_boolean_response_type(self):
""" Response (boolean) should have the same type as input """
self.assertIsInstance(self.boolean_response, bool)
def test_boolean_response(self):
""" Response (boolean) should have the opposite value as input """
self.assertEqual(self.boolean_response, not self.boolean_data)
def test_sequence_response(self):
""" Response (sequence) should have the same length and structure as input
"""
payload = [1, 'a', ['a', 'b', [{'a': 'b'}, 'a']], False]
response = randomizer(payload)
self.assertEqual(len(payload), len(response))
self.assertEqual(len(payload[2]), len(response[2]))
self.assertEqual(len(payload[2][2]), len(response[2][2]))
def test_dictionary_response(self):
""" Response (dictionary) should have the same length and structure as input
TODO: on older python versions key ordering could cause problems -
that's why they must be reordered
"""
payload = {
'array': [1, 'a', ['a', 'b', [{'a': 'b'}, 'a']], False],
'boolean': False,
'sub_dict': {
'key1': 'value1',
'sub_sub_dict': {
'key1': 'value1'
}
}
}
response = randomizer(payload)
self.assertEqual(len(payload), len(response))
if __name__ == "__main__":
unittest.main()
|
35df2944b0782ad6d3a02a187b0c0de64f90e9a7 | jgeskens/python-typing-test | /main.py | 1,137 | 3.96875 | 4 | from math import sin, cos, pi
from typing import Union
# Type declarations
class Move(object):
def __init__(self, dx: float, dy: float) -> None:
self.dx = dx
self.dy = dy
class Rotate(object):
def __init__(self, degrees: float) -> None:
self.degrees = degrees
class NoOp(object):
pass
Action = Union[Move, Rotate, NoOp]
class State(object):
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return 'State({}, {})'.format(self.x, self.y)
# Actual code here
def update(state: State, action: Action) -> State:
if isinstance(action, Move):
return State(state.x + action.dx, state.y + action.dy)
elif isinstance(action, Rotate):
s = sin(action.degrees)
c = cos(action.degrees)
return State(c * state.x + s * state.y, -s * state.x + c * state.y)
elif NoOp:
return state
def main() -> None:
state = State(0.0, 0.0)
state = update(state, Move(1.0, -1.0))
state = update(state, Rotate(pi / 2.0))
print(state)
if __name__ == '__main__':
main()
|
9a2135b4fa53538d1f9d4aa2bb966e913a4c3359 | elizabethrsotomayor/difference-of-squares | /difference_of_squares.py | 388 | 4.03125 | 4 | def square_of_sum(number: int) -> int:
total = 0
for n in range(1, number + 1):
total += n
return total ** 2
def sum_of_squares(number: int) -> int:
total = 0
for n in range(1, number + 1):
total += (n ** 2)
return total
def difference_of_squares(number: int) -> int:
total = square_of_sum(number) - sum_of_squares(number)
return total
|
e3b122d22eb72be424113dc45109c5bd52358619 | turtlingAround/bankSavingsAccounts | /BankSavingAccount.py | 441 | 3.546875 | 4 | from random import randint
from savingaccount import SavingAccount
class BankSavingAccounts:
def __init__(self,bankName,accounts):
self.bankName = bankName
self.accounts = accounts
self.numberOfAccounts = len(accounts)
def changeInterest(self,changeAmount):
decimalCount = len(str(changeAmount)) - 1
SavingAccount.interestRate = round(SavingAccount.interestRate + changeAmount,decimalCount)
|
f119375a12b12aeb774a55557518315eebd9d10e | nataliecosta0/curso-python-dn | /semana_4/exercicios_aula_8/Ex06.py | 1,037 | 4.4375 | 4 | '''
Classe TV: Faça um programa que simule um televisor criando-o como um objeto. O usuário deve ser capaz de informar o número do canal e aumentar ou diminuir o volume.
Certifique-se de que o número do canal e o nível do volume permanecem dentro de faixas válidas.
'''
class Tv():
def ___init__(self, numero = 1, volume = 2):
self.numero = numero
self.volume = volume
def numeroCanal(self):
canal = int(input("Informe o número do canal: "))
if canal > 0 and canal <= 60:
self.numero = canal
print("\nO número do canal é: {}".format(self.numero))
else:
print("\nCanal Inválido.")
def mudarVolume(self):
mudarVolumeA = int(input("\nInforme o aumento de volume: "))
if mudarVolumeA > 0 and mudarVolumeA <= 100:
self.volume = mudarVolumeA
print("\nO volume após o aumento é: {}".format(self.volume))
else:
print("\nVolume inválido.")
t = Tv()
t.numeroCanal()
t.mudarVolume() |
26d38e9f835b271a585f011424bf185ab64fbfc2 | sayantann11/Automation-scripts | /zip_password_cracker/zip_password_cracker.py | 958 | 3.78125 | 4 | #!/usr/bin/python
from pathlib import Path
from zipfile import ZipFile
import click
def extract_zip(zip_file: ZipFile, password_file: Path):
with open(password_file, 'r') as passwords:
for password in passwords.readlines():
try:
zip_file.extractall(pwd=password.strip().encode())
print(f"Found password: {password}")
break
except RuntimeError:
pass
else:
print("Password not found")
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option('--zip', help='Set path to zip file')
@click.option(
'--passwords',
default=Path().cwd() / 'passwords.txt',
help='Set path to file with passwords',
)
def main(zip, passwords):
"""Simple program that greets NAME for a total of COUNT times."""
zip_file = ZipFile(zip)
extract_zip(zip_file, passwords)
if __name__ == '__main__':
main()
|
9d4d4c00d77af637bd09f8afd3691d379969e470 | GABIGOLeterno/CursoemV-deoExerc-cios | /desafio42.py | 930 | 4.09375 | 4 | print("Analisador de Triângulos")
while True:
l1 = int(input("Digite o primeiro segmento: ").strip())
l2 = int(input("Digite o segundo segmento: ").strip())
l3 = int(input("Digite o terceiro segmento: ").strip())
if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2:
if l1 == l2 == l3:
print("Segmentos {}, {} e {} formam um triângulo do tipo \033[32;40mEQUILÁTERO\033[m.".format(l1, l2, l3))
elif l1 != l2 != l3:
print(("Segmentos {}, {} e {} formam um triângulo do tipo \033[33;40mESCALENO\033[m.".format(l1, l2, l3)))
else:
print(("Segmentos {}, {} e {} formam um triângulo do tipo \033[34;40mISÓCELES\033[m.".format(l1, l2, l3)))
else:
print("Segmentos não podem formar um triângulo..")
escolha = input("Digite 'q' para continuar, ou aperte ENTER para seguir: ").strip()
if escolha == "q":
break
|
278e64a8dec88dfa2ef615c383e29cbb0dc0ae8e | rupertsmall/numerical-tools | /derivative_standard.py | 1,429 | 4.25 | 4 | #program for finding the derivative of an arbitrary function
#uses the standard definition of the derivative
from math import * #will allow user to enter functions defined in Python math module
NUM_POINTS = 200 #number of points per unit interval. of course, cannot exceed 10e308
EPSILON = .2*sqrt(10e-15)
def evaluate_function(func, a): #evaluate the user-defined function
func_at_a = eval(func.replace('x', str(a)))
return func_at_a
def evaluate_derivative(func, a): #evaluate the derivative of func at the point a
h = max(abs(a), EPSILON**(.5)) * EPSILON**(.5)
derivative = (evaluate_function(func, a + h) - evaluate_function(func, a))/h
return derivative
#main program loop
while True:
increment = 1.0/NUM_POINTS
function = raw_input('enter function: ')
evaluate = raw_input('enter domain for derivative: ')
if ',' in evaluate:
start_val = float(evaluate.strip().split(',')[0])
end_val = float(evaluate.strip().split(',')[1])
evaluate_at = start_val #iterated variable
while evaluate_at <= end_val:
print str(evaluate_at) + '\t' + str(evaluate_derivative(function, evaluate_at))
evaluate_at += increment
elif evaluate:
evaluate_at = float(evaluate.strip())
print str(evaluate_derivative(function, evaluate_at))
else: break
|
b2db1eade72e744adbffffbb846188930cc16c4b | fredcallaway/lens-exp | /experiment.py | 3,909 | 3.78125 | 4 | """Evaluates net performance on an experiment"""
from random import random
import logging
from scipy import stats
def get_error(trial):
"""Returns float: the total error of one trial
Args:
trial str: lens output for one trial"""
# lines = trial.split('\n')
# error_line = re.search(r'Err.*', trial).group(0)
# error = re.search(r'[0-9.]+', error_line).group(0)
# return float(error)
examples = trial.split('\n')[3:-1]
try:
errors = [float(e.split(' ')[1]) for e in examples]
except:
errors = [float(e.split(' ')[2]) for e in examples]
return sum(errors)
def get_network_choices(trial_errors):
"""Returns ([int], [float]): choices and reaction time
choices is a list of 0 or 1 corresponding to word indices in one trial
reaction time is a list of floats
Args:
trial_errors [(float, float)]: each tuple represents
the reaction times for the two words in a trial
"""
# pairs of consecutive words correspond to trials
def choose(pair):
# p(choose word1) = error2/(error1+error2)
threshold = pair[0]/sum(pair)
choice = 0 if random() > threshold else 1
# reaction time is inverse of percentage difference between values
rt = 1 / (abs(pair[0]-pair[1])/(sum(pair)/2))
return (choice, rt)
results = [choose(p) for p in trial_errors]
choices = [r[0] for r in results]
reaction_times = [r[1] for r in results]
return choices, reaction_times
def get_correct_choices():
"""Returns [int]: tuple index of correct word for each trial"""
with open('experiment/answer-key.txt', 'r') as f:
key = f.read()
key = key.split('\r')
key = map(int, key)
return key
def test_word_choices(choices):
"""Returns [int]: indices of trials net was incorrect for
Args:
choices: [int] network's word choices, 1 or 0"""
key = get_correct_choices()
assert len(choices) == len(key)
incorrect = []
for i in xrange(len(key)):
if choices[i] != key[i]:
incorrect.append(i)
return incorrect
def run_one(out, ntrials=1000):
"""Returns accuracy and word errors for one condition"""
runs = out.split('***')[1:]
errors = [get_error(run) for run in runs]
# put errors into pairs corresponding to trials
trial_errors = [(errors[i], errors[i+1]) for i in xrange(0, len(errors), 2)]
accuracies = []
for t in xrange(ntrials):
choices, reaction_times = get_network_choices(trial_errors)
incorrect = test_word_choices(choices)
accuracies.append(1 - float(len(incorrect)) / len(choices))
d = stats.describe(accuracies)
accuracy_mean, accuracy_std = d[2], d[3]**0.5
return accuracy_mean, accuracy_std, trial_errors, reaction_times
def evaluate_experiment(lens_output):
"""Returns dict of net's performance on both word choice conditions
Args:
lens_output (str): lens output"""
logging.debug('============================================================')
logging.debug(lens_output)
logging.debug('============================================================')
with open('experiment-log.out', 'w+') as f:
f.write(lens_output)
A, B = map(run_one, lens_output.split('######'))
results = {'expA_accuracy' : A[0],
'expB_accuracy' : B[0],
'expA_std' : A[1],
'expB_std' : B[1],
'expA_errors' : A[2],
'expB_errors' : B[2],
'expA_reaction': sum(A[3]) / len(A[3]),
'expB_reaction': sum(B[3]) / len(B[3]),
'expA_rts' : A[3],
'expB_rts' : B[3],
}
return results
if __name__ == '__main__':
with open('experiment-log.out', 'r') as f:
res = evaluate_experiment(f.read())
print res['expA_std'], res['expB_std'] |
3038cc6fa5e142f5345844b39783cc1008db47af | stemasoff/GooglePythonExercises | /Basic/mimic.py | 2,574 | 4.21875 | 4 | """Mimic pyquick exercise -- optional extra exercise.
Google's Python Class
Read in the file specified on the command line.
Do a simple split() on whitespace to obtain all the words in the file.
Rather than read the file line by line, it's easier to read
it into one giant string and split it once.
Build a "mimic" dict that maps each word that appears in the file
to a list of all the words that immediately follow that word in the file.
The list of words can be be in any order and should include
duplicates. So for example the key "and" might have the list
["then", "best", "then", "after", ...] listing
all the words which came after "and" in the text.
We'll say that the empty string is what comes before
the first word in the file.
With the mimic dict, it's fairly easy to emit random
text that mimics the original. Print a word, then look
up what words might come next and pick one at random as
the next work.
Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict,
go back to the empty string to keep things moving.
Note: the standard python module 'random' includes a
random.choice(list) method which picks a random element
from a non-empty list.
For fun, feed your program to itself as input.
Could work on getting it to put in linebreaks around 70
columns, so the output looks better.
"""
import random
import sys
def mimic_dict(filename):
with open(filename, 'r') as inputFile:
words = inputFile.read().split()
mimicDict = {}
symbols = '`.,)(*-?:;"!`_' + "'"
for i in range(len(words) - 1):
if not words[i].isalpha():
words[i].strip(symbols)
if not mimicDict:
mimicDict[''] = [words[i]]
if words[i] not in mimicDict:
mimicDict[words[i]] = [words[i + 1].strip(symbols)]
else:
mimicDict[words[i]].append(words[i + 1].strip(symbols))
return mimicDict
def print_mimic(mimicDict, word):
text = ''
countWords = 200
while countWords != 0:
if word not in mimicDict:
word = random.choice(mimicDict[''])
text = text + word + ' '
word = random.choice(mimicDict[word])
countWords -= 1
return text
# Provided main(), calls mimic_dict() and mimic()
def main():
if len(sys.argv) != 2:
print('usage: ./mimic.py file-to-read')
sys.exit(1)
dict = mimic_dict(sys.argv[1])
with open('randomText.txt', 'w') as outFile:
outFile.write(print_mimic(dict, 'Rabbit'))
if __name__ == '__main__':
main()
|
1373ec252515cdc3dc4473fe1f1b67f401de59e2 | muhammednazeer/pyexercise | /experiments.py | 1,688 | 4.0625 | 4 | days = {"Mo": "Monday", "Tu": "Tuesday", "We": "Wednesday", "Th": "Thursday",
"Fr": "Friday", "Sa": "Saturday", "Su": "Sunday"}
for day in days.items():
for eachitem in day:
print (eachitem, end = ", ")
value = input("The abbr. of day: ")
if value in days.values():
print(value, " is a day in the week\n")
kanoCentral = ["Kano Municipal", "Tarauni", "Kumbotso", "Gwale", "Nasarawa", "Dala",
"Fagge", "Ungogo"]
kanoNorth = ["Dawakin Tofa", "Tofa", "Rimi-Gado", "Gabasawa", "Gezewa", "Munijibir",
"Bagwai", "Dambatta", "Makoda", "Shanono", "Kunchi", "Tsanyaisa",
"Gwarzo", "Bichi", "Karaye", "Rogo", "Kabo"]
kanoSouth = ["Takai", "Wudil", "Sumaila", "Bebeji", "Rano", "Bunkure", "Kibiya",
"Warawa", "Ajingi", "Garko", "Tudun Wada", "Doguisa", "Madobi", "Kura",
"Garun Mallam", "Dawakin Kudu", "Kiru", "Gaya", "Albasu"]
local = "" #Initializing
while local != "quit":
local = input("Enter LGA name(or 'quit' to exit: ")
if local == "quit": #checking the user input to determine if the program will run or exit
print ("...exiting the Program")
else: #Main program block
local_sen = local.title()
if local_sen in kanoCentral:
print ("You entered ", local_sen, " it is in Kano Central Senatorial District")
elif local_sen in kanoNorth:
print ("You entered ", local_sen, " it is in Kano North Senatorial District")
elif local_sen in kanoSouth:
print ("You entered ", local_sen, " it is in Kano South Senatorial District")
else:
print ("You entered ", local_sen, " \n Not a Local Government in Kano State.")
|
b1ca68b031211e1ee6307e03ef548218a742fc43 | ZhiQiangChu/PerformanceDemo | /示例10/coroutines.py | 884 | 4 | 4 | leftSteps=0 # 左侧起始步数
rightSteps=0 # 右侧起始步数
stepsLimit=10 # 总步数限制
stepsDifference=2 # 左右步数允许的最大差值
def leftForward():
global leftSteps
while True:
print("left forward ... ...")
while leftSteps < rightSteps + stepsDifference and leftSteps < stepsLimit:
leftSteps = leftSteps + 1
print("left steps: ",leftSteps)
yield
def rightForward(c):
global rightSteps
while rightSteps < stepsLimit or leftSteps < stepsLimit:
print("right forward ... ...")
while rightSteps < leftSteps + stepsDifference and rightSteps < stepsLimit:
rightSteps = rightSteps + 1
print("right steps: ",rightSteps)
c.send(None)
c.close()
if __name__=='__main__':
print("BEGIN")
c = leftForward()
rightForward(c)
print("FINISHED") |
c3a12fd92c701be1323f87b38f5bcc999b203ac5 | 3000manJPY/NLP100Knocks | /Chapter1/01.py | 603 | 4.34375 | 4 | #!/usr/local/bin python3
# -*- coding: utf-8 -*-
def extract_odd_chars(string: str) -> str:
"""
奇数番目の文字だけを抽出して返す関数
Parameter
----------
string: str
抽出対象の文字列
Return
----------
抽出された文字列
"""
return string[::2]
def main():
in_str = 'パタトクカシーー'
extracted_str = extract_odd_chars(in_str)
print('文字列(入力): {}'.format(in_str))
print('文字列(抽出): {}'.format(extracted_str))
if __name__ == '__main__':
main() |
f3b27123cf427c27ebf89ad31d2f04621e233c64 | pvcraven/arcade_book | /source/chapters/25_sprites_and_walls/step_4.py | 3,772 | 4.15625 | 4 | """ Sprite Sample Program """
import arcade
# --- Constants ---
SPRITE_SCALING_BOX = 0.5
SPRITE_SCALING_PLAYER = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
MOVEMENT_SPEED = 5
class MyGame(arcade.Window):
""" This class represents the main window of the game. """
def __init__(self):
""" Initializer """
# Call the parent class initializer
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "Sprite Example")
# Sprite lists
self.player_list = None
self.wall_list = None
# Set up the player
self.player_sprite = None
# This variable holds our simple "physics engine"
self.physics_engine = None
def setup(self):
# Set the background color
arcade.set_background_color(arcade.color.AMAZON)
# Sprite lists
self.player_list = arcade.SpriteList()
self.wall_list = arcade.SpriteList()
# Reset the score
self.score = 0
# Create the player
self.player_sprite = arcade.Sprite("images/character.png", SPRITE_SCALING_PLAYER)
self.player_sprite.center_x = 50
self.player_sprite.center_y = 64
self.player_list.append(self.player_sprite)
# --- Manually place walls
# Manually create and position a box at 300, 200
wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING_BOX)
wall.center_x = 300
wall.center_y = 200
self.wall_list.append(wall)
# Manually create and position a box at 364, 200
wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING_BOX)
wall.center_x = 364
wall.center_y = 200
self.wall_list.append(wall)
# --- Place boxes inside a loop
for x in range(173, 650, 64):
wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING_BOX)
wall.center_x = x
wall.center_y = 350
self.wall_list.append(wall)
# --- Place walls with a list
coordinate_list = [[400, 500],
[470, 500],
[400, 570],
[470, 570]]
# Loop through coordinates
for coordinate in coordinate_list:
wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING_BOX)
wall.center_x = coordinate[0]
wall.center_y = coordinate[1]
self.wall_list.append(wall)
# Create the physics engine. Give it a reference to the player, and
# the walls we can't run into.
self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)
def on_draw(self):
arcade.start_render()
self.wall_list.draw()
self.player_list.draw()
def update(self, delta_time):
self.physics_engine.update()
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
if key == arcade.key.UP:
self.player_sprite.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -MOVEMENT_SPEED
elif key == arcade.key.LEFT:
self.player_sprite.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
"""Called when the user releases a key. """
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
def main():
""" Main method """
window = MyGame()
window.setup()
arcade.run()
if __name__ == "__main__":
main()
|
84f8db6e1702bfa7353d28be7f4e4397aff60623 | buckeye76guy/QFinance | /trees.py | 19,422 | 3.78125 | 4 | __author__= 'JosiahHounyo'
def unique_cstm(alist):
'''
simple function for the variables_created list below
:param alist: a list
:return: list with unique elements
'''
temp = []
for element in alist:
if element not in temp:
temp.append(element)
return temp
class BinaryTree:
def __init__(self, root, val, **kwargs):
'''
:param root: the name of the root node. i.e. R for time 0, H for up at time 1,
T for tail, HH, HT etc.
:param val: the value of the root node
:param kwargs: up_factor and down_factor: multiplied to the root value.
up_value and down_value: when factors not known, these are used.
note that the up and down will be given nodes as well i.e. they too
will be an instance of this class. Their children will be set as 'None'.
Generally None signifies the end of the tree so if either of **kwargs
is none, they will be put in place. Please make sure if root is 'R' to have
children not None.
'''
self.root, self.val = root, val
assert (len(kwargs) >= 2), "Please provide up_factor/up_value and down_factor/down_value"
if 'up_factor' in kwargs.keys():
up = kwargs.get('up_factor')
if self.root == 'R':
self.up = {'root': 'H', 'val' : self.val*up if up is not None else None}
else:
self.up = {'root': self.root + 'H', 'val': self.val*up if up is not None else None}
# basically we are creating HH, HT, TH, TT etc as we go
if 'down_factor' in kwargs.keys():
down = kwargs.get('down_factor')
if self.root == 'R':
self.down = {'root': 'T', 'val': self.val*down if down is not None else None}
else:
self.down = {'root': self.root + 'T',
'val': self.val*down if down is not None else None}
if 'up_value' in kwargs.keys():
up = kwargs.get('up_value')
if self.root == 'R':
self.up = {'root': 'H', 'val': up}
else:
self.up = {'root': self.root + 'H', 'val': up}
if 'down_value' in kwargs.keys():
down = kwargs.get('down_value')
if self.root == 'R':
self.down = {'root': 'T', 'val': down}
else:
self.down = {'root': self.root + 'T', 'val': down}
def __str__(self):
return str({self.root: (self.val, self.up, self.down)})
def __repr__(self):
# couldn't recreate tree from str. Many assumptions would have to be made. Idea is to have a small 1 year tree
# that can be expanded with a good deal of freedom... in fact up factor from 1 year to another could differe, it
# suffices to insert a new tree with new parameters at the end of a previous one. but such tree would require
# different rates at different periods during discount. a list would suffice
return str(self)
def discount(self, p, r):
'''
must be fixed to... if up is a tree, .get('val') can be an issue
Only on a one period model. This function is irrelvant but I'll leave it here.
simply avoid using this
:param p: probability of up
:param r: rate of interest
:return: (1/(1+r))*Expected value
'''
assert (r > 0 and r < 1), "Please provide a positive rate that is less than 1"
assert (p >= 0 and p <= 1), "Please provide a valid probability"
return (1/(1+r))*(p*self.up.get('val') + (1-p)*self.down.get('val'))
def find(self, node):
'''
must add exception checking.
:param node: HHT, HTT etc...
:return: value and children if they exist
'''
assert (isinstance(node, str)), "Node must be a string!"
for lt in node:
if lt not in "HT":
raise ValueError('Path must contain only "H" and "T".' + lt + ' is not valid.')
assert (self.depth() >= len(node)), "You can search from root to the leaves of the tree; not beyond (DNE)!"
if len(node) == 1:
if node == 'H':
cursor = self.up
else:
cursor = self.down
return cursor
else:
cursor = 'self'
for root in node:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
return eval(cursor)
def insert(self, node, **kwargs):
# assumption is that we are inserting a new tree, i.e. updating self_up from dict to tree
# so make sure node is not already a tree
# I can now use depth to make sure insertion works. i.e. if depth is not equal to len(node) etc...
'''
Need error checking still
:param node:
:param kwargs:
:return:
'''
assert (isinstance(node, str)), "Node must be a string!"
for lt in node:
if lt not in "HT":
raise ValueError('Path must contain only "H" and "T".' + lt + ' is not valid.')
assert (self.depth() >= len(node)), "You can only insert a new tree at the end!" # could be better but...
if len(node) == 1:
if node == 'H':
val = self.up.get('val')
root = self.up.get('root')
self.up = BinaryTree(root, val, **kwargs)
else:
val = self.down.get('val')
root = self.down.get('root')
self.down = BinaryTree(root, val, **kwargs)
else:
cursor = 'self'
for root in node:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
# assuming errors are checked and node is reached, we upgrade it to binary tree
val = eval(cursor + ".get('val')") # because we only insert a tree at a node
# root = eval(cursor + ".get('root')")
# that was previously just a dictionary
exec(cursor + ' = BinaryTree(node, val, **kwargs)')
return None
def depth(self):
'''
:return: Takes a tree, goes through it i.e. one path until it reaches the end. returns N: number of periods
'''
path, flag = '', True
cursor = self
while flag:
if isinstance(cursor.up, dict):
flag = False
else:
path += 'H'
cursor = cursor.up
return len(path) + 1
def cut(self, n, keep = True):
'''
:param n: number of periods where to cut the tree
:return: a new tree with n periods. It would be easy to have a get_up and get_down factors method,
then simply recreate a tree using these factors. But this will limit some freedom
:param keep: if this is true, use deepcopy. if not, create a completely different copy
keep is only now used because having two copies of the same tree may not be good for memory
'''
assert (isinstance(n, int)), "Number of years (periods) must be an integer"
assert (n > 0), "Discount from at least one year in the future"
assert (n <= self.depth()), "Cannot discount from years past current tree depth"
N = self.depth()
if n == N:
return self
from itertools import product
from copy import deepcopy
if keep:
temp = deepcopy(self) # avoid changing the initial tree: inspect input tree, if any bug occurs, fix it
else:
temp = self
paths = product('HT', repeat = n)
paths = [''.join(node) for node in paths]
for path in paths:
cursor = 'temp'
for root in path:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
val = eval(cursor + '.val')
mydict = {'root':path, 'val':val}
exec(cursor + '= mydict')
return temp
def real_discount(self, N, p, r, keep = True):
'''
computes discount from a certain time to present. N should be at least 1 that is. But less than or equal
to tree depth. Keep in mind this can be useful for options. It is possible to create properties called
European_call, European_put etc... that use this type of discount function. American options would require
special handling. Note that this function is really useful when only the end nodes are known.
By using symbolic python or even bogus placeholder for all other nodes except the last ones, we can discount to
the present and obtain the true present value. In fact, if one can build a binomial tree using the stock_progress
function and only update all the last nodes to values of an option, one can discount all of it to the present!
:param N: period we want to discount from. [equal to depth at the moment, future work: N can be less than depth! done]
:param p: probability of up
:param r: rate of interest, could be an integer (or a list: future work) of size N! r should probably be restricted to 0 < r < 1
:param keep: if this is true, use deepcopy. if not, create a completely different copy
:return: present value
'''
assert (isinstance(N, int)), "Number of years (periods) must be an integer"
assert (N > 0), "Discount from at least one year in the future"
assert (N <= self.depth()), "N must match number of years(periods) in tree: edit: N <= depth"
assert (r > 0 and r < 1), "Please provide a positive rate that is less than 1"
assert (p >= 0 and p <= 1), "Please provide a valid probability"
from itertools import product
temp = self.cut(N, keep)
for step in range(N,0,-1):
paths = product('HT', repeat = step)
paths = [''.join(node) for node in paths] # goal is to collapse trees until we get a 1 period tree
# so we will have to use the exec() again. could create a function that updates a given node but this sort
# of freedom could be problematic. so no...
# thanks to itertool, we can advance through the list by pair, i.e. each group of 2 has the same parent node
length = len(paths)
for ind in range(0,length,2):
parent_node = paths[ind][0:-1]
vals_up = temp.find(parent_node).up.get('val') # since each tree is collapsed to a dictionary, this is ok
vals_down = temp.find(parent_node).down.get('val')
disc_val = (1/(1+r))*(p*vals_up + (1-p)*vals_down) # discounted value
temp_dict = {'root':parent_node, 'val':disc_val}
cursor = 'temp'
for root in parent_node:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
exec(cursor + ' = temp_dict')
return temp.discount(p, r)
class BDTTree(BinaryTree):
'''
This is an extension of the regular BinaryTree except that the discount functions are rewritten.
insert is fixed so that it allows each subtree to be BDTTree
'''
def insert(self, node, **kwargs):
# assumption is that we are inserting a new tree, i.e. updating self_up from dict to tree
# so make sure node is not already a tree
# I can now use depth to make sure insertion works. i.e. if depth is not equal to len(node) etc...
'''
Need error checking still
:param node:
:param kwargs:
:return:
'''
assert (isinstance(node, str)), "Node must be a string!"
for lt in node:
if lt not in "HT":
raise ValueError('Path must contain only "H" and "T".' + lt + ' is not valid.')
assert (self.depth() >= len(node)), "You can only insert a new tree at the end!" # could be better but...
if len(node) == 1:
if node == 'H':
val = self.up.get('val')
root = self.up.get('root')
self.up = BDTTree(root, val, **kwargs)
else:
val = self.down.get('val')
root = self.down.get('root')
self.down = BDTTree(root, val, **kwargs)
else:
cursor = 'self'
for root in node:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
# assuming errors are checked and node is reached, we upgrade it to binary tree
val = eval(cursor + ".get('val')") # because we only insert a tree at a node
# root = eval(cursor + ".get('root')")
# that was previously just a dictionary
exec(cursor + ' = BDTTree(node, val, **kwargs)')
return None
def real_discount(self, N, p = .5, r = None, keep = True):
'''
same thing as original, but this is solely for a BDT tree of rates
can be used to compute yield.
This function discounts bond values by actually making sure that only the last nodes
are of the form F/(1+r), the subsequent are just (1+r) times the future values.
Use this on any type of tree!
:param N:
:param p:
:param r:
:param keep: this should always be true for BDT
:return:
'''
assert (isinstance(N, int)), "Number of years (periods) must be an integer"
assert (N > 0), "Discount from at least one year in the future"
assert (N <= self.depth()), "N must match number of years(periods) in tree: edit: N <= depth"
assert (p >= 0 and p <= 1), "Please provide a valid probability"
from itertools import product
if N == 1:
temp = self.cut(1, keep)
u = temp.up.get('val')
d = temp.down.get('val')
r = temp.val
return (1 / (1 + r)) * (p/(1+u) + (1 - p)/(1+d))
temp = self.cut(N, keep)
for step in range(N, 0, -1):
paths = product('HT', repeat=step)
paths = [''.join(node) for node in paths]
length = len(paths)
for ind in range(0, length, 2):
parent_node = paths[ind][0:-1]
vals_up = temp.find(parent_node).up.get('val')
vals_down = temp.find(parent_node).down.get('val')
rate = temp.find(parent_node).val
if step == N:
disc_val = (1/(1+rate))*(p/(1+vals_up) + (1-p)/(1+vals_down))
else:
disc_val = (1/(1+rate))*(p*vals_up + (1-p)*vals_down)
temp_dict = {'root': parent_node, 'val': disc_val}
# print(temp_dict)
cursor = 'temp'
for root in parent_node:
if root == 'H':
cursor += '.up'
else:
cursor += '.down'
exec(cursor + ' = temp_dict')
u = temp.up.get('val')
d = temp.down.get('val')
r = temp.val
return (1/(1+r))*(p*u + (1-p)*d)
def stock_progress(S_0, u, d, N):
'''
Basic stock progression
:param S_0: Initial value of stock
:param u: up factor
:param d: down factor
:param N: number of periods
:return: binary tree with the right nodes and values
'''
assert (N > 0), "N should be at least 1. Otherwise stock progress isn't of interest"
from itertools import product
tree = BinaryTree('R', S_0, up_factor = u, down_factor = d)
# if N == 1:
# return tree # simply stop here
for i in range(1,N):
paths = product('HT', repeat = i)
paths = [''.join(node) for node in paths]
for node in paths:
tree.insert(node, up_factor = u, down_factor = d)
return tree
def bdt_sympy(N,r):
'''
This function simply creates an instance of BDTTree that
:param N: number of periods, not the expiration time! 1 less than expiration time
:param r: initial rate
:return: a BDT Tree with variables as short rates to be determined
'''
assert (N > 0), "N should be at least 1. Otherwise stock progress isn't of interest"
from sympy import Symbol, symbols
from itertools import product
assert (r > 0 and r < 1), "Please provide a positive rate that is less than 1"
r_u, r_d = symbols("r_u r_d", positive=True)
tree = BDTTree('R', r, up_value=r_u, down_value=r_d)
variables_created = [r_u, r_d]
for i in range(1,N):
paths = product('HT', repeat = i)
paths = [''.join(node) for node in paths]
for node in paths:
mylist = list(map(lambda x: 'u' if x == 'H' else 'd', node)) # simply gets the up-up, up-down etc based on node
mylist_up = mylist + ['u'] # the upper value
mylist_up.sort(reverse=True) # sorting since the tree is a recombining tree
mylist_dwn = mylist + ['d'] # the lower value
mylist_dwn.sort(reverse=True) # techinically since d is added, we do not need to sort but you never know
up_value = Symbol('r_' + ''.join(mylist_up), positive=True)
down_value = Symbol('r_' + ''.join(mylist_dwn), positive=True)
## this function will be more useful when it allows us to export a list or tuple of the variables created
variables_created.append(up_value)
variables_created.append(down_value)
# by keeping it this way, it is possible to iterate through the list one at a time. But due to the bdt
# function in bdtcodde.py, it's useful to keep unique elements only
##
tree.insert(node, up_value=up_value, down_value=down_value)
return (tree, unique_cstm(variables_created))
# print(bdt_sympy(4,.1)[1])
# a = BinaryTree('R', 12, up_value=24, down_value=6)
# a.insert('H', up_factor = 2, down_factor = .5)
# a.insert('T', up_factor = 2, down_factor = .5)
# a.insert('HH', up_factor = 2, down_factor = .5)
# a.insert('HT', up_factor = 2, down_factor = .5)
# a.insert('TH', up_factor = 2, down_factor = .5)
# a.insert('TT', up_factor = 2, down_factor = .5)
# print(a)
# print(a.find('HH'))
# print(a.depth())
# print(a.real_discount(3, .4, .1))
# print(a)
# b = stock_progress(12,2,.5,1)
# c = stock_progress(12,2,.5,3)
# d = c.cut(1)
# e = BDTTree('R',.1,up_value=.1432,down_value=.0979)
# e.insert('H',up_value=.1942,down_value=.1377)
# e.insert('T',up_value=.1377,down_value=.0976)
# e.insert('HH',up_value=.2179,down_value=.1606)
# e.insert('HT',up_value=.1606,down_value=.1183)
# e.insert('TH',up_value=.1606,down_value=.1183)
# e.insert('TT',up_value=.1183,down_value=.0872)
# print(b, '\n', b.depth())
# print(c)
# print(d)
# print(c.real_discount(2, .4, .1))
# print(type(e.find('HH')))
# print(e.real_discount(1)**(-1/4) - 1)
# f = e.up
# print(f)
# print(e.find('H'))
# print(f.real_discount(1)**(-1/2)-1)
# might consider creating an equal property for trees, in fact this could be easy if itertools is used again |
1bab3121934d48ba7b26f247850fbe2366585ec3 | Sadhana59/thinkpython | /ex 8.py | 123 | 4.03125 | 4 | def is_palindrome(word):
return word == word[::-1]
print(is_palindrome("malayalam"))
print(is_palindrome("cat")) |
ed315695c3f634a1bc01999d9b525a787340d20e | applepie787/Cloud_AI_Study | /python_workspace/operator.py | 483 | 3.890625 | 4 | # 단항연산자
value = 0
print(++value)
# 이항연산자 : 산술연산자 -, +, *, /, //, %
# 논리연산자 AND, OR
# 관계연산자 >, <,
# 대입연산자 =. +=, -=.
# PI = 3.14159265 원주율과 반지름 제공 원의 넓이, 둘레 구하는 연산
pi = 3.14159265
r = int(input("반지름을 입력하세요 : "))
print("원주율 = ", pi)
print("반지름 = ", r)
print("원의 둘레 = ", 2*pi*r)
print("원의 넓이 = ", r**2*pi)
|
947d5d18626f1f060e6786b3549e9b8c423a68ff | vaibhavcodes/OpenCV | /30_morphological_transformation.py | 2,999 | 4.1875 | 4 | # morphological transformation : It refers to the operations performed on the image shape. And these operations
# are mainly implemented on the binary gray scale images
# It basically removes the noise from the images. The most common ways of doing it is by dilation and erosion:
# Dilation :--> It is used to remove the noise from inside the object i.e. It expands the shape. It is used for
# growing features and filling gaps and holes.
# Erosion :--> It is used to remove the noise from outside the object i.e. It shrinks the the connected parts. It
# is used for shrinking the boundaries of the features, removing bridges and branches.
# The above two are performed by comparing the noise pixels with the kernel. If the size of the noise pixels are
# less than the size of kernel then it would get replace by the kernel or will get removed.
# Opening :--> Implementing erosion first and then the dilation
# Closing :--> Implementing dilation first and then the erosion
# Morphology Gradient --> It is difference between dilation and erosion. So we'll only the amount of expansion
# done by dilation
from cv2 import cv2
import numpy as np
# Our task here is to show only the balls(object) present in the below image by removing all the noise present
# inside as well as outside the balls
img = cv2.imread('smarties.png',0)
_ , mask = cv2.threshold(img, 220, 255, cv2.THRESH_BINARY_INV)
# We can see that there are lots of noise present in the masked image. Noise here are the black spots inside the
# balls and white spaces outside the balls and also few white spots between two balls
# So lets now remove the noise from inside the image i.e. filling the gaps inside the image.
# This is known as dilation.
kernel = np.ones( (2,2) , np.uint8)
dilated_img = cv2.dilate(mask , kernel, iterations=3)
# Iterations is used when we want to apply it one after other
# So here dilation will be applied 3 times one after the other.
# NOTE: If we will take size of the kernel large then it will start expanding the balls and will start getting
# connected to other balls.
# So lets now remove the noise from outside the image i.e. shrinking the connected branches between two balls
# and also removing white spaces from outside the balls
# This is known as erosion.
erosion_img = cv2.erode(mask , kernel, iterations=2)
opening_img = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing_img = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
morphological_gradient_img = cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernel)
cv2.imshow('Original Image' , img)
cv2.imshow('Masked Image' , mask)
cv2.imshow('Dilated Image' , dilated_img)
cv2.imshow('Erosion Image' , erosion_img)
cv2.imshow('Opening Image' , opening_img)
cv2.imshow('Closing Image' , closing_img)
cv2.imshow('Morphological Gradient Image' , morphological_gradient_img)
if cv2.waitKey(0) == 27:
cv2.destroyAllWindows()
|
f5b30116f32884784f33170c3121e0b684711c8c | Akshay-agarwal/DataStructures | /Stack/Fibonacci.py | 166 | 4.09375 | 4 | n=int(input("Please Enter how many numbers in Fibonacci series you want : "))
a=0
b=1
c=0
print(a)
print(b)
for i in range(n):
c=a+b
a=b
b=c
print(c)
|
2100a13ce61ae1b5b9c3de3866fb1f1b60609fce | mrwtx1618/python_learn | /python_cookbook/4-5_用内建的reversed函数来反向迭代序列.py | 638 | 4 | 4 | #encoding:utf-8
a = [1,2,3,4,5]
for ele in reversed(a):
print(ele)
print('***************************************')
#可以在自定义的类上实现__reversed__()方法来实现反向迭代
class Countdown:
def __init__(self,start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n = n-1
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n +=1
c = Countdown(10)
for ele in c:
print(ele)
print('***************************************')
for ele in reversed(c):
print(ele)
|
2513a24d06c224cd25ceb8b600f2733bece2f91d | peddroy/my-road-to-Python | /venv/Scripts/07_secao/41_collections_deque.py | 577 | 4.0625 | 4 | '''
MODO COLLECTIONS - DEQUE
Podemos dizer que o deque é uma lista de lta performance
'''
# Realizar importação
from collections import deque
#criando deques
deq = deque('geek')
print(deq)
#add elementos
deq.append('y') #add no final da lista
print(deq)
deq.appendleft('x') #add no começo da lista
print(deq)
# remover elementos
print(deq.pop()) #remove e retorna o removido (final lista)
print(deq)
print(deq.popleft()) #remove e retorno o removido (começo lista)
print(deq)
# help(deque)
deq.insert(2, 'alpha')
print(deq)
deq.reverse()
print(deq)
|
962cb96389631ace7114dd9bdeb2ae64d2498249 | katerina-ash/Python_tasks | /Цикл while/Максимальное число идущих подряд равных элементов.py | 616 | 3.75 | 4 | #Задача «Максимальное число идущих подряд равных элементов»
#Условие
#Дана последовательность натуральных чисел, завершающаяся числом 0.
#Определите, какое наибольшее число подряд идущих элементов
#этой последовательности равны друг другу.
b = int(input())
i = 1
c = 0
while b != 0:
a = int(input())
b, a = a, b
if b == a:
i += 1
if i>c:
c = i
if b != a:
i = 1
print(c) |
ddc48d4cc410613b4efd0f6f8faf6f6fecfb5aed | yf8848/Python_code | /blog/20180724-default_param.py | 267 | 3.96875 | 4 | # 定义具有默认参数的函数
def sayHello(name,greet='Hello'):
print(greet,name)
# 调用函数
sayHello('Abra')
sayHello('Abra','Hey')
def sayHello(name,greet='hello',word='how are you?'):
print(greet,name,word)
sayHello('Abra',word = 'are you Ok?') |
25eb975a70301a4ae3b89a92c93f0f92a8ab1739 | ShunKaiZhang/LeetCode | /integer_to_roman.py | 1,356 | 3.671875 | 4 | # python3
# Given an integer, convert it to a roman numeral.
# Input is guaranteed to be within the range from 1 to 3999.
# My solution
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return ""
all_roman_letters = [[1000, 'M'], [500, 'D'], [100, 'C'], [50, 'L'], [10, 'X'], [5, 'V'], [1, 'I']]
integer_to_roman = ""
i = 0
while i < 7:
print(num, i)
if i < 5 and i % 2 == 0 and num // all_roman_letters[i + 2][0] == 9:
integer_to_roman += (all_roman_letters[i + 2][1] + all_roman_letters[i][1])
num -= (9 * all_roman_letters[i + 2][0])
i += 2
elif i < 6 and i % 2 == 1 and num // all_roman_letters[i + 1][0] == 4:
integer_to_roman += (all_roman_letters[i + 1][1] + all_roman_letters[i][1])
num -= (4 * all_roman_letters[i + 1][0])
i += 1
elif num // all_roman_letters[i][0] > 0:
integer_to_roman += (num // all_roman_letters[i][0]) * all_roman_letters[i][1]
num -= (num // all_roman_letters[i][0] * all_roman_letters[i][0])
else:
i += 1
return integer_to_roman
|
aee6db2b7a6d81a36d075c9fdd79ef1033217555 | alexanderdemidkin/geekbrains | /1.py | 236 | 3.765625 | 4 | a = 6
b = 2.18
c = 'Hello world'
print(a)
print(b)
print(c)
a1 = input('введи целое число: ')
b1 = input('введи число с точкой: ')
s1 = input('введи строку: ')
print(a1)
print(b1)
print(s1) |
e7a67b50b6380904e6c9c4457144120e5b986aad | PrtagonistOne/Beetroot_Academy | /lesson_05/task_2.py | 177 | 4.1875 | 4 | # The birthday greeting program.
name = input('Enter your name: ')
age = int(input('Enter your age: '))
print(f'Hello {name}, on your next birthday you\'ll be {age + 1} years') |
3af6194e5635478dbf0941760412b5b0b4a0fc33 | janae01/independent-class-work | /workingTime.py | 2,862 | 4.1875 | 4 | # Name: Janae Dorsey
# File: workingTime.py
#
# Problem/Purpose: This program will calculate the amount of time worked by teams at a company in days, hours, and minutes.
#
# Certification of Authenticity:
# I certify that this lab is entirely my own work.
#
# Inputs: Number of teams, Number of employees on the team, Number of hours and minutes worked by each employee
# Outputs: Total number of hours and minutes worked by an entire team, Total number of days, hours, and minutes worked by teams in a company
def part1():
print("This program calculates the number of hours and minutes worked by employees on a team.")
total_hours = 0
total_minutes = 0
num_of_employees = eval(input("Enter the number of employees on the team: "))
for j in range(int(num_of_employees)):
hours = eval(input("\nEnter the number of hours worked by Employee #" + str(j+1) + " (Enter 0 if total time worked is in mintes): "))
minutes = eval(input("Enter the number of minutes worked by Employee#" + str(j+1) + " (Enter 0 if total time worked is in hours: "))
total_hours += hours
total_minutes += minutes
hour_calc = total_minutes // 60
minutes_calc = total_minutes % 60
total_hours += hour_calc
print("\nTotal time:", total_hours, "hours", minutes_calc, "minutes")
def part2():
print("This program calculates the number of days, hours, and minutes worked by teams in a company.")
teams_days = 0
teams_hours = 0
teams_minutes = 0
num_of_teams = eval(input("Enter the number of teams in the company: "))
for i in range(num_of_teams):
total_hours = 0
total_minutes = 0
num_of_employees = eval(input("\nEnter the number of employees on the team: "))
for j in range(int(num_of_employees)):
hours = eval(input("Enter the number of hours worked by Employee #" + str(
j + 1) + " (Enter 0 if total time worked is in mintes): "))
minutes = eval(input("Enter the number of minutes worked by Employee#" + str(
j + 1) + " (Enter 0 if total time worked is in hours: "))
total_hours += hours
total_minutes += minutes
hour_calc = total_minutes // 60
minutes_calc = total_minutes % 60
total_hours += hour_calc
teams_hours += total_hours
teams_minutes += minutes_calc
print("Team" + str(i+1) + " Total time:", total_hours, "hours", minutes_calc, "minutes")
teams_hours_calc = teams_minutes // 60
teams_minutes_calc = teams_minutes % 60
teams_hours += teams_hours_calc
teams_days_calc = teams_hours // 24
teams_hours = teams_hours % 24
teams_days += teams_days_calc
print("\nTotal time of all teams:",teams_days, "days", teams_hours, "hours", teams_minutes_calc, "minutes")
def main():
#part1()
part2()
main() |
4a2e5b8f641fb58b30f8e78c58f3cf6ab4d00b07 | cheekclapper69/01_Lucky_Unicorn | /076_statement gen.py | 2,632 | 4.03125 | 4 | # fully working program
# needs testing
import random
name = input("What is your name? ")
print("---------------------------")
print("Hello", name)
print("--------------")
def intcheck(question, low, high):
valid = False
error = "Please enter an number between {} and {}".format(low, high)
while not valid:
try:
response = int(input(question))
if low <= response <= high:
return response
else:
print(error)
print()
except ValueError:
print(error)
def token_statement(statement, char):
print()
print(char*len(statement))
print(statement)
print(char*len(statement))
print
# main
COST = 1
UNICORN = 5
HORSE_ZEBRA = 0.5
DONKEY = 0
print("**** Welcome to lucky Unicorn game ****")
print()
print("To play, enter an amount of money between 41 and $10 (whole dollars only),")
print()
print("- it costs $1/round")
print()
print("Payouts...")
print("-Unicorn: ${:.2f}".format(UNICORN))
print("-HORSE / ZEBRA:${:.2f}".format(HORSE_ZEBRA))
print("-DONKEY: ${:.2f}".format(DONKEY))
print()
balance = intcheck("How much money would you like to play with?", 1 , 10)
round_count = 0
print("***** Game in progress ******")
keep_going = ""
while keep_going =="":
# tokens list
tokens = ["Horse", "Horse" "Horse",
"Zebra", "Zebra", "Zebra",
"Donkey", "Donkey", "Donkey", "Unicorn"]
# randomly chosen token
token = random.choice(tokens)
print()
print("You got a {}".format(token))
# adjust the based balance
if token == "Unicorn":
token_statement("***** Congratulations! it's a ${:.2f} {}*****".format(UNICORN, token), "*")
balance += UNICORN
elif token == "Donkey":
token_statement("-- Sorry. it's a {}. You did not win anything this round --".format(token), "-")
balance -= COST
else:
token_statement("^^ Good try. it's a {}. You won back 50c ^^".format(token), "^")
balance -= HORSE_ZEBRA
print()
print("Rounds played: {} Balance: ${:.2f}".format(round_count, balance))
print()
# if user has enough money left to play ash if they want to play again...
if balance < COST:
print("Sorry you don't have enough money to continue. Game over")
keep_going = "end"
else:
keep_going = input("Press <enter> to play agian or any key to quit")
print("---------------------------------------------------")
# farewell to user
print('Thank you for playing.', name)
print("---------------------------")
|
73aeedf06c2a670ab95601d14aa92eb63887e103 | gabriellaec/desoft-analise-exercicios | /backup/user_192/ch49_2020_04_12_20_42_04_916488.py | 132 | 3.890625 | 4 | def inverte_lista(x):
invert = list()
for i in range(len(x)):
x.reverse()
invert.append(x)
return invert |
8de1f7bd0e3d3d45e041f888edbc5c20f32ed93e | gustavoddainezi/Exercicios-URI-Online-Judge | /Python/1134.py | 349 | 3.765625 | 4 | # -*- coding: utf-8 -*-
alcool = 0
gasolina = 0
diesel = 0
while True:
v = int(input())
if v == 1:
alcool += 1
elif v == 2:
gasolina += 1
elif v == 3:
diesel += 1
elif v == 4:
break
print("MUITO OBRIGADO")
print("Alcool:", alcool)
print("Gasolina:", gasolina)
print("Diesel:", diesel) |
c82806e2542ce8aae4f6e34e2cf3a475727b8028 | robertaaa/code_study | /CF/item_cf/demo1/item_cf.py | 3,296 | 3.515625 | 4 | import math
class ItemBasedCF:
def __init__(self, train_file):
self.train_file = train_file
self.readData()
def readData(self):
"""
读取数据
"""
self.train = dict()
for line in self.train_file:
user, score, item = line.strip().split(",")
self.train.setdefault(user, {})
self.train[user][item] = int(float(score))
# 输出数据集-用户(兴趣程度,物品)
print("输出测试数据集合:")
print(self.train)
def ItemSimilarity(self):
"""
物品相似度矩阵
"""
C = dict() # 物品-物品的共现矩阵
N = dict() # 物品被多少个不同用户购买
for user, items in self.train.items():
for i in items.keys():
N.setdefault(i, 0)
N[i] += 1 # 物品i出现一次就计数加一
C.setdefault(i, {})
for j in items.keys():
if i == j: continue
C[i].setdefault(j, 0)
C[i][j] += 1 # 物品i和j共现一次就计数加一
print("物品被不同用户购买次数:")
print('N:', N)
print("物品的共现矩阵:")
print('C:', C)
# 计算相似度矩阵
self.W = dict()
for i, related_items in C.items():
self.W.setdefault(i, {})
for j, cij in related_items.items():
self.W[i][j] = cij / (math.sqrt(N[i] * N[j])) # 按上述物品相似度公式计算相似度
print("物品相似度矩阵:")
for k, v in self.W.items():
print(k + ':' + str(v))
return self.W
def Recommend(self, user, K=3, N=10):
"""
给用户推荐前N个最感兴趣的物品
"""
rank = dict() # 记录用户的推荐物品(没有历史行为的物品)和兴趣程度
action_item = self.train[user] # 用户购买的物品和兴趣评分r_ui
for item, score in action_item.items():
print("item: ", item, "score: ", score)
for j, wj in sorted(self.W[item].items(), key=lambda x: x[1], reverse=True)[0:K]: # 使用与物品item最相似的K个物品进行计算
if j in action_item.keys(): # 如果物品j已经购买过,则不进行推荐
continue
rank.setdefault(j, 0)
print("j: ", j, "wj: ", wj, "score: ", score)
rank[j] += score * wj # 如果物品j没有购买过,则累计物品j与item的相似度*兴趣评分,作为user对物品j的兴趣程度
return dict(sorted(rank.items(), key=lambda x: x[1], reverse=True)[0:N])
def main():
# 测试集
uid_score_bid = ['A,1,a', 'A,1,b', 'A,1,d', 'B,1,b', 'B,1,c', 'B,1,e', 'C,1,c', 'C,1,d', 'D,1,b', 'D,1,c', 'D,1,d', 'E,1,a', 'E,1,d']
# 声明一个ItemBased推荐的对象
Item = ItemBasedCF(uid_score_bid)
# 商品相似度矩阵
Item.ItemSimilarity()
# 计算给用户A的推荐列表-K=3,N=10
print("给用户A推荐(K=3,N=10):")
recommedDic = Item.Recommend("A")
for k, v in recommedDic.items():
print(k, "\t", v)
if __name__ == '__main__':
main()
|
6baccb270aca97314cc96c226a6edad62f59a4b1 | adamcasey/Interview-Prep-With-Python | /isPalindrome.py | 3,050 | 4.40625 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-.
Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
'''
import math
class IsPalindrome_Solution:
def isPalindrome_brute(self, x: int) -> bool:
# First check if negative number
if x < 0:
return False
numString = str(x)
# Next check for odd/even length input
if len(numString) % 2 == 0:
leftIndex = rightIndex = math.floor(len(numString) // 2)
leftIndex -= 1
else:
# Everything starts in the middle of the list
middleIndex = math.floor(len(numString) // 2)
leftIndex = middleIndex - 1
rightIndex = middleIndex + 1
# Make an array of each digit
digitList = []
for eachNum in numString:
digitList.append(eachNum)
# Start at the middle index and go 'outwards' to check that each number matches
while leftIndex >= 0 and rightIndex <= len(numString) - 1:
if numString[leftIndex] != numString[rightIndex]:
return False
else:
leftIndex -= 1
rightIndex += 1
return True
def isPalindrome_better(self, x: int) -> bool:
'''
Special cases:
As discussed above, when x < 0, x is not a palindrome.
Also if the last digit of the number is 0, in order to be a palindrome, \
the first digit of the number also needs to be 0.
Only 0 satisfy this property.
'''
if x < 0 or (x % 10 == 0 and x != 0):
return False
revertedNum = 0
while x > revertedNum:
revertedNum = revertedNum * 10 + x % 10
# Don't forget to use '//' or else you'll get a decimal
x //= 10
'''
When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
For example when the input is 12321, at the end of the while loop we get x = 12, \
revertedNumber = 123, since the middle digit doesn't matter in palidrome(it will \
always equal to itself), we can simply get rid of it.
If either of these are True, it returns True
If both are False, it returns False
'''
return x == revertedNum or x == revertedNum // 10
palindromeConst = IsPalindrome_Solution()
test_Num = 12345654321
print("{} is a Palindrome: {}".format(test_Num, palindromeConst.isPalindrome_brute(test_Num)))
print("{} is a Palindrome: {}".format(test_Num, palindromeConst.isPalindrome_better(test_Num)))
|
c5aa8a523b7323b1ab78b69c783c8f452be987dd | mamathamereddy/python-and-data-science-tools | /week2/solution_to_week2_homework.py | 3,573 | 3.984375 | 4 | # 1.Write a function called fizz_buzz that takes a number
# a. If the number is divisible by 3, it should return “Fizz”.
# b. If it is divisible by 5, it should return “Buzz”.
# c. If it is divisible by both 3 and 5, it should return “FizzBuzz”.
# d. Otherwise, it should return the same number.
def fizzbuzz(n):
if n % 3 == 0 and n % 5 == 0:
print("fizz buzz")
elif n % 3 == 0:
print("fizz")
elif n % 5 == 0:
print("buzz")
else:
print(n)
number=int(input("enter a number:"))
fizzbuzz(number)
#2.Consider a lst= [5, 10, 20] and write a try and except block to avoid IndexError.
lst= [5, 10, 20]
def find_index(n):
try:
print(lst[n])
except IndexError:
print("index not found")
find_index(4)
#3.Create a class of Jet inventory with two arguments i.e name and country.
# Also add the minimum 2 items in the class and print them.
class Jet:
def __init__(self, name, country):
self.name = name
self.country = country
def jet_Info(self):
print(f'{self.name} is a {self.country} airline')
myjet = Jet("SAS", "Scandinavian")
myjet.jet_Info()
#5.Write a Python script to check whether a given key already exists in a dictionary.
# Dictionary Initialisation
My_Dict = {'1':'Joy', '2':'John', '3':'Joye', '4':'Jiya'}
for key, value in My_Dict.items():
print(key, value)
def guess_key(input_key):
if input_key in My_Dict:
print(f'key entered - {input_key} is found')
else:
print(" No key found!")
user_key = input("which key do you want to guess?\n")
print('user_key ', user_key)
guess_key(user_key)
#6.Write a function called showNumbers that takes a parameter called limit.
# It should print all the numbers between 0 and limit with a label to identify the even and odd numbers.
#For example, if the limit is 3, it should print:
#0 EVEN
#1 ODD
#2 EVEN
#3 ODD
def shownumber(limit):
for i in range(limit+1):
if i % 2 == 0:
print(f"{i} EVEN")
else:
print(f"{i} ODD")
limit_number=int(input("enter a limit number:"))
shownumber(limit_number)
#8.Create a class named Person, with firstname and lastname properties, and a print name method.
class Person:
def __init__(self, firstname,lastname):
self.first_name = firstname
self.last_name = lastname
def print_name(self):
print(f' Person Name is : {self.first_name} {self.last_name}')
person_name = Person("Mamatha","Mereddy")
person_name.print_name()
#9.Write a program asks for numeric user input. Instead the user types characters in the input box.
# The program normally would crash. But write try-except block so it can be handled properly.
def numeric_user_input():
try:
user_input=int(input("enter a number:"))
print(user_input)
except ValueError:
print("invalid input,try to enter a number")
numeric_user_input()
#10.Write a Python program to create two empty classes, Student and Marks.
# Now create some instances and check whether they are instances of the said classes or not.
# Also, check whether the said classes are subclasses of the built-in object class or not.
class Student:
pass
class Marks:
pass
student1 = Student()
marks1 = Marks()
print(isinstance(student1, Student))
print(isinstance(marks1, Marks))
print("\nCheck whether the said classes are subclasses of the built-in object class or not.")
#print(issubclass(Student, Marks))
print(issubclass(Student, object))
print(issubclass(Marks, object)) |
093452212334a263211c681c5249399d869cf9ae | noufal85/make_a_developer | /algorithms/grokking_algorithms/breadth_first_search.py | 957 | 4 | 4 | """simple graph based algorithms"""
# hash table -> graph -> queue
# First implement a graph (a hash table with the graph values)
from collections import deque
graph = {}
graph["you"] = ["alice", "bob", "clairem"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "johnny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
person_is_seller = lambda x: x[-1] == "m"
# search_queue = deque()
# search_queue += graph["you"] # your neighbours
def breadth_first_search(name):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if not person in searched:
if person_is_seller(person):
print(person + " is a seller")
return True
else:
search_queue += graph[person]
searched.append(person)
return False
|
1a5ebbf187264d2cae751fe6c3947ca728cdde8c | andrewjrangel/Pythoneze | /RockPaperScissors.py | 5,305 | 4.46875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is called Rock Paper Scissors
# The goal is to play the timeless game against the computer
# Who will win!?
playAgain = "yes"
import time
while playAgain == "yes":
print "Welcome to Rock Paper Scissors"
print "******************************"
playerMove = raw_input("Please enter your move: ").lower()
print " "
print " ...processing..."
time.sleep(2)
print " "
possibleMovesList = ["paper", "rock", "scissors"]
possible = False
playerMoveList = [playerMove]
while possible == False:
if (playerMove in possibleMovesList):
possible = True
else:
print "What?! That is not a possible move, and frankly is offensive. Try again please."
playerMove = raw_input("Please enter your move: ").lower()
import random
randomIndex = random.randint(0, len(possibleMovesList)-1)
computerMove = possibleMovesList[randomIndex]
playerMoveIndex = possibleMovesList.index(playerMove)
computerMoveIndex = possibleMovesList.index(computerMove)
if playerMoveIndex == 2:
if computerMoveIndex == 0:
print "Player wins with the wise choice of " + playerMove + ". computers are dumb, and it chose " + computerMove
else:
print "Computer wins, and will take over the world. It chose " + computerMove + ", silly human chose " + playerMove
elif playerMoveIndex == computerMoveIndex:
print "Tie! What does this mean for the battle of human vs machine?"
elif playerMoveIndex < computerMoveIndex:
if computerMoveIndex == 2:
print "Computer wins, and will take over the world. It chose " + computerMove + ", silly human chose " + playerMove
else:
print "Player wins with the wise choice of " + playerMove + ". computers are dumb, and it chose " + computerMove
else:
print "Computer wins with " + computerMove + " over player's " + playerMove + ", sigh... again."
print " "
playAgainInput = raw_input("Would you like to play again? ")
print " "
answerValid = False
while answerValid == False:
if playAgainInput.lower() == "no" or playAgainInput.lower() == "yes":
playAgain = playAgainInput.lower()
if playAgainInput.lower() == "yes":
print " "
print "Loading WATSON super computer as apponnent..."
print " "
time.sleep(2)
break
else:
time.sleep(2)
print "fine..."
time.sleep(3)
print " "
print "jerk"
time.sleep(4)
print " "
print "WHY ARE YOU STILL HERE??"
time.sleep(6)
print "OH MY GOD. YOU ARE FREAKING ME OUT"
print """⠀
⠀
⠀ ☄
⠀ ☄
⠀
⠀
◞◟﹏◞◟﹏◞◟﹏◞◟﹏◞◟﹏◞◟﹏
ˋ ˌ ˊˏ ˗ ˋˏ ˊˎˋ ˌ ˊˏ ˗ ˋˏ ˊˎˋ ˌ ˊˏ ˗ """
time.sleep(1)
print """
░░░░░░░░░░░░░░░░░░
╱◣░░╱◣░░░░░░░
█████████◣░░░░
██ ██ ██░░░░
███████████◤░
█████\/╲/░░░
█████████◣░░░░
███░░░░░░░░░░░░░░"""
time.sleep(1)
print """
⠀
⠀ ╭╮╭╮
╭╯(◉)(◉)╰━━━━━━╮
┃⠀⠀\/\/\/\/\/\/\/\/\/┃
┃⠀ ┏━━━━━━━━━╯
┃⠀ ┃
┃⠀ ┃
┃⠀ ┃
┃⠀ ┃"""
time.sleep(1)
print"""
▲⠀⠀⠀▼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀◥
⠀⠀🔻⠀⠀⠀⠀🔹⠀▾⠀⠀▴
⠀⠀⠀⠀▾⠀⠀⠀▼⠀⠀ 🔺
⠀◤
⠀⠀⠀⠀⠀🔸⠀⠀⠀⠀⠀⠀⠀⠀⠀🔹
⠀⠀⠀▲⠀⠀⠀⠀⠀⠀◤⠀⠀🔻
▲⠀⠀⠀⠀⠀🔹
⠀⠀🔻⠀⠀⠀⠀🔹⠀▾⠀⠀▴
⠀⠀⠀⠀▾⠀⠀⠀▼⠀⠀ 🔺
⠀▼▴
⠀⠀⠀⠀⠀🔺⠀⠀⠀🔸"""
time.sleep(1)
print """
⠀
⠀
⠀
⠀⠀
⠀
⠀⠀⠀┃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀╮
╭━┫⠀╭━╮⠀╭━╮ ┣━
┃⠀ ┃⠀┃⠀ ┃⠀┃⠀ ┃⠀┃
╰━╯⠀╰━╯⠀┃⠀ ┃⠀╰━╯
⠀
⠀
⠀DON'T PRESS THIS
⠀
⠀⠀⠀⠀⠀⠀⠀🔴
⠀
⠀
⠀⠀
⠀
⠀"""
time.sleep(2)
print"WHY WOULD YOU TRY AND PRESS THAT?"
print"It isn't even a touch screen"
time.sleep(3)
print """
⠀
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
▒░╭━━━━━━╮░▒▒
▒░┃⠀◕⃝◞⠀⠀◟◕⃝⠀⠀┃░▒▒
▒░┃⠀⠀⠀❣⠀💧⠀⠀┃░▒▒
▒░╰━━━━━━╯░▒▒
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
⠀⠀⠀╭╯⠀⠀⠀⠀ ╰╮
⠀⠀⠀┗━━━━━┛"""
time.sleep(1)
print "I give up....why can't you just leave me alone"
time.sleep(2)
print "*** SHUTTING DOWN WATSON SUPER COMPUTER ***"
time.sleep(2)
print "*********"
print "ERROR ERROR ERR"
import sys
sys.exit("aa! errors!")
break
else:
print "That's great...but do you want to play again?"
playAgainInput = raw_input(" ")
#print "Player move of {} is of index {}".format(playerMove, possibleMovesList.index(playerMove))
#print "Player Move " + playerMove
#print "Computer Move " + computerMove |
b653d0d83df5fe82c69e0d65981851aee99945f5 | smartvkodi/learn-python | /4-Python_Flow_Control_Part-1/62-if-elif-else_statement_and_applications.py | 1,803 | 4.25 | 4 | # 62 - if-elif-else statement and applications
msg = '62 if-elif-else statement and applications'
tn = ' '*5
text = '#'+ tn + msg + tn + '#'
i = len(text)
print('#'*i)
print(text)
print('#'*i)
print('\n')
print('''Example-1: simply if statement
name = input('Enter your name:')
if name == 'durga':
print('Hello Durga, Good Evening')
print('How are you?') # statement out of condition
''')
name = input('Enter your name:')
if name == 'durga':
print('Hello Durga, Good Evening') # identeted statement under if condition
print('How are you?')
print('''\nExample-2: if-else statement
if condition|:
Action-1
else:
Action-2
statement...
name = input('Enter your name:')
if name == 'durga':
print('Hello Durga, Good Evening')
else:
print('Hello Guest, Good Evening')
print('How are you?') # statement out of condition
''')
name = input('Enter your name:')
if name == 'durga':
print('Hello Durga, Good Evening')
else:
print('Hello Guest, Good Evening')
print('How are you?') # statement out of if-else
print('''\nExample-3: if-elif-else statement
if condition-1|:
Action-1
elif condition-2:
Action-2
elif condition-3:
Action-3
.
.
.
else:
Default Action
statement...
brand = input('Enter your favorite brand:')
if brand == 'KF':
print('It is a childrens brand')
elif brand == 'KO':
print('It is too light')
elif brand == 'RC':
print('It is not that much kick')
elif brand == 'FO':
print('Buy one Get one Free')
else:
print('Other brands are not recommended')
''')
brand = input('Enter your favorite brand:')
if brand == 'KF':
print('It is a childrens brand')
elif brand == 'KO':
print('It is too light')
elif brand == 'RC':
print('It is not that much kick')
elif brand == 'FO':
print('Buy one Get one Free')
else: # is always optional
print('Other brands are not recommended')
|
895c1ed9db478258e15e5495c9fd3d818ad94394 | SpringMagnolia/sentence_cut | /lib/cut_sentence.py | 4,100 | 3.5 | 4 | '''
切分句子
返回结果:[('Knowledge Graph', 'cymc'), ['在'], ('TBD云集中心', 'jgmc')]
类型:列表
元素类型:
列表:非核心词,用结巴切出,长度为1
元组:标识匹配出的核心词,比如课程名(kc),纯数字(N),数字+字母(A) ,长度为2
'''
import re
import jieba
import os
from .mm import MCut
__abs_path = os.path.split(os.path.abspath(__file__))[0]
# jieba.load_userdict("./词典/课程名词_kc.txt")
_re_match_number = re.compile("\d+")
_re_match_letter_number = re.compile("[a-zA-Z0-9_\-/]+",re.S)
def extract_letter_number_from_sentence(sentence):
ret_findall = _re_match_letter_number.findall(sentence)
ret_split = _re_match_letter_number.split(sentence)
# print(ret_split)
# print(ret_findall)
assert len(ret_split)-1 == len(ret_findall),"split之后的结果减去1:{} 应该和查到到的结果:{}相同".format(len(ret_split)-1,len(ret_findall))
_list = []
for i in range(len(ret_split)-1):
if ret_findall[i]!="":
_list.append([ret_split[i]])
_found_str = [ret_findall[i]]
_found_str.append("N" if ret_findall[i].isdigit() else "A")
_found_str = tuple(_found_str) #tuple 表示是英文和数字,后续进行命名体识别时候进行替换
_list.append(_found_str)
if ret_split[-1] != "":
_list.append([ret_split[-1]])
return _list
def load_user_dict(path="./词典"):
file_list = [os.path.join(path,i) for i in os.listdir(path)]
total_lines = []
[total_lines.extend(open(file).readlines()) for file in file_list]
user_dict = {}
for i in total_lines:
# print(i.split())
if len(i.strip())>=1:
user_dict[i.rsplit(maxsplit=1)[0].strip().lower()]=i.rsplit(maxsplit=1)[1].strip()
return user_dict
def mm_rmm_match(sentence,user_dcit):
"""
调用正向、反向最大匹配方法进行名词的匹配
:param sentence:
:param user_dcit:
:return:
"""
print(user_dcit)
window_size = max([len(i) for i in user_dcit])
if len(sentence)<window_size:
window_size = len(sentence)
m_cut = MCut(user_dcit,window_size)
ret = m_cut.cut(sentence)
print("mm_rmm_match_ret:",ret)
return ret
def cut_sentence(sentence):
'''
对文本进行分词
0. 对句子根据自定义的词典 按照正向反向最大匹配进行配
1. 先提取文本中的英文和数字
2. 对文本中除了英文和数字的内容进行分词
:param sentence:
:return:
'''
#0. 对句子根据自定义的词典 按照正向反向最大匹配进行配
user_dict_path = "../词典"
user_dict_path = os.path.join(__abs_path,user_dict_path)
user_dict = load_user_dict(user_dict_path)
mm_cut_ret = mm_rmm_match(sentence,user_dict)
#1. 先提取文本中的英文和数字
cut_ret = []
for i in mm_cut_ret:
if isinstance(i,tuple):
cut_ret.append(i)
elif isinstance(i,list):
assert len(i) == 1, "未匹配到的字符列表中只有一个元素"
#extracted_letters_sentence: [['我的微信是'], ('Ws23sf9', 'A'), [',我的电话是'], ('13146128763', 'N')]
extracted_letters_sentence = extract_letter_number_from_sentence(i[0])
cut_ret += extracted_letters_sentence
#2.对文本中除了英文和数字的内容进行分词
final_cut_ret = []
for i in cut_ret:
if isinstance(i,tuple):
final_cut_ret.append(i)
elif isinstance(i,list):
assert len(i) == 1, "未匹配到的字符列表中只有一个元素"
jieba_cut_ret = [[i] for i in jieba.cut(i[0])]
final_cut_ret += jieba_cut_ret
return final_cut_ret
if __name__ == '__main__':
text = "我的微信是Ws23sf9,我的电话是13146128763,我想从事UI/UE设计"
# text = "我想了解人工智能+Python这个学科的学费"
# text = "你好,世界"
# print(text)
ret = cut_sentence(text)
print(ret)
# print(__abs_path)
|
4f71d934c9456c9c1e9052eefb16af10235daf05 | preksha01/preksha01 | /calendar.py | 152 | 4.15625 | 4 | import calendar
the_year= int (input("enter the year: "))
the_month= int(input("enter the month: "))
print()
print (calendar.month(the_year,the_month))
|
33faf13bda85445cf8692ffb06972d3f15c786df | guozhaoxin/leetcode | /num601_700/num621_630/num623.py | 2,400 | 4.1875 | 4 | #encoding:utf8
__author__ = 'gold'
'''
623. Add One Row to Tree
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
Input:
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 2
Output:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5
Example 2:
Input:
A binary tree as following:
4
/
2
/ \
3 1
v = 1
d = 3
Output:
4
/
2
/ \
1 1
/ \
3 1
Note:
The given d is in range [1, maximum depth of the given tree + 1].
The given binary tree has at least one tree node.
'''
from common.tree import TreeNode,preOrder,arrayToTree
class Solution:
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
if d == 1:
newRoot = TreeNode(v)
newRoot.left = root
return newRoot
curRowNodes = [root]
while d != 2:
childNodes = []
for node in curRowNodes:
if node.left:
childNodes.append(node.left)
if node.right:
childNodes.append(node.right)
d -= 1
curRowNodes = childNodes
for node in curRowNodes:
left = TreeNode(v)
right = TreeNode(v)
left.left = node.left
right.right = node.right
node.left = left
node.right = right
return root
if __name__ == '__main__':
numList = [4,2,6,3,1,5, None]
root = arrayToTree(numList)
preOrder(root,True)
root = Solution().addOneRow(root,1,2)
preOrder(root,True) |
885b2b34061f8f530923bcb823fbc2779e3c282b | smart00912/newdj | /test.py | 484 | 3.9375 | 4 | class Test(object):
__slots__ = ('name', 'age')
test = Test()
test.name = 'sean.li'
test.age = '33'
# test.address='beijing' will have error
class Father(object):
def __init__(self):
print 'here is fathers class'
class Children(Father):
def __init__(self):
print 'here is childrens class'
# call father class
super(Children, self).__init__()
result = Children()
# show all father class for a children class
print Children.__base__
print issubclass(Children,Father)
|
489ec51aa811c71ed7f9baed1670cfb94c06cee3 | cardevisi/python-course | /indicador-passagem-decrescente.py | 915 | 4.09375 | 4 | ##Indicadores de passagem são variáveis condicionais que determinam uma mudança ou a quebra de execução de um trecho de código. No exemplo abaixo enquanto a variável decrescente for verdadeira o loop irá solicitar ao usuário que preencha o próximo número da sequência. Quando esse condição é quebrada, ou seja quando o próximo número da sequência não estiver na ordem decrescente o loop é interempido, o valor da variável decrescente passa a ser False indicando a passagem de um estado para outro.
decrescente = True
anterior = int(input('Digite o primeiro número da sequência: '))
valor = 1
while valor != 0 and decrescente:
valor = int(input('Digite o próximo número da sequência: '))
if valor > anterior:
decrescente = False
anterior = valor
if decrescente == True:
print('A sequência está em ordem descrecente')
else:
print('A sequência não está em ordem descrecente') |
ab95120f6a2904df0aa313d0e662fff6f0e4fa5f | tomku-personal/Games | /PlayCards/playing_cards.py | 1,195 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Classes to model a deck of playing cards and related basic functionalities
Created on Mon Sep 01 11:21:32 2014
@author: Tom
"""
class Card(object):
# default single-character reprsentation of high rank values.
# YYY: Assumes only single representation of numerical rank.
rank_mapping = [(10, 'T'),
(11, 'J'),
(12, 'Q'),
(13, 'K'),
(14, 'A')]
rank_val, rank_str = zip(*rank_mapping)
str_2_rank = dict(zip(rank_str, rank_val))
rank_2_str = dict(zip(rank_val, rank_str))
def __init__(self, suit, rank):
self.suit = suit
self.rank = Card.str_2_rank.get(rank, rank)
def __str__(self):
return '{s}{r}'.format(s = self.suit,
r = Card.rank_2_str.get(self.rank, self.rank))
def __repr__(self):
return 'Card({s}, {r})'.format(s = self.suit, r = self.rank)
# this only runs if the module was *not* imported
if __name__ == '__main__':
from random import randrange
deck = [Card(s, r) for r in range(2, 14) for s in ['S', 'H', 'D', 'C']]
print deck[randrange(len(deck))] |
bf21da96161744ec3a2e47351373377d7b8387b3 | jxie0755/Learning_Python | /ProgrammingCourses/MIT6001X/week2/an_letter_loop.py | 663 | 3.90625 | 4 | an_letters = "aefhilmnorsxAEFHILMNORSX"
word = input("Give me a word:")
times = int(input("Times to repeat:"))
i = 0
while i < len(word):
char = word[i]
if char in an_letters:
print("Give me an " + char + ": " + char + "!")
else:
print("Give me a " + char + ": " + char + "!")
i += 1
print("What does that spell?")
for n in range(times):
print(word + " !!!")
print()
word = input("Give me a word:")
times = int(input("Times to repeat:"))
i = 0
while i < len(word):
char = word[i]
print("Give me " + char + ": " + char + "!")
i += 1
print("What does that spell?")
for n in range(times):
print(word + " !!!") |
a8663ad1c3f922029c6ac6dfd3ef3a6cdbe669eb | DouglasRudd/astroberryAddons | /hw_testing/netTestServer.py | 722 | 3.875 | 4 | # Network comms test - server
# Very basic communication to a client
import socket
port = 3002 # A port to run the server on
print("Server starting......")
# Create a socket to listen on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind to the hostname
s.bind(('', port))
# Start listening
s.listen(5)
while True:
# accept connections from outside
(clientsocket, address) = s.accept()
print("New connection from ", address)
# Send a hello over the connection
msg = "Hello remote client\n"
clientsocket.send(msg.encode('ascii'))
# Receive data from the client
(bbuffer, raddr) = clientsocket.recvfrom(1024)
print("Message from", raddr)
print("Message: ", bbuffer)
|
5cdb82200b52fc2724675f8eb7aa81f15411c0f4 | chaeonee/Programmers | /level4/가사검색.py | 2,108 | 3.5 | 4 | from collections import deque
class Node:
def __init__(self, keyword = None):
self.keyword = keyword
self.n_data = {}
self.child = {}
class Trie:
def __init__(self):
self.root = Node()
def addData(self,word):
cur_node = self.root
w_len = len(word)
for w in word:
if w_len in cur_node.n_data.keys():
cur_node.n_data[w_len] += 1
else:
cur_node.n_data[w_len] = 1
if w in cur_node.child.keys():
cur_node = cur_node.child[w]
else:
cur_node.child[w] = Node(w)
cur_node = cur_node.child[w]
w_len -= 1
def search(self, query, n_blank):
num = 0
i = 0
q = deque()
q.append(self.root)
while q:
q_len = len(q)
for _ in range(q_len):
cur = q.popleft()
if i == len(query):
if n_blank in cur.n_data.keys():
num += cur.n_data[n_blank]
continue
if query[i] in cur.child.keys():
q.append(cur.child[query[i]])
i += 1
return num
def solution(words, queries):
pre_trie = Trie()
post_trie = Trie()
for w in words:
pre_trie.addData(w)
post_trie.addData(w[::-1])
answer = []
for query in queries:
n_blank = 0
if query[0] == '?':
for q in query:
if q != '?':
break
n_blank += 1
query = query[n_blank:][::-1]
answer.append(post_trie.search(query,n_blank))
else:
for q in query[::-1]:
if q != '?':
break
n_blank += 1
query = query[:len(query)-n_blank]
answer.append(pre_trie.search(query,n_blank))
return answer
|
d7c4f2b8afe94158e40f37d179c1546804b6264b | jedzej/tietopythontraining-basic | /students/burko_szymon/lesson_01_basics/digital_clock.py | 102 | 3.734375 | 4 | N = int(input("Minutes after midnight: "))
print("Actual hour: " + str(N // 60) + " " + str(N % 60))
|
e78db152761909421fccd714cbcffebe0fb582e6 | RianRBPS/PythonMundos | /Exercícios/Mundo02 036-071/ex047.py | 214 | 3.8125 | 4 | #Mais eficiente
print('Os números pares no intervalo de 1 a 50 são:')
for c in range(2, 51, 2):
print(c, end=' ')
print('Fim')
for n in range(1, 51):
if n % 2 == 0:
print(n, end=' ')
print('Fim') |
c93cd7290945097b04cdc0bd733094dfff554cad | oliverlai55/algo-toolbox | /weekly-assignments/week2/4_2_least_common_multiple.py | 378 | 3.671875 | 4 | # Uses python2
import sys
def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
remainder = a % b
gcdNum = gcd(b, remainder)
return gcdNum
def lcm(a, b):
gcdNum = gcd(a, b)
return a * b / gcdNum
if __name__ == '__main__':
input = sys.stdin.read()
a, b = map(int, input.rstrip().split())
print(int(lcm(a, b)))
|
a9919102bb29247bdbc81f34faa5e261253aa740 | sbtries/Class_Polar_Bear | /Code/Ryan/python/password_p_2.py | 1,549 | 4 | 4 | import random
import string
def verify_int(message):
while True:
length = input('message')
try:
lenth = int(length)
break
except ValueError:
print('Invalid number, try again.')
return length
password = ''
lower_letters = ''
uppercase_letters = ''
digits = ''
special_characters = ''
#----------------> trying something new that doesn't work yet <-------------------#
# special_password = [lower_letters, uppercase_letters, digits, special_characters]
# string_characters = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation]
# for character in special_password:
# character = verify_int(f'Enter number of {character}: ')
# for x in range(character):
# password += random.choice(string_characters)
# print(password)
lower_letters = verify_int('Enter number of lowercase letters: ')
for x in range(lower_letters):
password += random.choice(string.ascii_lowercase)
uppercase_letters = verify_int('Enter number of uppercase letters: ')
for x in range(uppercase_letters):
password += random.choice(string.ascii_uppercase)
digits = verify_int('Enter number of digits: ')
for x in range(digits):
password += random.choice(string.digits)
special_characters = verify_int('Enter number of special characters: ')
for x in range(special_characters):
password += random.choice(string.punctuation)
password_list = list(password)
random.shuffle(password_list)
password = ''.join(password_list)
print(password_list)
|
5a2af344901a3439691f25099ed9eb5c043d5fa3 | Miuywu/AirBnB_clone | /models/engine/file_storage.py | 2,358 | 3.5 | 4 | #!/usr/bin/python3
"""File storage.
This module defines a class `FileStorage` that is capable of serializing
application objects and storing them in files for later retreival.
"""
import json
from os import path
from models.base_model import BaseModel
from models.user import User
from models.place import Place
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.review import Review
class FileStorage():
"""
Serializes instances to a JSON file and deserializes JSON file to
instances.
"""
__file_path = "file.json"
__objects = {}
def all(self):
""" returns a dictionary of obj.id: <val> """
return FileStorage.__objects
def new(self, obj):
""" sets the instance: id pair in the dict __objects """
FileStorage.__objects[obj.__class__.__name__ + '.' + obj.id] = obj
def save(self):
""" serializes __objects to JSON file at __file_path """
with open(FileStorage.__file_path, 'w') as fi:
d = {k: v.to_dict() for k, v in FileStorage.__objects.items()}
fi.write(json.dumps(d))
def reload(self):
""" deserializes JSON file at __file_path and stores into __objects """
if path.isfile(FileStorage.__file_path):
with open(FileStorage.__file_path) as fi:
d = json.load(fi)
# FileStorage.__objects =\
# {k: BaseModel(**v) for k, v in d.items()}
FileStorage.__objects = {}
for k, v in d.items():
if k.startswith('BaseModel.'):
FileStorage.__objects[k] = BaseModel(**v)
elif k.startswith('User.'):
FileStorage.__objects[k] = User(**v)
elif k.startswith('Place.'):
FileStorage.__objects[k] = Place(**v)
elif k.startswith('State.'):
FileStorage.__objects[k] = State(**v)
elif k.startswith('City.'):
FileStorage.__objects[k] = City(**v)
elif k.startswith('Amenity.'):
FileStorage.__objects[k] = Amenity(**v)
elif k.startswith('Review.'):
FileStorage.__objects[k] = Review(**v)
|
4411ef712da83feee888819a5554aec64fb39806 | joseishere/jose_test2 | /tryFloat.py | 1,011 | 3.609375 | 4 | # tryFloat.py
import re
def floatChecker(arr):
# I did this one with regex after people started to talk about how they used it in the plc group chat
# of course all of the other ones I didn't do with regex bc they were already done
# really wish i would have done everything with regex
# also I used this website to help me build the regex string
# it is really well made and you should donate to help keep it running
# the website is : https://regex101.com
regexBase = r"(-)?(\d)*(.)?\d+(e|E)?(-)?\d(l|L|f|F)?"
if(re.fullmatch(regexBase, arr)):
# print('is valid')
return True
else:
return False
def main():
words = ["23.75", "0.59201E1", "1312221215e-2", "-2.5e-3", "15E-4", "121.0L", "122.0F", "1x0.0F", ".02ef3", "0.01ee1", "0.5e1lf", "69e--2"]
for word in words:
if(floatChecker(word)):
print(word + " is valid")
else:
print(word + " is not valid")
if __name__ == "__main__":
main()
|
6bcb4306682a87e8fae67a2e8deb04326450c22f | reyllama/leetcode | /Python/C394.py | 2,860 | 4.09375 | 4 | """
394. Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
"""
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
l = []
i = 0
while i < len(s)-1:
i += 1
if s[i] == "[":
l.append(i)
elif s[i] == "]":
j = l.pop()
try:
try:
num = int(s[j-3:j]) # 3 digit
prefix = s[:j-3]
except:
num = int(s[j-2:j]) # 2 digit
prefix = s[:j-2]
except:
num = int(s[j-1]) # 1 digit
try:
prefix = s[:j-1]
except:
prefix = ""
try:
suffix = s[i+1:]
except:
suffix = ""
s = prefix + num * s[j+1:i] + suffix
i -= 3
return s
"""
Runtime: 20 ms, faster than 43.14% of Python online submissions for Decode String.
Memory Usage: 13.6 MB, less than 54.92% of Python online submissions for Decode String.
"""
### reference code
def stacky(s):
"""
When we hit an open bracket, we know we have parsed k for the contents of the bracket, so
push (current_string, k) to the stack, so we can pop them on closing bracket to duplicate
the enclosed string k times.
"""
stack = []
current_string = ""
k = 0
for char in s:
if char == "[":
# Just finished parsing this k, save current string and k for when we pop
stack.append((current_string, k))
# Reset current_string and k for this new frame
current_string = ""
k = 0
elif char == "]":
# We have completed this frame, get the last current_string and k from when the frame
# opened, which is the k we need to duplicate the current current_string by
last_string, last_k = stack.pop(-1)
current_string = last_string + last_k * current_string
elif char.isdigit():
k = k * 10 + int(char) # Great Idea
else:
current_string += char
return current_string |
d935a675f450bcdb0470a716ce8bb1bcda3fb3a4 | trefael/CrackingTheCodingInterview-6th | /ArrayAndStrings/ArraysAndStrings_Q1_6_StringCompression.py | 934 | 4.53125 | 5 | """
1.6 String Compression
Implement a method to perform basic string compression using the counts of replaced chars.
i.e- aabbcccccaaa will become --> a2b1c5a3
If the new string wouldn't become smaller- method will return the original string.
Assumptions:
1. Case sensitive.
2. Strings in ASCII
3. input between a-z
"""
def StringCompression(myString):
compressedString = ''
charSequence = 0
for i in range(0, len(myString)):
# myString[i] = myString[i].lower()
charSequence += 1
if i+1 >= len(myString) or myString[i] != myString[i+1]:
compressedString += myString[i] + str(charSequence)
charSequence = 0
if len(myString) > len(compressedString):
return compressedString
return myString
if __name__ == '__main__':
print(StringCompression("aabbcccccaaa")) # Output- a2b1c5a3
print(StringCompression("aAbBcCcCccaA")) # Output- aAbBcCcCccaA
|
c344a6dff5459534ac6023e9b3cfe1f0890dab49 | qcmoke/study_python | /01_basic/py07_4继承.py | 951 | 4.40625 | 4 | """
子类属性和方法的查找原则:先查子类再查父类
"""
class Person:
"""人类"""
def __init__(self, name, age):
super().__init__()
self.name = name
self.age = age
def say(self):
print("{}在说话".format(self.name))
class Student(Person):
"""学生"""
def __init__(self, name, age, clazz):
super().__init__(name, age) # 由于父类的__init__()有对象属性的值形参,故一定要传入,否则无法初始化对象属性
self.clazz = clazz
def say(self, msg): # 重写父类方法
print("{}说了{}".format(self.name, msg))
class Teacher(Person):
"""教师"""
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
def teach(self):
print("在上课教书")
Student("zhangsan", 21, "软工1班").say("I am a good boy !")
Teacher("王老师", 31, 10000).say()
|
6b9a8dcd729ea2f0728201335c48349a1781b195 | kh896424665/Python | /pystudy/iterable.py | 212 | 3.75 | 4 | def findMinAndMax(L):
max = L[0]
min = L[0]
for item in L:
if item > max:
max = item
if item < min:
min = item
return (max, min)
print(findMinAndMax([7,1])) |
657ccee59e2a9fae72793b5d8f695c05fd5a5f7a | irenge/python_jogg | /cmp.py | 447 | 3.5 | 4 | x = "reset"
y = "rest"
def near(x,y):
count = 0
if ((len(y) + 1) == len(x)):
for i in range(len(y)):
for j in range(len(x)):
if count == len(x):
return False
elif y[i] == x[j]:
count = 0
continue
else:
count += 1
return True
else:
return False
print(near(x,y)) |
ae05eca20cd1986bcde9d76c652ea9cdca65e476 | Soojin-C/Soft_Dev_Work | /17_listcomp/problem.py | 2,419 | 3.75 | 4 | # Team Pizza - Bo Lu, Soojin Choi
# Softdev pd7
# k17 -- PPFTLCW
# 2019-04-15
def num1():
list = []
for i in range(5):
x = str(i*22)
list.append(x)
print(list)
return list
def num1_list():
list = [str(x*22) for x in range(5)]
print(list)
return list
num1()
num1_list()
def num2():
list = []
x = 7
for i in range(5):
list.append(x + i*10)
print(list)
return list
def num2_list():
rng = 5
start = 7
list = [(start+x*10) for x in range(rng)]
print(list)
return list
num2()
num2_list()
def num3(n):
list = []
for i in range(n):
for j in range(3):
list.append(i * j)
print(list)
return list
def num3_list(n):
list = [i * j for i in range(n) for j in range(3)]
print(list)
return list
num3(3)
num3_list(3)
primes = [0,2,3,5,7] #kind of cheating a bit
def num4():
list = []
for x in range(101):
if (x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0) and x not in primes:
list.append(x)
print(list)
return list
def num4_list():
list = [x for x in range(101) if (x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0) and x not in primes]
print(list)
return list
num4()
num4_list()
#num5 missing!!!
def num5():
list = []
for x in range(99):
add = True
for each in list:
if (x+2) % each == 0:
add = False
if (add):
list.append(x+2)
print(list)
return list
#print("Num5:")
num5()
def num6(num):
list = []
for x in range(1, num + 1):
if num % x == 0:
list.append(x)
print(list)
return list
def num6_list(num):
list = [x for x in range(1, num + 1) if num % x == 0]
print(list)
return list
num6(80)
num6_list(80)
num6(40150)
num6_list(64108)
def num7(matrix):
r = len(matrix)
c = len(matrix[0])
temp = []
for i in range(r):
temp2 = []
for j in range(c):
temp2.append(matrix[j][i])
temp.append(temp2)
print(temp)
return temp
#not sure why this works, I just kept switching i and j around.
def num7_list(matrix):
list = [matrix[i][j] for j in range(len(matrix))
for i in range(len(matrix[0]))]
print(list)
return list
test= [[0, 1, 2],
[0, 1, 3],
[5, 1, 2]]
num7(test)
num7_list(test) |
8edbd9c3d07db5825f517f27fb3629eb90face90 | Shashi-Chaurasia/Python_Code_Tutorials | /opps_concept/10_pr_04.py | 1,797 | 4.09375 | 4 | # class Train:
# def __init__(self , name , seat ,fare ) -> None:
# self.name = name
# self.seat = seat
# self.fare = fare
# def nameOfTrain(self):
# print(f" Indian Railway : {self.name}")
# def Trainfare(self):
# print("*********************")
# print(f"fare of {self.name} train is : {self.fare} ")
# print("*********************")
# def booking(self):
# if(self.seat > 0):
# print("*************************")
# print(f"seat is avilable you can book you seat {self.seat}")
# print("******************")
# self.seat -= 1
# else:
# ("Sorry ! seat are not avilable !")
# intercity = Train("SamparkKaranti" , 2 , 456)
# intercity.nameOfTrain()
# intercity.Trainfare()
# intercity.booking()
'''
1 2 3 4 5 6 7 8 9 10
'''
class Train:
def __init__(self, name, fare, seats):
self.name = name
self.fare = fare
self.seats = seats
def getStatus(self):
print("************")
print(f"The name of the train is {self.name}")
print(f"The seats available in the train are {self.seats}")
print("************")
def fareInfo(self):
print(f"The price of the ticket is: Rs {self.fare}")
def bookTicket(self):
if(self.seats>0):
print(f"Your ticket has been booked! Your seat number is {self.seats}")
self.seats = self.seats - 1
else:
print("Sorry this train is full! Kindly try in tatkal")
def cancelTicket(self, seatNo):
pass
intercity = Train("Intercity Express: 14015", 90, 2)
intercity.getStatus()
intercity.bookTicket()
intercity.bookTicket()
intercity.bookTicket()
intercity.getStatus()
|
7927514f7b568ec448b5120214a4a3f76a866e99 | godfreypj/cyclonescraper | /scraper.py | 2,767 | 3.671875 | 4 | #Import statements:
# requests for downloading needed webpage
# beatifulsoup for parsing the webpage
import pip._vendor.requests as requests
from bs4 import BeautifulSoup
#The module will retrieve data from the NOAA website. Depending on the users selection,
# this will either retrieve data from Atlantic Ocean, or Pacific or Central Pacific Ocean.
# Each function requests and parses two separate webpages, one for the strings of data
# on each area, and one for the image of active cyclones in that area. Each peice of data
# is set as a string in a given index of a list, and sent back to the main module.
def atlc():
page = requests.get("https://www.nhc.noaa.gov/?atlc")
soup = BeautifulSoup(page.content, 'html.parser')
imagePage = requests.get("https://www.nhc.noaa.gov/gtwo.php?basin=atlc&fdays=2")
imageSoup = BeautifulSoup(page.content, 'html.parser')
for text in soup.select('a[href="/cyclones/"]'):
title = text.get_text()
areaTitle = soup.select("th span")[0].get_text()
activeStorms = soup.find_all(class_='hdr')[0].get_text()
stormImage = imageSoup.find("img", {"id": "twofig0d"})
image = "https://www.nhc.noaa.gov" + stormImage["src"][:-7]
data = [title, areaTitle, "No Long/Lat Available", activeStorms, image]
return data
def epac():
page = requests.get("https://www.nhc.noaa.gov/?epac")
soup = BeautifulSoup(page.content, 'html.parser')
imagePage = requests.get("https://www.nhc.noaa.gov/gtwo.php?basin=epac&fdays=2")
imageSoup = BeautifulSoup(page.content, 'html.parser')
for text in soup.select('a[href="/cyclones/?epac"]'):
title = text.get_text()
areaTitle = soup.select("th span")[1].get_text()
areaLongLat = soup.select("th span")[2].get_text()
activeStorms = soup.find_all(class_='hdr')[1].get_text()
stormImage = imageSoup.find("img", {"id": "twofig0d"})
image = "https://www.nhc.noaa.gov" + stormImage["src"][:-7]
data = [title, areaTitle, areaLongLat, activeStorms, image]
return data
def cpac():
page = requests.get("https://www.nhc.noaa.gov/?cpac")
soup = BeautifulSoup(page.content, 'html.parser')
imagePage = requests.get("https://www.nhc.noaa.gov/gtwo.php?basin=cpac&fdays=2")
imageSoup = BeautifulSoup(page.content, 'html.parser')
for text in soup.select('a[href="/cyclones/?cpac"]'):
title = text.get_text()
areaTitle = soup.select("th span")[3].get_text()
areaLongLat = soup.select("th span")[4].get_text()
activeStorms = soup.find_all(class_='hdr')[2].get_text()
stormImage = imageSoup.find("img", {"id": "twofig0d"})
image = "https://www.nhc.noaa.gov" + stormImage["src"][:-7]
data = [title, areaTitle, areaLongLat, activeStorms, image]
return data |
e9f2da6612d02df9cda3ec6b0a05a0e70542ac73 | marri88/python-base | /FUNCTION_ERRORS/prob6.py | 377 | 3.65625 | 4 | # Возьмите код 1 с Classroom и создайте для него try... except...
# Создайте несколько except выражений для разных типов ошибок.
# at = 10
# iin = 15
# wo = 20
# try:
# for e in range(-at, at):
# print(wo / e)
# if at > '5':
# print("at > 5)
# except:SyntaxError
# print("mistake") |
baa7f53406695192a6ba14bc7abddba209b85136 | gyb1325/data_structure_algorithm | /Binary_Tree/Heap.py | 3,387 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 22:13:55 2018
@author: guyo
"""
#class HeapEmptyError(Exception):
# pass
#class Heap:
# def __init__(self, default_size = 10):
# self.a = [None]*default_size
# self.n = 0
# self.a[0] = 99999
# def insert(self,data):
# self.n = self.n + 1
# self.a[self.n] = data
# self.restore_up(self.n)
# def restore_up(self,x):
# k = self.a[x]
# parent = x // 2
# while self.a[parent] < k:
# self.a[x] = self.a[parent]
# x = parent
# parent = x //2
# self.a[x] = k
# def delete_root(self):
# if self.n == 0:
# raise HeapEmptyError("Heap is empty")
# maxValue = self.a[1]
# self.a[1] = self.a[self.n]
# self.n -= 1
# self.restore_down(1)
# return maxValue
# def restore_down(self, i):
# k = self.a[i]
# lchild = 2*i
# rchild = 2*i +1
# while rchild <= self.n:
# if k >= self.a[lchild] and k >=self.a[rchild]:
# self.a[i] = k
# return
# else:
# if self.a[lchild] > self.a[rchild]:
# self.a[i] = self.a[lchild]
# i = lchild
# else:
# self.a[i] = self.a[rchild]
# i = rchild
# lchild = i *2
# rchild = i*2 +1
# if lchild == self.n and k < self.a[lchild]:
# self.a[i] = self.a[lchild]
# i = lchild
# self.a[i] = k
# def display(self):
# if self.n == 0:
# print("Heap is empty")
# return
# print("Heap size is ", self.n)
# for i in range (1, self.n+1):
# print (self.a[i], " ", end = ' ')
# print()
#h = Heap()
#while True:
# choice = int(input("The choice is "))
# if choice ==1:
# value = int(input("Enter the value "))
# h.insert(value)
# elif choice == 2:
# print("Maximum value is ", h.delete_root())
# elif choice == 3:
# h.display()
# elif choice == 4:
# break
def build_heap_top_down(a, n):
for i in range (2,n+1):
restore_up(i,a)
def restore_up(i, a):
k = a[i]
parent = i // 2
while a[parent] < k:
a[i] = a[parent]
i = parent
parent = i //2
a[i] = k
def build_heap_bottom_up(a,n):
i = n//2
while i >=1:
restore_down(i, a, n)
i -= 1
def restore_down(i, a, n):
k = a[i]
lchild = 2* i
rchild = 2*i +1
while rchild <= n:
if a[rchild] <= k and a[lchild] <= k:
a[i] = k
return
else:
if a[lchild] > a[rchild]:
a[i] = a[lchild]
i = lchild
else:
a[i] = a[rchild]
i = rchild
lchild = 2* i
rchild = 2*i +1
if lchild == n and a[lchild]>k:
a[i] = a[lchild]
i = lchild
a[i] = k
a1 = [999999, 20 ,33,15,6,40,60,45,16,75,10,80,12]
n1 = len(a1)-1
build_heap_bottom_up(a1,n1)
for i in range (1, n1+1):
print (a1[i], " ", end = ' ')
print()
a2 = [999999, 20 ,33,15,6,40,60,45,16,75,10,80,12]
n2 = len(a2)-1
build_heap_top_down(a2,n2)
for i in range (1, n2+1):
print (a2[i], " ", end = ' ')
print() |
303aeae8b0ef10799d151c7fba1ab576234aa92b | Charles-8/ProjectStartup_Python | /Python_Part_1/ex17_sum_numbers.py | 194 | 4.09375 | 4 | number = int(input("Digite um numero inteiro"))
number1 = 1
number2 = 0
sum = 0
while number1 != 0:
number1 = number % 10
number = number // 10
sum = sum + number1
print(sum)
|
3c2e583af425c4772c5903fce344e4619cdf75e7 | mathankrish/Infy-Programs | /InfyTq Basic Programming/Day5/Day5Ass39.py | 2,420 | 3.875 | 4 | # Hotel ordering system
# Global variables
menu = ('Veg Roll', 'Noodles', 'Fried Rice', 'Soup')
quantity_available = [2, 200, 3, 0]
customer_ordered_food = []
customer_ordered_Quantity = []
def place_order(*item_tuple):
for i in range(0, len(item_tuple), 2):
customer_ordered_food.append(item_tuple[i])
for j in range(1, len(item_tuple), 2):
customer_ordered_Quantity.append(item_tuple[j])
for stock in customer_ordered_food:
if stock in menu:
if stock == menu[0]:
quan_avail = check_quantity_available(menu.index(stock), customer_ordered_Quantity[customer_ordered_food.index(stock)])
if quan_avail == False:
print("{0} stock is over".format(stock))
exit()
print("{0} is available".format(stock))
if stock == menu[1]:
quan_avail = check_quantity_available(menu.index(stock), customer_ordered_Quantity[customer_ordered_food.index(stock)])
if quan_avail == False:
print("{0} stock is over".format(stock))
exit()
print("{0} is available".format(stock))
if stock == menu[2]:
quan_avail = check_quantity_available(menu.index(stock), customer_ordered_Quantity[customer_ordered_food.index(stock)])
if quan_avail == False:
print("{0} stock is over".format(stock))
exit()
print("{0} is available".format(stock))
if stock == menu[3]:
quan_avail = check_quantity_available(menu.index(stock), customer_ordered_Quantity[customer_ordered_food.index(stock)])
if quan_avail == False:
print("{0} stock is over".format(stock))
exit()
print("{0} is available".format(stock))
else:
print("{0} is not available".format(stock))
def check_quantity_available(index, quantity_requested):
if quantity_requested <= quantity_available[index]:
quantity_available[index] -= quantity_requested
return True
else:
return False
place_order("Veg Roll", 2, "Noodles", 2)
#place_order("Soup", 1, "Veg Roll", 2, "Fried Rice", 1)
#place_order("Fried Rice", 2, "Soup", 1) |
8f46e0b32035876fa00dadfc9a1d24bd4dd523b3 | luisSantamariaCOL/PythonCompetitiveProgramming | /LeetCode/Problems/two_sum.py | 186 | 3.59375 | 4 | def twoSum(nums, target):
for i in nums:
print(i)
return nums
def main():
num_list = [2,7,11,15]
print(twoSum(num_list, 9))
if __name__ == "__main__":
main() |
3050e42550cd924f98a7983ff55bfc2d6e5d2b57 | warren511/210CT-coursework---Warren-Elliott | /Week 3 Question 1.py | 1,696 | 4.03125 | 4 | """
REVERSED_SENTENCE()
sentence<-input sentence
newList<-[]
newWord<-empty string
for charater in sentence
IF charater not space
append iteration to newWord
ELSE:
append newWord to newList
create new empty string
ENDIF
IF sentence not space:
append newWord to newList
ENDIF
outputList=[]
outputList=reverse newList
output<-"".separate outputList
OUTPUT (output)
"""
def reversed_sentence():
sentence=str(input("enter a sentence"))
newList=[]
newWord=" "
for character in sentence:
if character != " ":
newWord+=character
else:
newList.append(newWord)
newWord=" "
if sentence != " ":
newList.append(newWord)
outputList=[]
outputList=newList[::-1]
output="".join(outputList)
print (output)
"""
Line 22: this is the input that will be reversed;
Lines 23: creating an empty list where the list will be sliced
Line 24: group each word into a string within newList
Line 25: this iteration goes through every character in the string
Line 26: if the charater in the string is not a space,
each character that has been iterated will go to newWord;
Line 28: otherwise, once there is a space, store the word to the
list and recreate the variable to keep adding characters
Line 30: recreating this conditional for the last
word as there are no futher spaces after the last word;
Line 34: this line reverses the list and stores into a new list called output list
Line 25: the variables in this array are then split into strings stored
under the string variable "output"
"""
|
c05e291a486abe3b74acddb62f066e89127abec4 | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/04. Listas/01. informe 5 numeros.py | 273 | 3.859375 | 4 | #coding: utf-8
"""
Faça um Programa que leia um vetor de 5 números inteiros e mostre-os.
"""
ni = []
x = 1
while x <= 5:
n = int(input("Informe o " + str(x) + "º número: "))
ni.append(n)
x += 1
print()
for i in range(len(ni)):
print(str(ni[i]), " ", end="")
input() |
27ea7946fa4583b90c831b0c120d4d790b99787e | jonolimagnus/forritun_3 | /pygame_files/01_PyGame/03_pygame.py | 951 | 4.15625 | 4 | import pygame
pygame.init()
# Create some color constants for later use. The colors are created by RGB mixture.
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 150, 0)
BLUE = (0, 0, 255)
window_size = 640, 480
window = pygame.display.set_mode(window_size)
window.fill(GREEN) # This command sets the background color.
pygame.display.set_caption('Intro to Game Programming')
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
# since we are now setting the background color instead of using the default
# black one we need to update the display to make our color(GREEN) visible to the player.
# Try to comment out this line and run the program if you don't believe you need it :-)
pygame.display.update()
pygame.quit()
|
dfd4a053a0f6d20587ecd44fdfd6d47f9c08a385 | ornichola/learning-new | /pythontutor-ru/07_lists/09_swap_neighbours.py | 463 | 3.703125 | 4 | """
http://pythontutor.ru/lessons/lists/problems/swap_neighbours/
Переставьте соседние элементы списка (A[0] c A[1], A[2] c A[3] и т. д.).
Если элементов нечетное число, то последний элемент остается на своем месте.
"""
lst = input().split()
for i in range(0, len(lst) - 1, 2):
lst[i], lst[i + 1] = lst[i + 1], lst[i]
for el in lst:
print(el, end=' ')
|
0d0b855ef793f37f64aed4902c8d68f1f1d8dc69 | IvanAlexandrov/HackBulgaria-Tasks | /week_0/1-Python-simple-problem-set/zero_insert.py | 820 | 3.640625 | 4 | from list_to_number import list_to_number
def zero_insert(n):
n = str(n)
result = []
if len(n) == 1:
return int(n)
else:
for digit1, digit2 in zip(range(0, len(n)-1, 2), range(1, len(n), 2)):
if n[digit1] == n[digit1-1]:
result.append(0)
if n[digit1] == n[digit2] or (int(n[digit1]) + int(n[digit2])) % 10 == 0:
result.append(int(n[digit1]))
result.append(0)
result.append(int(n[digit2]))
else:
result.append(int(n[digit1]))
result.append(int(n[digit2]))
return list_to_number(result)
def main():
test = [116457, 555555555, 1, 6446]
for number in test:
print(zero_insert(number))
if __name__ == "__main__":
main()
505050505050505 |
dd15f92c8694d013e38e0c2326148e086efd50a1 | abhishekdwivedi3060/Python | /Practice/check_member.py | 381 | 4.15625 | 4 | def is_member(key,list1):
for x in list1:
if x == key:
return True
return False
list1 = list()
if __name__ == "__main__":
count = int(input("Enter the number of elements"))
while count > 0:
list1.append(input())
count -=1
key = input("Enter the key to search")
print(is_member(key, list1))
|
97596d027a9e8ef37b905e437e5cf06e3062c208 | DaospinaDLAB/coffee_machine | /Problems/Preprocessing/task.py | 190 | 3.609375 | 4 | sentence = input()
sentence = sentence.replace("!", "")
sentence = sentence.replace(",", "")
sentence = sentence.replace(".", "")
sentence = sentence.replace("?", "")
print(sentence.lower()) |
6a6c97881b26e11f0daae86d7ca6e03035c2fff9 | Hoang06691/bai-thuc-hanh-2 | /cau2.py | 252 | 4.03125 | 4 | import math;
x1=int(input("enter x1--->"))
y1=int(input("enter x2--->"))
x2=int(input("enter x2--->"))
y2=int(input("enter x1--->"))
d1= (x2-x1)*(x2-x1);
d2= (y2-y1)*(y2-y1);
res=math.sqrt(d1+d2)
print("distance betweem two points:",res);
|
8fb6b5eaf7e6c1dd50993999c27306a4cd221a77 | mliang810/itp115 | /ITP115_Project_Liang_Michelle/Diner.py | 1,065 | 4 | 4 | # Michelle Liang, liangmic@usc.edu
# ITP 115, Spring 2020
# Final Project
class Diner(object):
STATUSES = ["seated", "ordering", "eating", "paying", "leaving"]
def __init__(self, name):
self.name = name
self.order = []
self.status = 0
def getName(self):
return self.name
def getOrder(self):
return self.order
def getStatus(self):
return Diner.STATUSES[self.status]
def updateStatus(self):
if self.status <= 3:
self.status = self.status + 1
def addToOrder(self, menuItem):
self.order.append(menuItem)
def printOrder(self):
print(self.name, "ordered:")
for menuItem in self.order:
print("-", menuItem)
def calculateMealCost(self):
count = 0
for menuItem in self.order: # adds up all the costs of each individual menu item
count+=float(menuItem.price)
return count
def __str__(self):
result = "Diner " + self.name + " is currently " + Diner.STATUSES[self.status]
return result
|
f15c81f08bee51ceb8ff56461eb6f4bb2ae01a7b | phongle091/algorithm | /SelectionSort.py | 484 | 3.65625 | 4 | import numpy as np
import time
def SelectionSort(a, n):
for i in range(n-1):
value = a[i]
index = i
for j in range (i+1, n):
if (a[index] > a[j]):
index = j
if (i != index):
(a[i], a[index]) = (a[index], a[i])
return a
n = 50000
a = np.random.randint(500000,size=n)
start_time = time.time()
a = SelectionSort(a,n)
print(a)
print("--- sorting cost %s seconds ---" % (time.time() - start_time)) |
039792c90aaf118f08997cac5cac80fdd0bfef0f | yukgu/Machine-Learning-Univ-Washington | /Course-2-Regression/week-1-simple-regression-assignment-blank.py | 10,926 | 3.765625 | 4 |
# coding: utf-8
# # Regression Week 1: Simple Linear Regression
# In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:
# * Use graphlab SArray and SFrame functions to compute important summary statistics
# * Write a function to compute the Simple Linear Regression weights using the closed form solution
# * Write a function to make predictions of the output given the input feature
# * Turn the regression around to predict the input given the output
# * Compare two different models for predicting house prices
#
# In this notebook you will be provided with some already complete code as well as some code that you should complete yourself in order to answer quiz questions. The code we provide to complte is optional and is there to assist you with solving the problems but feel free to ignore the helper code and write your own.
# # Fire up graphlab create
# In[23]:
import graphlab
# # Load house sales data
#
# Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
# In[29]:
sales = graphlab.SFrame('kc_house_data.gl/')
graphlab.canvas.set_target('ipynb')
sales.show()
# # Split data into training and testing
# We use seed=0 so that everyone running this notebook gets the same results. In practice, you may set a random seed (or let GraphLab Create pick a random seed for you).
# In[30]:
train_data,test_data = sales.random_split(.8,seed=0)
# # Useful SFrame summary functions
# In order to make use of the closed form solution as well as take advantage of graphlab's built in functions we will review some important ones. In particular:
# * Computing the sum of an SArray
# * Computing the arithmetic average (mean) of an SArray
# * multiplying SArrays by constants
# * multiplying SArrays by other SArrays
# In[31]:
# Let's compute the mean of the House Prices in King County in 2 different ways.
prices = sales['price'] # extract the price column of the sales SFrame -- this is now an SArray
# recall that the arithmetic average (the mean) is the sum of the prices divided by the total number of houses:
sum_prices = prices.sum()
print "The sum of the house pricess is " + str(sum_prices)
num_houses = prices.size() # when prices is an SArray .size() returns its length
print "The number of houses is " + str(num_houses)
avg_price_1 = sum_prices/num_houses
avg_price_2 = prices.mean() # if you just want the average, the .mean() function
print "average price via method 1: " + str(avg_price_1)
print "average price via method 2: " + str(avg_price_2)
# As we see we get the same answer both ways
# In[32]:
# if we want to multiply every price by 0.5 it's a simple as:
half_prices = 0.5*prices
# Let's compute the sum of squares of price. We can multiply two SArrays of the same length elementwise also with *
prices_squared = prices*prices
sum_prices_squared = prices_squared.sum() # price_squared is an SArray of the squares and we want to add them up.
print "the sum of price squared is: " + str(sum_prices_squared)
# Aside: The python notation x.xxe+yy means x.xx \* 10^(yy). e.g 100 = 10^2 = 1*10^2 = 1e2
# # Build a generic simple linear regression function
# Armed with these SArray functions we can use the closed form solution found from lecture to compute the slope and intercept for a simple linear regression on observations stored as SArrays: input_feature, output.
#
# Complete the following function (or write your own) to compute the simple linear regression slope and intercept:
# In[38]:
def simple_linear_regression(input_feature, output):
N = input_feature.size()
# print str(N)
# compute the sum of input_feature and output
x_sum = input_feature.sum()
y_sum = output.sum()
# compute the product of the output and the input_feature and its sum
xy = input_feature*output
xy_sum = xy.sum()
# compute the squared value of the input_feature and its sum
x_sq = input_feature*input_feature
x_sq_sum = x_sq.sum()
# use the formula for the slope
slope = (xy_sum - (x_sum*y_sum)/N)/(x_sq_sum - (x_sum*x_sum)/N)
# use the formula for the intercept
intercept = (y_sum - slope*x_sum)/N
return (intercept, slope)
# We can test that our function works by passing it something where we know the answer. In particular we can generate a feature and then put the output exactly on a line: output = 1 + 1\*input_feature then we know both our slope and intercept should be 1
# In[39]:
test_feature = graphlab.SArray(range(5))
test_output = graphlab.SArray(1 + 1*test_feature)
(test_intercept, test_slope) = simple_linear_regression(test_feature, test_output)
print "Intercept: " + str(test_intercept)
print "Slope: " + str(test_slope)
# Now that we know it works let's build a regression model for predicting price based on sqft_living. Rembember that we train on train_data!
# In[40]:
sqft_intercept, sqft_slope = simple_linear_regression(train_data['sqft_living'], train_data['price'])
print "Intercept: " + str(sqft_intercept)
print "Slope: " + str(sqft_slope)
# # Predicting Values
# Now that we have the model parameters: intercept & slope we can make predictions. Using SArrays it's easy to multiply an SArray by a constant and add a constant value. Complete the following function to return the predicted output given the input_feature, slope and intercept:
# In[41]:
def get_regression_predictions(input_feature, intercept, slope):
# calculate the predicted values:
predicted_values = intercept + slope*input_feature
return predicted_values
# Now that we can calculate a prediction given the slope and intercept let's make a prediction. Use (or alter) the following to find out the estimated price for a house with 2650 squarefeet according to the squarefeet model we estiamted above.
#
# **Quiz Question: Using your Slope and Intercept from (4), What is the predicted price for a house with 2650 sqft?**
# In[42]:
my_house_sqft = 2650
estimated_price = get_regression_predictions(my_house_sqft, sqft_intercept, sqft_slope)
print "The estimated price for a house with %d squarefeet is $%.2f" % (my_house_sqft, estimated_price)
# # Residual Sum of Squares
# Now that we have a model and can make predictions let's evaluate our model using Residual Sum of Squares (RSS). Recall that RSS is the sum of the squares of the residuals and the residuals is just a fancy word for the difference between the predicted output and the true output.
#
# Complete the following (or write your own) function to compute the RSS of a simple linear regression model given the input_feature, output, intercept and slope:
# In[45]:
def get_residual_sum_of_squares(input_feature, output, intercept, slope):
# First get the predictions
predictions = get_regression_predictions(input_feature, intercept, slope)
# then compute the residuals (since we are squaring it doesn't matter which order you subtract)
residuals = predictions - output
# square the residuals and add them up
resid_sq = residuals*residuals
RSS = resid_sq.sum()
return(RSS)
# Let's test our get_residual_sum_of_squares function by applying it to the test model where the data lie exactly on a line. Since they lie exactly on a line the residual sum of squares should be zero!
# In[46]:
print get_residual_sum_of_squares(test_feature, test_output, test_intercept, test_slope) # should be 0.0
# Now use your function to calculate the RSS on training data from the squarefeet model calculated above.
#
# **Quiz Question: According to this function and the slope and intercept from the squarefeet model What is the RSS for the simple linear regression using squarefeet to predict prices on TRAINING data?**
# In[47]:
rss_prices_on_sqft = get_residual_sum_of_squares(train_data['sqft_living'], train_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on Square Feet is : ' + str(rss_prices_on_sqft)
# # Predict the squarefeet given price
# What if we want to predict the squarefoot given the price? Since we have an equation y = a + b\*x we can solve the function for x. So that if we have the intercept (a) and the slope (b) and the price (y) we can solve for the estimated squarefeet (x).
#
# Comlplete the following function to compute the inverse regression estimate, i.e. predict the input_feature given the output!
# In[48]:
def inverse_regression_predictions(output, intercept, slope):
# solve output = intercept + slope*input_feature for input_feature. Use this equation to compute the inverse predictions:
estimated_feature = (output - intercept)/slope
return estimated_feature
# Now that we have a function to compute the squarefeet given the price from our simple regression model let's see how big we might expect a house that costs $800,000 to be.
#
# **Quiz Question: According to this function and the regression slope and intercept from (3) what is the estimated square-feet for a house costing $800,000?**
# In[49]:
my_house_price = 800000
estimated_squarefeet = inverse_regression_predictions(my_house_price, sqft_intercept, sqft_slope)
print "The estimated squarefeet for a house worth $%.2f is %d" % (my_house_price, estimated_squarefeet)
# # New Model: estimate prices from bedrooms
# We have made one model for predicting house prices using squarefeet, but there are many other features in the sales SFrame.
# Use your simple linear regression function to estimate the regression parameters from predicting Prices based on number of bedrooms. Use the training data!
# In[50]:
# Estimate the slope and intercept for predicting 'price' based on 'bedrooms'
bed_intercept, bed_slope = simple_linear_regression(train_data['bedrooms'], train_data['price'])
print "Intercept: " + str(bed_intercept)
print "Slope: " + str(bed_slope)
# # Test your Linear Regression Algorithm
# Now we have two models for predicting the price of a house. How do we know which one is better? Calculate the RSS on the TEST data (remember this data wasn't involved in learning the model). Compute the RSS from predicting prices using bedrooms and from predicting prices using squarefeet.
#
# **Quiz Question: Which model (square feet or bedrooms) has lowest RSS on TEST data? Think about why this might be the case.**
# In[53]:
# Compute RSS when using bedrooms on TEST data:
rss_prices_on_bedrooms = get_residual_sum_of_squares(test_data['bedrooms'], test_data['price'], bed_intercept, bed_slope)
print 'The RSS of predicting Prices based on Square Feet is : ' + str(rss_prices_on_bedrooms)
# In[52]:
# Compute RSS when using squarefeet on TEST data:
rss_prices_on_sqft_test = get_residual_sum_of_squares(test_data['sqft_living'], test_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on Square Feet is : ' + str(rss_prices_on_sqft_test)
# In[ ]:
|
f0502a7e00aa92ed329755e8948205a19c120023 | dxmahata/codinginterviews | /dynamicprogramming/edit_distance.py | 1,742 | 4 | 4 | """
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
URL: https://leetcode.com/problems/edit-distance/
"""
class Solution(object):
def __init__(self):
self.dist_table = []
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if (word1 == None or word1 == "") and (word2 == None or word2 == ""):
return 0
elif word1 == "":
return len(word2)
elif word2 == "":
return len(word1)
else:
m = len(word1)
n = len(word2)
self.dist_table = [[0 for j in range(n+1)] for i in range(m+1)]
no_rows = m + 1
no_cols = n + 1
for i in range(0, no_rows):
for j in range(0, no_cols):
if i == 0:
self.dist_table[i][j] = j
elif j == 0:
self.dist_table[i][j] = i
elif word1[i-1] == word2[j-1]:
self.dist_table[i][j] = self.dist_table[i-1][j-1]
else:
self.dist_table[i][j] = 1 + min(self.dist_table[i][j-1], self.dist_table[i-1][j], self.dist_table[i-1][j-1])
return self.dist_table[no_rows-1][no_cols-1]
if __name__ == "__main__":
soln = Solution()
print(soln.minDistance("intention", "execution")) |
69b36703217f39186733519c6fb100cdf6e22069 | matheus-bernardino/cn-uece-2 | /sassenfeld.py | 2,188 | 3.625 | 4 | from decimal import Decimal, Context, setcontext, DivisionByZero, Underflow, Overflow
setcontext(Context(traps=[DivisionByZero, Underflow, Overflow]))
def check_convergence(A):
"""Verifica convergêcia da matriz A
Arguments:
A {list(list)} -- Matriz
Returns:
Boolean -- True se o método converge, False senão
"""
# Número de linhas do vetor A
n = len(A)
# Inicializa A_modified e B
A_modified = list(map(list, A))
B = [Decimal(0.0) for _ in range(n)]
# Coloca em B os valores beta calculados para o teste de convergência
for row in range(n):
for column in range(n):
if row != column:
B[row] += abs(A_modified[row][column])
if A_modified[row][row] != 0:
B[row] /= abs(A_modified[row][row])
for rows in range(row + 1, n):
A_modified[rows][row] *= B[row]
return max(B) < 1
def sassenfeld(A, _b):
"""Modifica a matriz de entrada para uma possível convergência do método
Arguments:
A {list(list)} -- Matriz
Returns:
list(list), None -- Retorna a matriz moficada se foi possível fazer a convergêcia, senão retorna None
"""
# Número de linhas do vetor A
n = len(A)
# Testa se a matriz original A já converge
if check_convergence(A):
return A, _b
# Faz o teste de convergência trocando as linhas
for a in range(n - 1):
for b in range(a + 1, n):
A[a], A[b] = A[b], A[a]
_b[a], _b[b] = _b[b], _b[a]
if check_convergence(A):
return A, _b
# Para cada linha trocada, troca todas as colunas e então aplica o teste de convergência
for c in range(n - 1):
for d in range(c + 1, n):
for line in A:
line[c], line[d] = line[d], line[c]
if check_convergence(A):
return A, _b
for line in A:
line[c], line[d] = line[d], line[c]
A[a], A[b] = A[b], A[a]
_b[a], _b[b] = _b[b], _b[a]
return None, None
|
3124a53863fdc613b097bc032374302ea9d4ff52 | zeruns/Python-programming-exercises | /基础/判断闰年.py | 397 | 3.875 | 4 | '''
用函数实现一个判断用户输入的年份是否是闰年的程序
1.能被400整除的年份
2.能被4整除,但是不能被100整除的年份
以上2种方法满足一种即为闰年
'''
def leapyear(year):
if year%400==0 or (year%4==0 and year%100!=0):
print("%d是闰年"%year)
else:
print("%d不是闰年"%year)
leapyear(int(input("请输入年份:"))) |
60a86fd1a12fa392f559c257086175722205dd90 | fpeterek/car-map-downloader | /downloader/map/geo_position.py | 415 | 3.609375 | 4 |
class GeoPosition:
def __init__(self, lat: float, lon: float):
self.lat = lat
self.lon = lon
def __hash__(self):
return hash((self.lat, self.lon))
def __eq__(self, other) -> bool:
if type(other) is not GeoPosition:
return False
return self.lat == other.lat and self.lon == other.lon
def __ne__(self, other):
return not (self == other)
|
a402873ca455036744eed8e5b3b2e26f390e10ab | hechenyu/book_code | /pythonnetprog/21/locks.py | 1,115 | 4 | 4 | #!/usr/bin/env python
# Threading with locks - Chapter 21 - locks.py
import threading, time
# Initialize a simple variable
b = 50
# And a lock object
l = threading.Lock()
def threadcode():
"""This is run in the created threads"""
global b
print "Thread %s invoked" % threading.currentThread().getName()
# Acquire the lock (will not return until a lock is acquired)
l.acquire()
try:
print "Thread %s running" % threading.currentThread().getName()
time.sleep(1)
b = b + 50
print "Thread %s set b to %d" % (threading.currentThread().getName(),
b)
finally:
l.release()
print "Value of b at start of program:", b
childthreads = []
for i in range(1, 5):
# Create new thread.
t = threading.Thread(target = threadcode, name = "Thread-%d" % i)
# This thread won't keep the program from terminating.
t.setDaemon(1)
# Start the new thread.
t.start()
childthreads.append(t)
for t in childthreads:
# Wait for the child thread to exit.
t.join()
print "New value of b:", b
|
ceaace2ae9f12439b2fb1a32bc938748a0bfaea9 | alinedsoares/Python1USP | /ordenacao.py | 269 | 4.03125 | 4 | N1 = (int(input("Digite o primeiro número inteiro:")))
N2 = (int(input("Digite o segundo número inteiro:")))
N3 = (int(input("Digite o terceiro número inteiro:")))
if N1 < N2 and N2 < N3:
print ("crescente")
else :print ("não está em ordem crescente")
|
e749f57bbe794d3a4e658115f50abb5419410565 | carlos-sales/exercicios-python | /ex105.py | 781 | 3.671875 | 4 | def boletim(*notas, situacao=False):
"""
-> Análise de notas e situação do aluno
:param notas: uma ou várias notas de um aluno
:param situacao: opcional, mostra se a situação do aluno ésta BOA, RAZOÁVEL ou RUIM
:return: retorna um dicionário com informações sobre a situação do aluno
"""
apv = dict()
apv['total'] = len(notas)
apv['Maior'] = max(notas)
apv['Menor'] = min(notas)
apv['Media'] = sum(notas) / len(notas)
if situacao:
if apv['Media'] < 5:
apv['Situacao'] = 'Ruim'
elif apv['Media'] < 8:
apv['Situacao'] = 'Razoável'
else:
apv['Situacao'] = 'Boa'
return apv
resp = boletim(6.5, 9, 9, 9, 10, 10, 6.5, situacao=True)
print(resp)
help(boletim)
|
2b70ae10182c9b38893be56365bca56df361fb92 | raj-andy1/mypythoncode | /sampefunction2.py | 303 | 3.765625 | 4 | """
sampleFunction2 py file
"""
def addTwo(startingValue):
endingValue = startingValue + 2
print ("The sum of", startingValue, "and 2 is:",endingValue)
addTwo(4)
addTwo(223)
addTwo(-25)
addTwo(55.37)
userNumber = input("Enter a number:")
#userNumber = int(userNumber)
addTwo(int(userNumber))
|
2bd6e7adadfe29316f9f588a309d3e5b2e1361de | dudwns9331/PythonStudy | /BaekJoon/Silver3/2992.py | 541 | 3.546875 | 4 | # 크면서 작은 수
"""
2021-05-29 오후 11:55
안영준
문제 : https://www.acmicpc.net/problem/2992
"""
import itertools
import sys
input = lambda: sys.stdin.readline().rstrip()
N = input()
result_list = set(itertools.permutations(N, len(N)))
result_list = list(result_list)
result_list.sort()
# print(result_list)
result = list()
for i in result_list:
result.append(int(''.join(map(str, i))))
# print(result)
if result.index(int(N)) + 1 == len(result):
print(0)
else:
print(result[result.index(int(N)) + 1])
|
7145ec464e4e11440e4f7afd6fa7c305b21f2f94 | beingnitisho7/Python_assignment | /Assignment/Assignment_1.py | 1,303 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
# Write a program that will convert Fahrenheit to Celsius in degrees.
def celsius(num):
fahrenheit = (num * 9/5) + 32
print('%.3f Celsius is: %0.2f Fahrenheit' %(num, fahrenheit))
celsius(23)
# In[10]:
# Write a program that takes seconds as time units and converts it to minutes and seconds.
def time(time_units):
minutes = time_units // 60
time_units %= 60
seconds = time_units
print("Converted time-> %d minute and %dsecond" % (minutes, seconds))
time(3800)
# In[11]:
# Consider a list of any arbitrary elements. Your codeshould print the length of the list and first and fourth element of the list.
Elements=['apple','mango','pine apple','Banana']
def element(elements):
print(len(Elements))
print(Elements[0])
print(Elements[3])
Elements=['apple','mango','pine apple','Banana']
element(Elements)
# In[12]:
# Create a list of any arbitrary elements. Your code should show the list methods as pop, insert and remove.
Elements=['apple','mango','pine apple','Banana']
def element_pop(elements):
Elements.pop(0)
print(Elements)
Elements.insert(1,'lichy')
print(Elements)
Elements.remove('mango')
print(Elements)
element_pop(Elements)
# In[ ]:
|
9f5aab8500f88924623cea1f707bd46660924415 | irichrei/Python | /Calculadora/Calculadora.py | 1,161 | 4.1875 | 4 | def operacoes():
n1 = float(input('Digite primeiro número: ')) # Recebe primeiro número.
s = str(input('Digite um dos sinais + - x / : ')) # Recebe Sinal.
n2 = float(input('Digite segundo número: ')) # Recebe segundo número.
if s == '+': # Efetua operação de soma.
print('Resultado : ', n1 + n2)
elif s == '/': # Efetua operação de divisão.
print('Resultado : ', n1 / n2)
elif s == '-': # Efetua operação de subtração.
print('Resultado : ', n1 - n2)
elif s == 'x': # Efetua operação de multiplicação.
print('Resultado : ', n1 * n2)
else: # Erro no operador.
print('Operador digitado não foi identificado.')
repetidor() # Chama função para repetir ou encerrar aplicação.
def repetidor():
reiniciar = input('Deseja calcular novamente?' +
'Digite Y para sim e N para não: ') # Valida repetição.
if reiniciar.upper() == 'Y': # Repete aplicação.
operacoes()
elif reiniciar.upper() == 'N': # Finaliza aplicação.
print('Obrigado! Até breve =)')
else:
repetidor()
operacoes()
|
614d590dca3151f0fea2e1e4b63d7c42e74b2ae7 | zaiyr-sh/yandex-algorithm-training | /lectures/week_4/task_4.py | 3,026 | 3.84375 | 4 | # 3. Задел под оптимизацию.
# Задача
# Сгруппировать слова по общим буквам
# Sample Input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
# Sample Output: [['ate', 'eat', 'tea'], ['nat', 'tan'], ['bat']]
# Решение здорового человека
# Отсортируем в каждом слове буквы и это будет выступать в роли
# ключа, а значение будет список слов
def group_words(words):
groups = {}
for word in words:
sorted_word = ''.join(sorted(word))
if sorted_word not in groups:
groups[sorted_word] = []
groups[sorted_word].append(word)
ans = []
for sorted_word in groups:
ans.append(groups[sorted_word])
return ans
print(group_words(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']))
# ------------------------------------------------------------------
# Подозрения здорового человека
# sortedword = ''.join(sorted(word))
# Вдруг слово будет длинное (N)? Сортировка займет O(N logN).
# Количество различных букв в слове K <= N, можем посчитать количество
# каждой за O(N) и отсортировать за O(K logK), теоритически
# ------------------------------------------------------------------
# Задел здорового человека
# Будет тормозить - посмотрим на профилировщике где, и если долго
# считается ключ - легко поправим на что-то более эффективное
def group_words(words):
def key_by_word(word):
return ''.join(sorted(word))
groups = {}
for word in words:
sorted_word = key_by_word(word)
if sorted_word not in groups:
groups[sorted_word] = []
groups[sorted_word].append(word)
ans = []
for sorted_word in groups:
ans.append(groups[sorted_word])
return ans
print(group_words(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']))
# ------------------------------------------------------------------
# Оптимизация (?) здорового человека
def group_words(words):
def key_by_word(word):
syms = {}
for sym in word:
if sym not in syms:
syms[sym] = 0
syms[sym] += 1
lst = []
for sym in sorted(syms.keys()):
lst.append(sym)
lst.append(str(syms[sym]))
return ''.join(lst)
groups = {}
for word in words:
sorted_word = key_by_word(word)
if sorted_word not in groups:
groups[sorted_word] = []
groups[sorted_word].append(word)
ans = []
for sorted_word in groups:
ans.append(groups[sorted_word])
return ans
print(group_words(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])) |
26cfd45f6df007634bbfcc261424f667140b00f3 | david-uni/python-help | /lectures/lesson-2.py | 2,736 | 4.34375 | 4 | # 01/11/2020 Lesson 2
import math
# string formating
name = 'David'
pi = math.pi
formated_str = 'My name is {0} and I like {1}'.format(name, pi)
print(formated_str)
formated_str = 'My name is {0} and I like {1:.2f}'.format(
name, pi) # convert to float with 2 decimals values
print(formated_str)
# a shorter way to use string formatting
formated_str = f'My name is {name} and I like {pi:.2f}'
print(formated_str)
# lists
my_list = [0, '1', 2.0] # saves the order
my_list[0]
my_list[:] # the entire list from the beginning till the end
my_list[::2] # only odd indexes
# when using negative 'jumps' the indexes can be omitted, or reversed
my_list[len(my_list):0:-1]
my_list.append(3) # adds the value 3 to the end of the list
my_list.remove(2.0) # removes the first time the value 2.0 exist in the list
my_list.pop() # removes the the value at the end of the list (last index)
my_list.pop(1) # removes the the value at index=1 from the list
# 2 dimensions list
my_list = [[1, 2, 3],
[4, 5, 6]]
my_list[0][0] # the value at row 0 and column 0
# sorting
first_list = [5, 2, 3, 1, 0]
second_list = ['5', '2', '3', '1', '10']
first_list.sort() # sorts the list itself, from now on first_list is sorted
# returns a copy of the sorted list, second_list is still with the same order it was
sorted(second_list)
sorted(second_list, key=len) # sort the list by the given function
# split string
s = 'I am David'
s_list = s.split() # splits the string into a list by spaces
s_list = s.split(' ') # splits the string into a list by the given value
# loops
# for
my_sum = 0
for i in [3, 5, 7, 9, 10]:
my_sum += i # i is equals to the value at the current index
# range
list(range(10)) # creates a list of numbers from 0 up to 9
list(range(1, 11)) # creates a list of numbers from 1 up to 10
my_sum = 0
for i in range(10):
my_sum += i
# while - beware that if the expression never returns False the loop will never end
n = 7
fact = 1
i = 1
while i <= n:
fact = fact * i
i += 1
print(str(n) + '! =', fact)
print(sum(range(1, 101))) # the function sum() is built into python
def fibonacci(n):
my_fibonacci = [1, 1]
for i in range(n-2):
my_fibonacci.append(my_fibonacci[i] + my_fibonacci[i+1])
return my_fibonacci
# continue & break
def even_numbers(my_list):
evens = []
for i in my_list:
if i % 2 != 0:
continue
evens.append(i)
print(evens)
even_numbers([1, 2, 3, 4, 5, 6, 2, 4, 5])
def prime_number(number):
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
break
if number % i == 0:
print(number, 'is not prime')
else:
print(number, 'is prime')
prime_number(121)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.