blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ff0a00a84d4f70123af40759e45177c01b39675b | magicleon94/farmaci | /Menu.py | 2,743 | 3.578125 | 4 | import os
def clear():
os.system('cls' if os.name=='nt' else 'clear')
def getChoice():
while (True):
clear()
print "---- MENU ----"
print "1. Ricerca farmaci per principio attivo"
print "2. Ricerca equivalenti ad un farmaco specificandone il nome"
print "3. Impostazioni generali"
print "4. Aggiorna banca dati"
print "0. Esci"
choice = raw_input("Scelta: \t")
if choice.isdigit():
choice = int(choice)
if choice>=0 and choice<=4:
return choice
blbl = raw_input("Scelta non valida, riprovare.\nPremere un tasto per continuare\t")
def getSettings(oldKey,oldVal):
while(True):
clear()
newKeySet = 0
newValSet = 0
print "---- IMPOSTAZIONI INTERROGAZIONI ----"
print "1. Parametro di ordine"
print "2. Criterio di ordinamento del parametro di ordine"
print "0. Indietro"
choice = raw_input("Scelta: \t")
if choice.isdigit():
choice = int(choice)
if choice == 1:
newKey = _getNewKey()
newKeySet = 1
elif choice==2:
newVal = _getNewVal()
newValSet = 1
elif choice == 0:
if newKeySet == 0:
newKey = oldKey
if newValSet == 0:
newVal = oldVal
return (newKey,newVal)
else:
blbl = raw_input("Scelta non valida, riprovare.\nPremere un tasto per continuare\t")
def _getNewKey():
clear()
while(True):
print "Seleziona la nuova chiave di ordinamento: "
print "1. Nome Farmaco"
print "2. Prezzo"
print "3. Nessuno"
choice = raw_input("Scelta: \t")
if choice.isdigit():
choice = int(choice)
if choice == 1:
return "Farmaco"
elif choice == 2:
return "Prezzo Pubblico 16 febbraio 2015"
elif choice == 3:
return None
blbl = raw_input("Scelta non valida, riprovare.\nPremere un tasto per continuare\t")
def _getNewVal():
while(True):
clear()
print "Seleziona il nuovo criterio di ordinamento: "
print "1. Ascendente"
print "2. Discendente"
print "3. Nessuno"
choice = raw_input("Scelta: \t")
if choice.isdigit():
choice = int(choice)
if choice == 1:
return 1
elif choice == 2:
return -1
elif choice == 3:
return None
blbl = raw_input("Scelta non valida, riprovare.\nPremere un tasto per continuare\t")
|
9e537cb4ebfd0da0101a1a4d4c44ed5ea79022dd | xhwupup/xhw_project | /64_Minimum Path Sum.py | 896 | 3.640625 | 4 | # 时间:20190510
# Exampole1:
# Input:
# [
# [1,3,1],
# [1,5,1],
# [4,2,1]
# ]
# Output: 7
# Explanation: Because the path 1→3→1→1→1 minimizes the sum.
# 难度:Medium(0.5)
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
m = len(grid[0])
for i in range(1, n):
grid[i][0] = grid[i - 1][0] + grid[i][0] # 首先需要寻找左边界各点的路径总和
for j in range(1, m):
grid[0][j] = grid[0][j - 1] + grid[0][j] # 寻找上边界各点的路径总和
for i in range(1, n):
for j in range(1, m):
grid[i][j] = min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j] # 以边界处为依据一步步推出内部个点的路径总和
return grid[n - 1][m - 1]
|
0109648e62e7b17582b9c171c9050c19a64ce337 | anujkumarthakur/Assignment-Python-Django-Developer-Startxlabs | /question_no_1.py | 2,144 | 4.09375 | 4 | '''QUESTION-1 Write a function which takes two arguments: a list of customers and the number of open cash
registers. Each customer is represented by an integer which indicates the amount of time needed
to checkout. Assuming that customers are served in their original order, your function should output
the minimum time required to serve all customers.
Example:
get_checkout_time([5, 1, 3], 1) should return 9
get_checkout_time([10, 3, 4, 2], 2) should return 10 because while the first register is busy serving
customer[0] the second register can serve all remaining customers.
'''
def Get_Check_OutTime(customers, person):
n = len(customers)
sum_init = 0
if(person is None or customers is None):
return 0
elif(person==1):
for i in range(0, n):
sum_init = sum_init + customers[i]
print(sum_init)
else:
#there are multiple person to serve customers so Logic
#step-1: customers list sorting
#step-2: find higest number and calculate other no and comapre with higest no
#step-3 if higest no greater then sum of another no it mean leave higest no and calculate another number
for i in range(0, n):
for j in range(0, n-i-1):
if customers[j] > customers[j+1]:
customers[j], customers[j+1] = customers[j+1], customers[j]
high_no = customers[-1]
other_no = 0
for i in range(0, n-1):
other_no = other_no + customers[i]
if(high_no > other_no):
print(high_no)
else:
print(other_no)
if __name__ == "__main__":
#indicates the amount of time to store in cus list
customers = []
#how many customers do you want
no_of_customer = int(input("how many customers do you want: "))
print("Enter number")
for i in range(0,no_of_customer):
inp = int(input())
customers.append(inp)
#no of person to serve customers
person = int(input())
Get_Check_OutTime(customers, person)
|
923c82150361b7f2b74d525278d73f8bd9e95325 | AdityaKumar123-aks/tathastu-week-of-code | /Day 2/program1.py | 953 | 4.3125 | 4 | # WRITE A PROGRAM TO CHECK WHETHER INPUT NUMBER IS ODD/EVEN,PRIME,PALINDROME,ARMSTRONG.
num=int(input("enter the number you want to check : "))
# TO CHECK EVEN/ODD
a = num%2
if a == 0:
print("even number")
if a != 0:
print("odd number")
# TO CHECK PRIME
if num < 2:
print("not a prime number")
else:
for i in range(2,num):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime number")
# TO CHECK PALINDROME NUMBER
rev = 0
a = num
while num > 0:
digit = num % 10
num = num // 10
rev = rev * 10 + digit
if a == rev:
print(a, "is a palindrome number")
else:
print(a,"is not a palindrome number")
# TO CHECK ARMSTRONG NUMBER
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum = sum + digit * digit * digit
temp = temp // 10
if sum == temp:
print(temp,"is armstrong number")
else:
print(temp,"is not an armstrong number")
|
d072eced58d6f874a9305ab2630629f050109670 | harshil1903/leetcode | /Math/0168_excel_sheet_column_title.py | 639 | 3.859375 | 4 |
# 168. Excel Sheet Column Title
#
# Source : https://leetcode.com/problems/excel-sheet-column-title/
#
# Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
#
# For example:
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
# ...
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
result, col = "", columnNumber
while int(col) != 0:
result += chr(int((col - 1) % 26) + 65)
col = (col - 1) / 26
return result[::-1]
if __name__ == "__main__":
s = Solution()
print(s.convertToTitle(523482374)) |
3b6bb8142db8f495ddd70a39096df313cd01a223 | yaggul/Programming0 | /week2/2List-Problems/sorted_names.py | 228 | 4.09375 | 4 | n=int(input("Please insert number of names: "))
count=1
names=[]
while count<=n:
name=input("Please insert a name: ")
names=names+[name]
count+=1
names=sorted(names)
print("Sorted names are: ")
for name in names:
print(name) |
a186d087a75b642bf7be296c426f35576c04b0ac | wanga0104/learn | /chapter_1/hello.py | 216 | 3.84375 | 4 | start = int(input('请为《叶问》的电影评分(请输入1-10):'))
if start > 10 or start <= 0:
print ('数字不能大于10或者小于0')
else:
print('您为《叶问》的电影打分为',start*'⭐') |
b21bf8de43fa044671a84141fde120f3284619d1 | kwx4github/facebook-hackercup-problem-sets | /2015/qualifying_round/1.Cooking_the_Books/solutions/sources/6170.Michał | 885 | 3.796875 | 4 | #!/usr/bin/env python
import unittest
def readints():
return list(map(int, input().strip().split()))
def swapped(s, p1, p2):
l = list(s)
l[p1], l[p2] = l[p2], l[p1]
return ''.join(l)
def testcase(num):
min_num, max_num = num, num
num = str(num)
for p1, _ in enumerate(num):
for p2, _ in enumerate(num):
cur = swapped(num, p1, p2)
if cur[0] == "0":
continue
cur_int = int(cur)
if cur_int < min_num:
min_num = cur_int
if cur_int > max_num:
max_num = cur_int
return min_num, max_num
def main():
T, = readints()
for testno in range(T):
input = readints()[0]
answers = testcase(input)
print("Case #{}: {} {}".format(testno+1, answers[0], answers[1]))
if __name__ == '__main__':
main()
|
f47d104a40c5642b93d586118504fd2e09f7ae2d | AaronRanAn/Python_Programming_MSU | /assignment 4.1.py | 335 | 3.84375 | 4 | def computepay(h, r):
if h <= 40:
p = r * h
else:
p = 40 * r + (h - 40) * r * 1.5
return p
hrs = raw_input("Enter Hours: ")
h = float(hrs)
rate = raw_input("Enter Rate Per Hour: ")
r = float(rate)
if h <= 40:
p = h * r
else:
p = computepay(h, r)
print p |
dbe92111cc82700c07cdf243972b26d26feebb24 | altro111/Home_work | /Задание 2, Пункт 1.py | 544 | 4.21875 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = ["abc", 1, 1.1, True, -11]
for el in my_list:
print(type(el))
|
e28fb68217079bc0ec94540a8153f462cc81f280 | krishnamanchikalapudi/examples.py | /PythonTutor/session-6/HomeWork.py | 781 | 4.375 | 4 | """
Session: 6
Topic: Homework
"""
a = 21
b = 10
if ( a == b ):
print ('a is equal to b')
else:
print ('a is not equal to b')
if ( a != b ):
print ('a is not equal to b')
else:
print ('a is equal to b')
if ( a < b ):
print ('a is less than b')
else:
print('a is not less than b')
if ( a > b ):
print ('a is greater than b')
else:
print ('a is not greater than b')
if ( a <= b ):
print ('a is either less than or equal to b')
else:
print ('a is neither less than nor equal to b')
if ( b >= a ):
print ('b is either greater than or equal to b')
else:
print ('b is neither greater than nor equal to b')
if a > 0 and b > 0:
print("The numbers a & b are greater than 0")
if a > 20 or b > 8:
print("The numbers a > 20 or b > 8 ") |
abbe16904eb288172898b33b2a1724d07b126f39 | jordanlui/DailyCodingProblem | /Prob1.py | 672 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 21:54:00 2018
@author: Jordan
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
Hash table (Python Dictionary) allows us to do this in one pass
"""
list = [10,15,3,7]
k = 17
diffs = {}
def complementInList(list):
# Check if complement value exists in list
for i,item in enumerate(list):
diffs[item] = k-item
print diffs
if k-item in diffs:
return True
return False
print complementInList(list)
|
f6d0770e01e04ff7d3bcdd1d43041835e84e7ce8 | metinsenturk/review-analysis | /src/data/data_builder.py | 678 | 3.640625 | 4 | import json
import pandas as pd
def create_dataset(from_path, to_path):
"""
Creates a comma seperated value (CSV) file from JSON file. Handles reviews and status during conversion.
from_path: The path to get JSON file for conversion.
to_path: The path to place the CSV file.
"""
with open(from_path) as f:
json_data = json.loads(f.read())
dataset = pd.io.json.json_normalize(json_data['reviews'])
dataset_new = pd.DataFrame()
dataset_new['status'] = dataset.iloc[:, 3].apply(lambda x: 1 if x > 3 else 0)
dataset_new['reviews'] = dataset.iloc[:,2].values
dataset_new.to_csv(to_path, index=False)
dataset_new.head()
|
ae7a9f1f467034915f105d414f389dec07db0036 | mveselov/CodeWars | /katas/kyu_6/arabian_string.py | 155 | 3.625 | 4 | from re import split
def camelize(string):
return ''.join(a.capitalize() for a in split('([^a-zA-Z0-9])', string)
if a.isalnum())
|
bf4028f5d624fd9d8d30e327562d9447b89d18ff | wenxingjiang/MIT6_0001F16 | /MIT60001 HW PS1.py | 1,760 | 3.734375 | 4 | ##Problem set 0
import math
def homework_0():
x = int(input("input value for x"))
y = int(input("input value for y"))
z1 = x**y
z2 = math.log(x,10)
print('Enter number x:', x)
print('Enter number y:', y)
print('x**y = ', z1)
print('log(x) = ', z2)
homework_0()
##Problem set 1
def hw1_A(annual_salary,save_percentage,total_cost):
total_saving = 0
month = 0
while total_saving - total_cost*0.25<=0:
total_saving = total_saving + total_saving*0.04/12 + annual_salary*save_percentage/12
month +=1
return month
def hw1_B(annual_salary,save_percentage,total_cost,semi_raise):
total_saving = 0
month = 0
while total_saving - total_cost*0.25<=0:
total_saving = total_saving + total_saving*0.04/12 + annual_salary*save_percentage/12
month +=1
if month % 6 ==0:
annual_salary =annual_salary*(1+semi_raise)
return month
def hw1_C(annual_salary):
start = 0
end = 10000
save_percentage = 0.5
step = 0
while abs(hw1_c_total_saved(annual_salary,save_percentage) - 250000) >=100:
if hw1_c_total_saved(annual_salary,save_percentage) > 250000:
end = save_percentage * 10000
else:
start = save_percentage * 10000
save_percentage = int((start + end) / 2) / 10000
step += 1
return save_percentage, step
def hw1_c_total_saved(annual_salary,save_percentage):
total_saving = 0
for i in range(0,96):
total_saving = total_saving + total_saving * 0.04 / 12 + annual_salary * save_percentage / 12
i += 1
if i % 12 == 0:
annual_salary = annual_salary * 1.04
return total_saving
|
85bf5d7f7fc5a470a870703dc2e35e1d78df01ab | Vinicius-Reinert/PythonLearning | /variaveis .py | 341 | 3.828125 | 4 | x = 20
y = 50
print(x)
print(y)
soma = x + y
print("soma: {}".format(soma))
subtracao = x- y
print("subtracao: {}".format(subtracao))
multiplicacao = x * y
print("multiplicacao: {}".format(multiplicacao))
divisao = x / y
print("divisao: {}".format(divisao))
potencia = x**2
print("potencia: {}".format(potencia))
|
dfbb229e443f4ded326ae4e1a294357cc177c963 | mtakanen/tiny-etl | /test/test_queries.py | 2,104 | 3.65625 | 4 | import sqlite3
DB_FILENAME = 'db/tiny_etl.db'
def game_gender_ratio():
print('Gender ratio in each game:')
sql = '''select
game,
cast(sum(case when gender = 'female' then 1 else 0 end) as float)/count(*) as female_ratio,
cast(sum(case when gender = 'male' then 1 else 0 end) as float)/count(*) as male_ratio
from accounts group by game;'''
with sqlite3.connect(DB_FILENAME) as conn:
conn.row_factory=sqlite3.Row
c = conn.cursor()
c.execute(sql)
for r in c.fetchall():
print('{0} female: {1}, male: {2}'.format(r['game'],
r['female_ratio'],
r['male_ratio']))
def country_age_span():
print('\nThe youngest and oldest player per country:')
with sqlite3.connect(DB_FILENAME) as conn:
conn.row_factory=sqlite3.Row
sql = '''select country, min(age) as min_age,max(age) as max_age
from accounts
where country is not null
group by country'''
c = conn.cursor()
c.execute(sql)
for r in c.fetchall():
print('{0}: {1} {2}'.format(r['country'],r['min_age'],r['max_age']))
def data_exists():
with sqlite3.connect(DB_FILENAME) as conn:
# check that table exists
c = conn.cursor()
sql = '''SELECT count(*) FROM sqlite_master
WHERE type='view' AND name=?'''
c.execute(sql, ('accounts',))
result = c.fetchone()
return result[0] > 0
def create_view():
with sqlite3.connect(DB_FILENAME) as conn:
sql = '''create view if not exists accounts
as
select * from hb_accounts
union
select * from wwc_accounts'''
conn.execute(sql)
if __name__ == '__main__':
create_view()
if data_exists():
game_gender_ratio()
country_age_span()
else:
print('Data is missing. Run etl.py for both games first!')
|
81d228264f2c454d22dbb1ab63eb844fd86cbe34 | JaehoonKang/Computer_Science_110_Python | /FinalProject/Pers_test.py | 3,206 | 3.65625 | 4 | from tkinter import *
class GUI:
global points
points = 0
def __init__(self):
self.__window = Tk()
self.__label = Label(self.__window, text = "Question 1")
self.__label.grid(columnspan = 3)
#self.__entry.config("<Return>", self.action)
self.__button1 = Button(self.__window)
self.__button1.config(text = "hi", command = self.question_two)
self.__button1.config(text = "hi", command = self.answer_one)
self.__button1.grid(row = 1, column = 0)
self.__button2 = Button(self.__window)
self.__button2.config(command = self.question_two)
self.__button2.config(command = self.answer_two)
self.__button2.grid(row = 1, column = 1)
self.__button3 = Button(self.__window)
self.__button3.config(command = self.question_two)
self.__button3.config(command = self.answer_three)
self.__button3.grid(row = 1, column = 2)
self.__button4 = Button(self.__window)
self.__button4.config(command = self.question_two)
self.__button4.config(command = self.answer_four)
self.__button4.grid(row = 1, column = 3)
self.__window.mainloop()
def question_two(self):
self.__label.config(text = "Question 2")
self.__button1 = Button(self.__window)
self.__button1.config(text = "Hello", command = self.question_three)
self.__button1.config(command = self.answer_one)
self.__button1.grid(row = 1, column = 0)
self.__button2 = Button(self.__window)
self.__button2.config(command = self.question_three)
self.__button2.config(command = self.answer_two)
self.__button2.grid(row = 1, column = 1)
self.__button3 = Button(self.__window)
self.__button3.config(command = self.question_three)
self.__button3.config(command = self.answer_three)
self.__button3.grid(row = 1, column = 2)
self.__button4 = Button(self.__window)
self.__button4.config(command = self.question_three)
self.__button4.config(command = self.answer_four)
self.__button4.grid(row = 1, column = 3)
def question_three(self):
self.__label.config(text = "Question 3")
self.__button1 = Button(self.__window)
self.__button1.config(command = self.question_four)
self.__button1.config(command = self.answer_one)
self.__button1.grid(row = 1, column = 0)
self.__button2 = Button(self.__window)
self.__button2.config(command = self.question_four)
self.__button2.config(command = self.answer_two)
self.__button2.grid(row = 1, column = 1)
self.__button3 = Button(self.__window)
self.__button3.config(command = self.question_four)
self.__button3.config(command = self.answer_three)
self.__button3.grid(row = 1, column = 2)
self.__button4 = Button(self.__window)
self.__button4.config(command = self.question_four)
self.__button4.config(command = self.answer_four)
self.__button4.grid(row = 1, column = 3)
def answer_one(self):
global points
points += 1
print(points)
def answer_two(self):
global points
points += 2
print(points)
def answer_three(self):
global points
points += 3
print(points)
def answer_four(self):
global points
points += 4
print(points)
GUI()
|
d0af5fd66c6960be4c0db52efef84edcaf579b9f | theboocock/python_introduction | /lesson/boiler_plate.py | 854 | 4.5 | 4 | #!/usr/bin/env python
#
# @date 25 Sept 2015
# @author james Boocock
#
import argparse
def print_file(input_file):
"""
Function opens a file and prints the
results to stdout.
@param input_file
"""
with open(input_file) as f:
for line in f:
print line
def main():
"""
First function to be run in a command-line program
"""
# Create a basic command-line program the reads a file and prints it out.
parser = argparse.ArgumentParser(description="Essentially cat, but for only one file")
# Adds a input file argument to the parser.
parser.add_argument("input_file")
# parses the arguments and stores the arguments in a dictionary.
args = parser.parse_args()
# Call the print_file function.
print_file(args.input_file)
if __name__ == "__main__":
main()
|
06e9bcd7f3e63b94ca5e1f7ccbe2c058a83fde64 | jonad/udacity_aipnd_mentorship | /myscript.py | 288 | 3.703125 | 4 |
def greetings(name):
'''
Say hello to someone
:param name: name of the person
:return:
'''
print(f'Hello {name}!')
def add(x, y):
'''
Add two integer
:param x: first integer
:param y: second integer
:return:
'''
return x + y
|
241097457c81609be674b349aa293218d516734f | mietINFO/feedbackBot | /db.py | 3,080 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import sqlite3
class DataBase:
def __init__(self, db_path, db_file):
self.db_file = db_path + db_file
self.db = None
def create_db(self):
"""
Создание необходимых таблиц для работы с ботом
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
# Создаём таблицу users, если она не существует
cursor.execute("""CREATE TABLE IF NOT EXISTS users
(
user_id INT PRIMARY KEY,
state INT,
email TEXT
)""")
self.db.commit()
def check_user(self, user_id):
"""
Проверяем на существование пользователя в системе
"""
self.create_db()
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
cursor.execute('SELECT * FROM users WHERE user_id = ?', [user_id])
if cursor.fetchone() == None:
self.add_user(user_id)
def add_user(self, user_id):
"""
Добавляем нового пользователя в БД
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
data = [user_id, '1']
cursor.execute('INSERT INTO users (user_id, state) VALUES (?, ?)', data)
self.db.commit()
def update_email(self, user_id, email):
"""
Добавляем или обновляем email пользователя
"""
self.check_user(user_id)
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
data = [email, user_id]
cursor.execute('UPDATE users SET email = ? WHERE user_id = ?', data)
self.db.commit()
def get_user(self, user_id):
"""
Возвращаем данные определённого пользователя
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
cursor.execute('SELECT state, email FROM users WHERE user_id = ?', [user_id])
return cursor.fetchone()
def get_state(self, user_id):
"""
Возвращаем текущее состояние пользователя
"""
self.check_user(user_id)
return self.get_user(user_id)[0]
def set_state(self, user_id, state):
"""
Устанавливаем определённое состояние пользователя
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
state = state
data = [state, user_id]
cursor.execute('UPDATE users SET state = ? WHERE user_id = ?', data)
self.db.commit()
def get_email(self, user_id):
"""
Возвращаем email пользователя
"""
return self.get_user(user_id)[1] |
c4e9c3faddee78bae52949a55fe0c53702c37743 | nuria/study | /EPI/string_dictionary.py | 1,891 | 3.875 | 4 | #!/usr/lib
"""
You are given a dictionary of words and a large input string. You have to find out whether the input string can be completely segmented into the words of a given dictionary.
dictionary = ['apple', 'apple', 'pear', 'pie']
string ="applepie' =>Y
string =applepeer=>no
this is called word break on let code
"""
import sys
def main():
# easy example: _input applepie, applepier
d = set(['apple', 'apple', 'pear', 'pie'])
# harder example: _input ='aaaaaaa'
#d = set (['aaaa', 'aaa'])
_input = sys.argv[1]
# this is a tree , the 1st posibility that matches might not be the best
# so you have to keep on trying possibilities until an optimal combination
_min = float('inf')
_max = 0
for w in d:
if len(w) > _max:
_max = len(w)
if len(w) < _min:
_min = len(w)
# returns 1 if parseable according to dictionary, 0 otherwise
# adding cache, this smells like DP
# 1 if string is parseable, 0 otherwise
# needs a cache to perform, which hints a DP solution
def parseable(c,d, _max, _min):
if len(c) > 0 and len(c) < _min:
return 0
if len(c) == 0:
return 1
j = 1
i = 0
possibilities = []
while j <= len(c):
s=c[i:j]
if j <= _max:
if s in d:
possibilities.append(parseable(c[j:],d, _max,_min))
print possibilities
# also continue
j = j + 1
else:
break
if sum(possibilities) > 0:
return 1
else:
return 0
is_parseable = parseable(_input, d, _max, _min)
if is_parseable > 0:
print "True"
return True
else:
print "false"
return False
if __name__=="__main__":
main()
|
f7cc4911e72d857cfe9bf6b6d65f339a3adf6f47 | Reena-Kumari20/FunctionQuestions | /more_exercise/question7.py | 897 | 3.75 | 4 | #Socho aapke paas 2 lists hain. Aapne aisa code likhna hain jisse ek nayi list banne
# jisme inn dono lists ke woh item hone chaiye ho dono list mein aa rahe hain.
# Socho aapki do list yeh hain:
#list1 = [1, 342, 75, 23, 98]
#list2 = [75, 23, 98, 12, 78, 10, 1]
#Inn dono list se aapki nayi list yeh banni chaiye:
#new_list = [1, 23, 75, 98]
#Iss nayi list mein sirf 1, 75 aur 98 isliye hain kyunki aur koi bhi items dono lists mein nahi aa rahi. Dusri saari items ya toh pehli list mein aa rahi hai ya dusri mein. Note: Aapka yeh code kitne bhi items ki list pe kaam karna chaiye. Aur dono lists ki length alag bhi ho sakti hai.
def new_list(list1,list2):
i=0
a=list1+list2
b=[]
while i<len(a):
if a[i] not in b:
b.append(a[i])
i=i+1
return(b)
list1 = [1, 342, 75, 23, 98]
list2 = [75, 23, 98, 12, 78, 10, 1]
print(new_list(list1,list2))
|
6088665f00977ed53ad97605266556048012ce80 | XiaoqinLI/-Python-Web-Developing-and-Programming-Language | /Building_Web_browser/ProgrammingLanguages_Udacity/List_comp_map.py | 692 | 3.640625 | 4 | ## Programming Language Python
## List_Comprehention_map analyzer
## Author: Xiaoqin LI
## Created Date: 03/23/2014
grammar = [
("exp", ["exp", "+", "exp"]),
("exp", ["exp", "-", "exp"]),
("exp", ["(", "exp", ")"]),
("exp", ["num"]),
]
def expand(tokens, grammar):
for pos in range(len(tokens)):
for rule in grammar:
if (tokens[pos] == rule[0]):
yield tokens[0:pos] + rule[1] + tokens[pos+1:]
depth = 1
utterances = [["a","exp"]]
for x in range(depth):
for sentence in utterances:
utterances = utterances + [ i for i in expand(sentence, grammar)]
for sentence in utterances:
print (sentence)
|
eba12bef29d577a7d5a276697963da757d0463b7 | UnSi/2_GeekBrains_courses_algorithms | /Lesson 3/hw/task3.py | 686 | 4.03125 | 4 | # 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import randint
rand_array = [randint(1, 100) for _ in range(100)]
min_el = max_el = rand_array[0]
min_idx = max_idx = 0
for i, num in enumerate(rand_array):
if num > max_el:
max_el, max_idx = num, i
if num < min_el:
min_el, min_idx = num, i
print(f"Максимальный: {max_el} на месте: {max_idx+1}\nМинимальный: {min_el} на месте: {min_idx+1}")
rand_array[max_idx], rand_array[min_idx] = rand_array[min_idx], rand_array[max_idx]
print(rand_array)
|
bdd71107a665c61d34660bd7be19e8d2d9d042ee | adampower48/codeforces | /Chat Room.py | 201 | 3.765625 | 4 | hello = "hello"
word = input()
index = 0
for letter in word:
if letter == hello[index]:
if index == 4:
print("YES")
break
index += 1
else:
print("NO")
|
5ef621350a817e0e3ab644085d7204824e095469 | VivianaMontacost/ProyectoBancoEAN | /BancoEAN.py | 5,292 | 4.09375 | 4 | """
Juandabu
"""
persona= ['clark kent', 'Bruce Wane' ]
usuario= ['superman' , 'batman' ]
contraseña= [1111 , 2222 ]
numero_de_cuenta= [ 3115996681 , 32221822 ]
tipo_de_cuenta= [ 'corriente', 'ahorros' ]
dinero= [ 1000.00 , 1500.00 ]
rta_pregunta_de_seguridad= ['perro' , 'murcielago' ]
estado_sesion= ['cerrada' , 'cerrada' ]
'''
print("Estado inicial en el banco")
for i in list(range(0,len(persona))):
print("\n")
print(" persona:",persona[i])
print(" usuario:",usuario[i])
print(" contraseña:",contraseña[i])
print(" numero_de_cuenta:",numero_de_cuenta[i])
print(" tipo_de_cuenta:",tipo_de_cuenta[i])
print(" dinero:",dinero[i])
print(" rta_pregunta_de_seguridad:",rta_pregunta_de_seguridad[i])
print(" estado_sesion:",estado_sesion[i])
print("\n")
'''
while(True):
sesion=False
while(sesion==False):
print("\n")
print("INICIO DE SESIÓN")
print("ingrese usuario:")
usuario_ingresado=input()
print("ingrese contraseña:")
contraseña_ingresada=input()
print(contraseña_ingresada)
if usuario_ingresado in usuario:
indice=usuario.index(usuario_ingresado)
if contraseña[indice] == int(contraseña_ingresada):
estado_sesion[indice] ='activa'
print("usuario logueado")
sesion=True
else:
print("contraseña invalida")
else:
print("usuario no existe")
sesion_terminada=False
while(sesion_terminada==False):
print("\n")
print("ELIJA ALGUNA TRANSACCION POR EL NUMERO:")
print("1: Consultar saldo")
print("2: Hacer retiro")
print("3: Transferir dinero")
print("4: Cerrar sesión")
print("5: Estado todas las cuentas del banco")
opcion=input()
opcion=int(opcion)
if opcion in [1,2,3,4,5]:
indice=usuario.index(usuario_ingresado)
if estado_sesion[indice] =='activa':
if opcion==1:
print("Saldo en cuenta",numero_de_cuenta[indice] ,":",dinero[indice] )
if opcion==2:
print("Digite el valor a retirar:")
valor_retiro=input()
valor_retiro=int(valor_retiro)
if valor_retiro > dinero[indice]:
print("Fondos insuficientes")
else:
dinero[indice]=dinero[indice]-valor_retiro
print("Valor retiro:",valor_retiro )
print("Saldo en cuenta:",dinero[indice] )
if opcion==3:
print("Digite el valor de la trasferencia:")
valor_trasferencia=input()
valor_trasferencia=int(valor_trasferencia)
print("Digite la cuenta de destino:")
numero_de_cuenta_final=input()
numero_de_cuenta_final=int(numero_de_cuenta_final)
if valor_trasferencia > dinero[indice]:
print("fondos insuficientes")
else:
if numero_de_cuenta_final in numero_de_cuenta:
indice_cta=numero_de_cuenta.index(numero_de_cuenta_final)
dinero[indice]=dinero[indice]-valor_trasferencia
dinero[indice_cta]=dinero[indice_cta]+valor_trasferencia
print("trasferencia exitosa al numero de cuenta:",numero_de_cuenta_final )
print("valor trasferencia:",valor_trasferencia)
print("saldo en cuenta",numero_de_cuenta[indice] ,":",dinero[indice] )
else:
print("la cuenta de destino no existe")
if opcion==4:
if estado_sesion[indice] =='activa':
estado_sesion[indice] ='cerrada'
print("sesion cerrada")
else:
print("sesion ya está cerrada")
sesion_terminada=True
if opcion==5:
print("\n")
print("Estado cuentas banco")
for i in list(range(0,len(persona))):
print("\n")
print(" persona:",persona[i])
print(" usuario:",usuario[i])
print(" contraseña:",contraseña[i])
print(" numero_de_cuenta:",numero_de_cuenta[i])
print(" tipo_de_cuenta:",tipo_de_cuenta[i])
print(" dinero:",dinero[i])
print(" rta_pregunta_de_seguridad:",rta_pregunta_de_seguridad[i])
print(" estado_sesion:",estado_sesion[i])
print("\n")
else:
print("sesion no activa, tramite invalido")
else:
print("Opción invalida") |
085177c3192c6ac4f13f07826c64222f6e86e220 | c-maragh/blackjack | /Blackjack.py | 4,948 | 3.59375 | 4 | # blackjack
import random
suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
playing = True
# Card class
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'{self.rank} of {self.suit}'
# Deck class
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
# shuffle function
def shuffle(self):
random.shuffle(self.deck)
# deal card function, removes one card from the deck
def deal_card(self):
return self.deck.pop()
# Player hand Class
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.value += values[card.rank]
if card.rank == 'Ace':
self.aces += 1
# function to adjust for ace if needed
def adjust_ace(self):
while self.aces > 0 and self.value > 21:
self.value -= 10
self.aces -= 1
# chips Class
class Chips:
def __init__(self):
self.total = 100
self.bet = 0
def win_bet(self):
self.total = self.total + self.bet
def lose_bet(self):
self.total = self.total - self.bet
if self.total <= 0:
print('Out of chips. You might owe money...')
else:
print(self.total)
# GENERAL FUNCTIONS #
def take_bet(chips):
while chips.bet == 0:
chips.bet = int(input('How many chips would you like to bet? Enter a numeric value higher than 0: '))
if chips.bet > chips.total:
print(f'Not enough chips. You have {chips.total} chips remaining.')
chips.bet = 0
def hit(deck, hand):
hand.add_card(deck.deal_card())
hand.adjust_ace()
def hit_or_stand(deck, hand):
# make more specific with a tuple/list and indexing
global playing
while True:
hit_choice = input('Would you like to hit or stand? Enter H or S? ')
if hit_choice[0].lower() == 'h':
hit(deck, hand)
elif hit_choice[0].lower() == 's':
print("Player stands, Dealer's turn.")
playing = False
else:
print('Try again, enter h or s')
continue
break
# PLAYER/DEALER SHOW HAND FUNCTIONS #
def show_some(player, dealer):
# Player Info
print("Player Info:")
print("Cards:")
print(*player.cards, sep='\n')
print(f"Card Value: {player.value}\n")
# Dealer Info
print("Dealer Info:")
print('Cards:')
print('<hidden>', *dealer.cards[1:], sep='\n')
def show_all(player, dealer):
# Player Info
print("Player Info:")
print("Cards:")
print(*player.cards, sep='\n')
print(f"Card Value: {player.value}\n")
# Dealer Info
print("Dealer Info:")
print("Cards:")
print(*dealer.cards, sep='\n')
print(f"Card Value: {dealer.value}")
# END GAME OUTCOMES #
def player_wins(player, dealer, chips):
print('Player wins!')
chips.win_bet()
def player_busts(player, dealer, chips):
print('Player busts!')
chips.lose_bet()
def dealer_wins(player, dealer, chips):
print('Dealer wins!')
chips.lose_bet()
def dealer_busts(player, dealer, chips):
print('Dealer busts!')
chips.win_bet()
def push(player, dealer):
print('Dealer and player tie! Game pushes.')
# GAME LOGIC #
while True:
print('Welcome to Blackjack!')
deck = Deck()
deck.shuffle()
# player setup
player_hand = Hand()
player_hand.add_card(deck.deal_card())
player_hand.add_card(deck.deal_card())
player_chips = Chips()
# dealer setup
dealer_hand = Hand()
dealer_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
# bet
take_bet(player_chips)
# show hands, one dealer card is hidden
show_some(player_hand, dealer_hand)
while playing:
hit_or_stand(deck, player_hand)
show_some(player_hand, dealer_hand)
if player_hand.value > 21:
player_busts(player_hand, dealer_hand, player_chips)
break
# dealer has to hit until 17 or bust
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
show_all(player_hand, dealer_hand)
# END GAME #
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
# player winnings/losses
print(f"Player's winnings: {player_chips.total}")
# play again check
new_game = input("Play again? Y or N: ")
if new_game[0].lower() == 'y':
playing = True
continue
else:
print('Thanks for playing!')
break
|
3ecf2fe80d4b46dfe585690ced9a4ccd3503c2c4 | s-passalacqua-iresm/AlgoritmosyEstructuraDatos1 | /Actividad 1- Decisión simple/ACTIVITY 1- EX 1.py | 305 | 3.96875 | 4 | #Algotimo que lea entero y verifique sea mayor a 10.
#Si lo es, escribir el número, si no, mensaje que diga que es menor o igual
numeroentero=int(input("Ingrese un número entero: "))
if int(numeroentero) >10:
print(f"{numeroentero}")
else:
print(f"El número ingresado es menor o igual a 10") |
d626aa2c9f60825cc273e3f91d20c9a7b0cb9c9b | AFLANSODEV/MetaLex | /dicOcrText/wordsCorrection.py | 4,508 | 3.546875 | 4 | #! usr/bin/env python
# coding: utf8
"""
Implémentation des outils de correction orthographique.
Usage:
>>> from MetaLex.wordsCorrection import *
>>> correctWord(word)
"""
# ----Internal Modules------------------------------------------------------
import MetaLex
# ----External Modules------------------------------------------------------
import re, sys, collections
from collections import Counter
# -----Exported Functions-----------------------------------------------------
__all__ = ['correctWord', 'wordReplace', 'caractReplace']
# -----Global Variables-----------------------------------------------------
# -------------------------------------------------------------------------------
def correctWord (word):
"""
Give a good spelling of the input word
@param word:str
@return: str:word
"""
correct = wordCorrection()
if len(word) > 1 :
word = word.strip()
if word[-1] in [u'.', u',']:
fin = word[-1]
if word[0].isupper() :
deb = word[0]
wordc = word[:-1]
goodword = correct.correction(wordc.lower())
wordg = deb+goodword[1:]+fin
return wordg
else :
wordc = word[:-1]
goodword = correct.correction(wordc)
wordg = goodword+fin
return wordg
elif word[-1] in [u')']:
return word
elif word[1] in [u"'", u"’"] :
wordtab = word.split(u"’")
deb, wordc = wordtab[0], wordtab[1]
goodword = correct.correction(wordc)
wordg = deb+u'’'+goodword[1:]
return wordg
elif word[0] in [u":"] :
wordtab = word.split(u":")
deb, wordc = wordtab[0], wordtab[1]
goodword = correct.correction(wordc)
wordg = deb+u'’'+goodword[1:]
return wordg
else :
goodword = correct.correction(word)
return goodword
else :
return word
class wordCorrection :
"""
Give a good spelling of the input word
@return: inst:objetwordcorrection
"""
def __init__(self):
MetaLex.dicPlugins
filepath = sys.path[-1]+'/METALEX_words-corpus.txt'
self.corpusData = open(filepath).read()
self.WORDS = {}
self.start()
self.lettersFr = u"abcdefghijklmnopqrstuvwxyzéèêîiïàùûâ'"
def start(self):
self.WORDS = self.train(self.words(self.corpusData))
def words(self, text):
return re.findall(r'(\s+)', text.lower())
def train(self, features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
def edits1(self, word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in self.lettersFr if b]
inserts = [a + c + b for a, b in splits for c in self.lettersFr]
return set(deletes + transposes + replaces + inserts)
def known_edits2(self, word):
return set(e2 for e1 in self.edits1(word) for e2 in self.edits1(e1) if e2 in self.WORDS)
def known(self, words): return set(w for w in words if w in self.WORDS)
def correction(self, word):
candidates = self.known([word]) or self.known(self.edits1(word)) or self.known_edits2(word) or [word]
return max(candidates, key=self.WORDS.get)
def wordReplace(word, data, test=False):
"""
"""
equiv_words = data
if test :
if equiv_words.has_key(word) :
return True
else :
return False
elif word in equiv_words.keys() :
return equiv_words[word]
def caractReplace(word, data, test=False):
"""
"""
equiv_caract = data
equiv_keys = equiv_caract.keys()
if test :
for k in equiv_keys:
#print word + ' ' + k
if word.find(k):
return True
else :
return False
else :
for k in equiv_keys :
#print equiv_caract.keys()
if word.find(k):
return re.sub(k, equiv_caract[k], word)
|
26a8d753caec82fc78e8087396eeebd01b7e072c | voyager1684/Basic-Physics | /CentripetalAcceleration.py | 1,862 | 4.28125 | 4 | print("\nSet the friction coefficient, mass of the object and the radius of the corner.\n") # Prints the protocol.
key = int(input("Press 1 to check the speed. \nPress 2 to get the technical information. \nPress 0 to exit.\n"))
if key == 0:
exit()
µ = float(input("Enter µ, the constant of static friction: "))
mass = float(input("Input Mass (in kilograms): "))
radius = float(input("Input the radius of the chicane/apex (in meters): "))
speed = 0.0
g = 9.81
def speedCheck():
speed = float(input("Enter speed (in meters per second): "))
safe = False
if speed <= (µ * radius * g) ** (1/2):
safe = True
if safe:
print("Safe.")
else:
difference = (speed - (µ * radius * g) ** (1/2))
print("NOT safe.\nDecrease speed by ", str(float(difference)), "m/s" )
def safeSpeed():
speed = (µ * radius * g) ** (1 / 2)
return("\nThe maximum speed you can attain without skidding is " + str(round(speed)) + " m/s (" + str(round(speed)*3.6) + " km/h, "
+ str(round(speed)*2.237) + " mi/h)")
def CentrAcc():
return (((µ * radius * g) ** (1 / 2)) ** 2 / radius) % 1000
def CentrForce():
return CentrAcc() * mass % 1000
while key != 0:
if key == 1:
speedCheck()
key = int(input("\n\nPress 1 to check the speed. \nPress 2 to get the technical information. \nPress 0 to exit.\n"))
elif key == 2:
print(safeSpeed(), "\nCentripetal acceleartion is ", str(CentrAcc()), " m/s^2", "\nCentripetal force is ",
str(CentrForce()), " Newtons")
key = int(input("\n\nPress 1 to check the speed. \nPress 2 to get the technical information. \nPress 0 to exit.\n"))
else:
print("Press 1, 2 or 0")
key = int(input("\n\nPress 1 to check the speed. \nPress 2 to get the technical information. \nPress 0 to exit.\n"))
|
f231d571cc9898da801e17f8476653c99727a9a1 | IanRivas/python-ejercicios | /tp2-Listas/7.py | 646 | 4.34375 | 4 | '''
7. Intercalar los elementos de una lista entre los elementos de otra. La intercalación deberá realizarse
exclusivamente mediante la técnica de rebanadas y no se creará una lista nueva sino que se modificará
la primera. Por ejemplo, si lista1 = [8, 1, 3] y lista2 = [5, 9, 7], lista 1 deberá quedar como
[8, 5, 1, 9, 3, 7].
'''
def intercalar(lista1,lista2):
hasta=len(lista1)
for i in range(0,hasta):
lista1[2*i+1:2*i+1]=lista2[i:i+1]
# lista1[1:1] = lista2[0:1] [8,5,1,3]
def main():
lista1=[8,1,3]
lista2=[5,9,7]
intercalar(lista1,lista2)
print(lista1)
if __name__ == '__main__':
main() |
cc6fcf9f15861328fb0dd2504e2b9f6cc3bf63c3 | pradeep1412/Coursera-Algorithmic-Toolbox | /week2_algorithmic_warmup/lcm.py | 370 | 3.609375 | 4 | # Uses python3
import sys
import time
def gcd(a, b):
if a < b:
temp = a
a = b
b = temp
while b != 0:
temp = a % b
a = b
b = temp
if a == 0 and b == 0:
a = 1
return a
if __name__ == '__main__':
a, b = map(int, input().split())
print((a * b) // gcd(a, b))
#print(time.process_time())
|
a5b08cbd86cae62c07cc6489d31bced424dbf6b0 | isaacdelarosamendez/CursoPythonAbril2019 | /Clase_04_05_2019/persona.py | 431 | 3.5 | 4 | class Persona:
def __init__(self,estatura, peso,tes):
self.estatura = estatura
self.peso = peso
self.tes = tes
def Pesar(self):
print("Peso "+str(self.peso))
class Hombre(Persona):
def __init__(self,estatura,peso, nombre):
self.nombre = nombre
Persona.__init__(self,estatura,peso)
def Descripcion(self):
print(self.nombre + " pesa "+ str(self.peso))
_hombre = Hombre(1.75,85, "Eliud ")
_hombre.Descripcion()
|
b057fc8b1c35f94fd19b70ea86c0fe05901c21a0 | KevinLAnthony/learn_python_the_hard_way | /ex20/ex20.2.py | 1,974 | 4.3125 | 4 | #import the argv module / library
from sys import argv
#hold arguments in argv module. Also, consider that script and filename are being declared as
#variables and are each being set to the argv module
script, input_file = argv
#create function and add parameter(s).
def print_all(f):
#run print() function using value from parameter from overall containing function
#and run read() function on parameter
print(f.read())
#create function and add parameter(s).
def rewind(f):
#run seek() function on parameter from overall containing function. Add a parameter to seek() function.
f.seek(0)
#create function and add parameter(s).
def print_a_line(line_count, f):
#run print() function using values from both parameters from overall containing function
#and run readline() function on one of those parameters
print(line_count, f.readline())
#declare object and set it equal to open() function containing variable set to argv module
current_file = open(input_file)
#print message
print("First let's print the whole file:\n")
#print value contained in object
print_all(current_file)
#print message
print("Now let's rewind, kind of like a tape.")
#run rewind function using valued contained within object
rewind(current_file)
#print message
print("Let's print three lines:")
#declare variable and give it a value
current_line = 1
#run print_a_line function using value contained within current_line variable and current_file object
print_a_line(current_line, current_file) # current_line = 1
#increment current_line variable by one
current_line = current_line + 1
#run print_a_line function using value contained within current_line variable and current_file object
print_a_line(current_line, current_file) # current_line = 2
#increment current_line variable by one
current_line = current_line + 1
#run print_a_line function using value contained within current_line variable and current_file object
print_a_line(current_line, current_file) # current_line = 3 |
2d93353c50743f5009df79f68123d9f72bbe22ef | Sleeither1234/t0_7_huatay.chunga | /huatay/bucle_para_02.py | 242 | 3.734375 | 4 | #tabla de multiplicar
import os
#Asignacion de valores
numero=int(os.sys.argv[1])
valor=range(1,13)
#bucle para
for elemento in valor:
producto=numero*elemento
print(numero,"x",elemento,"=",producto)
#fin_for
print("fin del bubcle")
|
41154e5ebc6e43884cafeb9931375b474374cda5 | submarrin/numerical_methods_Cauchy_problem | /main.py | 2,537 | 3.875 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab
# начальные условия
n = int(input('Введите число отрезков n = '))
x0 = 0
y0 = 0.1
xn = 1
h = (xn-x0)/n
x_list = np.linspace(0, 1, n + 1) # n отрезков, следовательно n + 1 точка
print(x_list)
def func(x, y):
return 50 * y * (x-0.6) * (x-0.85)
def accurAnswer(x):
return 0.1 * math.exp(50*pow(x, 3)/3 - 145*pow(x, 2)/4 + 25.5*x)
# массив со значениями точного решения
y_list = []
print("Точные значения в точках")
for x in x_list:
y_list.append(round(accurAnswer(x), 5))
print(y_list)
def eiler(x, y, h, f):
return y + h*f(x, y)
y = y0
y_list_eiler = [0.1]
print("Явный метод Эйлера для", n, "шагов")
for x in x_list:
y = eiler(x, y, h, func)
y_list_eiler.append(round(y, 5))
print(y_list_eiler[:n+1])
def runge_kutta(x, y, h, f):
def k_1(x, y):
return h * f(x, y)
def k_2(x, y):
return h * f(x + h/2, y + k_1(x, y)/2)
def k_3(x, y):
return h * f(x + h/2, y + k_2(x, y)/2)
def k_4(x, y):
return h * f(x + h, y + k_3(x, y))
return y + k_1(x, y) / 6 + k_2(x, y) / 3 + k_3(x, y) / 3 + k_4(x, y) / 6
y = y0
y_list_runge = [0.1]
print("Метод Рунге-Кутта 4-го порядка для", n, "шагов")
for x in x_list:
y = runge_kutta(x, y, h, func)
y_list_runge.append(round(y, 5))
print(y_list_runge[:n+1])
print("Метод Симпсона для ", n, "шагов")
def simpson(x_list, y_list_eiler, h, f):
prev = y_list_eiler[1]
preprev = y_list_eiler[0]
result_list = [preprev, prev]
for i in range(0, n - 1):
y = preprev + h * (f(x_list[i+2], y_list_eiler[i + 2]) + 4*f(x_list[i+1], prev) + f(x_list[i], preprev)) / 3
preprev = prev
prev = y
result_list.append(round(y, 5))
return result_list
y_list_simpson = simpson(x_list, y_list_eiler, h, func)
print(y_list_simpson)
plt.rc('font', **{'family': 'tahoma'})
plt.xlabel("abciss")
plt.ylabel("ordinat")
plt.plot(x_list, y_list, "c-", label=" accurate")
plt.plot(x_list, y_list_eiler[:n+1], "m-", label=" euler")
plt.plot(x_list, y_list_runge[:n+1], "y-", label=" runge")
plt.plot(x_list, y_list_simpson, "k-", label="simpson")
plt.legend()
plt.grid()
plt.show()
|
28e02b18cdaa0e4a1667ca4219bc21bf14b9be83 | rudrasingh21/Spark-2-Applications- | /PySpark Basic Spark SQL Operations JANANI RAVI.py | 4,051 | 3.8125 | 4 | ----------------------------------
Querying Data Using Spark SQL : Demo: Basic Spark SQL Operations:- Janani Ravi
----------------------------------
>>> from pyspark.sql.types import Row
from datetime import datetime
##### Creating a dataframe with different data types
record = sc.parallelize([Row(id = 1,
name = "Jill",
active = True,
clubs = ['chess', 'hockey'],
subjects = {"math": 80, 'english': 56},
enrolled = datetime(2014, 8, 1, 14, 1, 5)),
Row(id = 2,
name = "George",
active = False,
clubs = ['chess', 'soccer'],
subjects = {"math": 60, 'english': 96},
enrolled = datetime(2015, 3, 21, 8, 2, 5))
])
>>> record_df = record.toDF()
>>> record_df.show()
+------+---------------+--------------------+---+------+--------------------+
|active| clubs| enrolled| id| name| subjects|
+------+---------------+--------------------+---+------+--------------------+
| true|[chess, hockey]|2014-08-01 14:01:...| 1| Jill|Map(math -> 80, e...|
| false|[chess, soccer]|2015-03-21 08:02:...| 2|George|Map(math -> 60, e...|
+------+---------------+--------------------+---+------+--------------------+
NOTE:- If you want to run SQL query on this data then need to register DataFrame as a Table.
Table will be available only for a session.
Not shares across spark sessions.
#>>> record_df.registerTempTable("records") ----- in Spark 1.6
>>> record_df.createOrReplaceTempView("table1") -- table for session only
# table1 is the name of our sql table.
>>> all_records_df = sqlContext.sql('select * from table1')
# This sql query will act as data frame now , we can perform all data frame operations
>>> all_records_df.show()
+------+---------------+-------------------+---+------+--------------------+
|active| clubs| enrolled| id| name| subjects|
+------+---------------+-------------------+---+------+--------------------+
| true|[chess, hockey]|2014-08-01 14:01:05| 1| Jill|Map(english -> 56...|
| false|[chess, soccer]|2015-03-21 08:02:05| 2|George|Map(english -> 96...|
+------+---------------+-------------------+---+------+--------------------+
NOTE:- Complex sql query from table table1:-
>>> sqlContext.sql('select id,clubs[1], subjects["english"] from table1').show()
+---+--------+-----------------+
| id|clubs[1]|subjects[english]|
+---+--------+-----------------+
| 1| hockey| 56|
| 2| soccer| 96|
+---+--------+-----------------+
>>> sqlContext.sql('select * from table1 where subjects["english"] > 90').show()
+------+---------------+-------------------+---+------+--------------------+
|active| clubs| enrolled| id| name| subjects|
+------+---------------+-------------------+---+------+--------------------+
| false|[chess, soccer]|2015-03-21 08:02:05| 2|George|Map(english -> 96...|
+------+---------------+-------------------+---+------+--------------------+
*******************************GLOBAL TABLE******************************
Register a table so that it can access accross the session.
>>> record_df.createGlobalTempView("global_records")
>>> sqlContext.sql('select * from global_temp.global_records').show()
+------+---------------+-------------------+---+------+--------------------+
|active| clubs| enrolled| id| name| subjects|
+------+---------------+-------------------+---+------+--------------------+
| true|[chess, hockey]|2014-08-01 14:01:05| 1| Jill|Map(english -> 56...|
| false|[chess, soccer]|2015-03-21 08:02:05| 2|George|Map(english -> 96...|
+------+---------------+-------------------+---+------+--------------------+
|
e3cca4a15af61ffd345322fa017c89c966381b89 | jbro885/gigatron | /data/convert.py | 857 | 3.765625 | 4 | import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--binary", action="store_true",
help="convert to binary")
parser.add_argument("filename", type=str,
help="the filename to convert")
args = parser.parse_args()
filename = args.filename
is_binary = args.binary
with open(filename, "rb") as f:
data = f.read()
for i in range(0, len(data), 2):
byte2 = data[i]
byte1 = 0 if i + 1 == len(data) else data[i + 1]
if is_binary:
print("%s%s" %\
(bin(byte1)[2:].zfill(8),
bin(byte2)[2:].zfill(8)))
else:
print("%s%s" %\
(hex(byte1)[2:].zfill(2),
hex(byte2)[2:].zfill(2)))
if __name__ == "__main__":
main()
|
4cdd2bd068483d2c8989a639fc02fd75e402811f | camiloprado/Curso-Python | /Aula 21.py | 286 | 3.90625 | 4 | frase = str(input('Digite uma frase: ')).upper().strip()
print('A letra "A" aparece no total de {}'.format(frase.count('A')))
print('Sua primeira aparição foi na posição {}'.format(frase.find('A') + 1))
print('Sua ultima aparição foi na posição {}'.format(frase.rfind('A') + 1)) |
b4a5b022a40baa969e3c9ac74983176d544eb7c7 | eileenjang/algorithm-study | /src/sunwoo/source_code/week8/괄호_변환.py | 753 | 3.5 | 4 | def solution(p):
if len(p) == 0: return ''
left, right = p[0], ''
count = 1 if left == '(' else -1
for c in p[1:]:
if count == 0:
right += c
else:
count += 1 if c == '(' else -1
left += c
if valid(left):
return left + solution(right)
else:
answer = '(' + solution(right) + ')'
for c in left[1:-1]:
answer += '(' if c == ')' else ')'
return answer
def valid(p):
list = []
try:
for c in p: list.append(c) if c == '(' else list.pop()
return True
except:
return False
print(solution('(' + ')('[1:-1][::-1] + ')'))
print(solution('()))((()'))
print(solution('(()())()'))
print(solution('()))((()')) |
b567e9fabdb4d55a83788a21e3a2166bcef5386d | yanbinkang/problem-bank | /coderust/arrays/rotate_array_in_place.py | 1,004 | 4.125 | 4 | def rotate_array_in_place(nums, k):
"""
algorithm:
let a= [1,2,3,4,5,6,7]
k = 3.
1. we have to first reverse the whole array by swapping first element with the last one and so on..
you will get [7, 6, 5, 4, 3, 2, 1]
2. reverse the elements from 0 to k - 1
reverse the elements 7, 6, 5
you will get [5, 6, 7, 4, 3, 2, 1]
3. reverse the elements from k to n - 1
reverse the elements 4,3,2,1
you will get [5, 6, 7, 1, 2, 3, 4]
Note: we do k = k % len(nums) because sometimes, k is larger than the length of array. For example nums = [1, 2, 3, 4, 5], k = 12, this means we only need to rotate the last two numbers. k = k % nums.length = 2
"""
k = k % len(nums)
reverse(nums, 0, len(nums) - 1)
reverse(nums, 0, k - 1)
reverse(nums, k, len(nums) - 1)
def reverse(nums, first, last):
while first < last:
temp = nums[first]
nums[first] = nums[last]
nums[last] = temp
first += 1
last -= 1
|
9717ad2bf4fbc412980b022dbfa2fb1487f70fb3 | Deepakvm18/luminardeepak | /flowcontrols/decisionMaking/largestamong3.py | 337 | 4.15625 | 4 | n1=int(input("ENTER FIRST NUMBER: "))
n2=int(input("ENTER SECOND NUMBER: "))
n3=int(input("ENTER THIRD NUMBER: "))
if (n1>n2)&(n1>n3):
print("FIRST NUMBER IS LARGEST")
elif (n2>n1)&(n2>n3):
print("second number is largest")
elif (n3>n1)&(n3>n2):
print("third number is largest")
else:
print("numbers repeated or invalid") |
614a65779ba6014cd58944da58ae13722f014e06 | TakahiroSono/atcoder | /practice/python/ABC159/B.py | 296 | 3.703125 | 4 | S = input()
N = len(S)
def isPalindrome(s):
n = len(s)
re_s = s[::-1]
for i in range(n // 2):
if re_s[i] != s[i]:
break
else:
return True
return False
if isPalindrome(S) and isPalindrome(S[:N // 2]) and isPalindrome(S[(N + 1) // 2:]):
print('Yes')
else:
print('No')
|
8ae81d05b480e2cc0e1776813012587349c38557 | PrestonGetz/ProgrammingAssignments | /A10.py | 181 | 3.578125 | 4 | ans = 0
for i in range (0,500):
if(i % 3 == 0 or i % 5 == 0):
ans = ans+i
print(ans)
#ans2 = sum(set(list(range(0,500,3)) + list(range(0,500,5))))
#print(ans2) this is faster
|
3dd2c78024750c1506039c23eaf1415fc3d785b9 | pyupya/code_study | /programmers/sort/biggest_number_lv2.py | 823 | 3.515625 | 4 | def solution(numbers):
answer = ''
numbers = list(map(str, numbers)) # 숫자를 string으로 변환 --> 사전식 역순으로 정렬하기 위해서
numbers.sort(key = lambda x: x*4, reverse=True) # 문제에서 요구하는 제한사항 중, 원소가 0~ 1000의 수
# 1의 자리 수와 그 이상의 자리 수들을 비교하기 위함
# ex) 3, 30을 비교하면 330이 되어야하는데, 사전 역순 정렬시, 30이 더 앞으로 옴. --> 303이 됨
# 이를 위해 3->3333으로, 30 -> 30303030으로 변환 시, 사전식 역순 상 3333이 더 앞으로 옴
return str(int(''.join(numbers))) |
dff8ddb6ad86bd4e05429a92a07beec034c21f58 | NikiDimov/SoftUni-Python-Advanced | /error_handling_10_21/email_validator.py | 642 | 3.8125 | 4 | class NameTooShortError(Exception):
pass
class MustContainAtSymbolError(Exception):
pass
class InvalidDomainError(Exception):
pass
mail = input()
valid_domains = {"com", "bg", "net", "org"}
while not mail == "End":
if '@' not in mail:
raise MustContainAtSymbolError("Email must contain @")
name, domain = mail.split('@')
if len(name) <= 4:
raise NameTooShortError("Name must be more than 4 characters")
if domain.split('.')[-1] not in valid_domains:
raise InvalidDomainError("Domain must be one of the following: .com, .bg, .org, .net")
print("Email is valid")
mail = input()
|
37f2e3de29f728283749c62ae2ea835cc5e0599c | hmoshabbar/PracticeProgramAll | /dictMethod.py | 688 | 4.1875 | 4 | my_dict={"ID":123,"Name":"Moshabbar","Dept":"IT","Salary":12000}
# print my_dict.keys()
# print my_dict.values()
#
# # Only Keys output purpose...
# for i in my_dict.keys():
# print i
#
# # Only Values output showing Purpose....
# for j in my_dict.values():
# print j
# For Key value output Purpose.....
# var1=my_dict.iteritems()
# for key,v in var1:
# print key ,v
# print Out The Result as per Dictionary format
# for key,v in sorted(my_dict.iteritems()):
# print key,v
#
# for key, value in sorted(my_dict.iteritems(), key=lambda (k,v): (v,k)):
# print "%s: %s" % (key, value)
import collections
print collections.OrderedDict(my_dict)
|
d6b330ec737ee0781fbefe9135e47a3a1671f699 | omartorrado/di_ejerciciosRepaso | /Ejercicio8.py | 155 | 3.53125 | 4 | def consonantes(frase):
for l in frase:
if(l!="a" and l!="e" and l!="i" and l!="o" and l!="u"):
print(l)
consonantes("logaritmo")
|
e6187a38cc8f35a52ff323c0330ecbd4ce544a4d | mbaseman1918/testrep | /piglatin.py | 806 | 3.921875 | 4 | import string
answer = "yes"
while answer.lower() == "yes" or answer.lower() == "y":
word = input("Word? ")
word_list = list(word)
if word[0].lower() not in ["a", "e", "i", "o", "u"]:
for i in word:
if i not in ["a", "e", "i", "o", "u"]:
word_list.append(i)
word_list.remove(i)
else:
break
pig_latin = "".join(word_list) + "ay"
pig_latin = pig_latin[0].upper() + pig_latin[1:]
#pig_latin = word[1].upper() + word[2:] + word[0].lower() + "ay"
elif word[0].lower() in ["i", "a"] and len(word) == 1:
pig_latin = word.upper() + "yay"
else:
pig_latin = word[0].upper() + word[1:] + "yay"
print(pig_latin)
answer = input("Would you like to put in another word? ")
|
2f4af82e77bdfdb5aeda452321a7c174419af2bb | jjlehner/ML_cw_dec_tree | /source/draw/label.py | 2,254 | 3.671875 | 4 | import typing
import matplotlib
import numpy
from matplotlib.textpath import TextPath
from matplotlib.path import Path
from matplotlib import patches
# Height of all labels rendered, in points
_height = 0.5
def label(axes: matplotlib.axes,
origin: typing.Tuple[int, int],
text: str,
colour: typing.List = [1, 1, 1]) -> typing.Tuple[int, int]:
""" Draw a label
This function, unlike matplotlib.text(), draws text as a rendered series
of polygon segments. This means it scales and zooms appropriately, rather
than by staying a fixed size relative to the screen.
Arguments
---------
axes: matplotlib.axes
the axes on which to draw the text
origin: typing.Tuple[int, int]
the origin about which to draw the text
text: str
the text to write
Returns
-------
size: typing.Tuple[int, int]
size of the label rendered
"""
# Generate an array of points for a given string
path = TextPath((0, 0), text, size=1)
# Evaluate the glyph's size in terms of its bottom-left and top-right
# corners
bottom_left = numpy.amin(numpy.array(path.vertices), axis=0)
top_right = numpy.amax(numpy.array(path.vertices), axis=0)
# Calculate the text's scale and size
# scale = numpy.subtract(top_right, bottom_left)
# size = [_height / numpy.prod(scale), _height]
size = [0, _height]
scale = [0, 0]
scale[0] = (top_right[0] - bottom_left[0])
scale[1] = (top_right[1] - bottom_left[1])
size[0] = size[1] / scale[1] * scale[0]
# Scale each vertex's position relative to the origin
vertices = []
for vertex in path.vertices:
# Calculate the text's scaled position
position = numpy.multiply(vertex, size)
position = numpy.divide(position, scale)
position = numpy.add(position, origin)
# Centre the text about the origin
offset = numpy.divide(size, [2, 2])
position = numpy.subtract(position, offset)
vertices.append(position)
# Create a patch from the vertex points
path = Path(numpy.array(vertices), path.codes)
patch = patches.PathPatch(path, color=colour, lw=0, zorder=10)
axes.add_patch(patch)
return size
|
714169151a858730b28f2c503f089b53fe602e41 | a1774281/UndergraduateCode | /Python/Practicals/Prac 2/prac2exe12.py | 690 | 3.578125 | 4 | #
# File: Prac2Exc12.py
# Author: Ethan Copeland
# Email Id: copey006@mymail.unisa.edu.au
# Version: 1.0 16/03/19
# Description: Practical 2, exercise 12.
# This is my own work as defined by the University's
# Academic Misconduct policy.
#
temperature = int(input("Please enter the temperature: "))
if temperature >= 40:
print("Wayyy too hot inside!")
elif temperature >= 30 and temperature < 40:
print("Hot - Beach time")
elif temperature >= 20 and temperature < 30:
print("Lovely day - how about a pinic")
elif temperature >= 10 and temperature < 20:
print("On the cold side - bring a jacket")
elif temperature < 10:
print("Way too cold - stoke up the fire")
|
e68cc580c8c3f06c0742f9de9e129cd477fcf33c | 4mayet21/COM404 | /TCA practice/Q1.py | 168 | 3.78125 | 4 | #asking question and waiting for input
print("What Happens when the last petal falls? ")
response = input()
print("My dear Bella when the last petal falls " + response) |
bc0e52f8c19254ae51d68bc18228ad18cb1f4665 | cwlseu/Algorithm | /leetcode/sumoftwointeger.py | 420 | 3.78125 | 4 | #!encode=utf-8
"""Note:
the computer save negative number using code
"""
def getSum(a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MIN_INT = 0x80000000
MASK = 0x100000000
while b:
a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK
#print (a % MIN_INT) ^ MAX_INT
return a if a <= MAX_INT else ~((a % MIN_INT) ^ MAX_INT)
print getSum(-1, -9)
print getSum(3, -5)
print getSum(3, 4)
|
2400fd9095510118252f87557f3aad4912df5ba1 | sviridchik/prep_for_isp | /isp/14.py | 727 | 3.8125 | 4 | class Singleton():
data = {}
def __new__(cls, *args, **kwargs):
name = cls.__name__
if name not in Singleton.data:
l = object.__new__(cls)
res = [args, kwargs, l]
Singleton.data[name] = res
return Singleton.data[name][-1]
class Person(Singleton):
# def __new__(cls, *args, **kwargs):
# return super(Person, cls).__new__(cls)
def __init__(self, age, name):
self.name = name
self.age = age
inst1 = Person(12, "TOM")
print(inst1.age)
inst1.age *= 2
print(inst1.age)
inst2 = Person(12, "TOM")
print(inst1 is inst2)
print(inst2.age)
inst2.age *= 2
print(inst2.age)
inst3 = Person(22, "TOM")
print(inst3.age)
print(inst2 is inst3) |
cea532ccff335d6bd32c407d0e9f3af938f836c1 | r3do2/LeetCode-Solutions | /cycleLinkedList.py | 440 | 3.765625 | 4 | ''' Cycle in a linked LIST
head -> NULL id LIST is empty '''
# cheacking for cycle method
def has_cycle(head):
if (head == None):
return False
else:
slow = head
fast = head.next
while (slow != fast) :
if (fast == None or fast.next == None):
return False
else:
slow = slow.next;
fast = fast.next.next;
return True
|
34d1a459d83bb9eb06dd2341aba3ce057351298e | FcoAndre/DI_Bootcamp | /Week7/Day2/Exercise/Exercise.py | 1,464 | 4.25 | 4 | # # Exercise 1 : What Are You Learning ?
# def display_message():
# return('I am learning python! =)')
# display_message()
# # Exercise 2: What’s Your Favorite Book ?
# def favorite_book(title) :
# print (f"One of my favorite books is {title}”.")
# favorite_book("title")
# # Exercise 3 : Some Geography
# def describe_city(city,country="Iceland") :
# print (f"{city} is in {country}”.")
# describe_city("London","UK")
# describe_city("Reykjavik",)
# describe_city("Rio","Brasil")
# # Exercise 4 : Random
# import random
# def comparacao(numero):
# n = random.randint(1,100)
# if numero == n:
# print("You chose the same number")
# else:
# print (f"You chose a different number. The random number is {n} and you typed {numero}")
# comparacao(3)
# # Exercise 5 : Let’s Create Some Personalized Shirts !
# def make_shirt(size,text):
# print (f"You chose a shirt size {size} and - {text} - is gonna be printed on it")
# make_shirt("M","hey you")
# make_shirt(text="Drag Race",size="L")
# # Exercise 6 : Magicians …
# magicians = ["Mister M", "David Copperfield", "Ru Paul"]
# def show_magicians(magics):
# for magic in magics:
# print (magic)
# # show_magicians(magicians)
# def make_great(magics):
# for magic in magics:
# magic = magic + " the great"
# print(magic)
# make_great(magicians)
# show_magicians(magicians) |
f13add4fcfa747dce7c79f528ab5ff0b80af15b7 | MothishMC/Python | /OOPs/Class_instances.py | 2,050 | 4.25 | 4 | # class --> blueprint
# Object --> instance
# class data --> Attributes
# class function --> methods
class Employee:
'''
When we Create a method inside a Class ,by default ,it takes the instance as its first argument
'''
# Initialize -Similar to constructor
def __init__(self, first, last, pay):
# By convention ,we use self (can be any name) for instance
# Unlike Java , eventhough we use different name for attributes we have to use self.attribute
self.fname = first
#[ self is not like this reference in JAVA]
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.fname, self.last)
'''
if we not pass self to the method
def fullname(self):
return '{} {}'.format(self.fname, self.last)
Code : instance.fullname()
Output : TypeError: fullname() takes 0 positional arguments but 1 was given
Reason : while calling a method , the method takes the calling instance as it's first argument
'''
emp1 = Employee('Mothish', 'MC', 50000)
print(emp1.fname)
print(emp1.email)
Name = emp1.fullname() # to differentiate b/w attribute and method we should use ()
# if we forget to put () , this method will return only the methid not the values
print(emp1.fullname)
print(Name)
# we can also this way to call the method of class
Name1 = Employee.fullname(emp1)
''' note the above method of calling a method compulsory requires 1 argument (the instance)
without that ,it is meaning less & again throws an error
TypeError: fullname() missing 1 required positional argument: 'self' .
thar's why we have 'self' as parameter in the methods
'''
print(Name1)
'''
Explaination for this TypeError: fullname() takes 0 positional arguments but 1 was given :
When we call a method for emp1 says emp1.fullname() it will get transform to Employee.fullname(emp1) in background
'''
|
85e5c239aec663a3f870dbb9cff4df14181bedaa | lipingx/python_code_snippets | /logging_advanced/util.py | 661 | 3.515625 | 4 | import logging
def SetLogConfig(log_file_name):
# The log file will be in the current directory where you run this main file.
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s,%(levelname)-6s [%(filename)s:%(lineno)d] %(message)s',
filename=log_file_name,
)
# Set up logging to console besides store to log file.
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# Set a format which is simpler for console use
formatter = logging.Formatter(
'%(asctime)s,%(levelname)-6s [%(filename)s:%(lineno)d] %(message)s')
console.setFormatter(formatter)
logger = logging.getLogger('')
logger.addHandler(console)
|
9863f3802e871464a25689280d7d165654eb0e52 | visor517/GeekBrains_python | /lesson3/task5.py | 1,583 | 3.765625 | 4 | # 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться
# сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь
# введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный символ,
# выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно добавить
# сумму этих чисел к полученной ранее сумме и после этого завершить программу.
result = 0
def adder(arr):
global result
for item in arr:
try:
if item != 'q':
item = float(item)
result = result + item
else:
return True
except ValueError:
pass
return False
while True:
string = input('Введите строку чисел, разделенных пробелом. Или q для выхода: ')
arr = string.split(' ')
if adder(arr):
break
print(f'Промежуточный результат: {result}')
print(f'Итоговая сумма {result}')
|
4a26a686aeac3333fa58088898c39fed9096d6bf | moqi112358/leetcode | /solutions/0387-first-unique-character-in-a-string/first-unique-character-in-a-string.py | 532 | 3.71875 | 4 | # Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
#
# Examples:
#
#
# s = "leetcode"
# return 0.
#
# s = "loveleetcode"
# return 2.
#
#
#
#
# Note: You may assume the string contains only lowercase English letters.
#
class Solution:
def firstUniqChar(self, s: str) -> int:
h = {}
for i in s:
h[i] = h.get(i, 0) + 1
for i in range(len(s)):
if h[s[i]] == 1:
return i
return -1
|
c9d93620c58543d1b489fb39838502681801382d | Mat4wrk/Data-Types-for-Data-Science-in-Python-Datacamp | /5.Answering Data Science Questions/Find the Months with the Highest Number of Crimes.py | 546 | 4.03125 | 4 | # Import necessary modules
from collections import Counter
from datetime import datetime
# Create a Counter Object: crimes_by_month
crimes_by_month = Counter()
# Loop over the crime_data list
for row in crime_data:
# Convert the first element of each item into a Python Datetime Object
date = datetime.strptime(row[0], '%m/%d/%Y %I:%M:%S %p')
# Increment the counter for the month of the row by one
crimes_by_month[date.month] += 1
# Print the 3 most common months for crime
print(crimes_by_month.most_common(3))
|
6043c42ea5c9922a655c443d8ca84b7792ff3c42 | farstas/Les1_Reposit | /funk.py | 317 | 3.90625 | 4 |
def get_summ(one, two, delimeter=' '):
return str(one) + str(delimeter) + str(two)
one=input('Введите аргумент 1: ')
two=input('Введите аргумент 2: ')
delimeter=input('При необходимости введите аргумент 3: ')
print(get_summ(one, two, delimeter).upper()) |
47c8022c2b4ff08d56e1e7c875303f5576ebdc77 | philippe-lemaire/katas | /inverse-slicer.py | 1,085 | 4.25 | 4 | '''
You're familiar with list slicing in Python and know, for example, that:
>>> ages = [12, 14, 63, 72, 55, 24]
>>> ages[2:4]
[63, 72]
>>> ages[2:]
[63, 72, 55, 24]
>>> ages[:3]
[12, 14, 63]
write a function inverse_slice() that takes three arguments: a list items, an integer a and an integer b. The function should return a new list with the slice specified by items[a:b] excluded. For example:
>>>inverse_slice([12, 14, 63, 72, 55, 24], 2, 4)
[12, 14, 55, 24]
The input will always be a valid list, a and b will always be different integers equal to or greater than zero, but they may be zero or be larger than the length of the list.
'''
import codewars_test as test
def inverse_slice(items, a, b):
return items[:a] + items[b:]
test.assert_equals(inverse_slice([12, 14, 63, 72, 55, 24], 2, 4), [12, 14, 55, 24])
test.assert_equals(inverse_slice([12, 14, 63, 72, 55, 24], 0, 3), [72, 55, 24])
test.assert_equals(inverse_slice(['Intuition', 'is', 'a', 'poor', 'guide', 'when', 'facing', 'probabilistic', 'evidence'], 5, 13), ['Intuition', 'is', 'a', 'poor', 'guide']) |
ad44ffb660be83a772157defd1821c2fc9e16dd8 | KaranKendre11/cloudcounselage_intern | /CloudConselage/SOLN/problem8.py | 131 | 3.765625 | 4 | def sum_series(n):
s = n;
for i in range(2,n,2):
s += (n - i)
return s;
n = int(input())
print(sum_series(n))
|
c1be1093da2d83bfbbf554dee3b2841987667e2e | santiagocantu98/Multivariate-Linear-Regression | /artificial.py | 9,338 | 4.03125 | 4 | import numpy as np
import math
import pandas as pd
import time
"""
This Python script was done for the second practical exam of
Artificial Intelligence class, the exam consists of
creating functions in order to train the algorithmn
so it can find the optimal w0 and w1 of the data set
Author: Santiago Cantu
email: santiago.cantu@udem.edu
Institution: Universidad de Monterrey
First created: March 29, 2020
"""
def store_data(url,data):
"""
function that reads a csv file from a github url
and then stores it into x and y data for training
and testing
Inputs
:param url = string type
:param data = string type
Output
:return x: numpy matrix
:return y: numpy array
:return mean: numpy array
:return sd: numpy array
:return w: numpy array
"""
if(data == "training"):
# load data from an url
training_data = pd.read_csv(url)
#amount of samples and features
numberSamples, numberFeatures = training_data.shape
# remove headers from features and separates data in x and y
x = pd.DataFrame.to_numpy(training_data.iloc[:,0:numberFeatures-1])
y = pd.DataFrame.to_numpy(training_data.iloc[:,-1]).reshape(numberSamples,1)
# prints training data
print_data(training_data,"training")
# array for means of every feature
mean = []
# array for standard deviation of every feature
sd = []
# scale features so when returned, the data is already scalated stores x,mean and sd
x,mean,sd = scale_features(x,mean,sd,"training")
# prints scaled training data
print_scaled_data(x,"training")
# adds ones and transpose the matrix in order to multiply it by w
x = np.hstack((np.ones((numberSamples,1)),x)).T
# initializes an array with 0,0 for every feature
w = initialize_w(x,numberFeatures)
return x,y,mean,sd,w
if(data == "testing"):
#load data from an url
testing_data = pd.read_csv(url)
#amount of samples and features
numberSamples, numberFeatures = testing_data.shape
# remove headers from features and stores data x
x = pd.DataFrame.to_numpy(testing_data.iloc[:,0:numberFeatures])
# prints testing data
print_data(testing_data,"testing")
return x
def scale_features(x,mean,sd,data):
"""
function that scalates the x features from the
training data and testing data with the mean and
standard deviation
Input
:param x: numpy matrix
:param mean: numpy array
:param sd: numpy array
:param data: string type
Output
:return x: numpy matrix with scalated values
:return mean: numpy array of mean
:return sd: numpy array of standard deviation
"""
if(data == "training"):
# scalates data
for size in range(x.shape[1]):
x_data = x[:,size]
m_data = np.mean(x_data)
sd_data = np.std(x_data)
mean.append(m_data)
sd.append(sd_data)
x[:,size] = (x_data - m_data)/ sd_data
return x,mean,sd
if(data == "testing"):
#scalates testing data and prints it
x = (x-mean)/sd
print_scaled_data(x,"testing")
return x
def initialize_w(x,numberFeatures):
"""
function that initialized an array with 0,0
values for each of the features
Input
:param x: numpy matrix
:param numberFeatures: int type
Output
:return w: numpy array fill with 0,0 for each feature
"""
# array for w0 and w1 of every feature
w=[]
# appends 0,0 for every feature
for size in range(numberFeatures):
w.append([0,0])
# converts array into numpy array
w = np.asarray(w)
return w
def gradient_descent(x,y,w,stopping_criteria,learning_rate):
"""
function that iterates to get the gradient descendent
until the l2 norm is bigger than the set stopping
criteria = 0.001
Input
:param x: numpy matrix of data
:param y: numpy array of data
:param stopping criteria: float type variable
:param learning rate: float type variable
Output
:return w: returns the w array fill with the optimal w0 and w1 for each feature
"""
# declare a big l2_norm
l2_norm = 100000
# size of features and samples
numberFeatures, numberSamples = x.shape
# declares a variable to know the numbers of iterations
iterations = 0
while l2_norm > stopping_criteria:
# calculates the cost function for w0 and w1 for every feature
cost_function = calculate_gradient_descent(x,y,w,numberSamples,numberFeatures)
# reshapes the cost function array in order to multiply by a scalar adding 1 columns
cost_function = np.reshape(cost_function,(numberFeatures,1))
# calculates the gradient descent with the w0 and w1 of every feature - the learning rate * the cost function
w = w-learning_rate*cost_function
# euclidean norm, in order to stop the algorithmn
l2_norm = calculate_l2_norm(cost_function)
# variable counting the iterations
iterations = iterations+1
return w
def calculate_gradient_descent(x,y,w,numberSamples,numberFeatures):
"""
function that calculates the hypothesis function and the
cost function
Input
:param x: numpy matrix of data
:param y: numpy array of data
:param numberSamples: int type variable of number of samples in the data
:param numberFeatures: int type variable of the number of features in the data
Output
:return cost_function: returns the cost function
"""
# transpose of y data so it can be substracted
y = y.T
# gets the hypothesis function multiplying transpose of W with X
hypothesis_function = np.matmul(w.T,x)
# gets the difference betweenthe hypothesis and y data
difference = np.subtract(hypothesis_function,y)
# transpose the difference so it can be multiplied
difference = difference.T
# gets the cost function of the x axis of the matrix
cost_function = np.sum(np.matmul(x,difference)/numberSamples, axis=1)
return cost_function
def predict_last_mile(w,x,mean,sd):
"""
function that predicts the last mile cost
with the testing data using the trained w's
Input
:param w: numpy array with the optimal w0 and w1 for each feature
:param x: numpy matrix of testing data scalated
:param mean: numpy array with the mean of training data
:param sd: numpy array with the standard deviation of training data
Output
:return the predicted value
"""
# number of samples and features
numberSamples, numberFeatures = x.shape
# adds a row of 1's
x= np.hstack((np.ones((numberSamples,1)),x)).T
print_last_mile_cost(np.matmul(w.T,x))
return np.matmul(w.T,x)
def calculate_l2_norm(cost_function):
"""
function that calculates the l2 norm with the cost function
Input
:param cost_function: float type variable
Output
:return the l2_norm calculated
"""
return np.sqrt(np.sum(np.matmul(cost_function.T,cost_function)))
def print_w(w):
"""
function to print the optimal w
input
:param w: numpy array
output
prints the optimal w for each feature
"""
c = 0
print('------------------------------------------------')
print('W parameter')
print('------------------------------------------------')
for i in zip(w):
print('w%s: %s'%(c,i[0][0]))
c = c + 1
def print_data(sample,data):
"""
function to print the training and testing data
input
:param sample: numpy matrix with data
:param data: string type variable
output
prints the testing and training data
"""
if(data == "testing"):
print('------------------------------------------------')
print('Testing data')
print('------------------------------------------------')
print(sample)
if(data == "training"):
print('------------------------------------------------')
print('Training data')
print('------------------------------------------------')
print(sample)
def print_scaled_data(scaled_data,data):
"""
function to print the training and testing data scalated
input
:param sample: numpy matrix with data
:param data: string type variable
output
prints the testing and training data scalated
"""
if(data == "testing"):
print('------------------------------------------------')
print('Testing data scaled')
print('------------------------------------------------')
print(scaled_data)
if(data == "training"):
print('------------------------------------------------')
print('Training data scaled')
print('------------------------------------------------')
print(scaled_data)
def print_last_mile_cost(last_mile_cost):
"""
function to print the predicted last mile cost
input
:param last_mile_cost: float type
output
prints the predicted last mile cost
"""
print('------------------------------------------------')
print('Last-mile cost (predicted)')
print('------------------------------------------------')
print(last_mile_cost[0])
def table():
"""
function that prints the table with the different computing time
and iterations that took the program to run with different learning
rates
"""
print("Learning rate 0.0005 0.001 0.005 0.01 0.05 0.1 0.5")
print("Computing time 4.19 2.14 0.57 0.26 0.08 541 1714")
print("Iterations 108781 54389 10875 5436 1085 0.06 0.12") |
70cba8735fb8bdca4c57e137769305000a31ded3 | Willy-C/AdventOfCode2019 | /day3/day3.py | 1,117 | 3.546875 | 4 | with open('input.txt', 'r') as f:
wires = [[(path[0], int(path[1:])) for path in wire.split(',')] for wire in f.readlines()]
def get_coords(wire) -> list:
x, y = 0, 0
coords = []
for step in wire:
for _ in range(step[1]):
if step[0] == 'U':
y += 1
elif step[0] == 'D':
y -= 1
elif step[0] == 'R':
x += 1
elif step[0] == 'L':
x -= 1
coords.append((x, y))
return coords
coords1 = get_coords(wires[0])
coords2 = get_coords(wires[1])
intersects = set(coords1).intersection(coords2)
# Shortest Manhattan distance from central point
closest_intersection = (min([abs(x) + abs(y) for x, y in intersects]))
print(f'Part 1: {closest_intersection}')
# Part 2
def find_distance_to_intersect():
steps = []
for intr in intersects:
steps1 = coords1.index(intr) + 1
steps2 = coords2.index(intr) + 1
steps.append(steps1+steps2)
return min(steps)
# Fewest combined step to intersection
print(f'Part 2: {find_distance_to_intersect()}')
|
4b9d8db6035698c814d61062da11ad338d2ddca8 | Cameron-Calpin/Code | /Python - learning/test.py | 1,234 | 3.609375 | 4 | theIndex = {}
# def addword(word, pagenumber):
# if theIndex.has_key(word):
# theIndex[word].append(pagenumber)
# else:
# theIndex[word] = [pagenumber]
def addword2(word, pagenumber):
try:
theIndex[word].append(pagenumber)
except AttributeError:
theIndex[word] = [pagenumber]
def addword3(word, pagenumber):
theIndex.setdefault(word, []).append(pagenumber)
def contWords(word):
return len(theIndex.get(word, 0))
def duplicate(key, index):
theIndex.setdefault(key, {})[index] = 1
def has_key_with_some_values(d, key):
return d.has_key(key) and d[key]
def get_values_if_any(d, key):
return d.get(key, {})
if __name__ == '__main__':
addword3("hello", 3)
addword3("hi", 5)
addword3("hello", 9)
# print contWords("hello")
# print theIndex
# duplicate("hello", 1)
# print theIndex
# print get_values_if_any(theIndex, "hello")
# print theIndex.keys()[1]
# print theIndex.get("hello", 0)
example = {}
example.setdefault('a', {})['apple'] = 1
example.setdefault('b', {})['boots'] = 1
example.setdefault('c', {})['cat'] = 1
example.setdefault('a', {})['ant'] = 1
example.setdefault('a', {})['apple'] = 1
for i in example.items():
print i
# -------------------------------------------------
|
946d59849eda610436aca175263e5f044b4de6eb | samuelrslz/cse210-tc04 | /game/thrower.py | 1,853 | 4.3125 | 4 | import random
class Thrower:
"""A code template for a person who throws a card. The responsibility of this
class of objects is to throw the card, keep track of the value, the score
and determine whether or not it can throw again.
Attributes:
card (int): An int between 1 and 13.
"""
def __init__(self):
"""Class constructor. Declares and initializes instance attributes.
Args:
self (Thrower): An instance of Thrower.
"""
self.card = random.randint(1, 13)
self.card2 = random.randint(1, 13)
self.num_throws = 0
def can_throw(self, score):
"""Determines whether or not the Thrower can throw again according to
the rules.
Args:
self (Thrower): An instance of Thrower.
Returns:
If the player still has points than they can play.
"""
return (score > 0)
def get_points(self, guess):
"""Calculates the total number of points for the current throw. Correct guess is
worth 100 points. Wrong guess is worth -75 points.
Args:
self (Thrower): An instance of Thrower.
Returns:
number: The total points for the current throw.
"""
if guess.lower() == "h" and self.card > self.card2:
return 100
elif guess.lower() == "l" and self.card < self.card2:
return 100
elif self.card2 == self.card:
return 0
else:
return -75
def throw_card(self):
"""Throws the card by randomly generating five new values.
Args:
self (Thrower): An instance of Thrower.
"""
self.card2 = self.card
self.card = random.randint(1, 13) |
35750c7861871845d9b095b4e9c1d8be0bc50471 | yossizap/UV-Bicycle | /src/infra/lib/display/graphics/text2bitmap.py | 2,241 | 3.59375 | 4 | '''
Description: Converts a given text to a BMP file
Requirements: Pillow
'''
import PIL
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
from optparse import OptionParser
PIL_GREYSCALE = "L"
DEFAULT_FONT = "arial.ttf"
DEFAULT_FONT_SIZE = 10
def points_to_pixels(points):
"""
Converts the given number of points(PIL's representation of size) to pixels
"""
return int(round(points * 1.333333))
def pixels_to_points(pixels):
"""
Converts the given number of pixels to points
"""
return int(round(pixels * 0.75))
def text_to_image(string, font_path, font_size):
"""
Convert a given string to a grey-scale image
"""
try:
font = PIL.ImageFont.truetype(font_path, font_size)
except IOError:
font = PIL.ImageFont.load_default()
print('Could not use chosen font. Using default.')
height = points_to_pixels(font.getsize(string)[1])
width = points_to_pixels(font.getsize(string)[0])
image = PIL.Image.new(PIL_GREYSCALE, (width, height), "white")
draw = PIL.ImageDraw.Draw(image)
draw.text((5, 5), string, "black", font)
c_box = PIL.ImageOps.invert(image).getbbox()
image = image.crop(c_box)
return image
def main():
parser = OptionParser()
parser.add_option("-s", "--string", dest="string", help="String to convert")
parser.add_option("-f", "--font", dest="font", help="Font name/path")
parser.add_option("-o", "--output_path", dest="output_path", help="Output path for the resulting image")
parser.add_option("-S", "--font_size", dest="size", help="The size of the font in points")
(options, args) = parser.parse_args()
if not options.string:
print "A valid string must be provided, please read --help"
return
if not options.output_path:
print "A valid output path must be provided, please read --help"
return
if options.size:
size = int(options.size)
else:
size = DEFAULT_FONT_SIZE
image = text_to_image(unicode(options.string), options.font or DEFAULT_FONT, pixels_to_points(size))
image.save(options.output_path)
if __name__ == '__main__':
main() |
a094cdfc2bf05ff2c65d8100078bdfce8549a429 | Abhijith-1997/pythonprojects | /object oriented/constructor/student.py | 401 | 3.71875 | 4 | class Student:
def __init__(self,name,rollno,course):
self.name=name
self.rollno=rollno
self.course=course
def printval(self):
print("name of student",self.name)
print("rollno",self.rollno)
print("course",self.course)
def __str__(self):
return self.name+str(self.rollno)
stud=Student("abhi",1001,"python")
stud.printval()
print(stud) |
d6e651e7a3c63bc5baeebdc20acd200dacb1eae5 | seObando19/holbertonschool-higher_level_programming | /0x02-python-import_modules/3-infinite_add.py | 259 | 3.578125 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
argv = sys.argv
size = len(argv)
acum = 0
if size == 1:
print(0)
else:
for i in range(1, size):
acum += int(argv[i])
print("{}".format(acum))
|
b7927011b27caf819fc1b43a2d4ad72051dfad12 | handsome-fish/tips-python | /element_frequency.py | 511 | 3.8125 | 4 | # 统计列表中元素的频率
# 直接调用collections中的Counter类来统计元素的数量
# 也可以自己来实现这样的统计
# 但是从简洁性来讲,还是以Counter的使用比较方便
# 方法一
from collections import Counter
lst = [2, 1, '3', 3, 3, 2, 3, 1, 5, 6]
count = Counter(lst)
print(count)
print(count[2])
print(count.most_common(2))
# 方法二
dic = {}
for i in lst:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
print(max(dic, key=lambda x:dic[x]))
|
a960381442fd4a5551709cb3e1c22c31adf932be | sudacake/War_of_Aircraft | /War_of_Aircraft/player.py | 1,697 | 3.5 | 4 | import pygame
class Player():
def __init__(self, screen, game_settings):
"""初始化玩家并设置其初始位置"""
self.screen = screen
#获取游戏设置
self.game_settings = game_settings
#加载飞船图像并获取其外接矩形
self.image = pygame.image.load('images/player.png')
self.rect = self.image.get_rect()
self.screen_rect = self.screen.get_rect()
#将每艘新飞船放在屏幕底部中央
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#移动标志
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
#储存小数
self.center = float(self.rect.centerx)
self.bottom = float(self.rect.bottom)
def update(self):
"""更新player位置"""
if self.moving_right == True and self.rect.right < self.screen_rect.right:
self.center += self.game_settings.player_speed_right
if self.moving_left == True and self.rect.left > self.screen_rect.left:
self.center -= self.game_settings.player_speed_left
if self.moving_up == True and self.rect.top > self.screen_rect.top:
self.bottom -= self.game_settings.player_speed_up
if self.moving_down == True and self.rect.bottom < self.screen_rect.bottom:
self.bottom += self.game_settings.player_speed_down
self.rect.centerx = self.center
self.rect.bottom = self.bottom
def blit_player(self):
"""在指定位置绘制player"""
self.screen.blit(self.image, self.rect)
|
9a74757c3f83a0e9caec875304e935bd71d0910c | echo9527git/haige_selenium | /test_javascript_demo.py | 1,949 | 3.6875 | 4 | '''
WebDriver有两个方法来执行JavaScript来使页面滚动:
execute_script:同步执行
execute_async_script:异步执行
'''
'''
JavaScript滚动页面及点击事件API:
1、滚动到文档中的某个坐标
window.scrollTo(x-coord,y-coord )
window.scrollTo(options)
·x-coord 是文档中的横轴坐标。
·y-coord 是文档中的纵轴坐标。
·options 是一个包含三个属性的对象:
·top 等同于 y-coord
·left 等同于 x-coord
·behavior 类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant
例子:
window.scrollTo( 0, 1000 );
// 设置滚动行为改为平滑的滚动
window.scrollTo({
top: 1000,
behavior: "smooth"
});
'''
from selenium import webdriver
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Firefox()
self.driver.get("https://www.baidu.com")
def test1(self):
self.driver.execute_script("alert('test')")
sleep(2)
self.driver.switch_to.alert.accept()
def test2(self):
js = 'return document.title'
title = self.driver.execute_script(js)
print(title)
def test3(self):
js = 'var q = document.getElementById("kw"); q.style.border = "2px solid green"'
self.driver.execute_script(js)
def test4(self):
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
sleep(2)
# js = 'window.scrollTo(0,document.body.scrollHeight)'
js = "window.scrollTo({top:document.body.scrollHeight,behavior: 'smooth'})"
self.driver.execute_script(js)
if __name__ == '__main__':
case = TestCase()
# case.test1()
# case.test2()
# case.test3()
case.test4() |
1f8a4a5306953435ae7fd52afe33b79378d2520b | fjh1997/Learn-Python | /analysis/pydata_book | 752 | 3.703125 | 4 | #!/usr/bin/python
import json
from collections import Counter
def get_count(sequence):
counts = {}
for x in sequence:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
def top_counts(count_dict, n=10):
value_key_pairs = [(count, tz) for tz, count in count_dict.items()]
value_key_pairs.sort()
return value_key_pairs[-n:]
if __name__ == '__main__':
path = '/home/hiro/Documents/pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
timezones = [rec['tz'] for rec in records if 'tz' in rec]
# counts = get_count(timezones)
counts = Counter(timezones)
print(counts.most_common(10))
|
fef22469e1d323fce3db7e05a05e3a23632c6545 | a8346517/ML100days | /homework/Day9.py | 1,124 | 4.09375 | 4 | #HW1 請建立類似提供結果的 DataFrame
# Apples Bananas
# 0 30 21
import pandas as pd
df = pd.DataFrame({'Apples': [30] ,
'Bananas' : [21] })
print(df)
# Apples Bananas
# 2017 Sales 35 21
# 2018 Sales 41 34
df = pd.DataFrame({'Apples': [35,41] ,
'Bananas' : [21,34] },index=['2017 Sales','2018 Sales'])
print(df)
# HW2 請問如果現在有一個 DataFrame 如下,請問資料在 Python 中可能長怎樣?
# city visitor weekday
# 0 Austin 139 Sun
# 1 Dallas 237 Sun
# 2 Austin 326 Mon
# 3 Dallas 456 Mon
df1 = pd.DataFrame({'city':['Austin','Dallas','Austin','Dallas'],
'visitor':[139,237,326,456],
'weekday':['Sun','Sun','Mon','Mon']
})
print(df1)
df2 = pd.DataFrame([['Austin',139,'Sun'],['Dallas',237,'Sun'],['Austin',326,'Mon'],['Dallas',456,'Mon']],
columns=['city','visitor','weekday'])
print(df2)
print(df1[df1.weekday=='Sun']['visitor'].mean())
Mon=df2['weekday']=='Mon'
print(df2['visitor'][Mon].mean())
|
8cf717197f2401ad4e314f85b1d57ffe8b28d336 | CODE-Lab-IASTATE/MDO_course | /04_programming_with_scipy/newton_conjugate_gradient.py | 1,066 | 3.875 | 4 | #Tutorials for optimization in python
#2D
#Newton Conjugate gradient
#This is a modified Newton algorithm that uses the CG algorithm to approx invert the local hessian
#Requires both the gradient and hessian information
#Import libraries
from scipy import optimize
import numpy as np
#Objective function
def f(x): # The rosenbrock function
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
#Gradient of objective function
def jacobian(x):
return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
#Hessian of objective function
def hessian(x): # Computed with sympy
return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
#Run the optimizer
result = optimize.minimize(f, [2, -1], method="Newton-CG", jac=jacobian, hess=hessian)
#check if the solver was successful
result.success
#return the minimum
x_min = result.x
print("True minimum:",[1,1])
print("Minimum found by the optimizer:",x_min)
print("Value of the objective function at the minimum:",f([1,1]))
print("Minimum objective function value found:",f(x_min)) |
51e9fd840a7ca2bc35347597cf6a5ea572d7aa78 | Gendo90/HackerRank | /Strings/matchingStrings.py | 816 | 3.625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the matchingStrings function below.
# NOTE: Not optimized, could probably run faster if each string is placed
# in a hash map and counted, and then see which queries match strings in the
# hash map for O(n) running time, but O(n) space complexity, too
def matchingStrings(strings, queries):
output = []
for item in queries:
total_num = strings.count(item)
output.append(total_num)
return output
# if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
#
# strings_count = int(input())
#
# strings = []
#
# for _ in range(strings_count):
# strings_item = input()
# strings.append(strings_item)
#
# queries_count = int(input())
#
# queries = []
|
47ae3be952025c5473fad5229ef23c5cb2423d75 | Vigyrious/python_fundamentals | /Dictionaries-Lab/Odd-Occurrences.py | 257 | 3.609375 | 4 | elements = input().split(" ")
diction = {}
for word in elements:
lower = word.lower()
if lower not in diction:
diction[lower] = 0
diction[lower] += 1
for (key, value) in diction.items():
if value % 2 != 0:
print(key, end=" ") |
dcf083614a98c7b49d8914eba9c9491179900315 | daveh19/foxy-predictor | /Python_Gui/examples/ex_buttons_frames.py | 838 | 4.125 | 4 | from tkinter import *
root = Tk()
#myLabel = Label(root, text = 'text and stuff')
#myLabel.pack()
#upper half of window
topFrame = Frame(root)
topFrame.pack()
#lower half of window
bottomFrame = Frame(root)
bottomFrame.pack(side = BOTTOM)
#create buttons in topFrame
button1 = Button(topFrame, text = 'Button1', fg = 'red', bg = 'blue')
button2 = Button(topFrame, text = 'Button2', fg = 'blue')
button3 = Button(topFrame, text = 'Button3', fg = 'green')
#create button in bottomFrame
button4 = Button(bottomFrame, text = 'Button4', fg = 'purple')
#by default pack() stacks stuff on top of each other!!
button1.pack(side = LEFT) # places the buttons on the leftmost position --> they will lie next to each other
button2.pack(side = LEFT)
button3.pack(side = LEFT)
button4.pack(side = BOTTOM) #not really necessary
root.mainloop()
|
3a0d5a79d3e80f57c2d9f953e6cf0e35aded4853 | ksreddy1980/test | /General/Fibnoic.py | 397 | 4.15625 | 4 |
n = int(input("enter the value:"))
if(n <=0):
n = int(input("enter the value that greater than Zero:"))
def fib(n):
first = 1
second = 1
if(n <=2):
return 1
else:
for i in range(n-2):
current = first + second
first = second
second = current
return current
print("{0} Fibnoic number is {1}".format(n , fib(n)))
|
fa3fc58ba206c45902da1766b2d024aea87636a4 | detel/Miscellaneous | /Mind == Blown.py | 338 | 3.53125 | 4 | """ Raghav Passi(@grebnesieh)'s solution """
def move(A, B, C):
#print "A = %s B = %s C = %s"%(A,B,C)
if not A and not B:
if C == S:
count[0] += 1
distinct.add(C)
else:
if A:
move(A[1:], B + A[0], C)
if B:
move(A, B[:-1], C + B[-1])
S, distinct, count = raw_input(), set(),[0]
move(S, "", "")
print count[0], len(distinct)
|
f1621328203f355f6ba236bd40e53e73a32931e6 | FriendedCarrot4z/Final-Project-CSE-212 | /QueueMusicProblem.py | 2,908 | 3.515625 | 4 | import pygame
from pygame import mixer
pygame.mixer.init()
class Priority_Queue:
class Node:
def __init__(self, song, priority):
self.song = song
self.priority = priority
def __str__(self):
return "{} {}".format(self.song, self.priority)
def __init__(self):
self.queue = []
def enqueue(self, song, priority):
new_node = Priority_Queue.Node(song, priority)
self.queue.append(new_node)
def dequeue(self):
"""
In here create the base case for the dequeue and how to return and remove
a song in the queue after it plays
"""
pass
# Find the index of the item with the highest priority to remove
high_pri_index = 0
for index in range(0, len(self.queue)):
if self.queue[index].priority < self.queue[high_pri_index].priority:
high_pri_index = index
# Remove and return the item with the highest priority
pass
def __len__(self):
return len(self.queue)
def __str__(self):
"""
Here you will add the code to make place the songs in the queue into a string
"""
pass
def Play(self):
true = True
song = self.dequeue()
pygame.mixer.music.load(song)
pygame.mixer.music.play(0)
print(song)
print("If the song ends, press any key to jump to the next song")
while true:
Input = input("p to pause music, u to resume music, r to restart music, e to exit out ")
#use keyboard commands instead of inputs
while pygame.mixer.music.get_busy() == False:
if len(self.queue) == 0:
true = False
song = self.dequeue()
pygame.mixer.music.load(song)
pygame.mixer.music.play(0)
print(song)
if Input == "p":
pygame.mixer.music.pause()
if Input == "u":
pygame.mixer.music.unpause()
if Input == "r":
pygame.mixer.music.rewind()
pygame.mixer.music.play(0)
print("rewind")
if Input == "e":
true = False
priority = Priority_Queue()
priority.enqueue("Silent Night.wav", 1)
priority.enqueue("What Child Is This.wav", 2)
priority.enqueue("Did you Think to Pray.wav", 3)
priority.enqueue("His Hands.wav", 4)
priority.enqueue("Im Trying to Be like Jesus.wav", 5)
priority.enqueue("Israel Israel God Is Calling.wav", 6)
priority.enqueue("Lord I Would Follow Thee.wav", 7)
priority.enqueue("Nearer My God to Thee.wav", 8)
priority.enqueue("O Come All Ye Faithful.wav", 9)
priority.enqueue("O Come Emmanuel - Christmas Version - ThePianoGuys.wav", 10)
priority.Play()
|
66635f92a5357ddc553795796026d7cc56186921 | jinurajan/Datastructures | /LeetCode/mock_interviews/next_permutation.py | 1,365 | 4.1875 | 4 | """
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
"""
from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = n - 2
def reverse(nums, start):
i = start
j = n - 1
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
while i >= 0 and nums[i + 1] <= nums[i]:
i -= 1
if i >= 0:
j = len(nums) - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
reverse(nums, i + 1)
nums = [1,2,3]
print(Solution().nextPermutation(nums))
nums = [3,2,1]
print(Solution().nextPermutation(nums))
|
f47492080834d35eb46a797c3dbca6d770b4fc41 | AmritaDeb/Automation_Repo | /PythonBasics/py_programas/Generic/printList.py | 54 | 3.59375 | 4 | n=[1,2,3,4,5]
A=[i for i in range(1,6)]
print(list(A)) |
58173560c190f8c317f2e0211f22ce41eb849767 | lubyliao/cs305 | /HTMLgen/htmlgen.py | 5,789 | 3.546875 | 4 | """
Factor generic code from subclasses such as Href, Table, etc into a superclass
to achieves code reuse and avoid code duplication.
"""
class HTMLElement:
def __init__(self, **kw):
for attr in kw:
try:
getattr(self, attr)
setattr(self, attr, kw[attr])
except:
raise KeyError("Unsupported argument %s!" % attr)
class Table(HTMLElement):
""" Ported from Robin F's Table class in HTMLgen.py. Keep all his
Table attributes. Minimally rewrite __str__ to make it work with
Python 3. How does the __init__ code differ from Robin's code?
"""
caption_align = 'top'
border = 2
cell_padding = 4
cell_spacing = 1
width = '100%'
heading = None
heading_align = 'center'
heading_valign = 'middle'
body = [[' ']*3]
column1_align = 'left'
cell_align = 'left'
cell_line_breaks = 1
colspan = None
body_color= None
heading_color=None
def __init__(self, tabletitle='', **kw):
self.tabletitle = tabletitle
HTMLElement.__init__(self, **kw)
def __str__(self):
"""Generates the html for the entire table.
"""
if self.tabletitle:
s = ["<a name='%s'>%s</a><P>" % (self.tabletitle, self.tabletitle)]
else:
s = []
s.append('<TABLE border=%s cellpadding=%s cellspacing=%s width="%s">\n' % \
(self.border, self.cell_padding, self.cell_spacing, self.width))
if self.tabletitle:
s.append('<CAPTION align=%s><STRONG>%s</STRONG></CAPTION>\n' % \
(self.caption_align, self.tabletitle))
for i in range(len(self.body)):
for j in range(len(self.body[i])):
if type(self.body[i][j]) == type(''):
#process cell contents to insert breaks for \n char.
if self.cell_line_breaks:
self.body[i][j] = self.body[i][j].replace('\n','<br>')
else:
self.body[i][j] = Text(self.body[i][j])
# Initialize colspan property to 1 for each
# heading column if user doesn't provide it.
if self.heading:
if not self.colspan:
if type(self.heading[0]) == list:
self.colspan = [1]*len(self.heading[0])
else:
self.colspan = [1]*len(self.heading)
# Construct heading spec
# can handle multi-row headings. colspan is a list specifying how many
# columns the i-th element should span. Spanning only applies to the first
# or only heading line.
if self.heading:
prefix = '<TR Align=' + self.heading_align + '> '
postfix = '</TR>\n'
middle = ''
if type(self.heading[0]) == type([]):
for i in range(len(self.heading[0])):
middle = middle + '<TH ColSpan=%s%s>' % \
(self.colspan[i], \
self.get_body_color(self.heading_color,i)) \
+ str(self.heading[0][i]) +'</TH>'
s.append(prefix + middle + postfix)
for i in range(len(self.heading[1])):
middle = middle + '<TH>' + str(self.heading[i]) +'</TH>'
for heading_row in self.heading[1:]:
for i in range(len(self.heading[1])):
middle = middle + '<TH>' + heading_row[i] +'</TH>'
s.append(prefix + middle + postfix)
else:
for i in range(len(self.heading)):
middle = middle + '<TH ColSpan=%s%s>' % \
(self.colspan[i], \
self.get_body_color(self.heading_color,i)) \
+ str(self.heading[i]) +'</TH>'
s.append(prefix + middle + postfix)
# construct the rows themselves
stmp = '<TD Align=%s %s>'
for row in self.body:
s.append('<TR>')
for i in range(len(row)):
if i == 0 :
ss1 = self.column1_align
else:
ss1 = self.cell_align
s.append(stmp % (ss1, self.get_body_color(self.body_color,i)))
s.append(str(row[i]))
s.append('</TD>\n')
s.append('</TR>\n')
#close table
s.append('</TABLE><P>\n')
return ''.join(s)
def get_body_color(self, colors, i):
"""Return bgcolor argument for column number i
"""
if colors is not None:
try:
index = i % len(colors)
return ' bgcolor="%s"' % colors[index]
except:
pass
return ''
class Href(HTMLElement):
target = None
onClick = None
onMouseOver = None
onMouseOut = None
def __init__(self,
url='',
text='',
**kw):
self.url = url
self.text = text
HTMLElement.__init__(self, **kw)
def __str__(self):
s = ['<A HREF="%s"' % self.url]
if self.target: s.append(' TARGET="%s"' % self.target)
if self.onClick: s.append(' onClick="%s"' % self.onClick)
if self.onMouseOver: s.append(' onMouseOver="%s"' % self.onMouseOver)
if self.onMouseOut: s.append(' onMouseOut="%s"' % self.onMouseOut)
s.append('>%s</A>' % self.text)
return ''.join(s)
usd = Href(text='USD', url='http://www.sandiego.edu', target='_blank')
print(usd)
t = Table('Table')
t.heading = ['One', 'Two', 'Three']
t.body = [[1,2,3], [4,5,6]]
print ( t )
print(vars(t))
|
9536eae63d56d960f43e8ef6c8386883a4e9cf08 | cmu-db/noisepage | /script/self_driving/modeling/data/data_util.py | 592 | 3.921875 | 4 | def convert_string_to_numeric(value):
"""Break up a string that contains ";" to a list of values
:param value: the raw string
:return: a list of int/float values
"""
if ';' in value:
return list(map(convert_string_to_numeric, value.split(';')))
try:
return int(value)
finally:
return float(value)
def round_to_interval(time, interval):
""" Round a timestamp based on interval
:param time: in us
:param interval: in us
:return: time in us rounded to the closest interval ahead
"""
return time - time % interval
|
2efaaf8f615e333f67526fb3a04f8a7a66e921b4 | alrahmanak/python_bgn | /matplot1.py | 120 | 3.5625 | 4 | import matplotlib.pyplot as plt
# matplot lib Pyplot tutorial
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show() |
d7e350f56360448abe18b02748b00f0c40cf4d20 | 17602515236/Python_exercise | /test.py | 1,021 | 3.765625 | 4 | """
name2 = ['old_driver', 'rain_jack', ['old_boy', 'old_girl'], 'shanshan', 'peiqi', 'alex', 'black_girl', 1, 2, 3, 4, 2, 5, 6, 2]
print(name2)
index_2 = name2.index(2)
print(index_2)
index_22 = name2.index(2,index_2 + 1)
print(index_22)
for i in name2:
n = name2.index(i)
if n%2 == 0:
name2[n]=-1
print(n,name2[n])
"""
products = [['iphne8',6888],['MacPro',14800],['xiaomi8',2499],['Coffee',31],['Book',80],['Nike Shoes',799]]
products_car=[]
def show_product():
for i,v in enumerate(products):
print(i,'.',v[0],'\t',v[1])
def get_user_product():
u_in = input("Please input the product you want with number>>>")
if u_in.isdigit():
u_in = int(u_in)
if u_in >= len(products):
print("No products")
else:
products_car.append(products[u_in])
if u_in == 'q':
for i in products_car:
print(i)
exit()
else:
print("Error command!")
#start:
while True:
show_product()
get_user_product()
|
0a2d8675e5241667bbb9c7c60713c4cff61551a9 | ZaatarX/time-calculator | /time_calculator.py | 2,686 | 3.8125 | 4 | def add_time(start, duration, day=None):
hours = []
minutes = []
if day:
day = str(day)
weekdays = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
for key, value in weekdays.items():
if value == day.capitalize():
day = key
break
else:
day = ''
# breaking down the string into usable data
# extracting if am or pm
start = start.split()
dn = str(start[1])
if dn == 'AM':
flag = 0
else:
flag = 1
# extracting hours and minutes from start time
start = start[0].split(':')
hours.append(int(start[0]))
minutes.append(int(start[1]))
# extracting hours and minutes from duration time
duration = duration.split(':')
hours.append(int(duration[0]))
minutes.append(int(duration[1]))
# normalizing minutes and adding an hour if necessary
if minutes[0] + minutes[1] >= 60:
hours[1] += 1
minutes[0] = str((minutes[0] + minutes[1]) - 60)
else:
minutes[0] += minutes[1]
if int(minutes[0]) < 10:
temp = str(minutes[0])
minutes[0] = '0' + temp
# adding to get total hours and calculate passage of time
hours.append(hours[0] + hours[1])
shift = 0
# to each loop a shift is added meaning it went from AM to PM and vice-versa
while hours[2] >= 12:
hours[2] -= 12
shift += 1
if flag == 0:
flag = 1
else:
flag = 0
# time to build the string
if hours[2] == 0:
hours[2] = 12
hour = str(hours[2])
minute = str(minutes[0])
if flag == 0:
dn = 'AM'
else:
dn = 'PM'
# no shift difference
if shift == 0 or (shift == 1 and flag == 1):
if day != '':
day = f', {weekdays[day]}'
return f'{hour}:{minute} {dn}{day}'
# next day shifts
elif shift <= 2:
if day != '':
if day >= 6:
day %= 6
day = f', {weekdays[day]}'
else:
day = f', {weekdays[day]}'
return f'{hour}:{minute} {dn}{day} (next day)'
later = round(hours[1] / 24) + 1
if day != '':
day += later
if day > 6:
day %= 7
day = f', {weekdays[day]}'
else:
day = f', {weekdays[day]}'
if flag + (round(shift / 2) + 1) % 2 == 0:
return f'{hour}:{minute} PM{day} ({later} days later)'
else:
return f'{hour}:{minute} AM{day} ({later} days later)'
|
1b16e1a96de8c7b648c53a4981c71c3e0eceb3c5 | kettu-metsanen/python_course | /kierros4/2.py | 1,173 | 3.8125 | 4 | """
COMP.CS.100 Ensimmäinen Python-ohjelma.
Tekijä: Anna Rumiantseva
Opiskelijanumero: 050309159
"""
import math
def tarkista(yht, on):
"""tarkista onko mollemmat positivinen ja onko lottopallojen kokonaismäärä
isompi entä arvottavien pallojen määrän"""
if on > yht or on < 0 or yht < 0:
return False
else:
return True
def podschet(yht, on):
"""lsku faktorial ja antaa vastaus"""
if tarkista(yht, on) == True:
fact = (math.factorial(yht)) / (math.factorial(yht - on) * math.factorial(on))
return fact
elif tarkista(yht, on) == False:
return 0
def main():
vsego = int(input("Enter the total number of lottery balls: "))
nujno = int(input("Enter the number of the drawn balls: "))
vast = podschet(vsego, nujno)
if vast == 0:
if nujno < 0 or vsego < 0:
print("The number of balls must be a positive number.")
elif nujno > vsego:
print("At most the total number of balls can be drawn.")
elif vast > 0:
print(f"The probability of guessing all {nujno} balls correctly is 1/{vast:.0f}")
if __name__ == "__main__":
main() |
c5aaa218c5fb897e2bad6d80b7a24a97b7973e7a | jgarte/aoc-2 | /aoc/year_2020/day_08/accumulate.py | 585 | 3.546875 | 4 | from typing import List, Set, Tuple
from .parse import Cmd
Result = Tuple[int, int]
def loop_accumulate(commands: List[Cmd], idx_set: Set[int], values: Result) -> Result:
"""Accummulate values while iterating/jumping through commands"""
idx, acc = values
if idx in idx_set:
return idx, acc
idx_set.add(idx)
try:
cmd, val = commands[idx]
idx += 1 if cmd in ("nop", "acc") else val
acc += val if cmd == "acc" else 0
return loop_accumulate(commands, idx_set, values=(idx, acc))
except IndexError:
return idx, acc
|
7e3649f19a94bbc4a2de984f5bd20655e1b1d505 | catalystfrank/LeetCode10Py | /[OPEN--]LEET0214_SHORTEST_PALINDROME.py | 370 | 4.125 | 4 | #coding=utf-8
'''
Given a string S, you are allowed to convert it to a palindrome by adding
characters in front of it. Find and return the shortest.
'''
def shortestPalindrom(s):
n = len(s)
l, r = int(n/2), int((n+1)/2)
while l > 0:
if s[:l] == s[r+l-1: r-1: -1]: break
elif l == r: l -= 1
else : r -= 1
left_pal = s[n-1: l+r -1 : -1]
return left_pal + s
|
6316f3926bf976630c877384afc7eda94c11ac57 | zhaolanqi/C.C | /作业/04.py | 130 | 3.625 | 4 | i = '亚瑟'
u = input('请输入英雄')
if u == i:
print('%s是死亡骑士'%i)
else:
print('我不知道什么意思')
|
c3c7459ef1989a5ae114ce45aeecf17cff44ba04 | YilK/Notes | /Python-Crash-Course/第一部分 基础知识/第04章 操作列表/4-04 一百万.py | 276 | 3.65625 | 4 | '''
创建一个列表,其中包含数字1~1 000 000,再使用一个for 循环将这些数字打印出来
(如果输出的时间太长,按Ctrl + C停止输出,或关闭输出窗口)。
'''
numbers = list(range(1, 1000001))
for number in numbers:
print(number)
|
9287be3b87f10caddcbe58bbf686d2a72542a541 | stefanyl/python-challenge | /PyBank/main.py | 2,411 | 3.84375 | 4 | #Import the os module
import os
#Import module for reading in CSV file and set path.
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
#Set variables for Financial Analysis
total_months = []
total_profit = []
profit_change = []
#Read in the CSV and store the header row.
with open(csvpath, newline="", encoding='utf-8-sig') as budget_data:
csvreader = csv.reader(budget_data, delimiter=',')
header = next(csvreader)
#For loop to iterate through the rows
for row in csvreader:
#Calculate the total number of months included in the dataset.
total_months.append(row[0])
#Calculate the net total amount of "Profit/Losses" over the entire period
total_profit.append(int(row[1]))
#Calculate the changes in "Profit/Losses" over the entire period.
#Iterate through profits to find average of those changes.
for i in range(len(total_profit)-1):
profit_change.append(total_profit[i+1]-total_profit[i])
#Find the greatest increase in profits over the entire period
max_increase = max(profit_change)
max_increase_period = profit_change.index(max(profit_change)) + 1
#Find the greatest decrease in profits over the entire period
max_decrease = min(profit_change)
max_decrease_period = profit_change.index(min(profit_change)) + 1
#Print statement and export text file to analysis folder
print("Financial Analysis")
print("--------------------------")
print(f"Total Months: {len(total_months)}")
print(f"Total: ${sum(total_profit)}")
print(f"Average Change: ${round(sum(profit_change)/len(profit_change),2)}")
print(f"Greatest Increase in Profits: {total_months[max_increase_period]} (${(str(max_increase))})")
print(f"Greatest Decrease in Profits: {total_months[max_decrease_period]} (${(str(max_decrease))})")
#Assemble your output string
analysis_text = (
f'Financial Analysis\n'
f'--------------------------\n'
f'Total Months: {len(total_months)}\n'
f'Total: ${sum(total_profit)}\n'
f'Average Change: ${round(sum(profit_change)/len(profit_change),2)}\n'
f'Greatest Increase in Profits: {total_months[max_increase_period]} (${(str(max_increase))}\n'
f'Greatest Decrease in Profits: {total_months[max_decrease_period]} (${(str(max_decrease))}'
)
#Write your output string to a text file
with open('analysis_text.txt', "w") as txt_file:
txt_file.write(analysis_text)
|
be3bc4ed381168508dda0629089d683dfe475672 | JackMGrundy/coding-challenges | /companies-leetcode/amazon/trees/binary-tree-maximum-path-sum.py | 1,996 | 3.828125 | 4 | """
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
"""
# 3rd attempt. 98th percentile. 88ms.
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
bestPathValue = -float("inf")
def helper(root):
nonlocal bestPathValue
if not root:
return 0
leftsBestBranch = helper(root.left)
rightsBestBranch = helper(root.right)
rootsBestBranch = max(root.val, root.val + leftsBestBranch, root.val + rightsBestBranch)
bestPathValue = max(bestPathValue, \
rootsBestBranch, \
root.val + leftsBestBranch + rightsBestBranch)
return rootsBestBranch
helper(root)
return bestPathValue
"""
Notes:
Great question. Very intuitive actually.
Any solution we pick is only allowed to branch in two different directions at most once. Therefore at each node we record the "rootsBestBranch" meaning that if
we use this root in a path, what is the best value you can get out of it? We return that from each level to the level above it.
And to actually find the answer, we simply check at each node what's the best value we can get out of making the node the root. Given that we know the best
we can get out of the left and right branches, this is easy. Its either the just the roots value, the roots value + one of the branches, or the roots value
+ both branches best values.
""" |
ea6a3e6825f84c56041527dfc286a1372f014d57 | PROxZIMA/Python-Projects | /Fibonacci Series.py | 248 | 4.125 | 4 | n = int(input('Enter how many number in Fibonacci Series you want: '))
a, b = 0, 1
print(f'Fibonacci Series is given by: ')
for i in range (1, n+1):
if i == n:
print(b)
else:
print(f'{b}, ', end='')
a, b = b, a+b |
33296949d3cf049e945ec102558d77e668e96c53 | Rudya93/Python1 | /test.py | 1,132 | 3.8125 | 4 | class Simple:
def __init__(self):
self.list = []
def f1(self):
self.list.append(123)
def f2(self):
self.f1()
s = Simple()
s.f2()
print (s.list)
q = Simple()
print(q)
# a = 'ZENOVW'
# b = sorted(a)
# print (b)
# #['E', 'N', 'O', 'V', 'W', 'Z']
# c = ''.join(b)
# print (c)
#
#
#
# import string
# #print (string.ascii_uppercase)
# for c in string.ascii_letters:
# print(c)
#
# s = 'fooУБРАТЬbarОТСЮДАbazНЕЛАТИНСКОЕ'
# s2 = ''.join(c for c in s if c in string.ascii_letters)
# print(s2)
# #chr(65)
# #'A'
# #chr(122)
# #'z'
# #print(chr(128522))
# #123
#a = []
#i=0
#for i in range(int(3)):
# b = input("input matrix 1: ")
# a.append(b)
#print (a)
#num_array[:, i]
#a = [1, 2, 3]
#print (a[: 3])
#num_array = list()
#num = input("Enter how many elements you want:")
#print 'Enter numbers in array: '
#for i in range(int(3)):
# input ("input matrix 1 line: " ) a
#num_array[:, i]
# n = input("num :")
#num_array.append(int(n))
#print 'ARRAY: ',num_array
#print(num_array) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.