blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
9201174ec5ac6d814d7e832796a6c2cc2a71619c | SenseiCain/python_crash_course | /syntax/functions.py | 1,387 | 4.0625 | 4 | # -- FUNCTIONS --
# Same indention notation as for loops
# Define a Fn with def
# Snake case
def greet(name):
print(f'Hello, {name.title()}!')
# greet('Christian')
# Positional arguments
def greet_with_sirname(name, sirname='Mr/Mrs'):
print(f'Greetings {sirname}. {name}')
# greet_with_sirname('Christian', 'Mr')
# Key Name arguments
# Position doesn't matter here
# Define on execution!!!
# greet_with_sirname(sirname='Mr', name='Christian')
# Return Value
num = 2
def square(num):
return num**2
# print(square(num))
# Optional args
# Takes advantage of Python using non-empty strings as True
def get_formatted_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = f'{first_name} {middle_name} {last_name}'
else:
full_name = f'{first_name} {last_name}'
return full_name.title()
# print(get_formatted_name('Christian', 'Cain'))
# Functions & immutable lists
# function_name(list[:])
# Passing in an arbitrary amount of args
def make_pizza(*toppings):
for topping in toppings:
print(topping)
# make_pizza('cheese')
# make_pizza('cheese', 'pepperoni', 'mushrooms')
# Keyword Args
# Use when unsure of how many key-values pairs will be passed in
# **kwargs
def build_profile(first, last, **user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
# print(build_profile('Christian', 'Cain', hometown='Richwood'))
|
a0f3ce93b1b31b4832d13c8121ccd3a30d2ed717 | vparjunmohan/Python | /Basics-Part-I/program79.py | 189 | 4.125 | 4 | 'Write a Python program to get the size of an object in bytes.'
import sys
val = input('Enter a string object ')
print("Memory size of '"+val+"' = "+str(sys.getsizeof(val))+ " bytes")
|
1ee93d08f113ef38a6fd6a016cc19195c5ecbe32 | jsimfors/the_cash_register | /puppgift.py | 10,685 | 4.34375 | 4 | class Item:
"""
Attributes:
item: what kind of item, ex banana
price: the price of the item
amount: the amount left in stock
"""
def __init__(self, item, price, amount):
"""
:param item: what kind of item, ex. banana
:param price: The price of the item
:param amount: the amount left in stock
"""
self.item = item
self.amount = int(amount)
self.price = price
def __str__(self):
"""
prints the item name of the item, ex. banana
"""
return self.item
def decrease_stock(self, units):
"""
is used to decrease the amount of a certain item.
This method runs every time we use the 'buy' method from the 'Till' class.
:param units: The amount of, ex. bananas, we want to buy/reduce from stock.
:return: The amount left in stock, or False (if there's not enough in Stock)
"""
if self.amount >= units:
self.amount -= units
return self.amount
else:
return False
def raise_stock(self, units):
"""
Used to add items to stock, runs every time we use the "return item" method in the 'Till' class.
:param units: amount of items we want to add in stock.
:return: The amount
"""
self.amount += units
return self.amount
class Till:
"""
Keeps track of the current transaction.
"""
def __init__(self):
"""
current_transaction = A receipt, key = name of the item.
price_and_amount = A list of the price and amount of the item.
used as the value in the current_transactions dictionary.
"""
self.current_transaction = {}
self.price_and_amount = []
def print_receipt(self):
"""
Adds the current_transaction dictionary to the receipt.
Deletes an item if the customer returns all the purchased units.
Is used when the customer press # = Exit
:return: A receipt, with all information including total price.
"""
all_total = 0
str_current_transactions = ""
for i in self.current_transaction:
total = self.current_transaction[i][2]
all_total += total
to_add = "{0:18}{1:0} {2:8}{3:0}\n".format(i, self.current_transaction[i][0],
self.current_transaction[i][1],
self.current_transaction[i][2])
str_current_transactions += str(to_add)
return '----------------- RECEIPT -----------------\nItem Amount A-price Total\n{}\n' \
' total: {}'.format(str_current_transactions, round(all_total, 2))
def buy(self, item, units):
"""
Used to add items to receipt, this method calls the 'decrease_stock' method
If decrease_stock returns false, it'll print 'Not enough in stock".
:param item: name of the item, ex Banana.
:param units: Amount of items the customer buys
:returns: information about what the customer bought/that it's not in stock.
"""
if Item.decrease_stock(item, units) is not False:
price = item.price
value_list = []
str_item = str(item)
if str_item in self.current_transaction:
self.current_transaction[str_item][0] += units
self.current_transaction[str_item][2] = \
round(int(self.current_transaction[str_item][0]) * float(self.current_transaction[str_item][1]), 2)
return "You bought {} {}s".format(units, str_item)
else:
cost = round((int(units) * float(price)), 2)
value_list.append(units)
value_list.append(price)
value_list.append(cost)
self.current_transaction[str_item] = value_list
return "You bought {} {}s".format(units, str_item)
else:
return "Not enough {}s in stock".format(item)
def return_item(self, item, units):
"""
Used to remove items from receipt. Calls the raise_stock in the Item class.
:param item: name of the item, ex Banana.
:param units: Amount of items the customer returns
:return: information about what the customer returned
"""
str_item = str(item)
if str_item in self.current_transaction:
if self.current_transaction[str_item][0] >= units:
self.current_transaction[str_item][0] -= units
self.current_transaction[str_item][2] = \
round(int(self.current_transaction[str_item][0]) * float(self.current_transaction[str_item][1]), 2)
Item.raise_stock(item, units)
if self.current_transaction[str_item][0] == 0:
del self.current_transaction[str_item]
return "You returned {} {}s".format(units, str_item)
else:
return "You can't return more bananas than you bought"
else:
return "You did not buy any {}s".format(item)
def get_int_input(prompt_string):
"""
checks if the input is either a # or an integer
:param prompt_string: the input the customer buys
:return: An integer or an Error message.
"""
done = False
while done is not True:
string = input(prompt_string)
if string is not "0":
try:
return int(string)
except ValueError:
print("Unable to operate your request, please print a valid number.")
done = False
else:
print("0 is not an option")
done = False
def get_int_menu_input(choice_string):
"""
needs this error-handling-function, since the menu has 1, 2, OR the '#' as an option.
But the rest of the program just want's to check if it's an integer.
:param choice_string: the input, from the customer
:return: An integer, the string '#' or an Error message.
"""
done = False
while done is not True:
choice = input(choice_string)
if choice == '#':
return '#'
else:
try:
return int(choice)
except ValueError:
print("Unable to operate your request, please print a valid option.")
done = False
def get_item_code(code, all_items):
"""
Checks if the input from the customer corresponds with an item in stock
:param code: the item code, ex 001, 002...
:param all_items dictionary with all the items
:return: The item code or Error message.
"""
done = not True
while done is not True:
if code in all_items:
return code
else:
print("Unable to operate your request, please print a valid code.")
done = False
code = input()
def read_data_from_file(in_stock_file):
"""
Used to get information about the items in Stock.
:param in_stock_file: a file with all the information
:return: all_items, a dictionary with all data on it
"""
all_items = {}
with open(in_stock_file) as f:
for line in f:
all_as_list = line.split()
all_items[all_as_list[0]] = all_as_list[1:4]
return all_items
def convert_to_object(textfile):
"""
Converts the dictionary to an object for the Till class.
:param textfile: a file with all the information
:return: Objects for the Till class.
"""
all_items_obj = read_data_from_file(textfile)
for key in all_items_obj:
all_as_list = all_items_obj[key]
all_items_obj[key] = Item(all_as_list[0], all_as_list[1], all_as_list[2])
return all_items_obj
def write_to_file(my_obj, in_stock_file):
"""
When the customer is done shopping, this function takes the new information about what's left in stock,
and updates the textfile.
:param my_obj: the object from the Till class.
:param in_stock_file: A textfile, where we rite all the information.
:return: nothing
"""
f = open(in_stock_file, "w")
for i in my_obj:
to_write = str(i) + " " + str(my_obj[i].item) + " " + str(my_obj[i].price) + " " + str(my_obj[i].amount)
f.writelines(to_write + '\n')
def menu(till, dict_items):
"""
Used to display a meny for the user. With the options:
1 - Shopping
2 - Return item
# - Exit
:return: nothing
"""
print("""
-------------------------------
Hello Banana-Customer!
What would you like to do?
1 - Shopping
2 - Return item
# - Exit""")
execute(menu_choice(), dict_items, till)
def menu_choice():
"""
Used to get input on what the customer wants to do
:return: choice = an int, the chosen menu option
"""
return get_int_menu_input('Answer: ')
def execute(choice, all_items, till):
"""
used to execute the option that the user chose, calls a specific method from the Till class
:param choice: and int corresponding to the chosen option (from menu_choice() )
:param all_items: the objects for the Till class ?? eller?
:param till: object to the till class.
:return: nothing
"""
while choice != '#':
if choice == 1:
code = input("""What do you want to buy?
Normal Banana=001
Jungle Banana=002
Dangerous-Banana=003
Poisonous-Banana=004""")
name = get_item_code(code, all_items)
name_object = all_items[name]
amount = get_int_input("How many? ")
till.buy(name_object, amount)
all_items[name] = Item(name_object.item, name_object.price, name_object.amount)
elif choice == 2:
code = input("What would you like to return?")
name = get_item_code(code, all_items)
name_object = all_items[name]
amount = get_int_input("How many? ")
till.return_item(name_object, amount)
all_items[name] = Item(name_object.item, name_object.price, name_object.amount)
else:
print("There's obviously only 2 options...")
menu(till, all_items)
else:
print(till.print_receipt())
write_to_file(all_items, 'in_stock_file.txt')
exit()
def main():
"""
To start program.
"""
my_till = Till()
my_items = convert_to_object('in_stock_file.txt')
menu(my_till, my_items)
# To start program without the GUI:
# main()
|
fe9279a9cf98f8691ab0c37e276453c299487318 | alandmoore/tkinter-basics-code-examples | /Video2/diary.py | 1,611 | 3.59375 | 4 | """My Diary Application in Tkinter"""
import tkinter as tk
# First line
root = tk.Tk()
# configure root
root.title('My Diary')
root.geometry('800x600')
root.columnconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
# subject
subject_label = tk.Label(root, text='Subject: ')
subject_label.grid(sticky='we', padx=5, pady=5)
subject_inp = tk.Entry(root)
subject_inp.grid(row=0, column=1, sticky=tk.E + tk.W)
# category
categories = ['Work', 'Hobbies', 'Health', 'Bills']
cat_label = tk.Label(root, text='Category: ')
cat_label.grid(row=1, column=0, sticky=tk.E + tk.W, padx=5, pady=5)
cat_inp = tk.Listbox(root, height=1)
cat_inp.grid(row=1, column=1, sticky=tk.E + tk.W, padx=5, pady=5)
for category in categories:
cat_inp.insert(tk.END, category)
# message
message_inp = tk.Text(root)
message_inp.grid(row=2, column=0, columnspan=2, sticky='nesw')
# save button
save_btn = tk.Button(root, text='Save')
save_btn.grid(row=99, column=1, sticky=tk.E, ipadx=5, ipady=5)
# Status bar
status_bar = tk.Label(root, text='')
status_bar.grid(row=100, column=0, columnspan=2, ipadx=5, ipady=5)
# Functions and bindings
def save():
"""Save the data to a file"""
subject = subject_inp.get()
selected = cat_inp.curselection()
if not selected:
category = 'Misc'
else:
category = categories[selected[0]]
message = message_inp.get('1.0', tk.END)
filename = f'{category} - {subject}.txt'
with open(filename, 'w') as fh:
fh.write(message)
status_bar.configure(text='File saved')
save_btn.configure(command=save)
# Last line
root.mainloop()
|
63bbad4eba82181361a3a1273c5bf8847e71fbe7 | hungd25/projects | /CS6390/HW4_P1.py | 3,718 | 3.953125 | 4 | """
"""
def get_world_series_wins(file_location):
"""
This function reads the World Series Data and return a list type per line
:param file_location:
:return: list of wins
"""
series_file = open(file_location, 'r') # open file with read only
series_wins = series_file.read().splitlines() # read all lines and return a list
series_file.close() # close file
return series_wins # return series of wins
def get_team_wins_count(series_wins):
"""
This function count how many times a win based on the number of appearences in the list
:param series_wins:
:return: win_counts
"""
win_counts = {} # creates a empty dictionary
for team in series_wins: # loop through series wins
if team in win_counts: # if team(key) in win counts just add one to win count
win_counts[team] += 1 # add one to current win count
else:
win_counts[team] = 1 # if team(key) not in win_counts add key and value 1
return win_counts # return win_counts
def get_team_wins_year(series_wins):
"""
This function append the year of to team base on appearences in the list
:param series_wins:
:return: win_years
"""
win_years = {} # creates a empty dictionary
year = 1903 # initialize year
for team in series_wins:
if year == 1904 or year == 1994: # if year is 1904 or 1994, skip it
year += 1 # increment year by 1
if team in win_years: # if team(key) in win_years append the year to list
win_years[team].append(year)
else:
win_years[team] = [year] #if team(key) not in win_years, value is list with year
year += 1 # increment year by 1
return win_years # return win_years
def show_team_win_year(win_years):
"""
This function print the win years
:param win_years:
:return:
"""
print("%s" % ('-' * 50)) # print 50 dashes
print('{:26} {}'.format('Team:', 'Win Years')) # print title
print("%s" % ('-' * 50)) # print 50 dashes
for team in sorted(win_years.keys()): # loop through a sorted win_years by key
print("{:26} {}".format(team + ":", win_years[team]))
def show_team_total_wins(win_counts):
"""
This function print the win counts
:param win_counts:
:return:
"""
print("%s" % ('-' * 50)) # print 50 dashes
print('{:26} {}'.format('Team:', 'Total Wins')) # print title
print("%s" % ('-' * 50)) # print 50 dashes
for team in sorted(win_counts, reverse=True, key=win_counts.get): # loop sorted win_counts by value descending
print("{:26} {}".format(team + ":", win_counts[team]))
def show_team_win_bar_graph(win_counts):
"""
This function print the win counts
:param win_counts:
:return:
"""
print("%s" % ('-' * 50)) # print 50 dashes
print('{:26} {}'.format('Team:', 'Total Wins Bar Graph')) # print title
print("%s" % ('-' * 50)) # print 50 dashes
for team in sorted(win_counts, reverse=True, key=win_counts.get): # loop sorted win_counts by value descending
print("{:26} {}".format((team + "("+ str(win_counts[team]) + ")" + ":"), '*' * win_counts[team]))
file_location = "WorldSeriesWinners.txt" # location of file
series_wins = get_world_series_wins(file_location) # call read file and store wins data
win_counts = get_team_wins_count(series_wins) # call get win count with series wins
win_years = get_team_wins_year(series_wins) # call get team win years with series wins
show_team_win_year(win_years) # call print win years
show_team_total_wins(win_counts) # call print total wins count
show_team_win_bar_graph(win_counts) # call print total wins bar graph |
6eb5114bcff34b32d3bc764773dc76e812c092e5 | saikumarpochireddygari/Interview_Prep | /int_to_roman.py | 4,291 | 4.03125 | 4 | """
Question : Given a integer value convert it into it's equivalent roman representation and return the same.
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
"""
class Solution:
def intToRoman(self, num: int) -> str:
if not num:
return None
value_to_symbol_dict = dict()
#### Define dictionaries ######
value_to_symbol_dict[1] = 'I'
value_to_symbol_dict[5] = 'V'
value_to_symbol_dict[10] = 'X'
value_to_symbol_dict[50] = 'L'
value_to_symbol_dict[100] = 'C'
value_to_symbol_dict[500] = 'D'
value_to_symbol_dict[1000] = 'M'
value_to_symbol_dict[4] = 'IV'
value_to_symbol_dict[9] = 'IX'
value_to_symbol_dict[40] = 'XL'
value_to_symbol_dict[90] = 'XC'
value_to_symbol_dict[400] = 'CD'
value_to_symbol_dict[900] = 'CM'
digits_stack = []
original_number = num
while (original_number):
digit = original_number % 10
digits_stack.append(digit)
original_number = int(original_number/10)
equivalent_roman_rep = ''
pow_ten_multiplier = len(digits_stack) - 1
while(digits_stack):
current_digit = digits_stack.pop()
current_digit = current_digit * int(pow(10,pow_ten_multiplier))
pow_ten_multiplier -= 1
if current_digit in value_to_symbol_dict:
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[current_digit]
else:
if current_digit % 1000 == 0:
for i in range(int(current_digit/1000)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[1000]
elif current_digit > 500 and current_digit < 900:
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[500]
current_digit = current_digit - 500
for i in range(int(current_digit/100)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[100]
elif current_digit > 100 and current_digit < 400:
for i in range(int(current_digit/100)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[100]
elif current_digit > 50 and current_digit < 90:
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[50]
current_digit = current_digit - 50
for i in range(int(current_digit/10)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[10]
elif current_digit > 10 and current_digit < 40:
for i in range(int(current_digit/10)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[10]
elif current_digit > 5 and current_digit < 9:
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[5]
current_digit = current_digit - 5
for i in range(int(current_digit)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[1]
elif current_digit > 1 and current_digit < 4:
for i in range(int(current_digit)):
equivalent_roman_rep = equivalent_roman_rep + value_to_symbol_dict[1]
return equivalent_roman_rep
if __name__ =="__main__":
a = 3879
soln = Solution()
print(soln.intToRoman(a)) |
4fdefc5403a6fa5b8d05f1b6c9556b03903b87b9 | chrisjdavie/hackerrank_algos | /compare_the_triplets/src/test.py | 834 | 3.5 | 4 | import unittest
from .solution import competition, compare_scores
class testComplete(unittest.TestCase):
def test_example(self):
a_i = ( 5, 6, 7 )
b_i = ( 3, 6, 10 )
a_score, b_score = compare_scores( a_i, b_i )
self.assertEqual(a_score, 1)
self.assertEqual(b_score, 1)
class testOneComparison(unittest.TestCase):
def test_alice_wins(self):
a_score, b_score = competition( 2, 1 )
self.assertEqual(a_score, 1)
self.assertEqual(b_score, 0)
def test_draw(self):
a_score, b_score = competition( 1, 1 )
self.assertEqual( a_score, 0 )
self.assertEqual( b_score, 0 )
def test_bob_wins(self):
a_score, b_score = competition( 1, 2 )
self.assertEqual( a_score, 0 )
self.assertEqual( b_score, 1 )
|
f67c54e276519f3262c4de78033c72e900f5d988 | ashu20031994/HackerRank-Python | /Day-1-Python Introduction/3.Division.py | 629 | 4.375 | 4 | """Task
The provided code stub reads two integers, and , from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, // . The second line should contain the result of float division, / .
No rounding or formatting is necessary.
Example
The result of the integer division .
The result of the float division is ."""
def division(a, b):
"""This function will calculate floor division and division operation and then
print the results."""
print(a//b)
print(a/b)
if __name__ == '__main__':
a = int(input())
b = int(input())
division(a, b)
|
820439d74ac637d9c9cdf34d9b75369db5ec04e8 | chensheng1/gitskills | /python 实例/cstest.py | 580 | 3.71875 | 4 | #!usr/bin/env python
#coding:cp936
k=5 #Ӳҵıֵ
n=100 #֧Ǯ
mon=[] #ʼıֵ
backmon=[] #ѰıֵĿʹСʼ
for i in range(k+1): #Ŀеıֵб
mon.append(2**i)
mon.reverse()
for m in mon: #ѡıֵnȥõֵǴ˱ֵĿʣµҪжϵġ
backmon.append(n/m)
n=n%m
for j in range(k+1):
if backmon[j]!=0: #жϴӡ
print str(mon[j])+'Ҫ'+str(backmon[j])+''
|
1b17f63d3c562e74e3d22c15dcb5f134476ba6eb | masterprueba/Prueba-Big-Data | /primero/spark.py | 1,786 | 3.5625 | 4 |
##- 1.Cargar el archivo csv por medio de comandos dentro de Databricks Community.
## Primero, cargo el archivo CSV y muestro los datos.
import numpy as np
import pandas as pd
import collections
file_location = "/FileStore/tables/Tweets.csv"
file_type = "csv"
# Opciones
infer_schema = "false"
first_row_is_header = "true"
delimiter = ","
# Leer Csv
df = spark.read.format(file_type) \
.option("inferSchema", infer_schema) \
.option("header", first_row_is_header) \
.option("sep", delimiter) \
.load(file_location)
display(df)
#### Spark SQL
#- 2.Extraer las columnas text y tweet_created
#Capturo los dos campos con los que voy a trabajar y lo paso a DataFrame(pandas)
df.createOrReplaceTempView("tweets")
sqlDF = spark.sql("SELECT text,tweet_created FROM tweets")
tweetsanddate = sqlDF.toPandas()
#### DataFrame
#- 3.Construir una nueva columna con los hashtags dentro del tweet.
#Con la libreria pandas y una expresion regular creo la nueva columna con los hashtags
tweetsanddate["hashtag"] = tweetsanddate.text.str.findall(r'@.*?(?=\s|$)')
tweetsanddate.head()
#### RDD
#- 4.Encontrar cuales son los 10 hashtags que más se utilizan
#Elimino filas con datos nulos, realiza el conteo de los hashtag, ordeno y muestro los 10 hashtag mas utilizados
total = np.array([], dtype="str")
for tw in tweetsanddate.hashtag:
total = np.append(total,tw)
data_has = pd.DataFrame(total).reset_index()
data_has.columns = ['id','hashtag']
data_has = data_has.dropna()
data_has.head(5)
rdd_has = sc.parallelize(data_has.hashtag).filter(lambda x: x is not None)
d = rdd_has.countByValue()
ordered = collections.OrderedDict(sorted(d.items(), key=lambda t: t[1],reverse=True))
diez_hashtag = pd.DataFrame(ordered, columns=ordered.keys(), index=[1])
diez_hashtag.T.head(10)
|
6a6717d45c5cd3b387279cec4a73e4ce86f1f1e3 | breynaUC/py-clase04 | /ejercicios02.py | 175 | 4 | 4 | estudiantes= {"Raul":21,"Jairo":18,"Keyla":19}
nombre = input("Nombre: ")
if nombre.title() in estudiantes:
print(estudiantes[nombre.title()])
else:
print("No existe") |
34d245a28e407c72e235ca3cb860380e0bc3c606 | nazarov-yuriy/contests | /yrrgpbqr/p0347/__init__.py | 606 | 3.53125 | 4 | import unittest
from typing import List
import collections
# ToDo: use uniquiness of answer and implement bucket sort
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = collections.Counter(nums)
return sorted(counts, key=lambda x: -counts[x])[:k]
class Test(unittest.TestCase):
def test(self):
nums = [1, 1, 1, 2, 2, 3]
k = 2
out = [1, 2]
self.assertEqual(Solution().topKFrequent(nums, k), out)
nums = [1]
k = 1
out = [1]
self.assertEqual(Solution().topKFrequent(nums, k), out)
|
4db6f9178e623ddcffded9307e1f27ecc9c424fa | SoSopog-dev/All | /kryptering.py | 454 | 3.5625 | 4 | import random
from random import randint
alphabet = "abcdefghijklmnopqrstuvwxyzæøå "
p_al = ""
pairs = {}
p_al = list(p_al)
if int(input("Generate? 1 = Yes 2 = No")) == 1:
seed = randint(1,100)
random.seed(seed)
for letter in alphabet:
newletter = alphabet[randint(0,29)]
while newletter in p_al :
newletter = alphabet[randint(0,29)]
p_al.append(newletter)
pairs[letter]= newletter
print (seed)
p_al = ""
|
3e205f2cae2c99e36f307feab693797808b577e8 | piercepurselley/Python_Web_Dev_Practice | /Python Web Dev Practice/find_characters.py | 480 | 3.75 | 4 | word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna']
char = 'o'
new_list = []
#WE ARE GOING FOR...
# new_list = ['hello', 'world']
# print [s for s in list if sub in s]
# for x in range(0,len(word_list)):
# if let in len(word_list) == char:
# print "I did it!"
for x in word_list:
if x.find('o') > -1:
new_list.append(x)
print new_list
# for x in word_list:
# x = "hello"
# for x in range(0, len(word_list)):
# if x
# print x
|
ce64623746347a2eaf78a58cd551346b1c7468d2 | kavyaachu47/luminarpython | /luminar/Classroomassignments/fibnopgm.py | 161 | 4.15625 | 4 | #Program to produce fibonacci series
num=int(input("enter value"))
a=0
b=1
sum=0
c=1
while(c<=num):
print(sum,end="")
c+=1
a=b
b=sum
sum=a+b |
1c8f7223bd09bde85e8aac7bef38d6960dfdd5d8 | rustt71749/01_Lucky_Unicorn_V2 | /04_Lucky_Unicorn_payment_mechanics.py | 812 | 3.953125 | 4 | # Lucky Unicorn Decomposition Step 4
# Set up payment mechanics
# To do
# Adjust total correctly for a given token
# - if it's a unicorn add $5
# - if it's a zebra / horse, subtract 0.5
# - if it's a donkey,subtract 1
# Give user feedback based on winnings
# State new total
# Assume starting amount is $10
total = 10
# Assume manual token input for testing purposes
token = input("Enter a token: ")
# Adjust correctly for a given token
if token == "unicorn":
total += 5
feedback = "Congratulations, you got a lucky unicorn and have won $5.00!"
elif token == "donkey":
total -= 1
feedback = "Sorry, you did not win anything this round"
else:
total -= 0.5
feedback = "Congratulations, you won 50¢!"
print()
print(feedback)
print("You have ${:.2f} to play with".format(total))
|
85ff122284f8c29288f2032e8f94dce154b1a516 | Aasthaengg/IBMdataset | /Python_codes/p02393/s646088337.py | 363 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 30 16:38:31 2015
@author: hirose
"""
#Branch on Condition - Sorting Three Numbers
n = map(int, raw_input().split())
a = n[0]
b = n[1]
c = n[2]
for i in range(3):
for i in range(2):
if(n[i] > n[i+1]):
temp = n[i]
n[i] = n[i+1]
n[i+1] = temp
print n[0], n[1], n[2] |
e45fda96ee2cc0c772fc40fcdbfc40caaa64dafe | typemegan/Python | /CorePythonProgramming_2nd/ch14_excution/udm_method.py | 1,474 | 3.78125 | 4 | #!/usr/bin/python
#coding:utf-8
'''
比较类中的三种方法:
类方法,实例方法,静态方法
'''
class A(object):
def func(self): pass # self用来接收python自动传入的实例,无论绑定还是未绑定调用
@classmethod
def bar(cls):pass # cls用来接收由python自动传入的类对象
@staticmethod
def foo(*args):pass
print 'A:'
print 'A.func:'.ljust(12), A.func
print 'A.bar:'.ljust(12), A.bar
print 'A.foo:'.ljust(12), A.foo
print 'A type:'
print 'A.func:'.ljust(12), type(A.func)
print 'A.bar:'.ljust(12), type(A.bar)
print 'A.foo:'.ljust(12), type(A.foo)
print '-'*30
a = A()
print 'a:'
print 'a.func:'.ljust(12), a.func
print 'a.bar:'.ljust(12), a.bar
print 'a.foo:'.ljust(12), a.foo
print 'a type:'
print 'a.func:'.ljust(12), type(a.func)
print 'a.bar:'.ljust(12), type(a.bar)
print 'a.foo:'.ljust(12), type(a.foo)
'''
A:
A.func: <unbound method A.func>
A.bar: <bound method type.bar of <class '__main__.A'>>
A.foo: <function foo at 0x7fc581cf6aa0>
A type:
A.func: <type 'instancemethod'>
A.bar: <type 'instancemethod'>
A.foo: <type 'function'>
------------------------------
a:
a.func: <bound method A.func of <__main__.A object at 0x7fc581cf4b50>>
a.bar: <bound method type.bar of <class '__main__.A'>>
a.foo: <function foo at 0x7fc581cf6aa0>
a type:
a.func: <type 'instancemethod'>
a.bar: <type 'instancemethod'>
a.foo: <type 'function'>
'''
|
b489e48634ed1bdd7286e8b46978c7fccbd556b0 | tuouo/selfstudy | /learnfromBook/PythonCookbook/DataStructure/about_priority_queue | 919 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
a = Item('foo')
b = Item('bar')
c = Item('zoo')
q = PriorityQueue()
q.push(a, 1)
q.push(b, 2)
q.push(c, 5)
q.push(Item('tank'), 2)
q.push(Item('mike'), 3)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
# print(a < b) TypeError: unorderable types: Item() < Item()
aa = (1, a)
bb = (1, b)
# print(aa < bb) TypeError: unorderable types: Item() < Item()
bb = (2, b)
print(aa < bb) # True
|
efcdd0fce7bffdb788497ab7e787f41db40f8c48 | fmurray1/obs_overlay | /life_overlay_gen.py | 1,251 | 3.5 | 4 | """
Script generates a square image with a number in the middle
to use as an OBS overlay for playing magic over webcam.
"""
import click
from PIL import Image, ImageDraw, ImageFont
SNOW_WHITE = (255, 250, 250)
def text_on_img(text="NULL", filename='output.png', text_size=120, image_w=200, image_h=200):
"Draw a text on an Image, saves it"
fnt = ImageFont.truetype('arial.ttf', text_size)
# create image
image = Image.new(mode="RGB", size=(200, 200), color="black")
draw = ImageDraw.Draw(image)
# get center of img to put text
text_w, text_h = fnt.getsize(text)
# draw text
draw.text(((image_w-text_w)/2, (image_h-text_h)/2),
text, font=fnt, fill=(255, 250, 250))
# save file
image.save(filename)
@click.group()
def cli():
"""Base cli for click"""
@cli.command(name='tax')
@click.argument('tax', default='0', type=str)
def commander_tax(tax):
"""Make the command tax image"""
text_on_img(text=tax, filename='command_tax.png')
@cli.command(name='life')
@click.argument('life_count', default='40', type=str)
def life_counter(life_count):
"Make the life counter image"
text_on_img(text=life_count, filename='life_count.png')
if __name__ == "__main__":
cli()
|
65161b034f0738a7ecb1b15354604a5f5c66ee76 | Johnelvis/ECG-NN-Classifier | /ecg-nn-classifier/preprocessing/filters.py | 1,788 | 3.5 | 4 | from scipy.signal import medfilt, butter, lfilter
"""
Low pass filters the ecg signal to remove high frequency noise like electromagnetic interference.
"""
def low_pass_filter(data, cutoff, order, sample_rate=360):
# Nyquist frequency
ny = sample_rate >> 1
cut = cutoff / ny
# Calculate filter coefficients using butterworth filter
b, a = butter(order, cut, analog=False, btype="low")
# Return the filtered signal using linear filter
return lfilter(b, a, data)
"""
Band pass filters the ecg signal to remove low frequency noise like baseline drift
and high frequency noise like electromagnetic interference.
"""
def band_pass_filter(data, cutoff, order, sample_rate=360):
# Nyquist frequency
ny = sample_rate >> 1
cut = [c / ny for c in cutoff]
# Calculate filter coefficients using butterworth filter
b, a = butter(order, cut, analog=False, btype="band")
# Return the filtered signal using linear filter
return lfilter(b, a, data)
"""
High pass filters the ecg signal to remove low frequency noise like baseline drift.
"""
def high_pass_filter(data, cutoff, order, sample_rate=360):
# Nyquist frequency
ny = sample_rate >> 1
cut = cutoff / ny
# Calculate filter coefficients using butterworth filter
b, a = butter(order, cut, analog=False, btype="high")
# Return the filtered signal using linear filter
return lfilter(b, a, data)
"""
Applies a median filter on a dataset where its width is defined in ms.
"""
def median_filter(data, time, sample_rate=360):
window_size = int(time * sample_rate / 1000)
# Floor size by 1 if even, as window size must be odd
if window_size & 0x1 == 0: window_size -= 1
# Return the median filtered signal
return medfilt(data, window_size)
|
4ab2db331b42f517acce0877681669d791c37919 | shocklink/ShellScriptRepository | /shell-script/plot-memory-space/hex_to_binary.py | 197 | 3.53125 | 4 | #!/bin/python
count = 0;
with open('d','r') as f:
for line in f:
for word in line.split():
#print(word),
print(bin(int(word, 16))[2:].zfill(64)),
print
|
81111419f9b7f234b651b54444d1de6f093171f6 | vijaymaddukuri/python_repo | /training/sdArray.py | 169 | 3.84375 | 4 | color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
newList=[]
for (i,x) in enumerate(color):
if i not in (0,4,5):
newList.append(x)
print(newList) |
2fc1aca509b73e5b46cbd9c747a03c1689969d16 | Mike-Xie/cs-module-project-hash-tables | /hashtable/code_test.py | 1,349 | 3.984375 | 4 | all_ints = [85, 46, 27, 81, 94, 9, 27, 38, 43, 99, 37, 63, 31, 42, 14]
names = ["Bob", "Jane", "Bill"]
divisible_by_three = list(filter(lambda x: x % 3 == 0, all_ints))
names_that_are_4_chars = list(filter(lambda x: len(x) == 4, names))
for item in divisible_by_three:
print(item)
# Print out all of the strings in the following array that represent a number divisible by 3:
# [
# "five",
# "twenty six",
# "nine hundred ninety nine,
# "twelve",
# "eighteen",
# "one hundred one",
# "fifty two",
# "forty one",
# "seventy seven",
# "six",
# "twelve",
# "four",
# "sixteen"
# ]
# The expected output for the above input is:
# nine hundred ninety nine
# twelve
# eighteen
# six
# twelve
# You may use whatever programming language you wish.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
# pretty much you are writing a parser
# either start at the front or the back and recurse to other end
# while keeping a running total
# the strings alternate a number and an optional multiplier like
# 9 x 100 + 90 + 9
# terminals are below:
# one
# two
# three
# four
# five
# six
# seven
# eight
# nine
# ten
# eleven
# twelve
# thirteen
# fourteen
# fifteen
# sixteen
# seventeen
# eighteen
# nineteen
|
acf5892120dcb3c6204ddede75604f3279801bc4 | chenjiahui1991/LeetCode | /P0014.py | 735 | 3.734375 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
result = strs[0]
for i in range(1, len(strs)):
result = self.getLongest(result, strs[i])
return result
def getLongest(self, str1, str2):
result = '';
if len(str1) > len(str2):
tmp = str1
str1 = str2
str2 = tmp
for i, ch in enumerate(str1):
if ch == str2[i]:
result = result + ch
else:
return result
return result
s = Solution()
print(s.longestCommonPrefix(['flower','flow','flight']))
|
4e1f9bcbb5d1bc368136051e50bfa1a4f9b675ba | radhikaca/puzzles | /Largesum.py | 304 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 07:36:42 2020
@author: rad
"""
def fibonacci():
"""Fibonacci numbers generator, first n"""
a, b, i = 0, 1, 0
while i<10:
yield i
#yield a
#a, b = b, a + b
i += 1
f = fibonacci()
for i in f:
print(i)
|
b6a9835ce89cdd2ff0961c29f0d007d52cdc2713 | xyzhangaa/ltsolution | /CountandSay.py | 703 | 4 | 4 | ###The count-and-say sequence is the sequence of integers beginning as follows:
###1, 11, 21, 1211, 111221, ...
###1 is read off as "one 1" or 11.
###11 is read off as "two 1s" or 21.
###21 is read off as "one 2, then one 1" or 1211.
###Given an integer n, generate the nth sequence.
#time O(n*2^n)
#space O(2^n)
def counts(self,s):
count = 0
current = '#'
result = ''
for item in s:
if item != current:
if current!='#':
result += str(count)+current
count = 1
current = item
else:
count += 1
result += str(count)+current
return result
def countandsay(self,n):
string = '1'
for i in range(2,n+1):
string = self.counts(string)
return string
|
3c0abbab55674cae73b79d15de0f38e1aaaeba50 | maryyang1234/hello-world | /string/10.计算字符串中的数字和.py | 343 | 3.984375 | 4 | import re
def findSum(str1):
p = re.compile("[0-9]+")
list = p.findall(str1)
sum =0
for i in list:
sum= sum+int(i)
return sum
str1 = "12abc20yz68"
print(findSum(str1))
"""def find_sum(str1):
# Regular Expression that matches digits in between a string
return sum(map(int,re.findall('\d+',str1))) """ |
44cfca596adbb9b0d993b1d597c31e707c200180 | simonom/outreach | /tephiplt/tephiplt.py | 10,361 | 3.59375 | 4 | '''script to demonstrate the equations underlying the tephigram'''
# based on EART23001: Atmospheric Physics and Weather (University of Manchester)
# Simon O'Meara 2020: [email protected]
# other helpful resource(s): http://homepages.see.leeds.ac.uk/~chmjbm/arran/radiosondes.pdf
# -----------------------------------------------------------------------------------
# dependencies
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
import matplotlib.ticker as ticker
import ipdb
import scipy.constants as si
import math
# ------------------------------------------------------------------------------------
fig1, ax1 = plt.subplots() # initiate plot
# the anti-clockwise transformation needed to rotate plots away
# from conventional design of orthogonal with respect to screen
# angle - note this enables pressure to decrease with vertical in
# plot
trans = Affine2D().rotate_deg(315)
trans_data = trans + ax1.transData
# set temperature ranges & interval (oC) --------------------------------
Tmin = -120. # minimum
Tmax = 120. # maximum
Tint = 10. # interval within temperature range (oC and K)
# ------------------------------------------------------------------------------------
# temperature range (oC)
T_oC = (np.arange(Tmin, Tmax+0.1, Tint)).reshape(1, -1)
# potential temperature range (oC)
theta_oC = (np.arange(Tmax, Tmin-0.1, -Tint)).reshape(-1, 1)
# repeat temperatures over a matrix of changing potential
# temperature in rows and changing temperature in columns
T_oC = np.repeat(T_oC, theta_oC.shape[0], axis=0)
theta_oC = np.repeat(theta_oC, T_oC.shape[1], axis=1)
# first plot (just T and potential temperature lines) -------------------
# the isotherms to plot
Tlevels = np.arange(Tmin, Tmax+0.1, Tint)
# plotting temperature contours
tephi0 = ax1.contour(T_oC, theta_oC, T_oC, Tlevels, colors = 'black', linewidths = 0.5, linestyles = 'solid', transform = trans_data)
# contour labels
labels = [] # empty contour labels list
for it in range(len(Tlevels)):
labels.append(str(r'T=%s $\rm{^oC}$') %Tlevels[it])
fmt2 = {}
for l, s in zip(tephi0.levels[0::2], labels[0::2]):
fmt2[l] = s
ax1.clabel(tephi0, tephi0.levels[0::2], inline = False, fmt = fmt2, fontsize = 10)
# plotting potential temperature contours
tephi0 = ax1.contour(T_oC, theta_oC, theta_oC, Tlevels, colors = 'black', linewidths = 0.5, linestyles = 'solid', transform = trans_data)
# contour labels
labels = [] # empty contour labels list
for it in range(len(Tlevels)):
labels.append(str(r'$\rm{\theta}$=%s $\rm{^oC}$') %Tlevels[it])
fmt2 = {}
for l, s in zip(tephi0.levels[0::2], labels[0::2]):
fmt2[l] = s
ax1.clabel(tephi0, tephi0.levels[0::2], inline=False, fmt=fmt2, fontsize=10)
ax1.set_ylim([-5, 100])
ax1.set_xlim([-70, 60])
# turn off ticks on axis
plt.tick_params(axis = 'both', which = 'both', bottom = 0, left = 0, labelbottom = 0, labelleft = 0)
plt.draw()
plt.pause(1) # pause
# calculating pressures based on combinations of
# temperature and potential temperature -------------------------------------
T_K = T_oC+273.15 # convert to K
theta_K = theta_oC+273.15 # convert to K
# ratio of specific heat capacity at constant pressure to
# specific heat capacity at constant volume for dry air
gamma = 1.4
# pressure at temperature-potential temperature combination
# recall: theta = T(1.e3./P)**((gamma-1.)/gamma), where T in K, P in hPa
# and gamma is ratio of specific heat capacity at constant pressure to
# specific heat capacity at constant volume for dry air
P = 1.e3/((theta_K/T_K)**(gamma/(gamma-1)))
# second plot (just pressure = 1000 hPa) ---------------------------------------
# note 1000 hPa is treated here as the pressure representative of the Earth surface
levels = np.arange(1000., 1001., 100) # the isobar(s) to display
# plot pressure as contour lines
tephi1 = ax1.contour(T_oC, theta_oC, P, levels, colors = 'green', transform = trans_data)
# contour labels
fmt2 = {} # empty dictionary
labels = ['1000 hPa' ]
for l, s in zip(tephi1.levels, labels):
fmt2[l] = s
ax1.clabel(tephi1, tephi1.levels, inline = True, fmt = fmt2, fontsize = 10)
plt.draw()
plt.pause(1) # pause presentation
# third plot (all pressures (hPa)) ---------------------------------------------
levels = np.arange(3.e2, 9.01e2, 1e2) # the isobar(s) to display
# plot pressure as contour lines
tephi2 = ax1.contour(T_oC, theta_oC, P, levels, colors = 'green', transform = trans_data)
# contour labels
fmt2 = {} # empty dictionary
labels = ['300 hPa', '400 hPa', '500 hPa', '600 hPa', '700 hPa', '800 hPa', '900 hPa']
for l, s in zip(tephi2.levels[1::2], labels[1::2]):
fmt2[l] = s
ax1.clabel(tephi2, tephi2.levels[1::2], inline = True, fmt = fmt2, fontsize = 10)
plt.draw()
plt.pause(1) # pause
# fourth plot (wet bulb potential temperature (oC)) --------------------
# latent heat of vapourisation (J/kg) for water as a function of temperature
# doi.org/10.1002/qj.49711046626
Lw = 1.91846e6*(T_K/(T_K-33.91))**2.
Rw = 462. # J/kg.K energy per unit mass of water vapour per unit temperature
# ratio of latent heat of vapourisation to R
A = -Lw/Rw
# reference saturation vapour pressure at 0 oC (hPa) (Dry and Moist Air lecture)
esvp0 = 6.1
exp0 = A/273.15 # reference exponential index at 0 oC (dimensionless)
# saturation vapour pressure at all temperatures (hPa)
esvp = esvp0*(np.exp(A/T_K-exp0))
# latent heat of vapourisation (J/kg) for water as a function of temperature
# doi.org/10.1002/qj.49711046626
Lw = 1.91846e6*(T_K/(T_K-33.91))**2.
# rate of change of r (water mixing ratio) with temperature from saturated
# adiabatic lapse rate
# equation (Convection and SALR lecture), note the first term results from the
# differentiation of r = 5e_svp/8P with respect to T, where e_svp is given by the
# esvp equation above (/K)
drdT = 5.*(-A/(T_K**2.))*esvp/(8.*P)
# specific heat capacity of dry air (J/K.kg) (Convection and SALR lecture)
Cp = 1004.
# saturated adiabatic lapse rate (Dry and Moist Air lecture) (K/m)
Gamm = si.g/(Cp+Lw*drdT)
# prepare for storing wet bulb potential temperarure (oC)
thetaw_oC = np.zeros((theta_oC.shape))
# assume same as dry potential temperature to begin (oC)
thetaw_oC[:, :] = theta_oC[:, :]
# wet bulb potential temperatures at reference pressure (oC) is the same as for
# the actual temperature and the potential temperature
thetaw_oC[np.arange(theta_oC.shape[0]-1, -1, -1), np.arange(0, theta_oC.shape[1], 1)] = theta_oC[np.arange(theta_oC.shape[0]-1, -1, -1), np.arange(0, theta_oC.shape[1], 1)]
R = si.R*1.e3/28.966 # specific gas constant for air (m2/(K.s^2))
R = si.R*1.e3/18. # specific gas constant for water vapour (m2/(K.s^2))
Gammr = si.g/1004 # dry adiabatic lapse rate (K/m)
# ratio of isotherm adjacent to hypotenuse
mn = (T_K[0, 1]-T_K[0, 0])/((T_K[0, 1]-T_K[0, 0])**2.+(theta_K[1, 0]-theta_K[0, 0])**2.)**0.5
# scaling factor for wet bulb potential temperature estimation
mn = (T_K[0, 1]-T_K[0, 0])*mn
for ir in range(theta_oC.shape[0]): # loop through rows
# column where bottom left to top right diagonal met
cd = Gamm.shape[1]-ir
# below reference pressure (higher altitudes)
# height (m) between columns in this row
delz = (np.log(P[ir, 1:cd]/P[ir, 0:cd-1])/-si.g)*R*((T_K[ir, 1:cd]+T_K[ir, 0:cd-1])/2.)
# temperature change following dry adiabatic lapse rate
delTr = delz*Gammr
# change in temperature following saturated adiabatic cooling
delT = delz*Gamm[ir, 0:cd-1]
# change in temperature effect on saturated adiabatic isotherms
delTn = np.flip(np.cumsum(np.flip(mn-(delT/delTr)*mn)))
# saturated adiabatic temperature isopleth
thetaw_oC[ir, 0:cd-1] -= delTn
# above reference pressure (lower altitudes)
# height (m) between columns in this row
delz = (np.log(P[ir, cd::]/P[ir, cd-1:-1])/-si.g)*R*((T_K[ir, cd::]+T_K[ir, cd-1:-1])/2.)
# temperature change following dry adiabatic lapse rate
delTr = delz*Gammr
# change in temperature following saturated adiabatic cooling
delT = delz*Gamm[ir, cd::]
# change in temperature effect on saturated adiabatic isotherms
delTn = np.cumsum(mn-(delT/delTr)*mn)
# saturated adiabatic temperature isopleth
thetaw_oC[ir, cd::] += delTn
# plot wet bulb potential temperature contours
tephi3 = ax1.contour(T_oC, theta_oC, thetaw_oC, Tlevels, colors = 'black', linewidths = 0.1, linestyles = '-', transform = trans_data)
# contour labels
labels = [] # empty contour labels list
for it in range(len(Tlevels)):
labels.append(str(r'$\rm{\theta_w}$=%s $\rm{^oC}$') %Tlevels[it])
fmt2 = {}
for l, s in zip(tephi3.levels[0::2], labels[0::2]):
fmt2[l] = s
ax1.clabel(tephi3, tephi3.levels[0::2], inline = False, fmt = fmt2, fontsize = 10)
plt.draw()
plt.pause(1) # pause
# fifth isopleth (mass mixing ratio of water (g of water/kg dry air)) ----------
# using ideal gas equation, estimate mass (kg) of water vapour in 1m3 of air
# based on pressure, note hPa converted to Pa
mw = (esvp*1e2*1.)/(Rw*T_K)
mw = mw*1e3 # convert to g from kg
# using ideal gas equation estimate mass of dry air, note hPa
# converted to Pa
ma = (P*1e2*1.)/(R*T_K)
r = mw/ma # the mass mixing ratio (g of water/kg of dry air)
# state water mixing ratios to plot
rlevels = [0.15, 0.8, 2., 3., 5., 7., 9., 12., 16., 20., 28.]
# plot water mixing ratio contours
tephi4 = ax1.contour(T_oC, theta_oC, r, rlevels, colors = 'black', linewidths = 0.5, linestyles = '--', transform = trans_data)
# contour labels
labels = [r'0.15 $\rm{g\, kg^{-1}}$', r'0.8 $\rm{g\, kg^{-1}}$', r'2 $\rm{g\, kg^{-1}}$', r'3 $\rm{g\, kg^{-1}}$', r'5 $\rm{g\, kg^{-1}}$', r'7 $\rm{g\, kg^{-1}}$', r'9 $\rm{g\, kg^{-1}}$', r'12 $\rm{g\, kg^{-1}}$', r'16 $\rm{g\, kg^{-1}}$', r'20 $\rm{g\, kg^{-1}}$', r'28 $\rm{g\, kg^{-1}}$']
fmt2 = {}
for l, s in zip(tephi4.levels, labels):
fmt2[l] = s
ax1.clabel(tephi4, tephi4.levels, inline = False, fmt = fmt2, fontsize = 10)
plt.draw()
plt.pause(1) # pause
# finally plot example measurements -------------------
# measure temperatures (oC)
measT = 80, 60, 50, 15, 15, 15, 15
xT = -50, -55, -60, -60, -35, -10, 15
# measured wet-bulb temperature (oC)
measwT = 5, 5, 6, 7, 7, 7, 7
xwT = -90, -80, -75, -68, -35, -10, 5
# plot measurements
plt.plot(xT, measT, '-r', transform = trans_data)
plt.plot(xwT, measwT, '-b', transform = trans_data)
plt.draw()
plt.pause(1000) # pause
# end of script --------------------------------------------------- |
4be572ee85b35d30e9aba7a0d7c09a698ee83e35 | rv404674/Algo-Implementations | /graph/dfs.py | 1,145 | 3.828125 | 4 | # NOTE
# TIme complexity of In
# for list - Average(O(n)) ( Implemented as sequences)
# for dict - Average O(1), Worst O(n) ( as dict is hashing data type)
# edpresso.com for dfs implementation
# for a directed graph, the sum of size of adjaceny list of all nodes is E. 2+2+1+1 = 6
# hence O(V) + O(E) = O(V+E)
# OV) because you nead to visit each vertex alteast once.
# O(E) because you need to go through outgoing paths (edges) for each node
# for densely populated graphs, e=v^2. hence O(v^2)
graph = {
'a':['b','c'],
'b':['d','e'],
'c':['f'],
'd':[],
'e':['f'],
'f':[]
}
# visited = {}
# def dfs(graph, visited, node):
# if node not in visited:
# print(node)
# visited[node] = True
# for neighbour in graph[node]:
# dfs(graph, visited, neighbour)
#OR
def dfs(graph, visited, node):
print(node)
visited[node] = True
print(visited, "VISITED")
for neighbour in graph[node]:
if neighbour not in visited:
dfs(graph, visited, neighbour)
def dfsutil():
visited = {}
dfs(graph, visited, 'a')
dfsutil() |
daab04c1d1026165d2a385d0f75b7b6e741bd914 | Vputri/Python | /tugas.py | 276 | 3.78125 | 4 | print "Ketikkan Control C atau -1 untuk keluar"
number = 1
while number != -1:
print ''
try:
number = int(raw_input("Masukan angka : "))
print "Anda memasukan :",number
except ValueError:
print "Bukan angka bilangan integer atau float!"
|
fb15cf38c01c041585dab3b53621e5020e157446 | nirnicole/Artificial-Intelligence-Python-Repositories | /Evolutionary Computation/Genetic Algorithm/Maze.py | 11,164 | 3.765625 | 4 | import Problem
import random
from PIL import Image
import numpy as np
import math
class MazeProblem(Problem.EvolutionProblem):
"""
in this problem we get different attempts to find a solution to a distance problem and we try to utilize them.
its actually a local searching problem.
dna structure:
list of chars representing the direction the robot went from the set: {U,D,L,R}.
fitness function:
will be elaborate later.
maximization problem:
the fitness will be normalized between 0 to 1.
attributes:
initial population
generations
Swap function = Crossing at k random point
mutation probability
crossing probability
elitism probability
"""
def __init__(self,path, initpop_size, iterations,maze_diffic = 0, cross_rate = 0.3, mute_rate = 0.2, elitisem_rate=0.1, cool_after=500.0, start=[0,0], end=[0,0]):
"""
we need to add to the basic initialization the following factors,
including a layout data to compare to, start point and ending.
"""
self.layout_data= []
self.layout_data = self.translateMaze(path)
self.LAYOUT_LINES = self.layout_data.__len__()
self.LAYOUT_COLUMNS = self.layout_data[0].__len__()
self.MAX_DIMENSION = max(self.LAYOUT_LINES, self.LAYOUT_COLUMNS)
self.MAZE_DIFFICULTY = maze_diffic
Problem.EvolutionProblem.__init__(self, initpop_size, (maze_diffic+1)* self.MAX_DIMENSION , ['L', 'R', 'U', 'D'], iterations, cross_rate, mute_rate, elitisem_rate, cool_after)
self.SOURCE_COORDINATE = start
self.DESTINATION_COORDINATE = end
self.layout_data[end[0]][end[1]]=2
def generateInitialPopulation(self, use_heuristics=False):
"""
if heuristics are permitted,
half of the population will be biased and quit accurate to the destination.
although if obstacles are around, they will go through them and loose a lot of credit.
the rest of the population is randomized.
"""
self.CUR_GENERATION = 0
cutting_factor = 2
#create with heuristics
if use_heuristics:
cutting_factor*=2
#start with manhattan routes
x1, y1 = self.SOURCE_COORDINATE
x2, y2 = self.DESTINATION_COORDINATE
steps_vertically = x2 - x1
steps_horizontally = y2 - y1
self.GENES = ['L', 'R', 'U', 'D']
if steps_vertically>=0:
vertical_direction = self.GENES[3] #down
else:
steps_vertically *= -1
vertical_direction = self.GENES[2] #up
if steps_horizontally>=0:
horizontal_direction = self.GENES[1] #right
else:
steps_horizontally *= -1
horizontal_direction = self.GENES[0] #left
for i in range(2*self.INITIAL_POP_SIZE / cutting_factor):
new_dna = []
#creat manhattan route
for _ in range(steps_vertically):
new_dna.append(vertical_direction)
for _ in range(steps_horizontally):
new_dna.append(horizontal_direction)
while new_dna.__len__()<self.DNA_LENGTH:
new_dna.append(self.GENES[3])
# add to group with a starting fitness evaluation
self.population.append([self.getFitness(new_dna), new_dna])
#create random dna's
for i in range(self.INITIAL_POP_SIZE/cutting_factor):
action = i%4
new_dna = [self.GENES[action] for gene in range(self.DNA_LENGTH)]
#add to group with a starting fitness
self.population.append([self.getFitness(new_dna), new_dna])
while(self.population.__len__()<self.INITIAL_POP_SIZE):
# deep copy to new list
new_dna = self.dna[:]
# shuffle the new list
random.shuffle(new_dna)
#add to group with a starting fitness
self.population.append([self.getFitness(new_dna), new_dna])
def getFitness(self, dna):
"""
calculate how accurate the rout was,
punish for obstacles ignorance and bonus every improving step.
nonetheless, punish greatly for borders crossing.
"""
REPEATED_PENALTY = 2 # each repeated node is considered the same as REPEATED_PENALTY steps
OBSTACLE_PENALTY = 200 # each obstacle on the way is considered the same as OBSTACLE_PENALTY steps
DEST_NOT_REACHED_PENALTY = 2*self.DNA_LENGTH + self.manhattanDistance(self.SOURCE_COORDINATE, self.DESTINATION_COORDINATE) # if destination is not reached
#collect data of route
distance, bonus, repeated_nodes, obstacles, final_point, is_out_of_bound = self.simulateRoute(dna)
# Calculate Penalties
penalties = repeated_nodes * REPEATED_PENALTY + obstacles * OBSTACLE_PENALTY
#if out of bound
if is_out_of_bound:
aggregate_fitness = float('inf')
else:
if distance == float('inf'): #if the rout didnt achive destination its weight will be its final point dis +penalties
penalties += DEST_NOT_REACHED_PENALTY
aggregate_fitness = self.manhattanDistance(final_point, self.DESTINATION_COORDINATE) + penalties
else:
aggregate_fitness = distance + penalties
aggregate_fitness -= bonus
#normalization
normelized_fitness = 1.0 / (1+aggregate_fitness)
if distance < float('inf') and not obstacles:
print dna , (normelized_fitness)
self.paintRout(dna)
self.SOLVED = True
# returning the inverse of the cost, so it'll become a proper fitness function
return normelized_fitness
def isGoal(self):
if self.SOLVED : #if its fitness is perfect
return self.SOLVED
return self.SOLVED
#FUNCTIONS
def translateMaze(self, path, resize_factor=100.0):
# 'maze.png' = path
# Open the maze image and make greyscale, and get its dimensions
try:
im = Image.open(path).convert('L')
w, h = im.size
# Ensure all black pixels are 0 and all white pixels are 1
binary = im.point(lambda p: p > 128 and 1)
# Resize to about resize_factorXresize_factor pixels.
resizing_w = int(math.ceil(float(w)/resize_factor))
resizing_h = int(math.ceil(float(h)/resize_factor))
binary = binary.resize((w // resizing_w, h // resizing_h), Image.NEAREST)
w, h = binary.size
# Convert to Numpy array - because that's how images are best stored and processed in Python
nim = np.array(binary)
mat = []
# Print that puppy out
for r in range(h):
line = []
for c in range(w):
line.append(nim[r, c])
mat.append(line)
count=0
"""
print "\n\n"
for i in range(mat.__len__()):
count+=1
print mat[i]
print "\n"
"""
return mat
except:
print("Couldn't find path in images directory.")
print("For your Attatntion, this is the path to put your layouts:")
print path
print "try putting your layout there."
def paintRout(self, gene):
layout_copy = [row[:] for row in self.layout_data]
line = self.SOURCE_COORDINATE[0]
column = self.SOURCE_COORDINATE[1]
layout_copy[line][column] = 6
for action in gene:
# goal, do step and stop counting
if (line==self.DESTINATION_COORDINATE[0]) and (column==self.DESTINATION_COORDINATE[1]):
layout_copy[line][column] = 8
break
#do the action {'L','R','U','D'}
if action== 'L':
column-=1
elif action== 'R':
column+=1
elif action== 'U':
line-=1
elif action== 'D':
line+=1
#out of bounds
if line<0:
line+=1
elif line>= self.LAYOUT_LINES:
line-=1
if column<0:
column+=1
elif column>= self.LAYOUT_COLUMNS:
column-=1
layout_copy[line][column] = 7
layout_copy[line][column] = 8
print "\n\nRout Visualization :\n"
for i in range(layout_copy.__len__()):
print layout_copy[i]
print "\nend"
return layout_copy
def simulateRoute(self, route):
"""
Returns a tuple of (distance, repeated_nodes, obstacles, final_point, is_out_of_bound).
Distance will be infinity if the route is invalid (are taking us out of scope, or not reaching
the destination)
"""
source = self.SOURCE_COORDINATE
destination = self.DESTINATION_COORDINATE
NOT_REACHED = float('inf')
if source == destination:
return 0, 0, 0, source, False
point = source
steps = 0
bonus = 0
revisit = 0
obstacles = 0
initial_distance = self.manhattanDistance(source,destination)
points_visited = [point]
for action in route:
steps += 1
new_distance = self.manhattanDistance(point,destination)
if new_distance < initial_distance:
bonus +=1
initial_distance = new_distance
else:
bonus-=1
if action == "L":
point = [point[0], point[1]-1]
elif action == "R":
point = [point[0], point[1] + 1]
elif action == "U":
point = [point[0]-1, point[1]]
elif action == "D":
point = [point[0]+1, point[1]]
else:
break
#breaking out situations
if point == destination:
return steps ,3*bonus , revisit, obstacles, point, False
if point[0] < 0 or point[0] >= self.LAYOUT_LINES or point[1] < 0 or point[1] >= self.LAYOUT_COLUMNS:
# out of bounds, illegal move
return NOT_REACHED ,bonus , revisit, obstacles, point, True
#count obstacles
if self.layout_data[point[0]][point[1]]==0:
obstacles += 1
#count visited
if point in points_visited:
revisit += 1
else:
points_visited.append(point)
return NOT_REACHED ,bonus , revisit, obstacles, point, False
def manhattanDistance(self, xy1, xy2):
"Returns the Manhattan distance between points xy1 and xy2"
return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
|
0585b33867eaaa8a59059a63b4cc670f1bd4b615 | michaelRobinson84/CP1404_semester2 | /cp1404practicals/prac_09/sort_files_2.py | 1,503 | 4.125 | 4 | import shutil
import os
def main():
os.chdir("FilesToSort")
lst_file_extensions = []
for directory_name, subdirectories, filenames in os.walk('.'):
for filename in filenames:
str_file_extension = get_file_extension(filename)
if str_file_extension not in lst_file_extensions: # If we haven't dealt with this file type before
lst_file_extensions.append(str_file_extension)
str_user_input = input("What category would you lie to sort {} files into?".format(str_file_extension))
try:
os.mkdir(str_user_input)
except FileExistsError:
pass
for filename2 in filenames: # For each file in the current directory
if get_file_extension(filename2) == str_file_extension: # If the file's extension matches the file
# extension we are currently working on
shutil.move(filename2, str_user_input) # Move the file where the user says for it
# to go
def get_file_extension(filename):
index = 0
for char in filename:
if char != ".":
index += 1
else:
index += 1
file_extension = filename[index:]
return file_extension
main()
|
e8b75cdc4e175ac09576106e68aaebe00cfd8a81 | lucianojunnior17/Python | /Curso_Guanabara/aula72.py | 507 | 3.875 | 4 | cont = ('zero','um','dois','três','quatro','cinco','seis','sete','oito',
'nove','10','onze','doze','treze','quatorze','quize', 'dezeseis',
'dezessete','dezoito','dezenove','vinte','vinte um ','vinte dois',
'vinte três','vinte Quatro','vinte Cinco')
while True:
num = int(input('Digite um número entre 0 e 25 : '))
if 0 <= num <= 25:
break
else:
num = cont
print('Tente novamente : ', end='')
print(f'Você digitou o número {cont[num]}') |
1c13ac630b8d73c06c0fa14adb0c08669a7ef2d2 | helsonxiao/exercises | /dictionary.py | 413 | 4.25 | 4 | dictionary = {}
while True:
user_action = input("Add or look up a word (a/l)?")
if user_action == "a":
type_word = input("Type the word:")
type_definition = input("Type the definition:")
dictionary[type_word] = type_definition
elif user_action == "l":
type_word = input("Type the word:")
print(dictionary[type_word])
else:
print("Please enter a/l.") |
f9a21b792c1bc1a46163196eb52ce918fe3722c8 | Juanjo-M/Primero | /Lab3219-1.py | 309 | 4.21875 | 4 | #print ("¿Que palabra desea escribir?"):
#P=str(input(""))
P = input("¿Que palabra desea escribir? ")
while (P !="chupacabra"):
#print("Puede seguir escribiendo palabras")
if (P == "chupacabra"):
break
P = input("¿Que palabra desea escribir? ")
print("Aqui se detiene el bucle") |
6012313385274520a4dadff02ff1fbbeb5037f9a | KrisR15/Knots_and_Crosses | /Knots_&_Crosses.py | 6,157 | 3.953125 | 4 | import random
def display_board(board): #Create a game board
print("\n"*100)
print(" "+board[1]+" | "+board[2]+" | "+""+board[3]+" ")
print("-----------")
print(" "+board[4]+" | "+board[5]+" | "+""+board[6]+" ")
print("-----------")
print(" "+board[7]+" | "+board[8]+" | "+""+board[9]+" ")
def player_input(): #Decide player markers
player1_marker = "null"
player2_marker = "null"
marker_option_list = ["X","O"]
while player1_marker not in marker_option_list:
player1_marker = input("Player 1, would you like to be 'X' or 'O'? ").upper()
if player1_marker not in marker_option_list:
print("Sorry, invalid selection. Please input 'X' or 'O'")
else:
break
if player1_marker == "X":
player2_marker = "O"
else:
player2_marker = "X"
return(player1_marker,player2_marker)
def place_marker(board, marker, position): #Make a move
board[position] = marker
def win_check(board, mark): #Check if either player has won
#ROW CHECKS
return ((board[1] == mark and board[2] == mark and board[3] == mark) or
(board[4] == mark and board[5] == mark and board[6] == mark) or
(board[7] == mark and board[8] == mark and board[9] == mark) or
#COLUMN CHECKS
(board[1] == mark and board[4] == mark and board[7] == mark) or
(board[2] == mark and board[5] == mark and board[8] == mark) or
(board[3] == mark and board[6] == mark and board[9] == mark) or
#DIAGONAL
(board[1] == mark and board[5] == mark and board[9] == mark) or
(board[3] == mark and board[5] == mark and board[7] == mark))
def choose_first(): #randomly decide who starts
first_player = random.randint(1,2)
if first_player == 1:
return "Player 1"
elif first_player == 2:
return "Player 2"
def space_check(board, position): #check if the position is empty
return board[position] == " "
def full_board_check(board): #check if the board is full (tie check)
marker_options = ["X", "O"]
fill_counter = 0
for position in board:
if position == "X" or position == "O":
fill_counter += 1
else:
pass
return fill_counter == 9
def player_choice(board): #choose next move
position = int(input("Choose your next position: (1-9) "))
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
print("Invalid selection. Position is either not an option or already taken.")
position = int(input('Choose your next position: (1-9) '))
return position
def replay(): #Decide if you want to play again
response = input("Would you like to play again (Yes or No)?: ").lower()
replay_options = ["yes", "no"]
while True:
if response not in replay_options:
print("Invalid input, please type 'Yes' or 'No'.")
response = input("Would you like to play again (Yes or No)?: ").lower()
continue
elif response == "yes":
return True
else:
return False
#While loop to keep running the game
print("Welcome to Knots & Crosses!")
while True:
#Play The Game
#Set Everything Up (Board, whos first and marker choice)
the_board = [" "]*10 #Empty blank board
player1_marker, player2_marker = player_input() #Tuple unpacking to assign markers
turn = choose_first() #Decides who is going to play first
print(f"\n{turn} will play first")
play_game = input("Ready to play? 'Yes' or 'No': ").lower()
if play_game == "yes":
game_on = True
else:
game_on = False
#Game Play
while game_on == True:
#Player 1's turn
if turn == "Player 1":
#Show the board
display_board(the_board)
#Choose a position
print("\nPlayer 1")
position = player_choice(the_board)
#Place the marker on the position
place_marker(the_board,player1_marker,position)
#Check if they won
if win_check(the_board,player1_marker):
display_board(the_board)
print("PLAYER 1 WINS!")
game_on = False
#or check if there is a tie
else:
if full_board_check(the_board):
display_board(the_board)
print("THE GAME IS A TIE!")
game_on = False
#No tie or no win next players turn
else:
turn = "\nPlayer 2 plays first"
#Player 2's turn
else:
#Show the board
display_board(the_board)
#Choose a position
print("\nPlayer 2")
position = player_choice(the_board)
#Place the marker on the position
place_marker(the_board,player2_marker,position)
#Check if they won
if win_check(the_board,player2_marker):
display_board(the_board)
print("PLAYER 2 WINS!")
game_on = False
#or check if there is a tie
else:
if full_board_check(the_board):
display_board(the_board)
print("THE GAME IS A TIE!")
game_on = False
#No tie or no win next players turn
else:
turn = "Player 1"
#break out of game while loop on replay()
if not replay():
break
|
0e70290950aabafe8b9e6c5a0f2f44863186062c | RaskoANML/maths | /Python/LeoExoPoly1d.py | 424 | 3.5625 | 4 | """
First trial with data plotting
"""
import numpy as np
import matplotlib.pyplot as plt
p = np.poly1d([666,0,1,2])
x = np.arange(-20,60,1)
print "Voici les antecedants :", x
print "Voici le polynome", p
# calcul des ordonnees
y = p(x)
print "Voici les ordonnees correspondant a l'interval -20 a 59: ", y
plt.plot(x, y, color ='blue', linewidth=2.5, linestyle="--")
plt.legend("polynome 666 x^3 + x + 2")
plt.show()
|
f23398f7af6a1d7625dcab2dab3103b6fc93cd8b | Harry-Ramadhan/Basic-Phthon-5 | /casting.py | 377 | 3.78125 | 4 | # float to integer
# x = 1.99999
# print (x)
# print (type(x))
# y = int (x)
# print (y)
# print(type(y))
# int to float
# a = 100
# print(a)
# print(type(b))
# b = float(a)
# print(b)
# print(type(b))
# string to float
# x = "4.5"
# print(x)
# print(type(x))
# y = float (x)
# print(y)
# print(type(y))
# # float to string
# a = 9.999
# print(a)
# print(type(a))
# b =
|
530e7ee280aa40fb04cad40771b0e5549372cd5c | AChen24562/Python-QCC | /Exam2-Review/Review3d-if-loops.py | 311 | 4.3125 | 4 | #3d Loops and Input
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
if num1 < num2:
while num1 <= num2:
print(num1, end="|")
num1 += 1
elif num1 > num2:
for x in range(num1):
print(num1, end="|")
num1 -= 1
else:
print(f"{num1} = {num2}")
|
9a6e7affeb833bbea4288dc31bca0acf3e6042ec | ed-kiryukhin/MITx_6.00.1x | /ProblemSet01/PS01-1.py | 276 | 3.96875 | 4 | ## https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_2/Basic_Problem_Set_1/
## COUNTING VOWELS
## Assume s is a string of lower case characters
count=0
for letter in s:
if letter in "aeiou":
count += 1
print "Number of vowels: %d" % (count)
|
d70f05b74205bbbcb95b03f09e9dc76e6a71ed16 | mayurikpawar/pythonbasic | /data.py | 660 | 4.1875 | 4 | #python program demonstrating list
my_data = ["MY SELF MAYURI KAILAS PAWAR"]
l1 = ["I AM PERSUING BE E&TC FROM SANDIP FOUNDATION","nashik"]
print my_data
print l1
l1.reverse()
print l1
list = ['i am from jalgaon','but i am studying in nashik']
print('index of i am from jalgaon',list.index('i am from jalgaon'))
print(list)
l2 = ['m','a','r','v','e','l','o','u','s']
l2.count(3)
print l2
#output
#['MY SELF MAYURI KAILAS PAWAR']
#['I AM PERSUING BE E&TC FROM SANDIP FOUNDATION', 'nashik']
#['nashik', 'I AM PERSUING BE E&TC FROM SANDIP FOUNDATION']
#('index of i am from jalgaon', 0)
#['i am from jalgaon', 'but i am studying in nashik']
#['m', 'a', 'r', 'v', 'e', 'l', 'o', 'u', 's']
|
cd86db56f077762c121b7b85288385e5ef76039c | skuld1020/PY4E | /PY4E/triangle_area.py | 1,045 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 22:37:06 2020
@author: Happy sunday
"""
"""給三點求三角形邊長和面績"""
def area(a,b,c):
s = (a+b+c)/2
A = (s*(s-a)*(s-b)*(s-c))**(1/2)
return A
def length(x1,y1,x2,y2):
L = ((x1-x2)**2+(y1-y2)**2)**(1/2)
return L
A_x1 = input('Please input the x of A:')
A_y1 = input('Please input the y of A:')
B_x2 = input('Please input the x of B:')
B_y2 = input('Please input the y of B:')
C_x3 = input('Please input the x of C:')
C_y3 = input('Please input the y of C:')
try:
x1 = float(A_x1)
y1 = float(A_y1)
x2 = float(B_x2)
y2 = float(B_y2)
x3 = float(C_x3)
y3 = float(C_y3)
except:
print('Please enter the float')
quit()
AB = length(x1,x2,y1,y2)
BC = length(x2,x3,y2,y3)
AC = length(x1,x3,y1,y3)
A = area(AB,BC,AC)
print('A is','(',x1,',',y1,')')
print('B is','(',x2,',',y2,')')
print('C is','(',x3,',',y3,')')
print('The lengths are',AB,BC,AC)
print('The area for ABC is',A)
|
3a02b435c8dfc37ca835cfd443618bce0fa0b180 | KingJMS1/EEInformation | /Add.py | 221 | 3.546875 | 4 | from time import time
b = 5
c = 3
d = 2
initime = time()
for x in range(100000):
b = (c + d)%100
c= (b + d)%1000
d= (c + b + d)%500
b= (d - c)%150
fintime = time()
print("TIME: " + str(fintime - initime)) |
91d5f2188d3b1fd32e2df4ef54452ddf654a069e | Noksis/Python | /Sara/Task 5.py | 1,120 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame()
file = open('Input.csv','r')
df = pd.read_csv(file)
Answer = []
# First task (Index: 0,1,2)
Answer.append("Size:")
Answer.append(df.size)
Answer.append("10:")
Answer.append(df[:10])
Answer.append("Random 10:")
Answer.append(df.sample(n=10))
# Second task (Index: 3)
Answer.append("NaNs:")
Answer.append(df.isna().sum())
# 3 task (Index: 4)
Answer.append("IDs:")
Answer.append(len(pd.unique(df.ID)))
# 4 task (Index: 5)
# (2 is Women and 1 is Mens)
SEX = df['SEX'].value_counts(normalize=True) * 100
Answer.append("2 = women, 1 = mens")
Answer.append(SEX)
# 5 task
fig = plt.figure()
plt.title('A Horizontal Bar Chart')
plt.xlabel("Age")
plt.ylabel("Amount")
plt.grid(1)
plt.hist(df.AGE)
# 6 task (Index 6,7)
D = df["default.payment.next.month"].sum()
ND = len(df) - D
Answer.append("default")
Answer.append(D)
Answer.append("normal")
Answer.append(ND)
fig = plt.figure()
plt.pie([D,ND],labels = ["default","No default"],autopct='%1.1f%%')
plt.title('Pie of defaults')
plt.grid(True)
for i in Answer:
print(i)
plt.show()
|
0b504117f2537045f1ed76550798c36e5965e0b1 | NikolasMatias/urionlinejudge-exercises | /Iniciante/Python/exercises from 2001 to 2600/exercise_2493.py | 1,481 | 3.734375 | 4 | def is_calculo_possible(valor_a, valor_b, resultado_calculo):
return valor_a+valor_b == resultado_calculo or valor_a-valor_b == resultado_calculo or valor_a*valor_b == resultado_calculo
def test_calculo(calculo, expressao_escolhida):
valor_a,valor_b, resultado_calculo = [int(x) for x in calculo.replace('=', ' ').split()]
if expressao_escolhida == 'I':
return not is_calculo_possible(valor_a, valor_b, resultado_calculo)
if expressao_escolhida == '+':
return valor_a+valor_b == resultado_calculo
if expressao_escolhida == '-':
return valor_a-valor_b == resultado_calculo
if expressao_escolhida == '*':
return valor_a*valor_b == resultado_calculo
while True:
try:
qtdeExpressoes = int(input())
expressoes = [input() for x in range(qtdeExpressoes)]
respostaJogadores = [input() for x in range(qtdeExpressoes)]
jogadoresErrados = []
for resposta_jogador in respostaJogadores:
nome_jogador, indice, resposta = resposta_jogador.split()
if not test_calculo(expressoes[int(indice)-1], resposta):
jogadoresErrados.append(nome_jogador)
if len(jogadoresErrados) == 0:
print('You Shall All Pass!')
elif len(jogadoresErrados) == len(respostaJogadores):
print('None Shall Pass!')
else:
jogadoresErrados.sort()
print(' '.join(jogadoresErrados))
except EOFError:
break |
ee78ab4299708bdaa37f2acbf193a01ec7e91dbc | C-Powers/AutomateTheBoringStuff | /truthy_and_fasly.py | 595 | 4.5625 | 5 | #this code looks at truthy and falsey values.
#no boolean operators are used, but if we enter a name, it's "truthy" because
#we did input something
#if we dont input a name, it's falsey, because we did not input a name
name=raw_input("Please enter a name: ")
if name:
print "Thank you so much for entering a name. :]"
else:
print "you did not enter a name :["
'''
Please note that the above method is not particularly good. The best way to do it
would be by using an operator, such as !=. So, it would look like:
if name !=''
which means, that if the name input is not blank.
'''
|
b9d405a29353245bc80d8c9b9b15bf48f38d9c3b | gefranco/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 207 | 3.5625 | 4 | #!/usr/bin/python3
import json
def save_to_json_file(my_obj, filename):
with open(filename, mode="w", encoding="utf-8") as myFile:
json_obj = json.dumps(my_obj)
myFile.write(json_obj)
|
9be94a2011df44d9c00859fe28784a90589ea48b | wellingtongoncalves/Python | /desafio010.py | 143 | 3.796875 | 4 | carteira = float(input('Quanto você tem na carteira: '))
dolares = carteira / 3.27
print('Você pode comprar {:.2f} dolares'.format(dolares)) |
95a7f62ab6a223fae447c33adfd5cff3b31b8af4 | artneuronmusic/Blog_AcceptanceTesting | /app.py | 1,667 | 3.765625 | 4 | from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
posts = []
@app.route('/') #its show the homepage after url
def homepage():
return render_template('home.html') #will return the page: home.html
@app.route('/blog') #now in blog page
def blog_page():
return render_template('blog.html', posts=posts) #it might have posts after adding it later
@app.route('/post', methods=['GET', 'POST']) #go to the create page which is entitled with post, in this one, the server needs to receive input and post it.
def add_post():
if request.method == 'POST': #if the request of the func is equal to "POST, then input the forms for title and content
title = request.form['title']
content = request.form['content']
global posts #why need global? we have posts in the beginning.
posts.append({ #add materials in posts
'title': title,
'content': content
})
return redirect(url_for('blog_page')) #everytime return to the blog_page, not blog
return render_template('new_post.html') #create a new page for new_post
@app.route('/post/<string:title>') #in the post section, we have the data of the new input
def see_post(title):
global posts #the collection
for post in posts: # among those posts, if the one u want is found, then show the page
if post['title'] == title:
return render_template('post.html', post=post)
return render_template('post.html', post=None) #otherwise, show nothing
if __name__ == '__main__':
app.run()
|
0d1c2ac6bf562fbf71615a82ac83d1cff86ea1d9 | CppChan/Leetcode | /medium/mediumCode/BinaryTree/DistanceOfTwoNodes.py | 1,393 | 3.6875 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def distance(self, root, k1, k2):
if root == k1:return self.findnode(root, k2,0)
if root == k2: return self.findnode(root, k1,0)
return self.findcommon(root, k1, k2)[0]
def findnode(self, root, k,depth):
if root == k: return depth
if not root: return 0
left = self.findnode(root.left, k, depth+1)
right = self.findnode(root.right, k, depth+1)
if left == 0: return right
else: return left
def findcommon(self,root, k1, k2):
if not root:return (0, False)
if root == k1 or root == k2: return (0, True)
left = self.findcommon(root.left, k1, k2)
right = self.findcommon(root.right, k1, k2)
if left[1] and right[1]: return(left[0]+right[0]+2, False)
if left[1]: return(left[0]+1, True)
if right[1]: return(right[0]+1, True)
if not left[1] and not right[1]:
if left[0]>0:return (left[0], False)
if right[0]>0: return (right[0], False)
return(0, False)
if __name__ == "__main__":
s = Solution()
a = TreeNode(1)
# b = TreeNode(2)
c = TreeNode(3)
# d = TreeNode(4)
# e = TreeNode(5)
# f = TreeNode(6)
# g = TreeNode(7)
# a.left = b
a.right = c
# b.left = d
# b.right = e
# c.left = f
# c.right = g
print s.distance(a, a, c)
|
18400af13b65f17c94f4e27c2a25319ded04df08 | WD2016GitBuild/iPython | /itchat/timer.py | 507 | 3.53125 | 4 | #coding=utf8
import datetime
import time
def doSth():
print("acb")
# 一般网站都是1:00点更新数据,所以每天凌晨一点启动
def main(h=1,m=0):
while True:
now = datetime.datetime.now()
print(now.hour)
print(now.minute)
# print(now.hour, now.minute)
if now.hour == h and now.minute == m:
doSth()
# 每隔60秒检测一次
time.sleep(60)
if __name__ == "__main__":
main() |
531ac21c7675a1541892a43afa816412db3cdabc | venanciomitidieri/Exercicios_Python | /081 - Extraindo dados de uma Lista.py | 841 | 4.1875 | 4 | # Exercício Python 081 - Extraindo dados de uma Lista
# Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
# A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.
valores = list()
while True:
valores.append(int(input('Digite um valor: ')))
resp = str(input('Deseja continuar? [S/N] ')).strip().upper()
if resp in 'N':
break
print('-=' * 30)
print(f'Os valores digitados foram: {valores}')
print(f'O tamanho da lista é: {len(valores)}')
valores.sort(reverse=True)
print(f'A lista em ordem descresente será: {valores}')
if 5 in valores:
print('O valor 5 faz parte da lista.')
else:
print('O valor 5 não foi encontrado na lista.')
|
d834259aff6b772dd4de91b08ffd036ca61e882a | dushabella/Introduction_to_Bioinformatics | /03_genome_reconstruction/project3.py | 5,537 | 3.640625 | 4 | """
Mini project #3:
---------------
A project is focused on finding the minimum length k of k-mers for which it is possible to obtain unique cyclic genome.
It bases on constructing de Bruijn graph with k-mers on a nodes, which indeed is a solution of Eulerian path problem.
Good source of knowledge:
http://www.bioinformatika.matf.bg.ac.rs/predavanja/literatura/Phillip%20Compeau,%20Pavel%20Pevzner%20-%20Bioinformatics%20Algorithms_%20An%20Active%20Learning%20Approach.%201-Active%20Learning%20Publ.%20(2015).pdf
[pages 121-138]
"""
from typing import Dict, List, Set, Tuple
from sys import getrecursionlimit, setrecursionlimit
def read_file(path: str) -> Dict:
""" Reading genes from a file into a dictionary
in which keys represent a genome name,
and a values - the genomes. """
genomes = dict()
dict_hlpr = ""
with open(path, 'r') as file:
for line in file:
if line.startswith(">"):
dict_hlpr = line[2:-1]
# print(dict_hlpr)
else:
genomes[dict_hlpr] = line[:-1]
# print(line[:-1])
return(genomes)
def composition(genomes: str, k_len: int) -> List[str]:
"""
Takes a circular genes and divide it for all possible k-mers (fragments) of a size of "k-mer" parameter
and returns a list of k-mers that "wrap around" the end.
For example:
in: composition(“ATACGGTC”, 3)
out: [“ATA”, “TAC”, “ACG”, “CGG”, “GGT”, “GTC”, “TCA”, “CAT”]
:param gene: gene for reconstruction
:param k_len: size of each divided kmer (fragment)
:return fragments: list of kmers """
fragments = list()
length = len(genomes)
hlpr = ""
for i in range(length):
hlpr = genomes[i : i+k_len]
len2 = len(hlpr)
if len2 < k_len:
hlpr = hlpr + genomes[: k_len-len2]
fragments.append(hlpr)
return(fragments)
def simple_reconstruction(kmers: List[str]) ->str: #->List[str]:
"""
Reconstruction of a circular genome of k-mers
For example:
circular string assembled from the cycle "AC" -> "CT" -> "TA" is simply (ACT)
:param kmers: A list of mers
:return result: circular string """
result = ""
i = 0
for kmer in kmers:
result += kmer[-1]
i += 1
return(result)
def assembly(kmers: List[str], assembled: List[str], found_genomes: Set[str]) -> Set[str]:
"""
Recursive function for genome assembly using k-mers as edges of de Bruijn graph and prefixes/suffixes as nodes.
It solves Eulerian path problem in effect.
:param kmers: list of k-mers of genome sequence
:param assembled: [RECURSION PARAM] put empty list here
:param found_genomes: [RECURSION PARAM] put empty set here
:return found_genomes: genomes that might be constructed from given fragments. """
if len(kmers) == 0: # end
new_genome = simple_reconstruction(assembled)
found_genomes.add(new_genome)
return found_genomes
elif len(assembled) == 0: # begin
assembled.append(kmers[0])
found_genomes = assembly(kmers[1:], assembled, found_genomes)
else:
possible_to_join_id = [i for i, mer in enumerate(kmers) if mer[:-1] == assembled[-1][1:]] # if suffix == prefix
for index in possible_to_join_id:
assembled.append(kmers[index])
found_genomes = assembly(kmers[:index] + kmers[index+1:], assembled, found_genomes)
del assembled[-1]
return found_genomes
def is_same_as_original(original: str, assembled: str) -> bool:
"""
Checks if achieved genome assembly is same as original genome.
:param original:
:param created:
:return the_same: True - identical or identical but shifted """
concatenated = assembled + assembled
the_same = original in concatenated
return the_same
def remove_redundant(found_genomes: Set[str]) -> List[str]:
"""
Removes redundant found_genomes genomes (like 'CTGACATA' and 'CATACTGA')
:param found_genomes:
:return result: list with unique found_genomes genome """
found_genomes = list(found_genomes)
i = 0
while i < len(found_genomes):
if any([is_same_as_original(found_genomes[i], found_genomes[k]) for k in range(len(found_genomes)) if i != k]):
del found_genomes[i]
else:
i += 1
return found_genomes
def find_min_k(genome: str, k: int=30) -> str:
"""
Returns minimum k found for building k-mers that will achieve only one unique and correct genome from genome assembly
operation.
Starts from high value of k because the recursive assembly function is getting slow for low k.
:param genome: input genom that is first decomposed for k-mers
:param k: k-mer length from which the searching algorithm starts
:return min_k: minimum found k """
while k > 5:
comp = composition(genome, k)
created = assembly(comp, list(), set())
created = remove_redundant(created)
if len(created) > 1:
return k+1
last = created[0]
k -= 1
return k+1
def main():
setrecursionlimit(getrecursionlimit()*2)
genomes = read_file("genomes.txt")
for key in genomes:
print("____________________________________")
print("Name:", key)
genome = genomes[key]
print("genome:", genome)
min_k = find_min_k(genome)
print("min k: ", min_k)
if __name__ == "__main__":
main() |
f7887648f9e418c6406ff72f9b90938a22d54131 | raunakpalit/myPythonLearning | /venv/setChallenge.py | 429 | 4.40625 | 4 | # Create a program that takes some text and returns a list of
# all the characters in the text that are not vowels, sorted in
# alphabetical order.
#
# You can either enter the text from the keyboard or
# initialise a string variable with the string.
vowels = frozenset("aeiou")
random_text = input("Enter a text: ")
finalSet = set(random_text).difference(vowels)
print(finalSet)
finalList = sorted(finalSet)
print(finalList)
|
afb83515e78ac7f14d0b967d49e332c9d1bf5cea | 89Mansions/AI_STUDY | /keras/keras54_conv1d_09_cifar10.py | 2,952 | 3.796875 | 4 | # Dnn, LSTM, Conv2d 중 가장 좋은 결과와 비교
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
#1. DATA
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print(x_train.shape, y_train.shape) # (50000, 32, 32, 3) (50000, 1)
print(x_test.shape, y_test.shape) # (10000, 32, 32, 3) (10000, 1)
# print(x_train[0])
# print("y_train[0] : " , y_train[0]) # 6
# print(x_train[0].shape) # (32, 32, 3)
# plt.imshow(x_train[0], 'gray') # 0 : black, ~255 : white (가로 세로 색깔)
# plt.imshow(x_train[0]) # 색깔 지정 안해도 나오긴 함
# plt.show()
# print(np.min(x_train),np.max(x_train)) # 0 ~ 255
# x > preprocessing
x_train = x_train.reshape(x_train.shape[0],96,32) / 255.
x_test = x_test.reshape(x_test.shape[0],96,32) / 255.
# y > preprocessing
from tensorflow.keras.utils import to_categorical
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
print(y_train.shape) # (50000, 10)
print(y_test.shape) # (10000, 10)
#2. Modeling
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv1D, Flatten, MaxPool1D, Dropout
model = Sequential()
model.add(Conv1D(filters=64,kernel_size=3,padding='same',\
activation='relu',input_shape=(x_train.shape[1],x_train.shape[2])))
model.add(Dropout(0.2))
model.add(Conv1D(filters=64,kernel_size=3,padding='same'))
model.add(Dropout(0.3))
model.add(MaxPool1D(pool_size=2))
model.add(Conv1D(filters=128,kernel_size=3,padding='same'))
model.add(Dropout(0.4))
model.add(MaxPool1D(pool_size=2))
model.add(Conv1D(filters=128,kernel_size=3,padding='same'))
model.add(Dropout(0.5))
model.add(MaxPool1D(pool_size=2))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(Dense(512,activation='relu'))
model.add(Dense(10, activation='softmax'))
# model.summary()
#3. Compile, Train
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
modelpath = '../data/modelcheckpoint/k54_9_cifar10_{epoch:02d}-{val_loss:.4f}.hdf5'
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['acc'])
es = EarlyStopping(monitor='val_loss', patience=5, mode='max')
cp = ModelCheckpoint(filepath=modelpath,monitor='val_loss', save_best_only=True, mode='auto')
model.fit(x_train, y_train, epochs=70, batch_size=32, validation_split=0.2, callbacks=[es, cp])
#4. predict, Evaluate
loss, acc = model.evaluate(x_test, y_test, batch_size=32)
print("loss : ", loss)
print("acc : ", acc)
print("y_test : ", np.argmax(y_test[-5:-1],axis=1))
y_pred = model.predict(x_test[-5:-1])
print("y_pred : ", np.argmax(y_pred,axis=1))
# CNN
# loss : 9.670855522155762
# acc : 0.10000000149011612
# ModelCheckPoint
# loss : 1.1197590827941895
# acc : 0.6021000146865845
# y_test : [8 3 5 1]
# y_pred : [3 3 3 0]
# Conv1D
# loss : 1.9518097639083862
# acc : 0.4715999960899353
# y_test : [8 3 5 1]
# y_pred : [8 5 5 4] |
2e991dce3e99d8bd078e0d06d3f8de2a90e7cec2 | cp4011/Algorithms | /New_Interview/排序算法/10_桶排序.py | 2,838 | 4.3125 | 4 | """ 桶排序(Bucket Sort)
1. 设置一个定量的数组当作空桶;
2. 遍历输入数据,并且把数据一个一个放到对应的桶里去;
3. 对每个不是空的桶进行排序;
4. 从不是空的桶里把排好序的数据拼接起来。
桶排序实际上是计数排序的推广,但实现上要复杂许多。
桶排序先用一定的函数关系将数据划分到不同有序的区域(桶)内,然后子数据分别在桶内排序,之后顺次输出。
当每一个不同数据分配一个桶时,也就相当于计数排序。
假设n个数据,划分为k个桶,桶内采用快速排序,时间复杂度为O(n)+O(k * n/k*log(n/k))=O(n)+O(n*(log(n)-log(k))),
显然,k越大,时间复杂度越接近O(n),当然空间复杂度O(n+k)会越大,这是空间与时间的平衡。
桶排序最好情况下使用线性时间O(n),桶排序的时间复杂度,取决与对各个桶之间数据进行排序的时间复杂度,
因为其它部分的时间复杂度都为O(n)。很显然,桶划分的越小,各个桶之间的数据越少,排序所用的时间也会越少。但相应的空间消耗就会增大。
"""
def BucketSort(lst):
##############桶内使用快速排序
def QuickSort(lst):
def partition(arr, left, right):
key = left # 划分参考数索引,默认为第一个数,可优化
while left < right:
while left < right and arr[right] >= arr[key]:
right -= 1
while left < right and arr[left] <= arr[key]:
left += 1
(arr[left], arr[right]) = (arr[right], arr[left])
(arr[left], arr[key]) = (arr[key], arr[left])
return left
def quicksort(arr, left, right): # 递归调用
if left >= right:
return
mid = partition(arr, left, right)
quicksort(arr, left, mid - 1)
quicksort(arr, mid + 1, right)
# 主函数
n = len(lst)
if n <= 1:
return lst
quicksort(lst, 0, n - 1)
return lst
######################
n = len(lst)
big = max(lst)
num = big // 10 + 1
bucket = []
buckets = [[] for i in range(0, num)]
for i in lst:
buckets[i // 10].append(i) # 划分桶
for i in buckets: # 桶内排序
bucket = QuickSort(i)
arr = []
for i in buckets:
if isinstance(i, list):
for j in i:
arr.append(j)
else:
arr.append(i)
for i in range(0, n):
lst[i] = arr[i]
return lst
x = input("请输入待排序数列:\n")
y = x.split()
arr = []
for i in y:
arr.append(int(i))
arr = BucketSort(arr)
# print(arr)
print("数列按序排列如下:")
for i in arr:
print(i, end=' ')
|
bfa2301b4152e8ba54f19eb8afe20514ecb6813e | 2KNG/old_freshman | /python_source/수업/210401.py | 2,798 | 3.5 | 4 | # # # # g = [30,10,20]
# # # # print(g)
# # # # print(g[2])
# # # # import turtle as t
# # # # t. shape ('turtle')
# # # # t. speed (0)
# # # # a=['red','orange','yellow','green','blue','black' ]
# # # # t. begin_fill()
# # # # for i in range(300):
# # # # t. fd(i)
# # # # t. rt(i)
# # # # if i < len(a):
# # # # t. color(a[i])
# # # # else :
# # # # t. color(a[i%5])
# # # # t.end_fill()
# # # t= {1001:"홍길동", 1002:"이기자"}
# # # print(t[1001])
# # # print(t.get(1001))
# # # print(1002 in t)
# # # t[1003]="우리집"
# # # t[1001]="강아지"
# # # print(t)
# # # del t[1003]
# # # print(t)
# # # print(t.keys())
# # # print(t.values())
# # # print(t.items())
# # # print(t)
# # # a,b = set(t)
# # # print(a)
# # # print(b)
# # # b=set(a)
# # # primt(b)
# x = {"홍길동", "최고야", "이기자"}
# y = {"최고야", "이민호", "박호보"}
# print(x & y) #and
# print(x | y) #or
# a = x & y
# print(a)
# b = x | y
# print(b) # 순서가 없다
# x.add("단비")
# print(x)
# k = {"뉸뉴뉴뉸ㄴ뉴ㅠ":"우리집강아지"}
# print(k)
# x = list(x)
# print(x)
# y= tuple(y)
# print(y)
# k['단비'] = '우리집강아지'
# print(type(x))
# print(type(y))
# print(type(k))
# from random import*
# id = range(1,46)
# print(id)
# print(type(id))
# id=list(id)
# print(type(id))
# print(id)
# choice=sample(id,6)
# print(choice)
# print(choice[0])
# print(choice[1:])
# a, b = map(int, input(). split())
# print(a+b)
# print(a-b)
# print(a*b)
# print(a/b)
# print(a//b)
# print(a%b)
# weather = input("오늘 날씨는 비 or 눈 or 활사")
# temp = int(input("기온은 어때요? 정수입력"))
# if weather=="비" or weather=="눈":
# print("우산준비")
# elif weather=="황사":
# print("마스크준비")
# else :
# print("준비물이 필요 없음")
'''
3개의 정수를 입력받아서
평균(점수)을 구한다
평균이 90이상 "A학점:,# 평균이 90이상 "B학점"
평균이 70이상 "C학점, 그외는 "F학점" 출력
평균이 60점 이상이고, 모든 정수가 40점 이상이면 "합격"출력"
평균이 60점 미만이거나, 한 과목이라도 40미만이면 "불합격" 출력
'''
#학번 : 2161110053 #이름 : 김강현
a, b, c = map(int, input().split())
avg = (a+b+c)/3
if 60 <= avg and 40 <= a and 40 <= b and 40 <= c :
print("합격")
if avg>=90 :
print("A학점")
elif avg>=80 :
print("B학점")
elif avg>=70 :
print("C학점")
else :
print("F학점")
else :
print("불합격")
'''
문제 2. 3개의 정수를 입력받아서
평균을 구하고}
평균이 60점 이상이거, 모든 정수가 40점 이상이면 "합격"출력"
평균이 60점 미만이거나, 한 과목이라도 40미만이면 "불합격" 출력
'''
|
e42f13fa50de819f49b2a09086aee196a71e1b52 | 31more/Homework_python_1 | /hometask2_ready.py | 7,040 | 4.21875 | 4 | """
For и range, которые мы изучили
в предыдущем файле, можно использовать
для обращения к элементам списка
по индексам.
Немного про списки и индексы
l = [6,2,5,6,2,1,9] такие индексы
0 1 2 3 4 5 6
Если мы хотим получить доступ к элементам
списка, нам необходимо обращаться
по индексам. """
print("""Например 3-им элементом
списка выше будет:
""")
l = [6, 2, 5, 6, 2, 1, 9]
print(l[3])
##########################################
# TODO задание 1
##########################################
"""Выведите 5тый элемент списка"""
print("Результат задания 1")
l = [6, 2, 5, 6, 2, 1, 9]
print(l[4])
##########################################
# конец задания
##########################################
"""
Так же с помощью обращения по индексу в списке
можно не только узнавать значение списка,
но и изменять его, например заменим 4ое значение"""
print("Старый l ", l)
l[4] = 356
print("Новый l", l)
"""
Теперь увеличим 5ое значение в 2 раза"""
print("Старый l", l)
l[5] = l[5] * 2
print("Новый l", l)
##########################################
# TODO задание 2
##########################################
"""Замените предпоследний элемент списка на 10"""
print("Результат задания 2")
l = [6, 2, 5, 6, 2, 1, 9]
print("Старое значение: ", l[5])
l[5] = 10
print("Список после изменения", l)
##########################################
# конец задания
##########################################
##########################################
# TODO задание 3
##########################################
"""Уменьшите первый элемент в 3 раза"""
print("Результат задания 3")
l = [6, 2, 5, 6, 2, 1, 9]
l[0] = int(l[0]/3)
print("Список после изменения", l)
##########################################
# конец задания
##########################################
"""
Индексы у списка l любой длинны изменяются от 0
до числа len(l) - 1
То есть выглядят так 0, 1, 2, 3, ..., len(l)
с помощью range, который мы рассматривали раньше
можно получить набор индексов любого списка
Пример:"""
print("""Индексами списка l = [9,3,6,2,4,6,2,4,5,3,2,4,6]
являются числа:
""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(len(l)):
print(i)
"""
в данном случае в range мы начинали с 0, закончили числом
len(l)(не включительно) - то есть как раз последним индексом
и шли с шагом 1"""
print("""
Раз мы можем с помощью такого фора получить
доступ ко всем индексам, значит можем взаисодействовать
со всеми элементами списка. Например вывести их
(как ранее делали другим for)""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(len(l)):
print(l[i])
print("""
Или заменить все на 8
""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
print("Старый l", l)
for i in range(len(l)):
l[i] = 8
print("Новый l", l)
print("""
Или все уменьшить в 4 раза
""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
print("Старый l", l)
for i in range(len(l)):
l[i] = l[i] / 4
print("Новый l", l)
##########################################
# TODO задание 4
##########################################
"""Возвести каждый элемент во вторую степень"""
print("Результат задания 4")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(len(l)):
l[i] = l[i]**2
print("Список после изменения", l)
##########################################
# конец задания
##########################################
##########################################
# TODO задание 5
##########################################
"""Вычесть из каждого элемента результат
выражения 32/5"""
print("Результат задания 5")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(len(l)):
l[i] -= (32/5)
print("Список после изменения", l)
##########################################
# конец задания
##########################################
print("""
Так же как мы влияли на весь список,
так же можно повлиять и на часть,
например увеличит вдвое все элементы, кроме
первого:
""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
print("Старый l", l)
for i in range(1, len(l)):
l[i] = l[i] / 4
print("Новый l", l)
"""
Здесь важна 1 в range - которой раньше не было
"""
print("""
Или можем работать с элементами
с третьего по восьмой, например,
заменим их на 8ки
""")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
print("Старый l", l)
for i in range(3, 8):
l[i] = 8
print("Новый l", l)
"""
Стоит обратить внимание на изменения в range
"""
##########################################
# TODO задание 6
##########################################
"""Прибить к первым 5-ти элементам 16"""
print("Результат задания 6")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(0, 5):
l[i] = 16
print("Список после изменения", l)
##########################################
# конец задания
##########################################
##########################################
# TODO задание 7
##########################################
"""Возвести в степень самого себя (a**a)
числа с индексами от 7 до 11"""
print("Результат задания 7")
l = [9, 3, 6, 2, 4, 6, 2, 4, 5, 3, 2, 4, 6]
for i in range(7,12):
l[i] = l[i]**l[i]
print("Список после изменения", l)
##########################################
# конец задания
########################################## |
acace5e89b8c239d29084761f8075c429f73c18d | z627797668/PAT-B.py | /1001.py | 117 | 3.734375 | 4 | n=input()
ans=0
n=int(n)
while n!=1:
ans+=1
if n%2==0:
n/=2
else:
n=(3*n+1)/2
print(ans)
|
1c8e7c54e3e4071a478ba158a0af43e59102579e | PeterL64/UCDDataAnalytics | /5_Data_Manipulation_With_Pandas/2_Aggregating_Data/6_One_Method_Of_Calculating_Proportion_By_Subsetting_And_Summing.py | 931 | 3.859375 | 4 | # What percentage of sales occurred at each store type
# Calculating grouped summary statistics without using the .groupby() method
# From the sales DataFrame, Walmart has three different store types, A, B and C
import pandas as pd
# Calculate the total weekly_sales over the whole dataset.
sales_all = sales["weekly_sales"].sum()
# Subset for type A stores, calc total weekly sales
sales_A = sales[sales["type"] == "A"]["weekly_sales"].sum() # .agg(sum) gives the same answer
# Subset for type B stores, calc total weekly sales
sales_B = sales[sales['type'] == 'B']['weekly_sales'].sum()
# Subset for type C stores, calc total weekly sales
sales_C = sales[sales['type'] == 'C']['weekly_sales'].sum()
# Get proportion for each type
# Combine the A/B/C results into a list, and divide by sales_all to get the proportion of sales by type
sales_propn_by_type = [sales_A, sales_B, sales_C] / sales_all
print(sales_propn_by_type) |
232feb2fa72867a5ce9c6ae0c3e4f95332383aa2 | hysz/leetcode | /longest_substring.py | 1,885 | 3.640625 | 4 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
'''
We construct a lookup table that allows you to query for next occurence of a character.
We use len(s) to denote a non-existent index.
Ex for string "abab"
{
"a:
{
0: 2,
2: len(s),
-1: 2 // Used to lookup furthest occurence
},
"b":
{
1: 3,
3: len(s)
}
}
'''
# construct lookup
lookup = {}
for i,c in enumerate(s):
if not c in lookup:
lookup[c] = {}
l = lookup[c]
l[i] = len(s)
l[-1] = i
else:
l = lookup[c]
l[l[-1]] = i
l[i] = len(s)
l[-1] = i
# We trying forming a substring from each index `i` in `s`,
# using the lookup table to exit once we hit a repeated character.
longest_substr_len = 0
longest_substr_len_from_i = 0
for i,c in enumerate(s):
idx_of_next_repeating_char = lookup[c][i]
j = i + 1
while j < idx_of_next_repeating_char:
idx_of_next_repeating_char = min(idx_of_next_repeating_char, lookup[s[j]][j])
j += 1
longest_substr_len_from_i = j - i
if longest_substr_len_from_i > longest_substr_len:
longest_substr_len = longest_substr_len_from_i
return longest_substr_len
#print(Solution().lengthOfLongestSubstring(""))
#print(Solution().lengthOfLongestSubstring("a"))
#print(Solution().lengthOfLongestSubstring("abab"))
#print(Solution().lengthOfLongestSubstring("abcabcbb")) |
f9fa69f4d89dae8293c108caacbb123fa4f2244c | quake0day/oj | /sortColors2.py | 1,191 | 3.609375 | 4 | import sys
class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
# write your code here
count = 0
start = 0
end = len(colors) - 1
while count < k:
minium = sys.maxint
maxium = -minium - 1
for i in xrange(start, end):
minium = min(minium, colors[i])
maxium = max(maxium, colors[i])
left = start
right = end
cur = left
while cur <= right:
if colors[cur] == minium:
colors = self.swap(left, cur, colors)
cur += 1
left += 1
elif colors[cur] > minium and colors[cur] < maxium:
cur += 1
else:
colors = self.swap(cur, right, colors)
right -= 1
count += 2
start = left
end = right
return colors
def swap(self, left, right, colors):
tmp = colors[left]
colors[left] = colors[right]
colors[right] = tmp
return colors
a = Solution()
print a.sortColors2([8,1,10,1,8,8,2,4,9,3,8,1,3,3,6,2,5,1,1,7,1,1,3,9,6,4,6,6,7,2], 10) |
d2ee85b8419cce79cfaeadfc47dab7797ade8948 | mjefris16/Muhammad-Jefri-Saputra_I0320066_M-Abyan-Naufal_Tugas7 | /I0320066_soal1_tugas7.py | 996 | 3.765625 | 4 | print("="*40)
judul = "Program Kalimat Sapaan"
center = judul.center(40,"*")
print(center)
print("="*40)
Nama = input("Siapa nama anda: ")
kapital = Nama.capitalize()
print("Nama anda adalah: ", kapital)
sapaan = input("Masukkan kalimat sapaan anda: ")
print("Kalimat sapaan anda: ", sapaan)
print("Jumlah huruf kalimat sapaan anda: ", len(sapaan), "huruf")
sapaan1 = sapaan.upper()
sapaan2 = sapaan.lower()
print("Kalimat sapaan anda dalam huruf kapital: ", sapaan1)
print("Kalimat sapaan anda dalam huruf kecil: ", sapaan2)
a = sapaan.count("a")
i = sapaan.count("i")
u = sapaan.count("u")
e = sapaan.count("e")
o = sapaan.count("o")
print("Jumlah huruf a dalam kalimat sapaan anda = ", a, "huruf")
print("Jumlah huruf i dalam kalimat sapaan anda = ", i, "huruf")
print("Jumlah huruf u dalam kalimat sapaan anda = ", u, "huruf")
print("Jumlah huruf e dalam kalimat sapaan anda = ", e, "huruf")
print("Jumlah huruf o dalam kalimat sapaan anda = ", o, "huruf")
|
6b937beba87cf764239e14aa690e81771e6ac0dd | Eric-Wonbin-Sang/CS110Manager | /2020F_final_project_submissions/madireddysaumit/7395236_main-1.py | 1,914 | 3.5625 | 4 | import csv
import matplotlib.pyplot as plt
import yfinance as yf
date_list = []
price_list = []
with open("NFLX.csv") as csv_file:
for row in list(csv.reader(csv_file))[2:]:
print()
print(row[0])
date_list.append(row[0])
price_list.append(float(row[4]))
with open("AAPL.csv") as csv_file:
for row in list(csv.reader(csv_file))[2:]:
print()
print(row[0])
date_list.append(row[0])
price_list.append(float(row[4]))
with open("DIS.csv") as csv_file:
for row in list(csv.reader(csv_file))[2:]:
print()
print(row[0])
date_list.append(row[0])
price_list.append(float(row[4]))
with open("AMZN.csv") as csv_file:
for row in list(csv.reader(csv_file))[2:]:
print()
print(row[0])
date_list.append(row[0])
price_list.append(float(row[4]))
def get_date_list_and_price_list_from_csv(NFLX):
date_list, close_list = [], []
with open(csv_file_path) as csv_file:
for row in list(csv.reader(csv_file))[1:]:
date_list.append(row[0])
close_list.append(float(row[4]))
return date_list, close_list
def get_date_list_and_price_list_from_csv(AAPL):
date_list, close_list = [], []
with open(csv_file_path) as csv_file:
for row in list(csv.reader(csv_file))[1:]:
date_list.append(row[0])
close_list.append(float(row[4]))
return date_list, close_list
def get_date_list_and_price_list_from_csv(DIS):
date_list, close_list = [], []
with open(csv_file_path) as csv_file:
for row in list(csv.reader(csv_file))[1:]:
date_list.append(row[0])
close_list.append(float(row[4]))
return date_list, close_list
plt.plot(date_list, price_list)
plt.xlabel("Date")
plt.ylabel("Closing price")
plt.title("Best Streaming Stocks")
plt.xticks(rotation=90)
plt.show() |
ae359eab5722da60127ec70c3fe15ce3df7c4567 | Dolantinlist/DolantinLeetcode | /1-50/4*_median_of_arrays.py | 1,047 | 3.59375 | 4 | #There are two sorted arrays nums1 and nums2 of size m and n respectively.
#Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
l = len(nums1) + len(nums2)
if l%2:
return self.find_kth(nums1, nums2, l//2)
else:
return (self.find_kth(nums1, nums2, l//2 - 1) + self.find_kth(nums1, nums2, l//2))/2
def find_kth(self, a, b, k):
if not a:
return b[k]
if not b:
return a[k]
ia, ib = len(a)//2, len(b)//2
ma, mb = a[ia], b[ib]
if ia + ib < k:
if ma > mb:
return self.find_kth(a, b[ib+1:], k - ib - 1)
else:
return self.find_kth(a[ia+1:], b, k - ia - 1)
else:
if ma > mb:
return self.find_kth(a[:ia], b, k)
else:
return self.find_kth(a, b[:ib], k)
print(Solution().findMedianSortedArrays([1,2], [3,4])) |
98028f9379448d78e7c7fe5a0109d8c6947bdcc4 | paolofrd/PROBLEM-5 | /PROBLEM5.py | 1,836 | 3.59375 | 4 | import math #for user-inputs with lib-dependent characteristics
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
user = input('Input function x(n): ')
reses = [] #storage
xn = [] #storage of x(n) variables
gibx = list(range(0,200))
#y(n)
for n in range (0,200):
#y(n) = -1.5x(n) + 2x(n + 1) - 0.5x(n+2)
if n == 0:
#convert string input into a formula that python can utilize
n0 = -1.5*(eval(user)) #evaluate x(n) where n = 0, the result will then be multiplied to -1.5
n = n + 1 #x(n + a); in this case, a = 1
nm1 = 2*(eval(user))
n = n + 2
nm2 = -.5*(eval(user))
res1 = n0 + nm1 + nm2 #compilation of formulas
reses.append(res1) #storing of all values of y(n) into a single list
#y(n) = 0.5x(n + 1) - 0.5x(n-1)
elif n > 0 and n <= 198:
n = n + 1
n0 = .5*(eval(user))
n = n - 1
nm1 = -.5*(eval(user))
res2 = n0 + nm1
reses.append(res2)
#y(n) = 1.5x(n) - 2x(n - 1) + 0.5x(n - 2)
elif n == 199:
n0 = 1.5*(eval(user))
n = n - 1
nm1 = -2*(eval(user))
n = n - 2
nm2 = .5*(eval(user))
res3 = n0 + nm1 + nm2
reses.append(res3)
break #just in case the program enters an endless loop
#x(n) / user-defined function
for n in range(0,200):
xn.append(eval(user)) #evaluate x(n) with values of n ranging from 0 to 199
#plotting
plt.grid() #add grid
plt.xlabel('n elements')
plt.ylabel('x and y elements')
plt.plot(gibx,reses)
plt.plot(gibx,xn)
blu = mpatch.Patch(color = 'blue', label = 'y(n)') #add custom legend
orange = mpatch.Patch(color = 'orange', label = 'x(n)')
plt.legend(handles = [blu,orange]) #apply legend to graph
plt.show() #show graph |
0192eaedd7405159c4b68c5501b620ee6f0588a9 | occ010/aoc2019 | /day3/part1.py | 3,269 | 4 | 4 |
def main():
wire1 = []
wire2 = []
with open("input", 'r') as fp:
wire1 = parse_coordinates(fp.readline())
wire2 = parse_coordinates(fp.readline())
# Loop through all the line segments in wire1 and wire2 to see where they intersect
intersections = []
for i in range(len(wire1) - 1):
for j in range(len(wire2) - 1):
p1 = wire1[i]
q1 = wire1[i + 1]
p2 = wire2[j]
q2 = wire2[j + 1]
if (lines_intersect(p1, q1, p2, q2)):
intersections.append(calculate_intersection(p1, q1, p2, q2))
print("The two wires intersect at the following points:")
print (intersections)
min_dist = 0
for point in intersections:
dist = calculate_manhattan_dist(point)
if (min_dist == 0):
min_dist = dist
elif (min_dist > dist):
min_dist = dist
print("Closest intersection is at distance of {}.".format(min_dist))
def parse_coordinates(line):
paths = line.split(',')
x = y = 0
coordinates = [(x, y)]
for path in paths:
direction = path[0:1]
distance = int(path[1:])
if direction == 'D':
y -= distance
elif direction == 'U':
y += distance
elif direction == 'L':
x -= distance
elif direction == 'R':
x += distance
coordinates.append((x, y))
return coordinates
def lines_intersect(p1, q1, p2, q2):
'''
Checks if the two line segments given by (p1, q1) and (p2, q2) intersects.
Adapted from https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
'''
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
intersect = False
# general case
if (o1 != o2 and o3 != o4):
intersect = True
# Ignore colinear cases for purposes of this puzzle
return intersect
def orientation(p, q, r):
''' Checks orientation of ordered triplet (p, q, r).
Returns:
0 --> points are colinear
1 --> clockwise
2 --> counter-clockwise
'''
value = (q[1] - p[1]) * (r[0] - q[0])
value -= (q[0] - p[0]) * (r[1] - q[1])
if (value == 0):
return 0
elif (value >0):
return 1
else:
return 2
def calculate_intersection(p1, q1, p2, q2):
''' Calculates the intersection point of line segments (p1, q1) and (p2, q2).
Adapted from https://stackoverflow.com/a/1968345
'''
s1_x = q1[0] - p1[0]
s1_y = q1[1] - p1[1]
s2_x = q2[0] - p2[0]
s2_y = q2[1] - p2[1]
s = (-s1_y * (p1[0] - p2[0]) + s1_x * (p1[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y)
t = ( s2_x * (p1[1] - p2[1]) - s2_y * (p1[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y)
(x, y) = (0, 0)
if (s >= 0 and s <= 1 and t >= 0 and t <= 1):
# Collision detected
x = p1[0] + (t * s1_x)
y = p1[1] + (t * s1_y)
return (x, y)
def calculate_manhattan_dist(p):
''' Calculates the Manhattan distance for a given point (p) from origin (0,0) '''
return int(abs(p[0]) + abs(p[1]))
if __name__ == "__main__":
main() |
55bdeabb0b264434185d0b96b67df82699a315ca | swairshah/ml | /sampling/error_estimate.py | 1,960 | 3.546875 | 4 | # Sampling uniformly to calculate error wrt optimal model
# vs sampling with Importance sampling to calculate error wrt
# optimal model. Does one give a 'better' estimate than the other?
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn import datasets
from sklearn.datasets import make_regression
np.random.seed(0)
m = 10000
n = 50
I = 100
r = 10
weighted = True
X, y, coef = make_regression(n_samples = m, n_features = n, noise = 10, coef = True)
lm = LinearRegression()
lm.fit(X,y)
y_pred = lm.predict(X)
e = (y - y_pred)**2
w = e/np.sum(e)
err_base = np.mean(e)
# uniform sampling
unif_errors = []
for i in range(I):
idx = np.random.randint(0,len(X),size=r)
X1 = X[idx,:]
y1 = y[idx]
err = np.mean((lm.predict(X1) - y1)**2)
unif_errors.append(err)
# importance sampling
imp_errors = []
for i in range(I):
idx = np.random.choice(range(len(X)), r, p = w)
w1 = w[idx]
if weighted:
X1 = X[idx,:]/(m*w1[:,None])**0.5
y1 = y[idx]/(m*w1)**0.5
else:
X1 = X[idx,:]
y1 = y[idx]
e = np.mean((lm.predict(X1) - y1)**2)
# The following should be equlivalent to
# dividing x and y by sqrt(m*w1), since we are
# dividing the final error by m*w1.
# doesn't give the same answer.
#X1 = X[idx,:]
#y1 = y[idx]
#e = np.mean((lm.predict(X1) - y1)**2)
#if weighted:
# e = e/(m*w1)
imp_errors.append(e)
print "base error: %.2f" % err_base
print "imp err", np.mean(imp_errors), "uni err", np.mean(unif_errors)
#print "variance importance %.2f" % np.var(imp_errors)
#print "variance uniform %.2f" % np.var(unif_errors)
print "variance importance %.2f" % np.mean((imp_errors - err_base)**2)
print "variance uniform %.2f" % np.mean((unif_errors - err_base)**2)
#plt.subplot(211)
#plt.hist(unif_errors, color="blue")
#plt.subplot(212)
#plt.hist(imp_errors, color="orange")
#plt.show()
|
4f09bc904bbd8c7b7ba00bddbb5efc38ace9d707 | gsy/leetcode | /employee_importance.py | 1,180 | 3.640625 | 4 |
# Employee info
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
class Solution:
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
# 广度遍历,找到所有的下属,然后加上重要性
mapping = {}
for employee in employees:
mapping[employee.id] = employee
ids = [id]
total = 0
while len(ids) > 0:
current = mapping[ids.pop(0)]
total = total + current.importance
ids = ids + current.subordinates
return total
if __name__ == "__main__":
s = Solution()
r = s.getImportance([Employee(1, 5, [2, 3]), Employee(2, 3, []), Employee(3, 3, [])], 1)
assert r == 11
r = s.getImportance([Employee(1, 15, [2]), Employee(2, 10, [3]), Employee(3, 5, [])], 1)
assert r == 30
|
5186fc54db1173b8c5a1db6731fba7ccbbe117ad | jbro321/Python_Basic_Enthusiastic | /Python_Basic_Enthusiastic/Chapter_07/P_07_1_5.py | 457 | 3.78125 | 4 | # Enthusiastic_Python_Basic #P_07_1_5
def main():
num = int(input("값을 입력하세요: "))
if num < 0:
print("입력한 값은 0보다 작습니다.")
elif 0 <= num < 10: #파이썬만 가능한 수식
print("입력한 값은 0 이상 10 미만입니다.")
elif 10 <= num < 20:
print("입력한 값은 10 이상 20 미만입니다.")
else:
print("입력한 값은 20 이상입니다.")
print(main()) |
4443e279d14f83abdf021cd0c0362d40184a259c | Hellofafar/Leetcode | /Medium/681.py | 3,468 | 3.765625 | 4 | # ------------------------------
# 681. Next Closest Time
#
# Description:
# Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits.
# There is no limit on how many times a digit can be reused.
#
# You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid.
# "1:34", "12:9" are all invalid.
#
# Example 1:
# Input: "19:34"
# Output: "19:39"
# Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.
# It is not 19:33, because this occurs 23 hours and 59 minutes later.
#
# Example 2:
# Input: "23:59"
# Output: "22:22"
# Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the
# returned time is next day's time since it is smaller than the input time numerically.
#
# Version: 1.0
# 10/25/17 by Jianfa
# ------------------------------
import itertools
class Solution(object):
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
h1 = int(time[0])
h2 = int(time[1])
m1 = int(time[3])
m2 = int(time[4])
nums = [h1, h2, m1, m2]
groups = itertools.permutations(nums, 2)
# Check if there exists minutes that in the range (m1m2, 59]
candidates = [10 * x[0] + x[1] for x in groups]
candidates.extend([10 * h1 + h1, 10 * h2 + h2, 10 * m1 + m1, 10 * m2 + m2])
candidates = list(set(candidates))
candidates.sort()
mm = 10 * m1 + m2
mm_idx = candidates.index(mm)
if mm_idx + 1 < len(candidates) and candidates[mm_idx + 1] <= 59:
new_mm = candidates[mm_idx + 1]
if new_mm < 10:
return "%d%d:%d%d" % (h1, h2, 0, new_mm)
else:
return "%d%d:%d" % (h1, h2, new_mm)
# Check other hours
hh = 10 * h1 + h2
hh_idx = candidates.index(hh)
# If exist hour in (h1h2, 23]
if hh_idx + 1 < len(candidates) and candidates[hh_idx + 1] <= 23:
new_hh = candidates[hh_idx + 1]
new_mm = candidates[0]
if new_hh < 10:
new_hh = "0%d" % new_hh
else:
new_hh = str(new_hh)
if new_mm < 10:
new_mm = "0%d" % new_mm
else:
new_mm = str(new_mm)
return new_hh + ":" + new_mm
# If not exist hour in (h1h2, 23]
else:
new_hh = new_mm = candidates[0]
if new_hh < 10:
return "%d%d:%d%d" % (0, new_hh, 0, new_mm)
else:
return str(new_hh) + ":" + str(new_mm)
# Used for test
if __name__ == "__main__":
test = Solution()
time = "21:56"
print(test.nextClosestTime(time))
# ------------------------------
# Summary:
# My idea is to check the hour at first, then check the minutes. Assume original time is h1h2:m1m2
# For the same hour, if there exists a minute combination mimj that in the range (m1m2, 59], then return h1h2:mimj
# If not, then check another hour.
# If there exists a hour combination hihj that in the range (h1h2, 23], then find the smallest combination mimj,
# return hihj:mimj.
# If no hour in (h1h2, 23], find the smallest combination ninj, return ninj:ninj. Actually ni/nj should be the same.
|
f45ec95b7b2e24120bb6ca3bdb7196c2c13fb0c1 | thiago-allue/portfolio | /02_ai/1_ml/3_data_preparation/code/chapter_16/05_cart_regression.py | 637 | 3.84375 | 4 | # decision tree for feature importance on a regression problem
from sklearn.datasets import make_regression
from sklearn.tree import DecisionTreeRegressor
from matplotlib import pyplot
# define dataset
X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)
# define the model
model = DecisionTreeRegressor()
# fit the model
model.fit(X, y)
# get importance
importance = model.feature_importances_
# summarize feature importance
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
pyplot.bar([x for x in range(len(importance))], importance)
pyplot.show() |
c0ec19829fe70224b31690c061a7cec76a64238c | CatPhD/JSC_Python | /Day 1/W3/Sols/p4.py | 169 | 3.953125 | 4 | a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
R =((a+b>c) and (b+c>a) and (c+a>b))
print('Is this a triangle?:', R)
|
5ddea5ba935f16553b8466628f392a36f8debfba | Shobhit-hub/infomation-security-assignment-1 | /additive cypher.py | 1,832 | 4.03125 | 4 |
#Program for Additive Cypher
#function to encode
def encode(text,shift):
result=""
for i in range(0,len(text)):
if text[i]>='a' and text[i]<='z':
result+=chr(((ord(text[i])-ord('a')+shift)%26)+ord('a'))
elif text[i]>='A' and text[i]<='Z':
result+=chr(((ord(text[i])-ord('A')+shift)%26)+ord('A'))
else:
result+=text[i]
return result
#function to decode
def decode(text,shift):
result=""
for i in range(0,len(text)):
if text[i]>='a' and text[i]<='z':
result+=chr(((ord(text[i])-ord('a')-shift)%26)+ord('a'))
elif text[i]>='A' and text[i]<='Z':
result+=chr(((ord(text[i])-ord('A')-shift)%26)+ord('A'))
else:
result+=text[i]
return result
def main():
while True:
print("MENU")
print("1.Encode")
print("2.Decode")
print("3.Exit")
while True:
try:
choice=int(input('Enter choice: '))
if choice <1 or choice >3:
print("Input not in range 1-3 !! Try Again")
continue
break
except:
print("Invalid Choice")
if choice<3:
text=input("Enter a string : ") #Input string
while True:
try:
shift=int(input('Enter shift: ')) #input shift
break
except:
print("Please enter a number")
if choice==1:
print("Encoded String : ",encode(text,shift))
elif choice==2:
print("Decoded String : ",decode(text,shift))
else:
break
main()
|
f324c7c89a0153d73b1c2f6041a5ed728c9228f5 | Ebyy/python_projects | /Files/Refactoring.py | 480 | 3.6875 | 4 | import json
filename = 'username.json'
def greet_user():
"""Initiate code to greet user."""
try:
with open(filename) as f_object:
username = json.load(f_object)
except FileNotFoundError:
username = input("What is your username? ")
with open(filename,'w') as f_object:
json.dump(username,f_object)
print("We'll remember you next time!")
else:
print("Welcome back " + username + "!")
greet_user() |
ca770131f4604f4355ac9e429073c69ef300cc5c | phlalx/algorithms | /leetcode/523.continuous-subarray-sum.py | 1,697 | 3.671875 | 4 | #
# @lc app=leetcode id=523 lang=python3
#
# [523] Continuous Subarray Sum
#
# https://leetcode.com/problems/continuous-subarray-sum/description/
#
# algorithms
# Medium (24.24%)
# Likes: 1107
# Dislikes: 1559
# Total Accepted: 110K
# Total Submissions: 449.6K
# Testcase Example: '[23,2,4,6,7]\n6'
#
# Given a list of non-negative numbers and a target integer k, write a function
# to check if the array has a continuous subarray of size at least 2 that sums
# up to a multiple of k, that is, sums up to n*k where n is also an
# integer.
#
#
#
# Example 1:
#
#
# Input: [23, 2, 4, 6, 7], k=6
# Output: True
# Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to
# 6.
#
#
# Example 2:
#
#
# Input: [23, 2, 6, 4, 7], k=6
# Output: True
# Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and
# sums up to 42.
#
#
#
#
# Note:
#
#
# The length of the array won't exceed 10,000.
# You may assume the sum of all the numbers is in the range of a signed 32-bit
# integer.
#
#
#
# @lc code=start
#TAGS variant on 2-sum
#
# Several tricks
# 1. reduce to two-sum with partial sums and mod k
# 2. corner case % k
# 3. sub array length >= 2, imply to maintain cur and cur_prev
# see 974 for a simpler variant
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
n = len(nums)
prev = {0}
cur_prev = 0
cur = nums[0] % k if k else nums[0]
for i in range(1, n):
tmp = cur + nums[i]
cur_prev, cur = cur, (tmp % k if k else tmp)
if cur in prev:
return True
prev.add(cur_prev)
return False
# @lc code=end
|
435d913d035c7b65722ed1e4a780ed74d54a0fcf | mrinmayig/Python-data-structures-and-algorithms | /findminele.py | 509 | 3.84375 | 4 | #Given an array of length N find the minimum element in the array
def minElem(arr):
curr_num=0
min_num=arr[0]
for i in range(1,len(arr)):
curr_num=arr[i]
if curr_num < min_num:
min_num=curr_num
return min_num
#Given an array of length N find the maximum element in the array
def maxElem(arr):
curr_num=0
max_num=arr[0]
for i in range(1,len(arr)):
curr_num=arr[i]
if curr_num > max_num:
max_num=curr_num
return max_num |
0fed8ae7a5af8de3b4341cc637f33a309482effc | allyshoww/python-examples | /exemplos/ex6.py | 712 | 3.6875 | 4 | #!/usr/bin/python
carrinho = []
produto1 = {"nome": "Tenis", "valor": 21.70}
produto2 = {"nome": "Meia", "valor": 10}
produto3 = {"nome": "Camiseta", "valor": 17.30}
produto4 = {"nome": "Calca", "valor": 100.00}
carrinho.append(produto1)
carrinho.append(produto2)
carrinho.append(produto3)
carrinho.append(produto4)
def totalCarrinho(carrinho):
return sum(produto["valor"] for produto in carrinho)
def cupomDesconto(cupom=""):
if cupom == "xyzgratis":
return 0.50
else:
return 1
print("o total da sua compra e: ",
(totalCarrinho(carrinho)*cupomDesconto()))
print("utilizando o cupom xyzgratis o valor sera de ",
(totalCarrinho(carrinho)*cupomDesconto("xyzgratis")))
|
a8a1432aced1f46d13b3f3988bad93f5dd49ac72 | ZhouZiXuan-imb/pythonCourse | /python_Day09-字符串/03-字符串的模拟用户注册案例.py | 344 | 3.75 | 4 | count = 0
while (True):
username = input('请输入用户名:')
password = input('请输入密码:')
result = username.find(password)
if (count >= 5):
print('今日不能再次注册')
break
if (result != -1):
print('请重新输入')
count += 1
else:
print('登陆成功')
|
715262b2ba6193bcd68fb4b73b73c2dabb1fa3ba | koshikka/assingment1 | /a1_t1_4.py | 134 | 3.5625 | 4 | def c_to_k(c):
k = c + 273.15
return k
c = 27.0
k = c_to_k(c)
print ("celsius of" + str(c) + "is" + str(k) + "in kelvin")
|
d2cc82ee4b5eb82e4ad11c407d66dd12527c35ec | qumc8642/data_science_questionaire | /q2.py | 701 | 3.75 | 4 | import pandas as pd
import numpy as np
# The most important part of this dataset seems to be the salary,
data = pd.read_csv('data.csv')
imputed_data = data
#Impute the salary with the mean on the data (there are some 0s check for nan too)
salary = data['Salary']
mean = np.mean(salary)
index = 0
bad_indexes = []
for number in salary:
if number == np.nan or float(number) == 0.0:
data.iloc[index, 2] = mean.round()
index = index + 1
# Data after values have been imputed with the mean.
print(data)
# get some one hot encodes
staff_status_one_hot = pd.get_dummies(data['Employee Status'])
position_title_one_hot = pd.get_dummies(data['Position Title'])
print(position_title_one_hot) |
c9990236f7693bd7be5cfbd206be54fd97f43fe5 | mikeykh/prg105 | /12.3 Recursive Power Method.py | 612 | 4.3125 | 4 | # Design a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a positive integer.
def main():
# Get the product of the base raised to the exponent
x = get_power(3, 4)
# Displays the product
print(x)
# The get_power function accepts two arguments, base and exp
# and returns the product of base raised to exp
def get_power(base, exp):
if exp == 0:
return 1
else:
exp -= 1
return base * get_power(base, exp)
# Call the main function
main()
|
ba78696042f255ea658e195f8413dd2780678280 | loki-ppl/caesar-cipher | /caesar.py | 1,868 | 3.9375 | 4 | cifra = 3
alfabeto = "abcdefghijklmnopqrstuvwxyz"
letras = 26
new_texto = []
new_texto2 = []
texto = ""
resultado = ""
menu = True
while menu == True:
opcao = input("\nDigite 1 para Cifrar\nDigite 2 para Decifrar\nDigite 3 para mudar a Cifra\nDigite 0 para Sair\n")
# ============================= Cifrar =============================
if opcao == '1':
new_texto = []
texto = input("Digite o texto a ser cifrado: ")
for i in range(len(texto)):
cifrar = ord(texto[i]) + cifra
if cifrar > 122:
cifrar = cifrar - letras
cifrar = chr(cifrar)
new_texto.append(cifrar)
resultado = ''.join(new_texto)
print("\nTexto cifrado: ", resultado)
# ============================= Decifrar =============================
elif opcao == '2':
new_texto = []
texto = input("Digite o texto a ser decifrado: ")
for k in range(len(alfabeto)):
new_texto = []
for i in range(len(texto)):
decifrar = ord(texto[i]) + k
if decifrar > 122:
decifrar = decifrar - letras
decifrar = chr(decifrar)
new_texto.append(decifrar)
new_texto2.insert(k, new_texto)
new_texto2[k] = ''.join(new_texto)
print("Texto decifrado ",k+1,": ", new_texto2[k])
elif opcao == '3':
print("Valor atual da cifra: ", cifra)
cifra = int(input("Digite o novo valor para a cifra:"))
print("Valor da cifra alterado para: ", cifra)
# ================================ END =================================
elif opcao == '0':
menu = False
|
275d7652eb50cdd4d8148d9d3c465022ecf14013 | niralpokal/amazon_orders | /csvparser.py | 271 | 3.53125 | 4 | import csv
def parsecsv(filename):
with open(filename, newline='') as csvfile:
parsedcsv = []
ordersreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in ordersreader:
parsedcsv.append(row)
return parsedcsv |
80e7a9468b0b4b86dfb4cdc08131d60eb46c43eb | brianhuynh2021/Python-Crash-Course | /apostrophe.py | 651 | 3.53125 | 4 | # Avoiding Syntax Errors with Strings
# One kind of error that you might see with some regularity is a syntax error.
# A syntax error occurs when Python doesn’t recognize a section of your pro-
# gram as valid Python code. For example, if you use an apostrophe within
# single quotes, you’ll produce an error. This happens because Python inter-
# prets everything between the first single quote and the apostrophe as a
# string. It then tries to interpret the rest of the text as Python code, which
# causes errors.
msg = "One of Python's strengths is its diverse community."
print(msg)
msg = 'One of Python's strengths is its diverse community.' |
bd8c35eaf5bd3cfacef28ba4dfd57789dc457824 | nishantchaudhary12/Starting-with-Python | /Chapter 5/StringRepeater.py | 270 | 4.15625 | 4 | #string repeater
string = input('Enter the string: ')
number = int(input('Enter the number of times you want to print the string: '))
def string_print(x, y):
for num in range(y):
print(x,end='')
if __name__ == '__main__':
string_print(string,number)
|
2860e405f1620859125218b7dc77e4df93dae195 | kimmorsha/MarawiSiegeTweetsEmotionAnalysis | /marawi_tweets_with_location/marawi_tweets_august/official/initial_preprocessed/rename.py | 660 | 3.65625 | 4 | import os
"""
Renames the filenames within the same directory to be Unix friendly
(1) Changes spaces to hyphens
(2) Makes lowercase (not a Unix requirement, just looks better ;)
Usage:
python rename.py
"""
path = os.getcwd()
filenames = os.listdir(path)
print(path)
num = 8
for filename in filenames:
print(filename)
if f
if num < 9:
num = num + 1
new_filename = "marawi_tweets_08_0" + str(num) + ".csv"
os.rename(filename, new_filename)
elif num == 13 or num == 14 or num == 23 or num == 24 or num == 25 or num == 26:
pass
else:
num = num + 1
new_filename = "marawi_tweets_08_" + str(num) + ".csv"
os.rename(filename, new_filename)
|
7d16a609305084006db9bfd1e0313998a2e02d7d | jjdshrimpton/PythonJunk | /Sorting Visualiser2.py | 8,472 | 3.609375 | 4 | import math
from tkinter import *
from random import randint, shuffle, sample
from time import sleep
root = Tk()
root.title("Sorting Algorithms Visualiser")
sortType = StringVar()
menuText = StringVar()
colourOptions = ["Red", "Green", "Blue", "Monochrome", "Random"]
#Initialises the necessary functions based on entered parameters into the form.
def go():
global sortType
myText.delete("1.0",END)
#Creates a random set of data based on selected parameters.
data = []
quantity = int(myScaleQuantity.get())
rangeMax = int(myScaleRangeMax.get())
for i in range(quantity):
data.append(randint(0,rangeMax))
#Runs the appropriate function based on which radio button for types of sort has been selected
if sortType.get() == "Bubble":
bubble_sort(data,rangeMax)
elif sortType.get() == "Bogo":
bogo_sort(data,rangeMax)
elif sortType.get() == "Cocktail":
cocktail_shaker_sort(data,rangeMax)
#Takes in a value and a max value and returns a hex colour code of corresponding intensity. e.g. 23/100 = 23% brightness on RGB.
def get_colour(value,rangeMax):
global menuText
activeColour = menuText.get()
hexIntensity = str(hex(int(math.floor(float(value)/float(rangeMax)*255)))[2:])
while len(hexIntensity) < 2:
hexIntensity = "0" + hexIntensity
if activeColour == "Red":
return "#" + hexIntensity + "0000"
elif activeColour == "Green":
return "#00" + hexIntensity + "00"
elif activeColour == "Blue":
return "#0000" + hexIntensity
elif activeColour == "Monochrome":
return "#" + hexIntensity + hexIntensity + hexIntensity
else:
return "#" + "".join(sample("0123456789ABCDEF",6))
#Bubble sort function, takes in a set of data and the maximum value this data can be (used for some calculations regarding geometry)
def bubble_sort(data,rangeMax):
iterations = 1
#This simply inverts the speed selection (e.g. speed 100 leads to a sleep of 0, speed 1 leads to a sleep of 1 second, speed 50 leads to a sleep of 0.5 second)
speed = (100-myScaleSpeed.get()) / 100
sorted = False
while sorted == False:
changeMade = False
#log to the screen the current state of the data array
myText.delete("1.0",END)
myText.insert(END,"Iteration " + str(iterations) + ": " + str(data)+"\n")
for i in range(0,len(data)-1):
if data[i] > data[i+1]:
buffer = data[i]
data[i] = data[i+1]
data[i+1] = buffer
changeMade = True
iterations += 1
plot_boxes(data,rangeMax)
sleep(speed)
if changeMade == False:
sorted = True
myText.insert(END, "Sort completed after " + str(iterations) + " iterations.")
#Bubble sort function, takes in a set of data and the maximum value this data can be (used for some calculations regarding geometry)
def cocktail_shaker_sort(data,rangeMax):
iterations = 1
#This simply inverts the speed selection (e.g. speed 100 leads to a sleep of 0, speed 1 leads to a sleep of 1 second, speed 50 leads to a sleep of 0.5 second)
speed = (100-myScaleSpeed.get()) / 100
sorted = False
while sorted == False:
changeMade = False
#log to the screen the current state of the data array
myText.delete("1.0",END)
myText.insert(END,"Iteration " + str(iterations) + ": " + str(data)+"\n")
#first parse over data
for i in range(0,len(data)-1):
if data[i] > data[i+1]:
buffer = data[i]
data[i] = data[i+1]
data[i+1] = buffer
changeMade = True
iterations += 1
plot_boxes(data,rangeMax)
sleep(speed)
myText.delete("1.0",END)
myText.insert(END,"Iteration " + str(iterations) + ": " + str(data)+"\n")
#return parse over data
for i in range(len(data)-1,0,-1):
if data[i] < data[i-1]:
buffer = data[i]
data[i] = data[i-1]
data[i-1] = buffer
changeMade = True
iterations += 1
plot_boxes(data,rangeMax)
sleep(speed)
if changeMade == False:
sorted = True
myText.insert(END, "Sort completed after " + str(iterations) + " iterations.")
#Randomly re-orders the numbers over and over until they are placed in order by chance.
def bogo_sort(data,rangeMax):
iterations = 1
#This simply inverts the speed selection (e.g. speed 100 leads to a sleep of 0, speed 1 leads to a sleep of 1 second, speed 50 leads to a sleep of 0.5 second)
speed = (100-myScaleSpeed.get()) / 100
sorted = False
while sorted == False:
plot_boxes(data,rangeMax)
changeNeeded = False
#log to the screen the current state of the data array
myText.delete("1.0",END)
myText.insert(END,"Iteration " + str(iterations) + ": " + str(data)+"\n")
for i in range(0,len(data)-1):
if data[i] > data[i+1]:
changeNeeded = True
if changeNeeded == False:
sorted = True
else:
iterations += 1
sleep(speed)
shuffle(data)
myText.insert(END, "Sort completed after " + str(iterations) + " iterations.")
#Takes in a list of numbers as well as the maximum value each number can be. Plots these as points on the canvas relative to the parameters selected on the form.
def plot_boxes(data,rangeMax):
myCanvas.delete("all")
quantity = len(data)
rectangleWidth = 800/quantity
for i in range(quantity):
#TLX: i*canvas width/quantity of data items // TLY: canvas height - canvas height/max data value*current data value
#BRX: i*canvas width/quantity of data items+quantity of data items // BRY: height of canvas
myCanvas.create_rectangle(i*rectangleWidth,400-400/rangeMax*data[i],i*rectangleWidth+rectangleWidth,400, fill=get_colour(data[i],rangeMax))
myCanvas.update()
#Takes in a list of numbers as well as the maximum value each number can be. Plots these as points on the canvas relative to the parameters selected on the form.
def plot_boxes(data,rangeMax):
myCanvas.delete("all")
quantity = len(data)
rectangleWidth = 800/quantity
for i in range(quantity):
#TLX: i*canvas width/quantity of data items // TLY: canvas height - canvas height/max data value*current data value
#BRX: i*canvas width/quantity of data items+quantity of data items // BRY: height of canvas
myCanvas.create_rectangle(i*rectangleWidth,400-400/rangeMax*data[i],i*rectangleWidth+rectangleWidth,400, width=0, fill=get_colour(data[i],rangeMax))
myCanvas.update()
#Declaration of form objects
myCanvas = Canvas(root, width=800, height=400)
myRadioBubble = Radiobutton(root, text='Bubble', variable=sortType, value="Bubble")
myRadioCocktail = Radiobutton(root, text='Cocktail Shaker', variable=sortType, value="Cocktail")
myRadioInsertion = Radiobutton(root, text="Insertion", variable=sortType, value="Insertion")
myRadioBogo = Radiobutton(root, text='Bogo', variable=sortType, value="Bogo")
myLabelQuantity = Label(root, text="Data points:")
myScaleQuantity = Scale(root, from_=3, to=1000, orient=HORIZONTAL)
myLabelRangeMax = Label(root, text="Max value:")
myScaleRangeMax = Scale(root, from_=5, to=100, orient=HORIZONTAL)
myLabelSpeed = Label(root, text="Speed:")
myScaleSpeed = Scale(root, from_=0, to=100, orient=HORIZONTAL)
myButton = Button(root, text="Go!", command=go)
myDropdownColours = OptionMenu(root , menuText, *colourOptions)
myText = Text(root, height=8)
#Default values set to form objects
sortType.set("Bubble")
menuText.set("Red")
myScaleQuantity.set(25)
myScaleRangeMax.set(100)
myScaleSpeed.set(50)
#Form object 'packing' and layout.
myCanvas.grid(row=0, columnspan=4)
myRadioBubble.grid(row=1, column=0)
myRadioCocktail.grid(row=1, column=1)
myRadioInsertion.grid(row=2, column=0)
myRadioBogo.grid(row=2, column=1)
myText.grid(rowspan=10, row=1, column=2)
myLabelQuantity.grid(row=3,column=0)
myScaleQuantity.grid(row=3,column=1)
myLabelRangeMax.grid(row=4,column=0)
myScaleRangeMax.grid(row=4,column=1)
myLabelSpeed.grid(row=5,column=0)
myScaleSpeed.grid(row=5,column=1)
myDropdownColours.grid(row=6, column=0, columnspan=2, pady=10)
myButton.grid(row=6, column=2, columnspan=2, pady=10)
root.mainloop() |
34846e9ee05b0f08ccdcc8a6127dc7d74f80ec00 | manji-0/atcoder | /tenkai/2015/a.py | 157 | 3.5 | 4 | def main():
A = [100,100,200]
for i in range(3,20):
A.append(A[i-1]+A[i-2]+A[i-3])
print(A[-1])
if __name__ == '__main__':
main()
|
d01d04383b79db71acc820de63d8278259ae4d80 | jacquerie/leetcode | /leetcode/0012_integer_to_roman.py | 784 | 3.609375 | 4 | # -*- coding: utf-8 -*-
NUMERAL_ROMAN_MAP = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
class Solution:
def intToRoman(self, num):
result = []
for numeral, roman in NUMERAL_ROMAN_MAP:
while num >= numeral:
result.append(roman)
num -= numeral
return "".join(result)
if __name__ == "__main__":
solution = Solution()
assert "III" == solution.intToRoman(3)
assert "IV" == solution.intToRoman(4)
assert "IX" == solution.intToRoman(9)
assert "LVIII" == solution.intToRoman(58)
assert "MCMXCIV" == solution.intToRoman(1994)
|
41c176104cdcc2ff420a0a47a3319ddbfb8236a4 | ptkang/python-advanced | /chapter04/duck_4_1.py | 1,984 | 4.53125 | 5 | # 鸭子类型:当看到一只鸟走起来像鸭子,游泳起来像鸭子,叫起来也像鸭子,那么这只鸟就可以被称为鸭子
# 一个对象实现什么样的方法,则它就拥有什么样的类型和操作
# 一个对象只要实现了相关类型的魔法函数,那么就可以使用这个类型对应的方法操作这个对象
# 一个对象拥有一个已实现的魔法函数,那么这个对象就可以被这个魔法函数对应的操作正确使用
# 鸭子类型的本质:面向协议编程,一个类实现了对应协议的魔法函数,则可以使用这个类实现的协议操作来操作这个类.
# 即python本质是面向协议编程
# 多态:实现相同函数的不同对象,都可以使用相同的函数或操作去访问,将这个行为称为多态
# 例1:一个对象可以指向不同的类,并调用其共同的成员函数
# 这个在c++中被称为运行时多态
class Cat():
def say(self):
print('I am a cat')
class Dog():
def say(self):
print('I am a Dog')
class Duck():
def say(self):
print('I am a Duck')
animal_list = [Cat, Dog, Duck]
for animal in animal_list:
animal().say()
# 例2:只要一个对象满足某一个类型,则都可以被可调用这个类型的方法调用
# 以下代码能正确执行是应为name_list,name_tuple, name_set,company都是iterable的
# Extend list by appending elements from the iterable.
class Company():
def __init__(self, employee_list):
self.employee = employee_list
def __getitem__(self, item):
return self.employee[item]
name_list = ['person1', 'person2']
name_tuple = ['person3', 'person4']
name_set = set()
name_set.add('person4')
name_set.add('person5')
company = Company(['Bob', 'Lily'])
print(name_list)
name_list.extend(name_tuple)
print(name_list)
name_list.extend(name_set)
print(name_list)
name_list.extend(company)
print(name_list)
|
6333cdb7c1c8c009233cbe2f1eb9e3c0a790e02f | Nishinomiya0foa/Old-Boys | /2_Threading_MySql_html/day39_Pool/07_CallBack.py | 457 | 3.53125 | 4 | """回调函数
---- 把一个函数的返回值作为参数,执行另一个函数(在主进程执行)"""
import os
from multiprocessing import Pool
def func1(n):
print('In func1 ', os.getpid())
return n**2
def func2(n):
print('In func2 ', os.getpid())
print(n)
if __name__ == '__main__':
print('主进程:', os.getpid())
p = Pool(5)
p.apply_async(func=func1, args=(9, ), callback=func2)
p.close()
p.join() |
132381ce00557f229f7291fe5ff4fec741edd751 | DenysLins/code-interview | /leetcode/70-climbing-stairs/solution.py | 340 | 3.8125 | 4 | # https://leetcode.com/problems/climbing-stairs/
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 2
if n < 2:
return n
else:
for i in range(3, n + 1):
a, b = b, a + b
return b
if __name__ == "__main__":
print(Solution().climbStairs(10))
|
a698479abe43cba6b063e565a07d7b69806f32f0 | hammerdrucken65/t1 | /dice.py | 1,894 | 4.15625 | 4 | import random
# getnum print "prompt" to screen", takes input from user, and converts that input
# to an integer. If the user input cannot be converted to integer, the program
# informs the user and tells them to start again.
def getnum(prompt, min, max): # prompt = question statement to print to screen, min is the minimum valid integer, max is the max valid integer
validInput = False
while validInput==False:
userInput = input(prompt)
try:
userInput = int(userInput)
except:
print("bad input")
continue
if (userInput <= max and userInput >= min):
validInput = True
else:
print("bad input")
return userInput
def howManyDice():
print ("this stub pretends to ask user how many dice thay want")
dieCount = random.randint(1, 5)
print("dieCount = %s" % (dieCount))
return dieCount
def trueOrFalse(number):
getnum()
class Die():
def __init__(self, sides = 6):
self.rollval = None
self.sides = sides
self.color = "white"
def roll(self):
self.rollval = random.randint(1, self.sides)
rollagain = True # use different varialbe name, and default to True
while rollagain: # now change this to True (simplified version while rollagain)
die = []
total = 0
numberOfDice = getnum(prompt="how many dice would you like to roll: ",min=1,max=30)
sides = getnum(prompt="how many sides do you want them to have?: ",min=4, max=30)
for x in range(0,numberOfDice):
die.append(Die(sides=sides))
die[x].roll()
print("value of the die is %s" % (die[x].rollval))
total = total+die[x].rollval
print("total is %s" % (total))
if getnum(prompt="would you like to roll another die? 1: yes 2: no (please use number): ",min=1,max=2)==2:
rollagain = False
|
8076ca925bdf1a4951cc4d8d89dd05f74b91e703 | rubykumar1/python-creations | /palindrome_check.py | 477 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 2 08:24:28 2017
@author: Ruby Kumar
EXERCISE:Ask the user for a string and
print out whether this string is a
palindrome or not. (A palindrome is a
string that reads the same forwards and
backwards.)
"""
number = input("Enter a number: ")
num_list = [int(digit) for digit in str(number)]
if num_list == list(reversed(num_list)):
print("Your number is a palindrome.")
else:
print("Your number is not a palindrome.")
|
78d182a6a372d1f795b3c2eeb9d42951597bb7b7 | brotchie/brotchie-euler | /py/p30.py | 164 | 3.640625 | 4 | def isdigpow(x, p):
return x == sum(int(k)**p for k in str(x))
pows = []
for i in range(2, 2e5):
if isdigpow(i, 5):
pows.append(i)
print sum(pows)
|
aba6a94254c8a8b42d4646b5c7ba94b833bcd5b9 | vip7265/ProgrammingStudy | /leetcode/problems/sjw_sqrtx.py | 669 | 3.625 | 4 | """
Problem URL: https://leetcode.com/problems/sqrtx/
"""
class Solution:
def mySqrt(self, x: int) -> int:
# return self.naiveSolution(x) # 2020ms, O(sqrt(n))
return self.binarySearchSolution(x) # 40ms, O(logn)
def naiveSolution(self, x):
base = 0
while base*base <= x:
base += 1
return base-1
def binarySearchSolution(self, x):
lo, hi = 0, x
while lo < hi:
mid = (lo + hi) // 2
if mid*mid <= x < (mid+1)*(mid+1):
return mid
elif mid*mid < x:
lo = mid + 1
else:
hi = mid
return lo |
802fcdfa9702f243421523081a3d0c1df4ad3ccb | jennifer-ryan/pands-problem-set | /7_square_root.py | 861 | 4.28125 | 4 | # Problem: Write a program that that takes a positive floating point number as input and outputs an approximation of its square root.
# Import square root function from math module.
from math import sqrt
# Import getFloat function from pcinput.py to ensure input is a positive floating point number.
from pcinput import getFloat
# Prompt user to enter a positive floating point number and set value to variable i.
i = getFloat("Please enter a positive number: ")
# Format s so there is only 1 decimal place.
s = round(sqrt(i), 1)
# If s is the same as int(s), the number is a whole number square root and not approximate so the output is adjusted.
# Help from https://stackoverflow.com/q/4541155
if s != int(s):
print("The square root of", i, "is approximately " + str(s) + ".")
else:
print("The square root of", int(i), "is " + str(int(s)) + ".") |
897ed86105ae5b026b98a1fdb7c93cf7df15f3cd | Scottycags/csc201_fp_s2016_Scott_Cagnard | /election_Scott_Cagnard.py | 17,652 | 4 | 4 | # Name: Scott Cagnard
# Homework 5: Election prediction
import csv
import os
import time
def read_csv(path):
"""Reads the CSV file at path, and returns a list of rows from the file.
Parameters:
path: path to a CSV file.
Returns:
list of dictionaries: Each dictionary maps the columns of the CSV file
to the values found in one row of the CSV file. Although this function
will work for any csv file, for our purposes, depending on the contents
of the CSV file, this will typically be a list of *ElectionDataRow*s or
a list of *PollDataRow*s (or a list of electoral college data rows).
"""
output = []
for row in csv.DictReader(open(path)):
output.append(row)
return output
################################################################################
# Problem 1: State edges
################################################################################
def row_to_edge(row):
"""Given an *ElectionDataRow* or *PollDataRow*, returns the
Democratic *Edge* in that *State*.
Parameters:
row: an *ElectionDataRow* or *PollDataRow* for a particular *State*
Returns:
Democratic *Edge* in that *State*: a float
"""
return float(row["Dem"]) - float(row["Rep"])
def state_edges(election_result_rows):
"""Given a list of *ElectionDataRow*s, returns *StateEdge*s.
Parameters:
election_result_rows: list of *ElectionDataRow*s
This list has no duplicate *States*; that is, each *State* is
represented at most once in the input list.
Returns:
*StateEdges*:
dictionary from *State* (string) to *Edge* (float)
"""
state_edges = {} #Create empty dictionary
for row in election_result_rows: #Iterate through each row
state = row['State']
edge = row_to_edge(row)
state_edges[state] = edge #Map each state to the democratic edge of the state
return state_edges #Return the new dictionary
################################################################################
# Problem 2: Find the most recent poll row
################################################################################
def earlier_date(date1, date2):
"""Given two dates as strings, returns True if date1 is before date2.
Parameters:
date1: a string representing a date (formatted like "Oct 06 2012")
date2: a string representing a date (formatted like "Oct 06 2012")
Returns:
bool: True if date1 is before date2.
"""
return (time.strptime(date1, "%b %d %Y") < time.strptime(date2, "%b %d %Y"))
def most_recent_poll_row(poll_rows, pollster, state):
""" Given a list of *PollDataRow*s, returns the most recent row with the
specified *Pollster* and *State*. If no such row exists, returns None.
Parameters:
poll_rows: a list of *PollDataRow*s
pollster: a string representing a *Pollster*
state: a string representing a *State*
Returns:
A *PollDataRow*: a dictionary from string to string OR
None, if no such row exists
"""
mostrecent = None #Set a variable equal to None
date2 = 'Feb 10 1900' #Create an old formatted date
for row in poll_rows: #Iterate through each row
date = row['Date'] #Extract the date of each row
if row['State'] == state and row['Pollster'] == pollster and earlier_date(date, date2) == False:
mostrecent = row
date2 = row['Date']
return mostrecent
#If there is a state and pollster and it is the most recent poll, then
#we can return it as an output for our most recent poll.
#If not, it will produce the output None
################################################################################
# Problem 3: Pollster predictions
################################################################################
def unique_column_values(rows, column_name):
"""Given a list of rows and the name of a column (a string),
returns a set containing all values in that column.
Parmeters:
rows: a list of rows (could be a *PollDataRow* or another type of row)
column_name: a string
Returns:
A set: containing all unique values in column `column_name`
"""
values = [] #Create an empty list
for row in rows: #Iterate through each row
values.append(row[column_name])
values = set(values)
return values
#Append each unique value and transform it into a set and
#return the set as an output
def pollster_predictions(poll_rows):
"""Given a list of *PollDataRow*s, returns *PollsterPredictions*.
For a given pollster, uses only the most recent poll for a state.
Parameters:
poll_rows: a list of *PollDataRow*s
Returns:
A *PollsterPredictions*: a dictionary from *Pollster* to *StateEdges*
"""
dict = {} #Create an empty dictionary
dict = dict.fromkeys(unique_column_values(poll_rows, "Pollster"))
#Extract all the unique Pollster values and assign them as specific keys
for keys in dict: #Iterate through each key of the dictionary
list = [] #Create an empty list
for poll_row in poll_rows: #Iterate through each row
if (most_recent_poll_row(poll_rows, keys, poll_row["State"]) != None):
list.append(most_recent_poll_row(poll_rows, keys, poll_row["State"]))
dict[keys] = state_edges(list)
return dict
#Using only the most recent poll for a state, the pollsters become the key
#of the dictionary, and are assigned to the value of the state and its edge
################################################################################
# Problem 4: Pollster errors
################################################################################
def average_error(state_edges_predicted, state_edges_actual):
"""Given predicted *StateEdges* and actual *StateEdges*, returns
the average error of the prediction.
For each state present in state_edges_predicted, its error is
calculated. The average of all of these errors is returned.
Parameters:
state_edges_predicted: *StateEdges*, a dictionary from *State* to *Edge*
state_edges_actual: *StateEdges*, a dictionary from *State* to *Edge*
Returns:
float: the average error
"""
d1 = state_edges_predicted #Assign the predicted state edges to a variable
length = list(state_edges_predicted.values()) #Create a list of the predicted state edge values
z = len(length) #Find the number of elements in the list "length"
d2 = state_edges_actual #Assign the actual state edge values to a variable
d3 = {} #Create an empty dictionary
for k, v in d1.items():
d3[k] = v - d2.get(k, 0) #Find the difference between the predicted values and the actual values
list1 = list(d3.values()) #Assign the differences to a list
x = list(map(abs, list1)) #Take the absolute value of the differences
a = sum(x) #Take the sum of the new values
return a/z #Calculate the average of all the errors
def pollster_errors(pollster_predictions, state_edges_actual):
"""Given *PollsterPredictions* and actual *StateEdges*,
retuns *PollsterErrors*.
Parameters:
pollster_predictions: *PollsterPredictionss*, dictionary from *Pollster*
to *StateEdges*
state_edges_actual: *StateEdges*, dictionary from *State* to *Edge*
Returns:
*PollsterErrors*: a dictionary from *Pollster* to float (The float
represents the *Pollster*'s average error).
"""
totalAverage = {} #Create an empty dictionary
for k in pollster_predictions:
states = pollster_predictions[k]
for j in states:
if j in state_edges_actual:
average = average_error(pollster_predictions[k], state_edges_actual)
totalAverage[k] = average
#Map each pollster to its calculated average error of each state
return totalAverage
################################################################################
# Problem 5: Pivot a nested dictionary
################################################################################
def pivot_nested_dict(nested_dict):
"""Pivots a nested dictionary, producing a different nested dictionary
containing the same values.
The input is a dictionary d1 that maps from keys k1 to dictionaries d2,
where d2 maps from keys k2 to values v.
The output is a dictionary d3 that maps from keys k2 to dictionaries d4,
where d4 maps from keys k1 to values v.
For example:
input = { "a" : { "x": 1, "y": 2 },
"b" : { "x": 3, "z": 4 } }
output = {'y': {'a': 2},
'x': {'a': 1, 'b': 3},
'z': {'b': 4} }
"""
reverse_nest_dict = {} #Create an empty dictionary
for k, v in nested_dict.items(): #Iterate through each pair of elements
for k2, v2 in v.items(): #Iterate through pair of values
try:
reverse_nest_dict[k2][k] = v2
except KeyError:
reverse_nest_dict[k2] = { k : v2 }
return reverse_nest_dict
#Create a dictionary that produces a different nested dictionary which
#contains the same values
################################################################################
# Problem 6: Average the edges in a single state
################################################################################
def average_error_to_weight(error):
"""Given the average error of a *Pollster*, returns that pollster's weight.
Parameters:
error: a float representing a *Pollster*'s average error,
The error must be a positive number.
Returns:
float: weight, calculated as 1/(error)^2
"""
return error ** (-2)
# The default average error of a pollster who did no polling in the
# previous election.
DEFAULT_AVERAGE_ERROR = 5.0
def pollster_to_weight(pollster, pollster_errors):
""""Given a *Pollster* and a *PollsterErrors*, return
the given pollster's weight.
Parameters:
pollster: *Pollster*, a string
pollster_errors: *PollsterErrors*, a dictionary from *Pollster* to float
Returns:
float: weight
"""
if pollster not in pollster_errors:
weight = average_error_to_weight(DEFAULT_AVERAGE_ERROR)
else:
weight = average_error_to_weight(pollster_errors[pollster])
return weight
def weighted_average(items, weights):
"""Returns the weighted average of a list of items.
Parameters:
items: a list of numbers.
weights: a list of numbers, whose sum is nonzero.
Each weight in weights corresponds to the item in items at
the same index. items and weights must be the same length.
Returns:
float: the weighted average, the sum of (product of each item and
its weight) divided by (the sum of the weights)
"""
assert len(items) > 0
assert len(items) == len(weights)
a = items #Assign the items to a variable
b = weights #Assign the weights to a variable
x = list(items) #Transform the items to a list
y = list(weights) #Transform the weights to a list
sum1 = sum(weights) #Sum up all of the weights
z = [a*b for a,b in zip(x, y)] #Multiply both lists by matching up the elements from both lists
sum2 = sum(list(z)) #Take the sum of all of the products
return float(sum2/sum1) #Divide the sum of the products by the sum of the weights to get the weighted average
def average_edge(pollster_edges, pollster_errors):
"""Given *PollsterEdges* and *PollsterErrors*, returns the average
of these *Edge*s weighted by their respective *PollsterErrors*.
Parameters:
pollster_edges: *PollsterEdges*, a dictionary from *Pollster* to *Edge*
pollster_errors: *PollsterErrors*, a dictionary from *Pollster* to float
Returns:
float: the weighted average of the *Edge*s, weighted by the errors
"""
a = list(pollster_edges.values()) #List the values of the pollster edges
alen = len(a) #Obtain the length of the list of values above
b = list(pollster_edges.keys()) #List the keys of the pollster edges
pollster_errors = pollster_errors
c = [] #Create an empty list
for i in b: #Iterate through each key
c.append(pollster_to_weight(i, pollster_errors)) #Calcualte the weight of each pollster error
c1 = c[0:alen] #Ignore the pollster errors that dont have a pollster edge
final = weighted_average(a, c1)
#Use the weighted average function to get the weighted average function
#to get the weighted avergae of the Edge's, which are weighted by the errors
return final
################################################################################
# Problem 7: Predict the 2012 election
################################################################################
def predict_state_edges(pollster_predictions, pollster_errors):
"""Given *PollsterPredictions* from a current election and *PollsterErrors*
from a past election, returns predicted *StateEdges* of the current election.
Parameters:
pollster_predictions: *PollsterPredictions*, a dictionary from
*Pollster* to *StateEdges*
pollster_errors: *PollsterErrors*, a dictionary from *Pollster* to float
Returns:
*StateEdges*: predicted *StateEdges* of the current election
"""
dict = {} #Create an empty dictionary
pollster_state_prediction = pivot_nested_dict(pollster_predictions)
for state in pollster_state_prediction:
dict[state] = average_edge(pollster_state_prediction[state], pollster_errors)
return dict
#Iterate through each state and calculate the predicted edge for each state
################################################################################
# Electoral College, Main Function, etc.
################################################################################
def electoral_college_outcome(ec_rows, state_edges):
"""Given electoral college rows and *StateEdges*, returns the outcome of
the Electoral College.
Parameters:
ec_rows: a list of electoral college rows, where an electoral college
row is a dictionary from string to string (similar to an
*ElectionDataRow* or a *PollDataRow* but with different keys)
state_edges: *StateEdges*, a dictionary from *State* to *Edge*
Returns:
dictionary containing only the keys "Dem" and "Rep", mapped to a
number (as a float) of electoral votes won by that party.
If a state has an edge of exactly 0.0, its votes are evenly divided
between both parties.
"""
ec_votes = {} # maps from state to number of electoral votes
for row in ec_rows:
ec_votes[row["State"]] = float(row["Electors"])
outcome = {"Dem": 0, "Rep": 0}
for state in state_edges:
votes = ec_votes[state]
if state_edges[state] > 0:
outcome["Dem"] += votes
elif state_edges[state] < 0:
outcome["Rep"] += votes
else:
outcome["Dem"] += votes/2.0
outcome["Rep"] += votes/2.0
return outcome
def print_dict(dictionary):
"""Given a dictionary, prints its contents in sorted order by key.
Rounds float values to 8 decimal places.
Returns:
None
"""
for key in sorted(dictionary.keys()):
value = dictionary[key]
if type(value) == float:
value = round(value, 8)
print (key, value)
def main():
"""Main function, executed when election.py is run as a Python script.
"""
# Read state edges from the 2008 election
edges_2008 = state_edges(read_csv("data/2008-results.csv"))
# Read pollster predictions from the 2008 and 2012 election
polls_2008 = pollster_predictions(read_csv("data/2008-polls.csv"))
polls_2012 = pollster_predictions(read_csv("data/2012-polls.csv"))
# Compute pollster errors for the 2008 election
error_2008 = pollster_errors(polls_2008, edges_2008)
# Predict the 2012 state edges
prediction_2012 = predict_state_edges(polls_2012, error_2008)
# Predict the 2012 Electoral College outcome
ec_2012 = electoral_college_outcome(read_csv("data/2012-electoral-college.csv"), prediction_2012)
print("Predicted 2012 election results:")
print_dict(prediction_2012)
print()
print("Predicted 2012 Electoral College outcome:")
print_dict(ec_2012)
print()
# If this file, election.py, is run as a Python script (such as by typing
# "python election.py" at the command shell), then run the main() function.
#if __name__ == "__main__":
# main()
###
### Collaboration
###
# ... Write your answer here, as a comment (on lines starting with "#").
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.