blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
01c5b4b2259d1277efd2ceb2cdb8c72d3283111d | cseharshit/Python_Practice_Beginner | /48.Check_File_extension.py | 363 | 4.5 | 4 | extensions=['gif','png','jpeg','jpg','svg']
file_extension=input("Enter the filename with extension: ").split('.')
if (len(file_extension)>=2):
extension=file_extension[-1].lower()
if extension in extensions:
print("File Extension exists")
else:
print("File Extension does not exists")
else:
print("File does not have extension") |
239e5237c8930e932fe0e5460cfe53fd2b2e424d | Khawoat6/programming-skills-development-laboratory | /week05/5_BuggyRobot/5_BuggyRobot.py | 1,987 | 3.90625 | 4 | # Phattaraphon Chomchaiyaphum 5930300585
def buggyRobot(move_forward, move_back, distance, l, state):
while True:
if l >= distance:
state = state+distance
break
if move_forward >= distance:
state = state+distance
distance=0
else:
distance = distance - l
state = state + (move_forward+move_back)
return state;
move_forward, move_back, distance = [int(x) for x in input().split()]
l = move_forward - move_back
state = 0
print(buggyRobot(move_forward, move_back, distance, l, state))
#+--------------------------------------+
#| input | output |
#+--------------------------------------+
#| 5 2 9 | 17 |
#|--------------------------------------+
#| 8 7 9 | 23 |
#|--------------------------------------+
#| 9 8 8 | 8 |
#+--------------------------------------+
'''
def buggyRobot(move_forward, move_back, distance):
tmp1 = 0
x = move_forward - move_back
while(1):
if x>=distance:
tmp1 += distance
break
elif move_forward>=distance:
tmp1 +=distance
distance=0
else:
distance -=x
tmp1 += move_forward+move_back
return tmp1;
move_forward, move_back, distance = [int(x) for x in input().split()]
print(buggyRobot(move_forward, move_back, distance))
'''
'''
def buggyRobot(move_forward, move_back, distance, l, state):
while(1):
if l >= distance:
state = distance + state
break
elif move_forward>=distance:
state +=distance
distance=0
else:
distance -= l
state += move_forward+move_back
return state;
move_forward, move_back, distance = [int(x) for x in input().split()]
l = move_forward - move_back
state = 0
print(buggyRobot(move_forward, move_back, distance, l, state))
'''
|
c41b13e7800e58d7d3cfe5f9ad38c970d6ff77d1 | JAntonioMarin/PythonBootcamp | /Section3/20.py | 607 | 3.875 | 4 | my_list = [1,2,3]
my_list = ['STRING', 100, 23.2]
print(len(my_list))
my_list = ['one', 'two', 'three']
print(my_list[0])
another_list = ['four', 'five']
print(my_list+another_list)
my_list[0] = 'ONE ALL CAPS'
print(my_list)
my_list.append('six')
print(my_list)
my_list.pop()
print(my_list)
popped_item = my_list.pop()
print(popped_item)
my_list.pop(0)
print(my_list)
new_list = ['a', 'e', 'x', 'b', 'c']
num_list = [4,1,8,3]
print(new_list.sort())
print(num_list.sort())
new_list_sorted = new_list
num_list_sorted = num_list
print(new_list_sorted)
print(num_list_sorted)
num_list.reverse()
print(num_list) |
c6945ec32c781319816271bef9eace437719a505 | Vikatsy/Vacation_Planner | /database.py | 4,161 | 4.1875 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def main():
database = "Vacation.db"
sql_create_Projects_table = """ CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY AUTOINCREMENT,
name text NOT NULL,
begin_date text,
end_date text
); """
sql_create_Flights_table = """CREATE TABLE IF NOT EXISTS flights (
id integer PRIMARY KEY AUTOINCREMENT,
airline text NOT NULL,
departureStation text NOT NULL,
arrivalStation text NOT NULL,
departureDateTime text NOT NULL,
currencyCode text NOT NULL,
basePrice integer NOT NULL,
discountedPrice integer NOT NULL,
administrationFeePrice integer NOT NULL,
project_id integer NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects( id)
);"""
# create a database connection
conn = create_connection(database)
if conn is not None:
# create projects table
create_table(conn, sql_create_Projects_table)
# create flights table
create_table(conn, sql_create_Flights_table)
else:
print("Error! cannot create the database connection.")
def create_project(conn, project):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO flightss(name,begin_date,end_date)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
return cur.lastrowid
def create_flight(conn, flight):
"""
Create a new task
:param conn: db connection
:param flight: ScheduledFlight
:return:
"""
sql = ''' INSERT INTO flights(airLine, departureStation, arrivalStation, departureDateTime,
currencyCode, basePrice, discountedPrice, discountedPrice,administrationFeePrice)
VALUES(?,?,?,?,?,?,?,?,?) '''
cur = conn.cursor()
flight_values = (flight.airLine, flight.flightNumber, flight.departureStation, flight.arrivalStation, flight.departureDateTime,
flight.currencyCode, flight.basePrice, flight.discountedPrice, flight.administrationFeePrice)
cur.execute(sql, flight_values)
return cur.lastrowid
def get_schediled_flights(conn):
# return list of Flight objects
pass
if __name__ == '__main__':
main()
exit(0)
# from database import create_connection, save_flight, #...
# conn = create_connection()
# ...
# save_flight(conn, flight)
# flight = read_flight(conn, city, date)
# ...
# class SqliteBackend(object):
# def __init__(self):
# self.conn = None
# pass
# def create_connection(self, db_file):
# self.conn = ...
# def create_table(self, create_table_sql):
# self.conn =
# from database import SqliteBackend
#
# sqlite = SqliteBackend()
# sqlite.create_connection()
# ...
# sqlite.save_flight(flight)
# flight = sqlite.read_flight(city, date)
# ...
|
8fc2f51ab20d88a6e078b879e180b990238193bd | aa-ag/nano | /problems/reverse_polish_notation.py | 2,535 | 4 | 4 | ###--- CREATE STACK ----###
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
def push(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.num_elements += 1
def pop(self):
if self.is_stack_empty():
return None
temporary_data = self.head.data
self.head = self.head.next
self.num_elements -= 1
return temporary_data
def stack_top(self):
if self.head is None:
return None
return self.head.data
def size(self):
return self.num_elements
def is_stack_empty(self):
return self.num_elements == 0
###--- USE STACK TO EVALUATE INPUTS ----###
def evaluate_post_fix(input_list):
stack = Stack()
for element in input_list:
if element == '*':
second_num_in_pair = stack.pop()
first_num_in_pair = stack.pop()
operation_result = first_num_in_pair * second_num_in_pair
stack.push(operation_result)
elif element == '/':
second_num_in_pair = stack.pop()
first_num_in_pair = stack.pop()
operation_result = int(first_num_in_pair / second_num_in_pair)
stack.push(operation_result)
elif element == '+':
second_num_in_pair = stack.pop()
first_num_in_pair = stack.pop()
operation_result = first_num_in_pair + second_num_in_pair
stack.push(operation_result)
elif element == '-':
second_num_in_pair = stack.pop()
first_num_in_pair = stack.pop()
operation_result = first_num_in_pair - second_num_in_pair
stack.push(operation_result)
else:
stack.push(int(element))
return stack.pop() # pop for top element
###--- TESTS ---###
def test_function(test_case):
output = evaluate_post_fix(test_case[0])
print(output)
if output == test_case[1]:
print("Pass")
else:
print("Fail")
test_case_1 = [["3", "1", "+", "4", "*"], 16]
test_function(test_case_1)
test_case_2 = [["4", "13", "5", "/", "+"], 6]
test_function(test_case_2)
test_case_3 = [["10", "6", "9", "3", "+", "-11",
"*", "/", "*", "17", "+", "5", "+"], 22]
test_function(test_case_3)
|
72892cdca0dcdf3b48d749a813fd5c75d98c5993 | monteua/Python | /Python_Basic/6.py | 394 | 4.25 | 4 | '''
Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple
with those numbers.
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
'''
user_data = raw_input('Enter a sequence of comma-separated numbers: ').strip().split(',')
print "List:", user_data
print 'Tuple:', tuple(user_data)
|
2dbaa892f86d468cabbfba74dc1c32c452919478 | 05k001/WinterNetworkFinal | /UDP_Echo.py | 1,563 | 3.71875 | 4 | '''
The user datagram protocol (UDP) works differently from TCP/IP.
Where TCP is a stream oriented protocol, ensuring that all of the data is transmitted in the right order,
UDP is a message oriented protocol. UDP does not require a long-lived connection,
so setting up a UDP socket is a little simpler.
On the other hand, UDP messages must fit within a single packet (for IPv4, that means they can only
hold 65,507 bytes because the 65,535 byte packet also includes header information)
and delivery is not guaranteed as it is with TCP.
***************************************************************************
Since there is no connection, per se, the server does not need to
listen for and accept connections. It only needs to use bind() to
associate its socket with a port, and then wait for individual messages.
'''
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
'''
Messages are read from the socket using recvfrom(), which returns the data as
well as the address of the client from which it was sent.
'''
while True:
print >>sys.stderr, '\nwaiting to receive message'
data, address = sock.recvfrom(4096)
print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data
if data:
sent = sock.sendto(data, address)
print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)
|
969860bbe905574836fa62a970fef7400cba7609 | hyejun18/daily-rosalind | /scripts/bioinformatics-stronghold/SIGN.py | 1,119 | 3.828125 | 4 | ##################################################
# Enumerating Oriented Gene Orderings
#
# http://rosalind.info/problems/SIGN/
#
# Given: A positive integer n <=q 6.
#
# Return: The total number of signed permutations
# of length n, followed by a list of all such permutations
# (you may list the signed permutations in any
# order).
#
# AUTHOR : dohlee
##################################################
# Your imports here
from itertools import permutations
# Your codes here
def signed_permutation(n):
"""Return signed permutation of length n."""
return [x for x in permutations([i for i in range(-n, n+1) if i != 0], n) if set(range(1, n+1)) == set(map(abs, x))]
if __name__ == '__main__':
# Load the data.
with open('../../datasets/rosalind_SIGN.txt') as inFile:
n = int(inFile.readline())
# Print output
with open('../../answers/rosalind_SIGN_out.txt', 'w') as outFile:
signedPermutation = signed_permutation(n)
print(len(signedPermutation), file=outFile)
for perm in signedPermutation:
print(' '.join(map(str, perm)), file=outFile)
|
1b65a7cbadb7d0ec6ad73372b7fefecf43a6d82c | faneco/Programas | /Cursopython/exer53.py | 182 | 3.828125 | 4 | nome = input('Digite o nome: ').strip()
palavra = nome.split()
junto = ''.join(palavra)
inverso = ''
for i in range(len(junto)-1, -1, -1):
inverso += junto[i]
print (junto, inverso) |
b295e82e2c27b0f1d13f46e144a7719be4a6b038 | mjoehler94/login_system | /login.py | 7,570 | 3.546875 | 4 | # login.py --------------------------
# Author: Matt Oehler
# libraries
import getpass
import sqlite3
# global
_DATABASE_ = "data/user.db"
_LOGIN_OPTION_ = 1
_REGISTER_OPTION_ = 2
_QUIT_OPTION_ = 3
class Login():
def __init__(self, database):
self.db = database
self.conn = sqlite3.connect(self.db)
self.cursor = self.conn.cursor()
self.is_open_connection = True
# create tables if they don't already exist
self.cursor.execute('''CREATE TABLE IF NOT EXISTS USER (
"UserId" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"DateJoined" TEXT NOT NULL,
"UserName" TEXT NOT NULL UNIQUE,
"Password_Raw" TEXT NOT NULL,
"Password_Encrypted" TEXT);
''')
self.cursor.execute('''CREATE TABLE IF NOT EXISTS LoginHistory (
"UserHistoryId" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"UserId" INTEGER NOT NULL,
"LoginTime" TEXT NOT NULL
,FOREIGN KEY (UserId) REFERENCES USER(UserId)
);
''')
# Save (commit) the changes and close connection
self.conn.commit()
self.conn.close()
self.is_open_connection = False
return
def open_connection(self, verbose=False):
if self.is_open_connection:
if verbose:
print("The database is already open")
else:
self.conn = sqlite3.connect(self.db)
self.cursor = self.conn.cursor()
self.is_open_connection = True
if verbose:
print("The database has been opened")
return
def close_connection(self, verbose=False):
if self.is_open_connection:
self.conn.close()
self.is_open_connection = False
if verbose:
print("The database has been closed")
else:
if verbose:
print("The database is already closed")
return
def login(self):
# get username
username = input("Username:")
# check username
self.open_connection()
check_username = self.cursor.execute(f"SELECT UserName, UserId FROM USER WHERE UserName = '{username}'").fetchone()
if check_username is None:
print(f'Username {username} does not exist')
self.close_connection()
return None, None
# get password
# pwd = input("Password:")
pwd = getpass.getpass()
# check password:
check_password = self.cursor.execute(f"""SELECT Password_Raw
FROM USER WHERE UserName = '{username}'""").fetchone()[0]
if check_password == pwd:
self.cursor.execute(f"""INSERT INTO LoginHistory (UserId, LoginTime)
VALUES ('{check_username[1]}',DATETIME('now'))""")
self.conn.commit()
print("Login was successful!\n")
else:
print("Incorrect Password\n")
username = None
self.close_connection()
return username, pwd
def register(self, verbose=False):
# get and check username
print("Enter a Username (must be at least 5 characters).")
username = input("Username:")
if len(username) < 5:
print("Invalid Username")
return None, None
elif len(username) >= 5:
self.open_connection()
check_username = self.cursor.execute(f"SELECT Username FROM USER WHERE Username = '{username}'").fetchone()
self.close_connection()
if check_username is not None:
print(f"Sorry. The Username '{username}' is already taken.")
return None, None
else:
# get and check password
print('Create your password. (Passwords must be at least 7 characters)')
pwd = input("Password:")
if len(pwd) < 7:
print("Invalid Password")
return None, None
elif len(pwd) >= 7:
print("Confirm your password")
pwd2 = input("Password:")
if pwd != pwd2:
print("Passwords don't match")
return None, None
else:
self.add_user(username=username, password=pwd)
print("Regristration was successful!")
return username, pwd
def add_user(self, username, password):
encrypted_pwd = self.encrypt(password)
self.open_connection()
self.cursor.execute(f"""INSERT INTO USER (DateJoined, UserName, Password_Raw, Password_Encrypted)
VALUES (DATETIME('now'), '{username}', '{password}','{encrypted_pwd}')""")
self.conn.commit()
self.close_connection()
return
def fill_db(self, user_data=None):
# fake user data
if not user_data:
user_data = [
('KBryant_24', 'MVP_2008'), # R.I.P Kobe
('john_smith', 'hi-im-johnny'),
('robert_johnson', 'VERY SECURE PASSWORD'),
('t_jefferds', 'yogurt'),
('captain_holt', 'i<3kevin')
]
for username, pwd in user_data:
self.open_connection()
check_username = self.cursor.execute(f"SELECT Username FROM USER WHERE Username = '{username}'").fetchone()
self.close_connection()
if check_username is not None:
continue
else:
self.add_user(username=username, password=pwd)
return
@staticmethod
def encrypt(text):
# TODO: run an encryption algorithm on the password to store in the database
return 'encrypted_password'
@staticmethod
def decrypt(text):
# TODO: decrypt the password to ensure credentials are valid
return 'decrypted_password'
def main():
# initialize Login instance ---------------
login = Login(database=_DATABASE_)
login.fill_db()
# Main Menu ------------------
while True:
print("\nMain Menu -------------------------------")
option = input("""Please enter:
'1' to Login
'2' to Register
'3' to Quit\n-->""")
try:
option = int(option)
except:
option = -1 # invalid input
if option == _QUIT_OPTION_:
print("Quitting the program.")
return
elif option not in [1, 2]:
print("Invalid Selection. Please try again.")
continue
elif option == _LOGIN_OPTION_:
print("Enter your Username and Password to login.")
username, pwd = login.login()
if username is None:
continue
elif option == _REGISTER_OPTION_:
print("To Register, enter in your desired Username then password.")
username, pwd = login.register(True)
if username is None:
continue
break
# login or register ----------------------------
# username, pwd = login.prompt_user_input()
#
print(f"Username: {username}, Password: {pwd}")
login.conn.close()
return
if __name__ == '__main__':
main()
|
5ea62694c395fb9eda7173b3730e3f9c1afe465c | Georgeh30/Mini-Curso-Python | /clases/video12_metodo@staticmethod.py | 721 | 3.828125 | 4 | # 1. METODO CON DATOS INDEPENDIENTES --> CLASSMETHOD
# 2. METODO STATIC --> STATICMETHOD
# NINGUNO DE LOS DOS METODOS NECESITAN CREAR UNA INSTANCIA
import math
class Pastel:
def __init__(self, ingredientes1, tamano):
self.ingredientes1 = ingredientes1
self.tamano = tamano
def __repr__(self):
return f'pastel({self.ingredientes1}, 'f'{self.tamano})'
def area(self):
return self.tamano_area(self.tamano)
@staticmethod
def tamano_area(A):
return A ** 2 * math.pi
nuevo_pastel = Pastel(["harina", "azucar", "leche", "crema"], 4)
print(nuevo_pastel.ingredientes1)
print(nuevo_pastel.tamano)
# LLAMAMOS EL METODO ESTATICO
print(nuevo_pastel.tamano_area(12))
|
30923b7915b2ba3e487e59d83d0e5fcd7107cbe8 | PreciseSlice/python_practice | /io.py | 470 | 3.546875 | 4 | my_list = [i ** 2 for i in range(1, 11)]
my_file = open("output.txt", "w")
for item in my_list:
my_file.write(str(item) + "\n")
my_file.close()
# my_file = open("output.txt", "r")
# print(my_file.read())
# my_file.close()
# my_file = open("text.txt","r")
# print(my_file.readline())
# print(my_file.readline())
# print(my_file.readline())
# my_file.close()
# no call to close with as
with open("text.txt", "w") as textfile:
textfile.write("Success!")
|
28148f82ce64dc9d2336853c88151ee679a75a57 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/e96fe65800b445a3a6ec76aaf8eda1da.py | 804 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import re
class Phrase:
def __init__(self, text):
self.text = text.strip()
def is_question(self):
return self.text[-1] == '?'
def is_yelling(self):
return self.__contains_uppercase_letters() and \
not self.__contains_lowercase_letters()
def is_silence(self):
return re.match('^\s*$', self.text)
def __contains_uppercase_letters(self):
return re.search(u'[A-ZÜ]', self.text, re.UNICODE)
def __contains_lowercase_letters(self):
return re.search(u'[a-zä]', self.text, re.UNICODE)
def hey(text):
phrase = Phrase(text)
if phrase.is_silence():
return 'Fine. Be that way!'
elif phrase.is_yelling():
return 'Whoa, chill out!'
elif phrase.is_question():
return 'Sure.'
else:
return 'Whatever.'
|
38415a6bcca88b651339f4a8b3f1b2c02739ef61 | yielding/code | /lang.py/ternary.py | 206 | 3.953125 | 4 | #!/usr/bin/env python
#coding: utf-8
def translate(s):
res = map(lambda x: '.' if ord(x) % 2 == 0 else x, s)
return "".join(res)
s = "leech babo"
arr = [c for c in s]
print arr
print translate(arr)
|
18b36cad36422178f1d7b13b5b8f8ba030a2f199 | j-flammia/CoffeeMachine | /Topics/Invoking a function/Longest word/main.py | 67 | 3.59375 | 4 | word1 = len(input())
word2 = len(input())
print(max(word1, word2))
|
888803263d539695e94556b5cc9e49859a2387c0 | RajitPaul11/PythonBasix | /logical-relational-operators.py | 237 | 4.1875 | 4 | a=input("Enter a number: ")
b=input("Enter a number to compare to: ")
if a!=b and a>=b:
print(a," equals to or greater than ", b)
elif a!=b and a<=b:
print(a," not equal to and less than ",b)
else:
print(a," equals to ", b)
|
4c76d51affe82b462793cb6342ebdb8cf9800ca7 | ParulProgrammingHub/assignment-1-AmitDavra | /Answer-4.py | 54 | 3.5 | 4 | c=int(input("celcius= "))
c=c*1.8
f=c+32
print(f)
|
1877e6886e62995dc6fbf5c8dc99fa040e3933eb | paulreaver005/tarea_2 | /tarea2.py | 245 | 3.9375 | 4 | mis_valores = [5, 6, 10, 13, 3, 4]
sum = 0
for x in mis_valores:
sum = sum + x
average = sum / len(mis_valores)
print("los numeros de la lista son: ", mis_valores)
print("el promedio de los valores de la lista es: ", average) |
c82813e190960d4061fe481c96b0d799e262f208 | fajrinurhidayah/Fajri-Nur-Hidayah_I0320040_Andhika_Tugas2 | /Soal 1.py | 1,094 | 3.765625 | 4 | #menghitung luas persegi panjang
print("Menghitung luas persegi panjang")
Panjang = float(input("Masukkan nilai panjang: "))
Lebar = float(input("Masukkan nilai lebar: "))
luas_persegi_panjang = Panjang * Lebar
print("Luas persegi panjang adalah: ", luas_persegi_panjang)
#menghitung luas lingkaran
print("Menghitung luas lingkaran")
r = float(input("Masukkan jari-jari lingkaran: "))
luas_lingkaran = 3.14 * (r ** 2)
print("Luas lingkaran adalah: ", luas_lingkaran)
#menghitung luas kubus
print("Menghitung luas permukaan kubus")
panjang_sisi = float(input("Masukkan panjang sisi kubus: "))
luas_permukaan_kubus = 6 * (panjang_sisi ** 2)
print("Luas permukaan kubus adalah: ", luas_permukaan_kubus)
#mengkonversi suhu celcius ke fahrenheit
print("Mengkonversi suhu celcius ke fahrenheit")
C = float(input("Masukkan suhu dalam celcius: "))
C_F = (9 * C / 5) + 32
print("Suhu dalam fahrenheit: ", C_F)
#mengkonversi suhu reamur ke kelvin
print("Mengkonversi suhu reamur ke kelvin")
R = float(input("Masukkan suhu dalam reamur: "))
R_K = (5 * R / 4) + 273
print("Suhu dalan kelvin: ", R_K)
|
05ce138bae430e7337c1fcf6d1d6f8bb6e271163 | xwang322/Coding-Interview | /uber/uber_algo/RegularExpressionMatchingLC10Mutation_UB.py | 1,538 | 4.09375 | 4 | /*
* 第二题是
* The matching should cover the entire input string (not partial).
* The function prototype should be:
* bool isMatch(String str, String patter)
* Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa","a{1,3}") → true
* isMatch("aaa","a{1,3}") → false
* isMatch("ab","a{1,3}b{1,3}") → true
* isMatch("abc","a{1,3}b{1,3}c") → true
* isMatch("abbc","a{1,3}b{1,2}c") → false
* isMatch("acbac","a{1,3}b{1,3}c") → false
* isMatch("abcc","a{1,3}b{1,3}cc{1,3}") → true
**/
def isMatch(s, p):
p_list = []
while p.find('}') != -1:
index1 = 0
index2 = 0
num = 0
index1 = p.find('{')
temp = ''
temp_string = list(p[:index1])
while temp_string:
while len(temp_string)>1:
p_list.append(temp_string.pop(0))
temp = temp_string[0]
temp_string.pop()
p = p[index1+1:]
index1 = p.find(',')
index2 = p.find('}')
temp_string = list(p[index1+1:index2])
while temp_string:
num = num*10+int(temp_string.pop(0))
p_list.append(temp*(num-1))
p = p[index2+1:]
p_list.append(p)
p = ''.join(p_list)
m = len(s)
n = len(p)
dp = [[False for i in range(m+1)] for j in range(n+1)]
dp[0][0] = True
p = iter(p)
return all(char in p for char in s)
answer = isMatch('abcc','a{1,3}b{1,3}c{1,3}')
print answer
|
e9374f9710e69542fa1cfc17f84040d074b05ead | gauffa/mustached-dubstep | /ch5/ch5ex6.py | 517 | 3.90625 | 4 | #Matthew Hall
#ISY150
#Chapter 5 Exercise 6
#10/02/2013
#Celsius to Farenheit Table
def main():
#define constants
temp_range = 20
#print 'header' for table
print("\nFahrenheit\tCelsius")
print("----------------------")
#maths to determine a range of temps
for celsius in range (0, temp_range + 1, 1):#'c_temp + 1' ensure implied range
farenheit = (((9/5) * celsius) + 32)
print(format(farenheit,'.1f'),'\t\t',celsius)
print("")#blank line at end of table
#call main function
main()
|
e7be580b93ac5e4ff49b25c0275ab41187747824 | beingveera/whole-python | /python/projects/100`s of python/gratter.py | 670 | 3.90625 | 4 | class A:
def one(self,x):
self.val1=x
class B(A):
def two(self,y):
self.val2=y
class C(B):
def three(self,x,y,z):
self.val1=x
self.val2=y
self.val3=z
if self.val1 > self.val2 and self.val1>self.val3:
return "\n{} is Gretest...!!! ".format(self.val1)
elif self.val2 > self.val1 and self.val2 >self.val3:
return "\n{} is Gretest...!!! ".format(self.val2)
else:
return "\n{} is Gretest...!!! ".format(self.val3)
user=C()
a,b,c=int(input("Enter Value of X : ")),int(input("Enter Value of Y : ")),int(input("Enter Value of Z : "))
print(user.three(a,b,c))
|
c6dd3266793a64ed2a140b7f0351598465333c17 | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex090.py | 542 | 4.03125 | 4 | """
Faça um programa que leia nome e média de um aluno, guardando também a situação desse aluno em um dicionário. No final,
mostre o conteúdo da estrutura na tela.
"""
sit_aluno = dict()
sit_aluno['NOME'] = str(input('Nome: '))
sit_aluno['MEDIA'] = float(input('Média: '))
if sit_aluno['MEDIA'] < 5:
sit_aluno['SITUACAO'] = 'REPROVADO!'
elif 5 <= sit_aluno['MEDIA'] <= 7:
sit_aluno['SITUACAO'] = 'RECUPERAÇÃO!'
else:
sit_aluno['SITUACAO'] = 'APROVADO!'
for k, v in sit_aluno.items():
print(f'{k} do aluno é: {v}')
|
cf1beb99ca0ff03ed37555bc54d74479e744473c | rfa7/python | /add.py | 1,872 | 3.671875 | 4 | import sqlite3
from datetime import datetime
#def addDeveloper(name, joiningDate):
def addDeveloper(name):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_create_table_query = '''CREATE TABLE IF NOT EXISTS new_developers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
joiningDate timestamp);'''
cursor = sqliteConnection.cursor()
cursor.execute(sqlite_create_table_query)
# insert developer detail
sqlite_insert_with_param = """INSERT INTO 'new_developers'
('name', 'joiningDate')
VALUES(?,?);"""
#data_tuple = (id, name, joiningDate)
data_tuple = (name, datetime.now())
cursor.execute(sqlite_insert_with_param, data_tuple)
sqliteConnection.commit()
print("Developer added succesfully \n")
# get developer detail
sqlite_select_query = """SELECT name, joiningDate from new_developers where id = last_insert_rowid();"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
for row in records:
developer = row[0]
joining_Date = row[1]
print(developer, " joined on", joining_Date)
print("joining date type is", type(joining_Date))
cursor.close()
except sqlite3.Error as error:
print("Error while working with SQLite", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("sqlite connection is closed")
addDeveloper(input('Dev Name:'))
|
e3fe28cedded72f55cb34051ab0def4596258c52 | eulersformula/Lintcode-LeetCode | /Merge_Sorted_Array_II.py | 920 | 4.25 | 4 | #Merge two given sorted integer array A and B into a new sorted integer array.
#Example
#A=[1,2,3,4]
#B=[2,4,5,6]
#return [1,2,2,3,4,4,5,6]
#Method 1: Time complexity O(n), Space complexity O(n)
class Solution:
#@param A and B: sorted integer array A and B.
#@return: A new sorted integer array
def mergeSortedArray(self, A, B):
res = []
i, j, lenA, lenB = 0, 0, len(A), len(B)
while i < lenA and j < lenB:
if A[i] <= B[j]:
res.append(A[i])
i += 1
else:
res.append(B[j])
j += 1
if i == lenA:
return res + B[j:]
if j == lenB:
return res + A[i:]
#Challenge
#How can you optimize your algorithm if one array is very large and the other is very small?
#In this case, might use binary search to insert the small array. Time complexity will be O(m log(n)).
|
2e4954fae0201205a049f16753bd67df8edbbe37 | mahendraphd/Python_LD | /topLevelExample12.py | 663 | 3.78125 | 4 | import tkinter as tk
root = tk.Tk()
def create_top():
win = tk.Toplevel(root)
win.rowconfigure(1, weight=1)
win.columnconfigure(1, weight=1)
win.title("Toplevel")
f1 = tk.Frame(win, height=50, width=400, bg='red')
f1.grid_propagate(0)
f1.grid(row=0, column=0,sticky="nsew")
f2 = tk.Frame(win,height=20, width=400,bg='black')
f2.grid(row=1, column=0,sticky="nsew")
tk.Label(f1, text="FRAME1", bg='red',width=20,font=20,anchor="e").grid()
tk.Label(f2, text="FRAME 2").grid()
tk.Button(root, text="ABC").grid(column=0, row=0)
tk.Label(root, text="FOO").grid(column=1, row=1)
root.after(10, create_top)
root.mainloop() |
2882b8f46f61835a945749912cf79e89e9c1defd | BaoziSwifter/MyPythonLeetCode | /pythonLeetcode/53-最大子序和.py | 1,052 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/20 17:26
# @Author : Beliefei
# @File : 53-最大子序列.py
# @Software: PyCharm
"""
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
"""
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sumVal = 0
if nums is None:
return 0
max_sub = nums[0]
for item in nums:
sumVal += item
if sumVal > max_sub:
max_sub = sumVal
if sumVal < 0 :
sumVal = 0
return max_sub
if __name__ == "__main__":
s = Solution()
print("max value is %d" % s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
|
506d7e0207f0ff6e55debfbf2647ce85916e4804 | Ritvik19/CodeBook | /data/HackerRank-Python/Collections deque.py | 312 | 3.53125 | 4 | from collections import deque
d = deque()
for i in range(int(input())):
cmd, *arg = input().split()
if cmd == 'append':
d.append(int(arg[0]))
if cmd == 'pop':
d.pop()
if cmd == 'popleft':
d.popleft()
if cmd == 'appendleft':
d.appendleft(int(arg[0]))
print(*d)
|
7ad96483759e22a1d5c4adcb4ad879341ab328fa | sarahhancock/well_drawdown_model | /well_drawdown_model.py | 8,152 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy.special import exp1
import matplotlib.animation as animation
plt.style.use('ggplot')
"""
PROGRAM DESCRIPTION
This program models the impact of transient groundwater flow
and pumping wells on the hydraulic head in a confined aquifer.
It starts with a 100 by 100 numpy array containing the initial
hydraulic head levels in the aquifer, and it takes user input
for the aquifer properties, the number of wells, and the time
for the simulation to be run.
It uses the finite difference method to calculate the drawdown
due to transient water flow at each point in the grid for each
timestep, and it uses the Theis solution (calculated using the scipy
package) to calculate the drawdown due to each pumping well at each
point in the grid for each timestep. Then, because of the principle
of superposition, the drawdown values at each point are summed to get
the total change in hydraulic head at each timestep.
Finally, matplotlib's imshow function is used to create a pcolormesh
animation of the hydraulic heads every 20 time steps, and this
animation is saved to the current directory.
Assumes valid user input (i.e. users input integer values when asked).
"""
"""
METHODS
"""
"""
Returns the drawdown due to transient flow after one time step
in the aquifer at each point in the grid as a numpy array with
the same size as the grid.
"""
def get_transient_drawdown(S,T,dx,H,dt):
H_new = np.copy(H)
b = T*dt/(S*dx**2)
a = 1-4*b
H_new[1:99, 1:99] = a*H[1:99, 1:99] + \
b*(H[2:100, 1:99] + H[0:98, 1:99] + \
H[1:99, 2:100] + H[1:99, 0:98])
transient_drawdown = H_new - H
return transient_drawdown
"""
Returns the drawdown due to a particular well at a
single point at a distance, r, from the well.
Used as a helper function for get_well_drawdowns.
"""
def get_well_drawdown(S, T, r, t, Q):
u = S*r**2/(4*T*(t+1**-9))
W = exp1(u)
return Q*W/(4*np.pi*T)
"""
Adds a well to the grid.
"""
def add_well(well_locations, i, j, Q, X):
well_drawdown_prev = X*0
well_locations.append([i,j,Q,well_drawdown_prev])
return
"""
Gets the distance of a point from a well location.
Used as a helper function for get_well_drawdowns.
"""
def get_r_from_well(i,j,i_well, j_well):
return np.sqrt((i-i_well)**2 + (j - j_well)**2)
"""
Finds the drawdown caused by one well at each point
on the grid and returns the drawdown values as a numpy
array with the same shape as the grid.
"""
def get_well_drawdowns(well, S, T, t, dx, dy):
i_well = well[0]
j_well = well[1]
Q = well[2]
well_drawdown_prev = well[3]
i = np.arange(0,100,1)
j = np.arange(0,100,1)
I, J = np.meshgrid(i,j)
radii = np.copy(I)
radii[:] = get_r_from_well(I*dx,J*dy,i_well, j_well)
radii[int(j_well/dx), int(i_well/dy)] = 1**(-10)
well_drawdown = np.copy(radii)
well_drawdown = get_well_drawdown(S,T,radii[:],t,Q)
added_well_drawdown = well_drawdown - well_drawdown_prev
well_drawdown_prev[:] = well_drawdown
well[3] = well_drawdown_prev
return added_well_drawdown
if __name__ == '__main__':
"""
This part of the code sets up the initial conditions for the hydraulic head in a
100 by 100 numpy grid. The dimensions of the aquifer are set here as 1000 by 1000,
and the head has been raised between x = (200,300) and y = (600,800) to demonstrate
the transient groundwater flow, but these initial conditions can easily be changed
for different scenarios,
"""
dx = 10
dy = 10
xLen = 1000
yLen = 1000
x = np.arange(0., xLen, dx)
y = np.arange(0., yLen, dy)
X,Y = np.meshgrid(x,y)
H = np.full((100,100), 50.)
H[20:30, 60:80] = 60.
well_locations = []
min_h = np.amin(H)
max_h = np.amax(H)
t = 0
count = 0
heads_over_time = []
"""
This part of the code prompts the user to enter aquifer properties, well locations,
well properties, and the time for which the simulation should be run. It is important
to note that storativity values are typically very small (0.0001 to 0.00001), but this
creates a very small time step, dt, for using the finite difference method to get the drawdown
for transient flow. For testing the program, I recommend using a storativity of around 0.1 or
a very small time over which the simulation is run. However, if this program was being used
to model an actual aquifer over time with small storativity values, it would still work, it
would just take a long time to run.
"""
print("\nThis program allows you to simulate the effect of wells on a confined aquifer over time. \n ")
print("Your aquifer is {} by {} m. \n ".format(xLen,yLen))
print("Now, you can input the properties of the aquifer. \n")
S = float(input("Enter the storativity (unitless): "))
T = float(input("Enter the transmissivity (m^2/day): "))
dt = S*dx**2/(4*T)
n_wells = input("How many wells would you like to add? ")
for i in range(0, int(n_wells)):
x_well = int(input("Please enter the x coordinate of well " + str(i+1) + " in meters. "))
y_well = int(input("Please enter the y coordinate of well " + str(i+1) + " in meters. "))
Q = float(input("Please enter Q, the pumping rate of the well, in m^3/day (Q < 0 for pumping water out, and Q > 0 for pumping water in). "))
add_well(well_locations, x_well, y_well, Q, X)
t_max = float(input("Enter the number of days you would like the simulation to run for: "))
print("Ok, running simulation for " + str(t_max) + " days.")
while (t <= t_max+1):
transient_drawdown = get_transient_drawdown(S,T,dx,H,dt)
for well in well_locations:
well_drawdown = get_well_drawdowns(well, S, T, t, dx, dy)
H += well_drawdown
H += transient_drawdown
H = H*(H>=0)
if (count%20 == 0):
heads_over_time.append([t, H])
if np.amin(H) < min_h:
min_h = np.amin(H)
if np.amax(H) > max_h:
max_h = np.amax(H)
t+=dt
count+=1
"""
This part of the code creates a pcolormesh animation of the hydraulic
head over the given time range by creating a 3D array indexed by the
x-coordinate, y-coordinate, and time.
"""
nPlots = len(heads_over_time)
H3D = np.full((100,100,nPlots),0.)
T = np.arange(0, t_max, dt)
for k in range(nPlots):
heads = heads_over_time[k][1]
for i in range(0,100):
for j in range(0,100):
H3D[i,j,k] = heads[i,j]
fig = plt.figure(facecolor='w', figsize = (10,6))
ax = plt.axes(xlabel = "X Position (m)", ylabel = "Y Position (m)")
ax.set_title("Hydraulic Head from t=0 to t={} days".format(int(t_max)))
im = ax.imshow(H3D[:,:,0], origin = 'lower', vmin = min_h, vmax = max_h, extent = (0, xLen, 0, yLen))
im.set_data(H3D[:,:,0])
plt.close()
fig.colorbar(im, label = "Hydraulic Head (m)")
def update_data(i):
im.set_data(H3D[:,:,i])
return
ani = animation.FuncAnimation(fig, update_data, interval = 150, frames = nPlots, blit = False)
filename = 'aquifer_model.mp4'
ani.save(filename)
print("Task completed. File saved as {} in current directory".format(filename))
"""
Sarah Hancock, seh2209
12/4/2019
***ADDITIONAL SOURCES (other than class materials)***
Calculating Well Drawdown Resources:
Introduction to Hydrology, Margulis (textbook) (pg. 303 especially)
(for Theis solution equation and basic hydrology resources)
https://scipython.com/blog/linear-and-non-linear-fitting-of-the-theis-equation/)
(for numerical solution of Theis solution in Python)
Drawdown Superposition Resources:
https://pubs.usgs.gov/of/1984/0459/report.pdf
http://inside.mines.edu/~epoeter/_GW/15wh4Superpsition/WellHydraulics4pdf.pdf
Animating pcolormesh Resources:
https://brushingupscience.com/2016/06/21/matplotlib-animations-the-easy-way/
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.imshow.html
""" |
787db91ec148afd3a51bd71b23a4be7b1527dcf8 | turingtei/Python_Tutorial | /lesson_5b_ex1.py | 772 | 4.46875 | 4 | '''
Create a dictionary day_to_number that converts the days of
the week "Sunday", "Monday", … into the numbers 0, 1, ...,
respectively
'''
# Day to number dictionary problem
###################################################
# Student should enter code below
day_to_number = {"Sunday": 0, "Monday": 1, "Tuesday":2, "Wednesday":3,
"Thursday":4,"Friday":5,"Saturday":6}
###################################################
# Test data
print (day_to_number["Sunday"])
print (day_to_number["Monday"])
print (day_to_number["Tuesday"])
print (day_to_number["Wednesday"])
print (day_to_number["Thursday"])
print (day_to_number["Friday"])
print (day_to_number["Saturday"])
###################################################
# Sample output
#0
#1
#2
#3
#4
#5
#6
|
e5823469dfb8e1f724712e429038792d38c5a974 | unchitta/py | /smallest_num.py | 366 | 4.09375 | 4 | # smallest_num.py
# challenge: write a function that takes 3 numbers returns the smallest one
# Sep 2014, Unchitta Kan
print "Finding the smallest number"
def getMin(a,b,c):
x = 0
if (a > b):
x = b
else:
x = a
if (x < c):
print "the smallest number is " , x
else:
print "the smallest number is " , c
getMin(3,10,14)
|
b5216cc5c8f79da0dbbb46ef9f432e4c4fa0455d | Viccari073/extra_excercises | /estruturas_condicionais5.py | 993 | 4.1875 | 4 | """
Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade:
- Se ele ainda vai se alistar ao serviço militar;
- Se é a hora de se alistar;
- Se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
"""
from datetime import date # pega o ano atual
ano_nasc = int(input('Digite o ano do seu nascimento: '))
ano_atual = date.today().year
idade = ano_atual - ano_nasc
print(f'Quem nasceu em {ano_nasc} tem {idade} anos.')
if idade == 18:
print(f'Com {idade} você deve se alistar imediatamente!')
elif idade < 18:
saldo = 18 - idade
print(f'Ainda faltam {saldo} ano(s) para o alistamento.')
ano = ano_atual + saldo
print(f'Seu alistamento será {ano}.')
else: # elif idade > 18:
saldo = idade - 18
print(f'Você deveria ter se alistado à {saldo} ano(s).')
ano = ano_atual - saldo
print(f'Seu alistamento foi {ano}.')
|
c62e91789e93ed5ed2c10618eeda45ccd2102954 | ShararAwsaf/Algorithms-Course | /Course-Contents/assignments/A4/practice/OBST.py | 4,487 | 3.5 | 4 |
class CRCell:
def __init__(self, C, R):
self.C = C
self.R = R
class TreeNode:
def __init__(self, value):
self.value = value
self.left_subtree = None
self.right_subtree = None
class Item:
def __init__(self, v, prob):
self.v = v
self.prob = prob
def Construct_OBST_Table(K):
# K is 1 indexed
# assumes k is sorted
n = len(K) - 1
print("N:", n)
CR_Table = [[CRCell(0, None) for _ in range(0, n+1)] for _ in range(0, n+2)]
# initialize with base case
for i in range(1, n+1):
CR_Table[i][i-1] = CRCell(0, None)
CR_Table[i][i] = CRCell(K[i].prob, i) # index to the nodes are held not the actual value
CR_Table[n+1][n] = CRCell(0, None)
print("INITIALIZATION")
print_CR_Table(CR_Table)
# create table using bottom up
for d in range(1, n): # diagonals 1 to n-1
print('D: ',d)
for i in range(1, n - d+1): # all rows until d
j = d + i # i used as offset
print("i: ", i, "j: ", j)
min_cost = float('inf')
min_root = None
# finds the minimum among the Ci,j until current from left to right and bottom up
for l in range(i, j+1): # i<= l <= j
cost = CR_Table[i][l-1].C + CR_Table[l+1][j].C
if cost < min_cost:
min_cost = cost
min_root = l
W = 0
for s in range(i, j+1):
W += K[s].prob
CR_Table[i][j] = CRCell(min_cost + W, min_root)
return CR_Table
def print_CR_Table(CR_Table):
ROW = len(CR_Table)
COL = len(CR_Table[0])
print('I:', ROW, 'J:', COL)
for i, r in enumerate(CR_Table):
if i: # skip the 0-th row
print('{}:'.format(i), end=' ')
for cell in r:
print("[({:.0f})({})] ".format(cell.C, cell.R), end=' '*(4-len(str(cell.R))))
print()
def ConstructTreeFromTable(CR_Table, K):
def find_subtree_rec(L, R):
R_lr = CR_Table[L][R].R
node= TreeNode(K[R_lr])
print("L:{} R:{}".format(L,R))
print("Going Left ({})".format(node.value.v))
node.left = None if R_lr-1 < L else find_subtree_rec(L, R_lr-1)
print("Going Right ({})".format(node.value.v))
node.right = None if R_lr+1 > R else find_subtree_rec(R_lr+1, R)
return node
T = find_subtree_rec(1, len(K)-1) # 1,n is the first root
return T
def CreateOBST(items):
# Items are a list of items with their probabilities
n = len(items)
K = [Item(None, 0.0) for _ in range(0, n+1)]
K[1:n+1] = sorted(items, key=lambda x:x.v)[:] # sort based on the value of the items and store them in 1 indexed K
printItems(K)
CR_Table = Construct_OBST_Table(K)
print("COST-ROOT TABLE")
print_CR_Table(CR_Table)
T = ConstructTreeFromTable(CR_Table, K)
print("LEVEL BY LEVEL TREE (L->R)")
bfs(T)
def bfs(T):
levels = [(T, 1)]
level = 1
frontier = [T]
while frontier:
nxt = []
level += 1
for v in frontier:
# if v.left or v.right:
levels.append((v.left, v.right, level))
if v.left:
# print("{}".format(v.left.value.v), end=' ')
nxt.append(v.left)
if v.right:
# print("{}".format(v.right.value.v), end=' ')
nxt.append(v.right)
frontier=nxt
levels.sort(key=lambda x: x[-1])
prev_level = 1
for L in levels:
for x in range(0,len(L)-1):
if prev_level != L[-1]:
print()
else:
print(L[-1], end = " ")
v = L[x].value.v if L[x] else None
print("{} ".format(v), end=' ') # print left to right (in-order)
prev_level = L[-1]
print()
def printItems(items):
for i in items:
print(" {} : {} ".format(i.v, i.prob))
# TA = [
# Item('D', 0.100),
# Item('B', 0.020),
# Item('A', 0.213),
# Item('C', 0.547),
# Item('E', 0.12),
# ]
TA = [
Item('C', 4),
Item('A', 1),
Item('B', 2),
Item('D', 3),
]
CreateOBST(TA)
|
c8a8dcedeada81fb94067cddcbb518024b4ce236 | surferJen/practice_problems | /coderbyte_timeConvert.py | 354 | 4.03125 | 4 | # Have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon.
# Sample Test Cases
# Input:126
# Output:"2:6"
# Input:45
# Output:"0:45"
def TimeConvert(num):
|
74477f1d4aa19e88778c992678655b7f4d687cfe | Devika-Baddani/python-program | /amstrong.py | 240 | 4.125 | 4 | num = int(input("enter a number: "))
d_num = num
s = 0
while num>0:
r = num%10
s = s + r**3
num //= 10
if s== d_num:
print(d_num, "is an amstrong number")
else:
print(d_num, "is not an amstrong number")
|
f052e6d032ca3481513a1f2e319e282d0ef6ed20 | green-fox-academy/Atis0505 | /week-02/day-01/animals_and_legs.py | 331 | 4.40625 | 4 | # Write a program that asks for two integers
# The first represents the number of chickens the farmer has
# The seconf represents the number of pigs the farmer has
# It should print how many legs all the animals have
chickens = int(input("Chicken: "))
pigs = int(input("Pig: "))
print("Legs number: " + (str(2*chickens + 4*pigs))) |
517b63618e548904b9772056523fe166ed1a962d | cs-fullstack-2019-spring/python-review-functions-cw1-gkg901 | /morningCW.py | 1,641 | 4.09375 | 4 | def main():
# ex1()
ex2()
def dothemath(n1,n2):
myDict = {"SUM": n1+n2,"DIFF":n1-n2,"PROD":n1*n2,"QUOT":n1/n2}
return myDict
# Create a function that has a loop
# Prompt for numbers until the user enters q to quit
# If the user doesn't enter q, ask them to input another number
# When the user enters q to quit, print the SUM of all numbers entered
def ex1():
nums = []
userInput = ""
while (userInput != 0):
userInput = int((input("enter a number")))
nums.append(userInput)
print(sum(nums))
# Create a function problem2()
# In this function prompt the user for 2 numbers
# Create a second function called do_the_math that accepts 2 parameters (the 2 entered numbers)
# In the do_the_math calculate the SUM, DIFFERENCE, PRODUCT, and QUOTIENT (division result)
# and return them as a dictionary to the calling function
# Example: Dictionary result returned if the arguments 25 and 10 are passed to the function:
# {'diff': 15, 'prod': 250, 'quot': 2.5, 'sum': 35}
# In your problem2() function, print the dictionary result
# returned from your do_the_math function using string literal formatting
def ex2():
num1 = int(input("enter a number\n"))
num2 = int(input("enter a number\n"))
result = dothemath(num1,num2)
print(f'Here are your results for the numbers {num1} and {num2}')
print(f'The SUM result is {result["SUM"]}')
print(f'The DIFFERENCE result is {result["DIFF"]}')
print(f'The PRODUCT result is {result["PROD"]}')
print(f'The DIVISION result is {result["QUOT"]}')
if __name__ == '__main__':
main() |
e2b60c729c42736b0db3f3ad01b425d009664b53 | cat-box/2019PythonAssignments | /assignment1/test_team.py | 6,943 | 3.5 | 4 | import unittest
from unittest import TestCase
from team import Team
from player_forward import PlayerForward
from player_goalie import PlayerGoalie
import inspect
class TestTeam(TestCase):
""" Unit Tests for the Team Class """
def setUp(self):
self.logPoint()
self.team = Team()
self.forward = PlayerForward(47, "Sven", "Baertschi", 180.34, 190, 47, "Oct 5, 1992", "2011", "LW", "L", 8, 5, 40)
self.goalie = PlayerGoalie(1, "Roberto", "Luongo", 190.5, 215, 1, "Apr 4, 1979", 1997, 788, 83, 705, 30, 12, 13)
self.undefined_value = None
self.empty_value = ""
def test_team(self):
""" 010A: Valid Construction """
self.logPoint()
self.assertIsNotNone(self.team, "Team must be defined")
def test_add(self):
""" 020A: Valid Add Player """
self.logPoint()
self.assertIsNotNone(self.forward, "Player must be defined")
self.team.add(self.forward)
self.assertEqual(len(self.team.get_all_players()), 1, "Team must have 1 player")
def test_add_undefined(self):
""" 020B: Invalid Add Player """
self.logPoint()
undefined_player = None
self.assertRaisesRegex(ValueError, "Player must be defined", self.team.add, undefined_player)
def test_add_player_already_exists(self):
""" 020C: Invalid Add Player - Player Already Exists """
self.logPoint()
self.assertEqual(len(self.team.get_all_players()), 0, "Team must have no players")
self.team.add(self.forward)
self.assertEqual(len(self.team.get_all_players()), 1, "Team must have 1 player")
self.team.add(self.forward)
self.assertEqual(len(self.team.get_all_players()), 1, "Team must still only have 1 player")
def test_delete(self):
""" 030A: Valid Delete Player """
self.logPoint()
self.team.add(self.forward)
player_list = self.team.get_all_players()
self.assertEqual(len(player_list), 1, "Team must have 1 player")
self.assertEqual(player_list[0].get_id(), 47)
self.team.delete(47)
self.assertEqual(len(self.team.get_all_players()), 0, "Team must have no players")
def test_delete_invalid_player_id(self):
""" 030B: Invalid Delete Player Parameters """
self.logPoint()
self.assertRaisesRegex(ValueError, "Player ID cannot be undefined", self.team.delete, self.undefined_value)
self.assertRaisesRegex(ValueError, "Player ID cannot be empty", self.team.delete, self.empty_value)
def test_delete_non_existent_player(self):
""" 030C: Invalid Delete Player - Player is Non-Existent """
self.logPoint()
self.team.add(self.forward)
player_list = self.team.get_all_players()
self.assertEqual(len(player_list), 1, "Team must have 1 player")
self.assertEqual(player_list[0].get_id(), 47)
self.team.delete(99)
self.assertEqual(len(self.team.get_all_players()), 1, "Team must have 1 player")
def test_get_player(self):
""" 040A: Valid Get Player """
self.logPoint()
self.team.add(self.forward)
retrieved_player = self.team.get_player(47)
self.assertEqual(retrieved_player.get_id(), 47, "Player must have player ID 47")
self.assertEqual(retrieved_player.get_zone(), "LW", "Player must have zone LW")
self.assertEqual(retrieved_player.get_stats(), [8, 5, 40], "Player must have stats [8, 5, 40]")
def test_get_player_invalid_player_id(self):
""" 040B: Invalid Get Player Parameters """
self.logPoint()
self.assertRaisesRegex(ValueError, "Player ID cannot be undefined", self.team.get_player, self.undefined_value)
self.assertRaisesRegex(ValueError, "Player ID cannot be empty", self.team.get_player, self.empty_value)
def test_get_player_non_existent(self):
""" 040C: Invalid Get Player - Player is Non-Existent"""
self.logPoint()
self.team.add(self.forward)
self.team.add(self.goalie)
self.assertIsNone(self.team.get_player(99), "No player should exist for 99")
def test_get_all_players(self):
""" 050A: Valid get_all_players() """
self.logPoint()
self.team.add(self.forward)
self.team.add(self.goalie)
list_players = self.team.get_all_players()
self.assertEqual(len(list_players), 2)
self.assertEqual(list_players[0].get_fname(), "Sven", "Player must have first name 'Sven'")
self.assertEqual(list_players[1].get_id(), 1, "Player must have id '1'")
def test_get_all_players_invalid(self):
""" 050B: Invalid get_all_players() """
self.logPoint()
list_players = self.team.get_all_players()
# Check empty list
self.assertEqual(len(list_players), 0, "Team must have no players")
self.team.add(self.forward)
list_players = self.team.get_all_players()
self.assertIsNotNone(list_players[0], "Player must be defined")
def test_get_all_by_type(self):
""" 060A: Valid Get all by Type """
self.logPoint()
self.team.add(self.forward)
self.team.add(self.goalie)
list_players_forward = self.team.get_all_by_type("Forward")
list_players_goalie = self.team.get_all_by_type("Goalie")
self.assertEqual(len(list_players_forward), 1)
self.assertEqual(list_players_forward[0].get_type(), "Forward", "Player must have Player Type Forward")
self.assertEqual(len(list_players_goalie), 1)
self.assertEqual(list_players_goalie[0].get_type(), "Goalie", "Player must have Player Type Goalie")
def test_get_all_by_type_invalid_player_type(self):
""" 060B: Invalid Get all by Type Parameters """
self.logPoint()
self.assertRaisesRegex(ValueError, "Player Type cannot be undefined", self.team.get_all_by_type, self.undefined_value)
self.assertRaisesRegex(ValueError, "Player Type cannot be empty", self.team.get_all_by_type, self.empty_value)
self.assertRaisesRegex(ValueError, "Player Type must be Forward or Goalie", self.team.get_all_by_type, "Defense")
def test_update(self):
""" 070A: Valid Update """
self.logPoint()
self.team.add(self.forward)
self.team.add(self.goalie)
new_forward = PlayerForward(47, "Yann", "Sauve", 190.5, 207.24, 47, "Feb 18, 1990", "2008", "RW", "L", 12, 8, 43)
self.team.update(new_forward)
self.assertEqual(self.team.get_player(47).get_full_name(), "Yann Sauve")
def tearDown(self):
self.logPoint()
def logPoint(self):
currentTest = self.id().split('.')[-1]
callingFunction = inspect.stack()[1][3]
print('in %s - %s()' % (currentTest, callingFunction))
if __name__ == "__main__":
unittest.main() |
0b8a9f2ac8d6fceb9900d7d370652d2fef536267 | rinman75/lesson1 | /cod.py | 182 | 3.5 | 4 |
def get_summ(one, two, delimiter = "&"):
b = one + delimiter + two
return b.upper()
learn = "hello"
python = "yury"
get_summ(learn, python)
print(get_summ(learn, python)) |
dfbb4a4ea8352adb5a56bca9066acd506993f0e3 | novartval/simplebot | /ls2.py | 2,418 | 3.671875 | 4 | school = [
{'Class':'11', 'Оценки': [3,4,5,6,4,5]},
{'Class':'10', 'Оценки': [5,4,5,2,3,4]},
{'Class':'10', 'Оценки': [5,4,5,2,3,4]},
{'Class':'10', 'Оценки': [5,4,5,2,3,4]},
{'Class':'10', 'Оценки': [5,4,5,2,3,4]},
{'Class':'10', 'Оценки': [5,4,5,2,3,4]},
{'Class':'9', 'Оценки': [3,4,5,6,3,5]}
]
def mean_assessment_class(school):
mean_assessments = {}
for classes in school:
mean_assessments[classes[u'Class']] = sum(classes[u'Оценки']) / float(len(classes[u'Оценки']))
return mean_assessments
def mean_assessments_school(school):
sum_assessments = 0
cnt_assessments = 0
for classes in school:
sum_assessments += sum(classes[u'Оценки'])
cnt_assessments += len(classes[u'Оценки'])
return sum_assessments / cnt_assessments
mean_assessments_dict = mean_assessment_class(school)
for key, value in mean_assessments_dict.items():
print(key,value)
print(mean_assessments_school(school))
''''
def age_input(age):
if age < 7:
print('Пользователь еще в детском саду.')
elif age >= 7 and age <= 18:
print('Пользователь учится в школе')
elif age >= 18 and age <= 25:
print('Пользователь учится в вузе')
else:
print('Пользователь работает.')
age = int(input('Введите возраст пользователя:'))
alex = age_input(age)
'''
def check_str(first_str,second_str):
if not isinstance(first_str,str) or not isinstance(second_str, str):
return 0
elif first_str == second_str:
return 1
elif first_str != second_str and second_str != 'learn':
if len(first_str) > len(second_str):
return 2
else:
return 'Ни одно условие не будет выполнено'
elif first_str != second_str:
if second_str == 'learn':
return 3
def asking_qwest():
asking_dict = {'Как ты?':'Неплохо', 'Чем занят?':'учусь',
'Что будешь делать дальше?':'спать'}
while True:
ask = str(input(''))
if ask in asking_dict:
print(asking_dict[ask])
else:
print('мммммммм, все понятно')
asking_qwest()
|
284d2f98ff6f6cee87f6ed2f4e2103fa2071cc03 | sandeepkumar8713/pythonapps | /10_dynamic_programming/34_assembly_line.py | 2,789 | 3.875 | 4 | # https://www.geeksforgeeks.org/assembly-line-scheduling-dp-34/
# Question : A car factory has two assembly lines, each with n stations. A station is denoted by Si,j where i
# is either 1 or 2 and indicates the assembly line the station is on, and j indicates the number of the station.
# The time taken per station is denoted by ai,j. Each station is dedicated to some sort of work like engine fitting,
# body fitting, painting, and so on. So, a car chassis must pass through each of the n stations in order before
# exiting the factory. The parallel stations of the two assembly lines perform the same task. After it passes
# through station Si,j, it will continue to station Si,j+1 unless it decides to transfer to the other line.
# Continuing on the same line incurs no extra cost, but transferring from line i at station j – 1 to station j on
# the other line takes time ti,j. Each assembly line takes an entry time ei and exit time xi which may be different
# for the two lines. Give an algorithm for computing the minimum time it will take to build a car chassis.
#
# Question Type : ShouldSee
# Used : At each station of each assembly line, calculate minimum time to reach this station, i.e (from previous
# station of same line or previous station of other line). Try to reach exit station, while calculating
# minimum path to reach exit.
# Logic: carAssembleTime(assemTime, transferTime, entryTime, exitTime):
# n = len(assemTime[0])
# first = entryTime[0] + assemTime[0][0]
# second = entryTime[1] + assemTime[1][0]
# for i in range(1, n):
# up = min(first + assemTime[0][i],
# second + transferTime[1][i] + assemTime[0][i])
# down = min(second + assemTime[1][i],
# first + transferTime[0][i] + assemTime[1][i])
# first, second = up, down
# first += exitTime[0], second += exitTime[1]
# return min(first, second)
# Complexity : O(n)
def carAssembleTime(assemTime, transferTime, entryTime, exitTime):
n = len(assemTime[0])
# Time taken to leave first station in line 1
first = entryTime[0] + assemTime[0][0]
# Time taken to leave first station in line 2
second = entryTime[1] + assemTime[1][0]
for i in range(1, n):
up = min(first + assemTime[0][i],
second + transferTime[1][i] + assemTime[0][i])
down = min(second + assemTime[1][i],
first + transferTime[0][i] + assemTime[1][i])
first, second = up, down
first += exitTime[0]
second += exitTime[1]
return min(first, second)
if __name__ == "__main__":
a = [[4, 5, 3, 2], [2, 10, 1, 4]]
t = [[0, 7, 4, 5], [0, 9, 2, 8]]
e = [10, 12]
x = [18, 7]
print(carAssembleTime(a, t, e, x))
|
64c5665dcb6a88551680fe7def8587ba798c82f2 | aamirna/python | /text_module.py | 981 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#This function counts tabs in the text
def count_tabs(text):
return text.count("\t")
#This function counts lines in the text
def count_lines(text):
return text.count("/n")
#This function counts words in the given text
def count_words(text):
return len(text.split())
#This function counts sentences in the given text
def count_sentences(text):
if text[-1] == ".":
return len(text.split(".")) - 1
else:
return len(text.split("."))
#This function remove whitespaces (if more than one consecutive) from the given text
def remove_white_spaces(text):
return " ".join(text.split())
#This function removes punctuation symbols from the given text.
def remove_punctuations(text):
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
output_text = text
for punctuation in punctuations:
output_text = output_text.replace(punctuation, "")
return output_text
# In[ ]:
|
0098f453f83d8133ad81704ee510ae44cd7358c3 | JDavid121/Script-Curso-Cisco-Python | /52 for loop.py | 228 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:45:03 2020
@author: David
"""
for i in range(2, 8, 3):
# 2: initial value.
# 8: final value
# 3: increment
print("The value of i is currently", i) |
c3cf58331b5f8fd26795fceb5b122e7c80a80d40 | hilalekinci/HackerRank-Solutions | /Codes/diagonalDifference.py | 651 | 3.671875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the diagonalDifference function below.
def diagonalDifference(n,arr):
PrimarySum = 0
SecondarySum = 0
for i in range(n):
PrimarySum += arr[i][i]
for j in range(n):
SecondarySum += arr[j][n - j - 1]
return abs(PrimarySum - SecondarySum)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(n,arr)
fptr.write(str(result) + '\n')
fptr.close()
|
b21b6cc68ac01b997a6b214e0d139c6a7068966e | chloro4m/python_practice_codes | /test.py | 98 | 3.75 | 4 | x=1
if x==2:
print("f")
else:
leftt = 7
rightt = 7
print(leftt)
print(rightt)
|
e018ce87d2ac928d64f34032e3d296fc46b082b9 | LyricLy/python-snippets | /quick_sort.py | 498 | 4.09375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
# Public Domain
def quick_sort(t):
if len(t) < 2:
return t
# copy the list (don't modify it)
t = t[:]
# pick the middle element as the pivot
pivot = t.pop((len(t) - 1)//2)
left = list(filter(lambda x: x < pivot, t))
right = list(filter(lambda x: x >= pivot, t))
return quick_sort(left) + [pivot] + quick_sort(right)
if __name__ == '__main__':
import random
nums = [random.randrange(100) for _ in range(20)]
print(quick_sort(nums)) |
4283cc93401afd1400c9c46edd6bd5b875f0d761 | slickFix/Python_algos | /DS_ALGO/GFG_practise/Deque.py | 2,012 | 3.796875 | 4 | class Deque:
def __init__(self,capacity):
self.capacity = capacity
self.arr = [None]*capacity
self.size = self.front = 0
self.rear = capacity-1
def is_full(self):
return self.size == self.capacity
def is_empty(self):
return self.size == 0
def enque_f(self,data):
if self.is_full():
print('Q is full')
return
self.front = (self.front -1) % self.capacity
self.arr[self.front] = data
self.size +=1
def enque_l(self,data):
if self.is_full():
print('Q is full')
return
self.rear = (self.rear + 1) % (self.capacity)
self.arr[self.rear] = data
self.size = self.size + 1
def deque_f(self):
if self.is_empty():
print('Q is empty')
return
data = self.arr[self.front]
self.front = (self.front + 1) % self.capacity
self.size -= 1
def deque_l(self):
if self.is_empty():
print('Q is empty')
return
data = self.arr[self.rear]
self.rear = (self.rear - 1) % self.capacity
self.size -=1
return data
def print_q(self):
front = self.front
rear = self.rear
if abs(self.front -self.rear) == 1:
while front != rear:
print(self.arr[front], end=',')
front = (front + 1) % self.capacity
print(self.arr[rear])
else:
rear = (self.rear + 1) % self.capacity
while front != rear:
print(self.arr[front], end=',')
front = (front + 1) % self.capacity
print(self.arr[rear])
# Driver Code
if __name__ == '__main__':
queue = Deque(3)
queue.enque_f(10)
queue.enque_f(20)
queue.enque_l(30)
print('first')
queue.print_q()
queue.enque_l(40)
queue.deque_f()
queue.enque_l(50)
print('second')
queue.print_q()
|
cd15147e2001ed669acd0b6e99a8bc078f20b135 | Sergio16T/algorithms-dataStructures-python | /dataStructures/queue.py | 842 | 4.28125 | 4 | # (“first-in, first-out”)
# While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a
# list is slow (because all of the other elements have to be shifted by one).
# Due to challenges with list implementation, Python3 has collections.deque which was designed
# to have fast appends and pops from both ends.
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
firstToLeave = queue.popleft() # The first to arrive now leaves
print(firstToLeave) # 'Eric'
secondToLeave = queue.popleft() # The second to arrive now leaves
print(secondToLeave) # 'John'
print(queue) # Remaining queue in order of arrival: deque(['Michael', 'Terry', 'Graham'])
|
08238217714b4f8ff6cc613bee8d28f4ed48990d | youinmelin/practice2020 | /oo_practice_count_time.py | 791 | 3.734375 | 4 | # compute the end time of an opera,while start time and duration time are given
class Time:
def __init__(self,hours:int,minutes:int,seconds:int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def add_time(self,duration):
end_hours = end_minutes = end_seconds = 0
end_hours = self.hours + duration.hours
end_minutes = self.minutes + duration.minutes
end_seconds = self.seconds + duration.seconds
end_hours += int(end_minutes/60)
end_minutes = end_minutes%60
end_minutes += int(end_seconds/60)
end_seconds = end_seconds%60
print (end_hours,':',end_minutes,':',end_seconds)
start_time = Time(10,30,30)
duration_time = Time (2,45,50)
start_time.add_time(duration_time)
|
95ea56571394eb4a6ffeab3e4279f601cad40dac | chai1323/Data-Structures-and-Algorithms | /InterviewBit/Strings/Reverse the String.py | 153 | 3.65625 | 4 | def rev(st):
st = st.split()
rev = st[::-1]
print(rev)
rev = ' '.join(rev)
return rev
s = " hello world! "
print(rev(s))
|
c7eb337499fa11c7e4c19791b1364f73f888b8ce | supportaps/python050920 | /ua/univer/base/hw01arifmetic/task03.py | 729 | 4.15625 | 4 | #3. Расчет площади земельного участка. Один акр земли эквивалентен квадратным метрам.
#Напишите программу, которая просит пользователя ввести общее количество квадратных
#метров участка земли и вычисляет количество акров в этом участке.
#Подсказка: разделите введенное количество на 4047, чтобы получить количество акров.
square_metres = float(input(" Input total amount of square metres: "))
result = square_metres / 4047
print(" The quantity of Akr: ", result) |
5d3d1cc0a76b90dbad54b332074a11b00ad3e806 | g2des/taco4ways | /hackerrank/python/nested_list.py | 594 | 3.703125 | 4 | from operator import itemgetter
if __name__ == '__main__':
scores = list()
second_lowest = None
for _ in range(int(input())):
name = input()
score = float(input())
scores.append([name, score])
scores.sort(key=itemgetter(1,0))
minVal = min(scores, key=itemgetter(1))[1]
# print(scores, minVal)
for score in scores:
if score[1] != minVal and second_lowest is None:
second_lowest = score[1]
# print(second_lowest)
if score[1] == second_lowest:
print(score[0])
|
f2d9cf8404ded5ea82393ff305c12e6d77b21c9c | chends888/CodingInterviews | /rotate_matrix_chen.py | 997 | 3.59375 | 4 | class Solution:
def rotate(self, matrix):
import math
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(math.ceil(len(matrix) / 2)):
for j in range(i, len(matrix[i]) - 1 - i):
print(i, j)
old_index = [i, j]
new_index = [j, len(matrix) - i - 1]
old_tmp = matrix[old_index[0]][old_index[1]]
new_tmp = matrix[new_index[0]][new_index[1]]
matrix[new_index[0]][new_index[1]] = old_tmp
old_index = new_index
new_index = [old_index[1], len(matrix) - old_index[0] - 1]
for _ in range(3):
old_tmp = new_tmp
new_tmp = matrix[new_index[0]][new_index[1]]
matrix[new_index[0]][new_index[1]] = old_tmp
old_index = new_index
new_index = [old_index[1], len(matrix) - old_index[0] - 1] |
b5826d07798740c4f60a8ca0b65d09c00e8487ef | ashleykwan8/class_lab | /skills-1-ashleykwan8/functions.py | 7,804 | 4.1875 | 4 | """SKILLS: FUNCTIONS
Please complete the following promps.
"""
#################### PART 1 ####################
"""PROMPT 1
Write a function that returns `True` if a town name matches the name of your
hometown.
Examples: (let's say my hometown is San Francisco)
- 'Oakland' -> False
- 'San Francisco' -> True
Arguments:
- The name of a town (str)
Return:
- True or False (bool)
"""
# Write your function here
hometown = "San Francisco"
your_hometown = input("What's the name of your hometown?>")
print()#adding space
def matching_hometowns(hometown):
"""Checks if your hometown matches the given hometown."""
if your_hometown == hometown: #check if both match
return True
else:
return False
print(matching_hometowns(hometown))#call the function
print()#adding space
"""PROMPT 2
Write a function that takes in a first and last name and returns a full name.
Examples:
- 'Brighticorn', 'Hackbright' -> 'Brighticorn Hackbright'
Arguments:
- First name (str)
- Last name (str)
Return:
- Full name (str)
"""
# Write your function here
first = input("What is your first name?>")#ask for first name
last = input("What is your last name?>")#ask for last name
print()#adding space
def full_name(first,last):
"""Prints out the full name from the given first and last name."""
return f"{first} {last}"#return full name
print(full_name(first,last))
print()#adding space
"""PROMPT 3
Write a function that prints a greeting.
If the person is from your hometown, print
Hi <full name>, we're from the same place!
Otherwise, print
Hi <full name>, I'd like to visit <town name>!
HINT: You can reuse the functions that you wrote in PROMPT 1 and Prompt 2.
Examples: (still assume my hometown is San Francisco)
- 'Fido', 'Bark', 'Oakland' -> Hi Fido Bark, I'd like to visit Oakland!
- 'Mel', 'M', 'San Francisco' -> Hi Mel M, we're from the same place!
Arguments:
- First name (str)
- Last name (str)
- Hometown (str)
"""
# Write your function here
def greeting(hometown,first,last):
"""Greet the user and say if they're from the same place or wanting to visit their hometown"""
hometown = matching_hometowns(hometown)#reusing function
name = full_name(first,last)#reusing function
if hometown == "San Francisco":
return f"Hello {name}, we're from the same town!"
else:
return f"Hey {name}, I want to visit {your_hometown} some day!"
print(greeting(hometown, first, last))#call function
print()#adding space
"""PROMPT 4
Write a function that returns True if a fruit is a berry.
Valid berries are:
- strawberry
- raspberry
- blackberry
- currant
Examples:
- currant -> True
- durian -> False
Arguments:
- A fruit (str)
Return:
- True or False (bool)
"""
# Write your function here
fruits = input("Write the name of a fruit: ")
berries = ['strawberry', "raspberry", 'blackberry', 'currant','blueberry','boysenberry']
def identify_berry(fruits):
"""See if the given fruits are berries or not"""
# berries = ['strawberry', "raspberry", 'blackberry', 'currant','blueberry','boysenberry']#list of potential berries
if fruits in berries: #check if given fruit is in the berries list
return "Yes, that's a berry!"
else:
return "Sorry, that's not a berry"
print(identify_berry(fruits)) #call function
print()#adding space
"""PROMPT 5
Write a function that returns the shipping cost of an item.
Berries cost $0 to ship. Everything else costs $5.
Arguments:
- Something that needs to be shipped (str)
Return:
- Shipping cost (int)
"""
# Write your function here
def shipping_cost(fruits):
"""Tells user the shipping cost for berries or other items"""
berry = identify_berry(fruits) #getting input from previous function
if fruits in berries: #comparing input to the berries list
return f"The {fruits} will ship for FREE!"
else:
return f"The {fruits} will cost $5 to ship."
print(shipping_cost(fruits))#call the function
print()#adding space
"""PROMPT 6
Write a function that returns the total cost of something by applying
taxes and fees of various states.
States will be given as their two-letter abbreviations. For example,
California's abbreviation is 'CA'.
There are some states with special fees. All fees should be added to the new
subtotal *after* tax:
- CA (California): add a 3% (0.03) tax for recycling
- PA (Pennsylvania): add $2.00 safety fee
- MA (Massachusettes):
- add $1.00 for items with a base price of $100.00 or less
- add $3.00 for items over $100.00
Arguments:
- Base price (int)
- Two-letter state abbreviation (str)
- Tax percentage as a decimal (optional, float)
- If a tax percentage is not given, it defaults to 0.05 (or 5%)
Return:
- Total price after taxes and fees (float)
"""
# Write your function here
price = float(input("How much is your item?> "))
state = input("Choose a state [CA, PA, MA] > ")
print()#adding space
def total_cost(price,state,tax_and_fees = 0.05):
"""Calculate the taxes and cost by state"""
CA_tax = 0.03
PA_fee = 2.00
MA_fee = 1.00 #if cost is < $100
MA_added_fee = 3.00 #if cost is > $100
total_price = 0
if state == "CA":
CA_total = price + CA_tax
total_price += CA_total
elif state == "PA":
PA_total = price + PA_fee
total_price += PA_total
elif state == "MA": #MA has 2 conditions
if price < 100.00:
MA_total = price + MA_fee
total_price += MA_total
else:
total_price = price + MA_added_fee
return f"Your total cost is: ${float(total_price)}"
print(total_cost(price,state,tax_and_fees = 0.05))#call the function
print()#adding space
"""PROMPT 7
Write a function that takes in a list and *any* number of additional arguments.
The function should add all those items to the end of the list and return
the list.
We haven't taught you how to do this! You'll need to do some research on your
own --- find a way to write a Python function that can take in an arbitrary
amount of arguments.
Arguments:
- A list (list)
- Additional args
Return:
- A list with arguments added to the end (list)
"""
# Write your function here
groceries = ['cereal', 'bananas', 'almond milk', 'spinach']
def grocery_list(groceries, *added_groceries):
"""Add groceries to the current grocery list"""
return groceries + list(added_groceries)#add to the groceries list and change tuple into a list
print(grocery_list(groceries, 'tofu', 'apples'))#call the function
print()#adding space
"""PROMPT 8
Write a function that takes in a word and returns a tuple. You'll do this in an
interesting way though, so make sure you read these directions thoroughly.
The tuple will contain two items:
- The given word
- The given word, multiplied 3 times
To do this, your function will create an *inner* function. The *inner*
function will multiply the given word by 3 and return it.
Then, the outer function will call the *inner* function to create a tuple.
Examples:
- 'hi' -> ('hi', 'hihihi')
Arguments:
- A word (str)
Return:
- (word, wordx3) (tuple)
"""
# Write your function here
users_word = input("Type in a word: ")
def create_a_tuple(users_word):
"""Take in a word and mulitply it by 3"""
def multiple_word(users_word, n=3): #hidden from outer function
return users_word * n
new_word = multiple_word(users_word, n=3)#call the inner function
# return word, new_word
return users_word, (new_word) #return the user's word and the tuple
print(create_a_tuple(users_word))#call the outer function
|
11790885a826a5b5434be78c183700e7a9ce0366 | max-szostak/coding_challenges | /leet_code/trapping_rainwater.py | 768 | 3.640625 | 4 | """ Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. """
class Solution:
def trap(self, height):
lmaxes, rmaxes = [], []
hmax = 0
for h in height:
if h > hmax:
hmax = h
lmaxes.append(hmax)
hmax = 0
for h in reversed(height):
if h > hmax:
hmax = h
rmaxes.append(hmax)
rmaxes.reverse()
combined = [min(lmaxes[i], rmaxes[i]) for i in range(len(height))]
water = 0
for i in range(len(height)):
water += combined[i] - height[i]
return water
sol = Solution()
print(sol.trap([0,1,0,2,1,0,1,3,2,1,2,1])) |
ecc6b06574fd5b7e39c89fc55cb00483d2fa10fd | AshwinRaikar88/Python | /Assignments/Class Assignments/Assignment 1/pgm3.py | 313 | 4.1875 | 4 | #Assignment Program 3
number=list()
while(True):
num=input("Enter a number:")
if(num=="done"):
print("Maximum value:",max(number),"Minimum value:",min(number))
break
try:
number.append(int(num))
except:
print("\nInvalid input")
|
5536252a582fe668166671a1bec234f678bd36ca | louismatsika/python | /triangle.py | 129 | 3.796875 | 4 | a=input("enter hieght ")
b=input("enter base ")
height=int(a)
base=int(b)
area=((height*base)/2)
print("the area is",area)
|
0c890156bf6b01d598c2be703c39b8f9386afe95 | Yurikimkrk/PythonInterview | /les2/task_6.py | 1,487 | 3.96875 | 4 | """
6. Проверить на практике возможности полиморфизма.
Необходимо разделить дочерний класс ItemDiscountReport на два класса.
Инициализировать классы необязательно.
Внутри каждого поместить функцию get_info,
которая в первом классе будет отвечать за вывод названия товара,
а вторая — его цены.
Далее реализовать выполнение каждой из функции тремя способами.
"""
class ItemDiscount:
def __init__(self, name, price):
self.__name = name
self.__price = price
def get_name(self):
return self.__name
def get_price(self):
return self.__price
def set_price(self, price):
self.__price = price
class ItemDiscountReportName(ItemDiscount):
def get_parent_data(self):
print(self.get_name())
class ItemDiscountReportPrice(ItemDiscount):
def get_parent_data(self):
print(self.get_price())
PRODUCT1 = ItemDiscountReportName('iPhone 11', 99999)
PRODUCT2 = ItemDiscountReportPrice('Nokia3310', 999)
PRODUCT1.get_parent_data()
PRODUCT2.get_parent_data()
for product in (PRODUCT1, PRODUCT2):
product.get_parent_data()
def product_handler(product):
product.get_parent_data()
product_handler(PRODUCT1)
product_handler(PRODUCT2)
|
82105e7f3450a039dd9d7126b79ff330e33af2cb | spidermedic/Games | /blackjack/cards.py | 1,434 | 4.0625 | 4 | """ Functions related to the deck of cards
The first digit is the suit.
The last two digits are the card.
1 = Ace, 11,12,13 = J, Q, K """
import random
from colors import Colors
color = Colors()
def shuffle():
""" Returns a shuffled 52 card deck."""
main_deck = [101,102,103,104,105,106,107,108,109,110,111,112,113,
201,202,203,204,205,206,207,208,209,210,211,212,213,
301,302,303,304,305,306,307,308,309,310,311,312,313,
401,402,403,404,405,406,407,408,409,410,411,412,413]
# Make a copy of the deck so that the main_deck isn't affected
new_deck = list(main_deck)
# Shuffle the new deck
random.shuffle(new_deck)
return new_deck
def rank(card):
""" Returns the rank of a card. Converts A,J,Q,K to alpha """
if card % 100 == 1:
return ' A'
elif card % 100 == 11:
return ' J'
elif card % 100 == 12:
return ' Q'
elif card % 100 == 13:
return ' K'
else:
return card % 100
def suit(card):
""" Returns a unicode graphic of the suit based on the first number """
# Clubs
if card in range(100,114):
return " \u2663"
# Diamonds
elif card in range(200,214):
return f" {color.red}\u2666{color.blk}"
# Hearts
elif card in range(300,314):
return f" {color.red}\u2665{color.blk}"
# Spades
else:
return " \u2660"
|
97d4d24fd4fea06e0b6815c94575892cd7543146 | srinivasycplf8/LeetCode | /binary_subarrays_with_sum.py | 359 | 3.625 | 4 | def num_sub_array(A):
left_pointer=0
right_pointer=0
count=0
for i in range(len(A)):
if right_pointer>=len(A):
break
if A[left_pointer]+A[right_pointer]==2:
count+=1
left_pointer+=1
right_pointer+=1
right_pointer+=1
print(count)
num_sub_array([1,0,1,0,1]) |
39957ec043beb2a41e4def28ff50680855e135e2 | shyamambilkar/PracticePythonPrograms | /Module_7/Price_of_Product.py | 338 | 4.03125 | 4 | products = {"Mango": 6.9, "Banana": 4.9, "Apple": 4.7}
for pro, price in products.items():
print(pro, " = ", price)
cost = 0
while True:
pro = input("Select Product (n = nothing): ")
if pro == 'n':
break
qty = int(input("Number of Products? "))
cost += products[pro]*qty
print("Price of Product(s): ", cost) |
e2bcff36566e6fcf1c1f7bb53618b00c4eaf92bb | AndreaInfUFSM/elc117-2017a | /trabalhos/t2/svgcolors.py | 1,234 | 3.5 | 4 | #!/usr/bin/env python3
import itertools
'''
Programacao funcional para gerar SVG:
- gera uma lista de coordenadas de retangulos
- define uma lista de estilos (cores), em qualquer quantidade
- aplica os estilos aos retangulos, gerando uma lista com todos os dados para o SVG
- coloca os dados no formato SVG, concatenando strings
'''
def svgRect(rs):
(((x,y),w,h),style) = rs
return "<rect x='%.3f' y='%.3f' width='%.2f' height='%.2f' style='%s'/>\n" % (x,y,w,h,style)
def svgImage(w, h, rs):
return "<svg width='%.2f' height='%.2f' xmlns='http://www.w3.org/2000/svg'>\n" % (w,h) + \
''.join(map(svgRect, rs)) + "</svg>"
def applyStyles(rects, styles):
return list(zip(rects, itertools.cycle(styles)))
# TODO: modifique essa funcao para gerar mais retangulos
def genRects(n, w, h):
return [((0.0,0.0),w,h)]
def writeFile(fname, contents):
f = open(fname, 'w')
f.write(contents)
f.close()
def main():
maxWidth = 1000
maxHeight = 100
rects = genRects(10,50,50)
styles = ["fill:rgb(140,0,0)","fill:rgb(0,140,0)"]
rectstyles = applyStyles(rects, styles)
writeFile("mycolors.svg", svgImage(maxWidth, maxHeight, rectstyles))
if __name__ == '__main__':
main()
|
40fdd8f45580403f0f11fa64ee195b5487371e6d | kevingreenb/Python | /most frequent word.py | 523 | 3.890625 | 4 | """Quiz: Most Frequent Word"""
def most_frequent(s):
arr = s.split();
arr.sort();
m = 0;
for each in arr:
if(arr.count(each)>m):
results = each;
m = arr.count(each);
return results
def test_run():
"""Test most_frequent() with some inputs."""
print(most_frequent("cat bat mat cat bat cat")) # output: 'cat'
print(most_frequent("betty bought a bit of butter but the butter was bitter")) # output: 'butter'
if __name__ == '__main__':
test_run()
|
25c60b9b705099d82a672183b3f4d1a89f782c32 | elocj/FirstWebApp | /convoNN/cnn.py | 2,569 | 3.546875 | 4 | import numpy as np
from convoNN.conv import Conv3x3
from convoNN.maxpool import MaxPool2
from convoNN.softmax import Softmax
conv = Conv3x3(8)
pool = MaxPool2()
softmax = Softmax(47 * 47 * 8, 2)
class Action:
def __init__(self, y_train):
data = np.load('/Users/anthonyjoo/Google Drive/Python/FirstWebApp/convoNN/datatemp.npy')
self.x_train = data[:450]
self.y_train = np.zeros(450).astype(int)
# For when you're ready do
# self.y_train = y_train
self.x_test = data[450:]
self.y_test = np.zeros(147).astype(int)
# self.run()
def forward(self, image, label):
'''
Completes a forward pass of the CNN and calculates the accuracy and
cross-entropy loss.
- image is a 2d numpy array
- label is a digit
'''
# We transform the image from [0, 255] to [-0.5, 0.5] to make it easier
# to work with. This is standard practice.
out = conv.forward((image / 255) - 0.5)
out = pool.forward(out)
out = softmax.forward(out)
# Calculate cross-entropy loss and accuracy. np.log() is the natural log.
loss = -np.log(out[label])
acc = 1 if np.argmax(out) == label else 0
return out, loss, acc
def train(self, im, label, lr=.005):
'''
Completes a full training step on the given image and label.
Returns the cross-entropy loss and accuracy.
- image is a 2d numpy array
- label is a digit
- lr is the learning rate
'''
# Forward
out, loss, acc = self.forward(im, label)
# Calculate initial gradient
gradient = np.zeros(2)
gradient[label] = -1 / out[label]
# Backprop
gradient = softmax.backprop(gradient, lr)
gradient = pool.backprop(gradient)
gradient = conv.backprop(gradient, lr)
return loss, acc
def run(self):
print('MNIST CNN initialized!')
# Train the CNN for 3 epochs
for epoch in range(1):
print('--- Epoch %d ---' % (epoch + 1))
# Shuffle the training data
permutation = np.random.permutation(len(self.x_train))
self.x_train = self.x_train[permutation]
self.y_train = self.y_train[permutation]
# Train!
loss = 0
num_correct = 0
for i, (im, label) in enumerate(zip(self.x_train, self.y_train)):
if i > 0 and i % 100 == 99:
print('[Step %d] Past 100 steps: Average Loss %.3f | Accuracy: %d%%' % (i + 1, loss / 100, num_correct))
# print(softmax.weights)
loss = 0
num_correct = 0
l, acc = self.train(im, label)
loss += l
num_correct += acc
return softmax.weights |
4e1fe34bc121658eef85a30a193fbe7d00caa60a | graceliu2006/LearnToCode | /python/notin.py | 447 | 3.921875 | 4 | # activity = input("What would you like to do today? ")
# if "cinema" not in activity.casefold():
# print("But I want to go to the cinema")
name = input("What is your name? ")
age_string = input("What is your age? ")
if name!="" and age_string!="":
if 18 <= int(age_string) < 31:
print("Welcome to the holiday," + name)
else:
print("Go away! Nobody wants you here, " + name)
else:
print("Please enter an input.") |
b82ded7968d50a106a4a30da360b2ed989f42601 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/FILE I & O/Day79 Tasks/Task3.py | 241 | 4.25 | 4 | '''3. Write a Python program to read a file line by line store it into a variable. '''
def file_read(fname):
with open (fname, "r") as myfile:
data=myfile.readlines()
print(data)
file_read('test.txt') |
a97f074c559e5a091ac66053e99a1d7207cbe638 | arkimede/pysynfig | /objects/tags/Vector.py | 794 | 3.703125 | 4 | class Vector:
def __init__(self, x,y):
self.x = x
self.y = y
self.node = None
def __init__(self,x,y,node=None):
#self.x = x
#self.y = y
self.node = node
self.setX(x)
self.setY(y)
def setNode(self, node):
self.node = node
def getNode(self):
return self.node
def getX(self):
return self.x
def getY(self):
return self.y
def setX(self,x):
self.x = x
if self.node is not None:
self.node.find('x').text = self.x
def setY(self,y):
self.y = y
if self.node is not None:
self.node.find('y').text = self.y
def printXML(self):
xml = """\n""" + "<vector>" + """\n\t""" + "<x>" + self.x + "</x>" + """\n\t""" + "<y>" + self.y + "</y>\n" + "</vector>" + """\n"""
return xml
|
f2acc97bc0fd88d10227e6058e59f6bca19d7d4b | tugisuwon/hackerrank | /exp_by_square.py | 213 | 3.546875 | 4 | def exp_by_square(x,n):
if n == 0:
return 1
elif n == 1:
return x
elif n % 2:
return x*exp_by_square(x*x,(n-1)/2)
elif n % 2 == 0:
return exp_by_square(x*x,n/2)
print exp_by_square(2,15)
|
ea7073d46ec728db3e56ce941f8d13cf9b7f65ca | claraj/ProgrammingLogic1150Examples | /4_loops/while_loop_check_for_number.py | 2,544 | 4.4375 | 4 | """
What if your program expects a numeric value, for example,
number = int(input('Please enter a number: '))
and a user types in 'cat' or
something that is not a number?
The program will crash with a message like this,
Please enter a number: cat
Traceback (most recent call last):
File "while_loop_check_for_number.py", line 10, in <module>
number = int(input('Please enter a number: '))
ValueError: invalid literal for int() with base 10: 'cat'
Python can't convert 'cat' to an int so it "raises an exception" which
means that the program is reporting an error that it can't deal with.
And when a program experiences an error it can't deal with, it crashes and
displays an error message.
It's possible to anticipate and "catch" handle this type of error/exceptions
in your program. In this case, we'd like to allow the user to try again.
"""
# Try to ask user for input... but anticipate there may be an error.
# this is a basic try-except structure. If the user doesn't enter
# a number, they don't get to try again.
try:
number_1 = int(input('Please enter an integer number. You only get one chance: '))
# if the user enters a number, it will be stored in the variable
# number and your program can use it.
print(f'Thank you for entering the number {number_1}')
# note you can only use the number_1 variable here.
except ValueError:
# if the user doesn't enter a number, the line with int() in raises
# A ValueError exception and then this block of code will run.
print('That was not an integer number')
# note that you can't use number_1 variable here - it doesn't exist if the user doesn't enter a number.
# How about allowing the user to try again? Use a while loop.
while True:
try:
number_2 = int(input('Please enter an integer number. You have as many tries as you need to enter a number: '))
# if the user enters a number, it will be stored in the variable
# number and your program can use it.
print(f'Thank you for entering the number {number_2}')
break # we have a number, no need to repeat the loop
except ValueError:
# if the user doesn't enter a number, the line with int() in raises
# A ValueError exception and then this block of code will run.
print('That was not an integer number. Try again.')
# since we are in a while True loop, the loop will repeat and ask the user for input again.
print(f'Number 2 was {number_2}') # What value does this have? Are we guaranteed to have a value?
|
169ae59347df9decf31556b69c85a1bc1c2c7bb2 | masterugwee/StockDataAutomation | /stock.py | 1,805 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
import sqlite3
import os
import datetime
from tabulate import tabulate
from time import sleep
from pathlib import Path
def stocks(con,cursor):
print("Have you made any trades today(y/n)")
checker = input()
counter = 0
while(checker == 'y'):
try:
if(checker == 'y'):
counter += 1
print("Name of stock")
name = input()
print("Amount invested")
amount = float(input())
print("Profit Made")
profit = float(input())
returnAmount = float(input("Return Amount\n"))
numberofstocks = int(input("Number of Stocks\n"))
else:
print("Got! it")
except:
counter = 0
print("Amount/Profit/Return/Stocks values might be wrong")
if(counter >= 1):
date = str(datetime.date.today())
cursor.execute("insert into dailytransaction values(?,?,?,?,?,?)",(name,amount,profit,returnAmount,numberofstocks,date))
conn.commit()
print("Transaction history updated")
checker=input("You wish to add more trades(y/n)\n")
def display(conn,cursor): #DisplayMethod
cursor.execute("select * from dailytransaction")
result = cursor.fetchall()
print(tabulate(result,headers=['Name','Amout Invested','Profit','Return Amount','Number Of Stocks','Date'],tablefmt='psql'))
sleep(20)
if __name__ == "__main__":
conn = sqlite3.connect('/home/varun/stock/Stock.db')
cursor = conn.cursor() #Executer
stocks(conn,cursor)
hist = input("View history(y/n)\n")
if(hist == 'y'):
display(conn,cursor)
conn.close()
else:
print("Bye!")
conn.close()
|
f4ae094851f1289d6a4c29395e8f0b19247a23f9 | trueneu/algo | /interviewcake/delete_node_from_linked_list.py | 886 | 3.90625 | 4 | from copy import deepcopy
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
a = LinkedListNode('A')
b = LinkedListNode('B')
c = LinkedListNode('C')
a.next = b
b.next = c
head = a
def delete_node_linear_with_head(node):
global head
prev_node = None
n = head
while n:
if n is node:
break
prev_node = n
n = n.next
else:
print("Couldn't find the node")
return None
next_node = n.next
if prev_node:
prev_node.next = next_node
else:
head = next_node
def delete_node(node):
try:
node.next, node.value = node.next.next, node.next.value
except AttributeError:
node.value = None
def traverse(head):
n = head
print(n.value)
while n.next:
n = n.next
print(n.value)
traverse(head)
|
db13f1e386beb25e708bebd3428cdce9c22117c7 | adithshetty1995/python-aws-materials | /python_oops.py | 990 | 4.125 | 4 | class Human:
def __init__(self,h,w):
self.h=h
self.w=w
def intro(self):
print(f"Weight of the person is {self.w}")
print(f"Height of the person is {self.h}")
def set_height(self,height): # Set Function
self.h=height
def set_weight(self,weight): # Set Function
self.w=weight
class Male(Human):
def __init__(self, name,h, w):
super().__init__(h, w)
self.name=name
def intro(self):
super().intro()
def set_h(self,height):
super().set_height(height)
def set_w(self,weight):
super().set_weight(weight)
# person=Human(180,65)
# person.intro()
male=Male("Yush",195,70)
male.intro()
male.set_h(200)
male.set_w(100)
# print(f"Weight of the Male is {male.w}")
print(f"Height Modified : {male.h}")
print(f"Weight Modified : {male.w}")
# person.set_height(190)
# person.set_weight(75)
# print(f"Weight of the person is {person.w}")
# print(f"Height of the person is {person.h}") |
2549402c5b3103983e22d50054164a2703235dd3 | superlk/python_study | /登陆时验证用户名和密码 | 1,986 | 3.515625 | 4 | #!/usr/bin/env python
#_*_coding:utf-8_*_
#用户名密码用:分割,让用户输入用户名和密码,判断是否能登陆
arr=['user:pwd','user1:pwd1','user2:pwd2']
while True:
ra_user=raw_input('请输入你的用户名:')
ra_pwd=raw_input('请输入你的密码:')
a=ra_user+':'+ra_pwd
#把两字符串拼接在一起,中间加:
# a=':'.join([ra_user,ra_pwd]) 此方法也可以
print a
if a in arr:
print '登陆成功'
break
else:
print '用户名或密码错误'
-------------------------------------------
请输入你的用户名:user
请输入你的密码:pwd
user:pwd
登陆成功
------------------------------------------
先判断用户名是否正缺,然后再判断密码
arr=['user:pwd','user1:pwd1','user2:pwd2']
#先判断用户名,成功后在判断密码
user_list=[]
pwd_list=[]
for i in arr: #挨个循环列表里的字符串
temp=i.split(':') #把每字符串以‘:’切割成 list
print temp
user_list.append(temp[0]) #把列表里第0个放到一个新的列表
#
pwd_list.append(temp[1]) #把列表里第1个放到另一个新的列表
while True:
raw_user=raw_input('输入用户名:')
if raw_user in user_list:
raw_pwd=raw_input('输入密码')
if raw_pwd == pwd_list[user_list.index(raw_user)]: #user列表里和pwd列表里位置一一对应,user表里第几个索引,对应pwd里德索引值
print 'success'
break
else:
print 'not passwd'
pass
else:
print 'user not exists'
print user_list
print pwd_list
-----------------------------------------------
输入用户名:user
输入密码ii
not passwd
输入用户名:user
输入密码paww
not passwd
输入用户名:user
输入密码pwd
success
['user', 'user1', 'user2']
['pwd', 'pwd1', 'pwd2']
---------------------------------------------------
|
dbf504f7828433a7a0cf7d509e7b947417263c85 | RobertNguyen125/PY4E | /ex_07_files/ex_07_01.py | 185 | 3.765625 | 4 | fname = input ('Enter file name: ')
try:
fhand = open(fname)
except:
print ('file name invalid')
quit()
for line in fhand:
line = line.rstrip().upper()
print(line)
|
a776828330d2a94c34c472695ab6f2c5826fe527 | AlexAbades/Python_courses | /2 - Python Bootcamp/Lesson_3_Classes/Classes.py | 8,903 | 4.78125 | 5 | # Object Oriented Programming
# Working with classes, the way to create our own objects
import numpy as np
class Sample:
pass
my_sample = Sample()
print('my_sample type is: ', type(my_sample))
print('\n')
class Cat:
def __init__(self, breed):
self.breed = breed
my_cat = Cat(breed='Siamese')
print('my_cat type is: ', type(my_cat))
print('my_cat attribute is: ', my_cat.breed)
print('\n')
class Dog:
def __init__(self, breed, name, spots): # Breed it's a parameter, it's also an argument
# __init__ It's a constructor, it's going to be called automatically right after the object has been created
# The keyword "self" it represents the instance of the object itself
self.breed = breed
self.name = name
self.spots = spots
# Attribute are characteristics from the objects, in this case it's self.breed
# We take in the argument, in this case it's breed
# We assign it using self.attribute_name
# The arguments can be different objects, string objects, integer, float, boolean...
# If we define 3 arguments in the constructor, we'll have to pass three parameters
my_neighbour_dog = Dog(breed='Lab', name='Lucas', spots=False)
my_dog = Dog('Mix', 'Miro', False)
print("my_neighbour_dog's class is: ", type(my_neighbour_dog))
print("my_dog's class is: ", type(my_dog))
print('\n')
print('my_dog breed is: ', my_dog.breed)
print('my_dog name is: ', my_dog.name)
print('my_dog has spots: ', my_dog.spots)
print('\n')
class Bird:
# CLASS OBJECT ATTRIBUTE
# SAME FOR ANY INSTANCE OF THE CLASS
# We don't have to use the self keyword, because it's a reference to a particular instance.
species = 'Aves'
# We can define an attribute as a class object level, foe example, a bird, no matter what name, breed or colors,
# it's going to be always an Aves, or a dog a Mammal...
# So instead, of defining a particular instance where we have to define that our dog it's a mammal,
def __init__(self, breed, name, spots):
self.breed = breed
self.name = name
self.spots = spots
my_bird = Bird(breed='parrot', name='perki', spots=False)
my_bird.name
print("my_bird's type is: ", type(my_bird))
print('')
print("my_bird's breed is: ", my_bird.breed)
print("my_bird's name is: ", my_bird.name)
print("my_bird has spots: ", my_bird.spots)
print("my_bird's species is: ", my_bird.species, ", and all my bird instances are going to be ", my_bird.species)
print("\n")
my_neighbour_bird = Bird(breed='cacatua', name='pco', spots=True)
print("my_neighbour_bird's spice is: ", my_neighbour_bird.species)
# METHODS
# Methods are functions defined inside the body of a class. They are used to perform operations with the
# attributes of our objects. Methods are a key concept of the OOP paradigm. They are essential to dividing
# responsibilities in programming, especially in large applications.
class Doggy:
specie = 'Mammal'
def __init__(self, breed, name):
self.breed = breed
self.name = name
# OPERATIONS/Actions --> Methods
# Methods are functions defined inside of a class
def bark(self, age): # We can ask for some parameter when we call our method, like age
print('Woof! My name is {} and I am {} years old'.format(self.name, age)) # self key is no longer needed
# here, because we are passing the age as a parameter in the method, 'cause is not referencing any attribute
# for that instance of the class
my_doggy = Doggy('Lab', 'Lucas')
my_doggy.bark(5)
print('\n')
class Circle:
# Class object attribute
pi = np.pi
def __init__(self, radius=1): # We pass the to the radius parameter the default value of 1
self.radius = radius
self.area = self.radius * self.radius * Circle.pi # We can reference the class object attributes as,
# name_class.name_attribute
# Methods
def get_circumference(self):
return 2 * self.pi * self.radius
my_circle = Circle(8)
print(my_circle.radius)
print(my_circle.area)
print(my_circle.get_circumference())
print('\n')
# INHERITANCE & POLYMORPHISM
class Animal: # We'll call to the class that we want to use in an other class, base class
def __init__(self):
print('Animal created')
def who_am_i(self):
print('I am an animal')
def eat(self):
print('I am eating')
my_animal = Animal()
my_animal.who_am_i()
my_animal.eat()
print('\n')
class Doggo(Animal): # We inherit the base class in the Dog class, it's known as a derived class
def __init__(self):
Animal.__init__(self) # So I'm going to create an instance of the animal class when I create an instance
# on my Doggo class. I'm able to do that because i'm inheriting from the animal class
print('Doggo Created')
# We can rewrite the functions,
def who_am_i(self):
print('I am a Dog')
def bark(self):
print('WOOF!')
my_doggo = Doggo()
my_doggo.who_am_i()
my_doggo.eat()
print('\n')
# POLYMORPHISM
# polymorphism refers to the way in which different object classes can share the same method name, and those methods
# can be called from the same place even though a variety of different objects might be passed in.
class Dinosaur:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' says warg'
class Fish:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' says gluglu'
alan = Dinosaur('Alan')
nemo = Fish('Nemo')
print(alan.speak())
print(nemo.speak())
print('\n')
# PROBE THE POLYMORPHISM
for pet in [alan, nemo]:
print(type(pet))
print(pet.speak())
print(type(pet.speak()))
print('\n')
def pet_class(pet):
print(pet.speak())
pet_class(alan)
pet_class(nemo)
print('\n')
# So in both cases we're able to pass in different objects (Dinasour and Fish) and we obtain object specific results
# from the same mechanism that same method call.
# We can use abstract classes and inheritance, which are those ones that we never expect to instantiate, it only serve
# as a base class
class Insect:
# This class it will never expect to be instantiate it , my_insect = Insect()
def __init__(self, name):
self.name = name
def speak(self):
return NotImplemented("Subclass must implement this abstract method ")
# This will give us an error
# my_insect = Insect('bichi')
# my_insect.speak()
class Bee(Insect):
def speak(self):
return self.name + ' says bsss'
class Fly(Insect):
def speak(self):
return self.name + ' says bsss'
iris = Bee('Iris')
paul = Fly('Paul')
print(iris.speak())
print(paul.speak())
# SPECIAL METHODS
# How to use built in methods such as len, or print
my_lst = [1, 2, 3]
print(my_lst)
print(len(my_lst))
class Sample:
pass
my_sample = Sample()
print(my_sample) # It's going to print where is located the Sample object in memory
# print(len(my_sample)) Erro: object of type 'Sample' has no len(). We don't have this method in our class
print('\n')
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
b = Book('Python bases', 'Alex', 350)
print('Book class, whithout string representation')
print(b) # What is the string representation of b?
# If I ask for the string representation of b, str(b). It will output he same result as print() but as a str,
# between quotation marks
print(str(b))
print('\n')
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self): # We can define a string representation for our class with __str__, so whenever we ask for the
# string representation for our class, it will print whatever we define in that method.
return f"{self.title} by {self.author} "
def __len__(self):
return self.pages
def __del__(self):
print('A book object has been deleted')
my_book = Book('Python advanced', 'Alex Abades', 450)
print('Book class with string representation: ')
print(my_book) # All it does the print method is print the what the sring representation "str()" returns back
print(len(my_book))
# DELETE
# If we want to delete an object of a determinate class of our memory we use "del", in this case we want to delete
# the my_book object from the Book class
del my_book
print(my_book) |
70196630bf988ee8a1b2e572790180c78f77f4e9 | JoseArtur/phyton-exercices | /cap3/c3e3.12.py | 308 | 4.3125 | 4 | #Write a program that calculate the time of a car trip.Ask the distance to go and the medium speed waited for the trip.
dist=int(input("Type the distance of the trip(in km):"))
speed=int(input("Type the medium speed waited(in km/h): "))
time=dist/speed
print(f"The duration of the trip will be {time} hours") |
8d089ac6a5d584d7d7c372d71c91e4ff7ac5b355 | gyoomi/orange | /base/OOPDemo1.py | 3,511 | 4.0625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : Leon
# @Version : 2018/8/27 15:33
# class Car:
# def toot(self):
# print("汽车在鸣笛!")
#
# def move(self):
# print("汽车正在移动...")
#
#
# bm = Car()
# bm.color = "黑色"
# bm.price = "35W"
# print(bm.color)
# print(bm.price)
# bm.move()
# bm.toot()
# __init__()方法
#
# class Car:
# def __init__(self, color, price):
# self.color = color
# self.price = price
#
# def toot(self):
# print("汽车有知识产权")
#
# def move(self):
# print(self.color + "汽车在奔跑...")
#
#
# bm = Car("白色", "Audi")
# print(bm.color)
# print(bm.price)
# 魔法方法
# class Car:
# def __init__(self, color, brand):
# self.color = color
# self.brand = brand
#
# def move(self):
# print(self.color + "的" + self.brand + "汽车在公路上狂奔...")
#
# def __str__(self):
# msg = self.color + "的" + self.brand + "汽车"
# return msg
#
#
# bm = Car("黑色", "宝马")
# bm.move()
# print(bm)
# self类似于c++、java中的this
# python解释器会把这个对象作为第一个参数传递给self,所以开发者只需要传递后面的参数即可
# class Potato:
#
# def __init__(self):
# self.cookedLevel = 0
# self.cookedString = "生的"
# self.condiments = []
#
# def cook(self, time):
# self.cookedLevel += time
# if self.cookedLevel > 8:
# self.cookedString = "烤成灰了"
# elif self.cookedLevel > 5:
# self.cookedString = "烤好了"
# elif self.cookedLevel > 3:
# self.cookedString = "半生不熟"
# else:
# self.cookedString = "还是生的"
#
# def addConditon(self, condiment):
# self.condiments.append(condiment)
#
# def __str__(self):
# msg = self.cookedString + "地瓜"
# if len(self.condiments) > 0:
# msg += "("
# for item in self.condiments:
# msg += item + ","
# msg.strip(",")
# msg += ")"
# return msg
#
#
# sweetPotato = Potato()
# print(sweetPotato)
# sweetPotato.cook(2)
# print(sweetPotato)
# sweetPotato.cook(2)
# print(sweetPotato)
# sweetPotato.cook(2)
# print(sweetPotato)
# class Person:
# def __init__(self, name):
# self.__name = name
#
# def get_name(self):
# return self.__name
#
# def set_name(self, name):
# if len(name) > 5:
# self.__name = name
# else:
# print("error:名字长度需要大于或者等于5")
#
#
# p = Person("小明")
# print(p.get_name())
# __del__()方法
# 创建对象后,python解释器默认调用__init__()方法;
# 当删除一个对象时,python解释器也会默认调用一个方法,这个方法为__del__()方法
class Car:
def __init__(self, brand, color):
self.color = color
self.brand = brand
def __del__(self):
print("对象" + self.brand + "被销毁了")
c1 = Car("宝马", "白色")
c2 = Car("奔驰", "黑色")
del c1
del c2
# 结论:
# 执行del之后如果引用计数等于0,则会立即调用__del__()。
# 执行del之后如果引用计数不等于0,则会在所有程序执行完后自动调用__del__()。
# 如果没有del语句,当所有的程序执行完之后,__del__()会自动被调用,用来清理实例对象,回收内存。
|
4892d1caf1525aef395453f52e2e9ded7e6b3159 | mikhail-ukhin/problem-solving | /array-of-digits.py | 1,021 | 3.71875 | 4 | # Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
# The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
# You may assume the integer does not contain any leading zero, except the number 0 itself.
# Example 1:
# Input: [1,2,3]
# Output: [1,2,4]
# Explanation: The array represents the integer 123.
# Example 2:
# Input: [4,3,2,1]
# Output: [4,3,2,2]
# Explanation: The array represents the integer 4321.
class Solution(object):
def plusOne(self, digits):
i, add_new_r = len(digits) - 1, False
while i >= 0:
new_digit = digits[i] + 1
if new_digit < 10:
digits[i] = new_digit
break
else:
digits[i] = 0
if i == 0:
add_new_r = True
i-= 1
if add_new_r:
digits = [1] + digits
return digits |
bad1b4da6b2f71ff1b10b565eb90547ac98d3503 | sanshitsharma/pySamples | /strings/rabin_karp.py | 2,321 | 4.1875 | 4 | #!/usr/bin/python
'''
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that
prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
'''
def brute_force_matching(text, pattern):
p_len = len(pattern)
t_len = len(text)
if p_len > t_len:
print "pattern cannot exist in text"
return None
indexes = []
for i in range(t_len - p_len + 1):
substr = text[i:i+p_len]
found = True
for j in range(p_len):
if pattern[j] != text[i+j]:
found = False
break
if found:
indexes.append(i)
return indexes
def rabin_karp(text, pattern):
t_len = len(text)
p_len = len(pattern)
if p_len > t_len:
print "pattern", word, "cannot exist in text", text
return None
# Prime number that will be used to generate the hash
q = 101
# We will use the ASCII values of the characters
d = 256
# Calculate the hash_seed, this will be used later to calculate the rolling hash
h_seed = 1
for i in range(p_len - 1):
h_seed = (h_seed*d)%q
# Initialize the pattern hash & text hash to 0
p_hash = 0
t_hash = 0
indexes = []
# Find the hash of the pattern
for i in range(p_len):
p_hash = (d*p_hash + ord(pattern[i]))%q
t_hash = (d*t_hash + ord(text[i]))%q
# From this point on, we only need to update the rolling hash
# of the text string
for i in range(t_len - p_len + 1):
if t_hash == p_hash and text[i:i+p_len] == pattern:
indexes.append(i)
# Roll the window
if i < t_len - p_len:
t_hash = (d*(t_hash - ord(text[i])*h_seed) + ord(text[i+p_len]))%q
if t_hash < 0:
t_hash = t_hash + q
return indexes
if __name__ == "__main__":
#indexes = brute_force_matching('aagcgagcgatatatat', 'ata')
#print "pattern appears at indexes", indexes
print rabin_karp('aagcgagcgatatatat', 'ata') |
35344c587916a80e6e8263a3730327729fbe3a1a | dltech-xyz/Alg_Py_Xiangjie | /第10章/feibo.py | 404 | 3.875 | 4 | #coding=utf-8
def fib_list(n) :
if n == 1 or n == 2 :
return 1
else :
m = fib_list(n - 1) + fib_list(n - 2)
return m
print("**********请输入要打印的斐波拉契数列项数n的值***********")
try :
n = int(input("enter:"))
except ValueError :
print("请输入一个整数!")
exit()
list2 = [0]
tmp = 1
while(tmp <= n):
list2.append(fib_list(tmp))
tmp += 1
print(list2) |
2bd1754993eed7fae3b9c641604ba061b8bf3d95 | holyrib/Django | /Lab_1/informatics/for/j.py | 60 | 3.546875 | 4 | a = 0
for x in range(0, 100):
a = a + int(input())
print(a) |
7ac40e0bf69d64ce889f0fc2176a7803d3d51289 | ledbagholberton/holbertonschool-machine_learning | /supervised_learning/0x05-regularization/5-dropout_gradient_descent.py | 1,946 | 3.84375 | 4 | """
updates the weights of a neural network with Dropout regularization
using gradient descent:
Y is a one-hot numpy.ndarray of shape (classes, m) that contains the correct
labels for the data:
classes is the number of classes
m is the number of data points
weights is a dictionary of the weights and biases of the neural network
cache is a dictionary of the outputs and dropout masks of each layer of
the neural network
alpha is the learning rate
keep_prob is the probability that a node will be kept
L is the number of layers of the network
All layers use the tanh activation function except the last, which uses the softmax
activation function
The weights of the network should be updated in place
"""
import tensorflow as tf
import numpy as np
def tanh(Z):
"""Function tanh"""
tanh = np.tanh(Z)
return tanh
def softmax(Z):
"""Function softmax"""
t = np.exp(Z)
sum = np.sum(t, axis=0, keepdims=True)
softmax = t / sum
return softmax
def dropout_gradient_descent(Y, weights, cache, alpha, keep_prob, L):
"""FUnction Dropout Gradient Descent"""
cache = {}
for i in range(L):
if i == 0:
cache['A0'] = X
else:
A_tmp_0 = np.matmul(weights['W' + str(i)],
cache['A' + str(i-1)])
A_tmp = A_tmp_0 + weights['b' + str(i)]
cache['D' + str(i)] = np.random.rand(A_tmp.shape[0],
A_tmp.shape[1])
cache['D' + str(i)] = cache['D' + str(i)] < keep_prob
cache['D' + str(i)] = int(cache['D' + str(i)] == 'true')
A_tmp = np.multiply(A_tmp, cache['D' + str(i)])
A_tmp = A_tmp / keep_prob
if i == L:
H_tmp = softmax(A_tmp)
else:
H_tmp = tanh(A_tmp)
cache['A' + str(i)] = H_tmp
return (cache)
|
e10965b9d7d525cbe88c16e7eba12c6a9df2d75a | magks/leetcode | /6. Zigzag conversion Difficulty: Medium.py | 2,567 | 3.5625 | 4 | #python3
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
rowsOfLetters = [ [] for _ in range(numRows) ]
# print(json.dumps( rowsOfLetters ))
lastRow = numRows-1
firstRow = currentRow = 0
climbingToLastRow = True
climbingToFirstRow = False
for c in s:
# print("for " + c, end=' when ')
if ( climbingToLastRow ):
# print("climbingToLastRow")
# print("::currentRow="+ str(currentRow))
# print("::lastRow="+str(lastRow))
if ( currentRow <= lastRow ):
rowsOfLetters[ currentRow ].append(c)
currentRow += 1
if (currentRow > lastRow):
climbingToLastRow = False
climbingToFirstRow = True
currentRow = lastRow-1 if numRows > 1 else 0
elif ( climbingToFirstRow ):
# print("climbingToFirstRow")
# print("::currentRow="+ str(currentRow))
# print("::firstRow="+str(firstRow))
if (currentRow >= firstRow):
rowsOfLetters[ currentRow ].append(c)
currentRow -= 1
if (currentRow < firstRow):
climbingToLastRow = True
climbingToFirstRow = False
currentRow = firstRow if numRows == 1 else firstRow+1
# print(json.dumps( rowsOfLetters ))
return ''.join( str(c) for row in rowsOfLetters for c in row )
# ''.join([str(item) for sublist in a for item in sublist])
'''
P Y A I H R N
A P L S I I G
P A H N
A P L S I I G
Y I R
P P I
A Y A H R
Y A L S I G
P I N
P h
a s i
y i r
p l i g
a n
'''
def stringToString(input):
input = input[1:-1].encode('latin1')
return input.decode('unicode_escape')
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.__next__()
s = stringToString(line);
line = lines.__next__()
numRows = int(line);
ret = Solution().convert(s, numRows)
out = (ret);
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()
|
7eccf101bad98e0ff156e8520a8e4dbf21f1d1bd | dougallison/udemy-pythonbootcamp | /15-DictionaryEx/ex33.py | 775 | 4.21875 | 4 | # List to Dictionary Exercise
# Given a person variable:
# person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# Create a dictionary called `answer`, that makes each first item
# in each list a key and the second item a corresponding value.
# Output should look like this:
# {'name': 'Jared', 'job': 'Musician', 'city': 'Bern'}
person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# my solution
answer = {person[i][0]: person[i][1] for i in range(0, len(person))}
print(answer)
# alternate solution
answer = {p[0]: p[1] for p in person}
print(answer)
# alternate solution
answer = {k: v for k, v in person}
print(answer)
# if you have a list of pairs, it can be turned into a dictionary
# using dict()
answer = dict(person)
print(answer)
|
d1b0dbd44cd3c3d1c54a354468c85bdb04bf2f48 | cpalm9/PythonDataStructures | /recursionPractice.py | 316 | 3.546875 | 4 | import os
def search_directory(level, dirname):
# search the dirname
print(level, '>>>>>', dirname)
#recurse through the directories
for fn in os.listdir(dirname):
path = dirname + '/' + fn
if os.path.isdir(path):
search_directory(level + 1, path)
search_directory(0,'.') |
b51dea523548cbd88e3e697be055dba26fe31eb8 | jethropalanca/Quantnet_Python | /Level1/Section1_2/Exercise6.py | 384 | 4.25 | 4 | '''
This program creates a list comprehension that results in a list of the squares of all numbers 0 through 100.
'''
def main():
list_square = [i**2 for i in range(101)]
list_1000 = [value for value in list_square if value > 1000]
list_even = [value for value in list_1000 if value%2 == 0]
print(list_1000)
print(list_even)
if __name__=='__main__':
main()
|
50b5a2ae8f9b1e38c9ae3fdb89f416fdbc4cbc58 | johnhuzhy/StellaPythonExam | /src/practiceFunction/h11.py | 519 | 3.859375 | 4 | # def demo():
# c=10 #局部变量
# #NameError: name 'c' is not defined
# print(c)
def demo1():
c=50
for i in range(0,3):
a='abc'
c+=1
print(c)
#和Java不同之处,在Java里不能调用for循环里定义的变量,如果想要用,就先要提到for循环外,在里面改变。然后for循环外就可以调用了
#python里for循环外直接可以调用for循环里定义的变量。因为python没有块级作用域,只有函数作用域
print(a)
demo1()
|
967811ae0646a86f3280f7faac84b72c02e00daf | JacekGorski01/KursPython | /homeworks/day6/picle_loader.py | 3,410 | 3.75 | 4 | import pprint
import pickle
import random
from create_menu import menu_builder
from datetime import datetime
def search_book(string):
'''Search substring in strings - values in dictionary and print them
Parameters:
string (str) - piece of string you want to find
Return:
None
'''
for i,row in enumerate(entries):
for key in row.keys():
result = row[key].find(find_value)
if result >= 0:
print(row.items())
else:
pass
menu_builder(["menu"], 5)
with open('book.pkl', 'rb+') as book_file:
entries = pickle.load(book_file)
print(entries)
right_values = ["1", "2", "3", "4", "5", "Q", "R"]
choice = input('\nWybierz program (1-10,"R","Q"): ')
while choice not in right_values:
print('Nieprawidłowy wybór, wpisz liczbę w przedziale 1-10, "R" lub "Q": ')
choice = input("\nWybierz program (1-10): ")
print(f"Wybrałeś: {choice}")
if choice == "R":
choice = random.choice(right_values[0:6]) #wykluczam by nie wylosowało się ponownie R
print(f"Wylosowałęś opcję {choice}")
else:
pass
if choice == "Q":
print("Do zobaczenia!")
exit(5)
elif choice == "1":
ans = "T"
while ans == "T":
inserts_num = len(entries)
print("Dodaj wpis!")
title_content = input("Tytuł wpisu : ")
body_content = input("Treść wpisu : ")
author_content = input("Autor wpisu : ")
date_content = str(datetime.now())
entries.append({"title": title_content, "body": body_content, "author": author_content, "date": date_content})
ans = input(f'Dziękujemy za dodanie {inserts_num} wpisu. Czy chcesz dodać kolejny (T)? ')
elif choice == "2":
find_value = input("Wyszukaj: ")
search_book(find_value)
elif choice == "3":
print(lambda x:x['date'])
entries.sort(key = lambda x:x['date'], reverse = True)
for i in entries:
print(i)
elif choice == "4":
entries.sort(key=lambda x: x['date'],)
for i in entries:
print(i)
elif choice == "5":
show = 0
print(entries[show])
while show in range(0,len(entries)):
if show == 0:
prev_nest = input(f"To jest pierwszy wpis, pokazać następny (n)? :")
if prev_nest == "n":
show =+ 1
print(entries[show])
else:
print(f"Do zobaczenia!")
exit(5)
elif show in range(1,len(entries)- 1):
prev_nest = input(f"Pokazać następny (n) lub poprzedni (p)? : ")
if prev_nest == "n":
show += 1
print(entries[show])
elif prev_nest == "p":
show -= 1
print(entries[show])
else:
print(f"Do zobaczenia!")
exit(5)
elif show == (len(entries) -1):
prev_nest = input(f"To ostatni wpis, pokazać poprzedni (p)? :")
if prev_nest == "p":
show -= 1
print(entries[show])
else:
print(f"Do zobaczenia!")
exit(5)
with open('book.pkl', 'wb+') as book_file:
pickle.dump(entries, book_file)
|
30afe757f2effb046d6354ed49bde93a9b880db0 | og-python-scripts/Automate-the-Boring-Stuff-with-Python-2015 | /pg.106.sublists.slices.py | 1,919 | 4.5 | 4 | spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4]
['cat', 'bat', 'rat', 'elephant']
spam[1:3]
['bat', 'rat']
spam[0:-1]
['cat', 'bat', 'rat']
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4]
['cat', 'bat', 'rat', 'elephant']
spam[1:3]
['bat', 'rat']
spam[0:-1]
['cat', 'bat', 'rat']
spam[:]
['cat', 'bat', 'rat', 'elephant']
spam = ['cat', 'dog', 'moose']
len(spam)
3
'''
Changing Values in a List with Indexes
Normally a variable name goes on the left side of an assignment statement,
like spam = 42. However, you can also use an index of a list to change
the value at that index. For example, spam[1] = 'aardvark' means “Assign the
value at index 1 in the list spam to the string 'aardvark'.” Enter the following
into the interactive shell:
'''
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1] = 'aardvark'
spam
['cat', 'aardvark', 'rat', 'elephant']
spam[2] = spam[1]
spam
['cat', 'aardvark', 'aardvark', 'elephant']
spam[-1] = 12345
spam
['cat', 'aardvark', 'aardvark', 12345]
'''
List Concatenation and List Replication
The + operator can combine two lists to create a new list value in the same
way it combines two strings into a new string value. The * operator can also
be used with a list and an integer value to replicate the list. Enter the following
into the interactive shell:
'''
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
'''
Removing Values from Lists with del Statements
The del statement will delete values at an index in a list. All of the values
in the list after the deleted value will be moved up one index. For example,
enter the following into the interactive shell:
'''
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
|
996a1242575fdbc346f6979313ecad37ea1fbc0a | boulund/qnr-assembly | /extract_from_fasta.py | 2,889 | 3.609375 | 4 | #!/usr/bin/env python3.5
# Fredrik Boulund 2016
# Extract sequences from a FASTA file
from read_fasta import read_fasta
from sys import argv, exit, maxsize
import argparse
import re
def parse_args(argv):
"""
Parse commandline arguments.
"""
desc = """Extract sequences from FASTA files. Fredrik Boulund 2016"""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("FASTA", nargs="+",
help="FASTA file(s) to sample from.")
parser.add_argument("-M", "--maxlength", metavar="M", type=int,
default=0,
help="Maximum length of sequences to extract, 0 means no limit [%(default)s]")
parser.add_argument("-m", "--minlength", metavar="m", type=int,
default=0,
help="Minimum length of sequences to extract, 0 means no limit [%(default)s].")
parser.add_argument("-o", "--outfile", metavar="FILE", dest="outfile",
default="",
help="Write output to FILE instead of STDOUT.")
parser.add_argument("-r", "--regex", metavar="'REGEX'", dest="regex",
default="",
help="Extract sequences with header that match REGEX.")
parser.add_argument("-R", "--regex-file", metavar="FILE", dest="regex_file",
default="",
help="Extract sequences with header matching any of multiple regexes on separate lines in FILE.")
if len(argv)<2:
parser.print_help()
exit()
options = parser.parse_args()
return options
def extract_from_fasta(fastafile, maxlength=0, minlength=0, regexes=""):
"""
Extract sequences from FASTA.
"""
for header, seq in read_fasta(fastafile):
if regexes:
if not any((re.search(rex, header) for rex in compiled_regexes)):
continue
seqlen = len(seq)
if seqlen >= minlength and seqlen <= maxlength:
yield (">"+header, seq)
if __name__ == "__main__":
options = parse_args(argv)
if not options.maxlength:
maxlength = maxsize
else:
maxlength = options.maxlength
if options.regex:
compiled_regexes = [re.compile(options.regex)]
elif options.regex_file:
with open(options.regex_file) as regexes:
compiled_regexes = [re.compile(rex.strip()) for rex in regexes.readlines()]
else:
compiled_regexes = ""
extraction_generators = (extract_from_fasta(filename, maxlength, options.minlength, compiled_regexes) for filename in options.FASTA)
if options.outfile:
with open(options.outfile, 'w') as outfile:
for extraction_generator in extraction_generators:
for seq in extraction_generator:
outfile.write('\n'.join(seq)+"\n")
else:
for extraction_generator in extraction_generators:
for seq in extraction_generator:
print('\n'.join(seq))
|
a813bb350e3cbbae1dd72b9442c09da1192250b2 | RadkaValkova/SoftUni-Web-Developer | /Programming Fundamentals Python/18 Objects and classes/Party.py | 756 | 3.734375 | 4 | # class Party:
# def __init__(self):
# self.people = []
#
#
# party = Party()
#
# while True:
# line = input()
# if line == 'End':
# break
# name = line
# party.people.append(name)
#
# print(f"Going: {', '.join(party.people)}")
# print(f'Total: {len(party.people)}')
class Party:
def __init__(self):
self.people = []
def invite(self, name):
self.people.append(name)
def names_of_all_people(self):
return f'Going: {", ".join(self.people)}'
def num_people(self):
return f'Total: {len(self.people)}'
p = Party()
while True:
line = input()
if line == 'End':
break
name = line
p.invite(name)
print(p.names_of_all_people())
print(p.num_people())
|
069363c29ada4822bc4f12bbe0bea3e22839dc4a | annewoosam/underpaid_customers | /underpaid_customers2.py | 1,918 | 4.21875 | 4 |
MELON_COST = 1.00
def print_payment_status(payment_data_filename):
"""Calculate cost of melons and determine who has underpaid."""
payment_data = open(payment_data_filename) # open the file
# Iterate over lines in file
for line in payment_data:
# Split line by '|' to get a list of strings
order = line.split('|')# because the pipe is the separator. In many cases it will be a tab or a comma
# Get customer's full name
full_name = order[1] #second column in line
# Split `customer_name` by space (' ') to get
# a list of [first_name, last_name].
#
# Then, assign first name (at index 0) to `customer_first`
first_name = full_name.split(" ")[0] #tells to split and take first item in split
# Get no. of melons in the order and amount customer paid
melons_qty = int(order[2])
amt_paid = float(order[3])# float for currency
difference = float(order[3])-float(order[2])
# Calculate expected price of customer's order
expected_price = melons_qty * MELON_COST
# Print general payment info
print(f"{full_name} paid ${amt_paid:.2f}, expected",
f"${expected_price:.2f}", "for a difference of", f"${difference:.2f}")
# $ .2f for currec=ncg and f for avoiding strip space.
# Print payment status
#
# If customer overpaid, print that they've overpaid for their melons. If
# customer underpaid, print that they've underpaid for their melons.
if expected_price < amt_paid:
print(f"{first_name} has overpaid for their melons")
elif expected_price > amt_paid:
print(f"{first_name} has underpaid for their melons.")
# Close the file
payment_data.close()
# Call the function
print_payment_status("customer-orders.txt") |
667288bd35135f81ce23f67fa61468f83b5cdc06 | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_2_list/list7_remove.py | 434 | 4.15625 | 4 | # remove items from list
my_list = ['p','r','o','g','r','a','m','i','z']
# remove() - remove one item
my_list.remove('p')
print(my_list)
my_list = ['p','r','o','g','r','a','p','m','i','z']
# remove() - remove one item
my_list.remove('p')
print(my_list)
my_list = ['p','r','o','g','r','a','p','m','i','z']
# remove() - remove 3 items
my_list.remove('p')
my_list.remove('p')
# my_list.remove('p') # ValueError
print(my_list)
|
e844701ed4a7d484bed55731241ab1b80775160d | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4343/codes/1644_1053.py | 189 | 3.984375 | 4 | patrono = input("Qual o nome do patrono?")
if(patrono == "cervo")
mensagem = "cervo eh patrono de Harry Potter"
else:
mensagem = patrono + "nao eh patrono de Harry Potter"
print(mensagem) |
60a71455396e3d7c61227c04a44523efb6182a6a | andrezzadede/Curso-de-Python-POO | /polimorfismo.py | 1,171 | 4.09375 | 4 | # Quando um método é chamado por outra classe e é utilizado de outra forma
import math
class Forma():
def __init__(self): # Inicializador de instancia/ Construtor
print('Construtor da forma')
def area(self):
print('Area da forma')
def perimetro(self):
print('Perimetro da forma')
def descrição(self):
print('Descrição da forma')
class Quadrado(Forma):
# Forma é uma generalização de quadrado
def __init__(self, lado):
self.lado = lado
def area(self):
return self.lado ** 2
def perimetro(self):
return self.lado * 4
class Circulo(Forma):
def __init__(self, raio):
self.raio = raio
def area(self):
return math.pi * self.raio ** 2
def perimetro(self):
return 2 * math.pi * self.raio
def descrição(self):
return print('Descrição do circulo')
quad = Quadrado(2)
print(f'Area {quad.area()}')
print(quad.perimetro())
print('Circulo')
circulo = Circulo(3)
print(f'Area do Circulo: {circulo.area()}')
print(f'Perimetro do circulo: {circulo.perimetro()}')
print(circulo.descrição())
|
839c8d3495c8c9ca1740386a60acabcdf6250285 | ysze/python-refactorings | /week3/refactored.py | 1,167 | 4.28125 | 4 | def create_pixel_row(width, pixel):
""" creates and returns a "row" of pixels with the specified width
in which all of the pixels have the RGB values specified by pixel.
input: width is a non-negative integer
pixel is a list of RBG values of the form [R,G,B],
where each element is an integer between 0 and 255.
"""
return [pixel[:] for _ in range(width)]
def create_uniform_image(height, width, pixel):
""" creates and returns a 2-D list of pixels with height rows and width columns in which all of the pixels have the RGB values given by pixel."""
return [create_pixel_row(width, pixel)[:] for _ in range(height)]
def blank_image(height, width):
"""creates and returns a 2-D list of pixels with height rows and width columns in which all of the pixels are green (i.e., have RGB values [0,255,0])."""
return create_uniform_image(height, width, pixel=[0, 255, 0])
def transpose(pixels):
""" takes the 2-D list pixels containing pixels for an image, and that creates and returns a new 2-D list that is the transpose of pixels. """
return [list(row) for row in zip(*pixels)]
|
d49324055676a2756bbec94103360ef8e370d288 | gabriel-roque/python-study | /01. CursoEmVideo/Mundo 01/Aula 07 - Operadores Aritimeticos/Desafio09.py | 582 | 3.921875 | 4 | valor = int(input('De qual numero gostaria obter a tabuada: '))
print('-------------')
print('{} x 1 = {}'.format(valor,(valor*1)))
print('{} x 2 = {}'.format(valor,(valor*2)))
print('{} x 3 = {}'.format(valor,(valor*3)))
print('{} x 4 = {}'.format(valor,(valor*4)))
print('{} x 5 = {}'.format(valor,(valor*5)))
print('{} x 6 = {}'.format(valor,(valor*6)))
print('{} x 7 = {}'.format(valor,(valor*7)))
print('{} x 8 = {}'.format(valor,(valor*8)))
print('{} x 9 = {}'.format(valor,(valor*9)))
print('{} x 10 = {}'.format(valor,(valor*10)))
print('-------------') |
4e6842d9f53c4758de4a8bdb5814dd3832d27866 | Zahidsqldba07/CodeSignal-26 | /Intro/Rains of Reason/028 - alphabeticShift.py | 151 | 3.625 | 4 | def alphabeticShift(inputString):
res = ''
for c in list(inputString) :
res += chr(97) if ord(c)==122 else chr(ord(c)+1)
return "".join(res)
|
816c1d3e1e6931d218cb81285fea98d747e3e974 | marco9663/Command-line-chess-game | /Queen.py | 1,519 | 3.59375 | 4 | from termcolor import colored
from Coordinate import Coordinate as C
from Move import Move
White = True
Black = False
class Queen:
value = 90
def __init__(self, board, side, coord, movesMade=0):
if side:
self.side = White
self.direction = -1
else:
self.side = Black
self.direction = 1
self.board = board
self.coord = coord
self.movesMade = movesMade
self.symbol = "q"
def __str__(self):
return colored("q", "red" if self.side else "cyan")
def getMoves(self):
currentCoordinate = self.coord
directions = [C(0, 1), C(0, -1), C(1, 0), C(-1, 0),
C(1, 1), C(-1, 1), C(1, -1), C(-1, -1)]
for direction in directions:
for dis in range(1, 8):
movement = C(dis * direction[0], dis * direction[1])
newPosition = currentCoordinate + movement
if self.board.isValidPos(newPosition):
pieceAtNewPos = self.board.pieceAtPosition(newPosition)
if pieceAtNewPos is None:
yield Move(self, newPosition)
else: # if new position is not empty
# and belongs to the enemy
if pieceAtNewPos.side != self.side:
yield Move(self, newPosition, capturing=pieceAtNewPos)
# if block by same side then stop
break
|
e2e037efd8c9afb004cdfaa60cc3c95e3f494cff | Aasthaengg/IBMdataset | /Python_codes/p03555/s343436550.py | 100 | 3.875 | 4 | a = input()
b = input()
b_reverse = b[::-1]
if a == b_reverse:
print('YES')
else:
print('NO')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.