blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
19deb174db758ed0c8be222869a29e019020093c | manisaiprasad/Data-Structures-and-Algorithms | /max_sum_subarray.py | 773 | 4.21875 | 4 | def max_sum_subarray(arr):
"""
:param - arr - input array
return - number - largest sum in contiguous subarry within arr
"""
# Solution
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(current_sum + num, num)
max_sum = max(current_sum, max_sum)
return max_sum
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
output = max_sum_subarray(arr)
if output == solution:
print("Pass")
else:
print("Fail")
arr= [1, 2, 3, -4, 6]
solution= 8 # sum of array
test_case = [arr, solution]
test_function(test_case)
arr = [1, 2, -5, -4, 1, 6]
solution = 7 # sum of last two elements
test_case = [arr, solution]
test_function(test_case) |
12b8a183272a4d9a2e6410f3a935d75ed0d265e6 | leosanchezsoler/bilbo-the-bot | /src/api/utils/functions.py | 1,089 | 3.515625 | 4 | import json
import pandas as pd
from nltk.stem import WordNetLemmatizer
def read_json(fullpath):
with open(fullpath, "r") as json_file_readed:
json_readed = json.load(json_file_readed)
return json_readed
def read_my_json():
'''
@leosanchezsoler
This function reads the data
Returns:
- my_json
'''
df = pd.read_json('data/data.json')
return df.to_json(orient='records', indent=4)
def tokenize_and_lemmatize(text):
'''
@leosanchezsoler
This function transforms words in order to attach them to their root
Parameters:
- text
Returns:
- lem: the lemmatized text
'''
lemmatizer = WordNetLemmatizer()
# tokenization to ensure that punctuation is caught as its own token
tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
filtered_tokens = []
for token in tokens:
if re.search('[a-zA-Z]', token):
filtered_tokens.append(token)
lem = [lemmatizer.lemmatize(t) for t in filtered_tokens]
return lem |
a2e2254f61fccfbec29fae8d2e7cfe82c0d07952 | Aasthaengg/IBMdataset | /Python_codes/p02910/s758644353.py | 216 | 3.546875 | 4 | s = input().rstrip()
for i,l in enumerate(s):
if i&1:
if 'R' in l:
print('No')
break
else:
if 'L' in l:
print('No')
break
else:
print('Yes') |
d30da5077c711e6ea662ab0601e192afac9f2948 | tarekFerdous/Python_Crash_Course | /003.List/0.3.5.ex.py | 295 | 3.546875 | 4 | invitation_list = ['Tarek', 'Ferdous', 'Madara']
message = ' will be invited'
temp = invitation_list.pop(0)
print(temp + ' cannot make it to dinner.')
invitation_list.insert(0, 'Itachi')
print(invitation_list[0] + message)
print(invitation_list[1] + message)
print(invitation_list[2] + message)
|
933f1dd6a6596b065f3b8bee9a7be1c5d13157c0 | jack234414/BCDE321_Assignment2 | /edan_unit_tests.py | 690 | 3.6875 | 4 | import unittest
class MainTests(unittest.TestCase):
def setUp(self):
# be executed before each test
self.x = 5
def tearDown(self):
# be executed after each test case
print('down')
def test_03(self):
print(3)
self.assertTrue(self.x == 5, "the value of x should be 5!")
def test_02(self):
print(2)
self.x = 6
self.assertEqual(6, 3 * 2)
@unittest.skip('I have not coded how this will work yet.')
def test_01(self):
print(1)
self.assertTrue(None is 42)
self.x = 666
if __name__ == '__main__':
unittest.main(verbosity=2) # with more details
# unittest.main() |
b27d94391e57d6013c1ba2c5060f478c2a0453d7 | blueones/LeetcodePractices | /cousinsinbinarytree993.py | 4,991 | 3.59375 | 4 | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
#remember each nodes parent and level
dict_nodes = {root.val:(0, None)}
def helper(node, level):
if node != None:
helper(node.left, level+1)
helper(node.right, level+1)
if node.left:
dict_nodes[node.left.val] = (level+1, node.val)
if node.right:
dict_nodes[node.right.val] = (level+1, node.val)
helper(root, 0)
x_level, x_parent = dict_nodes[x]
y_level, y_parent = dict_nodes[y]
if x_level == y_level and x_parent != y_parent:
return True
return False
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
#when find either one, mark the level and for the rest only go that far down the path.
self.recorded_depth = None
def helper(node, level, parent, x, y):
if node:
if node.val == x or node.val == y:
if self.recorded_depth == None:
self.recorded_depth = (level, parent)
else:
if level == self.recorded_depth[0]:
if parent != self.recorded_depth[1]:
return True
else:
if self.recorded_depth and self.recorded_depth[0] <= level:
return False
return helper(node.left, level+1, node.val, x, y) or helper(node.right, level+1, node.val, x, y)
else:
return False
return helper(root, 0, None, x, y)
class Solution2:
def isCousins(self, root, x, y):
#bfs normally we use queue. but this question is doing level order traversal so I guess it's okay.
stack = [(root, None)]
flag = False
marked_parent = None
while stack:
new_layer = []
while stack:
current_node, parent = stack.pop()
if current_node.val == x or current_node.val == y:
if flag == True:
if parent != marked_parent:
return True
else:
return False
else:
flag = True
marked_parent = parent
if current_node.left:
new_layer.append((current_node.left, current_node.val))
if current_node.right:
new_layer.append((current_node.right, current_node.val))
stack = new_layer
if flag == True:
return False
class Solution3:
def isCousins(self, root, x, y):
#bfs using stack.... normally we use queue. but this question is doing level order traversal so I guess it's okay.
#cleaned up
stack = [(root, None)]
flag = False
marked_parent = None
while stack:
new_layer = []
while stack:
current_node, parent = stack.pop()
if current_node.val == x or current_node.val == y:
if flag == True:
if parent != marked_parent:
return True
return False
flag = True
marked_parent = parent
if current_node.left:
new_layer.append((current_node.left, current_node.val))
if current_node.right:
new_layer.append((current_node.right, current_node.val))
stack = new_layer
if flag == True:
return False
from collections import deque
class Solution4:
def isCousins(self, root, x, y):
#BFS using queue and counter using null to mark a different parent.
queue = deque()
queue.append(root)
while queue:
length_level = len(queue)
siblings = False
cousins = False
for i in range(length_level):
current_node = queue.popleft()
if current_node == None:
siblings = False
else:
if current_node.val == x or current_node.val == y:
if siblings == False and cousins == True:
return True
siblings = True
cousins = True
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
queue.append(None)
if cousins == True:
return False
return False
|
f69983984fa80efb3d3a1d45ca5cdb8b57926925 | aaspeel/optiMeasRL | /utils/save.py | 4,635 | 3.65625 | 4 | """
Code from https://stackoverflow.com/questions/2960864/how-to-save-all-the-variables-in-the-current-python-session
Slight modifications.
"""
import pickle
import shelve
import time
def save_workspace(filename, names_of_spaces_to_save, dict_of_values_to_save, add_time_stamp=True):
'''
filename = location to save workspace. A time stamp is added at the end of the name.
names_of_spaces_to_save = use dir() from parent to save all variables in previous scope.
-dir() = return the list of names in the current local scope
dict_of_values_to_save = use globals() or locals() to save all variables.
-globals() = Return a dictionary representing the current global symbol table.
This is always the dictionary of the current module (inside a function or method,
this is the module where it is defined, not the module from which it is called).
-locals() = Update and return a dictionary representing the current local symbol table.
Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Example of globals and dir():
>>> x = 3 #note variable value and name bellow
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'x': 3, '__doc__': None, '__package__': None}
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
Example:
save_workspace('file_name', dir(), globals())
'''
if add_time_stamp:
time_str = time.strftime("%Y%m%d-%H%M%S") # time stamp added to the file name to avoid overwriting
filename=filename+time_str
my_shelf = shelve.open(filename,'n', writeback=True) # 'n' for new
for key in names_of_spaces_to_save:
try:
try:
if key not in ['exit','get_ipython','quit','agent']: # not working for these keys (and not the same error)
my_shelf[key] = dict_of_values_to_save[key]
print(key)
except TypeError:
#
# __builtins__, my_shelf, and imported modules can not be shelved.
#
print('ERROR shelving (TypeError): {0}'.format(key))
pass
except AttributeError:
print('ERROR shelving (AttributeError): {0}'.format(key))
# This loop is to actualise the keys of my_shelf
for key in names_of_spaces_to_save:
try:
try:
if key not in ['exit','get_ipython','quit','agent']:
my_shelf[key]
except TypeError:
#
# __builtins__, my_shelf, and imported modules can not be shelved.
#
print('ERROR shelving (TypeError): {0}'.format(key))
pass
except AttributeError:
print('ERROR shelving (AttributeError): {0}'.format(key))
#my_shelf.sync()
my_shelf.close()
def load_workspace(filename, parent_globals):
'''
filename = location to load workspace.
parent_globals use globals() to load the workspace saved in filename to current scope.
Don't load 'workspace_path'.
Example:
load_workspace('file_name', globals())
'''
my_shelf = shelve.open(filename)
print(type(my_shelf))
for key in my_shelf:
print(key)
if key != 'workspace_path':
parent_globals[key]=my_shelf[key]
print(key)
print("load done")
my_shelf.close()
def pickle_save(filename, names_of_spaces_to_save, dict_of_values_to_save, add_time_stamp=True):
if add_time_stamp:
time_str = time.strftime("%Y%m%d-%H%M%S") # time stamp added to the file name to avoid overwriting
filename=filename+time_str
my_dic = dict()
for key in names_of_spaces_to_save:
try:
my_dic[key] = dict_of_values_to_save[key]
print(key)
except Exception as e:
print('ERROR in saving')
print('key:',key)
print(e)
file = open(filename, 'wb')
pickle.dump(my_dic, file)
file.close()
def pickle_load(filename, parent_globals, suffix=""):
file = open(filename,'rb')
data = pickle.load(file)
file.close()
for key in data:
if key != 'workspace_path':
parent_globals[key+suffix]=data[key]
print(key+suffix)
print("load done")
|
2a240bf49f25c3f794f02dce2a250c090487d70e | sohil86/python_all | /subtract.py | 212 | 4.21875 | 4 | # This program subtracts two numbers
num1 = 1.5
num2 = 6.3
# Subtracts two numbers
sub = float(num1) - float(num2)
# Display the difference
print('The difference of {0} and {1} is {2}'.format(num1, num2, sub)) |
40ad318556ffba060f01c36b42113decd6e21514 | MrDebugger/BSLABS | /semester3/lab2/task1.py | 357 | 3.921875 | 4 | # Task 1:
def addMatrixes(m1,m2):
finalMatrix = [[0,0,0],[0,0,0],[0,0,0]]
print(finalMatrix)
for i in range(len(m1)):
for j in range(len(m1[0])):
finalMatrix[i][j] = m1[i][j] + m2[i][j]
return finalMatrix
matrix1 = eval(input("Enter 2D Matrix1: "))
matrix2 = eval(input("Enter 2D Matrix2: "))
fMatrix = addMatrixes(matrix1,matrix2)
print(fMatrix)
|
a5f383a9978a703764b17c8cb8137c476cfc44a4 | achenriques/EjerciciosALS | /objetos.py | 1,596 | 3.640625 | 4 | # objetos
import math
class Punto:
_origen = None
@staticmethod
def get_origen():
if not Punto._origen:
Punto._origen = Punto()
return Punto._origen
def __init__(self, x=0, y=0):
self.x = x
self.y = y
@property
def x(self):
return self._x
@x.setter
def x(self, v):
self._x = v
@property
def y(self):
return self._y
@x.setter
def y(self, v):
self._y = v
def distancia_origen(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def distancia(self, other):
a = abs(self.x - other.x)
b = abs(self.y - other.y)
return math.sqrt(a ** 2 + b ** 2)
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
class Linea:
def __init__(self, x1, y1, x2=None, y2=None):
if isinstance(x1, Punto):
self.p1 = x1
self.p2 = y1
else:
self.p1 = Punto(x1, y1)
self.p2 = Punto(x2, y2)
@property
def p1(self):
return self._p1
@p1.setter
def p1(self, v):
self._p1 = v
@property
def p2(self):
return self._p2
@p2.setter
def p2(self, v):
self._p2 = v
def __str__(self):
return str(self.p1) + " - " + str(self.p2)
p1 = Punto(10, 10)
print(p1)
p2 = Punto(20, 20)
print(p2)
l1 = Linea(p1.x, p1.y, p2.x, p2.y)
print(l1)
p3 = Punto(20, 20)
p4 = Punto(30, 30)
l2 = Linea(p3, p4)
print(l2)
#print(Punto.get_origen())
#print(p1.distancia_origen())
#print(p1.distancia(p2))
|
72c8bf0b59d73cb36b2b6b5f53018f27497427f9 | restevesr3/my_scripts | /Lecture_18_Drop_Entry.py | 719 | 3.90625 | 4 |
# coding: utf-8
# # Lecture 18 - Drop Entry
# ## Robert Esteves
# In[1]:
import pandas as pd
# In[2]:
import numpy as np
# In[3]:
from pandas import Series, DataFrame
# In[5]:
ser1 = Series(np.arange(3), index=['a', 'b', 'c'])
# In[6]:
ser1
# In[7]:
# how to drop an index
ser1.drop('b')
# In[11]:
# how it works with a dataframe
dframe1 = DataFrame(np.arange(9).reshape((3,3)), index=['SF','LA','NY'], columns=['pop', 'size', 'year'])
# In[12]:
dframe1
# In[14]:
# drop a row
dframe1.drop('LA')
# In[16]:
# To make it permanent save it into another datafram
dframe2 = dframe1.drop('LA')
# In[17]:
dframe2
# In[19]:
# Drop a column
dframe1.drop('year', axis=1)
# In[ ]:
|
e55640a66ce692eaeb375af9e374facbbafd70fd | herisson31/Python-3-Exercicios-1-ao-104 | /ex091 - Jogo de Dados em Python.py | 804 | 3.84375 | 4 | ''' 091: Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios.
Guarde esses resultados em um dicionário em Python. No final, coloque esse dicionário em ordem,
sabendo que o vencedor tirou o maior número no dado.'''
from random import randint
from time import sleep
from operator import itemgetter
print()
print(' << JOGO DE DADO >>')
dado = {'Jogador 1': randint(1,6),
'Jogador 2': randint(1,6),
'Jogador 3': randint(1,6),
'Jogador 4': randint(1,6)}
ranking = list()
for k , v in dado.items():
print(f' - {k} jogou: {v}')
sleep(1)
print()
print(' <<< RANKING >>>')
ranking = sorted(dado.items(), key=itemgetter(1), reverse=True)
for i , v in enumerate(ranking):
print(f'{i +1}ª lugar: {v[0]} com {v[1]}')
sleep(1)
|
b152af57c67c9825d935cbd1f034f180a6474ade | chrikin1/ping-pong | /pass-locker/pass-lock-master/run.py | 9,277 | 4.25 | 4 | #!/usr/bin/env python3.6
import random
from user import User
from credentials import Credentials
def create_new_credential(account_name, account_password):
'''
The method that creates new account name.
'''
new_credential = Credentials(account_name, account_password)
return new_credential
def delete_credential(credentials):
'''
method to delete a credential that has been created
'''
return Credentials.delete_credentials(credentials)
def save_new_credential(credentials):
'''
method to save new credentials
'''
credentials.save_credentials()
def find_credential(account_name):
'''
method to find a credential that has been created
'''
return Credentials.find_by_name(account_name)
def display_credential():
'''
THis method displays credentials.
'''
return Credentials.display_credentials()
def main():
print('\n')
while True:
print(
"-------Welcome to my password locker app--------"
)
print('\n')
print("If you dont have an acount create a new one but if you have an account proceed to login using the codes below")
print("""Use these codes: \n "new"- create new user \n "log"-login to your account \n "ex"-to exit""")
Code = input().lower()
print('\n')
if Code == 'new':
print('*****Enter new username*****')
new_user_name = input()
print('*****Enter new password*****')
new_user_password = input()
print('*****confirm password*****')
confirm_password = input()
print('\n')
while confirm_password != new_user_password:
print("*****Password doesn't MATCH*****")
print("*****Enter username again*****")
new_user_password = input()
print("*****Confirm the password*****")
confirm_password = input()
print('\n')
else:
print(
f"Hello {new_user_name}! Congratulations you have created yourself an account!"
)
print('\n')
print("*****Now we move on to the login****")
print('\n')
print("*****Type in your username*****")
typed_name = input()
print("*****Type in the password*****")
typed_password = input()
while typed_name != new_user_name or typed_password != new_user_password:
print('\n')
print("*****Password or username is wrong*****")
print("*****Username*****")
typed_name = input()
print("*****The password*****")
typed_password = input()
print('\n')
else:
print('\n')
print(
f"***** Welcome {typed_name} to your account*****"
)
print('\n')
print("Select an option to continue: \n Enter 1, 2, 3, 4 or 5")
print('\n')
while True:
print("1:view your credentials")
print("2:New credentials")
print("3:Delete credentials")
print("4:search credentials")
print("5:log out")
choice = input()
if choice == '1':
while True:
print("***** This is a list of your credentials *****")
if display_credential():
for credential in display_credential():
print(
f"***** Account Name:{credential.account_name} *****")
print(
f"***** Password:{credential.account_password}***** ")
else:
print('\n')
print("-------No credentials available------")
print('\n')
print("Back to menu? y/n")
back = input().lower()
if back == 'y':
break
elif back == 'n':
continue
else:
print("***** invalid option ******")
continue
elif choice == '2':
while True:
print("-----------Enter account username-----------")
user_name = input()
print('\n')
print(
"** I can create a password for if you type in - 'gp' \n** Or create your own password with - 'yp'")
codeword = input().lower()
if codeword == 'gp':
user_password = random.randint(
11111, 111111)
print('\n')
print('This is your password')
print(
f" ******* Account: {user_name} *******")
print(
f" ******* Password: {user_password} *******")
print('\n')
elif codeword == 'yp':
print("Create your own password password")
user_password = input()
print(
f" *******Account: {user_name} *******")
print(
f" ******* Password: {user_password} *******")
print('\n')
else:
print(" ****** Enter a valid codeword *****")
print("Back to menu? y/n")
back = input().lower()
if back == 'y':
break
elif back == 'n':
continue
else:
print("***** invalid option ******")
continue
elif choice == '3':
while True:
print("---- search for credential to delete ----")
search_name = input()
# if check_existing_credentials(search_name):
search_credential = find_credential(search_name)
print(
f"Account Name: {search_credential.account_name}\n Password: {search_credential.account_password}")
print("Delete? y/n")
confirm = input().lower()
if confirm == 'y':
delete_credential(search_credential)
print("----- Account successfully removed -----")
break
elif confirm == 'n':
continue
else:
print("** Account does not exist -----")
break
elif choice == '4':
while True:
print("continue? y/n")
option = input().lower()
if option == 'y':
print("*****Enter account name to find credentials*****")
search_name = input()
# if check_existing_credentials(search_name):
search_credential = find_credential(
search_name)
print(
f"Account Name: {search_credential.account_name}\n Password: {search_credential.account_password}")
print("*****Account does not exist *****")
elif option == 'n':
break
else:
print("*****Invalid code*****")
print("*****Invalid code*****")
continue
elif Code == 'ex':
break
else:
print("Enter valid code to continue")
elif Code == 'lg':
print("----- welcome -----")
print("----- Enter user name -----")
user_name = input()
print('\n')
elif choice == '5':
print(
"WARNING all your details will be lost. \n Proceed? y/n")
logout = input().lower()
if logout == 'y':
print("-------- You have logged out successfully --------")
print('\n')
break
elif logout == 'n':
continue
if __name__=='__main__':
main()
|
737ff092b25dbfcc9e6c722bf47ac886640de58e | pchaow/pythonteach | /10_exerciese02_ifans.py | 725 | 3.703125 | 4 | def showMenu():
print("กด 1 เพื่อคำนวณพื้นที่สี่เหลี่ยม")
print("กด 2 เพื่อคำนวณพื้นที่สามเหลี่ยม")
pass
def calRectangleArea():
a:float = float(input('Enter high'))
b:float = float(input('Enter width'))
c:float = a * b
print(c)
pass
def calTriangleArea():
b : float = float(input("Enter your base = "))
h : float = float(input("Enter your High = "))
area = 1/2 * b * h
print(area)
pass
def main():
showMenu()
choice: int = int(input("Select Menu : "))
if choice == 1:
calRectangleArea()
else:
calTriangleArea()
main()
|
fd75771bb774e92be9cb28d7e4291e8dcfa35db8 | Jizishuo/daily_code | /断点调试.py | 637 | 3.609375 | 4 |
def getAv(a, b):
result = a+b
print(result)
return result
a = 100
b =200
c =a+b
ret = getAv(a, b)
print(ret)
#暂停 等输入
#python -m pdb xxx.py
# l list 看走到哪一步(全部代码)
# n next 走一波 (具体哪一行代码)
# c contiue 继续执行代码
# b break 添加断点 b 7 c 执行到第7行停 (可以多个断点)
# clear 1 删除第一个断点
# s ---step 在ret = getAv(a, b) 回进入函数
# p print 打印一个变量的值 p a 打印 100
# a args 打印所有形参的数据 a 打印 a=100, b=200
# q quit 退出调试
# r return 快速执行函数到最后一行
|
eb882962c8b3b36e468abcab6969dbea29617478 | hamedmeshkin/SVM-with-Ada-Boosting | /get_data.py | 2,269 | 3.53125 | 4 | from pandas_datareader import data
import pandas as pd
import matplotlib.pyplot as plt
# Define the instruments to download. We would like to see Apple, Microsoft and the S&P500 index.
tickers = ['AAPL', 'MSFT', '^GSPC']
#tickers = ['^GSPC']
# Define which online source one should use
data_source = 'yahoo'
# We would like all available data from 01/01/2000 until 12/31/2016.
start_date = '2000-01-01'
end_date = '2016-12-31'
# User pandas_reader.data.DataReader to load the desired data. As simple as that.
panel_data = data.DataReader(tickers, data_source, start_date, end_date)
# show the index of each dimension
panel_data.axes
# Getting just the adjusted closing prices. This will return a Pandas DataFrame
# The index in this DataFrame is the major index of the panel_data.
adj_close = panel_data.ix['Adj Close']
# Getting all weekdays between 01/01/2000 and 12/31/2016
all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B')
# How do we align the existing prices in adj_close with our new set of dates?
# All we need to do is reindex close using all_weekdays as the new index
adj_close = adj_close.reindex(all_weekdays)
# Reindexing will insert missing values (NaN) for the dates that were not present
# in the original set. To cope with this, we can fill the missing by replacing them
# with the latest available price for each instrument.
adj_close = adj_close.fillna(method='ffill')
#print(adj_close.head(10))
adj_close.describe()
# save data
#adj_close.to_pickle('three_stocks.pkl')
# Get the snp time series. This now returns a Pandas Series object indexed by date.
snp = adj_close.ix[:, '^GSPC']
# save data
#snp.to_pickle('sp500_adj_close.pkl')
# Calculate the 20 and 100 days moving averages of the closing prices
short_rolling_snp = snp.rolling(window=20).mean()
long_rolling_snp = snp.rolling(window=100).mean()
# Plot everything by leveraging the very powerful matplotlib package
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(snp.index, snp, label='S&P 500')
ax.plot(short_rolling_snp.index, short_rolling_snp, label='20 days rolling')
ax.plot(long_rolling_snp.index, long_rolling_snp, label='100 days rolling')
ax.set_xlabel('Date')
ax.set_ylabel('Adjusted closing price ($)')
ax.legend()
plt.show()
|
f6eb98ee3271c0f5a42b4e02415733ba866bfbd0 | sajanrav/scripts | /remove_outliers.py | 724 | 4.125 | 4 | '''
Script to remove outliers from a series and print
output on console
Usage : python remove_outliers.py <series>
Help : python remove_outliers.py -h
'''
import pandas as pd
import re
import argparse as ag
if __name__ == "__main__":
parser = ag.ArgumentParser()
parser.add_argument('series', help='Enter values seperated by comma', type=str)
args = parser.parse_args()
values = args.series
list_values = [ int(val) for val in values.split(",") ]
ds = pd.Series(list_values)
mean = ds.mean()
std = ds.std()
ds = ds[(ds>(mean-(2*std))) & (ds<(mean+(2*std)))]
print("With outliers : {}".format(list_values))
print("Without outliers : {}".format(ds.tolist()))
|
420c8169ba45632f6c007d8bbbb6ec4f38302fbf | Margasoiu-Luca/Python-Algorithms | /Viva Standard 4 - Sorting Algorithms Comparison/bubbleSort.py | 265 | 4 | 4 |
def bubbleSort(lst):
sorted = False
while not sorted:
sorted = True
for i in range(0, len(lst) - 1):
if lst[i] > lst[i + 1]:
sorted = False
lst[i], lst[i + 1] = lst[i + 1], lst[i]
return lst
|
37782a20480f64d3c46bd85dc073c1219206dcfc | delekta/agh-asd | /2.1dynamic/bonus/DP005.py | 1,817 | 3.9375 | 4 | # Longest increasing subsequence (nlogn)
# finding position for replacing
def binary_search(arr, left, right, searched):
while right >= left:
mid = (right + left) // 2
if arr[mid] == searched:
return mid
elif arr[mid] > searched:
right = mid - 1
elif arr[mid] < searched:
left = mid + 1
# print("Searched:", searched, "left:", left, "right", right)
return left
def LIS(arr):
list_of_tails = [0 for _ in range(len(arr))]
# always points empty slots
length = 0
list_of_tails[0] = arr[0]
length += 1
for el in arr:
if el < list_of_tails[0]:
list_of_tails[0] = el
elif el > list_of_tails[length - 1]:
list_of_tails[length] = el
length += 1
else:
idx = binary_search(list_of_tails, 0, length - 1, el)
list_of_tails[idx] = el
return length
arr = [0, 8, 4, 1, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
print(LIS(arr))
# binary search test
binary_search_test = [2, 4, 6, 7, 8, 10, 12, 13, 14]
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 1)
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 3)
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 5)
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 9)
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 11)
binary_search(binary_search_test, 0, len(binary_search_test) - 1, 15)
# Conclusion: when we have right >= left
# If we search for element that is not included in array, at the end
# right points the greatest element which is smaller than searched
# left point the smallest element which is bigger than searched
|
5c94d3230de3e28e85659b29ff7861e3103ca2f1 | mashworth11/python_tricks | /robots.py | 6,857 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This program is a way of corroborating, and a reference for, some of the things
I learnt from the Python Tricks book. Things included are listed below. The program
itself is based on a robot and it's derivatives, that can do (pretty random)
menial tasks.
Python tricks: patterns for cleaner code (asserts, string interpolation, underscores
and dunders), looping and iteration (generators), classes and OOP (inheritance and
__repr__), dictionary tricks
# python_tricks
Repo for making code snippets of cool python tricks, to try and improve programming skills. robots_py and funky_functions.py are based on notes from the Python tricks book by Dan Bader.
# robots.py
Incorporates OOP with tricks to write cleaner code (asserts, string interpolation, underscores and dunders), looping and iteration (generators), classes and OOP (__repr__), dictionary tricks
"""
import numpy as np
import collections
## asserts, dunders, string interpolation, __repr__ ##
class basic_bot(object):
def __init__(self, name, age):
assert len(name) < 10, 'Name toooo long for a basic bot' # assertion for unexpected error
self.name = name
self.__type = 'basic' # dunder protects 'type' variable values between classes
self.age = age
self.ability = f'{self.name} of bot type {self.__type} can only move'
self.location = np.zeros(2)
def __repr__(self):
"""
__repr__ method adds an unambiguous way of inpsecting a class
"""
return (f'{self.__class__.__name__}({self.name!r}, {self.age!r})') # string interpolation
def move(self):
"""
Method to move to a robot
"""
self.location += np.array([np.random.random(), np.random.random()])
return None
## inheritance with super(), static method, and dictionary unpacking ##
class librarian_bot(basic_bot):
def __init__(self, name, age):
super().__init__(name, age) # super function required for calling constructor, methods and properties of parent class
self.__type = 'librarian'
self.ability = f'{self.name} of bot type {self.__type} can move' + \
' and make a library of books of varying lengths'
@staticmethod # shhhtatic method
def create_library(no_of_books):
"""
Method to create a library of books of varying lengths
"""
library = {}
for i in range(no_of_books):
# An alternative to library.update({'book'+str(i):np.random.randint(1,1001)})
library = dict(library, **{'book'+str(i):np.random.randint(1,1001)}) # dictionary unpacking using **
return library
## default dictionary values i.e. .get(), ask for user input(), assert, ##
## and dictionary udpate ##
class book_worm_bot(basic_bot):
def __init__(self, name, age, library_dict):
super().__init__(name, age)
self.__type = 'book worm'
self.ability = f'{self.name} of bot type {self.__type} can move' + \
' and choose a book from a library'
self.library_dict = library_dict
def choose_a_book(self, book_name):
"""
Method to choose a book from the library, return a default value if
it's not there, and ask for user input on whether you'd like to add it
to the library.
"""
if self.library_dict.get(book_name, None) == None:
answer = input('Would you like to add this book to the library? ')
if (answer == 'Yes') or (answer == 'Y') or (answer == 'y'):
how_long = int(input('How long is the book? '))
assert how_long < 1000, 'Sorry, this library only accepts books under 1000 pgs.'
self.library_dict.update({book_name: how_long})
return self.library_dict
else:
print('Ok, no problemo, have a nice day!')
else:
print(f'Here is {book_name} that you requested, it is'
f' {self.library_dict[book_name]} pages long.') # f needs to be on each line
## dictionary sorting by book length, return a sorted dict ##
class sorting_bot(basic_bot):
def __init__(self, name, age, library_dict):
super().__init__(name, age)
self.__type = 'sorting'
self.ability = f'{self.name} of bot type {self.__type} can move' + \
' and choose a book from a library'
self.library_dict = library_dict
def sort_by_booklength(self):
"""
Method to sort the library by book length
"""
sorted_lib = sorted(self.library_dict.items(), key = lambda x: x[1])
return collections.OrderedDict(sorted_lib)
## private property naming convention, and __str__ method ##
class speaking_bot(basic_bot):
def __init__(self, name, age):
super().__init__(name, age)
self.__type = 'speaking'
self.ability = f'{self.name} of bot type {self.__type} can move' + \
' and can repeat user input'
self._sentence = input(f'Hi, my name is {self.name}, and I just looove'
' to speak. Please give me something to say: ')
def __str__(self):
"""
__str__ method adds some kind of textual information
"""
return self._sentence
## generators and generator expressions, iterator chain ##
class generator_bot(basic_bot):
def __init__(self, name, age, sentence):
super().__init__(name, age)
self.__type = 'generator'
self.ability = f'{self.name} of bot type {self.__type} can move' + \
' and can repeat user input'
self.gen_obj = (sentence for i in range(5)) # generator expression
# create a series of static generator methods that can be used as part of
# an iterator chain
@staticmethod # this needs to come first
def integers():
"""
Method to create an integer generator
"""
for i in range(1,9):
yield i
@staticmethod
def squared(seq):
"""
Method to create an integer generator
"""
for i in seq:
yield i*i
@staticmethod
def halved(seq):
"""
Method to create an integer generator
"""
for i in seq:
yield i/2
@staticmethod
def add_10(seq):
"""
Method to create an integer generator
"""
for i in seq:
yield i + 10
# e.g. chain = halved(add_10(squared(integers())))
|
becd6021ae1564e2f607fd9f7d4f1838bc2ebb37 | kotys07/myfirstprojectpython | /enumerate__.py | 330 | 3.59375 | 4 | date = [2,3,8,9,6,4,7,8,5,41,2,3]
for num, val in enumerate(date, 1):
print(str(num) + '-e значення рівне ' + str(val))
#без функції enumerate
date1 = [5,6,8,9,4,5,22,66,44,56,88,952,1,2,3]
ind = 1
for datee in date1:
print(str(ind) + '-e значення рівне ' + str(datee))
ind += 1
|
a13c476ce123430f92393a790b5a4a8e17b202e2 | snehilk1312/Python-Progress | /shoe_cost.py | 699 | 3.625 | 4 | '''
CALCULATIONS
Explanation
Customer 1: Purchased size 6 shoe for $55.
Customer 2: Purchased size 6 shoe for $45.
Customer 3: Size 6 no longer available, so no purchase.
Customer 4: Purchased size 4 shoe for $40.
Customer 5: Purchased size 18 shoe for $60.
Customer 6: Size 10 not available, so no purchase.
COST(or total money earned)=$55+$45+$40+$60=$200
'''
import collections
X=int(input())
d=dict(collections.Counter(list(map(int,input().split()))))
N=int(input())
cost=0
for i in range(N):
size,price=list(map(int,input().split()))
if size in d:
if d[size]!=0:
d[size]-=1
cost+=price
else:
pass
else:
pass
print(cost)
|
6433a105bf9d5ac3c19962b1ae0cc48a8201386f | romulopro/Hackerrank-Python-Solutions | /Basic Data Types/python-lists.py | 406 | 3.515625 | 4 | if __name__ == '__main__':
N = int(input())
novaLista = []
for i in range(0,N):
ent = input().split()
comando=ent[0]
argu = ent[1:]
if comando != "print":
comando = comando+"("+ ",".join(argu)+ ")"
eval("novaLista."+comando)
else:
print (novaLista, sep=',')
|
90a9dbb83d1e4435cc8ffc6dd45a93629b357305 | lengyugo/leetcode | /BFS_DFS.py | 9,436 | 3.65625 | 4 | """
从上到下打印二叉树3
"""
import collections
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) :
if not root: return []
ans,queue = [],collections.deque()
queue.append(root)
while queue:
tmp = collections.deque()
for _ in range(len(queue)):
node = queue.popleft()
if len(ans) % 2:
tmp.appendleft(node.val)
else:
tmp.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
ans.append(list(tmp))
return ans
"""
朋友圈
"""
class Solution:
def findCircleNum(self, M) -> int:
n = len(M)
visited = [0] * n
ans = 0
queue = []
for i in range(n):
if visited[i] == 0:
queue.append(i)
while queue:
s = queue.pop()
visited[s] = 1
for j in range(n):
if M[s][j] == 1 and visited[j] == 0:
queue.append(j)
ans += 1
return ans
"""
二叉树中和为某一值的路径
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
ans, path = [], []
def recur(root, tar):
if not root: return
path.append(root.val)
tar -= root.val
if tar == 0 and not root.left and not root.right:
ans.append(list(path))
recur(root.left, tar)
recur(root.right, tar)
path.pop()
recur(root, sum_)
return ans
"""
除法求值
先建图,在dfs
"""
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = {}
for (x, y), v in zip(equations, values):
if x in graph:
graph[x][y] = v
else:
graph[x] = {y: v}
if y in graph:
graph[y][x] = 1 / v
else:
graph[y] = {x: 1 / v}
def dfs(s, t):
if s not in graph:
return -1
if s == t:
return 1
for node in graph[s].keys():
if node == t:
return graph[s][node]
elif node not in visited:
visited.add(node)
v = dfs(node, t)
if v != -1:
return graph[s][node] * v
return -1
ans = []
for ds, dt in queries:
visited = set()
ans.append(dfs(ds, dt))
return ans
"""
课程表
"""
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
ind = [0 for _ in range(numCourses)]
adj = [[] for _ in range(numCourses)]
for cur,per in prerequisites:
ind[cur] += 1
adj[per].append(cur)
print(ind,adj)
q = collections.deque()
for i in range(len(ind)):
if not ind[i]: q.append(i)
print(q)
while q:
per = q.popleft()
numCourses -= 1
for cur in adj[per]:
ind[cur] -= 1
#print(ind[cur])
if not ind[cur]: q.append(cur)
return not numCourses
"""
课程表2
"""
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
edges = collections.defaultdict(list)
inges = [0] * numCourses
ans = list()
for info in prerequisites:
edges[info[1]].append(info[0])
inges[info[0]] += 1
q = collections.deque([u for u in range(numCourses) if inges[u]==0])
while q:
u = q.popleft()
ans.append(u)
for v in edges[u]:
inges[v] -= 1
if inges[v] == 0:
q.append(v)
if len(ans) != numCourses:
ans = list()
return ans
"""
字符串解码
"""
class Solution:
def decodeString(self, s: str) -> str:
def dfs(s,i):
ans,mutil = '', 0
while i < len(s):
if '0' <= s[i] <= '9':
mutil = mutil * 10 + int(s[i])
#print(mutil)
elif s[i] == '[':
i,tmp = dfs(s,i+1)
ans += mutil * tmp
print(ans)
mutil = 0
elif s[i] == ']':
return i,ans
else:
ans += s[i]
i+=1
return ans
return dfs(s,0)
"""
字符串解码
"""
class Solution:
def decodeString(self, s: str) -> str:
stack,mutli,ans = [],0,''
for c in s:
if c == '[':
stack.append([mutli,ans])
mutli,ans = 0,''
elif c == ']':
cur_mutli,last_ans = stack.pop()
ans = last_ans + cur_mutli * ans
elif '0' <= c <= '9':
mutli = mutli * 10 + int(c)
else:
ans += c
return ans
"""
删除无效括号
"""
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def isValued(s):
cnt = 0
for c in s:
if c == '(':
cnt += 1
elif c == ')':
cnt -= 1
if cnt < 0: return False
return cnt == 0
level = {s}
while True:
print(level)
vailued = list(filter(isValued, level))
print(vailued)
if vailued: return vailued
next_level = set()
for item in level:
for i in range(len(item)):
if item[i] in '()':
next_level.add(item[:i] + item[i + 1:])
level = next_level
"""
单词接龙
"""
from collections import defaultdict,deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList or not beginWord or not endWord or not wordList:
return 0
all_word = defaultdict(list)
for word in wordList:
for i in range(len(beginWord)):
all_word[word[:i]+'-'+word[i+1:]].append(word)
print(all_word)
queue = [(beginWord,1)]
visited = {beginWord:True}
while queue:
cur_word,level = queue.pop(0)
for i in range(len(beginWord)):
match = cur_word[:i] + '-' + cur_word[i+1:]
for word in all_word[match]:
if word == endWord:
return level + 1
if word not in visited:
visited[word] = True
queue.append((word,level+1))
all_word[match] = []
return 0
"""
单词接龙2
"""
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
wordList.append(beginWord)
buckets = defaultdict(list)
for word in wordList:
for i in range(len(beginWord)):
match = word[:i] + '-' + word[i + 1:]
buckets[match].append(word)
# print(buckets)
preWords = defaultdict(list)
toSeen = deque([(beginWord, 1)])
beFound = {beginWord: 1}
while toSeen:
curWord, level = toSeen.popleft()
for i in range(len(beginWord)):
match = curWord[:i] + '-' + curWord[i + 1:]
for word in buckets[match]:
if word not in beFound:
beFound[word] = level + 1
toSeen.append((word, level + 1))
if beFound[word] == level + 1:
preWords[word].append(curWord)
if endWord in beFound and level + 1 > beFound[endWord]:
break
# print(preWords)
if endWord in beFound:
ans = [[endWord]]
while ans[0][0] != beginWord:
ans = [[word] + r for r in ans for word in preWords[r[0]]]
print(ans)
return ans
else:
return []
"""
矩阵中的路径
"""
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(i,j,k):
if not 0 <= i < len(board) or not 0<= j < len(board[0]) or board[i][j] != word[k]:
return False
if k == len(word) -1: return True
tmp,board[i][j] = board[i][j],'/'
ans = dfs(i-1,j,k+1) or dfs(i+1,j,k+1) or dfs(i,j-1,k+1) or dfs(i,j+1,k+1)
board[i][j] = tmp
return ans
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i,j,0): return True
return False |
d80da4d195e9bca9aff68848788bf8a6b9214e60 | zihuaweng/leetcode-solutions | /leetcode_python/bisection_algorithm.py | 1,505 | 4.03125 | 4 | # Time complexity: O()
# Space complexity: O()
# Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.
"""Bisection algorithms."""
def bisect_right(a, x, lo=0, hi=None):
"""寻找右边界,所有左边数, a[:i]小于等于x, 所有右边数, a[i:], 大于x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
a[mid] > x: hi = mid
a[mid] == x: lo = mid + 1
a[mid] < x: lo = mid + 1
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if x < a[mid]:
hi = mid
else:
lo = mid + 1
return lo
def bisect_left(a, x, lo=0, hi=None):
"""寻找左边界,所有左边数, a[:i]小于x, 所有右边数, a[i:], 大于等于x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
a[mid] > x: hi = mid
a[mid] == x: hi = mid
a[mid] < x: lo = mid + 1
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
# Overwrite above definitions with a fast C implementation
try:
from _bisect import *
except ImportError:
pass
# Create aliases
bisect = bisect_right
insort = insort_right
|
95907a05c512a4d97deda0e9e008152cd17e36d2 | snigi-gupta/Algorithms | /Insertion_Sort.py | 737 | 4.21875 | 4 | # https://www.geeksforgeeks.org/insertion-sort/
class InsertionSort:
# O(n^2)
def sorting(self, A):
for i in range(1, len(A)):
unsorted_element = A[i]
# print("A[{}] = {}".format(i,unsorted_element))
j = i-1
# print("j = {}".format(j))
while unsorted_element < A[j] and j >= 0:
A[j+1] = A[j]
# print("A[{}] = A[{}]: {}".format(j+1, j, A))
j -= 1
A[j+1] = unsorted_element
# print("A[{}] = {}".format(j+1, unsorted_element))
# print("A", A)
return A
if __name__ == "__main__":
A = [38,27,43,3,9,82,10]
obj = InsertionSort()
print("Sorted", obj.sorting(A)) |
4d1bb2f8fff41233c5970d473bf486ac889d6b78 | nicolascarratala/2020.01 | /59174.Calderón.Federico/tp.2020.0512/app.py | 2,139 | 3.984375 | 4 | from person import Person
from personService import PersonService
if __name__ == "__main__":
personService = PersonService()
print("\nMenu")
print("0: para mostrar menú")
print("1: para mostrar base de datos")
print("2: para agregar personas a la base de datos")
print("3: para modificar datos de las personas")
print("4: para eliminar datos de una persona\n")
while True:
entrada = int(input("Seleccione una opción: "))
if entrada == 0:
print("\nMenu")
print("0: para mostrar menú")
print("1: para mostrar base de datos")
print("2: para agregar una persona a la base de datos")
print("3: para modificar datos de una persona")
print("4: para eliminar datos de una persona\n")
if entrada == 1:
print("\nBase de datos\n")
print(personService.get_personList())
print("")
if entrada == 2:
nPersons = int(input("\nCuantas personas desea agregar: "))
for i in range(nPersons):
pi = Person()
pi.name = input("Ingrese nombre: ")
pi.surname = input("Ingrese apellido: ")
pi.age = input("Ingrese edad: ")
personService.add_person(pi)
print("\nPersona agregada correctamente!!\n")
if entrada == 3:
nPersons = int(input("Cuantas personas desea modificar: "))
for i in range(nPersons):
key = int(input("Inserte clave de datos de persona: \n"))
pi = Person()
pi.name = input("Ingrese nombre: ")
pi.surname = input("Ingrese apellido: ")
pi.age = input("Ingrese edad: ")
personService.update_person(key, pi)
print("\nPersona modificada correctamente!!\n")
if entrada == 4:
print("Eliminar datos de persona\n")
key = int(input("Ingrese la clave de la persona a eliminar: "))
print(personService.delete_person(key))
print("\nDatos eliminados correctamente\n")
|
d21ab956224ac4d67ad63eb31b7734723189056a | Spydy/Advent-of-Code-2019 | /1/advent_1_2.py | 523 | 3.6875 | 4 | import math
total_fuel_need = 0
with open("input.txt", "r") as input_file:
line = input_file.readline()
while line:
module_mass = int(line)
fuel = math.floor(module_mass / 3) - 2
total_fuel_need += fuel
additional_fuel_need = math.floor(fuel / 3) - 2
while additional_fuel_need > 0:
total_fuel_need += additional_fuel_need
additional_fuel_need = math.floor(additional_fuel_need / 3) - 2
line = input_file.readline()
print(total_fuel_need)
|
2828d3f8fdb477dfcf0d0d02415cf4a4f369860d | gustavocrod/os-process | /src/main.py | 1,348 | 3.71875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python3
from process import Process
from scheduler import Scheduler
from random import randrange
def make_processes(n=5):
"""
Funcao para gerar processos para teste
:param num: quantidade de processos
:return:
"""
dados = []
for p in range(n):
process = dict()
process['pid'] = p + 1 # id do processo
process['size'] = randrange(1, 15) # tamanho
process['priority'] = int(randrange(1, 20)) # prioridade
process['arrival_time'] = int(randrange(0, 9)) # tempo de chegada
dados.append(process)
return dados
if __name__ == "__main__":
quantum = 4
dados = make_processes()
# Printa os simbolos dos estados dos processos
print(" ===>> LEGENDA <<===")
print("Processo em espera: _ ")
print("Processo em execução: x")
print("Processo terminado: .")
processes = []
for dado in dados:
# criando os dados
p = Process(dado)
processes.append(Process(dado))
# Chamada dos métodos dos algoritmos de escalonamento
sche = Scheduler(processes)
sche.first_come_first_served()
sche = Scheduler(processes)
sche.shortest_job_first()
sche = Scheduler(processes)
sche.round_robin(quantum)
sche = Scheduler(processes)
sche.priority()
|
2f578381f4da158f9a0031cfa1706add3eaf6961 | gavt45/nti_2017_gornostay | /wave_1/gav_solutions/nti_7_8.py | 1,539 | 3.78125 | 4 | import math
x1,y1,x2,y2,x3,y3=0, 2, 2, 0, 2, 2#input().split()
dots=[(x1,y1),(x2,y2),(x3,y3)]
dx,dy=3, 1#input().split()
"""
Этот код не работает
Я его не дописал
"""
"""
x1,y1 --- a
x2,y2 --- b
x3,y3 --- c
"""
def deg(rad):
return (rad*180)/math.pi
def border_length(x1,y1,x2,y2):
return math.sqrt(((x1+x2)/2)**2+((y1+y2)/2)**2)
def get_angle(dx,dy,x1,y1,x2,y2):
a=border_length(dx,dy,x2,y2)
b=border_length(dx,dy,x1,y1)
c=border_length(x1,y1,x2,y2)
cosa = (b**2+c**2-a**2)/(2*b*c)
return math.acos(cosa)
"""
dangles=[]
dangles.append(get_angle(dx,dy,x1,y1,x2,y2))
dangles.append(get_angle(dx,dy,x2,y2,x3,y3))
dangles.append(get_angle(dx,dy,x3,y3,x1,y1))
angles=[]
angles.append(get_angle(x3,y3,x1,y1,x2,y2))
angles.append(get_angle(x3,y3,x2,y2,x3,y3))
angles.append(get_angle(x2,y2,x3,y3,x1,y1))
lens=[]
lens.append(border_length(x1,y1,x2,y2))
lens.append(border_length(x2,y2,x3,y3))
lens.append(border_length(x3,y3,x1,y1))
print "dangles: ",map(deg, dangles)
print "angles: ",map(deg, angles)
"""
def get_blizh():
lengths = []
blizh = []
for dot1 in dots:
lengths.append(border_length(dx,dy,dot[0],dot[1]))
lengths.remove(max(lengths))
for dot in dots:
if lengths.__contains__(border_length(dx,dy,dot[0],dot[1])):
blizh.append(dot)
return blizh
for i in range(0,3):
print "angle:",angles[i],";dangle:",dangles[i]
if angles[i] >= dangles[i]:
print "final: ",lens[i]
elif angles[i] < dangles[i]:
print "final: ",lens[i]+lens[i+1]
|
99f3cdd7f103ca3e0c2637af351a1855bc709298 | henrikgruber/PythonSIQChallenge | /#3 TrackingGamificationApp/results.py | 2,963 | 3.84375 | 4 | # pandas is being used for dataframes (loading all data from survey results)
import pandas
# matplotlib is neccesary for creating statistical diagrams based on former surveys
import matplotlib.pyplot as plt
# squarify is necessary for creating a treemap diagram
import squarify as sq
def write_results(p_person,p_category,p_confidence,p_date):
df_write = pandas.DataFrame({'\n\nPerson': [p_person],
'Category': [p_category],
'Confidence': [p_confidence],
'Date': [p_date]})
df_write.to_csv('tracking_results.csv', mode='a', header=False,index=False)
return
def create_diagrams():
tracking_results = pandas.read_csv('tracking_results.csv')
print("")
print("")
print("Additionally, you'll find some diagrams about our stored data.")
print("")
# part 2 - Creating a treemap to show distribution
results_grouped = tracking_results.groupby("Category", as_index=False)["Confidence"].sum()
sq.plot(sizes=results_grouped['Confidence'], label=results_grouped['Category'], alpha=.8 )
# Hiding axis
plt.axis('off')
# Set labels
plt.title("Confidence per Category")
#View the plot
plt.show()
# part 3 - piechart
#grouped by surveys, build the sum
results_by_area = tracking_results.groupby("Category", as_index=False)["Confidence"].count()
# sum the instances of A (position 0) and B (position 1)
A_results = results_by_area.loc[0,"Confidence"]
B_results = results_by_area.loc[1,"Confidence"]
# put them into a list called proportions
proportions = [A_results, B_results]
plt.pie(
# using proportions
proportions,
# with the labels being names
labels = ['A', 'B'],
# with no shadows
shadow = False,
# with colors
colors = ['blue','red'],
# with one slide exploded out
explode = (0.15 , 0),
# with the start angle at 90%
startangle = 90,
# with the percent listed as a fraction
autopct = '%1.1f%%'
)
# View the plot drop above
plt.axis('equal')
# Set labels
plt.title("Points achieved in areas")
# View the plot
plt.tight_layout()
plt.show()
return
def motivational_booster():
print("")
print("")
print("Keep up the good work")
print("")
print("")
print("")
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.'_'._ ")
print("")
print("")
return
motivational_booster() |
437d221e004f89fb5725efd0aadfcce3349a2625 | isabella0428/Leetcode | /python/102.py | 1,170 | 3.71875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [[root]]
ans = [[root.val]]
start = 1
while start <= len(stack):
nodelist = stack[-1]
level = []
tmp = []
for node in nodelist:
if node.left:
level.append(node.left)
tmp.append(node.left.val)
if node.right:
level.append(node.right)
tmp.append(node.right.val)
if len(tmp) != 0:
start += 1
ans.append(tmp)
stack.append(level)
else:
break
return ans
if __name__ == "__main__":
a = Solution()
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(a.levelOrder(root))
|
d012dff406762cfe3fba2c672618b85684133a96 | magladde/Python-CSC-121 | /Lesson 11/Lab11P01.py | 1,675 | 4.125 | 4 | # Lab 11 Problem 1
def main():
# get user input
user_input = input('Enter a string: ')
dictionary = get_dictionary(user_input)
print(dictionary)
# take user input and check if in dictionary
user_char = input('Choose a letter: ')
dictionary = char_count(user_char, dictionary)
print('Dictionary after that letter removed:', dictionary)
# create a list that stores the letters in dictionary and srot and display list
letters = dictionary.keys()
sorted_characters = sorted(letters)
print('Letters sorted:', sorted_characters)
# convert user input into a dictionary containing the count of each character
def get_dictionary(user_input):
user_input = user_input.upper()
# generate list of letters, non overlapping
string_length = len(user_input)
characters = []
for i in range(string_length):
if user_input[i].isalpha():
if user_input[i] not in characters:
characters.append(user_input[i])
# count the occurance of characters in list characters
char_count = []
for i in range(len(characters)):
char_count.append(user_input.count(characters[i]))
# combine two lists, convert to dictionary
combined = list(zip(characters, char_count))
dictionary = dict(combined)
return(dictionary)
# checks to see if character is in dictionary and displays frequency, removes character from dictionary
def char_count(x, dictionary):
x = x.upper()
if x in dictionary:
print('Frequency count of that letter: ', dictionary[x])
del dictionary[x]
else:
print('Letter not in dictionary.')
return(dictionary)
main() |
a2d33e7813f4bbe79c712a2aaf7725c1e020767d | rainydayinlondon/Python_Basic_Applications | /largest_number.py | 457 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 13:31:32 2021
@author: Feyza
"""
# Python program to find largest
# number in a list
def high_and_low(numbers):
max = numbers[0]
min =numbers[0]
for i in numbers:
if i>max:
max=i
if i<min:
min=i
return max,min
numbers=[1364,6,2,9,3]
print("Largest element and min number:", high_and_low(numbers)) |
d39d4239828afc862e7053b21052eb94b84812c6 | Limarceu/CorrelacaoRegressao | /janela/programinha.py | 1,359 | 3.6875 | 4 | '''Este é um programa complementar a disciplina de análise exploratória.add()'''
'''Este programa serve para resolver exercicios de correlação e regressão linear,
dado um dataset ou um banco de dados.'''
import tkinter as tk
janela = tk.Tk()
janela.title('Correlacao e Regressao')
janela.geometry('300x500')
#função faz algo
def add():
res_box.delete(1.0, 'end')
try:
res_box.insert(tk.INSERT, int(first_nr.get()) + int(second_nr.get())
except ValueError:
res_box.insert(tk.TK(INSERT, 'number required')
def sub():
res_box.delete(1.0, 'end')
try:
res_box.insert(tk.INSERT, int(first_nr.get()) - int(second_nr.get()))
except ValueError:
res_box.insert(tk.INSERT, 'Number Required')
#all elements inside the window
lbl_nr_one = tk.Label(janela, text='Digite o primeiro numero: ', bg='green')
lbl_nr_one.pack(padx = 5, pady = 5)
lbl_nr_two = tk.Label(janela, text = "Digite o segundo número", bg='red')
lbl_nr_two.pack(padx=10,pady=5)
button_add = tk.Button(janela, text='Numeros Adicao', command = add)
button_add.pack()
button_sub = tk.Button(janela, text = 'subtract numero', command=sub)
button_sub.pack()
lbl_res = tk.Label(janela, text='Resuldado é: ')
lbl_res.pack(padx=10, pady=5)
res_box = tk.Text(janela, width=15, height = 1)
res_box.pack(padx=10, pady=5)
janela.mainloop()
|
c4b0f3a58198985452ea4914ef1454682d4f02d4 | sungwooman91/python_code | /01.jump_to_python/정리/jumptopy_summary.py | 357 | 3.984375 | 4 | #문자열 슬라이싱
a="Life is too short, You need Python"
b=a[0]+a[1]+a[2]+a[3]
print(b)
print(a[0:4])
print(a[12:17])
print(a[19:])
# 문자열 삽입
a=' '
a.join('Life')
print(a.join('Life'))
#리스트에 요소 추가
b=['human','animal','mammal']
b.append(['insect','reptilia'])
print(b)
a="Life si too short"
a.index('t')
print(a.index('t'))
|
3f363df84abe3861510b9303b000956ad4bbe447 | JoshuaNow/Digital-Crafts-Classes | /Python/day_3/exercises/sm2-Helloyou.py | 184 | 4.15625 | 4 | #small exercise
name = input("What is your name?\n".upper())
num = str(len(name))
print(f"Hello, {name}.".upper())
print("Your name has ".upper() + num +" letters in it!".upper())
|
a48e52e75768a2cd618c3d1f94ea6205b995bc1f | CraneJen/Python-Learning | /do_reduce.py | 933 | 3.71875 | 4 | from functools import reduce
print('=== Reduce ===')
def fn(x, y):
return x * 10 + y
result = reduce(fn, [1, 3, 5, 7, 9])
result1 = reduce(lambda x, y: x * 10 + y, [1, 3, 5, 7, 9])
print("Result: {result}".format(result=result))
print("Result1: {result1}".format(result1=result1))
# result: 13570
print("=== Reduce & Map ===")
def char2int(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
s = '1234'
result2 = reduce(fn, map(char2int, s))
print("Result2: {result2}".format(result2=result2))
print("=== Palindrome ===")
def is_palindrome(n):
# n = str(n)
# return n == n[::-1]
lsn = list(str(n))
# ls = lsn[:]
# ls = list(lsn)
ls = lsn * 1
lsn.reverse()
return ls == lsn
output = filter(is_palindrome, range(1, 1000))
print(list(output))
# print(range(1, 1000))
print(list(filter(lambda n: str(n) == str(n)[::-1], range(1, 1000))))
|
2d91b05cce74f23094d6f5177d768a5de834f0ac | Aasthaengg/IBMdataset | /Python_codes/p02713/s042769760.py | 204 | 3.640625 | 4 | import math
k=int(input())
result=0
for i in range(1,k+1):
for j in range(1,k+1):
first=math.gcd(i,j)
for g in range(1,k+1):
result=result+math.gcd(first,g)
print(result)
|
47e869c625a2c8769d7e7765ef5f992404fd6eeb | javedmomin99/Find-the-greatest-Number-out-of-3-numbers | /main.py | 384 | 4.1875 | 4 | def name(num1,num2,num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
else:
return num3
num1 = int(input("pls enter number 1\n"))
num2 = int(input("pls enter number 2\n"))
num3 = int(input("pls enter number 3\n"))
print(name(num1,num2,num3))
print("The greatest number is " + str(name(num1,num2,num3))) |
3aae94d7136065259d2d995b83ee6e5e877c7c46 | jonas-skywalker/linear-equation-system | /lgs.py | 978 | 3.875 | 4 | # Python file to calculate a LGS with Gaussian elimination
zero = [0]
def calcStepform(stepmatrix):
# Stepform example
# 2 4 2 | 1
# 1 2 | 2
# 3 | 3
def calcEquation(equation):
# This is a function to calculate solution of a simple equation
if len(equation) > 2:
for i in range(1, len(equation)-1):
equation[-1] = equation[-1] - equation[i]
solution = 1 / equation[0] * equation[-1]
return solution
else:
solution = 1 / equation[0] * equation[1]
return solution
def scramble(equation):
for i in range(len(equation) - 2):
print(len(equation))
if equation[i] == 0:
equation.pop(i)
stepmatrix1 = [[1* x3, -1 * x2, 2 * x1, 0],
[-1, -2, 0],
[-6, 3]]
matrix1 = [[1, -1, 2, 0],
[0, -1, -2, 0],
[0, 0, -6, 3]]
print(calcStepform(stepmatrix1))
# calcEquation([1, 2, 3, 4])
# print(calcEquation(equation))
|
6e1ebc1b1f077968f102c31e157e7d1af37a0e3a | TuhinChandra/PythonLearning | /Basics/Shaswata/test5_video12_intFunc.py | 599 | 4.375 | 4 | print('int function examples are here...')
x = '1100'
print("x =", x)
print("type of x :", type(x))
# int string -> int
print('int string -> int')
y = int(x) # default base is 10
print("y =", y)
print("type of y :", type(y))
# binary string -> int
print('binary string -> int')
z = int(x, 2)
print("z =", z)
# ValueError: invalid literal for int() with base 2: '1234'
x = '12347'
print("x =", x)
# y = int(x, 2)
# Oct string -> int
print('Oct string -> int')
y = int(x, 8)
print("y =", y)
# Hex string -> int
print('Hex string -> int')
x = '1a'
print("x =", x)
y = int(x, 16)
print("y =", y)
|
664138a61dad23395541542ff15080a24aa7cc63 | Rushi21-kesh/30DayOfPython | /Day-13/Day13-by-ShubbhRMewada.py | 691 | 3.875 | 4 | def binary_search(l,x):
start=0
end=len(l)-1
if(len(l)>1):
mid=(start+end)//2
if(x==l[mid]):
print(mid)
else:
if(x>l[mid]):
l=l[mid+1:end+1]
else:
l=l[start:mid]
return binary_search(l,x)
if (l[start]==x) or (l[end]==x) :
print(start)
else:
print('-1')
n=int(input('Enter the Size of your List: '))
l=[]
for i in range(n):
l.append(int(input(f'Enter Numner {i+1}: ')))
print(binary_search(l,x=int(input("Enter the Value to be found: ")))) |
0b57b801957b0e9c40decffd314170e5f04cec1a | kckotcherlakota/algoexpert-data-structures-algorithms | /Hard/quickselect.py | 952 | 3.765625 | 4 |
# QUICK SELECT
# BEST AND AVERAGE: O(N) time and O(1) space
# WORST: O(N^2) time and O(1) space
def quickselect(array, k):
# Write your code here.
position = k - 1
return quickSelectHelper(array, 0, len(array) - 1, position)
def quickSelectHelper(array, startIdx, endIdx, position):
while True:
if startIdx > endIdx:
raise Exception("Should not occur")
pivotIdx = startIdx
leftIdx = startIdx + 1
rightIdx = endIdx
while leftIdx <= rightIdx:
if array[leftIdx] > array[pivotIdx] and array[rightIdx] < array[pivotIdx]:
swap(leftIdx, rightIdx, array)
if array[leftIdx] <= array[pivotIdx]:
leftIdx += 1
if array[rightIdx] >= array[pivotIdx]:
rightIdx -= 1
swap(pivotIdx, rightIdx, array)
if rightIdx == position:
return array[rightIdx]
elif rightIdx < position:
startIdx = rightIdx + 1
else:
endIdx = rightIdx - 1
def swap(one, two, array):
array[one], array[two] = array[two], array[one] |
9a7788a6a1f394b8b101e568cc44d5d21f70b1fd | ireprincev/pinpong | /104580/training_classes_1.py | 554 | 3.6875 | 4 | class Button():
def __init__(self, title_text, x_num, y_num):
self.title = title_text
self.x = x_num
self.y = y_num
self.appearance = True
def hide(self ):
self.appearance = False
def show(self ):
self.appearance = True
def print_status(self):
print('Данные о виджете:')
print(self.title, self.x, self.y, self.appearance)
ok_button = Button('ok', 100, 100)
ok_button.print_status()
ok_button.hide()
ok_button.print_status()
ok_button.show()
ok_button.print_st |
4e078974e70c9b6a446b50b8d803a3e64e444594 | sinofeng/vlcp | /vlcp/event/future.py | 5,862 | 3.703125 | 4 | '''
Created on 2016/9/28
:author: hubo
Future is a helper class to simplify the process of retrieving a result from other routines.
The implementation is straight-forward: first check the return value, if not set, wait for
the event. Multiple routines can wait for the same Future object.
The interface is similar to asyncio, but:
- Cancel is not supported - you should terminate the sender routine instead. But `RoutineFuture` supports
`close()` (and `cancel()` which is the same)
- Callback is not supported - start a subroutine to wait for the result instead.
- `result()` returns None if the result is not ready; `exception()` is not supported.
- New `wait()` async function: get the result, or wait for the result until available. It is
always the recommended way to use a future; `result()` is not recommended.
`wait()` will NOT cancel the `Future` (or `RoutineFuture`) when the waiting coroutine is
closed. This is different from `asyncio.Future`. To ensure that the future closes after awaited,
use `wait_and_close()` of `RoutineFuture`.
- `ensure_result()` returns a context manager: this should be used in the sender routine,
to ensure that a result is always set after exit the with scope. If the result is not set,
it is set to None; if an exception is raised, it is set with set_exception.
Since v2.0, you can directly use `await future` to wait for the result
'''
from vlcp.event.event import withIndices, Event
from contextlib import contextmanager
from vlcp.event.runnable import GeneratorExit_
@withIndices('futureobj')
class FutureEvent(Event):
pass
class FutureCancelledException(Exception):
pass
class Future(object):
"""
Basic future object
"""
def __init__(self, scheduler):
self._scheduler = scheduler
def done(self):
'''
:return: True if the result is available; False otherwise.
'''
return hasattr(self, '_result')
def result(self):
'''
:return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that.
'''
try:
r = getattr(self, '_result')
except AttributeError:
return None
else:
if hasattr(self, '_exception'):
raise self._exception
else:
return r
async def wait(self, container = None):
'''
:param container: DEPRECATED container of current routine
:return: The result, or raise the exception from set_exception.
'''
if hasattr(self, '_result'):
if hasattr(self, '_exception'):
raise self._exception
else:
return self._result
else:
ev = await FutureEvent.createMatcher(self)
if hasattr(ev, 'exception'):
raise ev.exception
else:
return ev.result
def set_result(self, result):
'''
Set the result to Future object, wake up all the waiters
:param result: result to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = result
self._scheduler.emergesend(FutureEvent(self, result = result))
def set_exception(self, exception):
'''
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = None
self._exception = exception
self._scheduler.emergesend(FutureEvent(self, exception = exception))
@contextmanager
def ensure_result(self, supress_exception = False, defaultresult = None):
'''
Context manager to ensure returning the result
'''
try:
yield self
except Exception as exc:
if not self.done():
self.set_exception(exc)
if not supress_exception:
raise
except:
if not self.done():
self.set_exception(FutureCancelledException('cancelled'))
raise
else:
if not self.done():
self.set_result(defaultresult)
def __await__(self):
return self.wait().__await__()
class RoutineFuture(Future):
'''
Quick wrapper to create a subroutine and return the result to a Future object
'''
def __init__(self, subprocess, container):
'''
Start the subprocess
:param subprocess: a generator process, which returns the result to future on exit
:param container: the routine container to run the subprocess with
'''
Future.__init__(self, container.scheduler)
async def _subroutine():
with self.ensure_result(True):
try:
r = await subprocess
except GeneratorExit_:
raise FutureCancelledException('close is called before result returns')
else:
self.set_result(r)
self._routine = container.subroutine(_subroutine())
def close(self):
'''
Terminate the subprocess
'''
if not self.done():
self._routine.close()
def cancel(self):
'''
Same as close()
'''
self.close()
async def wait_and_close(self):
"""
wait for result; always close no matter success or failed
"""
try:
return await self.wait()
finally:
self.close()
|
1d3d5c687466d19eafd29d449b5c3696241fba82 | Bikashacharaya/Jspider_Python | /Number Series/Q_1.py | 218 | 3.859375 | 4 | # Ouput : 1 4 9 8 15 12 21 16
num = int(input("Enter any number: "))
x = 1
print(x, end=" ")
for i in range(2, num+1):
if(i % 2 == 0):
print(i*2, end=" ")
else:
print(i*3, end=" ")
|
d5e2f4c0eb891da663c31e7990d99f40faa5c463 | Daweet/ImmersiveData | /Employee_Pay.py | 2,262 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Assignment:
#
# Using a text editor, write a program that calculates the salary for the week of the employees listed below. If an employee worked more than 40 hours that week, then calculate the remaining hours as time and a half (1.5x the normal rate).The program should print their name and salary earned. Upload your finished script to Github and use its URL for your assignment submission.
# In[10]:
employee_data = [['ID_Number', 'Name', 'Pay_Rate', 'Hours_Worked'],[1, 'Mary', 15.00, 40], [2, 'John', 22.00, 25],
[3, 'Bob', 35.00, 4], [4, 'Mel', 43.00, 62],
[5, 'Jen', 17.00, 33],[6, 'Sue', 29.00, 45],
[7, 'Ken', 40.00, 36],[8, 'Dave', 20.00, 17],
[9, 'Beth', 37.00, 37],[10, 'Ray', 16.50, 80]]
#Let me retrive important datas for calculating the pay and this are Name, Hours, and Rate
Employee_Name = []
for employee in employee_data[1:]: # loops through the big list employee_data
Employee_Name.append(employee[1] ) # adds it to Employee_Name list
Hours_Worked = []
for employee in employee_data[1:]: # loops through the big list employee_data
Hours_Worked.append(employee[3] ) # adds it to Hours_Worked list
Pay_Rate = []
for employee in employee_data[1:]: # loops through the big list employee_data
Pay_Rate.append(employee[2] )# adds it to Pay_Rate list
# Define a function that calculates the salary
def payroll(Hours_Worked, Pay_Rate):
if Hours_Worked <= 40:
Salary = (Pay_Rate * 40)
else:
Salary = (Pay_Rate * 40) + (Hours_Worked - 40)*Pay_Rate*1.5
return Salary
# Make a dictionary with Hours_Worked and Pay_Rate list
Salary_dict = dict(zip(Hours_Worked, Pay_Rate))
# Calculate the salary using payroll function and put it as list
Salary_cal = []
for key, value in Salary_dict.items(): # loops through the big list (wines)
Salary_cal.append(payroll(key , value ) )
#return Salary_cal
# Make a dictionary with Employee's name as key and its salary as value
Salary_Employee = dict(zip(Employee_Name, Salary_cal))
# Print the salary of each employee along thierr names
for key, value in Salary_Employee.items():
print(f"Salary earned by {key} is ${value} ")
# In[ ]:
|
116223430e82bb0d6128c7e04cffefe78dedd4d7 | mking20/RouteAlgorithmsSimulator | /AStar.py | 569 | 4.375 | 4 | """This function receives a two-dimensional list of 0's and 1's that represents a square maze, a tuple (row, column)
for the starting tile and a tuple(row, column) for the goal tile, and a boolean variable predermined to True indicating
if one can travel diagonally between two adjacent tiles or not. It returns a list of tuples (row, column) of all
the tiles that form the path between the start and the goal; None is returned if no path is found. """
def AStar(maze, startTuple, endTuple, diagonalsAllowed=True):
return """List of tuples of the path's tiles """
|
5187345b08faa0b3520a4051574bc7f7eaff5c90 | dixit5sharma/Individual-Automations | /Pandas_Numpy/Vectors_Numpy.py | 1,361 | 4.09375 | 4 | import numpy as np
""" Vectors in Normal Python """
u = [1,0]
v = [0,1]
z=[]
for n,m in zip(u,v):
z.append(n+m)
print(z)
""" Vectors from Numpy """
u = np.array([1,0])
v = np.array([0,1])
z = u+v
print(z)
k = u-v
print(k)
""" Scalar Multiplication in Normal Python """
y = [1,2]
z = []
for n in y:
z.append(2*n)
print(z)
""" Scalar Multiplication with Numpy """
y = np.array([1,2])
z = 2*y
print(z)
""" Multiplication of Vectors in Normal Python """
u = [1,2]
v = [3,4]
z=[]
for n,m in zip(u,v):
z.append(n*m)
print(z)
""" Multiplication of Vectors from Numpy """
u = np.array([1,2])
v = np.array([3,4])
z = u*v
print(z)
""" Dot Product in Numpy """
u = np.array([1,2])
v = np.array([3,4])
z = np.dot(u,v)
print(z)
""" BroadCasting or Scalar Addition to a Vector """
u = np.array([1,2,3,4,5])
z = u+1
print(z)
""" Universal Functions """
u = np.array([1,2,-3,4,5,-6])
print(u.mean()) # Mean = Sum/Count
print(u.max()) # Returns Maximum value of the array
print(np.pi) # Numpy PI value
x = np.array([0,np.pi/2,np.pi])
y = np.sin(x) # Applies to all the element in X
print(y)
print(np.linspace(-5,5,num=11)) # Creates a numpy array with 11 numbers equally spaces between -5 to 5
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show() |
b13222ac6218429d7a40ab2e67e4f8b8be68b14f | jean-guo/unitconvert | /unitconvert/distance.py | 630 | 4.15625 | 4 | """
A python module for converting distances between miles and kilometers
"""
import numpy as np
def miles_to_kilometers(miles):
"""Convert miles to kilometers
PARAMETERS
----------
miles : float
A distance in miles
RETURNS
-------
distance : float
"""
# apply formula
return miles*1.609344
def kilometers_to_miles(kilo):
"""Convert kilometers to miles
PARAMETERS
----------
kilo : float
A distance in kilometers
RETURNS
-------
distance : float
"""
# apply formula
return kilo*0.621371
|
999e5ad143437571460f11515fb1aaa5c75f0000 | mal1kofff/python | /12_luckyticket.py | 506 | 3.9375 | 4 | """Написать программу, которая проверит равенство сумм и выведет "Счастливый", если суммы совпадают,
и "Обычный", если суммы различны. На вход программе подаётся строка из шести цифр."""
s = str(input())
sum1 = int(s[0])+int(s[1])+int(s[2])
sum2 = int(s[3])+int(s[4])+int(s[5])
if sum1 == sum2:
print('Счастливый')
else:
print('Обычный')
|
9f31822e4aedfe0d77aed9faae1fb3a59c5addc0 | ver0nika4ka/PythonCrashCourse | /9.13_Dice.py | 717 | 4.40625 | 4 | """A class Die with one attribute sides has a default value of 6.
Method roll_die() prints random num from 1 and num of sides die has.
Make a 6-sided die and roll it 10 times.
Make a 10-sided die and a 20-sided die. """
from random import randint
class Die:
"""This class represents a die with arbitrary number of sides."""
def __init__(self, sides=6):
"""Initialize a die."""
self.sides = sides
def roll_die(self):
"""Print a random number."""
roll = randint(1, self.sides)
print(roll)
cubic = Die()
cubic_10 = Die(10)
cubic_20 = Die(20)
# Rolling each die 10 times.
for i in range(10):
cubic.roll_die()
cubic_10.roll_die()
cubic_20.roll_die()
|
3b84a7c7dffe287dc2cc9aed6c0f1250efc8be9f | LucasKetelhut/cursoPython | /desafios/desafio066.py | 198 | 3.6875 | 4 | soma=cont=0
while True:
n=int(input('Digite um valor [999 para parar]: '))
if n==999:
break
cont+=1
soma+=n
print(f'A soma dos {cont} valores digitados é igual a {soma}!')
|
6b4d6dc4d4e477e10652b286878e31108fc6f215 | ptsiampas/Exercises_Learning_Python3 | /04_Functions/function_example.py | 764 | 4.03125 | 4 | __author__ = 'petert'
import turtle
def draw_rectangle(t, w, h):
"""
:param t: turtle object to move
:param w: width of rectangle
:param h: height of rectable
:return: none
"""
for i in range(2):
t.forward(w)
t.left(90)
t.forward(h)
t.left(90)
def draw_square(tx,sz):
"""Make turtle t draw a square of sz."""
draw_rectangle(tx,sz,sz)
turtle.setup(600,400) # Set the size of the window to 600x400
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
wn.title("Alex meets function")
alex=turtle.Turtle()
alex.pensize(3)
size=20
for i in range(15):
draw_square(alex,size)
size+=10
alex.forward(10)
alex.right(18)
turtle.mainloop() |
e8b7ebff2334ddb7a1ed7ec58c8fe22c26bb9d77 | jaklocko/argparser | /app.py | 886 | 3.890625 | 4 | import sys
'''This is a simply argument parser, for training purposes'''
version = 0.1
def parse_opts(opts):
opts = sorted(opts)
for opt in opts:
if opt == "--help" or opt == "-h":
print("""Help Info\n------\nThis program is a simple argument parser\n\n""")
elif opt == "--version" or opt == "-v":
print("""Version Info\n------\napp.py""")
print("v{}\n\n".format(version))
def parse_args(args):
for arg in args:
print("Argument:", arg)
def main(args):
options = []
arglist = []
for arg in args:
if arg.startswith("--") or arg.startswith("-"):
options.append(arg)
else:
arglist.append(arg)
# print("Options:", options)
# print("Arguments:", arglist)
parse_opts(options)
parse_args(arglist)
if __name__ == '__main__':
main(sys.argv[1:])
|
43fa543d2d5e3efcd9c93361fe63a7b7e272dba2 | doytsujin/stanford-algorithms | /01-divide-and-conquer-sorting-searching-randomized/week-01/merge_sort.py | 1,823 | 4.625 | 5 | import random
def merge_sort(arr):
"""
Sorts an array of integers using Merge-Sort in O(n log n) time.
The array is recursively split into the left and right half and then recurses on each half.
:param arr: array of integers
:return: array with the same elements in sorted order
"""
if len(arr) <= 1:
# nothing to sort
return arr
# split into left and right half
left = arr[:len(arr) // 2]
right = arr[len(arr) // 2:]
# recursively sort each half
left = merge_sort(left)
right = merge_sort(right)
# merge both sorted halves into a new array
return merge(left, right)
def merge(left, right):
"""
Merge subroutine: Merges two sorted halves into a new array.
Merging is done using separate indices for the left and right half and copying over elements of either into the new
array.
- The current left is copied if it is smaller than the current right element and the index is moved.
- Vice versa the current right element is copied if it is smaller than the current left element
Above steps are repeated until all the elements from both halves have been copied to the new array
:param left: left half
:param right: right half
:return: both sides merged with element in ascecnding order
"""
n = len(left) + len(right)
c = [None] * n
i, j = 0, 0
for k in range(n):
if j >= len(right) or i < len(left) and left[i] < right[j]:
c[k] = left[i]
i += 1
elif j < len(right):
c[k] = right[j]
j += 1
return c
if __name__ == '__main__':
arr = list(range(10))
random.shuffle(arr)
print('array:', arr)
arr_sorted = merge_sort(arr)
print('sorted array:', arr_sorted)
assert arr_sorted == list(range(10))
|
34a2729829a7ffc87cd7e4bf4e496801cae4fd4b | PatrickPuente/Curso-Python-CEC-EPN | /Clase 15-11-2019/dfdsfdfd.py | 402 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 19:29:29 2019
@author: CEC
"""
a = int (input("Ingrese un numero entre -10 a 10: "))
v=[]
for i in range(-11, 10):
i+=1
v.append(i)
print(v[4][1])
''' if a <= i:
print("No es mayor que", i)
elif a>= i:
print("Si es mayor que", i)
else:
print("Esta en el rango") '''
|
098fdf3c9481ae0d6c411a9db4f9abe2f0fb6ee1 | ulimy/p2_201611082 | /w14Main.py | 559 | 3.734375 | 4 | class Dog(object):
def __init__(self,name):
self.name=name
def talk(self):
print ('my dog is',self.name,'mung mung')
class ShihTzuDog(object):
def __init__(self,name):
self.name=name
def talk(self):
print ('my dog is',self.name,'si si')
class Maltese(object):
def __init__(self,name):
self.name=name
def talk(self):
print ('my dog is',self.name,'mal mal')
mydog=Dog('dog')
mydog.talk()
mydog=ShihTzuDog('ShihTzuDog')
mydog.talk()
mydog=Maltese('Maltese')
mydog.talk() |
8ad2aecf6be699a40e6d678e6222f444948ff234 | vit-shreyansh-kumar/code-droplets | /src/Copy.py | 559 | 4.0625 | 4 | __about__ = """ Shallow and Deep Copy """
"""
Assignment statements in Python do not copy objects,
they create bindings between a target and an object.
"""
from collections import OrderedDict
import copy
data = [1,2,3,4,[5,6,7,8],9]
data1 = copy.copy(data)
data2 = copy.deepcopy(data)
"""
Will not work for these cases.
"""
mydata = [1,2,3,4,5,6,7]
mydata1 = copy.copy(mydata)
mydata2 = copy.deepcopy(mydata)
mydata1[0] = 100
data1[4][3] = 10
data2[4][3] = 11
print(data)
print(data1)
print(data2)
print(mydata)
print(mydata1)
print(mydata2)
|
df3e54d0ebc445d2021ca97efa77392949abaae5 | Aneesawan34/Assignments | /modifying element in list.py | 1,221 | 4.40625 | 4 | #changing element
motercycle=['honda', 'suzuki', 'yamaya']
print(motercycle[0])
motercycle[0]='ducati'
print(motercycle[0])
#Adding element by append1
print("\n")
motercycle=['honda', 'suzuki', 'yamaya']
print(motercycle) #3 element of list cant read now(you cant jump to 3 element)
motercycle.append('ducati')
print(motercycle)
print(motercycle[3]) #now you can jump or reach to 3 element
#adding element by insert2
print("\n")
print(motercycle)
motercycle.append('Honda')
print(motercycle)
motercycle.append('Suzuki')
print(motercycle)
motercycle.append('yamaha')
print(motercycle)
#adding and removing by pop element3
print("\n")
game=['mario 1', 'mario 2', 'mario 3']
print(game)
game.insert(1,'mario 1.5 new version and mario 2 will be gone soon')
print(game)
game.pop(2)
game[1]='mario 1.5 new version updated'
print(game)
#removing element by remove4
print("\n")
print("List of motercycles given below:")
motercycle=['Honda', 'suzuki', 'yamaha']
print(motercycle)
too_expensive='yamaha'
motercycle.remove(too_expensive)
print(motercycle)
print("\nThe " + too_expensive + " is too expensive for me")
print(motercycle)
budget='Honda'
motercycle.remove(budget)
print("\nThe " + budget + " is for my budget")
|
8101dd50a6da5470e2db10191945a8161d8dc058 | gusdn3477/Algorithm_Study | /baekjoon/3000~5999/3062_수뒤집기.py | 209 | 3.6875 | 4 | N = int(input())
for i in range(N):
num = input()
num_reverse = num[::-1]
total = str(int(num) + int(num_reverse))
if total == total[::-1]:
print('YES')
else:
print('NO') |
466d41b823ebe30944a63a98e1ccbfdfffc3e1bf | joestalker1/leetcode | /src/main/scala/contest/227/LargestMergeOfTwoStrings.py | 381 | 3.765625 | 4 | class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
if not word1 and not word2:
return ''
if not word1:
return word2
if not word2:
return word1
if word1 >= word2:
return word1[0] + self.largestMerge(word1[1:], word2)
return word2[0] + self.largestMerge(word1, word2[1:]) |
44f893f699c41e53d897dd105550e1d5ff1fea89 | mluizaa00/learning-python | /alura/modules/one/hangman_game.py | 2,548 | 3.921875 | 4 | import json;
import random;
import game_controller;
def load_words():
with open("/resources/words.json") as file:
words_file = file;
words_data = json.loads(words_file.read());
words = [word.lower() for word in words_data];
return words;
points = 0;
positions_found = [];
chances = 0;
def start_game():
won = False;
lose = False;
words = load_words();
secret_word = words[random.randrange(0, len(words))].lower();
global chances;
chances = len(secret_word) * 2;
while(not won and not lose):
right_guess = False;
already_found = False;
print("-------------------------")
alternative = input("What letter will you choose? ").lower().strip();
print(" ")
for letter in secret_word:
index = -1;
count = 0;
# Finds available letter depending on it's position
for letterFound in secret_word:
if (letterFound == letter and count not in positions_found):
index = count;
break;
count = count + 1;
if (index == -1):
break;
# Check if the letter from that position was already found
if (index in positions_found):
already_found = True;
continue;
if (alternative == letter):
right_guess = handle_correct(letter, index)
break;
handle_guess(already_found, right_guess, secret_word);
def handle_guess(already_found, right_guess, secret_word):
if (already_found == True):
print("You already found that position!")
if (right_guess == False):
handle_incorrect();
if (chances == 0 or points >= len(secret_word)):
game_controller.finish_game(points);
print("The correct word is: {}".format(secret_word))
return;
letters_left = len(secret_word) - len(positions_found);
print("You still got {} letters left!".format(letters_left))
def handle_correct(letter, index):
print("You got it right! It's letter {} in position {}.".format(letter.upper(), index + 1));
global points;
points = points + 1;
positions_found.append(index);
return True;
def handle_incorrect():
print("You didn't got it right! Try again...")
global chances;
chances = chances - 1;
|
1c347a19e275af17e4f0eebdf57e8ce852166e27 | masonpitts6/snake_game | /main.py | 1,739 | 3.890625 | 4 | import time
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
# Screen background color
screen.bgcolor('black')
screen.title('My Snake Game')
#Causes the animation to display only when update is called
screen.tracer(0)
#################################
# -------------------------------
# Creating the Snake Body
# -------------------------------
#################################
snake = Snake()
food = Food()
scoreboard = Scoreboard()
# Feeds key presses into python
screen.listen()
# Methods or functions within a function do not have ()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
#################################
# -------------------------------
# Move the Snake
# -------------------------------
#################################
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()
#Detect collision with food
if snake.head.distance(food) < 15:
food.refresh()
snake.extend()
scoreboard.refresh_scoreboard()
# Detect collision with wall
if snake.head.xcor() > 300 or snake.head.xcor() < -300 or snake.head.ycor() > 300 or snake.head.ycor() < -300:
scoreboard.game_over()
scoreboard.reset()
snake.reset()
# Detect collision with tail
# If head collides with any segment in the tail
for segment in snake.segments[1:]:
if snake.head.distance(segment) < 10:
scoreboard.game_over()
scoreboard.reset()
snake.reset()
screen.exitonclick()
screen.exitonclick()
|
8ba664fdfaf62268cf4915d336e93936012a0de8 | nemilshah54/Connect-4-Game | /Piece.py | 824 | 3.5 | 4 | import abc
class Piece(abc.ABC):
def __init__(self, col=-1, row=-1, b=None):
self.col = col
self.row = row
self.disp = ' '
self.board = b
def debug_string(self):
if(debug_flag):
return self._printInfo()
return ""
def _printInfo(self):
s = "col: " + str(self.col) + "\nrow: " + str(self.row) + "\ntype of piece: " + self.disp
print(s)
return s
def __str__(self):
return self.disp
class Connect_four(Piece):
def __init__(self, player, col=-1, row=-1):
super().__init__(col, row)
def set_location(self, loc):
pass
def validate_move(self, x, y):
pass
def make_move(self, x, y):
pass
def _printInfo(self): # Unnecessary as of now
super()._printInfo() |
608207cb01f7b5adcba67e363b4d367accbb4220 | C-likethis123/rosettaprogrammingproblems | /Python3/Simple Tasks/SimpleWindowedApplication.py | 1,168 | 3.65625 | 4 | import tkinter
from tkinter.constants import *
counter = [1]
def increment():
if counter[0] == 1:
label.configure(text = "There has been " + str(counter[0]) + " click!")
label.pack(fill=X, expand=2)
counter[0] = counter[0] + 1
else:
label.configure(text = "There has been " + str(counter[0]) + " clicks!")
label.pack(fill=X, expand=2)
counter[0] = counter[0] + 1
tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=3)
frame.pack(fill=BOTH,expand=2)
label = tkinter.Label(frame, text = "There has been no clicks")
label.pack(fill=X, expand=2)
clickme = tkinter.Button(frame, text="Click Me!", command=increment)
button = tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)
clickme.pack(side=BOTTOM)
tk.mainloop()
''' Model answer:
from Tkinter import Tk, Label, Button
def update_label():
global n
n += 1
l["text"] = "Number of clicks: %d" % n
w = Tk()
n = 0
l = Label(w, text="There have been no clicks yet")
l.pack()
Button(w, text="click me", command=update_label).pack()
w.mainloop()
'''
|
e8ce89055af229ece815fc8a352ed0c71f1191bb | liuwanping/leetcode-problems-python-solutions | /Search_Insert_Position.py | 604 | 4.125 | 4 | # def searchInsert( nums, target):
# if target<nums[0]:
# return 0
# elif target>nums[-1]:
# return len(nums)
# else:
# for num in nums:
# if target == num or num > target:
def searchInsert( nums, target):
l=0
r=len(nums)-1
while True:
m=(l+r)//2
if target<nums[m]:
r=m-1
if r>=0:
if target == nums[r]:
return r
elif target>nums[r]:
return r+1
else:
return 0
elif target>nums[m]:
l=m+1
if l<len(nums):
if target<=nums[l]:
return l
else:
return len(nums)
else:
return m
nums=[1,3,5]
target=2
print(searchInsert(nums,target)) |
02796c5f0280e15a74d78a6bc0d918d639bace09 | andyvand/sy201 | /classwork/cw47/countryStats.py | 1,560 | 4.3125 | 4 | # Notice the format for importing our Country class from the "classes.py" file,
# located in the "utils" directory.
from utils.classes import Country
def main():
# Start with an empty dictionary and open the file.
D = {}
fin = open("populationData.csv","r")
# Write the code to read all the lines in the file. Call your Country class
# initializer for each line you read, and add the object returned by the
# initializer to your dictionary. When complete, your dictionary will
# contain all the country data.
# Your code goes here....
# Write a loop. Inside the loop, ask the user for a letter. Since your
# country search needs to be case in-sensitive, cast the letter from the user
# to uppercase. When searching through your dictionary, compare the uppercase
# version of the first letter of each country to the uppercase letter entered
# by the user. If they match, print that country's name, along with its
# data. Access the fields in each Country object in your dictionary by using
# the Country class getter methods.
while True:
letter = input("Enter a letter: ")
# What if the user pressed enter with no input (blank line)?
if ....
# Do something if blank line...
else:
# Got a valid letter, so lookup country data.
# Here's how to iterate across a sorted list of dictionary keys
for key in sorted(D.keys()):
# Your code goes here....
# Call the main() function.
main()
|
2e2bf76abbfefe6c4c39f014514fa8d327dfbe34 | shubhangi2803/Python-Exercise | /Python-Exercise/7.py | 224 | 3.890625 | 4 | import numpy as np
print("Enter the dimensions of matrix : ")
X,Y=(input().split(','))
X=int(X)
Y=int(Y)
A=[]
for i in range(0,X):
B=[]
for j in range(0,Y):
B.append(i*j)
A.append(B)
print(A)
|
f452a043ad7fb44890724c3602301624c1c6bca5 | adepalatis/EE379K | /Lab2/problem2.py | 758 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame as df
from pandas.tools.plotting import scatter_matrix
# Read data from CSV
data = df.from_csv(path="C:\Users\Tony\Downloads\DF2")
# Get the mean and covariance of the data
mean = data.mean()
cov = data.cov()
# Find the inverse of the covariance matrix
cov_inv = pd.DataFrame(np.linalg.pinv(cov.values), cov.columns, cov.index)
# Multiply the identity matrix by the result
idMatrix = df(np.identity(2))
transFactor = np.dot(idMatrix, cov_inv)
# Plot the untransformed data
data.columns = ['a', 'b']
plt.scatter(data.a, data.b)
plt.show()
# Transform the data and plot again
data = np.dot(data, transFactor)
plt.scatter(data[:,0], data[:,1])
plt.show()
|
0745154b0251b6862ef3b4fb97a16f561718b8ae | pythonnewbird/LeetCodeSolution | /6.12/75.分类颜色.py | 482 | 3.5625 | 4 | class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i=0
j=len(nums)-1
k=0
while k<=j:
if nums[k]==0:
nums[k],nums[i]=nums[i],nums[k]
i+=1
elif nums[k]==2:
nums[k],nums[j]=nums[j],nums[k]
j-=1
k-=1
k+=1 |
1c6b9e16806d38ca79f060e333726204d2608f14 | KoliosterNikolayIliev/Softuni_education | /Fundamentals2020/MID EXAM Preparation/Biscuits Factory.py | 641 | 3.78125 | 4 | import math
biscuits_day_w = int(input())
workers_c = int(input())
comp_bis_30 = int(input())
total_biscuits = 0
for day in range(1, 31):
if day % 3 == 0:
total_biscuits += math.floor(0.75 * workers_c * biscuits_day_w)
else:
total_biscuits += workers_c * biscuits_day_w
difference = total_biscuits - comp_bis_30
percentage = difference / comp_bis_30 * 100
print(f"You have produced {total_biscuits:.0f} biscuits for the past month.")
if total_biscuits >= comp_bis_30:
print(f"You produce {percentage:.2f} percent more biscuits.")
else:
print(f"You produce {abs(percentage):.2f} percent less biscuits.")
|
f7295c97e8b5405de10db8e84058f51b19819e59 | wma8/SeniorDesign | /readop/models/ddve_output.py | 1,008 | 3.5 | 4 | """
Class for output message storing from ddve system.
"""
class DDVEOutput:
"""
Maintains the messages of executing commands in ddve system.
"""
def __init__(self, inputValue, outputValue, errorValue):
"""
Initializes the messages of executing commands in ddve system.
"""
self.inputValue = inputValue
self.outputValue = outputValue
self.errorValue = errorValue
def getInput(self):
"""
Return input message from the commands.
:return: Input message of the command.
"""
return self.inputValue
def getOutput(self):
"""
Return output message from executing the commands.
:return: Output message of executing the commands.
"""
return self.outputValue
def getErrors(self):
"""
Return error message in executing the commands.
:return: Error message in executing the commands.
"""
return self.errorValue
|
e5bbd3aa10fd6582b047704b5aa501fa56bbc5f1 | AnuragJ05/Python-Learning | /String_Length.py | 70 | 3.8125 | 4 | a=input("Enter String : ")
print("The Lengh of String is :",len(a))
|
2440b938508495f9b0e657fdfe1e011db812d137 | lsighiartau/learn-python-automation | /methods/methods_demo2.py | 488 | 3.828125 | 4 | """
Naming convention: letters, numbers, underscore
ex: sum_num, find_car
Docstring: see example below
"""
def sum_nums1(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return n1 + n2
sum1 = sum_nums1(6, 9)
print(sum1)
string_add = sum_nums1('one', 'two')
print(string_add)
def is_metro(city):
l = ['sfo', 'city', 'cluj']
if city in l:
return True
else:
return False
x = is_metro('boston')
print(x)
|
2aa45fd141ca042e8945d8436215f6ce803b42a7 | NenadPantelic/Algorithms-and-Data-Structures-Implementation | /Data Structures/Linked List/singly_linked_list.py | 3,051 | 3.796875 | 4 | # Singlу linked list
import gc
class Node:
def __init__(self, value):
self._value = value
self._next = None
def setValue(self, value):
self._value = value
def getValue(self):
return self._value
def setNext(self, next):
self._next = next
def getNext(self):
return self._next
def __str__(self):
return str(self._value)
class LinkedList:
def __init__(self):
self._head = None
self._tail = None
def setHead(self, head):
self._head = head
def getHead(self):
return self._head
def setTail(self, tail):
self._tail = tail
def getTail(self):
return self._tail
def printList(self):
node = self._head
while node:
print(node)
node = node.getNext()
def pushAtHead(self, value):
# create new node
node = Node(value)
# set new node's next node
node.setNext(self.getHead())
# set head (new node)
self.setHead(node)
def insertAfterNode(self, prevNode, value):
if prevNode is None:
print("The given node is None. Operation forbidden")
return
nextNode = prevNode.getNext()
node = Node(value)
prevNode.setNext(node)
node.setNext(nextNode)
def pushAtTail(self, value):
node = Node(value)
if self.getHead() is None:
self.setHead(node)
return
last = self.getHead()
while last.getNext():
last = last.getNext()
last.setNext(node)
def pushAtTail2(self, value):
node = Node(value)
if self.getHead() is None:
self.setHead(node)
self.setTail(node)
else:
tail = self.getTail()
tail.setNext(node)
self.setTail(node)
# without tail reference version
def removeNode(self, value):
temp = self.getHead()
# head node case
if temp.getValue() == value:
self.setHead(temp.getNext())
temp = None
return
while temp is not None:
if temp.getValue() == value:
break
prev = temp
temp = temp.getNext()
if temp is None:
print('Value was not found')
return
prev.setNext(temp.getNext())
if temp is self.getTail():
self.setTail(prev)
temp = None
gc.collect()
ll = LinkedList()
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.setNext(n2)
n2.setNext(n3)
ll.setHead(n1)
ll.setTail(n3)
print()
ll.printList()
ll.pushAtHead(20)
print()
print(ll.getHead())
print()
ll.printList()
ll.insertAfterNode(n2, 50)
print()
ll.printList()
ll.pushAtTail(1000)
print()
ll.printList()
ll.pushAtTail2(2000)
print()
ll.printList()
print()
ll.removeNode(20)
ll.printList()
ll.removeNode(1000)
print()
ll.printList()
ll.removeNode(2000)
print()
print(ll.getTail())
|
5f85dc2e4b9a4080c5fd3d641ae267e7b527e773 | tongbc/algorithm | /src/justForReal/replaceSpace.py | 278 | 3.609375 | 4 | # -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
lis = s.split(" ")
res = ""
n = len(lis)
for a in lis[:n-1]:
res=res+a+"%20"
res+=lis[n-1]
return res |
c52f992833b157af4a6456d0874cac83b7af1b10 | tanya-afanaseva/NoteBook | /Book.py | 5,217 | 3.53125 | 4 | from Tkinter import *
import datetime
import time
import re
class Book(object):
def __init__(self):
pass
def checkName(self, string):
match = re.match("""^[a-zA-Z., ]+$""", string)
if match:
contactFile = open(".contacts.csv", "a+")
contacts = contactFile.read()
contactsSplit=contacts.split(';')
i=0
name="\n"+string
while i<len(contactsSplit):
if contactsSplit[i]==name:
return False
i=i+3
contactFile.close()
return bool(match)
def checkPhone(self, string):
match = re.match("""^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$""", string)
return bool(match)
def checkBirthday(self, string):
match = re.match("""^(0?[1-9]|([12][0-9]|3[01]))\.(0?[1-9]|1[012])$""", string)
return bool(match)
def reminder(self):
contactFile = open(".contacts.csv", "a+")
contacts = contactFile.read()
contactsSplit=contacts.split(';')
i=2
k=0
listName=[]
now = datetime.datetime.now()
today=str(now.day)+"."+str(now.month)
while not i>len(contactsSplit):
if contactsSplit[i]==today:
k=k+1
listName.append(contactsSplit[i-2].replace("\n", "").replace("'", ""))
i=i+3
text1=str(listName).strip("'[\n]'")
fullText="Today is a birthday of " + text1
if not k==0:
self.labelBirthday=Label(text=str(fullText), font=("Courier", 9))
self.labelBirthday.place(x=140, y=90)
contactFile.close()
def seeAll(self):
try:
self.buttonSave.destroy()
self.labelName.destroy()
self.labelPhone.destroy()
self.labelDay.destroy()
self.entryName.destroy()
self.entryPhone.destroy()
self.entryDay.destroy()
except:
pass
try:
self.labelSuccess.destroy()
except:
pass
try:
self.labelError.destroy()
except:
pass
try:
self.labelBirthday.destroy()
except:
pass
contactsFile = open(".contacts.csv", "a+")
self.labelHead = Label(text="Name \t \t|\t Phone \t \t\t|\t Birthday \n _")
self.labelHead.place(x=10, y=35)
self.labelMain = Label("")
self.labelMain.place(x=10, y=65)
contacts = contactsFile.read()
allNames=""
self.labelMain.config(text=contacts.replace(";", "\t \t|\t ").replace(" ", ""))
contactsFile.close()
def saveContact(self, name, phone, birtdayForm):
contactsFile = open(".contacts.csv", "a+")
contactsFile.write(name+";"+phone+";"+birtdayForm+";"+"\n")
contactsFile.close()
def addContact(self):
try:
self.labelBirthday.destroy()
except:
pass
try:
self.labelHead.destroy()
self.labelMain.destroy()
except:
pass
try:
self.labelSuccess.destroy()
self.labelError.destroy()
except:
pass
self.labelName = Label(text="Name: ")
self.labelName.place(x=100, y=35)
self.entryName = Entry()
self.entryName.place(x=200, y=35)
self.labelPhone = Label(text="Phone: ")
self.labelPhone.place(x=100, y=65)
self.entryPhone = Entry( )
self.entryPhone.place(x=200, y=65)
self.labelDay = Label(text="Birthday(dd.mm): ")
self.labelDay.place(x=100, y=95)
self.entryDay = Entry()
self.entryDay.place(x=200, y=95)
def callback():
self.labelError = Label(text="", fg="red")
self.labelError.place(x=180, y=135)
self.labelSuccess = Label(text="", fg="blue")
self.labelSuccess.place(x=180, y=220)
name = self.entryName.get()
phone = self.entryPhone.get()
birthday = self.entryDay.get()
if not self.checkName(name):
self.labelError.config(text="Incorrect name")
return
if not self.checkPhone(phone):
self.labelError.config(text="Incorrect phone ")
return
if not self.checkBirthday(birthday):
self.labelError.config(text="Incorrect date ")
return
birtdayForm=birthday
try:
if birthday[3]=="0":
birtdayForm=birthday.replace(birthday[3], "")
elif birthday[2]=="0":
birtdayForm=birthday.replace(birthday[2], "")
elif birthday[0]=="0":
birtdayForm=birthday.replace(birthday[0], "")
except:
pass
self.saveContact(name, phone, birtdayForm)
self.labelError.destroy()
self.labelSuccess.config(text="Contact was saved")
self.buttonSave=Button( text="Save contact", command=callback )
self.buttonSave.place(x=180, y=165)
|
8e993a986cefd7d616780b2cb8d8d19f2bc373d6 | haiyuancheng/Python_practise_Hard_Way | /python_09/data.py | 182 | 3.84375 | 4 | cycle = int(raw_input("please input your number: "))
data = float(raw_input("please input your nuber: "))
print "your input is %d and %d " % (cycle, data) #%d 取整数
print data |
ba3656b04a0640429e48733e8eeac2d7a4c98897 | tianshang486/Pythonlaonanhai | /day10 课堂笔记以及代码/day10/02 函数的参数2.py | 2,592 | 4.03125 | 4 | # 形参角度:
# 万能参数。
# def eat(a,b,c,d):
# print('我请你吃:%s,%s,%s,%s' %(a,b,c,d))
#
# eat('蒸羊羔', '蒸熊掌', '蒸鹿邑','烧花鸭')
# def eat(a,b,c,d,e,f):
# print('我请你吃:%s,%s,%s,%s,%s,%s' %(a,b,c,d,e,f))
#
# eat('蒸羊羔', '蒸熊掌', '蒸鹿邑','烧花鸭','烧雏鸡','烧子鹅')
# 急需要一种形参,可以接受所有的实参。#万能参数。
# 万能参数: *args, 约定俗称:args,
# 函数定义时,*代表聚合。 他将所有的位置参数聚合成一个元组,赋值给了 args。
# def eat(*args):
# print(args)
# print('我请你吃:%s,%s,%s,%s,%s,%s' % args)
#
# eat('蒸羊羔', '蒸熊掌', '蒸鹿邑','烧花鸭','烧雏鸡','烧子鹅')
# 写一个函数:计算你传入函数的所有的数字的和。
# def func(*args):
# count = 0
# for i in args:
# count += i
# return count
# print(func(1,2,3,4,5,6,7))
# tu1 = (1, 2, 3, 4, 5, 6, 7)
# count = 0
# for i in tu1:
# count += i
# print(count)
# **kwargs
# 函数的定义时: ** 将所有的关键字参数聚合到一个字典中,将这个字典赋值给了kwargs.
# def func(**kwargs):
# print(kwargs)
# func(name='alex',age=73,sex='laddyboy')
# 万能参数:*args, **kwargs,
# def func(*args,**kwargs):
# print(args)
# print(kwargs)
# func()
# print()
# * **在函数的调用时,*代表打散。
def func(*args,**kwargs):
print(args) # (1,2,3,22,33)
print(kwargs)
# func(*[1,2,3],*[22,33]) # func(1,2,3,22,33)
# func(*'fjskdfsa',*'fkjdsal') # func(1,2,3,22,33)
func(**{'name': '太白'},**{'age': 18}) #func(name='太白',age='18')
# 形参角度的参数的顺序
# *args 的位置?
# def func(*args,a,b,sex= '男'):
# print(a,b)
# func(1,2,3,4)
# args得到实参的前提,sex必须被覆盖了。
# def func(a,b,sex= '男',*args,):
# print(a,b)
# print(sex)
# print(args)
# func(1,2,3,4,5,6,7,)
# def func(a,b,*args,sex= '男'):
# print(a,b)
# print(sex)
# print(args)
# func(1,2,3,4,5,6,7,sex='女')
# **kwargs 位置?
def func(a,b,*args,sex= '男',**kwargs,):
print(a,b)
print(sex)
print(args)
print(kwargs)
# func(1,2,3,4,5,6,7,sex='女',name='Alex',age=80)
# 形参角度第四个参数:仅限关键字参数 (了解)
def func(a,b,*args,sex= '男',c,**kwargs,):
print(a,b)
print(sex)
print(args)
print(c)
print(kwargs)
# func(1,2,3,4,5,6,7,sex='女',name='Alex',age=80,c='666')
# 形参角度最终的顺序:位置参数,*args,默认参数,仅限关键字参数,**kwargs |
933b069a4e3d24ace3063378f973fc7d88b5fc69 | sarahwu710/password-retry | /password.py | 355 | 3.875 | 4 | password = 'a123456'
chance = 3 # 最多3次輸入機會
while chance > 0:
chance = chance - 1
pwd = input('請輸入密碼: ')
if pwd == password:
print('登入成功!')
break # 逃出迴圈
else:
print('密碼錯誤!')
if chance > 0:
print('還有', chance, '次機會')
else:
print('沒有機會嘗試了! 要鎖帳號了啦!')
|
c39187ea2baffd9396e5cf153006234fc16612cc | QI1002/exampool | /Leetcode/84.py | 905 | 3.546875 | 4 |
#84. Largest Rectangle in Histogram
def largestRect(data):
s = sorted(data)
maxRect = (0, len(data)-1), s[0]
maxArea = len(data) * s[0]
for i in range(1, len(s), 1):
start = -1
for j in range(len(data)):
if (data[j] >= s[i]):
if (start == -1):
start = j
else:
if (start != -1):
area = (j - start)*s[i]
if (area > maxArea):
maxArea = area
maxRect = (start, j-1), s[i]
start = -1
if (start != -1):
area = (len(data)-start)*s[i]
if (area > maxArea):
maxArea = area
maxRect = (start, len(data)-1), s[i]
return maxRect
sample = [2, 1, 5, 6, 2, 3]
t = largestRect(sample)
print(t) |
839311777e72e1a6544b8d889c330b25dea79a14 | GItHub-yang369/PycharmProjects | /PythonLearnFishc/11/11-9/Python-2.py | 383 | 3.71875 | 4 | class C:
def __init__(self, x=6):
self.x = x
c1 = C()
print(hasattr(c1, 'x')) # 返回对象中是否有指定的属性
print(getattr(c1, 'x')) # 返回对象指定的属性值或者默认的属性值
setattr(c1, 'x', 9) # 设置对象属性值
print(getattr(c1, 'x'))
delattr(c1, 'x') # 删除对象属性
print(getattr(c1, 'x')) # 删除之后再输出会报错
|
f420a151b91fcc7451438ed4f3a53582f7fbc060 | raykrishardi/FIT1045-Graph-Problem-Solving-in-Python3 | /intersection.py | 10,106 | 3.765625 | 4 | # ----------------------------------------------------------------------------------------------------------------------
# Name: Ray Krishardi Layadi
# Student ID: 26445549
# ----------------------------------------------------------------------------------------------------------------------
# Import the required functions from the graphFileOps.py file
from graphFileOps import getVerticesFromFile, getAdjacencyMatrixFromFile, writeMatrixToFile, getIndex
# Function that returns the intersect vertices given two vertices
def getIntersectVertices(vertices1, vertices2):
intersectVertices = []
# Loop through each vertex in vertices 1 and 2
# If they are equal then append the vertex to the list of intersect vertices
for vertex1 in vertices1:
for vertex2 in vertices2:
if vertex1 == vertex2:
intersectVertices.append(vertex1)
return intersectVertices
# Function that checks and gets the appropriate intersect vertices given two vertices
def checkAndGetIntersectVertices(vertices1, vertices2):
# Check the number of vertices in vertices 1 and 2 and get the appropriate intersect vertices
# We need to check the number of vertices because we want to loop through the larger vertices in the outer loop
# so that we can cover every vertex in the larger vertices and compare it with the smaller one
if len(vertices1) > len(vertices2):
return getIntersectVertices(vertices1, vertices2)
else:
return getIntersectVertices(vertices2, vertices1)
# Function that returns the intersect edges given the intersect vertices
# In this case, the intersect edges contains duplicate edges (e.g. ['a', 'c'] and ['c', 'a'])
def getIntersectEdges(intersectVertices, vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2):
intersectEdges = []
# Loop through each vertex in the intersect vertices
for i in range(len(intersectVertices)):
# Find the index of the intersect vertex in vertices 1 and 2
# This is because the index of the intersect vertex differ from vertices 1 and 2
vertex1IndexInVertices1 = getIndex(vertices1, intersectVertices[i])
vertex1IndexInVertices2 = getIndex(vertices2, intersectVertices[i])
# Loop through each vertex in the intersect vertices again because we want to get the intersect edges
for j in range(len(intersectVertices)):
# Find the index of the intersect vertex in vertices 1 and 2
# This is because the index of the intersect vertex differ from vertices 1 and 2
vertex2IndexInVertices1 = getIndex(vertices1, intersectVertices[j])
vertex2IndexInVertices2 = getIndex(vertices2, intersectVertices[j])
# Only process different intersect vertices (exclude same vertices (e.g. index of 'a' and 'a'))
if vertex1IndexInVertices1 != vertex2IndexInVertices1 and vertex1IndexInVertices2 != vertex2IndexInVertices2:
# Get the intersect edges by checking the value of the weight in adjacencyMatrix 1 and 2 (there is an edge if the weight is not equal to 0)
if adjacencyMatrix1[vertex1IndexInVertices1][vertex2IndexInVertices1] != 0 and adjacencyMatrix2[vertex1IndexInVertices2][vertex2IndexInVertices2] != 0:
intersectEdges.append([intersectVertices[i], intersectVertices[j]])
return intersectEdges
# Function that returns a valid intersect edges given an intersect edges
# In this case, the valid intersect edges does NOT contain duplicate edges (e.g. ['a', 'c'] and ['c', 'a'])
def getValidIntersectEdges(intersectEdges):
validIntersectEdges = []
# Loop through each edge in the intersect edges
for i in range(len(intersectEdges)):
# Get the vertices from the intersect edges
vertex1 = intersectEdges[i][0]
vertex2 = intersectEdges[i][1]
# Loop through each edge in the intersect edges again because we want to eliminate duplicate edges
for j in range(i+1, len(intersectEdges)):
# If there is an edge that is a duplicate (e.g. ['a', 'c'] and ['c', 'a']) then add one of the edge to the
# list of valid intersect edges
if vertex1 in intersectEdges[j] and vertex2 in intersectEdges[j]:
validIntersectEdges.append(intersectEdges[i])
return validIntersectEdges
# Function that returns a valid intersect vertices by using the valid intersect edges
# In this case, the valid intersect vertices does NOT contain vertices that are NOT actually used in the intersection
# For example, in finding the intersection of graph G and H, vertex 'Q' is not actually used in the intersection (i.e. no edges connecting 'Q')
# Therefore, vertex 'Q' is not included in the valid intersect vertices
def getValidIntersectVertices(validIntersectEdges):
validIntersectVertices = []
# Loop through each edge in the valid intersect edges
for validEdge in validIntersectEdges:
# Get vertices from edge
vertex1 = validEdge[0]
vertex2 = validEdge[1]
# Check whether each vertex in the edge is already included in the valid intersect vertices
# If not then add that vertex to the valid intersect vertices
if vertex1 not in validIntersectVertices:
validIntersectVertices.append(vertex1)
if vertex2 not in validIntersectVertices:
validIntersectVertices.append(vertex2)
return validIntersectVertices
# Function that returns the appropriate adjacency matrix based on the given vertices
# In this case, the function will return the intersect adjacency matrix
def getAdjacencyMatrix(vertices):
adjMatrix = []
# Initialise the adjacency matrix based on the number of vertices
for _ in range(len(vertices)):
adjMatrix.append([0] * len(vertices))
return adjMatrix
# Function that initialises the intersect adjacency matrix with the largest weight from adjacency matrix 1 or 2
# This is achieved by comparing the weight in adjacency matrix 1 and 2
def initialiseIntersectAdjacencyMatrixWithLargestWeight(intersectAdjMatrix, validIntersectVertices, validIntersectEdges, vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2):
# Loop through each edge in the valid intersect edges
for edge in validIntersectEdges:
# Get the index of the intersect vertices in vertices 1 and 2
vertex1IndexInVertices1 = getIndex(vertices1, edge[0])
vertex1IndexInVertices2 = getIndex(vertices2, edge[0])
vertex2IndexInVertices1 = getIndex(vertices1, edge[1])
vertex2IndexInVertices2 = getIndex(vertices2, edge[1])
# Get the index of the intersect vertices in valid intersect vertices
vertex1IndexInIntersectVertices = getIndex(validIntersectVertices, edge[0])
vertex2IndexInIntersectVertices = getIndex(validIntersectVertices, edge[1])
# Compare the weight of the intersect vertices in adjacency matrix 1 and 2
# Assign weight to the larger weight
if adjacencyMatrix1[vertex1IndexInVertices1][vertex2IndexInVertices1] >= adjacencyMatrix2[vertex1IndexInVertices2][vertex2IndexInVertices2]:
weight = adjacencyMatrix1[vertex1IndexInVertices1][vertex2IndexInVertices1]
else:
weight = adjacencyMatrix2[vertex1IndexInVertices2][vertex2IndexInVertices2]
# Assign larger weight to the intersect adjacency matrix
intersectAdjMatrix[vertex1IndexInIntersectVertices][vertex2IndexInIntersectVertices] = weight
intersectAdjMatrix[vertex2IndexInIntersectVertices][vertex1IndexInIntersectVertices] = weight
# Function that writes the intersect adjacency matrix and vertices to a file with the appropriate formatting
def writeIntersectAdjacencyMatrixToFile(vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2, fileName1, fileName2):
# Generate the output file name
# This is done by removing the ".txt" extension from the file names and concatenate the required additional string
# at the middle of it and adding a new .txt extension at the end of it
graphOutputFileName = fileName1[:len(fileName1)-4] + "_and_" + fileName2[:len(fileName2)-4] + ".txt"
# Get the intersect vertices and edges, valid intersect vertices and edges, and intersect adjacency matrix
intersectVertices = checkAndGetIntersectVertices(vertices1, vertices2)
intersectEdges = getIntersectEdges(intersectVertices, vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2)
validIntersectEdges = getValidIntersectEdges(intersectEdges)
validIntersectVertices = getValidIntersectVertices(validIntersectEdges)
intersectAdjMatrix = getAdjacencyMatrix(validIntersectVertices)
# Initialise the intersect adjacency matrix with largest weight from adjacency matrix 1 or 2
# This is achieved by comparing the weight in adjacency matrix 1 and 2
initialiseIntersectAdjacencyMatrixWithLargestWeight(intersectAdjMatrix, validIntersectVertices, validIntersectEdges, vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2)
# Write the intersect adjacency matrix and vertices to a file with the appropriate formatting
writeMatrixToFile(graphOutputFileName, validIntersectVertices, intersectAdjMatrix)
def main():
# Prompt the user for input graph files
graphInputFileName1 = input("Enter input file name: ")
graphInputFileName2 = input("Enter input file name: ")
# Get the vertices and adjacency matrix from the graph files
vertices1 = getVerticesFromFile(graphInputFileName1)
adjacencyMatrix1 = getAdjacencyMatrixFromFile(graphInputFileName1)
vertices2 = getVerticesFromFile(graphInputFileName2)
adjacencyMatrix2 = getAdjacencyMatrixFromFile(graphInputFileName2)
# Write the intersect adjacency matrix and vertices to the output graph file with the appropriate formatting
writeIntersectAdjacencyMatrixToFile(vertices1, vertices2, adjacencyMatrix1, adjacencyMatrix2, graphInputFileName1, graphInputFileName2)
if __name__ == "__main__":
main() |
44c894e257e0f718ae793244d204a7e1f98a6709 | brroberts/Python201608 | /HeffnerDaniel/assignments/Python/OOP/car.py | 1,212 | 3.8125 | 4 | import random
class Car(object):
def __init__(self, price = 10000, speed = 70, fuel = 15, mileage = 0):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
self.display_all()
def display_all(self):
print '------------------'
print 'Price: ' + str(self.price)
print 'Speed: ' + str(self.speed)
print 'Fuel: ' + str(self.fuel)
print 'Mileage: ' + str(self.mileage)
print 'Tax: ' + str(self.tax)
c1 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
c2 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
c3 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
c4 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
c5 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
c6 = Car(random.randrange(5000,30000), random.randrange(50,150), random.randrange(10,50), random.randrange(0,3000))
|
fd00f06e5e42fa4eac8925db28c6ea45fd217968 | jtlai0921/AEL022000 | /AEL0220_SampleFiles/Python 程式設計技巧(EL0220)-範例/時間日期-datetime.py | 1,114 | 3.578125 | 4 | import time; # 引入time 模組
localtime = time.localtime(time.time())
print ("本地時間: :", localtime)
# 格式化成 2018-11-24 11:28:31 格式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
# 格式化成 Sat Nov 24 11:28:31 2018 格式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )
# 將格式字符串轉換為時間戳 , 這種格式目前少用
a = "Sat Nov 24 11:30:06 2018"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
import calendar # 引入calendar 模組
cal = calendar.month(2019, 1)
print ("以下輸出2019年1月份的日曆:")
print ( cal )
import datetime # 引入datetime 模組
i = datetime.datetime.now()
print ("當前的日期和時間是 %s" % i)
print ("ISO格式的日期和時間是 %s" % i.isoformat() )
print ("當前的年份是 %s" %i.year)
print ("當前的月份是 %s" %i.month)
print ("當前的日期是 %s" %i.day)
print ("dd/mm/yyyy 格式是 %s/%s/%s" % (i.day, i.month, i.year) )
print ("當前小時是 %s" %i.hour)
print ("當前分鐘是 %s" %i.minute)
print ("當前秒是 %s" %i.second)
|
ed52cef98fbd20073e7456a6cf99e5d9ce1a33df | n0pe13/NSA-Python-Guide | /lesson1.py | 618 | 3.75 | 4 | # 1 - 3, 7
def main():
total = 0
grocery_list = list(["peanut butter", "oatmeal", "honey", "chicken", "fruit"])
for s in grocery_list:
print(s + "\n")
grocery_bill = [9.42, 5.67, 3.25, 13.40, 7.50]
total = (sum(grocery_bill[:4]) + grocery_bill[-1] * 5)
print(total)
# 4
def main2():
print(len("blood-oxygenation level dependent functional magnetic resonance imaging"))
# 5
def main3():
print("fruit " * 100)
# 6
def main4():
print(dir(__name__))
#print(help(str))
print(help(int))
if __name__=='__main__':
#main()
#main2()
#main3()
#main4() |
a1b4df087c0b7062eaf1bb0c54ab0f6a48fd145b | pani3610/AJGAR | /02binocthex.py | 767 | 3.578125 | 4 | accuracy=10
n=float(input("Enter a no. > "))
t=input("Convert to (B)inary , (O)ctal or (H)exadecimal > ")
if t.lower().startswith('b'):
b=2
elif t.lower().startswith('o'):
b=8
elif t.lower().startswith('h'):
b=16
nint=int(n//1)
nflt=n%1
x=""
y=""
while True:
if int(nint%b) <= 9:
x=x+str(int(nint%b))
if int(nint%b) > 9 :
h=(int(nint%b)-9)
x=x+chr(64+h)
nint=nint//b
if nint == 0:
break
while True:
if int((nflt*b)//1) <= 9:
y=y+str(int((nflt*b)//1))
if int((nflt*b)//1) > 9:
h=(int((nflt*b)//1)-9)
y=y+chr(64+h)
nflt=(nflt*b)%1
if nflt==0 or len(y)>=accuracy:
break
print("The %s value of number is"%{2:'binary',8:'octal',16:'hexadecimal'}[b],x[::-1]+"."+y)
|
9546a8d06dc4013766603c1675c4e3b5325e9508 | yosifnandrov/softuni-stuff | /advanced/stacks and queues/supermarket.py | 315 | 3.703125 | 4 | from collections import deque
people = deque()
command = input()
while not command == "End":
if command == "Paid":
while len(people) > 0:
print(people.popleft())
else:
name = command
people.append(name)
command = input()
print(f"{len(people)} people remaining.")
|
8a7c026e73e4b9eb9349d44ea544ce29edcf8d10 | RocketMirror/AtCoder_Practice | /pbbb.py | 110 | 3.640625 | 4 | n = int (input())
l = [2, 1]
for i in range (2, n + 1):
s = l[i-2] + l[i-1]
l.append(s)
print (l[n]) |
9eb0d8f2c3220daf499cfb6d57af7be1b5fb5fcf | chinayangd/-----Python | /Python01/ex10.py | 1,835 | 3.5625 | 4 | # coding=utf-8
# 10: 那是什么?(转义字符)
# ex10.py
tabby_cat ="\tI'm tabbed in."
persian_cat="I'm split\non a line."
backslash_cat="I'm \\ a \\ cat."
fat_cat="""
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip \n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
print u"--------以下为加分练习题--------"
'''上网搜索一下还有哪些可用的转义字符。
\(在行尾) 续行,表示不换行
\\ 反斜杠
\' 单引号
\" 双引号
\a 响铃
\b 退格,表示删除前面一个字符
\t 水平制表符
\v 垂直制表符,表示换行,然后从\v的地方开始输出。
\n 换行
\f 换页
'''
# ''' (三个单引号)取代三个双引号,效果同样
# 将转义序列和格式化字符串放到一起,创建一种更复杂的格式
print "backslash_cat = "+backslash_cat
backslash_cat2="I'm \\ a \\ cat \n \t* %s *." %backslash_cat
print "backslash_cat2 = "+backslash_cat2
print u"----------------"
# %r 打印出来的是你写在脚本里的内容,而 %s 打印的是你应该看到的内容
backslash_cat3="I'm \\ a \\ cat \t* %r *." %backslash_cat
print "backslash_cat3 = "+backslash_cat3
print u"----------------"
print "backslash_cat r= %r" %backslash_cat
print "backslash_cat s= %s" %backslash_cat
print u"----------------"
print "I am 6'2\" tall." # 将字符串中的双引号转义
print 'I am 6\'2" tall.' # 将字符串种的单引号转义
# 使用 %r 搭配单引号和双引号转义字符打印一些字符串出来。
print u"----------------"
tabby_cat2 ="I'm tabbed in %r %s." %('a',"house")
print tabby_cat2
tabby_cat2 ="I'm tabbed in \"%r\" %s." %('a',"house")
print tabby_cat2
tabby_cat2 ="I'm tabbed in \"%r %s." %('a',"house")
print tabby_cat2
tabby_cat2 ="I'm tabbed in %r \'%s\'." %('a',"house")
print tabby_cat2
print r'\t\r' |
d857c7ba8e2b348cb3a595ee1cc007a9910e47f7 | MauriceSch-dev/Python3 | /Aufgabe4.py | 199 | 3.59375 | 4 | price = 500
while True:
discount_input = input("Wie hoch ist der Rabatt?")
discount = price / 100 * float(discount_input)
price = price - discount
print ("Neuer Preis: " + str(price)) |
11c738b3ac2f759163e0a645711ef575d98bc540 | rileylyman/python-games | /Pong.py | 3,182 | 3.59375 | 4 | import graphics
class Paddle:
def __init__(self,height,width,speed,color):
self.height = height
self.width = width
self.speed = speed
self.color = color
self.paddle = graphics.Rectangle(graphics.Point(0,0),graphics.Point(0+self.width,0+self.height))
self.paddle.setFill(self.color)
def draw(self,win):
self.paddle.draw(win)
def glide(self,dir,fps):
self.paddle.move(0,dir*self.speed/fps)
def setLocation(self,x,y):
self.paddle.move(x-(self.paddle.getCenter().getX()),y-(self.paddle.getCenter().getY()))
def getXRange(self):
return self.paddle.getP1().getX(), self.paddle.getP2().getX()
def getYRange(self):
return self.paddle.getP1().getY(),self.paddle.getP2().getY()
class Ball:
def __init__(self,radius,speed,color,fps):
self.radius = radius
self.speed = speed
self.color = color
self.dx = self.speed /fps
self.dy = self.speed/fps*2/4
self.ball = graphics.Circle(graphics.Point(0,0),self.radius)
self.ball.setFill(self.color)
def draw(self,win):
self.ball.draw(win)
def setLocation(self,x,y):
self.ball.move(x-self.ball.getCenter().getX(),y-self.ball.getCenter().getY())
def moveBehavior(self,center,width,height,fps,win,paddle):
if self.ball.getCenter().getY()+self.radius >= height:
self.dy = -self.dy
if self.ball.getCenter().getY()-self.radius <= 0:
self.dy = -self.dy
if self.ball.getCenter().getX()+self.radius >= width:
self.dx = -self.dx
if self.ball.getCenter().getX()-self.radius <= 0:
self.ball.undraw()
paddleXLeft, paddleXRight = paddle.getXRange()
paddleYLow , paddleYHigh = paddle.getYRange()
if (self.ball.getCenter().getX()-self.radius <= paddleXRight and self.ball.getCenter().getX()+self.radius >= paddleXLeft
and self.ball.getCenter().getY()+self.radius > paddleYLow and self.ball.getCenter().getY()-self.radius < paddleYHigh):
self.dx = -self.dx
self.ball.move(self.dx,self.dy)
def getXRange(self):
return self.ball.getCenter().getX()-self.radius, self.ball.getCenter().getX()+self.radius
def getYRange(self):
return self.ball.getCenter().getY()-self.radius, self.ball.getCenter().getY()+self.radius
def main():
win = graphics.GraphWin('Paddle Game',800,800,autoflush = True)
win.setBackground('gray')
win.setCoords(0,0,10,10)
ball = Ball(0.2,5,'blue',30)
ball.setLocation(5,5)
ball.draw(win)
paddle = Paddle(4,.3,11,'blue')
paddle.draw(win)
paddle.setLocation(1.5,5)
while True:
graphics.update(30)
ball.moveBehavior(graphics.Point(5,5),10,10,30,win,paddle)
key = win.checkKey()
if key == 'Up':
paddle.glide(1,30)
elif key == 'Down':
paddle.glide(-1,30)
if key == 'r':
ball = Ball(0.2,5,'blue',30)
ball.setLocation(5,5)
ball.draw(win)
if __name__=='__main__': main()
|
f700f4ab2f601b70054a6835a1466457582bd5df | mihirsam/CS1465-ALGORITHM-LAB | /18.01.18/Reverse_Inbuilt.py | 117 | 3.859375 | 4 |
List = [int(x) for x in input("Enter integer input for list : ").split()]
RevList = List.reverse()
print (RevList)
|
9c888a591dbb41ad6e4b00270c4ced31326d73e3 | OCSWENG/PythonDevStudies | /examples/Algorithms/lambdas.py | 672 | 4.09375 | 4 |
#given a dataset interpret the data using lambdas
data = [44,92,2,6,22,29,33,13,-1,8,-21,17]
#find all even/odd numbers
evens = filter(lambda a: a%2 ==0, data)
odds = filter(lambda a: a%2 ==1, data)
#add value to the data set
mappedData = map(lambda a: a /3, data)
# sum up the data
reduction = reduce(lambda a,b: a-b, data)
print("data: ", data)
print("evens: " , evens)
print("odds: ", odds)
print("Mapped by dividing by 3: " , mappedData)
print("Reduction (a - b) : ", reduction)
words = ["data", "evens", "odds", "Mapped", "by", "dividing","Reduction"]
lengths = map(lambda word: len(word), words)
print ("words: ", words)
print ("word lengths: ", lengths)
|
bdbd6be3649058c37209df5c8989ce3d16a75ddd | N-eeraj/code_website | /Code/py/multiply_2_numbers.py | 123 | 3.9375 | 4 | product = 1
product *= float(input("Enter First Number: "))
product *= float(input("Enter Second Number: "))
print(product) |
2a2460c601359ff9384425bdd40e7150d36b01ab | sgoley/DataCamp | /23-introduction-to-pyspark/3 - Getting started with machine learning pipelines/02 - string to integer.py | 796 | 4.09375 | 4 | '''
String to integer
Now you'll use the .cast() method you learned in the previous exercise to convert all the appropriate columns from your DataFrame model_data to integers!
As a little trick to make your code more readable, you can break long chains across multiple lines by putting .\ then calling the method on the next line, like so:
string = string.\
upper().\
lower()
The methods will be called from top to bottom.
'''
# Cast the columns to integers
model_data = model_data.withColumn("arr_delay", model_data.arr_delay.cast("integer"))
model_data = model_data.withColumn("air_time", model_data.air_time.cast("integer"))
model_data = model_data.withColumn("month", model_data.month.cast("integer"))
model_data = model_data.withColumn("plane_year", model_data.plane_year.cast("integer"))
|
43bc33726066c00a6961fb30ad9ec624d99d5da8 | gabriellaec/desoft-analise-exercicios | /backup/user_256/ch42_2020_04_06_19_23_09_141850.py | 233 | 3.734375 | 4 | perg = input("Digite as palavra: ")
vazia = []
while perg!= "fim":
if perg[0] == "a":
vazia.append(perg)
perg = input("Digite as palavra: ")
i = 0
while i < len(vazia):
print(vazia[i])
i+=1
|
ff8ac755550b9fd09303be15109308e771eddd67 | jonathanecm/Fundamentals-of-Computing | /An Introduction to Interactive Programming in Python (Part 1)/Week 0 - Statements, expressions, variables/The perimeter and area of a rectangle.py | 484 | 4.4375 | 4 | # Compute the length of a rectangle's perimeter, given its width and height.
###################################################
# Rectangle perimeter formula
# Student should enter statement on the next line.
width = 4
height = 7
rectangle_perimeter = 2 * (width + height)
print(rectangle_perimeter)
area = 4 * 7
print(area)
###################################################
# Expected output
# Student should look at the following comments and compare to printed output.
#22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.