blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
271f09d6dea8257845188ff3b7ee157e6016a4d6 | netgroup/ABEbox | /old/Encryptor.py | 15,472 | 3.53125 | 4 | """
This file contains all functions used during encryption process. To perform this procedure, firstly, an hybrid
encryption is applied to the plaintext. Then the resulting ciphertext needs to be transformed through an All-Or-Nothing
transformation.
"""
from old.crypto.Const import AONT_DEFAULT_ENCODING, AONT_DEFAULT_N, AONT_DEFAULT_K0, CHUNK_SIZE
def create_encrypted_file(plaintext_infile=None, ciphertext_outfile=None, pk_file=None, policy=None, n=AONT_DEFAULT_N,
k0=AONT_DEFAULT_K0, encoding=AONT_DEFAULT_ENCODING, chunk_size=CHUNK_SIZE, debug=0):
"""
Create the encrypted file starting from a plaintext input file and applying hybrid encryption and transformation.
:param plaintext_infile: file to encrypt
:param ciphertext_outfile: file where transformed ciphertext will be saved
:param pk_file: ABE public key file used for hybrid encryption
:param policy: ABE policy to apply to the ciphertext
:param n: transformation chunk length in bits
:param k0: transformation random length in bits
:param encoding: transformation encoding used
:param chunk_size: size of each plaintext chunk to encrypt and transform
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
"""
from old.crypto.SymEncPrimitives import sym_key_gen
from old.crypto.Const import SYM_KEY_DEFAULT_SIZE, VERSION
from binascii import hexlify
import logging
import os
# Check if plaintext_infile is set and it exists
if plaintext_infile is None or not os.path.exists(plaintext_infile):
logging.error('create_encrypted_file plaintext_infile exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in create_encrypted_file plaintext_infile')
raise Exception
# Check if pk_file is set and it exists
if pk_file is None or not os.path.exists(pk_file):
logging.error('create_encrypted_file pk_file exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in create_encrypted_file pk_file')
raise Exception
# Check if policy is set
if policy is None:
logging.error('create_encrypted_file policy exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in create_encrypted_file policy')
raise Exception
# Create the key for symmetric encryption of the plaintext
sym_key = sym_key_gen(sym_key_size=SYM_KEY_DEFAULT_SIZE, debug=debug)
if debug: # ONLY USE FOR DEBUG
print('[ENCRYPTOR] SYM KEY =', sym_key)
from old.crypto.SymEncPrimitives import generate_iv
from old.crypto.Const import IV_DEFAULT_SIZE
# Create the initialisation vector for symmetric encryption
iv = generate_iv(IV_DEFAULT_SIZE, debug)
if debug: # ONLY USE FOR DEBUG
print('[ENCRYPTOR]\tIV = (%d) %s -> %s' % (len(iv), iv, hexlify(iv).decode()))
# Encrypt symmetric key with ABE using given public key and policy
enc_key = encrypt_sym_key(sym_key, pk_file, policy, debug)
if debug: # ONLY USE FOR DEBUG
print('ENCRYPTED SYMMETRIC KEY =', enc_key)
# If output file is not defined, set a default one
if ciphertext_outfile is None:
ciphertext_outfile = 'enc_' + plaintext_infile
# Protection scheme version
version = VERSION
# Put together all header data to write
header = [version, n, k0, len(enc_key), enc_key, iv, os.path.getsize(plaintext_infile)]
# Write header on the output file
write_header_on_file(ciphertext_outfile, header, debug)
# Apply encryption, transform ciphertext and write result on the output file
apply_enc_aont(plaintext_infile, ciphertext_outfile, sym_key, iv, n, encoding, k0, chunk_size, debug)
def apply_enc_aont(plaintext_infile=None, ciphertext_outfile=None, key=None, iv=None, n=AONT_DEFAULT_N,
encoding=AONT_DEFAULT_ENCODING, k0=AONT_DEFAULT_K0, chunk_size=CHUNK_SIZE, debug=0):
"""
Apply hybrid encryption and All-Or-Nothing Transformation to the plaintext input file.
:param plaintext_infile: file with the plaintext to encrypt and transform
:param ciphertext_outfile: file where transformed ciphertext will be saved
:param key: symmetric encryption key
:param iv: symmetric encryption initialisation vector
:param n: transformation chunk length in bits
:param encoding: transformation encoding
:param k0: transformation random length in bits
:param chunk_size: size of each plaintext chunk to encrypt and transform
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
"""
import logging
import os
# Check if plaintext_infile is set and it exists
if plaintext_infile is None or not os.path.exists(plaintext_infile):
logging.error('apply_enc_aont plaintext_infile exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in apply_enc_aont plaintext_infile')
raise Exception
# Check if ciphertext_outfile is set and it exists
if ciphertext_outfile is None or not os.path.exists(ciphertext_outfile):
logging.error('apply_enc_aont ciphertext_outfile exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in apply_enc_aont ciphertext_outfile')
raise Exception
# Check if key is set
if key is None:
logging.error('apply_enc_aont key exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in apply_enc_aont key')
raise Exception
# Check if iv is set
if iv is None:
logging.error('apply_enc_aont IV exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in apply_enc_aont IV')
raise Exception
from old.crypto.SymEncPrimitives import sym_encrypt
from binascii import hexlify
# Read data chunk from the plaintext input file
with(open(plaintext_infile, 'rb')) as fin:
# Encrypt and transform chunks until all plaintext is encrypted and transformed
for plaintext_chunk in iter(lambda: fin.read(chunk_size), ''):
# Last read is empty, so processing will be skipped
if not len(plaintext_chunk):
return
if debug: # ONLY USE FOR DEBUG
print('[ENCRYPTOR] PLAINTEXT CHUNK = (%d) %s -> %s' % (len(plaintext_chunk), plaintext_chunk,
hexlify(plaintext_chunk)))
# Encrypt the plaintext chunk using AES GCM with the given key
ciphertext_chunk = sym_encrypt(key=key, iv=iv, plaintext=plaintext_chunk, debug=debug)
if debug: # ONLY USE FOR DEBUG
print('[ENCRYPTOR] CIPHERTEXT CHUNK = (%d) %s -> %s' % (len(ciphertext_chunk), ciphertext_chunk,
hexlify(ciphertext_chunk).decode()))
# Apply All-Or-Nothing Transformation to the ciphertext chunk
transf_ciphertext_chunk = apply_aont(ciphertext_chunk, n, encoding, k0, debug)
if debug: # ONLY USE FOR DEBUG
print('[ENCRYPTOR] TRANSFORMED CIPHERTEXT CHUNK = (%d) %s -> %s'
% (len(transf_ciphertext_chunk), transf_ciphertext_chunk, hexlify(transf_ciphertext_chunk)))
# Write transformed ciphertext chunk on output file
write_data_on_file(ciphertext_outfile, transf_ciphertext_chunk, debug)
def apply_aont(data=None, n=AONT_DEFAULT_N, encoding=AONT_DEFAULT_ENCODING, k0=AONT_DEFAULT_K0, debug=0):
"""
Apply All-Or-Nothing Transformation to the given data
:param data: data to transform
:param n: transformation chunk length in bits
:param encoding: transformation encoding
:param k0: transformation random length in bits
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
"""
import logging
# Check if data is set
if data is None:
logging.error('apply_aont data exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in apply_aont data')
raise Exception
if debug: # ONLY USE FOR DEBUG
print('DATA BYTES = (%d) %s' % (len(data), data))
# Initialise variables
transformed_data = ''
# Divide data in chunks to perform the transformation
step = (n - k0) // 8
for i in range(0, len(data), step):
# Compute next data chunk starting byte
next_i = i + step
# Check if last chunk is shorter than previous ones
if next_i > len(data):
next_i = len(data)
# Get a data chunk of fixed length
to_transform = data[i: next_i]
if debug: # ONLY USE FOR DEBUG
print('TO_TRANSFORM = (%d) %s' % (len(to_transform), to_transform))
from old.crypto.OAEPbis import init, pad
from binascii import hexlify
# Initialise transformation parameters
init(n=n, enc=encoding, k0=k0)
# Apply transformation to data chunk
transformed_data_chunk = pad(hexlify(to_transform).decode(), debug)
if debug: # ONLY USE FOR DEBUG
print('TRANSFORMED DATA CHUNK = (%d) %s' % (len(transformed_data_chunk), transformed_data_chunk))
# Append transformed data chunk to the final transformation result
transformed_data += transformed_data_chunk
if debug: # ONLY USE FOR DEBUG
print('TRANSFORMED DATA BITS = (%s) (%d) %s' % (type(transformed_data), len(transformed_data),
transformed_data))
from binascii import unhexlify
# Convert transformation result from hexadecimal to bytes and fill it with leading zeros
transformed_data_bytes = unhexlify(hex(int(transformed_data, 2))[2:].zfill(len(transformed_data) // 4))
if debug: # ONLY USE FOR DEBUG
print('TRANSFORMED DATA BYTES = (%d) %s' % (len(transformed_data_bytes), transformed_data_bytes))
return transformed_data_bytes
def encrypt_sym_key(key=None, pk_file=None, policy=None, debug=0):
"""
Encrypt the given symmetric key with an asymmetric encryption scheme (particularly, ABE).
:param key: symmetric key to encrypt
:param pk_file: ABE public key file
:param policy: ABE policy to apply to the encrypted key
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
:return: encrypted symmetric key
"""
import logging
import os
# Check if key is set
if key is None:
logging.error('encrypt_sym_key key exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in encrypt_sym_key key')
raise Exception
# Check if pk_file is set and it exists
if pk_file is None or not os.path.exists(pk_file):
logging.error('encrypt_sym_key pk_file exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in encrypt_sym_key pk_file')
raise Exception
# Check if policy is set
if policy is None:
logging.error('encrypt_sym_key policy exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in encrypt_sym_key policy')
raise Exception
from old.crypto.Const import TEMP_PATH
# Define temporary files for key encryption
temp_sym_key_file = 'sym_key'
temp_enc_sym_key_file = 'enc_' + temp_sym_key_file
# Write key on temporary file
# with(open(TEMP_PATH + temp_sym_key_file, 'wb')) as fout:
# with(open(TEMP_PATH + temp_sym_key_file, 'w')) as fout:
# fout.write(key)
from re_enc_engine.abe_primitives import encrypt
# Encrypt temporary key file with ABE
encrypt(enc_outfile=TEMP_PATH + temp_enc_sym_key_file, pk_file=pk_file,
plaintext_file=TEMP_PATH + temp_sym_key_file, plaintext=key, policy=policy, debug=debug)
# Read encrypted key from temporary outfile
with(open(TEMP_PATH + temp_enc_sym_key_file, 'r')) as fin:
enc_key = fin.read()
# Delete temporary files
os.remove(TEMP_PATH + temp_enc_sym_key_file)
return enc_key
def write_header_on_file(ciphertext_outfile=None, data=None, debug=0):
"""
Write the header parameters on the given output ciphertext file
:param ciphertext_outfile: file where header will be written
:param data: header params to write
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
"""
import logging
# Check if ciphertext_outfile is set
if ciphertext_outfile is None:
logging.error('write_header_on_file ciphertext_outfile exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in write_header_on_file ciphertext_outfile')
raise Exception
# Check if data is set
if data is None:
logging.error('write_header_on_file data exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in write_header_on_file data')
raise Exception
# Get values to write on file
version = data[0]
n = data[1]
k0 = data[2]
enc_key_length = data[3]
enc_key = data[4]
iv = data[5]
ciphertext_length = data[6]
re_enc_num = 0
if debug: # ONLY USE FOR DEBUG
print('VERSION = %d' % version)
print('N = %d' % n)
print('K0 = %d' % k0)
print('ENC SYM KEY = (%d) %s' % (enc_key_length, enc_key))
print('IV = (%d) %s' % (len(iv), iv))
print('CIPHERTEXT LENGTH = %d' % ciphertext_length)
print('RE-ENCRYPTIONS NUM = %d' % re_enc_num)
# Create string format for struct
struct_format = 'BHHH%ds%dsQH' % (enc_key_length, len(iv))
if debug: # ONLY USE FOR DEBUG
print('STRING FORMAT FOR STRUCT = ', struct_format)
import struct
# Create struct with all header parameters
data_to_write = struct.pack(struct_format, version, n, k0, enc_key_length, enc_key, iv, ciphertext_length,
re_enc_num)
if debug: # ONLY USE FOR DEBUG
print('DATA TO WRITE ON FILE = (%d) %s' % (len(data_to_write), data_to_write))
from old.FunctionUtils import write_bytes_on_file
# Write data bytes on given outfile
write_bytes_on_file(outfile=ciphertext_outfile, data=data_to_write, debug=debug)
def write_data_on_file(ciphertext_outfile=None, data=None, debug=0):
"""
Append given data on the given file
:param ciphertext_outfile: file where data will be written
:param data: data to write
:param debug: if 1, prints will be shown during execution; default 0, no prints are shown
"""
import logging
import os.path
# Check if ciphertext_outfile is set and it exists
if ciphertext_outfile is None or not os.path.exists(ciphertext_outfile):
logging.error('write_data_on_file ciphertext_outfile exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in write_data_on_file ciphertext_outfile')
raise Exception
# Check if data is set
if data is None:
logging.error('write_data_on_file data exception')
if debug: # ONLY USE FOR DEBUG
print('EXCEPTION in write_data_on_file data')
raise Exception
from old.FunctionUtils import write_bytes_on_file
# Append data to the end of the given outfile
write_bytes_on_file(ciphertext_outfile, data, 'ab', 0, debug)
|
8956e4d15be3616e2fe8040a1938a8ef0c97e71d | chrisliatas/py4e_code | /py4e_ex_02_03.py | 99 | 3.828125 | 4 | hours = input("Enter Hours: ")
rate = input("Enter Rate: ")
print("Pay:",float(hours)*float(rate))
|
853061867e2044fbbdee391959f65c38a2ba514b | xili-h/PG | /Python/ch1/dog_age.py | 191 | 4.03125 | 4 | dog_name = input("What is youe dog's name? ")
dog_age = int(input("Whai is your dog's age? "))
human_age = dog_age * 7
print('Your dog',dog_name,'is', human_age,'years old0 in human years ') |
03fbee68aaee0b13ec392c4d14e14529b7622f98 | mehedees/FindPair | /findPair.py | 1,158 | 3.546875 | 4 |
class PairFinder:
def __init__(self, inputArray, target):
self.inputArray = inputArray
self.target = target
self.items = self.inputArray[1:-1] # stripping square brackets from both end
self.items = self.items.split(', ') # getting a string list of the numbers
self.items = list(map(int, self.items)) # converting to a num string
self.resultList = []
def findPairs(self):
for x in self.items:
for y in self.items:
diff = x - y
if diff == target:
self.resultList.append([x, y])
if len(self.resultList) != 0:
self.resultString = '{0} -> '.format(len(self.resultList))
for it, pair in enumerate(self.resultList):
if it == len(self.resultList) - 1:
self.resultString += '{}'.format(pair)
else:
self.resultString += '{}, '.format(pair)
print(self.resultString)
else:
print('0')
inputArray = input()
target = int(input())
p = PairFinder(inputArray, target)
p.findPairs()
|
04ac14ba888c85291eeb34400ee54357a175d205 | gabriellaec/desoft-analise-exercicios | /backup/user_211/ch45_2020_04_10_23_16_20_290482.py | 109 | 3.890625 | 4 | x=0
lista=[]
i=0
while x>=0:
x=int(input("digita um número")
lista.append(x)
i+=1
print(l[::-1]) |
e7722ea887a9428086f1fd2c4b0eb1e7ec9a30b7 | Global19-atlassian-net/the_pool | /das_schwimmbad.py | 1,686 | 3.765625 | 4 | #das schwimmbad
class Liegewiese(object):
loc_index = 0
def enter(self):
if first_visit:
print "Du befindest die auf der Liegewiese des Schwimmbads."
else:
print "Du warst schon eimal hier."
class GertrudesBaum(object):
loc_index = 1
loc_name = 'Gertrude\'s Baum'
def enter(self):
if first_visit:
print "Du bist an Gertrudes Baum."
else:
print "Du warst schon eimal hier."
gertudesbaum = GertrudesBaum()
class Beckenrand(object):
loc_index = 2
loc_name = 'Beckenrand'
def enter(self):
if first_visit:
print "Du bist Beckenrand."
else:
print "Du warst schon eimal hier."
beckenrand = Beckenrand()
class Sprungturm(object):
loc_index = 3
loc_name = 'Sprungturm'
def enter(self):
if first_visit:
print "Du bist am Sprungturm."
else:
print "Du warst schon eimal hier."
sprungturm = Sprungturm()
class Schwimmbecken(object):
loc_index = 4
loc_name = 'Schwimmbecken'
def enter(self):
if first_visit:
print "Du bist im Schwimmbecken."
else:
print "Du warst schon eimal hier."
schwimmbecken = Schwimmbecken()
class Imbiss(object):
loc_index = 5
def enter(self):
if first_visit:
print "Du bist am Imbiss."
else:
print "Du warst schon eimal hier."
imbiss = Imbiss()
class Kassenhaus(object):
loc_index = 6
def enter(self):
if first_visit:
print "Du bist am Kassenhaus."
else:
print "Du warst schon eimal hier."
kassenhaus = Kassenhaus()
|
5cd014e5006782074cfcbda6f9cb22be3d3b2d2b | charliealpha094/Python_Crash_Course_2nd_edition | /Chapter_9/try_9.3.py | 1,538 | 4.25 | 4 | #Done by Carlos Amaral in 04/07/2020
"""
Make a class called User . Create two attributes called first_name
and last_name , and then create several other attributes that are typically stored
in a user profile. Make a method called describe_user() that prints a summary
of the user’s information. Make another method called greet_user() that prints
a personalized greeting to the user.
Create several instances representing different users, and call both methods
for each user.
"""
#Users
class User:
"""A class that represents a User."""
def __init__(self, first_name, last_name, username, email, phone_no):
"""Initialize first name and last name attributes."""
self.first_name = first_name
self.last_name = last_name
self.username = username
self.email = email
self.phone_no = phone_no
def describe_user(self):
"""Prints a summary of the user's information."""
print(f"{self.first_name} {self.last_name}"
f"\nUsername: {self.username}"
f"\nEmail: {self.email}"
f"\nPhone number: {self.phone_no}")
def greet_user(self):
"""Prints a greeting to the user."""
msg = f"\nWelcome {self.username}!"
print(msg)
charlie = User('Carlos', 'Amaral', 'charliealpha094',
'[email protected]', 916165804)
Tereza = User('Tereza', 'Srbova', 'TerezaS',
'[email protected]', 917389765)
charlie.describe_user()
charlie.greet_user()
print("\n")
Tereza.describe_user()
Tereza.greet_user()
|
df27d1122dab3d34ae15986b0c4d176feb5ae196 | acrual/repotron | /Unidad3_10/src/actividadUF3_10/tresenraya/Partida.py | 3,009 | 3.671875 | 4 | from Tablero import Tablero
from random import randint
class Partida(object):
def __init__(self):
self.tablero = Tablero()
num = randint(1,2)
if num == 1:
self.turno = "jugador"
else:
self.turno = "cpu"
def jugar(self):
hayGanador = False
while self.tablero.hayCasillaLibre() and not hayGanador:
#Mostramos estado actual del tablero
print(self.tablero)
#determinamos si está jugando jugador o cpu
if self.turno == "jugador":
#Pedimos datos al jugador
fila = int(input("Dime la fila: "))
columna = int(input("Dime la columna: "))
while not self.tablero.esPosibleColocar(fila,columna):
print("Casilla incorrecta. Vuelve a intentarlo por favor")
fila = int(input("Dime la fila: "))
columna = int(input("Dime la columna: "))
if self.tablero.esPosibleColocar(fila,columna):
self.tablero.colocarFicha(fila,columna, Tablero.SIMBOLOJUGADOR)
if self.tablero.hayTresEnRaya(Tablero.SIMBOLOJUGADOR):
hayGanador = True
else:
print("casilla equivocada")
#turno CPU
else:
mejorFila = self.tablero.devolverMejorFila()
if mejorFila != 0:
#Elegir casilla aleatoria, pero ojo con la fila fija
posiciones = self.tablero.elegirPosicionAleatoria2(mejorFila, "fila")
print("POSICION ELEGIDA POR LA CPU(",posiciones[0],",",posiciones[1],")")
else:
mejorColumna = self.tablero.devolverMejorColumna()
if mejorColumna != 0:
posiciones = self.tablero.elegirPosicionAleatoria2(mejorColumna, "columna")
print("POSICION ELEGIDA POR LA CPU(",posiciones[0],",",posiciones[1],")")
else:
posiciones = self.tablero.elegirPosicionAleatoria()
print("POSICION ELEGIDA POR LA CPU(",posiciones[0],",",posiciones[1],")")
self.tablero.colocarFicha(posiciones[0],posiciones[1], Tablero.SIMBOLOCPU)
if self.tablero.hayTresEnRaya(Tablero.SIMBOLOCPU):
hayGanador = True
if self.turno == "jugador":
self.turno = "cpu"
else:
self.turno = "jugador"
if hayGanador:
if self.turno == 'jugador':
print("GANA LA CPU")
ganador = 'cpu'
print(self.tablero)
else:
print("GANA EL JUGADOR")
ganador = 'jugador'
print(self.tablero)
else:
print("HABÉIS EMPATADO")
ganador = 'ninguno'
print(self.tablero)
return ganador
|
d21139320f76081bb802016e1ee69e4a589fe577 | DB-DeKoN/DeKoN | /06-list.py | 814 | 4.15625 | 4 | lenguajes = ['python','kotlin','java']
print (lenguajes)
#los arrays (lists) comienzan en la posicion 0
print (lenguajes[0])
lenguajes.sort() # esta funcion de lista ordena alfabeticamente
print(lenguajes)
#acceder a un elemento dentro de un texto
aprendiendo = f'Estoy aprendiendo {lenguajes[2]}'
print(aprendiendo)
#Modificando valores de un arreglo
lenguajes[2] = 'php'
print (lenguajes)
#agregar elementos a un list o arreglo
lenguajes.append('ruby')
print(lenguajes)
#Eliminar a un arreglo (list)
del lenguajes[1]
print(lenguajes)
#Eliminar a un arreglo o list el ultimo elemento
lenguajes.pop ()
print(lenguajes)
#Eliminar con .pop una posicion en especifico
lenguajes.pop (0)
print (lenguajes)
#Eliminar por nombre
lenguajes.remove ('php')
print (lenguajes)
|
0b0cf7c3179553f93b9e5091959535bfc82ff64f | themockingjester/leetcode-python- | /257. Binary Tree Paths.py | 1,102 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def check(self,root,s):
if root:
if root.left==None and root.right==None:
k = str(root.val)
s=s+k
self.lis.append(s)
return
if root.left:
self.check(root.left,s+str(root.val)+"->")
if root.right:
self.check(root.right,s+str(root.val)+"->")
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if root:
self.lis = []
if root.left==None and root.right == None:
self.lis.append(str(root.val))
else:
if root.left:
s = str(root.val)+"->"
self.check(root.left,s)
if root.right:
s = str(root.val)+"->"
self.check(root.right,s)
return self.lis
|
3cfa99e61337350c3acdc5db7fc58fdaec183452 | wangerzi/bmtrip-technology-sharing | /2019-11 Python基础分享/code/hanoi.py | 453 | 4 | 4 | def hanoi(n, A, B, C):
"""表示将n个碟子,从A借助B移动到C"""
if n == 1:
# A 通过 B 移动到 C,如果只有一个盘子,
print("Move %s => %s"%(A, C))
else:
hanoi(n-1, A, C, B) # 将 A 上 N-1 个盘子,从 A 借助 C 移动到 B
print("Move %s => %s"%(A, C)) # 将 A 上最后一个盘子,直接移动到 C
hanoi(n-1, B, A, C) # 将 B 上 N-1 个盘子,从 B 借助 A 移动到 C
hanoi(64, "A塔", "B塔", "C塔")
|
ba3a175344987631912e353b232b0969f1b0bc41 | mfkiwl/gnssIR_python | /ymd.py | 500 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
converts ymd to doy
kristine larson
Updated: April 3, 2019
"""
import gps as g
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("year", help="year ", type=int)
parser.add_argument("month", help="month ", type=int)
parser.add_argument("day", help="day ", type=int)
args = parser.parse_args()
year = args.year
month = args.month
day = args.day
# compute filename to find out if file exists
doy,cdoy,cyyyy,cyy = g.ymd2doy(year, month, day )
print(cdoy)
|
ff42ab6be1c6ed147ae9aacf5a803ff161e0fdb4 | gracomot/Basic-Python-For-College-Students | /Lectures/Lesson 5/Python Libary Functions/circle.py | 432 | 4.46875 | 4 | # A program to find the circumference and area of a circle
import math
def main():
radius = float(input("Enter the radius of the circle: "))
circumference = 2 * math.pi * radius
area = math.pi*radius**2
print("The circumference of a circle with radius",radius,
"is",format(circumference,'.2f'))
print("The area of a circle with radius",radius,"is",format(area,'.2f'))
# Call the main function
main()
|
481af5c8b61daa9e65e9ba48858ddfe074ce15c2 | rxue07/TestPython | /test/three.py | 288 | 4.0625 | 4 | '''
今天习题:
1 字符串:
a = 'abcd'
用2个方法取出字母d
2:
a = 'jay'
b = 'python'
用字符串拼接的方法输出:
my name is jay,i love python.
'''
a='abcd'
print(a[3])
print(a[-1])
a='jay'
b='python'
print(('%s'+ a +'%s'+ b)%('my name is ',',i love '))
|
826e5e6fe660fba3cb33aa6f6e2776ae03423b9c | devak23/python | /python_workbook/test/ch01/test_summation.py | 913 | 3.640625 | 4 | import unittest
from python_workbook.ch01.p07_summation import Summation
class TestSummation(unittest.TestCase):
def setUp(self):
self.summation_instance = Summation()
def test_summation_with_positive_number_gives_correct_result(self):
self.assertEqual(231, self.summation_instance.summation(21))
self.assertEqual(1, self.summation_instance.summation(1))
def test_summation_with_negative_number_gives_None(self):
self.assertEqual(None, self.summation_instance.summation(-23))
self.assertEqual(None, self.summation_instance.summation(-1))
def test_summation_with_None_returns_None(self):
self.assertEqual(None, self.summation_instance.summation(-23))
self.assertEqual(None, self.summation_instance.summation(-1))
def test_summation_with_zero_returns_None(self):
self.assertEqual(None, self.summation_instance.summation(0))
|
458c1dc8153440d4a148f7a06def04b274fd87fe | danTaler/Python_examples | /regex.py | 2,944 | 4.1875 | 4 | import re
text = "This is a good day"
#search looks for some pattern and returns BOOLEAN
if re.search("good",text):
print("found")
else:
print("Not found")
#the findall() and split() functions will parse the string for us and return chunks:
text = "Amy works diligently. Amy gets good grades. Our student Amy is successful."
result = re.split("Amy",text)
print(result)
# Find all occurances
result = re.findall("Amy",text)
print(result)
#complex patters, finding patterns
#
print(re.search("^Amy",text))
sometext = "asd adfdghtdx sfgdhgtd edit"
print(re.findall("[\w ]*edit",sometext))
#Groups:
for t in re.findall("[\w ]*edit",sometext):
print(re.split("...",t)[0])
#for item in re.finditer("",sometext):
# print(item.group(1))
# https://www.coursera.org/learn/python-data-analysis/programming/4Wy6F/lab
# assignment1
#----------------------------------------
# Part A
def names():
simple_string = """Amy is 5 years old, and her sister Mary is 2 years old.
Ruth and Peter, their parents, have 3 kids."""
# YOUR CODE HERE
result = re.findall("Amy|Mary|Ruth|Peter",simple_string)
return result
raise NotImplementedError()
assert len(names()) == 4, "There are four names in the simple_string"
# Part B
'''
def grades():
with open ("assets/grades.txt", "r") as file:
grades = file.read()
#Ronald Mayr: A
#Simon Loidl: B
#Bell Kassulke
#Simon Loidl
#print(re.split('\s+',grades))
return re.findall("\w+\s\w+: B",grades)
raise NotImplementedError()
assert len(grades()) == 16
'''
print('-------------Part C ----------\n')
# Part C
def logs():
mylist = []
counter = 0
with open("logdata.txt", "r") as file:
logdata = file.readline()
print(type(logdata))
#146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622
while logdata:
log_list = (re.split("\s",logdata))
mydict= {}
mydict['host'] = log_list[0]
mydict['user_name'] = log_list[2]
#remove '[' ']'
str_with_brackets = (' '.join(log_list[3:5])) # 'time': '[21/Jun/2019:15:45:24 -0700]'
mydict['time'] = str_with_brackets[1:-1]
str_with_quotes = (' '.join(log_list[5:8]))
mydict['request'] = str_with_quotes[1:-1] #'request': ['"POST', '/incentivize', 'HTTP/1.1"']
#print(mydict)
mylist.append(mydict)
counter = counter +1
logdata = file.readline()
print(counter)
return mylist
raise NotImplementedError()
assert len(logs()) == 979
one_item={'host': '146.204.224.152',
'user_name': 'feest6811',
'time': '21/Jun/2019:15:45:24 -0700',
'request': 'POST /incentivize HTTP/1.1'}
assert one_item in logs(), "Sorry, this item should be in the log results, check your formating"
|
3214d258b3b6dd426d622a4ca8b76da43a8a9755 | vairus666/lesson9 | /fizzbuzz.py | 367 | 4 | 4 |
def Fizz(a = 0, b = 0):
for number in range(a, b):
# if number % 3 == 0 and number % 5 == 0:
# print('FizzBuzz')
if number % 3 == 0:
print('Fizz')
# elif number % 5 == 0:
# print('Buzz')
else:
print(number)
a = int.input('a')
b = int.input('b')
print(Fizz(a,b))
|
a34d6cdebef1ec6fb8ac8edaf8f102babddb6707 | ivan-ops/progAvanzada | /triangulo_dos.py | 487 | 3.515625 | 4 |
class Triangulo:
def __init__ (self,angulo1,angulo2,angulo3):
self.angulo1 = angulo1
self.angulo2 = angulo2
self.angulo3 = angulo3
def checar_angulos(self):
suma = self.angulo1+self.angulo2+self.angulo3
if suma == 180:
print('True')
else:
print('False')
mi_triangulo= Triangulo(90,30,60)
mi_triangulo2= Triangulo(60,30,90)
mi_triangulo.checar_angulos()
mi_triangulo2.checar_angulos()
|
a29667186ab9008018c7e2d8ee93e3f7280c2699 | JeffJetton/tia-counter | /tia_counter_demo.py | 612 | 3.578125 | 4 | from tia_counter import *
# Create a list-based counter object
tia1 = TiaCounterV1()
# Create a bit-based counter object
tia2 = TiaCounterV2()
# Cycle through every period of each and compare states
print('\n i List Counter Bit Counter Match?')
print('-- ------------ ----------- ------')
for i in range(2 ** 6):
s = "{:>2d} ".format(i+1)
s += str(tia1) + ' ' + str(tia2) + ' '
if int(tia1) == int(tia2):
s += "Yes"
else:
s += "No"
print(s)
# Cycle both counters to their next state
tia1.shift()
tia2.shift()
print('\n')
|
be5632bc7dfac82949bc6876a1d1d836afe3c485 | Languomao/PythonProject | /python_learn_01/demo_01.py | 475 | 3.8125 | 4 | from random import randint
print("开始游戏,你只有三次机会。。。")
i = 0
num = randint(1, 10)
while i < 3:
input_num = input("随机输入一个数字:")
guess = int(input_num)
if guess == num:
print("恭喜你猜对了!")
break
else:
if guess > num:
print("大了。。。")
i += 1
if guess < num:
print("小了。。。")
i += 1
print("不玩了。。。")
|
c76ba1e8c5f63d665dd062bc018fcc5251baa492 | DAGG3R09/coriolis_training | /assignments/Q17_panlindrome_recognizer.py | 515 | 4.125 | 4 | from string import ascii_lowercase
lowercase = set(ascii_lowercase)
def palindrome_recognizer(string):
string = string.lower()
string = list(filter(lambda x: x in lowercase, string))
if(string == string[::-1]):
return True
else:
return False
if __name__ == "__main__":
s1 = "Go hang a salami I'm a lasagna hog."
s2 = "Lisa Bonet ate no basil"
s3 = "Sufiyan Parkar"
print(palindrome_recognizer(s1))
print(palindrome_recognizer(s2))
print(palindrome_recognizer(s3))
|
6e41e2eff03e996ded0dd0e863880660d085a9e2 | irinacastillo/repo-team-tel | /bot login.py | 662 | 3.8125 | 4 | login = str(input("ingrese su ID: "))
list(login)
if not login.isnumeric():
print ('esta mtricula: ', login, 'es invalida')
elif len(list(login)) == 8:
print('la matricula', login, 'es valida')
else:
print ('su matricula', login, 'es invalida')
while login == True:
if login:
continue
else:
break
archivo = input('dirreccion del archivo: ')
if not result_irina.csv.csv():
print ('archivo no encontrado')
pass
with open ('d:/result_irina.csv.csv', 'r') as archivo:
lineas = archivo.read().splitlines()
lineas.pop(0)
for i in lineas:
linea = i.split(',')
print (linea)
|
607da25476a47a13a467a743b75d89ae1d28dfe4 | the-nans/py2-repo_gb | /lesson1/lesson1_task3.py | 1,411 | 3.96875 | 4 | """
Написать программу, которая генерирует в указанных пользователем границах:
a. случайное целое число,
b. случайное вещественное число,
c. случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона. Например, если надо получить случайный символ
от 'a' до 'f', то вводятся эти символы. Программа должна вывести на экран любой символ алфавита от 'a' до 'f'
включительно.
"""
from random import uniform, randint
a = input("Введите нижнюю границу случайности")
b = input("Введите верхнюю границу случайности")
c = ''
if a.isdigit() and b.isdigit():
c = randint(int(a), int(b))
else:
if a.replace(".", "").isdigit() and b.replace(".", "").isdigit():
c = uniform(float(a), float(b))
else:
if len(a) == 1 and len(b) ==1 and 96 < ord(a) < 123 and 96 < ord(b) < 123:
lim_upper = ord(a)
lim_lower = ord(b)
c = chr(randint(lim_upper, lim_lower))
else:
print("Границы случайности не опознаны")
print(c)
|
5aa2906f698b77928c156aa8577c2eee732e629d | arokasprz100/Python-exercises | /banks_task/task.py | 8,903 | 4.1875 | 4 | import json
def get_valid_option_from_user(lower_bound, upper_bound):
while True:
value = input("Please input proper option: ")
try:
value = int (value)
if value < lower_bound or value > upper_bound:
continue
else: break
except ValueError:
print ("You should enter integer.\n")
return value
def get_valid_amount_of_money_from_user():
while True:
amount_of_money = input ("Please input amount of money: ")
try:
amount_of_money = int (amount_of_money)
break
except ValueError:
print ("You should enter a number.\n")
return amount_of_money
def get_personal_data_from_user():
name = input ("Please enter name: ")
surname = input ("Please enter surname: ")
return name + " " + surname
def get_new_password():
while True:
password1 = input ("Please enter new password: ")
password2 = input ("Please repeat your password: ")
if password2 != password1:
print ("Passwords are not the same. Try again.\n")
else: return password1
def get_welcome_message():
message = ( "\n\nWelcome to the banking system simulator.\n" +
"From here, you can do several things: \n" +
"1. Log in as a bank employee.\n" +
"2. Log in as a customer. \n" +
"3. Create new customer account.\n" +
"4. Use system without logging in.\n" +
"5. Quit.\n" +
"If You are using this system for the first time, " +
"you should use options 1, 3 and 4\n\n" )
return message
def get_choices_message(type_of_user):
message = ( "\n\nIn our system you can do several things.\n" +
"Below is the list of them. Please choose proper option number.\n" +
"1. Display whole system.\n" +
"2. Display one whole bank.\n" +
"3. Print account balance for one customer.\n" +
"4. Save to file.\n" +
"5. Load state from file.\n" +
"6. Back to logging screen.\n")
if type_of_user == "employee":
message += "7. Add new customer.\n"
message += "8. Handle transaction.\n"
if type_of_user == "customer":
message += "7. Print my account balance.\n"
message += "8. Input cash.\n"
message += "9. Withdraw cash. \n"
message += "10. Transfer money.\n"
return message
def create_new_account(bank_network):
new_personal_data = get_personal_data_from_user()
new_password = get_new_password()
new_money = get_valid_amount_of_money_from_user()
print("Choose a bank. Options are as follows:")
for bank_name in bank_network:
print (bank_name)
while True:
choosen_bank = input()
if choosen_bank not in bank_network:
print ("There is no such bank. Try again.")
else:
new_customer = {new_personal_data : {"Money" : new_money, "Password" : new_password}}
return new_customer, choosen_bank
if __name__ == "__main__":
with open ("pseudodatabase.txt", 'r') as inputfile:
bank_network = json.load(inputfile)
loggin_modes = ["employee", "customer", "nobody"]
while True:
print(get_welcome_message())
log_in_mode = "logged out"
loggin_type = get_valid_option_from_user(1, 5)
if loggin_type == 1:
try:
bank = input ("For which bank do you work? ")
if bank not in bank_network:
raise ValueError
if input("Please enter password: ") != "admin":
raise ValueError
print ("Logged in as a bank employee!\n")
log_in_mode = "employee"
option_upper_bound = 8
except ValueError:
print ("Could not log in as bank employee\n")
if loggin_type == 2:
try:
bank = input ("In which bank are you: ")
if bank not in bank_network:
raise ValueError
customer_data = input ("Enter your name and surname: ")
if customer_data not in bank_network[bank]:
raise ValueError
password = input ("Enter password: ")
if password != bank_network[bank][customer_data]["Password"]:
raise ValueError
print ("Logged in as a bank customer!\n")
log_in_mode = "customer"
option_upper_bound = 10
except ValueError:
print ("Wrong user data. Please try again.\n")
if loggin_type == 3:
print ("Our system will now ask you for your personal data, password and amount of money you want to input.")
new_account_data = create_new_account(bank_network)
bank_network[new_account_data[1]].update(new_account_data[0])
if loggin_type == 4:
print ("You are going to use banking system without logging in.")
log_in_mode = "nobody"
option_upper_bound = 6
if loggin_type == 5:
print ("Thank you for using my banking simulator. ")
break
while log_in_mode in loggin_modes:
print(get_choices_message(log_in_mode))
user_input = get_valid_option_from_user(1, option_upper_bound)
### Display whole system
if user_input == 1:
for bank_name, bank_customers in bank_network.items():
print ("\n" + bank_name)
print ("{:<40} {:>40}".format("CUSTOMER", "MONEY"))
for customer_name, customers_data in bank_customers.items():
print ("{:<40} {:>40}".format(customer_name ,customers_data["Money"] ))
### Display one bank
elif user_input == 2:
while True:
bank_to_display = input ("Please enter name of bank to display: ")
if bank_to_display not in bank_network.keys():
print("No such bank in system. Try again.")
continue
bank_to_display = bank_network[bank_to_display]
break
print ("{:<40} {:>40}".format("CUSTOMER", "MONEY"))
for customer_name, customers_data in bank_to_display.items():
print ("{:<40} {:>40}".format(customer_name ,customers_data["Money"] ))
### Print one customer
elif user_input == 3:
while True:
try:
bank_to_display = input ("Please enter bank name: ")
if bank_to_display not in bank_network:
raise ValueError
person = get_personal_data_from_user()
if person not in bank_network[bank_to_display]:
raise ValueError
print ("{}: {}".format(person, bank_network[bank_to_display][person]["Money"]))
break
except:
print("Wrong data. Try again")
### Save to file
elif user_input == 4:
with open ("pseudodatabase.txt", 'w') as outfile:
json.dump(bank_network, outfile, indent = 4)
print("Data has been saved to file")
### Load from file
elif user_input == 5:
with open ("pseudodatabase.txt", 'r') as inputfile:
bank_network = json.load(inputfile)
### Back to log-in screen
elif user_input == 6:
print ("Logged out")
log_in_mode = "logged out"
### Print personal data
elif user_input == 7 and log_in_mode == "customer":
print ("{}: {}".format(customer_data, bank_network[bank][customer_data]["Money"]))
### Input cash
elif user_input == 8 and log_in_mode == "customer":
how_much_money = get_valid_amount_of_money_from_user()
bank_network[bank][customer_data]["Money"] +=how_much_money
print ("Cash input succesful!")
### Withdraw cash
elif user_input == 9 and log_in_mode == "customer":
how_much_money = get_valid_amount_of_money_from_user()
bank_network[bank][customer_data]["Money"] -=how_much_money
print ("Cash withdraw succesful!")
### Transfer money
elif user_input == 10 and log_in_mode == "customer":
print("Who are you going to transfer your money to? ")
while True:
try:
other_customer = get_personal_data_from_user()
if other_customer not in bank_network[bank]:
raise ValueError
break
except ValueError:
print ("No such customer in our bank")
how_much_money = get_valid_amount_of_money_from_user()
bank_network[bank][other_customer]["Money"] += how_much_money
bank_network[bank][customer_data]["Money"] -= how_much_money
print ("Transaction between {} and {} has been succesful".
format(customer_data, other_customer))
### Add new account
elif user_input == 7 and log_in_mode == "employee":
new_account_data = create_new_account(bank_network)
bank_network[new_account_data[1]].update(new_account_data[0])
### Handle transaction
elif user_input == 8 and log_in_mode == "employee":
while True:
try:
customers_in_transaction = list(get_personal_data_from_user() for i in range(2))
for checked_customer in customers_in_transaction:
if checked_customer not in bank_network[bank]:
raise ValueError
how_much_money = get_valid_amount_of_money_from_user()
bank_network[bank][customers_in_transaction[0]]["Money"] -= how_much_money
bank_network[bank][customers_in_transaction[1]]["Money"] += how_much_money
print ("Transaction between {} and {} has been succesful".
format(customers_in_transaction[0], customers_in_transaction[1]))
break
except ValueError:
print ("One of these customers does not exist.")
|
04121b971ea9afe06da156dbaf72925d06e04960 | d-ignatovich/Binary-search | /main.py | 929 | 3.71875 | 4 | import timeit
# The function determines the index of the first occurrence of the specified element.
def ind_rec(numbers, x):
low = 0
high = len(numbers) - 1
while low < high:
m = (low + high) // 2
if x > numbers[m]:
low = m + 1
else:
high = m
if numbers[high] == x:
return high
return None
# Data entry
numbers = list(map(int, input().split()))
value = int(input())
# Recursive search
t0 = timeit.default_timer()
print(ind_rec(numbers, value))
t1 = timeit.default_timer() - t0
print(t1)
# Iterative search
t0 = timeit.default_timer()
mid = len(numbers) // 2
low = 0
high = len(numbers) - 1
while numbers[mid] != value and low <= high:
if value > numbers[mid]:
low = mid + 1
else:
high = mid - 1
mid = (low + high) // 2
if low > high:
print("None")
else:
print(mid)
t1 = timeit.default_timer() - t0
print(t1)
|
b792f2d676652222eaf549ca8143d596860efca3 | mohits1005/DSAlgo | /maths2/maxgcd-delete-one.py | 2,053 | 3.5 | 4 | '''
Delete one
Problem Description
Given an integer array A of size N. You have to delete one element such that the GCD(Greatest common divisor) of the remaining array is maximum.
Find the maximum value of GCD.
Problem Constraints
2 <= N <= 105
1 <= A[i] <= 109
Input Format
First argument is an integer array A.
Output Format
Return an integer denoting the maximum value of GCD.
Example Input
Input 1:
A = [12, 15, 18]
Input 2:
A = [5, 15, 30]
Example Output
Output 1:
6
Output 2:
15
Example Explanation
Explanation 1:
If you delete 12, gcd will be 3.
If you delete 15, gcd will be 6.
If you delete 18, gcd will 3.
Maximum vallue of gcd is 6.
Explanation 2:
If you delete 5, gcd will be 15.
If you delete 15, gcd will be 5.
If you delete 30, gcd will be 5.
'''
class Solution:
# @param A : list of integers
# @return an integer
def gcd(self, A, B):
gcd = 1
if B == 0:
return 0
if A < B:
A, B = B, A
while B > 0:
if A % B == 0:
gcd = B
A = A % B
A,B = B,A
return gcd
def solve(self, A):
leftgcd = [0 for elem in A]
leftgcd[0] = A[0]
for i in range(1, len(A)):
leftgcd[i] = self.gcd(leftgcd[i-1],A[i])
rightgcd = [0 for elem in A]
rightgcd[len(A)-1] = A[len(A)-1]
for i in range(len(A)-2, -1, -1):
rightgcd[i] = self.gcd(rightgcd[i+1],A[i])
maxgcd = 0
ans = 0
for i in range(0, len(A)):
if i == 0:
if rightgcd[1]>maxgcd:
maxgcd = rightgcd[1]
ans = 0
elif i == len(A)-1:
if leftgcd[len(A)-2]>maxgcd:
maxgcd = rightgcd[len(A)-2]
ans = len(A)-1
else:
commongcd = self.gcd(leftgcd[i-1],rightgcd[i+1])
if commongcd > maxgcd:
maxgcd = commongcd
ans = i
return A[ans]
|
4f2ca22001f373ee211bbcaae5227b4d620d434a | Hugo-Oliveira-RD11/aprendendo-PYTHON-iniciante | /download-deveres/para-execicios-curso-em-video/exe037.py | 560 | 4.1875 | 4 | numero = int(input('digite um numero inteiro :'))
print('''escolhar um numero para a converçao
[ 1 ] BINARIO
[ 2 ] OCTAL
[ 3 ] HEXADECIMAL''')
escolha = int(input('digite um dos numeros dentro das opções :'))
if escolha == 1:
print('A BINARIA do numero {} e {}'.format(numero, bin(numero)[2:]))
elif escolha == 2:
print('O OCTANAL do numero {} e {}'.format(numero, oct(numero)[2:]))
elif escolha == 3:
print('O hexadecimal do numero {} e {}',format(numero, hex(numero)[2:]))
else:
print('por favor, DIGITE UM NUMERO DENTRO DAS OPÇOES!!')
|
8cb6d3090f386cb7a271bdd6fc77890c99df8bb3 | jamesgrimmett/geolocation_solver | /geolocation/utils/conversion.py | 3,555 | 3.703125 | 4 | """
Utils for converting coordinates / units.
"""
import numpy as np
from . import earth_model, error_handling
def geographic2cartesian(lat, lon, h = None, lat_is_geocentric = True):
"""
Convert geographic coordinates to geocentric cartesian coordinates.
Args:
lat: Latitude in degrees (neg. south) [-90,90]
lon: Longitude in degrees (neg. west) [-180,180]
h: Height in meters above the Earth's surface.
lat_is_geocentric: Boolean indicating whether the
given latitude is geocentric (False is geodetic)
Returns:
x: X geocentric coordinate (positive x-axis passing
through 0 degrees longitude at the equator).
y: Y geocentric coordinate (positive y-axis passing
through 90 degress longitude at the equator).
z: Z geocentric coordinate (positive z-axis passing
through north pole).
"""
r_e = earth_model.r_e
ecc = earth_model.ecc
if h is None:
h = 0.0
# Convert angles in degrees to radians
lat = np.deg2rad(lat)
lon = np.deg2rad(lon)
# Convert geographic latitude to geodetic latitude
if lat_is_geocentric:
lat = geographic2geodetic(lat)
# Equations 57 - 59 in Ho & Chan (1997)
gamma = r_e / np.sqrt(1 - ecc**2 * np.sin(lat)**2)
x = (gamma + h) * np.cos(lat) * np.cos(lon)
y = (gamma + h) * np.cos(lat) * np.sin(lon)
z = ((1 - ecc**2) * gamma + h) * np.sin(lat)
return x, y, z
def cartesian2geographic(x, y, z):
"""
Convert cartesian coordinates to geographic coordinates.
Args:
x: X geocentric coordinate (positive x-axis passing
through 0 degrees longitude at the equator).
y: Y geocentric coordinate (positive y-axis passing
through 90 degress longitude at the equator).
z: Z geocentric coordinate (positive z-axis passing
through north pole).
Returns:
lat: Latitude in degrees (neg. south) [-90,90]
lon: Longitude in degrees (neg. west) [-180,180]
h: Height in meters above the Earth's surface.
"""
r_e = earth_model.r_e
ecc = earth_model.ecc
r = np.sqrt(x**2 + y**2 + z**2)
p = np.sqrt(x**2 + y**2)
f = np.roots([1,-2,ecc**2])
#f = f[f <= 2][f >= 1]
f = f[f>=0][f<=1]
if len(f) > 1:
raise error_handling.InvalidSolutionError("Unable to convert coordinates.")
f = float(f)
mu = np.arctan(z / p * ((1 - f) + ecc**2 * r_e / r) )
lon = np.arctan(y / x)
lat = np.arctan((z * (1-f) + ecc**2*r_e*np.sin(mu)**3) / ((1 - f) * (p - ecc**2*r_e*np.cos(mu)**3)))
lat = geodetic2geographic(lat)
# Convert angles in degrees to radians
lat = np.rad2deg(lat)
lon = np.rad2deg(lon)
local_r = earth_model.local_earth_radius(lat,lon)
h = r - local_r
return lat, lon, h
def geographic2geodetic(lat):
"""
Converts geographic latitude (radians) to geodetic latitude (radians).
Eq. 58 of Ho & Chan (1997).
Args:
lat: Latitude in degrees (neg. south) [-90,90]
"""
ecc = earth_model.ecc
geod_lat = np.arctan( np.tan(lat) / (1 - ecc**2) )
return geod_lat
def geodetic2geographic(geod_lat):
"""
Converts geodetic latitude (radians) to geographic latitude (radians).
Eq. 58 of Ho & Chan (1997).
Args:
lat: Geodetic latitude in degrees (neg. south) [-90,90]
"""
ecc = earth_model.ecc
lat = np.arctan( np.tan(geod_lat) * (1 - ecc**2) )
return lat
|
9c8894f6fef436d48eb2e67fa235c41eff295b09 | OmkarRatnaparkhi/Basic_Python_Programs | /Problems_on_numbers/Q9_Display_First_Number_In_Second_Number_Times/Module.py | 339 | 3.859375 | 4 |
#Defination of Display funtion
#Function Name : Display
#Description: It is use to display first number in second number times
#Date : 08 Feb 2021
#Author name : OMKAR NARENDRA RATNAPARKHI
def Display(no,frequency):
if (frequency < 0):
frequency = -frequency
for iCnt in range (0,frequency,+1):
print(no,end =" ") |
57de86fa5f63935fc26b5126c10c25f7b5936a6c | RWEngelbrecht/Learning_Python | /random_tests/whtShldWtch.py | 750 | 3.515625 | 4 | # What Should I Watch
import random
# def make_choice(possibilities):
# secure_random = random.SystemRandom()
# print(secure_random.choice(secure_random.choice(possibilities)))
def make_choices(possibilities, amount):
secure_random = random.SystemRandom()
option = possibilities[secure_random.randint(1, 3)]
for i in range(0, amount):
print(option[secure_random.randint(1, 3)])
shows = {
1: "Mad Men",
2: "Naruto",
3: "American Vandal",
}
tutorials = {
1: "Python",
2: "CTF",
3: "Networks",
}
misc = {
1: "random youtube videos",
2: "pr0n",
3: "read a book, dammit",
}
options = {
1: shows,
2: tutorials,
3: misc,
}
# make_choice(options)
make_choices(options, 5)
|
8956ad6540a92fea4ce4e02b5347dee82ac729c2 | furkanbogaci/gaih-students-repo-example | /Homeworks/HW1.py | 207 | 4.03125 | 4 | import numpy as np
matrix = [[],[],[]]
for i in range(0,3):
for j in range(0,3):
for k in np.random.randint(0,10,1):
matrix[i].append(k)
for i in range(3):
print(matrix[i])
|
cb8caa87be5b0dcdd3ad94a0d55fb434ea7c3fc0 | JJHYE0N/Bitcoin-Supply-Calculator | /btcsupply.py | 556 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
def btcSupplyAtBlock(b):
if b >= 33 * 210000:
return 20999999.9769
else:
reward = 50e8
supply = 0
y = 210000 # reward changes all y blocks
while b > y - 1:
supply = supply + y * reward
reward = int(reward / 2.0)
b = b - y
supply = supply + b * reward
return (supply + reward) / 1e8
if __name__ == "__main__":
block = 1000000 # you want the supply after which block?
print(btcSupplyAtBlock(block))
|
9f70df178dfbe74702e47c2c0725a6ac74674080 | aaryanredkar/prog4everybody | /week 8/8-2.py | 424 | 3.578125 | 4 | fname = raw_input("Enter file name: ")
fh = open(fname)
dic = dict()
for line in fh:
if line.startswith('From'):
t=line.split()
email = t[1]
if email not in dic:
dic[email] = 1
else:
dic[email] +=1
bigcount = None
bigemail = None
for email,count in dic.items():
if bigcount is None or count > bigcount:
bigemail = email
bigcount = count
print bigemail, bigcount
|
f93143cd1fe85b15735af4769297eef153316abf | KuMuAB/Python_Flask | /列操作.py | 583 | 3.546875 | 4 | from numpy import column_stack
import pandas as pd
import numpy as np
page_001 = pd.read_excel('Students_27.xlsx',sheet_name='Page_001',)
page_002 = pd.read_excel('Students_27.xlsx',sheet_name='Page_002',)
students= pd.concat([page_001,page_002]).reset_index(drop=True)
# 追加一列
students['Age'] = 30
# 删除列
students.drop(columns = ['Age','Score'],inplace=True)
# 插入列
students.insert(1,column = 'Foo',value=np.repeat('foo',len(students)))
# 修改列名
students.rename(columns={'Foo':'FOO','Name':'NAME'},inplace=True)
print(students)
|
fa5ed5552e7c46e15d0ff9050684d4939c564715 | sage-kanishq/PythonFiles | /Challenges/occurence.py | 124 | 3.515625 | 4 | import itertools as it
string = input()
for key, grp in it.groupby(string):
print(f'({len(list(grp))},{key})',end = ' ') |
021e74efc0b738e86709e0e7a8543bfa80e50d0d | PrLayton/SeriousFractal | /PartDesign/Scripts/FilletArc.py | 2,687 | 3.5 | 4 | #! python
# -*- coding: utf-8 -*-
# (c) 2010 Werner Mayer LGPL
__author__ = "Werner Mayer <wmayer[at]users.sourceforge.net>"
# Formulas:
# M2 = P + b*r2 + t*u
# S1 = (r2*M1 + r1*M2)/(r1+r2)
# S2 = M2-b*r2
import math
# 3d vector class
class Vector:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def add(self,vec):
return Vector(self.x+vec.x,self.y+vec.y,self.z+vec.z)
def sub(self,vec):
return Vector(self.x-vec.x,self.y-vec.y,self.z-vec.z)
def dot(self,vec):
return self.x*vec.x+self.y*vec.y+self.z*vec.z
def mult(self,s):
return Vector(self.x*s,self.y*s,self.z*s)
def cross(self,vec):
return Vector(
self.y * vec.z - self.z * vec.y,
self.z * vec.x - self.x * vec.z,
self.x * vec.y - self.y * vec.x)
def length(self):
return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)
def norm(self):
l = self.length()
if l > 0:
self.x /= l
self.y /= l
self.z /= l
def __repr__(self):
return "(%f,%f,%f)" % (self.x,self.y,self.z)
# A signum function
def sgn(val):
if val > 0:
return 1
elif val < 0:
return -1
else:
return 0
# M1 ... is the center of the arc
# P ... is the end point of the arc and start point of the line
# Q .. is a second point on the line
# N ... is the normal of the plane where the arc and the line lie on, usually N=(0,0,1)
# r2 ... the fillet radius
# ccw ... counter-clockwise means which part of the arc is given. ccw must be either True or False
def makeFilletArc(M1,P,Q,N,r2,ccw):
u = Q.sub(P)
v = P.sub(M1)
if ccw:
b = u.cross(N)
else:
b = N.cross(u)
b.norm()
uu = u.dot(u)
uv = u.dot(v)
r1 = v.length()
# distinguish between internal and external fillets
r2 *= sgn(uv);
cc = 2.0 * r2 * (b.dot(v)-r1)
dd = uv * uv - uu * cc
if dd < 0:
raise RuntimeError("Unable to caluclate intersection points")
t1 = (-uv + math.sqrt(dd)) / uu
t2 = (-uv - math.sqrt(dd)) / uu
if (abs(t1) < abs(t2)):
t = t1
else:
t = t2
br2 = b.mult(r2)
print br2
ut = u.mult(t)
print ut
M2 = P.add(ut).add(br2)
S1 = M1.mult(r2/(r1+r2)).add(M2.mult(r1/(r1+r2)))
S2 = M2.sub(br2)
return (S1,S2,M2)
def test():
from FreeCAD import Base
import Part
P1=Base.Vector(1,-5,0)
P2=Base.Vector(-5,2,0)
P3=Base.Vector(1,5,0)
#Q=Base.Vector(5,10,0)
#Q=Base.Vector(5,11,0)
Q=Base.Vector(5,0,0)
r2=3.0
axis=Base.Vector(0,0,1)
ccw=False
arc=Part.ArcOfCircle(P1,P2,P3)
C=arc.Center
Part.show(Part.makeLine(P3,Q))
Part.show(arc.toShape())
(S1,S2,M2) = makeArc(Vector(C.x,C.y,C.z),Vector(P3.x,P3.y,P3.z),Vector(Q.x,Q.y,Q.z),Vector(axis.x,axis.y,axis.z),r2,ccw)
circle=Part.Circle(Base.Vector(M2.x,M2.y,M2.z), Base.Vector(0,0,1), math.fabs(r2))
Part.show(circle.toShape())
|
e4c3b3026248943e317309a460e6cdea5611d508 | 742darek/Programming-for-computation | /example_symbolic.py | 374 | 3.640625 | 4 | from sympy import *
x = Symbol('x')
y = Symbol('y')
print (2*x + 3*x - y) # Algebraic computation
print (diff(x**2, x)) # Differentiates x**2 wrt. x
print (integrate(cos(x), x)) # Integrates cos(x) wrt. x
print (simplify((x**2 + x**3)/x**2)) # Simplifies expression
print (limit(sin(x)/x, x, 0)) # Finds limit of sin(x)/x as x->0
print (solve(5*x - 15, x)) # Solves 5*x = 15 |
50f87542bda61b46ee81352ae664d4130f52f30f | gabriel-valenga/CursoEmVideoPython | /ex106.py | 1,434 | 4 | 4 | def notas(medias, sit=False):
"""
Função que recebe as médias de uma turma e retorna uma análise sobre esses dados.
:param medias: um ou mais valores do tipo Float
:param sit: parâmetro opcional, se for True exibirá também a situação da turma
:return: tipo dict, retorna um dicionário no formato: {'total': x, 'maior': x, 'menor': x, 'média': x, 'situação': x} (situacao é exibido ou não de acordo com o parâmetro sit)
"""
maior = menor = cont = soma = 0
for m in medias:
num = float(m)
if cont == 0:
maior = menor = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
soma += num
cont += 1
mediageral = round((soma / len(medias)), 2)
if not sit:
return {'total': soma, 'maior': maior, 'menor': menor, 'média': mediageral}
else:
if mediageral <= 3:
situacao = 'PÉSSIMA'
elif mediageral <= 5.9:
situacao = 'RUIM'
elif mediageral <= 7.9:
situacao = 'BOA'
else:
situacao = 'EXCELENTE'
return {'total': soma, 'maior': maior, 'menor': menor, 'média': mediageral, 'situação': situacao}
notasTurma = input('Digite as notas da turma:').split(', ')
exibirSituacao = input('Deseja exibir a situação? (S/N)') in 'Ss'
print(notas(notasTurma, exibirSituacao))
|
4d1bb4a35c46cacb394dc7ad833c3184bc6c63cc | sraaphorst/daily-coding-problem | /dcp_py/day121/day121.py | 1,503 | 4.0625 | 4 | #!/usr/bin/python3
def is_k_palindrome_rec(str1: str, str2: str, m: int, n: int):
""""
Determine if a string is a k-palindrome:
A k-palindrome transforms into a palindrom by removing at most k ccharacters from it.
To avoid exponential time, we use dynamic programming.
"""
# Create a table to store the results of the subproblems.
dp = [[0] * (n+1) for _ in range(n+1)]
# Fill in the table in a bottom up manner.
for i in range(m+1):
for j in range(n+1):
# If str1 is empty, our only valid option is to return all characters from str2 to get the palindrome.
if not i:
dp[i][j] = j
# Same in reverse
elif not j:
dp[i][j] = i
# If the characters are the same, ignore the last character and recurse for remaining string.
elif str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
# If the characters are different, remove and find the minimum.
else:
# First: remove from str1, second: remove from s2.
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])
return dp[m][n]
def is_k_palindrome(s, k):
"""
Returns true if str is k-palindrome.
"""
return is_k_palindrome_rec(s, s[::-1], len(s), len(s)) <= k * 2
if __name__ == '__main__':
assert(is_k_palindrome('waterrfetawx', 2))
assert(is_k_palindrome('abcdecba', 1))
assert(not is_k_palindrome('abcdecab', 1))
|
9840c1deb0db0c13263ed1205d2e52df96ae6e42 | faizanzafar40/Intro-to-Programming-in-Python | /5. Full Exercises/e7_extract_numbers.py | 407 | 4.125 | 4 | """
Problem
-------
Write a function that takes a number as input and return all the individual numbers in it as a list
For example: if the input is 18382109, the output should be [1, 8, 2, 8, 2, 1, 0, 9]
"""
def extract_numbers(number):
n=list(number)
l=[]
for i in n:
a=int(i)
l.append(a)
return l
number=input("Enter the number: ")
l = extract_numbers(number)
print(l)
|
fe7dff5f364c1f092fb46df972a093d93e29e7ad | ArisbethAg/Laboratorio_A01274803 | /padding.py | 590 | 3.984375 | 4 |
import numpy as np
#matriz para poder probar el codigo
mat1 = np.array([[1,2],[3,4]])
#funcion para agregar padding, recibe la matriz y la dimension del padding que se desea agregar
def padding (mat1, pad):
row, col = mat1.shape
row2 = 0
col2 = 0
#definen las dimensiones de la matriz con el padding
row2 = row + 2*pad
col2 = col + 2*pad
matres = np.zeros((row2, col2))
#ciclo que llena matres a partir del padding que fue indicado
for i in range(pad, row2-pad):
for j in range(pad, col2-pad):
matres[i][j] = mat1[i-pad][j-pad]
return matres
print padding(mat1, 1)
|
12e5a01e6ee45aacfff50ba5c727fa5e24d39376 | stanlee321/javascript-curso | /clase 2/main.py | 159 | 3.59375 | 4 | #
# Funciones en python
def calc_vol_cilinder(r, h):
V = 3.14159654 * (r ** 2) * (h)
return V
volumen = calc_vol_cilinder(200, 800)
print(volumen) |
671a27c1ba58ddf287e9f47b3007f4137a044dab | JulianYG/practice | /fibonnacci_string.py | 1,440 | 4.09375 | 4 |
def find_char(s0, s1, n, k):
"""
Given two base strings s0, s1, find the kth character
of the nth fibonnacci string constructed by the two
strings. E.g:
s0 = "aaa", s1 = "bcdef"
n = 5, k = 12
aaa, bcdef, aaabcdef, bcdefaaabcdef, aaabcdefbcdefaaabcdef
The 12th character of the 5th string is 'e'.
"""
if n == 1:
if k < 1 or k > len(s0):
raise AssertionError("Invalid input k!")
return s0[k - 1]
if n == 2:
if k < 1 or k > len(s1):
raise AssertionError("Invalid input k!")
return s1[k - 1]
a, b = len(s0), len(s1)
for i in range(n - 2):
c = a
a = b
b = c + b
if k > b - a:
return find_char(s0, s1, n - 1, k - (b - a))
else:
return find_char(s0, s1, n - 2, k)
def test_find_char():
"""
Test function for corner cases
"""
test_one = ''
for j in range(1, 13):
test_one += find_char('ab', 'cogna', 4, j)
if test_one != 'cognaabcogna':
print 'Test 1 Failed; Got ' + test_one + ', Expecting ' + 'cognaabcogna'
else:
print 'Passed Test 1'
test_two = ''
for j in range(1, 15):
test_two += find_char('cdk', 'l', 6, j)
if test_two != 'lcdklcdkllcdkl':
print 'Test 2 Failed; Got ' + test_two + ', Expecting ' + 'lcdklcdkllcdkl'
else:
print 'Passed Test 2'
test_three = ''
for j in range(1, 6):
test_three += find_char('a', 'b', 5, j)
if test_three != 'abbab':
print 'Test 3 Failed; Got ' + test_three + ', Expecting ' + 'abbab'
else:
print 'Passed Test 3'
test_find_char()
|
36e0dd2223322c83cd91143bc8709d9db67b20f9 | LeoKnox/py_essential_training | /hello2.py | 262 | 3.8125 | 4 | print ('words, yada yada yada'.upper())
print ('words, yada yada yada'.swapcase())
class MyString(str):
def __str__(self):
return self[::-1]
s = 'flea fly flo. {}'
t = MyString('the fellowship of the ring')
print (s.format(8*8))
print (t) |
361f3e6b0d2d172114ccca9068a301bbe29ab10a | royels/BeyondHelloWorld | /pythonsnippets/FindPi.py | 465 | 3.5625 | 4 | from sympy import *
def FindPi():
limit = int(raw_input("To how many demical places do you want to calculate pi? (can only go up to 200,000) "))
if limit > 200000:
limit = 200000
print pi.evalf(limit)
piFill = 0
for num in range(0, limit):
piFill += 16.0**-num * (4.0 / (8 * num + 1) - 2.0 / (8 * num + 4) - 1.0 / (8 * num + 5) - 1.0 / (8 * num + 6))
print round(piFill, limit-1)
if __name__ == "__main__":
FindPi()
|
7b49395389c950ee2547a22205166f27388e2ded | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/travis_nelson/lesson06/cat_dog.py | 173 | 3.96875 | 4 | #!
# Return True if the string "cat" and "dog" appear
# the same number of times in the given string.
def cat_dog(str):
return (str.count('cat') == str.count('dog'))
|
3c0eccf0a3b2ed72e238a276df870400cb2fa04b | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_201/2445.py | 2,473 | 3.578125 | 4 |
def main(input):
file = open(input)
txt = file.read().split()
file.close()
file = open("result.txt", 'w')
i = 0
j = 1
while i < int(txt[0])*2:
spaces = int(txt[i+1])
population = int(txt[i+2])
#print spaces, population
stalls = [1]
for k in range(spaces):
stalls.append(0)
stalls.append(1)
#print sidesSpaces(stalls, 3)
if (population == spaces): file.write("Case #"+str(j)+": "+str("0 0")+"\n")
#elif (population == 1): file.write("Case #"+str(j)+": "+str(spaces/2)+" "+str(spaces/2 - 1)+"\n")
else:
for p in range(population):
result = fillPosition(stalls)
file.write("Case #" + str(j) + ": " +str(result[2])+" "+str(result[0])+ "\n")
j += 1
i += 2
file.close()
def sidesSpaces(stalls, index):
left = right = 0
i = index
while i > 1 and stalls[i-1] == 0:
left += 1
i -= 1
i = index
while i < len(stalls)-2 and stalls[i+1] == 0:
right += 1
i += 1
return left, right
def fillPosition(stalls):
valuesFirst = []
candidats = []
candidatsSecond = []
for i in range(1, len(stalls)-1):
if stalls[i] == 0:
distances = sidesSpaces(stalls, i)
minDistance = min(distances[0], distances[1])
maxDistance = max(distances[0], distances[1])
valuesFirst.append((minDistance, i, maxDistance))
valuesFirst.sort(key=lambda x: x[0], reverse=True)
#print values
maximum = valuesFirst[0][0]
j = 0
while j < len(valuesFirst) and valuesFirst[j][0] == maximum:
candidats.append(valuesFirst[j])
j += 1
if len(candidats) == 1:
stalls[candidats[0][1]] = 1
return candidats[0]
else:
candidats.sort(key=lambda x: x[2], reverse=True)
maximum = candidats[0][2]
j = 0
while j < len(candidats) and candidats[j][2] == maximum:
candidatsSecond.append(candidats[j])
j += 1
if len(candidatsSecond) == 1:
stalls[candidatsSecond[0][1]] = 1
return candidatsSecond[0]
else:
candidatsSecond.sort(key=lambda x: x[1], reverse=False)
stalls[candidatsSecond[0][1]] = 1
return candidatsSecond[0]
main("C-small-1-attempt1.in") |
f15e54b2ce69ff307ff4def68c7e280543f0f678 | w00tzenheimer/pythonformatter | /tests/test_continue/input.py | 137 | 3.703125 | 4 | a = 0
b = 0
while a > 10:
if a > b + 10:
break
elif b > 100:
continue
a = a + 1
else:
b = 100
|
d18494d6550c762c0c627c64b69a9cf1af168fa6 | shanJoy/python_work | /09-类/9_test2.py | 4,912 | 3.921875 | 4 | __Author__ = "noduez"
# 9-6冰淇淋小店
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.name.title()+' ' +self.cuisine_type)
def open_restaurant(self):
print("It's opening!")
def set_number_served(self, num):
self.number_served = num
def increment_number_served(self, num):
self.number_served += num
class IceCreamStand(Restaurant):
def __init__(self,name,cuisine_type='ice_cream'):
super().__init__(name,cuisine_type)
self.flavors = []
def show_flavors(self):
print("\nThe IceCreamStand's flavors: ")
for fla in self.flavors:
print(fla.title())
bigOne = IceCreamStand('The Big One')
bigOne.flavors = ['vanilla', 'chocolate', 'black cherry']
bigOne.describe_restaurant()
bigOne.show_flavors()
# 9-8权限 - 将实例用作属性
class Privileges():
def __init__(self, privileges=['can add post', 'can delete post', 'can ban user']):
self.privileges = privileges
def show_privileges(self):
print('\nAdmin have these privileges: ')
for privilege in self.privileges:
print(privilege)
#9-7 管理员
class User():
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0
def describe_user(self):
print(self.first_name.title() +' '+ self.last_name.title())
def greet_user(self):
print('How are you doing?')
def increment_login_attemps(self):
self.login_attempts += 1
def rest_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self,first_name, last_name):
super().__init__(first_name, last_name)
self.privileges = Privileges()
admin = Admin('tom', 'alun')
# admin.show_privileges()
admin.privileges.show_privileges()
#9-9 电瓶
class Car():
"""A simple attempt to represent a car."""
def __init__(self, manufacturer, model, year):
"""Initialize attributes to describe a car."""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
class Battery():
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=60):
"""Initialize the batteery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 60:
range = 140
elif self.battery_size == 85:
range = 185
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
"""Upgrade the battery if possible."""
if self.battery_size == 60:
self.battery_size = 85
print("Upgraded the battery to 85 kWh.")
else:
print("The battery is already upgraded.")
class ElectricCar(Car):
"""Models aspects of a car, specific to electric vehicles."""
def __init__(self, manufacturer, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(manufacturer, model, year)
self.battery = Battery()
print("Make an electric car, and check the battery:")
my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.battery.describe_battery()
print("\nUpgrade the battery, and check it again:")
my_tesla.battery.upgrade_battery()
my_tesla.battery.describe_battery()
print("\nTry upgrading the battery a second time.")
my_tesla.battery.upgrade_battery()
my_tesla.battery.describe_battery()
|
2569e495f5b8ab05096d524fab7795bc50b12947 | sarat21/Projects-in-Python | /Project2/HW6_sarat.py | 8,948 | 4.3125 | 4 |
# import the functions used from their modules
# this does NOT import the entire module but only specific functions! However,
# it imports them directly into the current name space so you don't have to
# call them with their module name in front, e.g. isdir() instead of os.path.isdir()
# if you want to use other functions defined in os or os.path, add them
# to the imports listed below in the same way.
from glob import glob
from os.path import exists, isdir, isfile, getsize, basename, join, split
from os import sep, getcwd, walk, listdir, chdir
"""
Problem 1
Define a function get_folder_names() that asks the user to enter the names of two folders as strings.
Check that folder1 and folder2 are valid sub-folders within the
current folder, i.e. it exists and that it is a folder, not a file; and that both are not the same
If one or both do not exist, go back and have the user re-enter the sub-folder names.
If the names for both folder are valid, return them inside a list
[ 2 pts ] Prompt the user for the folder names
[ 2 pts ] Check that folder1 and folder2 are valids ub-folders within the current folder
"""
def get_folder_names():
#Shows the user the content of the current folder.
#Asks the user to enter the names of the first and the second folder (must be different!)
#If those names are in facts folders inside the current folder (they could be files or not exist at all!),
#the two names are returned inside a list. In any other case, have the user repeat the input
#(you can be brutal and just demand both of them again, even if one of them is actually ok ...)
#Note that getcwd() return the full (absolute) path of a folder, but glob("*") will return the folder's
#content as relative paths!
# List current files and folders in the current folder ("*" matches everything)
print "The current folder is", getcwd() # getcwd() returns the path to the current folder
files_and_folders = glob("*") # glob("*") will return a list of (relative) file/folder names, not their absolute path!
print "It contains:\n", files_and_folders
# Get user input
print "Enter the name of two folders in the current folder:"
folder1 = raw_input("First folder: ") # get input from the user (raw_input)
folder2 = raw_input("Second Folder: ") # get input from the user (raw_input)
# check if folder1 and folder2 are valid sub-folders within the current folder (files_and_folders):
# a) check that each of them actually exists (potential user error)
while (exists(folder1) is False) or (exists(folder2) is False) :
if exists(folder1) is False:
folder1 = raw_input("Folder 1 does not exist. Enter First Folder name again: ")
if exists(folder2) is False:
folder2 = raw_input("Folder 2 does not exist. Enter Second Folder name again: ")
# b) check that each of them is a folder, not a file
while (isdir(folder1) is False) or (isdir(folder2) is False):
if isdir(folder1) is False:
folder1 = raw_input("Folder 1 is not a folder. Enter First Folder name again: ")
if isdir(folder2) is False:
folder2 = raw_input("Folder 2 is not a folder. Enter Second Folder name again: ")
# c) check that they are not equal (i.e. that they are not same folder), again, potential user error
while folder1 == folder2:
print "First and Second Folder names are equal. Enter the name of two folders in the current folder, again:"
folder1 = raw_input("First folder: ")
folder2 = raw_input("Second Folder: ")
while (isdir(folder1) is False) or (isdir(folder2) is False): #This check is required again to ensure that the entered folder names actually exist as folders
if isdir(folder1) is False:
folder1 = raw_input("Folder 1 is not a folder. Enter First Folder name again: ")
if isdir(folder2) is False:
folder2 = raw_input("Folder 2 is not a folder. Enter Second Folder name again: ")
#A second check, similar to part(b) is required in part(c) to ensure that the function accepts ONLY those folder names which actually exist.
#In this code, the user has to re-enter only the folder name which is invalid.
#So I'm not being brutal!
# if there's a problem, give feedback to the user and have the user enter both again.
# (yes, you can make it simple on yourself and ask to re-enter both, even if one
# imput was in fact valid ...)
# Now that you're sure that folder1 and folder2 are valid, return them inside a list (or tuple)
return [folder1, folder2]
"""
Problem 2
Define a function get_dups(folder1, folder2) that returns a list
of duplicate filnames in folder1 and folder2, e.g. here
get_dups("folderA", "folderB") should returns ["B.txt", "C.txt"].
Remember that you can use split() (os.path.split()) to split a full path
c:\HW6\folder1\A.txt into a folder part (c:\HW6\folder1) and a file part (A.txt)
and that you should glue together path names using + and os.sep (<- has the correct slash)
[ 8 pts ]
"""
def get_dups(folder1, folder2):
## folder1 and folder2 are names of subfolder within the current folder
## ex: "folderA" and "folderB"
## make a list of strings containing the filenames of the files in each folder
## ex: files_in_folder1 would contain ["A.txt", "C.txt"]
## files_in_folder2 would contain ["A.txt", "B.txt"]
## create and return a list that contains duplicates:
## ex: duplicate_files would contain ["A.txt"]
## note: you can use in to test: "bla" in ["whatever", "stuff", "bla"] => true
## for extra credit, also test for equal file size in bytes
# ???
files_in_folder1 = listdir(folder1) #List of files in folder1
files_in_folder2 = listdir(folder2) #List of files in folder2
#To ensure that only file names are present in the list files_in_folder1
chdir(folder1) #Moving into folder1
f1path = getcwd()
i=0
while i<len(files_in_folder1):
if isfile(files_in_folder1[i]) is False:
del files_in_folder1[i]
i += 1
#In the above piece of code, if the list element is NOT a file, but a folder, then it is deleted from the list since we are looking only for matching files and not for folders
chdir("..") #Moving back to the parent folder
chdir(folder2) #Moving into folder2
f2path = getcwd()
#To ensure that only file names are present in the list files_in_folder2
i=0
while i<len(files_in_folder2):
if isfile(files_in_folder2[i]) is False:
del files_in_folder2[i]
i += 1
#To check for duplicates and make a list of duplicates
chdir("..")
duplicate_files = [x for x in files_in_folder1 for y in files_in_folder2 if x==y and getsize(f1path + sep + x)==getsize(f2path + sep + y)]
#The above code uses list comprehension to create a list of all elements which are present in both files_in_folder1 as well as files_in_folder2, only if they have the same name AND the same file size.
#Solution for Problem 3 is incorporated in this code.
return duplicate_files
# ---------------------------- MAIN part --------------------------------
# Note: I have hardcoded folder1 and folder2 to specific names to get you started,
# however, once you've defined it, you'll need to replace the following 2 lines with
# a way of setting folder1 and folder2 via your get_folder_names() !
# get user input
folder_names = get_folder_names() # uncomment after you've completed the get_folder_names() function
folder1 = folder_names[0] #Extracting name of folder1 from the returned value from the function get_folder_names()
folder2 = folder_names[1] #Similarly, for folder2
# run get_dups() with the two subfolders
dups = get_dups(folder1, folder2)
# Print out those files that occur in both folders:
print folder1, "and", folder2, "contain these duplicate files:"
for fname in dups:
print fname,
print
"""
Problem 3
Optional: Using getsize(), refine your get_dups() function so that files only
count as duplicates if they also have the same size (in bytes).
[ +3 pts ]
"""
#Solution for this Problem incorporated in code for get_dups() above.
[ +5 pts ]
"""
# function to return the cummulative size of all files inside all sub-folders in bytes
def get_total_size(folder):
total_size_in_bytes = 0
# ???
# add up sizes of single files into total_size_in_bytes
return total_size_in_bytes
|
5898494cb1ed8c81b8a955fec3d2e44a674f070b | ThomasLEBRET/programmation_etudes-sup | /BTS-SIO/algorithme/1ère année/TP6-Matrices/exercice1.py | 314 | 3.59375 | 4 | def creerMatrice(n,p):
mat = []
for i in range(0,n):
mat.append([])
for j in range(0,p):
mat[i].append(0)
return mat
def creerMatriceDeux(n,p):
return [[0 for j in range (n)]for i in range(p)]
mat = creerMatrice(3,3)
mat2 = creerMatriceDeux(3,3)
print(mat)
print(mat2)
|
df5add8b164f8cb92e133b49a27cdbe8b3cfddd2 | mukosh123/Day1_Exercises | /fizz.py | 194 | 3.71875 | 4 |
def fizz_buzz(no):
if no % 3 == 0:
if no % 5 == 0:
return "FizzBuzz"
return "Fizz"
elif no % 5 == 0:
return "Buzz"
else:
return no
|
e3e39d38e961bfd599dfa1e4b52b70c3ecd706a4 | RuzimovJavlonbek/qudrat-abduraximovning-kitobidagi-masalalarni-pythonda-ishlanishi | /if30/if_10.py | 236 | 3.671875 | 4 | a = int(input("A butun Sonni kiriting: A = "))
b = int(input("B butun Sonni kiriting: B = "))
if a != b:
c = a+b
a = c
b = c
print("A = ", a , "B = ", b)
elif a==b:
a = 0
b = 0
print("A = ", a, "B = ", b)
input()
|
abe2952778b63ef362a8e1773cbac7545df8bf35 | pkulkar/Leetcode | /Python Solutions/897. Increasing Order Search Tree.py | 1,573 | 3.90625 | 4 | """
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
Constraints:
The number of nodes in the given tree will be between 1 and 100.
Each node will have a unique integer value from 0 to 1000.
"""
"""
Time Complexity: O(n)
Space Complexity: O(h) where h is height of the tree
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
nodes = list()
self.inorder(root, nodes)
preNode = TreeNode(-1)
root = preNode
for node in nodes:
if node:
preNode.right = TreeNode(node.val)
preNode = preNode.right
return root.right
def inorder(self, root, nodes):
if not root:
return
nodes.append(self.inorder(root.left, nodes))
nodes.append(root)
nodes.append(self.inorder(root.right, nodes)) |
eb6374561baec47b544ac8adb7c52501829e1d69 | daniel-reich/ubiquitous-fiesta | /DjyqoxE3WYPe7qYCy_21.py | 95 | 3.640625 | 4 |
def reverse_odd(txt):
return ' '.join([s[::-1] if len(s)%2 else s for s in txt.split()])
|
66f68d6b3d082e2953167730ad871656d2b476f5 | Aakashdeveloper/python-web | /session8_numpy.py | 97 | 3.609375 | 4 | import numpy as np
a = np.array([[1,2,3],['A','B','C']])
print(a)
print(a.shape)
print(a[1,1])
|
03039c5a13a501922437ad68ea07103cc03c3c63 | kajrud/Python-kurs-iSA | /Homeworks/Day 02/ex_02.py | 405 | 4 | 4 | # Napisz program do przeliczania stopni Fahrenheita na Celsjusza (wyświetlając wzór i kolejne obliczenia)
print("""Aby przeliczyć stopnie Fahrenheita na stopnie Celsjusza należy użyć wzoru:
T(cel) = 5 / 9 *(T(fah) - 32).
Ale od czego jest komputer...""")
far = float(input("Podaj temperaturę w stopniach Fahrenheita: "))
cel = 5 / 9 * (far - 32)
print ("W stopniach Celsjusza to ", cel, "stopni") |
c604ec22ab1973c692a01568484ebc1e1ed2c013 | rhzx3519/leetcode | /python/1329. Sort the Matrix Diagonally.py | 843 | 3.71875 | 4 | class Solution(object):
def diagonalSort(self, mat):
"""
:type mat: List[List[int]]
:rtype: List[List[int]]
"""
m, n = len(mat), len(mat[0])
starts = [(i, 0) for i in range(m-1, -1, -1)] + [(0, j) for j in range(1, n)]
for x, y in starts:
i, j = x, y
a = []
while i < m and j < n:
a.append(mat[i][j])
i += 1
j += 1
a.sort()
i, j = x, y
k = 0
while i < m and j < n:
mat[i][j] = a[k]
k += 1
i += 1
j += 1
return mat
# 思路:寻找斜对角遍历的所有起点
if __name__ == '__main__':
mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
su = Solution()
su.diagonalSort(mat)
|
688d88333d7b4d91729f2815d22e75f836032560 | Dpp3a/CSHL_PFB | /Py4/start_end_range.py | 427 | 3.953125 | 4 | #!/usr/bin/env python3
#script that takes the start and end values from the command line. If you call your script like this count.py 3 10 it will print the numbers from 3 to 10
import sys
start_num = int(sys.argv[1])
end_num = int(sys.argv[2])+1
for num in range (start_num, end_num):
if num%2==0:
print(num)
|
77baeecb49652bf0027b1e1a1bfce6d650ce80de | fabiocoutoaraujo/CursoVideoPython | /mundo-01/aula10-ex033.py | 375 | 3.96875 | 4 | n1 = float(input('Digite o 1º número: '))
n2 = float(input('Digite o 2º número: '))
n3 = float(input('Digite o 3º número: '))
maior = n1
menor = n1
if n2 > n1:
maior = n2
if n3 > maior:
maior = n3
if n2 < n1:
menor = n2
if n3 < menor:
menor = n3
print('O menor valor digitado é {}'.format(menor))
print('O maior valor digitado é {}'.format(maior))
|
bed628af023416e2c68946fc1d45cf8e692fb523 | gautamgitspace/Beginning-with-Python-Scripting | /tuples.py | 1,233 | 4.3125 | 4 | #tuples are like lists but are immutables like strings
#things you can't do to tuples: modify, sort, append, reverse
#tuples are comparable
tupA=tuple
print dir(tupA)
x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
y = x.items()
print y
tupA = (0,1,2)
tupB = (0,1,2)
print tupB
if tupA < tupB:
print 'true'
else:
print 'false'
#sorting list of tuples: key sorted
d = dict()
m = list()
d = {'z': 10, 'b': 20, 'a': 4}
print '\nKey Value Pairs in dict: '
for k, v in d.items():
print k, v
print '\nKey Sorted Order: '
for k, v in sorted(d.items()):
print k, v
#sorting list of tuples: value sorted
for k,v in d.items():
m.append((v,k))
print ('\nValue Sorted Order: ')
print 'unsorted: ', m
m.sort(reverse=True)
print 'sorted: ', m
#print top 10 most common words in romeo.txt
d=dict()
l=list()
fileName = raw_input('Enter the name of the file: ')
fileHandle = open(fileName)
for line in fileHandle:
words=line.rstrip()
l=words.split()
for iterator in l:
d[iterator]=d.get(iterator,0)+1
for key, value in d.items():
l.append((value,key))
l.sort(reverse=True)
for value, key in l[:10]:
print key, value
#shorter version:
print sorted([(value, key) for key, value in d.items()]) |
e32ed23b1854f1f621011a5a44d1be48b6f4e151 | Ankan07/LeetCode | /986.py | 983 | 3.5625 | 4 | from typing import Any, List
import math
class Solution:
def __init__(self) -> None:
pass
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
firstList.sort()
secondList.sort()
first_length = len(firstList)
second_length = len(secondList)
i = 0
j = 0
result = []
while i < first_length and j< second_length:
result.append(self.find_interval(firstList[i],secondList[j]))
j=j+1 if firstList[i][1] >= secondList[j][1] else i=i+1
return result
def find_interval(self,first,second) -> List[int]:
a = -math.inf
b = +math.inf
if first[0] >= second[0]:
a = first[0]
else:
a = second[0]
if first[1] <= second[1]:
b = first[1]
else:
b = second[1]
if a<=b:
return [a,b]
else:
return[]
|
00405aa9b9795de005b6e23a814cb4cb93da5b88 | RedwanQ/basicpython3 | /mathhw.py | 369 | 4.1875 | 4 | import math
#
def sq():
width = int(input('Enter the Width'))
length = int(input('Enter the Length'))
area = width * length
print(f'the square footage of a house is {area} ')
# Circumference of circle
def cir():
radius = float(input('Enter the raduis of your circle'))
C = 2*math.pi*radius
print(f'Cirumference of circle is {C}')
|
d89aa33587255e2786ca2be259af450d4414252c | yinglin33/calendarocr | /convertToCalendar.py | 6,641 | 3.59375 | 4 | import datetime
from PIL import Image
import re
'''
Takes a string (cal) and looks for month, date, time, and event name in the string. Returns a string
containing the event name and Datetime object containing the month, date, time.
'''
'''
TODO change convertToCalendar so it returns the time interval of the event
todo account for leap years for feburary
might be a good idea to remove spaces from string to help with processing
'''
def convertToCalendar(cal):
#lists containing date keywords
monthShort=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
dates =[31,28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
monthLong = ["january","february","march","april","may","june","july","august","september","october","november","december" ]
days = [" mon", " tues", " wed", " thur", " fri"]
#list containing regex expressions for dates in the form of XX/XX/XXXX
possibleDateRegex = ["[0-1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]", "[1-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]", "[0-1][0-9]/[1-9]/[0-9][0-9][0-9][0-9]", "[1-9]/[1-9]/[0-9][0-9][0-9][0-9]", "[0-1][0-9]/[0-3][0-9]/[0-9][0-9]", "[1-9]/[0-3][0-9]/[0-9][0-9]", "[0-1][0-9]/[1-9]/[0-9][0-9]", "[1-9]/[1-9]/[0-9][0-9]", "[0-1][0-9]/[0-3][0-9]", "[1-9]/[0-3][0-9]", "[0-1][0-9]/[1-9]", "[1-9]/[1-9]" ]
#Creates datetime object based on today's time
today = datetime.datetime.today()
# made default datetime object using today's time
#the parameters are year, month, day, hour, minutes, seconds
Calendar= datetime.datetime(today.year, today.month, today.day, 0, 0, 0)
#default event name
eventName = cal
#tracks if the date is in regex form or XX/XX/XXXX
dateNotRegex = True
index= -1
#Tracking these indexes to eventually determine the event name
calDelIndex = -1
dateDelIndex= -1
yearDelIndex = -1
timeIndex = -1
day_index = -1
#searches for matches from possibleDateRegex backwards.
#This is because regex's at the end of the list are substrings of regex's at the beginning
for i in range( len(possibleDateRegex)-1, -1, -1):
x = re.findall(possibleDateRegex[i], cal)
if len(x) != 0:
calDelIndex = cal.find(x[0])
dateDelIndex = cal.find(x[0])
dateNotRegex = False
info=[]
#splits the match into month, day, year
info=x[0].split("/")
#replaces month and day
Calendar = Calendar.replace(month = int(info[0]))
Calendar = Calendar.replace(day = int(info[1]))
# replaces year based on if year was represented with 4 numbers or 2 numbers
# ex : 1/1/2021 vs 1/1/21
# if there was no year in the date year stays the same
if len(info) == 3 and len(info[2]) == 4:
Calendar = Calendar.replace(year = int(info[2]))
elif len(info) == 3 and len(info[2]) == 2:
Calendar = Calendar.replace( year = ((Calendar.year // 100)*100 + int(info[2])))
# if date was found in regex no need to look for month or day
if dateNotRegex:
#searches for the month in the string using monthShort
for i in range(len(monthShort)):
#convert string to lowercase before searching for months
calDelIndex = cal.lower().find(monthShort[i])
calDelIndex2= cal.lower().find(monthLong[i])
#replace the month
if calDelIndex != -1:
Calendar = Calendar.replace(month=(i+1))
index=i
break
# looks for the day. If the date is 16 would find 1 first, but then find 16 later and day would be set to 16
for i in range(1,dates[index]+1):
#looks for dates with a space before and after or at the end or beginning of string
if cal.find(" "+str(i)+" ") != -1 or cal.find(" " + str(i)) != -1 and (cal.find(" "+str(i)) + 1 + len(str(i))) < len(cal) or cal.find(str(i)+" ") != -1 and (cal.find(str(i)+" ") + 1 + len(str(i))) < len(cal) :
#changes the day
Calendar = Calendar.replace(day=i)
dateDelIndex = cal.find(str(i))
#searches for the year starting from 2000
for i in range (2000, today.year+1):
yearDelIndex = cal.find(str(i))
if yearDelIndex != -1:
Calendar = Calendar.replace(year=i)
# looks for time by looking for pm and then am.
# if there are two times, currently this finds the start time.
# if there is a time at am and pm. It will choose the am as the start time.
if cal.lower().find("pm") != -1:
timeIndex = find_n(cal, ' ', cal.lower().find("pm"))
Calendar = Calendar.replace(hour=12)
if cal.lower().find("p.m") != -1:
timeIndex = find_n(cal, ' ', cal.lower().find("p.m"))
Calendar = Calendar.replace(hour=12)
if cal.lower().find("am ") != -1:
timeIndex = find_n(cal, ' ', cal.lower().find("am"))
Calendar = Calendar.replace(hour=0)
if cal.lower().find("a.m") != -1:
timeIndex = find_n(cal, ' ', cal.lower().find("a.m"))
Calendar = Calendar.replace(hour=0)
#checks if the time index is not out of bounds and string is numeric
if timeIndex != -1 and timeIndex < len(cal) and cal[timeIndex].isnumeric():
Calendar = Calendar.replace(hour = (Calendar.hour + int(cal[timeIndex])))
#searches for day
for day in days:
if cal.lower().find(day) != -1:
day_index = cal.lower().find(day)
#sets the eventName to the shortest string created from cal using the various indexes
if timeIndex >= 0 and len(cal[:timeIndex]) < len(eventName):
eventName=cal[0:timeIndex]
if calDelIndex >= 0 and len(cal[:calDelIndex]) < len(eventName):
eventName=cal[0:calDelIndex]
if yearDelIndex >= 0 and len(cal[:yearDelIndex]) < len(eventName):
eventName=cal[0:yearDelIndex]
if dateDelIndex >= 0 and len(cal[:dateDelIndex]) < len(eventName):
eventName=cal[0:dateDelIndex]
if day_index >= 0 and len(cal[:day_index]) < len(eventName):
eventName = cal[0:day_index]
return Calendar, eventName
# finds the instance of searchterm in bigstring that is before index n and the closest to index n
# returns the index of the searchterm
def find_n(bigstring, searchterm, n):
start = bigstring.find(searchterm)+1
while start >= 0:
temp = bigstring.find(searchterm, start+len(searchterm))
if n > temp and temp+1 != n and bigstring[temp+1] !=" ":
start = temp+1
else:
break
return start
|
1f59169032dcbea6c31ba8bd74f03368a7d8a39b | marcuscarr/UCB_cs61a | /hw/hw1/q4.py | 427 | 4.15625 | 4 | def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
steps = 1
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = (3 * n) + 1
print(n)
steps += 1
return steps
|
5e59675955ccee0ca942a8fad22ea010fef73709 | YoungWoongJoo/Learning-Python | /list/list5.py | 225 | 4 | 4 | """
numbers에 5가 들어있을때, "5가 있다"를 출력하도록 빈칸을 채워 보세요.
numbers = [1,2,3,4,5]
if ___ in ___:
print("5가 있다")
"""
numbers = [1,2,3,4,5]
if 5 in numbers:
print("5가 있다") |
6fdf57067a989749d9c8697a9929dc363679090f | bkelly1984/umba_trial | /generic_dao.py | 5,250 | 3.515625 | 4 | import logging
class GenericDao:
"""
This abstract class contains information and parameters to manipulate a database table.
Attributes:
GenericDao.table_name (str): the name of this table in the database.
GenericDao.columns (list): the names of the columns in this table.
GenericDao.column_types (list): the data types of the columns in this table.
GenericDao.primary_key_index (int): the index of the table primary key.
"""
@property
def table_name(self):
raise NotImplementedError
@property
def columns(self):
raise NotImplementedError
@property
def column_types(self):
raise NotImplementedError
@property
def primary_key_index(self):
raise NotImplementedError
def clear_table(self, db):
"""
Delete all records from the table.
Parameters:
db (Db): the database on which to operate.
Returns: None
"""
logging.info(f"Clearning {self.table_name} table")
db.cursor.execute(f"DELETE FROM {self.table_name}")
db.commit()
def create_or_clear_table(self, db):
"""
End with an empty table in the database regardless of starting state.
Parameters:
db (Db): the database on which to operate.
Returns: None
"""
if db.does_table_exist(self):
self.clear_table(db)
else:
db.create_table(self)
def get_count(self, db):
"""
Get the number of records for this table in the passed database.
Parameters:
db (Db): the database on which to operate.
Returns:
int: the number of records in the table.
"""
return db.cursor.execute(f"SELECT COUNT(*) FROM {self.table_name}").fetchone()[0]
def create(self, db, value_dict):
"""
Create a new record in this table on the passed database.
Parameters:
db (Db): the database on which to operate.
value_dict (dict): The values of the new record in order of columns
Returns: None
"""
# Check that we were passed a dict object
if not isinstance(value_dict, dict):
logging.error(f"create passed an object of type {type(value_dict)}")
return
# Create a list of new values in order of the table columns
value_list = []
for column_name in self.columns:
if column_name in value_dict:
value_list.append(value_dict[column_name])
else:
logging.warning(f"value_dict does not contain a value for field {column_name}")
value_list.append(None)
# Write a row to the database
sql_string = f"INSERT INTO {self.table_name} VALUES ({', '.join('?' * len(self.columns))})"
logging.debug(f"Executing create: {sql_string}")
db.cursor.execute(sql_string, value_list)
def read(self, db, offset, limit, sort_by, desc_flag=False):
"""
Read records in this table from the passed database and return them in a list.
Parameters:
db (Db): the database on which to operate.
offset (int): The number of records to skip before returning results
limit (int): The maximum number of records to return, capped by Db.max_limit
sort_by (string): The name of the column on which to sort
desc_flag (bool): Sort in descending order rather than ascending?
Returns:
list: A list of all the records found with the passed paramerers.
"""
# Check the passed offset and limit
if offset < 0:
logging.warning(f"invalid offset of {offset} for table {self.table_name}, setting to 0")
offset = 0
if limit < 0:
logging.warning(f"invalid limit of {limit} for table {self.table_name}, setting to 0")
limit = 0
elif limit > db.max_limit:
logging.warning(f"limit of {limit} exceeds maximum, setting to {db.max_limit} records")
limit = db.max_limit
# Set a default order_string
if not sort_by:
order_string = f"{self.columns[0]} ASC"
# Parse, verify, and convert the passed sort parameters
elif sort_by.lower() in self.columns:
if self.column_types[self.columns.index(sort_by.lower())] == "text":
order_string = f"LOWER({sort_by.lower()})"
else:
order_string = f"{sort_by.lower()}"
if desc_flag:
order_string = f"{order_string} DESC"
else:
order_string = f"{order_string} ASC"
else:
logging.warning(f"invalid sort_by column {sort_by} for table {self.table_name}")
order_string = f"{self.columns[0]} ASC"
# Build the SQL -- two layers so it can be filtered by result numbers
sql_string = f"SELECT {', '.join(self.columns)} FROM {self.table_name} ORDER BY {order_string} LIMIT ? OFFSET ?"
logging.debug(f"Executing read: {sql_string}")
return db.cursor.execute(sql_string, (limit, offset)).fetchall()
|
97cd6acbcd6cc51d12a95c6f575bbb128e6dad5e | shyams1993/caesars-cipher | /caesar_cipher.py | 6,500 | 4.40625 | 4 | import time,sys
encrypted_result=[]
decrypted_result=[]
def encrypt_caesar_cipher():
'''
DOCSTRING: Function to encrypt a given string using caesar cipher.
\nINPUT: Any string.
\nLOGIC: To encrypt, it uses the basic formula : (character + shift digits)
\nOUTPUT: The encrypted string result.
\n\nThis logic uses ASCII codes to convert the strings to integers. It uses Python's in-built ord() method.
\nFirst, we convert the input string to lower-case (since upper-case has a different set of ASCII Codes). To normalise, we convert input strings to lowercase.
\nThen,we get the number of digits that you want to shift. Then we read each letter in the word using a for loop.
\nWe calculate the shift character using the formula : (character + shift digits).
\nIf the values go more than the ASCII Code of 'z' (the last character in the alphabet,i.e. 122).
\nIf it does, minus the value with 122 & add the result with 96 (If the letter crosses z, loop back from a).
\nAppend it to the list
\nElse, print the character value of the word using Python's inbuilt method chr().
\nFinally, to print the string, join the individual characters of the list using join() and list comprehension for loop.
\nClear the list at the end otherwise, retrying will keep appending all old results to the list continuously.
'''
global encrypted_result
word = input("Enter a sentence to encrypt: ")
word = word.lower()
n = int(input("Enter the number of characters you want to shift: "))
for w in range(len(word)):
x = (ord(word[w]) + n)
if x > 122:
y = (x-122)+96
encrypted_result.append(chr(y))
elif ord(word[w]) == 32:
y = 32
encrypted_result.append(chr(y))
else:
encrypted_result.append(chr(x))
print("\nThe encrypted result is",''.join([str(s) for s in encrypted_result]))
encrypted_result.clear()
retry()
def decrypt_caesar_cipher():
'''
DOCSTRING: Function to decrypt a given string using caesar cipher.
\nINPUT: Any string.
\nLOGIC: To decrypt, it uses the basic formula : (character + shift digits)
\nOUTPUT: The decrypted string result.
\n\nThis logic uses ASCII codes to convert the strings to integers. It uses Python's in-built ord() method.
\nFirst, we convert the input string to lower-case (since upper-case has a different set of ASCII Codes). To normalise, we convert input strings to lowercase.
\nThen,we get the number of digits that you want to shift. Then we read each letter in the word using a for loop.
\nWe calculate the shift character using the formula : (character - shift digits).
\nIf the values go more than the ASCII Code of 'a' (the first character in the alphabet,i.e. 96). First letter because we're going in reverse.
\nIf it does, minus the value with 96 & add the result with 122 (If the letter crosses a, loop back from z).
\nAppend it to the list
\nElse, print the character value of the word using Python's inbuilt method chr().
\nFinally, to print the string, join the individual characters of the list using join() and list comprehension for loop.
\nClear the list at the end otherwise, retrying will keep appending all old results to the list continuously.
'''
global decrypted_result
word = input("Enter a sentence to decrypt: ")
word = word.lower()
n = int(input("Enter the number of characters you want to shift: "))
for w in range(len(word)):
x = (ord(word[w]) - n)
if x>=70 and x < 97:
y = (x-96)+122
decrypted_result.append(chr(y))
elif ord(word[w]) == 32:
decrypted_result.append(chr(32))
else:
decrypted_result.append(chr(x))
decrypted_results = ''.join([str(s).capitalize() for s in decrypted_result])
print("\nThe decrypted result is",decrypted_results.capitalize())
decrypted_result.clear()
retry()
def bruteforce_caesarcipher_decrypter():
'''
DOCSTRING: Function to decrypt a given string that's encrypted using caesar cipher
when you don't know the number of shift digits it has been encrypted with
INPUT: Any string
OUTPUT: All possible decrypted string results from which you can choose the right string
'''
global decrypted_result,n,word
word = word.lower()
for w in range(len(word)):
x = (ord(word[w]) - n)
if x>=70 and x < 97:
y = (x-96)+122
decrypted_result.append(chr(y))
elif ord(word[w]) == 32:
decrypted_result.append(chr(32))
else:
decrypted_result.append(chr(x))
print("\nThe decrypted result is",''.join([str(s) for s in decrypted_result]))
decrypted_result.clear()
def cipher_game():
'''
DOCSTRING: Function to accept the user's choice of what they want to do: Whether they want to encrypt a string
or, decrypt a string encrypted string using Caesar's Cipher.
INPUT: Numeral choice of 1 (or) 2.
OUTPUT: Execution of Encryption program (or) Decryption program based on user's choice.
'''
global word,n
choice = int(input("What do you want to do?\n1.Encrypt using Caesar Cipher\n2.Decrypt an encrypted Caesar Cipher\n3.Decrypt a Caesar cipher using brute force\n\nNOTE: Use option 3 to decrypt a Caesar Cipher if you don't know the number of shift digits needed to decrypt.\nThis option loops through 1-26 and gives you all results.\nYou can choose the result that makes sense,from all the results.\n\n"))
if choice == 1:
encrypt_caesar_cipher()
elif choice ==2:
decrypt_caesar_cipher()
elif choice ==3:
word=input("Enter a sentence to decrypt: ")
for n in range(1,26):
bruteforce_caesarcipher_decrypter()
retry()
def retry():
'''
DOCSTRING: Function to accept user's choice whether they want to retry. If they do, it loops back to the main choice function.
INPUT: 'y' or anything else
OUTPUT: If 'y' then, loops back to main choice function - cipher_game() ; else, exits after waiting for 3 seconds
'''
ch=input("\nDo you want to try again?(y/n)\n")
if ch == 'y':
cipher_game()
else:
print("Exiting in 3 seconds...")
time.sleep(3)
sys.exit()
cipher_game()
|
a82fe6111311f4dd23abffd528c2115caffcde8a | hianjana/Disaster_Response_Pipeline_Project_Udacity | /data/process_data.py | 4,459 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # ETL Pipeline
#
# The intent of this notebook is to load the 2 files which have disaster response data: messages.csv, categories.csv, clean them, combine them and load it into a SQL database.
# **Sections:**
# 1. Load csv files
# 2. Data cleaning
# 3. Data merge
# 4. Load data to SQL database
# #### Import required libraries
# In[56]:
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
# ### 1. Load csv files
# In[57]:
def load_data(filepath):
'''
This fucntion will load data from CSV files
'''
df = pd.read_csv(filepath)
return df
# ### 2. Data cleaning
# In[58]:
def categories_cleaning(categories):
'''
This function will do the following:
Split the values in the categories column on the ; character so that each value becomes a separate column.
Use the first row of categories dataframe to create column names for the categories data.
Rename columns of categories with new column names.
'''
# create a dataframe of the 36 individual category columns
categories_split = categories['categories'].str.split(';', expand=True)
# select the first row of the categories dataframe
row = categories_split.iloc[0]
# use this row to extract a list of new column names for categories
category_colnames = [each[:-2] for each in row]
#print(category_colnames)
# rename the columns
categories_split.columns = category_colnames
for column in categories_split:
# set each value to be the last character of the string
categories_split[column] = categories_split[column].apply(lambda x: x[-1:])
# convert column from string to numeric
categories_split[column] = categories_split[column].astype('int')
categories_split['related'].replace({2: 1}, inplace=True)
categories_clean = categories.merge(categories_split, left_index=True, right_index=True, how='inner')
# drop the original categories column
categories_clean.drop(['categories'], axis=1,inplace=True)
return categories_clean
# ### 3. Data merge
# In[59]:
def data_merge(messages, categories_clean):
'''
This function will merge the messages and cleaned categories datasets
'''
df = pd.merge(messages, categories_clean,on='id')
# drop duplicates
df.drop_duplicates(inplace=True)
return df
# ### 4. Load data to SQL database
# In[60]:
def load_into_sql(df, database_filepath):
'''
This function will load the datafame to a SQL database
'''
db = 'sqlite:///' + database_filepath
# Extract database name from the database path
pos = database_filepath.rindex('/') # Find the position of the last occurance of "/"
db_nm = database_filepath[pos+1:]
db_name = db_nm.replace('.db', '')
print('DB path: ', db)
print('DB name: ', db_name)
engine = create_engine(db)
df.to_sql(db_name, engine, index=False, if_exists='replace')
print('Data load complete!')
# In[61]:
def main():
'''
This is the main function which calls all other functions to load data from the CSV files, clean them, merge them and
load it back to a SQL database.
'''
if len(sys.argv) == 4:
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
# Load the messages dataset
messages = load_data(messages_filepath)
# Load the categories dataset
categories = load_data(categories_filepath)
# Clean the categories dataset and split the 'categories' column into individual columns per category
categories_clean = categories_cleaning(categories)
# Merge the cleaned categories dataset and messages dataset
df = data_merge(messages, categories_clean)
# Load to a SQL database
load_into_sql(df, database_filepath)
else:
print('Please provide the filepaths of the messages and categories '\
'datasets as the first and second argument respectively, as '\
'well as the filepath of the database to save the cleaned data '\
'to as the third argument. \n\nExample: python process_data.py '\
'disaster_messages.csv disaster_categories.csv '\
'DisasterResponse.db')
# In[63]:
if __name__ == '__main__':
main()
# In[ ]:
|
f5fc349ae2db6e1d1c2eb6b0a7c4b3ee6b2f7fb5 | Npurdie/lab2 | /processing.py | 2,572 | 3.5625 | 4 | def to_bin(fractional):
fraction = float('0.' + fractional)
binary = ''
while(fraction != 0.0):
fraction = fraction * 2
if (fraction < 1):
binary = binary + '0'
else:
binary = binary + '1'
fraction = fraction - 1
return binary
def to_twos_comp(word, word_precision, fractional, fractional_precision):
p = '0' + str(word_precision) + 'b'
converted = bin(int(word) % (1 << word_precision))
binary = format(int(converted, 2), p)
while (len(fractional) < fractional_precision):
fractional = fractional + '0'
return binary + fractional
def calculatePrecision(values):
word_precision = 1
fractional_precision = 0
for i in range(len(values)):
word = len(bin(int(values[i][2]))) - 1 # precision of decimal
fractional = len(to_bin(values[i][3])) # precision of fraction
if (word > word_precision): word_precision = word
if (fractional > fractional_precision): fractional_precision = fractional
return word_precision, fractional_precision
def calculateTwosComplements(values, word_precision, fractional_precision):
output = []
for i in range(len(values)):
output.append(to_twos_comp(values[i][1] + values[i][2], word_precision, to_bin(values[i][3]), fractional_precision))
return output
def writeOutput(output_values, filename):
output = ''
for i in range(len(output_values)):
output = output + output_values[i] + '\n'
writer = open(filename, 'w')
writer.write(output)
def vectorize(values, string):
for i in range(0, len(string)-1):
value = string[i]
vector = ['1', '', '0', '0']
vector[0] = value
if (value[0] == '-'):
value = value.replace('-', '')
vector[1] = '-'
split = value.split('.')
vector[2] = split[0]
if (len(split) == 2):
vector[3] = split[1]
values.append(vector)
x_values = []
y_values = []
vectorize(x_values, open('lab2-x.txt', 'r').readlines()[0].split(' '))
vectorize(y_values, open('lab2-y.txt', 'r').readlines()[0].split(' '))
w_x, f_x = calculatePrecision(x_values)
w_y, f_y = calculatePrecision(y_values)
print('Word Precision x : ' + str(w_x))
print('Fractional Precision x: ' + str(f_x))
print('Word Precision y : ' + str(w_y))
print('Fractional Precision y : ' + str(f_y))
writeOutput(calculateTwosComplements(x_values, w_x, f_x), 'lab2-x-fixed-point.txt')
writeOutput(calculateTwosComplements(y_values, w_y, f_y), 'lab2-y-fixed-point.txt')
|
ef108e44133cd0ea567bcdea04d3aa08ffeb2a25 | humachine/AlgoLearning | /leetcode/Done/71_SimplifyPath.py | 1,351 | 3.828125 | 4 | #https://leetcode.com/problems/simplify-path/
''' Given a Unix-style path, simplify it.
Inp: "/home/"
Out: "/home"
Inp: "/a/../b/../../c/"
Out: "/c" (From directory /, /a + .. + /b + .. brings us back to / and / + .. -> / and lastly / + /c brings us to /c)
'''
class Solution(object):
def simplifyPath(self, path):
# We first get a list of directory changes that is present in this path by splitting on '/'
# We ignore any splits that are = '.' (/abc/./def/ghe) to ignore the ./ of current directory
# We also ignore any empty splits which happen when we have multiple consecutive / together
dirs = [pt for pt in path.split('/') if pt not in ['.', '']]
st = []
# We build a stack of directories. Every time we see a directory, we go deeper a level into the file system. Every time we see a '..', we pop the stack thereby going back a level lower.
for dir in dirs:
if dir == '..':
if len(st)>0:
st.pop()
else:
st.append(dir)
# Finally, we return / + all the relevant directories slash-separated
return '/' + '/'.join(st)
s = Solution()
print s.simplifyPath("/a/../b/../../c/")
print s.simplifyPath("/../")
print s.simplifyPath("/a///.b/c/")
print s.simplifyPath("/..")
|
8b632abb6c668b0c9163cdffe0e2bb2bf774b126 | charles-wangkai/exercism | /python/rotational-cipher/rotational_cipher.py | 253 | 3.640625 | 4 | import string
def rotate(text, key):
return text.translate(str.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[0:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[0:key])) |
563c7188f39af90c2b8dde732789416a10c59517 | lollipopnougat/AlgorithmLearning | /力扣习题/538把二叉搜索树转换为累加树/problems.py | 2,928 | 3.75 | 4 | import math
from typing import Optional
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
return self.helper(root, 0)
def helper(self, root: Optional[TreeNode], addVal: int) -> Optional[TreeNode]:
if root:
rt = self.helper(root.right, addVal)
val = self.rightMax(rt)
if val == 0:
val = addVal
val += root.val
lt = self.helper(root.left, val)
node = TreeNode(val, lt, rt)
return node
return None
def rightMax(self, root: Optional[TreeNode]) -> int:
if root:
if root.left:
return self.rightMax(root.left)
else:
return root.val
return 0
class Solution2:
'''
暂存大法
'''
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.res = []
self.lrr(root)
n = len(self.res)
for i in range(n - 2, -1, -1):
self.res[i].val += self.res[i + 1].val
return root
def lrr(self, root: TreeNode):
if root:
self.lrr(root.left)
self.res.append(root)
self.lrr(root.right)
def check_tree(root: TreeNode):
if root:
if root.left and not root.left.val:
root.left = None
if root.right and not root.right.val:
root.right = None
if root.left:
check_tree(root.left)
if root.right:
check_tree(root.right)
def build_tree(li: list) -> TreeNode:
root = TreeNode(None)
queue = [root]
le = len(li)
layers = math.ceil(math.log(le + 1, 2))
limits = 2**(layers - 1) - 1
i = 0
while i < le:
t = queue.pop(0)
if li[i]:
t.val = li[i]
if i < limits:
t.left = TreeNode(None)
t.left.parents = t
t.right = TreeNode(None)
t.right.parents = t
queue.append(t.left)
queue.append(t.right)
i += 1
check_tree(root)
return root
def levelOrder(root: TreeNode) -> List[List[int]]:
if root == None:
return []
cur = [root]
result = []
while len(cur):
culen = len(cur)
tmp = []
for i in range(culen):
p = cur.pop(0)
if p:
tmp.append(p.val)
cur.append(p.left)
cur.append(p.right)
if len(tmp):
result.append(tmp)
return result
t = [4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8]
tree = build_tree(t)
s = Solution()
res = s.convertBST(tree)
rr = levelOrder(res)
print(rr) |
d2b06c8b312750994e75deb16c9a3c748a960df8 | xinghalo/DMInAction | /src/basic/07string.py | 240 | 3.8125 | 4 | var1 = 'hello'
var2 = 'world'
print(var1[0])
print(var2[1:5])
# 输出原始字符串
print(r'hello\n')
# 格式化字符串
str1='''
hello
nijhao
'''
print(str1)
# 内建函数
# print(capitalize('hello'))
# center()
# count('hello')
|
34c4fda378bc4a4f80c937232364224088076f79 | magedu-pythons/python-25 | /25009-qinzhichao/week-2/fib2.py | 145 | 3.59375 | 4 | def fib(a,b):
return a+b
a=0
b=1
print(a)
print(b)
for c in range(0,100):
c=a+b
if c>100:
break
print(c)
a=b
b=c
|
a79595e626088bef4bb095a10dcb5fa8ab0c9a37 | mavenskylab/TechnicalAnalysis | /plot_line.py | 869 | 3.59375 | 4 | import matplotlib.pyplot as plt
def plot_line(df):
"""Graph: Plot close with indicators"""
plt.plot(df.index, df['close'])
for col in df.columns:
if col not in ['open', 'high', 'low', 'volume']:
plt.plot(df.index, df[col], label=col)
plt.ylabel("Price")
plt.xlabel("Date")
plt.legend()
plt.show()
plot_line.__doc__ = \
"""
Grpahs the closing price along side other indicators included in the
pandas dataframe. Ignores open, high, low and volume columns.
Sources:
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
Method:
plt.plot(df.index, df['close'])
for col in df.columns:
if col not in ['open', 'high', 'low', 'volume']:
plt.plot(df.index, df[col], label=col)
Params:
df (Pandas Dataframe): Dataframe of ohlc and indicator data
Returns:
None
""" |
328dbb13e3d3bc8c5480502983b22796b43a325b | Haugen/python-fun | /simplified-fractions.py | 547 | 3.953125 | 4 | # https://edabit.com/challenge/vQgmyjcjMoMu9YGGW
# Simplified Fractions
def simplify(txt):
n,d = map(int, txt.split('/'))
result = ""
while True:
for i in reversed(range(2, int(n)+1)):
if (d/i).is_integer() and (n/i).is_integer():
n = n/i
d = d/i
break
break
if n > d and (n/d).is_integer():
result = str(int(n/d))
else:
result = "/".join([str(int(n)),str(int(d))])
print(result)
simplify("4/6") # "2/3"
simplify("10/11") # "10/11"
simplify("100/400") # "1/4"
simplify("8/4") # "2" |
f34d2c70aea11dfb75123dbc93c45cfd2dfe1d5f | lincolen/Python-Crash-Course | /7 input and while/seating.py | 195 | 3.75 | 4 | party_size = input("nannmei sama desu ka: " )
party_size=int(party_size)
if party_size<=8 and party_size>0:
print("te-buru ni goannai shimasu")
elif party_size>8:
print("shosho omachikudasai")
|
42a417e4ed9f75eba7431c572ed15ac45767d491 | jmabf/uri-python | /2029.py | 273 | 3.53125 | 4 | while True:
try:
v = float(input())
d = float(input())
r=d/2
pi=3.14
ar=(r**2)*pi
h=v/ar
print('ALTURA = {:.2f}'.format(h))
print('AREA = {:.2f}'.format(ar))
except EOFError:
break
|
e256bad7d1ae7b0684403508a7f28d8942d9141f | KuanTingLin/TibaMe_CFI101 | /test.py | 2,162 | 3.53125 | 4 | import sys
from datetime import datetime, timedelta
import time
import os
from test.test_file import current_file_dir
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-g',
'--group',
help='Type of mail',
dest='group',
type=str,
default='C0203000063')
parser.add_argument('-t',
'--time',
help='due time',
dest='due_time',
type=str)
parser.add_argument('-s',
'--seconds',
help='seconds of countdown',
dest='seconds',
type=int)
def clock(due_time, fmt="%Y-%m-%d %H:%M:%S"):
"""
:param due_time: str or datetime object, example: 2020-09-26 11:02:11
:param fmt: str
:return:
"""
if isinstance(due_time, str):
due_time = datetime.strptime(due_time, fmt)
elif isinstance(due_time, datetime):
pass
else:
return False
if due_time < datetime.today():
return False
while due_time.strftime("%H:%M:%S") > datetime.today().strftime("%H:%M:%S"):
today = datetime.today()
delta_seconds = (due_time - today).seconds
if (delta_seconds <= 10):
print("\r",
"現在時間為:",
today.strftime("%H:%M:%S"),
"距離目標時間",
due_time.strftime("%H:%M:%S"),
"剩餘 {} 秒鐘".format(str(delta_seconds).zfill(2)), end="")
time.sleep(1)
print()
print("Ring~~~~~")
def countdown(second=0, minute=0, hour=0):
total_time = hour * 3600 + minute * 50 + second
for i in range(total_time):
print("\r剩餘{}秒".format(str(total_time - i).zfill(len(str(total_time)))),
end="")
time.sleep(1)
print("\n", "Ring~~~~~")
if __name__ == "__main__":
args = parser.parse_args()
# print(args)
if args.due_time:
clock(args.due_time)
elif args.seconds:
countdown(args.seconds)
# clock(args.due_time)
|
ce9a1cd223acd185cb4e76afc5f25e262306fe20 | Manmohit10/data-analysis-with-python-summer-2021 | /part03-e13_read_series/src/read_series.py | 614 | 3.625 | 4 | #!/usr/bin/env python3
import pandas as pd
def read_series():
df=pd.Series()
a1=[]
a2=[]
while True:
x=input("Enter values separated by string: ")
if not x:
break
try :
temp=x.split()
if len(temp)>2:
raise ValueError
a2.append(temp[1])
a1.append(temp[0])
#df[temp[0]]=df[temp[1]]
except :
print("Retry")
continue
df=pd.Series(a2,index=a1)
return df
def main():
a=read_series()
print(a)
if __name__ == "__main__":
main()
|
f78dd20e575f877e27491235bac4c8fa4b3ddc00 | Rodrigo00909/pythonfacultad1 | /tp1 Funciones/ej6.py | 719 | 4.09375 | 4 | # 6. Desarrollar una función que reciba como parámetros dos números enteros positivos y devuelva el número que resulte de concatenar ambos valores. Por ejemplo,
# si recibe 1234 y 567 debe devolver 1234567. No se permite utilizar facilidades de
# Python no vistas en clase.
def concatenar(num1, num2):
contador=1
num2contador=num2
while num2contador>9:
num2contador//=10
contador+=1
concatenacion=num1*(10**contador)+num2
return concatenacion
#Programa principal
a=int(input("Ingrese el primer número a concatenar: "))
b=int(input("Ingrese el segundo número a concatenar: "))
resultado=concatenar(a, b)
print("El resultado es", resultado) |
11a9c40de70ac4fef15f2b8382813b19686e2834 | mattman555/python | /ex44.py | 1,181 | 4.09375 | 4 | class other(object):#Make a class called other that has-a object
def implicit(self):#Procedure that prints when called
print "Other implicit()"
def altered(self):#Procedure that prints when called
print "Other altered()"
class child(object):#Make a class called other that has-a object
def __init__(self):#intialization procedure that gives the self.other object the propreties of the other class
self.other = other()
def implicit(self):#Procedure that prints then calls the implicit procedure from the other class then prints something else
self.other.implicit()
def overide(self):#Procedure that prints when called
print "Child overide"
def altered(self):#Procedure that prints then calls the altered procedure from the other class then prints something else
print"Child before"
self.other.altered()#call the altered procedure from the other class
print"Child after"
son = child()#make the son object with the propreties of the child class
son.implicit()#class the implicit procedure from child through son
son.overide()#class the overide procedure from child through son
son.altered()#class the altered procedure from child through son
|
5c8f611549b886d2813a1428fc4b78e6581d9be1 | Morek999/OMSCS_Taiwan_Leetcode | /Max/Max_0056_20200115.py | 1,243 | 3.6875 | 4 | """
56. Merge Intervals
https://leetcode.com/problems/merge-intervals/
Time complexity: O(nlogn)
Space complexity: O(n)
Solution:
"""
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
holding = []
for i in intervals:
if holding and i[0] <= holding[-1][1]:
holding[-1][1] = max(holding[-1][1], i[1])
else:
holding.append(i)
return holding
# def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# if len(intervals) <= 1: return intervals
# intervals.sort()
# holding = [intervals[0]]
# for i in range(1, len(intervals)):
# if holding[-1][1] >= intervals[i][0]:
# if holding[-1][1] < intervals[i][1]:
# holding[-1][1] = intervals[i][1]
# else:
# holding.append(intervals[i])
# return holding
ans = [
[[1,3],[2,6],[8,10],[15,18]], # output: [[1,6],[8,10],[15,18]]
[[1,4],[4,5]], # output: [[1,5]]
[[1,4],[2,3]] # output: [[1,4]]
]
for trails in ans:
print(Solution().merge(trails))
|
866c6088b1e0997299c74dbd96f60a68f9520e08 | alexgrand/Grokking-algorhithms | /ch4/ex4.5-4.8.py | 781 | 4 | 4 | print("4.5 Вывод значения каждого элемента массива.")
print("O(n)")
print('-' * 20)
print("4.6 Удвоение значения каждого элемента массива. ")
print("O(n)")
print('-' * 20)
print("4.7 Удвоение значения только первого элемента массива.")
print("O(1)")
print('-' * 20)
print("4.8 Создание таблицы умножения для всех элементов массива. Например, если массив состоит из элементов [2, 3, 7, 8, 10], сначала каждый элемент умножается на 2, затем каждый элемент умножается на 3, затем на 7 и т. д.")
print("O(n^2)") |
ac516544ff41a0f2902ed5811cdc8b2eaca64a57 | VanessaCapuzzi/mackenzie_algoritmosI | /app_conhecimento_aula2.py | 579 | 3.859375 | 4 | # Faça um programa em Python que receba o custo (valor em reais) de um espetáculo teatral e o preço do convite (valor em reais) desse espetáculo. Esse programa deve calcular e mostrar:
# a) A quantidade de convites que devem ser vendidos para que, pelo menos, o custo do espetáculo seja alcançado.
# b) A quantidade de convites que devem ser vendidos para que se tenha um lucro de 23%.
import math
custo = float(input())
convite = float(input())
quantidade = (custo/convite)
lucro = ((custo*1.23)/convite)
print(math.ceil(quantidade))
print(math.ceil(lucro))
|
3e90a1b05f745febc8d26c5002d9684b92073d83 | ccomangi2/Python_study | /venv/35.6 날짜 클래스 만들기.py | 526 | 4.03125 | 4 | #다음 소스 코드에서 Date 클래스를 완성하세요. is_date_valid는 문자열이 올바른 날짜인지 검사하는 메서드입니다.
#날짜에서 월은 12월까지 일은 31일까지 있어야 합니다.
class Date:
@staticmethod
def is_date_valid(date_string):
year, month, day = map(int, date_string.split('-'))
return month <= 12 and day <= 31
if Date.is_date_valid('2000-10-31'):
print('올바른 날짜 형식입니다.')
else:
print('잘못된 날짜 형식입니다.') |
0ecd2e1075612308ea38121d0d06806f9ab442d6 | Sniper970119/Algorithm | /chapter_4/Find_max_subarray.py | 2,921 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class FIndMaxSubarray:
def __init__(self, init_array):
self.init_array = init_array
pass
def find(self, start, end):
"""
递归寻找最大子数组
:return:
"""
# 递归结束标记
if start == end:
return [self.init_array[start]], self.init_array[start]
mid = int((start + end) / 2)
# 分别处理左、右、以及跨越重点的情况
left_subarray, left_sum = self.find(start, mid)
right_subarray, right_sum = self.find(mid + 1, end)
cross_subarray, cross_sum = self.find_max_crossing_subarray(target_array=self.init_array[start:end+1])
# 比较三种结果大小并返回
if left_sum >= right_sum and left_sum >= cross_sum:
return left_subarray, left_sum
elif right_sum >= left_sum and right_sum >= cross_sum:
return right_subarray, right_sum
else:
return cross_subarray, cross_sum
def find_max_crossing_subarray(self, target_array):
"""
寻找当前列表以中点为基准的最大子列表
:param target_array:
:return:
"""
# 左最大子数组
left_max_sub_array = []
# 右最大子数组
right_max_sub_array = []
# 中间索引
mid_index = int(len(target_array) / 2)
# 最大子数组
max_subarray = []
# 中间值
mid_number = target_array[mid_index]
# 临时存储的最大值
_sum = 0
# 临时存储的索引值
_index = 0
# 用于存放临时和的变量
temp_sum = 0
# 对左侧数字查找最大子数组
for i in range(mid_index, 0, -1):
# 计算临时和
temp_sum = temp_sum + target_array[i]
# 判断该位取舍
if temp_sum > _sum:
_sum = temp_sum
_index = i
# 截取数组
left_max_sub_array = target_array[_index:mid_index]
# 数据初始化
_sum = 0
_index = 0
temp_sum = 0
# 对右侧数字查找最大子数组
for i in range(mid_index, len(target_array)):
temp_sum = temp_sum + target_array[i]
if temp_sum > _sum:
_sum = temp_sum
_index = i
# 截取数组
right_max_sub_array = target_array[mid_index:_index + 1]
# 合并数组
max_subarray = left_max_sub_array + right_max_sub_array
# 求和
max_subarray_sum = sum(max_subarray)
return max_subarray, max_subarray_sum
if __name__ == '__main__':
init_array = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
max_sum, max_array = FIndMaxSubarray(init_array).find(0, len(init_array) - 1)
print(init_array)
print(max_array, '\t', max_sum)
pass
|
8f7d98181689476800b1d956b95786ee435ab01f | tk42/ProjectEuler | /34. 桁の階乗.py | 734 | 3.890625 | 4 | import math
#### DACLARE VARIABLES ####
def num2digit(num) :
return [int(x) for x in str(num)]
def digit2num(digit) :
num = 0
for i in range(len(digit)):
num += digit[i] * pow(10 , len(digit) - i - 1)
return num
def digit_factorial(num) :
if num == 0:
return 1
elif num == 1:
return 1
elif num == 2:
return 2
elif num == 3:
return 6
elif num == 4:
return 24
elif num == 5:
return 120
elif num == 6:
return 720
elif num == 7:
return 5040
elif num == 8:
return 40320
elif num == 9:
return 362880
if __name__ == "__main__":
s = 0
for num in range(3 , 99999):
if num == sum(map(digit_factorial , num2digit(num))) :
print num
s += num
print "Calculation was finished. Answer is " , s
|
97d7492ea3cf030d4e21230b99bf833eb0c08d4b | Naateri/JustForFun | /iRacing-Schedules/sched.py | 2,980 | 3.734375 | 4 | import csv
import sys
import time
sched = list()
with open("Sched 2017-2.csv", "rU") as f: #importing schedule
rows = csv.DictReader(f)
for r in rows:
sched.append(r) #saving schedule
monthsDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #dias por mes, empezando en Enero
def askAuto():
a = raw_input("Se ha detectado la fecha en el ordenador. Desea usar esta fecha? (s/n) ")
a = a.lower()
if a == "s":
return True
elif a == "n":
return False
else:
print "Ingrese un valor valido."
askAuto()
def askWeek():
a = input("Ingrese el numero de la semana que quiera ver: ")
if a <= 0 or a > 12:
print "Debe ingresar un numero valido."
askWeek()
else:
return a
def getWeekIfTUE(month, day, week = 0):
for m8 in sched:
if int(m8["startsMonth"]) == month and int(m8["startsDay"]) == day:
week = int(m8["week"])
break
if week != 0:
return week
else:
print "Error. Csv no es el de la season actual."
sys.exit()
def getWeek():
day = int(time.strftime("%d"))
dof = int(time.strftime("%w")) #day of week
month = int(time.strftime("%m"))
year = int(time.strftime("%y"))
#week = 0
if year % 4 == 0: #si es anho bisiesto
monthsDays[1] = 29 #febrero tiene 29 dias
if dof == 2: #if it is tuesday
week = getWeekIfTUE(month, day)
elif dof > 2: #if it is wednesday - saturday
gap = dof - 2
day -= gap
if day <= 0:
if month-2 < 0:
month = 12
day += monthsDays[month-1]
else:
gap = 2 - dof
day += gap
if day >= monthsDays[month-1]:
if month == 12:
month = 1
else:
month += 1
day -= monthsDays[month-1]
week = getWeekIfTUE(month, day)
return week
def getEvents(week, maxim):
if week < 0 or week > 13:
print "Error. Semana fuera del rango."
sys.exit()
else:
print "Sus eventos para esta semana son: "
events = sched[week-1]
curseries = 1
str_series = "series" + str(curseries)
while events[str_series] != "-": #or curseries > maxim:
str_car = "car" + str(curseries)
str_track = "track" + str(curseries)
str_laps = "laps-time" + str(curseries)
str_dttr = "dttr" + str(curseries) #day and time to race
print "Series: " + events[str_series]
print "Car: " + events[str_car]
print "Track: " + events[str_track]
laps = events[str_laps]
if len(laps) == 3 and laps[2] == "m":
laps = "Time: "
else:
laps = "Laps: "
print laps + events[str_laps]
print "Preferred time to race: " + events[str_dttr]
print " "
curseries += 1
if curseries > maxim:
break
else:
str_series = "series" + str(curseries)
def main():
print "Fecha de hoy: " + time.strftime("%d/%m")
if askAuto():
week = getWeek()
#print "Estamos en la semana: " + str(week)
else:
week = askWeek()
print "Estamos en la semana: " + str(week)
getEvents(week, 6)
while True:
a = raw_input("Desea continuar? (s)")
if a.lower() != "s":
break
week = askWeek()
getEvents(week, 6)
print "Gracias por usarme. Hasta pronto!"
sys.exit()
main()
|
3822fc9e8c0c874800c97f7f5fd46cc5b808f3ea | erjan/coding_exercises | /verify_preorder_serialization_of_binary_tree.py | 711 | 3.796875 | 4 | '''
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.
'''
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
preorderList = preorder.split(',')
if len(preorderList)%2 != 1:
return False
stack = []
for node in preorderList:
stack.append(node)
while len(stack) >= 3 and stack[-2] == stack[-1] == '#' and stack[-3] != '#':
for i in range(3):
stack.pop()
stack.append('#')
return len(stack) == 1 and stack[0] == '#'
|
c454daf1176ea214e9f66efd70f538bf7c78e68e | mingcn/kyleboard | /__init__.py | 9,822 | 3.53125 | 4 | from random import randint
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Set Up Board
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
dims = 0
while dims % 2 == 0 or dims < 6:
dims = int(raw_input("How many tiles long do you want your board (choose an odd number > 5)? "))
board = []
for x in range(dims):
board.append(["O "] * dims)
# Print the board with unit and shop locations
def spawn_player(player):
if player.health > 0:
board[player.x][player.y] = player.mark
else:
board[player.x][player.y] = '0 '
player.x = player.home_x
player.y = player.home_y
board[player.x][player.y] = player.mark
def print_board(board, player_count):
if boss.health > 0:
board[boss.x][boss.y] = boss.mark
spawn_player(p1)
if player_count > 1:
spawn_player(p2)
if player_count > 2:
spawn_player(p3)
if player_count > 3:
spawn_player(p4)
for row in board:
print " ".join(row)
print "---"
def print_stats(player_count):
print "P1 - Level: " + str(p1.lvl) + ", HP/ATK/DEF: " + str(p1.health) + "/" + str(p1.atk) + "/" + str(p1.dfn)
if player_count > 1:
print "P2 - Level: " + str(p2.lvl) + ", HP/ATK/DEF: " + str(p2.health) + "/" + str(p2.atk) + "/" + str(p2.dfn)
if player_count > 2:
print "P3 - Level: " + str(p3.lvl) + ", HP/ATK/DEF: " + str(p3.health) + "/" + str(p3.atk) + "/" + str(p3.dfn)
if player_count > 3:
print "P4 - Level: " + str(p4.lvl) + ", HP/ATK/DEF: " + str(p4.health) + "/" + str(p4.atk) + "/" + str(p4.dfn)
print "---"
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Auxiliary Functions
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Check if a space is vacant
def movable(player, x, y):
if player.x + x >= 0 and player.x + x < 9 and player.y + y >= 0 and player.y + y < 9:
if board[player.x + x][player.y + y] == 'O ':
return True
else:
return False
else:
return False
def attackable(player):
targets = []
x = player.x
y = player.y
if x - 1 >= 0:
if 'P' in board[x - 1][y]:
targets.append(board[x-1][y])
if x + 1 <= dims - 1:
if 'P' in board[x + 1][y]:
targets.append(board[x-1][y])
if y - 1 >= 0 :
if 'P' in board[x][y - 1]:
targets.append(board[x-1][y])
if y + 1 <= dims - 1:
if 'P' in board[x][y + 1]:
targets.append(board[x-1][y])
return targets
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Create the character classes
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
class unit(object):
def __init__(self, row, col, mark, level):
self.x = row
self.y = col
self.mark = mark
self.health = level
self.atk = level / 2
self.dfn = level / 2
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.delete(item)
class hero(unit):
def __init__(self, row, col, mark, level, health, items, n_items, n_rolls, n_moves, n_battles, n_buys):
self.x = row # x position of hero
self.y = col # y position of hero
self.home_x = row # x starting position
self.home_y = col # y starting position
self.mark = mark # hero label (P#)
self.lvl = level # hero level
self.health = health # hero current health
self.fullhealth = health # hero max health
self.atk = level # hero base attack power
self.dfn = level # hero base defense power
self.items = items # hero items inventory
self.n_items = n_items # number of items
self.n_rolls = n_rolls # number of rolls remaining
self.n_moves = n_moves # number of spaces able to move
self.n_battles = n_battles # number of battles able to commence
self.n_buys = n_buys # number of buys able to perform
self.revenge = "" # change to player who previous attacked this hero
def acts_remaining(self):
return self.n_items + n_moves + n_battles + n_buys
def move(self, x, y):
if abs(x) + abs(y) <= self.n_moves and movable(self, x, y):
board[self.x][self.y]= 'O '
self.x += x
self.y += y
board[self.x][self.y]= self.mark
self.n_moves -= abs(x + y)
else:
print
print "You can't move there!"
print
def attack(self,target):
print self.mark + " attacked " + target.mark + "!"
roll1 = randint(1,3)
print self.mark + " rolls a " + str(roll1)
roll2 = randint(1,3)
print target.mark + "The defender rolls a " + str(roll2)
if self.revenge == target.mark:
atk = self.atk + roll1 + 1
print "<< " + self.mark + " has a revenge bonus of +1 ATK! >>"
else:
atk = self. atk + roll1
print "<< " + self.mark + " has an ATK power of " + str(atk) + "! >>"
dfn = target.dfn + roll2
print "<< " + target.mark + " has an DEF power of " + str(dfn) + "! >>"
if atk > dfn:
print "<< " + target.mark + " took " + str(atk-dfn) + " damage! >>"
else:
print "<< " + target.mark + " absorbed all the damage! >>"
target.health -= (atk - dfn)
self.revenge = ""
target.revenge = self.mark
class item(object):
def __init__(self, cost, level):
self.cost = cost
self.level = level
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
boss = unit((dims-1)/2, (dims-1)/2, 'X ', 5)
# Find out how many players there are
player_count = int(raw_input("How many players (1-4)? "))
if player_count > 4:
print "Only 4 players can play at once!"
if player_count < 1:
print "At least 1 player must be present."
# Add the appropriate number of players to the game
p1 = hero(0, 0, 'P1', 1, 5, {}, 0, 0, 0, 0, 0)
if player_count > 1:
p2 = hero(dims-1, dims-1, 'P2', 1, 5, {}, 0, 0, 0, 0, 0)
if player_count > 2:
p3 = hero(0, dims-1, 'P3', 1, 5, {}, 0, 0, 0, 0, 0)
if player_count > 3:
p4 = hero(dims-1, 0, 'P4', 1, 5, {}, 0, 0, 0, 0, 0)
# Opening message, display the board
print "Let's Begin the game"
print "---"
print_board(board, player_count)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Remaining actions
def perform_turn(player):
action = ""
player.n_rolls = 1
while action != "end":
action = raw_input("> Player " + str(player_turn) + ", what action would you like to perform (roll/move/attack/buy/item/end)? ")
# If there are items or abilities to use, perform an item phase
# Perform a dice roll
if action == "roll":
if player.n_rolls == 0:
print
print "<< You've already rolled the dice! It was a " + str(roll) + ". >>"
print
else:
# roll = randint(2,5)
roll = 100
print
print "<< Player " + str(player_turn) + " has rolled a " + str(roll) + ". >>"
print
player.n_moves = roll
player.n_rolls = 0
# If there is a space to move to perform a movement phase
if action == "move":
if player.n_moves == 0:
if player.n_rolls > 0:
print
print "<< You must first roll the dice. >>"
print
else:
print
print "<< You cannot move any further >>"
print
else:
y = int(raw_input("Horizontal motion (+/- #)? "))
x = int(raw_input("Vertical motion (+/- #)? "))
player.move(x, y)
print
print_board(board, player_count)
if action == "attack":
if len(attackable(player)) > 0:
tgt_player = raw_input("Who do you wish to attack (P#)? ")
if tgt_player == 'P1':
target = p1
elif tgt_player == 'P2':
target = p2
elif tgt_player == 'P3':
target = p3
elif tgt_player == 'P4':
target = p4
player.attack(target)
else:
print "<< There are no reachable targets! >>"
# If the unit is on a shop, perform a buy phase
# If there is a unit to trade with, perform a trade
# If there is a unit to attack, perform an attack phase
# No more actions available, pass onto next turn
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""Conduct the turns and update results"""
turn = 0
# Perform a turn if the boss is still alive
while boss.health > 0:
# Whose turn is it?
player_turn = turn % player_count + 1
if player_turn == 1:
perform_turn(p1)
elif player_turn == 2:
perform_turn(p2)
elif player_turn == 3:
perform_turn(p3)
elif player_turn == 4:
perform_turn(p4)
if raw_input("Would you like to exit the game ('y' to exit)? ") == 'y':
boss.health = 0
else:
print"---"
print_board(board, player_count)
print_stats(player_count)
turn += 1
if boss.health < 1:
print "Player " + str(player_turn) + " has slain the Boss and won the battle!" |
09832a7167a22aa199415c794f00b6cfc03cf8ef | nicecode996/Python_Test | /python基础/for.py | 808 | 3.90625 | 4 | # !usr/bin/env python 3
# coding=utf-8
print("----范围------")
<<<<<<< HEAD
for num in range(1,100):
print("{0} * {0} = {1}".format(num ,num * num))
=======
for num in range(1, 10):
print("{0} * {0} = {1}".format(num , num * num))
>>>>>>> 7250e8d (第三次提交)
print("----范围------")
# for语句
for item in 'Hello':
print(item)
<<<<<<< HEAD
# 生命整数列表
numbers = {43,32,53,54,75,7,10}
=======
# 生命整数列表
numbers = {43, 32, 53, 54, 75, 7, 10}
>>>>>>> 7250e8d (第三次提交)
print("----整数列表------")
# for语句
for item in numbers:
print("Counts is : {0}".format(item))
sum = 0
<<<<<<< HEAD
for x in (1,2,3,4,5):
sum = sum + x
print(sum)
=======
for x in (1, 2, 3, 4, 5):
sum = sum + x
print(sum)
>>>>>>> 7250e8d (第三次提交)
|
9f0abdf4467c128b6a6e298afc8c7f47c47e3fea | frannyfra/Python-The-Basic | /dictionary.py | 623 | 3.890625 | 4 | # Key value pairs
# our_dictionary = {"key1": "one", "key2": "two"}
# print(our_dictionary)
# product1= "apple"
# product2= "hey"
# product3= "bye"
# products = [product1, product2, product3]
# # total = 0
# # for( i = count(products) -1; i>= 1; i++) {
# # total += products[i].price
# # }
# print(count(products))
# def main():
# n = 1024
# while n > 0:
# print(n % 10)
# n = n // 10
# print(main())
def main():
actualString = "reverse"
reversedString = ""
length = len(actualString)
for i in range(1, lenght+ 1):
for i in range(0, length):
print(reversedString[i])
|
bad79752d5189c400d39721b115c0a7e4771c89c | gaohaoning/leetcode_datastructure_algorithm | /LeetCode/HashMap/350.py | 2,119 | 4.09375 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
350. 两个数组的交集 II
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
"""
# ================================================================================
# 方法1 (代码较麻烦)
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s1 = {}
s2 = {}
sret = {}
for n in nums1:
s1[n] = s1.get(n, 0) + 1
pass
for n in nums2:
s2[n] = s2.get(n, 0) + 1
pass
for k, v in s1.iteritems():
if k in s2:
sret[k] = min(v, s2[k])
pass
pass
ret = []
for k, v in sret.iteritems():
ret.extend([k] * v)
pass
return ret
# ================================================================================
# 方法2(代码较简洁)
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s = set(nums1) & set(nums2)
l = []
for x in s:
l.extend([x] * min(nums1.count(x), nums2.count(x)))
pass
return l
# ================================================================================
# ================================================================================
|
3315285a7dca97141f1dfb10fb53524d20344eef | yangguangleiyang/selenium-unittest | /study-unittest/类方法、类属性、成员方法、成员属性学习.py | 1,023 | 3.703125 | 4 | import unittest
#各个成员之间self对象是不一样的
class TestMyCase(unittest.TestCase):
step = 1
ipadder = "192.168.1.1" # 类属性
name = None
@classmethod
def setUpClass(cls): #类方法
print("-----setupclass")
@classmethod
def tearDownClass(cls):
print("----setupclass")
def setUp(self):
print("----setup")
def tearDown(self):
print("----teardown")
def test_1(self): #成员方法
print("do test1",TestMyCase.ipadder)
TestMyCase.name = "Sigper"
@unittest.skip("test_2暂时不执行此用例")
def test_2(self):
print("do test2",TestMyCase.name)
# @unittest.skipIf(2>1,"因为2>1,所以跳过")
@unittest.skipIf(print("skip",step),"因为step等于1,所以跳过") #skip装饰器在执行所有之前最先执行,包括setupclass
def test_3(self):
print("do test2",TestMyCase.name)
if __name__ == '__main__':
unittest.main() |
55838b152583525b429d91e0841a7fdccfc1718e | RakhshandaMujib/Simple-Python-Programs-on-Classic-Algorithms | /11 Counting Sort.py | 794 | 4.03125 | 4 | def counting_sort(list_is, lower, upper):
count = {i : 0 for i in range(lower, upper +1)}
for i in range(len(list_is)):
if list_is[i] > (upper + 1) or list_is[i] < lower:
print(f'{list_is[i]} is not within [{lower},{upper}].')
return
elif list_is[i] in count:
count[list_is[i]] += 1
print('The sorted list is:')
for i in count.items():
print(f"{(str(i[0]) + ' ') * i[1]}", end = '')
return
def main():
lower, upper = map(int, input('Enter the range (separated by space):\n').split())
list_is = []
list_is = input("Enter the numbers in your list (separated by spaces):\n").split()
list_is = [int(item) for item in list_is]
print(f"The elements are:\n\t{list_is}")
counting_sort(list_is, lower, upper)
if __name__ == '__main__':
main()
|
449dd7dd425b896126bd99530d05d2a52458c66b | yuliy/sport_programming | /algorithms/roman2integer/main.py | 629 | 3.6875 | 4 | #!/usr/bin/env python3
#
# Solution for leetcode problem:
# https://leetcode.com/problems/roman-to-integer/
#
class Solution:
def romanToInt(self, s: str) -> int:
s2r = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000,
}
r = [s2r[ch] for ch in s]
if len(r)==1:
return r[0]
result = 0
for i in range(len(r)-1):
if r[i+1] > r[i]:
result -= r[i]
else:
result += r[i]
result += r[-1]
return result
|
9debebbd80dd58c6a0cc98fbf592851e56c65952 | isdewo/python | /file/practice1.py | 981 | 3.71875 | 4 | '''
파이썬 - 7 파일 다루기
p. 21
연습 문제1
'''
'''
파일에서 특정 단어를 다른 단어로 교체하는 프로그램을 작성하시오.
예를 들어, "abc", "111로 대체시킴.
파일 이름과 단어 2개는 키보드로 입력받는다.
'''
filename = input("파일 이름을 입력하세요: ")
word1, word2 = input("단어 2개를 띄어쓰기로 구분하여 입력하세요: ").split(" ")
print("filename: ", filename)
print("word1: {0}, word2: {1}".format(word1, word2))
# 파일을 열어 단어를 대체함.
with open(filename, "r") as f:
text = f.read()
print("----- 대체 이전 -----")
print(text)
text = text.replace(word1, word2)
print("----- 대체한 문장 -----")
print(text)
# 교체된 문장을 파일에 다시 입력
with open(filename, "w") as f:
f.write(text)
# 단어가 교체된 파일 내용 확인
print("----- 파일 내용 교체 -----")
with open(filename, "r") as f:
text = f.read()
print(text)
|
58abd84aee77c7035e97e0261b16e0a372fe4a31 | bithyf/leetcode_pycharm | /剑指offer/剑指 Offer 24. 反转链表.py | 155 | 3.921875 | 4 | def reverseList(head):
p = head
while p.next:
p1 = p.next
p.next = p1.next
p1.next = head
head = p1
return head |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.