blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
40da06e6cafdf80c4c5e513e45df39f05ed904b3 | emanuelfeld/advent-of-code-2017 | /day_04/main.py | 1,151 | 3.5625 | 4 | with open('input.txt', 'r') as infile:
data = infile.readlines()
data = [row.split() for row in data]
# part 1
def is_valid_1(row):
return len(row) == len(set(row))
def part_1(data):
return sum([is_valid_1(row) for row in data])
def test_1():
assert is_valid_1('aa bb cc dd ee'.split()) == True
assert is_valid_1('aa bb cc dd aa'.split()) == False
assert is_valid_1('aa bb cc dd aaa'.split()) == True
print('part 1 tests pass')
test_1()
print(part_1(data))
# part 2
def is_valid_2(row):
sorted_set = set()
for word in row:
sorted_word = tuple(sorted(list(word)))
sorted_set.add(sorted_word)
return len(row) == len(sorted_set)
def part_2(data):
return sum([is_valid_2(row) for row in data])
def test_2():
assert is_valid_2('abcde fghij'.split()) == True
assert is_valid_2('abcde xyz ecdab'.split()) == False
assert is_valid_2('a ab abc abd abf abj'.split()) == True
assert is_valid_2('iiii oiii ooii oooi oooo'.split()) == True
assert is_valid_2('oiii ioii iioi iiio'.split()) == False
print('part 2 tests pass')
test_2()
print(part_2(data))
|
97801fad6e272de3c1f1e41528095ffd871508f1 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/22 MID EXAM - Дата 2-ри ноември/Group 2 (My Group)/03. Tanks Collector.py | 4,465 | 3.625 | 4 | """
Programming Fundamentals Mid Exam - 2 November 2019 Group 2
Check your code: https://judge.softuni.bg/Contests/1862/Programming-Fundamentals-Mid-Exam-2-November-2019-Group-2
SUPyF2 P.-Mid-Exam/2 November 2019/2. - Experience Gaining
Problem:
Tom is a world of tanks player and he likes to collect premium tanks.
You will receive a list of Tom's already owned premium vehicles on a single line separated by ", ".
On the next n lines you will receive commands that could be:
• Add, {tankName}: Check if he already owns the wanted tank.
• If he owns it, print on console: "Tank is already bought"
• If not, print on console: "Tank successfully bought" and add it to the tank list.
• Remove, {tankName}: Check if he owns the tank.
• If he owns it print on console: "Tank successfully sold" and remove it from the tank list.
• If not print on console: "Tank not found"
• Remove At, {index}: Check if the index is in the range of the list.
• If not print on console: "Index out of range" and continue.
• If it’s in range, remove at the given index and print on console: "Tank successfully sold"
• Insert, {index}, {tankName}: Check if the index is in range of the list and check if he already owns the tank.
• If not print on console: "Index out of range" and continue.
• If it's in range and he doesn't own the tank then add the tank at the given index and print on console:
• "Tank successfully bought"
• If the tank is in range and he owns it already than print on console:
• "Tank is already bought"
After you go through all the commands you need to print the list on a single line separated by ", ".
Input:
• The first input line will contain the list of already owned tanks.
• The second input line will be the number of commands – an integer number in range [0…50].
• On the next input lines you will be receiving commands.
Output:
• As output you must print a single line containing the elements of the list, joined by ", ".
Examples:
Input:
T-34-85 Rudy, SU-100Y, STG
3
Add, King Tiger(C)
Insert, 2, IS-2M
Remove, T-34-85 Rudy
Output:
Tank successfully bought
Tank successfully bought
Tank successfully sold
SU-100Y, IS-2M, STG, King Tiger(C)
Comments:
The first command gives the tank list so its splitted and added into the list.
"T-34-85 Rudy, SU-100Y, STG"
The second commands gives the number of commands that will be received.
"3"
The Add command adds the tank to the list after the necessary checks.
"Add, King Tiger(C)" – "Tank successfully bought"
The Insert commands also adds the tank at the given spot after the necessary checks.
"Insert, 2, IS-2M" – "Tank successfully bought"
The Remove command is the last one and after the checks the tank is sold.
"Remove, T-34-85 Rudy" – "Tank successfully sold"
After that we print the list on the console.
"SU-100Y, IS-2M, STG, King Tiger(C)"
Input:
T 34, T 34 B, T92, AMX 13 57
4
Add, T 34
Remove, AMX CDC
Insert, 10, M60
Remove At, 1
Output:
Tank is already bought
Tank not found
Index out of range
Tank successfully sold
T 34, T92, AMX 13 57
"""
owned_tanks = input().split(", ")
num = int(input())
for i in range(num):
command = input().split(", ")
if command[0] == "Add":
tank_name = command[1]
if tank_name in owned_tanks:
print(f"Tank is already bought")
else:
owned_tanks.append(tank_name)
print("Tank successfully bought")
elif command[0] == "Remove":
tank_name = command[1]
if tank_name in owned_tanks:
owned_tanks.remove(tank_name)
print("Tank successfully sold")
else:
print("Tank not found")
elif command[0] == "Remove At":
index = int(command[1])
if 0 <= index < len(owned_tanks):
owned_tanks.pop(index)
print(f"Tank successfully sold")
else:
print(f"Index out of range")
elif command[0] == "Insert":
index, tank_name = int(command[1]), command[2]
if 0 <= index < len(owned_tanks):
if tank_name not in owned_tanks:
owned_tanks.insert(index, tank_name)
print(f"Tank successfully bought")
else:
print("Tank is already bought")
else:
print(f"Index out of range")
print(', '.join(owned_tanks))
|
3e247a0be9bcec16c53d3260e78e4b3b93b1f83c | jmgc/pyston | /test/tests/boolops.py | 1,167 | 3.578125 | 4 | def f(msg, rtn):
print msg
return rtn
n = 0
while n < 64:
i = n & 3
j = (n >> 2) & 3
k = (n >> 4) & 3
print f('a', i) and f('b', j)
print f('a', i) or f('b', j)
print f('a', i) and f('b', j) and f('c', k)
print f('a', i) and f('b', j) or f('c', k)
print f('a', i) or f('b', j) and f('c', k)
print f('a', i) or f('b', j) or f('c', k)
n = n + 1
class C(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
print "C.__nonzero__", self.x
return self.x
def __repr__(self):
return "<C object>"
print hash(True) == hash(False)
print int(True), int(False)
c = C("hello") # This object has an invalid __nonzero__ return type
if 0:
print bool(c) # this will fail
print 1 and c # Note: nonzero isn't called on the second argument!
print C(True) or 1 # prints the object repr, not the nonzero repr
print
# nonzero should fall back on __len__ if that exists but __nonzero__ doesn't:
class D(object):
def __init__(self, n):
self.n = n
def __len__(self):
print "__len__"
return self.n
for i in xrange(0, 3):
print i, bool(D(i))
|
b0ae0a60c7bb4ec45dc74e2c860b3de5d9ec763c | JeonSuHwan/StudyingPython | /Chapter4/h4_1.py | 156 | 4.1875 | 4 | num=int(input("Enter number : "))
count=0 #number of digits
while num>0:
count+=1
num//=10
print("The number of digits in the number is :",count)
|
ac7860e98d6e4f61c49fdb6dbd4025a9c5ecba5a | abbhowmik/PYTHON-Course | /chapter 10.py/constructor.py | 907 | 3.9375 | 4 | class Employee:
company = 'Google'
def __init__(self, name, salary, subunit):
self.name = name
self.salary = salary
self.subunit = subunit
print('Employee is created!')
def getDetails(self):
print(f'The name of the employee is {self.name}')
print(f'The salary of the employee is {self. salary}')
print(f'The subunit of the employee is {self. subunit}')
harry = Employee('Harry', 100, 'YouTube')
harry.getDetails()
# class Employee:
# company = 'Microsoft'
# def __init__(self, name, marks, division):
# self.name = name
# self.marks = marks
# self.division = division
# def getDetails(self):
# print(
# f"The name of the employee is {self.name}\nHis marks is {self.marks}\nHe got {self.division} division in exam")
# ashis = Employee('Ashis', 90, 'A')
# ashis.getDetails()
|
d5b135739b40cb2ca034d69a6a26c52fc9930ee5 | harshadevireddy/Instacart-Product-Recommendation | /EDA.py | 8,866 | 3.671875 | 4 |
# coding: utf-8
#import libraries and modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
color = sns.color_palette()
plt.style.use('ggplot')
#load and read all six csv datasets as dataframe objects and then look into them
# aisles.csv -- contains aisles identifier and name of the aisles
# unique in aisle_id
aisles = pd.read_csv('.../aisles.csv')
print('Total aisles: {}'.format(aisles.shape))
print(aisles.head(5))
#cheking for missing values
missing = aisles.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
# departments.csv -- contains department identifer and name of the department
# unique in department_id
departments = pd.read_csv('../departments.csv')
print('Total departments: {}'.format(departments.shape))
print(departments.head(5))
missing = departments.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
# products.csv -- contains all product information
# unique in product_id
products = pd.read_csv('../products.csv')
print('Total products: {}'.format(products.shape))
print(products.head(5))
missing = products.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
# orders.csv -- contains all order and customer purchase information
# tells us which set (prior, train, test) an order belongs to
# unique in order_id
orders = pd.read_csv('../orders.csv')
print('Total orders: {}'.format(orders.shape))
print(orders.head(5))
missing = orders.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
# order_products_prior.csv -- contains previous orders for all customers
#unique in order_id & product_id
orders_prior = pd.read_csv('../order_products_prior.csv')
print('Total prior orders: {}'.format(orders_prior.shape))
print(orders_prior.head(5))
missing = orders_prior.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
# order_products_train.csv -- contains last orders for all customers
#unique in order_id & product_id
orders_train = pd.read_csv('../order_products_train.csv')
print('Total last orders: {}'.format(orders_train.shape))
print(orders_prior.head(5))
missing = orders_train.isnull().sum().sort_values(ascending=False)
print("Missing data: ", missing)
#combine order_products_prior.csv and order_products_train.csv into one dataframe
orders_products = pd.concat([orders_prior, orders_train], axis=0)
print("Total is: ", orders_products.shape)
print(orders_products.head(5))
# combine aisles.csv, departments.csv and products.csv into one dataframe
products_data = pd.merge(left=pd.merge(left=products, right=departments, how='left'), right=aisles, how='left')
# to make product_name and aisle more usable and remove spaces between words
products_data.product_name = products_data.product_name.str.replace(' ', '_').str.lower()
products_data.aisle = products_data.aisle.str.replace(' ', '_').str.lower()
print("Total rows: ", products_data.shape)
print(products_data.head(5))
# 'eval_set' in orders.csv informs the given order goes to which of the three datasets (prior, train or test)
count_set = orders.eval_set.value_counts()
print(count_set)
# define function to count the number of unique customers
def customer_count(x):
return len(np.unique(x))
customer = orders.groupby("eval_set")["user_id"].aggregate(customer_count)
print(customer)
# number of unique orders and unique products
unique_orders = len(set(orders_products.order_id))
unique_products = len(set(orders_products.product_id))
print("There are %s orders for %s products" %(unique_orders, unique_products))
#number of products that customers usually order
data = orders_products.groupby("order_id")["add_to_cart_order"].aggregate("max").reset_index()
data = data.add_to_cart_order.value_counts()
plt.figure(figsize=(12, 8))
sns.barplot(data.index, data.values, alpha=0.8)
plt.xticks(rotation='vertical')
plt.ylabel('Number of Orders', fontsize=12)
plt.xlabel('Number of products added in order', fontsize=12)
plt.show()
#the number of orders made by each costumer in the whole dataset
data = orders.groupby('user_id')['order_id'].apply(lambda x: len(x.unique())).reset_index()
data = data.groupby('order_id').aggregate("count")
sns.set_style("whitegrid")
f, ax = plt.subplots(figsize=(15, 12))
sns.barplot(data.index, data.user_id)
plt.ylabel('Numbers of Customers')
plt.xlabel('Number of Orders per customer')
plt.xticks(rotation='vertical')
plt.show()
# time at which people usually order products
# hours of order in a day
data = orders.groupby("order_id")["order_hour_of_day"].aggregate("sum").reset_index()
data = data.order_hour_of_day.value_counts()
sns.set_style('darkgrid')
plt.figure(figsize=(12, 8))
sns.barplot(data.index, data.values)
plt.ylabel('Number of orders', fontsize=12)
plt.xlabel('Hours of order in a day', fontsize=12)
plt.title('When people buy groceries online?', fontweight='bold')
plt.xticks(rotation='vertical')
plt.show()
# order and day of a week
data = orders.groupby("order_id")["order_dow"].aggregate("sum").reset_index()
data = data.order_dow.value_counts()
days=[ 'sat','sun', 'mon', 'tue', 'wed', 'thu', 'fri']
plt.figure(figsize=(12,8))
sns.barplot(data.index, data.values)
plt.ylabel('Number of orders', fontsize=12)
plt.xlabel('Days of order in a week', fontsize=12)
plt.title("Frequency of order by week day", fontweight='bold')
plt.xticks(rotation='vertical')
plt.xticks(np.arange(7), ( 'sat','sun', 'mon', 'tue', 'wed', 'thu', 'fri'))
plt.show()
# When do they order again? time interval between orders
plt.figure(figsize=(12,8))
sns.countplot(x="days_since_prior_order", data=orders)
plt.ylabel('Nuumber of Orders', fontsize=12)
plt.xlabel('Days since prior order', fontsize=12)
plt.xticks(rotation='vertical')
plt.xticks(np.arange(31))
plt.title("Time interval between orders", fontsize=15)
plt.show()
# percentage of reorders in prior set #
print(orders_prior.reordered.sum() / orders_prior.shape[0])
# percentage of reorders in train set #
print(orders_train.reordered.sum() / orders_train.shape[0])
#reorder frequency
data = orders_products.groupby("reordered")["product_id"].aggregate({'Total_products': 'count'}).reset_index()
data['Ratios'] = data["Total_products"].apply(lambda x: x /data['Total_products'].sum())
data
data = data.groupby(['reordered']).sum()['Total_products'].sort_values(ascending=False)
sns.set_style('darkgrid')
f, ax = plt.subplots(figsize=(6, 8))
sns.barplot(data.index, data.values)
plt.ylabel('Number of Products', fontsize=12)
plt.xlabel('Not Reordered = 0 and Reordered = 1', fontsize=12)
plt.title('Reorder Frequency', fontweight='bold')
plt.ticklabel_format(style='plain', axis='y')
plt.show()
#merge products_data with the orders_products data.
orders_products_all = pd.merge(orders_products, products_data, on='product_id', how='left')
print("Total rows: ", orders_products_all.shape)
print(orders_products_all.head(5))
#merge products_data with the orders_prior data.
orders_prior_all = pd.merge(orders_prior, products_data, on='product_id', how='left')
print("Total rows: ", orders_prior_all.shape)
print(orders_prior_all.head(5))
#which products are ordered the most
data = orders_products.groupby("product_id")["reordered"].aggregate({'Total_reorders': 'count'}).reset_index()
data = pd.merge(data, products[['product_id', 'product_name']], how='left', on=['product_id'])
data = data.sort_values(by='Total_reorders', ascending=False)[:10]
print(data)
data = orders_products.groupby("product_id")["reordered"].aggregate({'Total_reorders': 'count'}).reset_index()
data = pd.merge(data, products[['product_id', 'product_name']], how='left', on=['product_id'])
data = data.sort_values(by='Total_reorders', ascending=False)[:10]
data = data.groupby(['product_name']).sum()['Total_reorders'].sort_values(ascending=False)
sns.set_style('darkgrid')
f, ax = plt.subplots(figsize=(12, 8))
plt.xticks(rotation='vertical')
sns.barplot(data.index, data.values)
plt.ylabel('Number of Reorders', fontsize=12)
plt.xlabel('Most ordered Products', fontsize=12)
plt.title('which products are ordered the most', fontweight = 'bold')
plt.show()
#most important aisles: best selling
data = orders_prior_all['aisle'].value_counts()
plt.figure(figsize=(12,10))
sns.barplot(data.index, data.values, alpha=0.8)
plt.ylabel('Number of Occurrences', fontsize=12)
plt.xlabel('Aisle', fontsize=12)
plt.title('Important Aisles', fontweight ='bold')
plt.xticks(rotation='vertical')
plt.show()
#customer's favorite best selling departments (number of orders)
data = orders_prior_all['department'].value_counts()
plt.figure(figsize=(12,10))
sns.barplot(data.index, data.values, alpha=0.8)
plt.ylabel('Number of Occurrences', fontsize=12)
plt.xlabel('Department', fontsize=12)
plt.title("Departments wise distribution of products", fontweight='bold')
plt.xticks(rotation='vertical')
plt.show()
|
7259e49c97fba352f431fec1bcd24c01cb3a03cf | charan2108/pyprocharmprojects | /pythoncrashcourse/crashcourse/inputs/inputs.py | 221 | 4.03125 | 4 | name =input("Enter your name\n")
age =int(input("Enter age\n"))
city =input("Enter city\n")
email =input("Enter email\n")
print(f"your name is {name} \n and age is{age} \n and city is{city}\n and email is {email}\n")
|
07afea790adfa8625ea3983bd8fb4ab90bfe5d03 | khatoonfatima/Python-Programming | /Recursive Function.py | 5,175 | 4.84375 | 5 | #!/usr/bin/env python
# coding: utf-8
# # RECURSIVE FUNCTION
# A function that calls itself is known as Recursive Function
# Example:
# factorial(3)=3*factorial(2)
#
# =3*2*factorial(1)
#
# =3*2*1*factorial(0)
#
# = 3*2*1*1
#
# =6
# factorial(n)=n*factorial(n-1)
#
# The main advantage of recursive functions are:
#
# 1.We can reduce the length of the code and redability
#
# 2.We can solve the complex problems very easily
# # Write a python function to find factorial of given number with recursion
# In[8]:
def factorial(n): #the product of an integer and all the integers below it; e.g. factorial four ( 4! ) is equal to 24.
if n==0:
result=1
else:
result =n*factorial(n-1)
return result
print("Factorial of 4 is:",factorial(4)) #4*3*2*1=24
print("Factorial of 5 is :",factorial(5)) #5*4*3*2*1=120
# # n!=n(n-1)(n-2)(n-3)
# #### factorial is used for questions that ask you to find how many ways you can arrange or order a set number of things.
# # Anonymous Function
# Sometimes we can declare a function witout any name,such type of function is called anonymous functions or lambda functions.
#
#
# Thee main purpose of the function is just for instant use (i.e, for one time usage)
# # Normal Function
# We can define by using def keyword.
# def squarelt(n):
# return n*n
# # Lambda function
# ## We can define by lambda keyword lambda n:n*n
# ## Syntax For lambda function:
# ### lambda argument_list:expression
# By using Lambda Functions we can write in very concise code so that readability of the program will be improved.
# # Write a program top create a lambda function to find square of given number?
# In[10]:
s=lambda n:n*n
print("The square of 4 is:",s(4))
print("The square of 5 is :",s(5))
# # Lambda function to find sum of 2 given number
# In[12]:
s=lambda a,b:a+b
print("The sum of 10,20 is:",s(10,20))
print("The sum of 100,200 is:",s(100,200))
# # Lambda function to find the sum og two given number
# In[2]:
s=lambda a,b:a+b
print("The sum of 10,20 numbers",s(10,20))
print("The sum of 100,200 number",s(100,200))
# # Lambda function to find the biggest among two numbers
# In[5]:
s=lambda a,b:a if a>b else b #lambda with if and else
print("The biggest number among 10,20 is",s(10,20))
print("The biggest number among 100,200 is",s(100,200))
# Note:Lambda function internally returns expression value and we are not required to write return statement explicitly.
#
# Note:Sometimes we can pass function as arguments to another function.In such cases lambda function are best choice.
# # We can use the lambda function very commonly with the filter(),map(),and reduce()functions,because these functions expect function as arguments.
# # filter()
# We can use filter() function to filter values from the given sequence based on some condition
# # Syntax:
#
# filter(function,sequence)
# where function arguments is responsible to perform conditional check sequence can be list or a tuple or string
# # Program to filter only even numbers from list by using filter() function?
# # without lambda function
# In[8]:
def isEven(x):
if x%2==0:
return True
else:
return False
l=[0,5,10,15,20]
l1=list(filter(isEven,l))
print(l1)
# # without lambda function
# In[15]:
l=[0,5,10,15,20,25,30,35,40]
l1=list(filter(isEven,l))
print(l1) #[0,10,20,30]
# # map() function
# #### For every element present in the sequence ,apply some functionality and generate new element with the required modification.For this requirement we should go for map() function
# Example:
# For every element present in the list perform double and generate new lists of doubles.
# # Syntax
# # map(function,sequence)
# The function can be applied to each element of the sequence nad generates new sequence
# # example:
# without lambda
#
# In[10]:
l=[1,2,3,4,5]
def doublelt(x):
return 2*x
l1=list(map(doublelt,l))
print(l1)
# # To find the square of the given number
# In[11]:
l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1)
# We can apply map() function on multiple lists also.but make sure all list should have the same length.
# Syntax:map(lambda x,y:x*y,l1,l2)
#
# x is from l1
# y is from l2
# In[13]:
l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3)
# # reduce() function
# reduce() function reduce sequence of elements into a single element by applying the specified function.
# reduce() function is present in functools module and hence we should write import statement
# In[19]:
from functools import *
l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result)
# In[20]:
result=reduce(lambda x,y:x*y,l)
print(result)
# In[21]:
from functools import *
result=reduce(lambda x,y:x+y,range(1,101))
print(result)
# Note:
# In python everything is created as an object.
# Even functions also internally traeted as objects only.
#
# In[22]:
def f1():
print("Hello")
print(f1)
print(id(f1))
|
a36d7ec6f2760bfb814c09424395027f24cfaf8d | ryanpbrewster/Python-Tic-Tac-Toe | /src/AI.py | 2,988 | 4.1875 | 4 | """
A class containing all of the logic for an AI that plays TicTacToe
A note on the way the static and non-static methods work in this class:
* Static methods take a board, a tac to check, and a position, and return an
evaluation (true or false).
* Non-static methods, however, are called by an instance of the AI class. These
methods are specifically used for making moves on a board which has been
supplied. They're role is more than returning an evaluation: they change the
state of the board which they are supplied with.
* Basically, methods that are called by an instance of the class are proactive,
i.e., they change the state of something. Class methods merely supply
information.
"""
from copy import deepcopy
class AI:
WIN_REWARD = 100
UNKNOWN_REWARD = 50
LOSE_REWARD = 0
def __init__(self, tac, level=1):
"""
Initializes an AI instance with appropriate tacs. Should only be used
if AI is going to play, not for making detections.
"""
self.tac = tac
self.enemy_tac = 'O' if tac == 'X' else 'X'
self.level = level
def chooseMove(self, large_board):
"""
Return (board_pos, pos), where board_pos is the position of the board
you want to make a move in, and pos is the position within that board.
If board_pos == None then it means you there is a free choice
For now, the AI is dumb and just makes the first legal move it finds
"""
moves = self.allLegalMoves(large_board)
scores = [ self.scoreMove(large_board, move) for move in moves ]
best_move = max(zip(scores, moves))[1]
return best_move
def allMoves(self):
return [ ((i,j), (ii,jj)) for i in range(3) for j in range(3)
for ii in range(3) for jj in range(3) ]
def allLegalMoves(self, large_board):
return [ move for move in self.allMoves() if large_board.isLegalPlay(move) ]
def firstLegalMove(self, large_board):
return self.allLegalMoves(large_board)[0]
def dumbScore(self, large_board):
winner = large_board.winner()
if winner == self.tac:
return AI.WIN_REWARD
elif winner == self.enemy_tac:
return AI.LOSE_REWARD
else:
return AI.UNKNOWN_REWARD
def scoreBoard(self, large_board):
if self.level == 0:
return self.dumbScore(large_board)
lower_ai = AI(self.enemy_tac, self.level - 1)
enemy_moves = lower_ai.allLegalMoves(large_board)
if len(enemy_moves) == 0:
return self.dumbScore(large_board)
enemy_scores = [ lower_ai.scoreMove(large_board, move) for move in enemy_moves ]
enemy_best_score = max(enemy_scores)
return -enemy_best_score
def scoreMove(self, large_board, move):
copy_board = deepcopy(large_board)
copy_board.putTac(self.tac, move)
return self.scoreBoard(copy_board)
|
7fa74a7e2632d59652adcc411374558c81311f65 | jonathanshuai/solid | /liskov_substitution_principle/animal.py | 1,022 | 4.125 | 4 | """This animal class is to look at Liskov Substitution Principle.
The Liskov substitution principle says a sub-class must be substitutable for its
super class. In other words, we should be able to put a subclass in place of a
super class and run without errors.
"""
# We have our animal class again. Let's say we want to add sounds to it.
# Outside in the run.py class, you can see the example of us trying to add
# sounds to each animal.
class Animal:
def __init__(self, name):
self.name = name
def get_animal_name(self):
return self.name
def count_legs(self):
return 0
class Dog(Animal):
def __init__(self, name):
super(Dog, self).__init__(name)
def count_legs(self):
return 4
class Duck(Animal):
def __init__(self, name):
super(Duck, self).__init__(name)
def count_legs(self):
return 2
class Snake(Animal):
def __init__(self, name):
super(Snake, self).__init__(name)
def count_legs(self):
return 0 |
913dfc4cce717fcad35331ee2d957995b11d9b8f | ramador0010/github-upload | /for.py | 67 | 3.71875 | 4 | for i in range(2,8,3):
print("The Value of i is currently:",i)
|
402c6d71acb6fb65a1cc4d390fbf2b062b4d7cef | oneiromancy/leetcode | /medium/1315. Sum of Nodes with Even-Valued Grandparent.py | 1,361 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def sumEvenGrandparent(self, root):
nodes = [root]
total = 0
while nodes:
currentNode = nodes.pop()
if hasattr(currentNode, 'parent') and hasattr(currentNode.parent, 'parent'):
if currentNode.parent.parent.val % 2 == 0:
total += currentNode.val
if currentNode.right:
currentNode.right.parent = currentNode
nodes.append(currentNode.right)
if currentNode.left:
currentNode.left.parent = currentNode
nodes.append(currentNode.left)
return total
# Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
# If there are no nodes with an even-valued grandparent, return 0.
# Example 1:
# Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
# Output: 18
# Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
# Constraints:
# The number of nodes in the tree is between 1 and 10^4.
# The value of nodes is between 1 and 100.
|
599285ff90828874c7e8e654f9feb26e5fae7fc1 | jbeaulieu/MIT-ES.S70 | /lecture_9/group_9_with_plot.py | 2,827 | 3.65625 | 4 | #################################
# Title: Lecture 9 Group Script #
# Lesson: Magnetic Field/Force #
# Filename: group_9.py #
# Original Author: Joe Griffin #
# Most Recent Edit: 2/6/2014 #
# Last Editor: Joe Griffin #
#################################
# This script calculates positions, velocities, and accelerations as numpy arrays and
# records tuples of those data in a text file to read into VPython elsewhere.
from matplotlib.pyplot import plot, show
import numpy as np
from math import pi,sqrt
from matplotlib.pyplot import plot, title, show, grid, subplot
startPos = np.array((0,0, 0)) # Initial Conditions
startVel = np.array((10,2., 0))
B = np.array((0,1e-3,0)) # Environmental Conditions
B_mag = np.linalg.norm(B) # magnitude of B (In T)
m = 1e-22 # Particle Properties ([m]=kg, [q]=C)
q = 1.6*1e-19
v_p = sqrt( startVel[0]**2 + startVel[2]**2 ) # component of the velocity in the
# direction perpendicular to the B-filed
R = m * v_p/(abs(q) * B_mag) # Radius of the orbit [R] = m
T = 2. * pi * m / (abs(q) * B_mag) # Period [T[]= s
Np = 3 # Number of periods
#dt = 1e-3 # Simulator Settings
dt = T /1000 # 1000 points in one period
numPoints = Np * int ( T /dt)
print "mag B",B_mag
print "R", R
print "v_p", v_p
print "Period", T
print "dt", dt
print "Number of periods", Np
print "number of iterations", numPoints
# Start calculations and storage
pos=[]
acc=[]
vel=[]
force=[]
with open('traj1.txt', 'w', 0) as text: # Open a writeable text file
p = startPos
v = (startVel)
for iteration in xrange(numPoints):
t = dt * iteration
f = np.cross(q * v, B) # Magnetic force calculation
a = f / m
v = v + (a * dt) # Integrals
p = p + (v * dt)
pVec = p.tolist() # This will make reading from the
vVec = v.tolist() # file much nicer.
aVec = a.tolist()
text.write(str((pVec, vVec, aVec)) + '\n') # Data dump
pos.append(p)
acc.append(a)
vel.append(v)
force.append(f)
# If we want to plot to see things are OK Define the np.arrays
pos_a = np.array(pos)
acc_a = np.array(acc)
vel_a = np.array(vel)
force_a=np.array(force)
subplot(221)
grid(True)
plot(pos_a[:,0]/R)
title("x/R vs t")
subplot(222)
grid(True)
plot(pos_a[:,0]/R,pos_a[:,2]/R)
title('z/R vs x/R')
subplot(212)
grid(True)
plot(( vel_a[:,0]**2 + vel_a[:,1]**2+vel_a[:,2]**2 )**0.5 )
title("Kinetic energy vs time")
show()
|
a11a919f3ab831162d61becfe7962f48ebf7fe2c | margaridav27/feup-fpro | /PEs/PE02 model/genealogy_by_order.py | 1,006 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 09:06:34 2019
@author: Margarida Viera
"""
def rule(item):
name, relation = item
order = ('sibling', 'parent', 'cousin', 'grandparent').index(relation)
return order, name
def genealogy(l):
tree = sorted(l, key = rule, reverse = False)
return tree
print(genealogy([('maria', 'parent'), ('matilde', 'grandparent'), ('geraldes', 'grandparent'), ('carlos', 'sibling'), ('paulo', 'sibling'), ('artur', 'grandparent'), ('pedro', 'parent'), ('alfredo', 'cousin'), ('carla', 'cousin')]))
print()
print(genealogy([('sofia', 'sibling'), ('sara', 'parent'), ('bernardo', 'parent')]))
print()
print(genealogy([('bart', 'sibling'), ('mona', 'grandparent'), ('ling', 'cousin'), ('homer', 'parent'), ('magie', 'sibling'), ('marge', 'parent'), ('abraham', 'grandparent')]))
print()
print(genealogy([('geraldes', 'cousin'), ('mario', 'parent'), ('sara', 'sibling'), ('carlos', 'cousin'), ('maria', 'parent'), ('rui', 'cousin'), ('raul', 'cousin')]))
|
d74ef1fc6f148ad2ca7ce4a39c567e2e512078bd | zhangchizju2012/LeetCode | /134.py | 786 | 3.515625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 6 19:57:49 2017
@author: zhangchi
"""
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if len(gas) == 0:
return 0
dif = []
for a,b in zip(gas,cost):
dif.append(a-b)
for i in range(len(dif)):
if dif[i] >= 0:
temp = 0
label = True
for item in dif[i:] + dif[:i]:
temp += item
if temp < 0:
label = False
break
if label == True:
return i
return -1 |
50439f98a547e1d8290d8344941c5fc1955cb302 | SanchoMontana/Pong | /Pong.py | 7,995 | 3.671875 | 4 | import pygame
from time import sleep, time
if __name__ == '__main__':
from Paddle import Paddle
from Ball import Ball
from PowerUp import PowerUp
DISPLAY_WIDTH = 1200
DISPLAY_HEIGHT = 700
PADDLE_GAP = 60
PADDLE_GIRTH = 20
PADDLE_SPEED = 8
BALL_RADIUS = 25
BALL_START_VEL = 10
FPS = 80 # Frames per second.
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
SCORE_TO_WIN = 5
START_TIME = int(time()) # This is used for creating powerUps.
pygame.init()
pygame.mouse.set_visible(False)
gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
clock = pygame.time.Clock()
score_font = pygame.font.SysFont(None, DISPLAY_WIDTH // 20)
alert_font = pygame.font.SysFont(None, 24)
# Waits until the user is ready to start the next round.
def start_round(ball, velocity):
alert = alert_font.render("Press [space] to continue", True, WHITE)
pygame.draw.rect(gameDisplay, BLACK,
[DISPLAY_WIDTH // 2 - alert.get_width() // 2,
DISPLAY_HEIGHT - 2 * alert.get_height() - 15,
alert.get_width(), alert.get_height() * 2])
gameDisplay.blit(alert, (DISPLAY_WIDTH // 2 - alert.get_width() // 2, DISPLAY_HEIGHT - alert.get_height() - 15))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball.x_vel = velocity
ball.vel = abs(velocity)
return
def main():
def draw():
# Updates the black background, everything that is drawn should be after this.
gameDisplay.fill(BLACK)
# Draws the middle line
for i in range(20):
pygame.draw.rect(gameDisplay, WHITE,
[DISPLAY_WIDTH / 2 - 3, DISPLAY_HEIGHT / 20 * i, 6, DISPLAY_HEIGHT / 40])
# Draw paddles
pygame.draw.rect(gameDisplay, WHITE, [P1.x - P1.girth / 2, P1.y - P1.height / 2, P1.girth, P1.height])
pygame.draw.rect(gameDisplay, WHITE, [P2.x - P2.girth / 2, P2.y - P2.height / 2, P2.girth, P2.height])
# Draws the ball
pygame.draw.circle(gameDisplay, WHITE, (int(ball.x), int(ball.y)), int(ball.radius))
# Draws powerUps
for i in power:
if i.visibility:
pygame.draw.circle(gameDisplay, i.color, (i.x, i.y), 30)
# Draws the score of each player on the top of the screen
leftScoreText = score_font.render(str(score[0]), True, WHITE)
gameDisplay.blit(leftScoreText, (DISPLAY_WIDTH / 2 - leftScoreText.get_width() - 20, 10))
rightScoreText = score_font.render(str(score[1]), True, WHITE)
gameDisplay.blit(rightScoreText, (DISPLAY_WIDTH / 2 + 20, 10))
pygame.display.update()
# Checks if one player reached the winning score. If so, it displays the winner and restarts the game.
def end_of_game(scores):
if scores[0] >= SCORE_TO_WIN or scores[1] >= SCORE_TO_WIN:
draw()
# Win condition
if scores[0] >= SCORE_TO_WIN:
winner = score_font.render("Left Paddle Wins!", True, WHITE)
else:
winner = score_font.render("Right Paddle Wins!", True, WHITE)
pygame.draw.rect(gameDisplay, BLACK,
[DISPLAY_WIDTH / 2 - winner.get_width() / 2,
DISPLAY_HEIGHT / 2 - winner.get_height() / 2 - 20,
winner.get_width(), winner.get_height() + 40])
gameDisplay.blit(winner,
(DISPLAY_WIDTH / 2 - winner.get_width() / 2,
DISPLAY_HEIGHT / 2 - winner.get_height() / 2))
pygame.display.update()
sleep(2)
alert = alert_font.render("Press [space] to play again or [esc] to quit.", True, WHITE)
pygame.draw.rect(gameDisplay, BLACK,
[DISPLAY_WIDTH // 2 - alert.get_width() // 2,
DISPLAY_HEIGHT - 2 * alert.get_height() - 15,
alert.get_width(), alert.get_height() * 2])
gameDisplay.blit(alert, (DISPLAY_WIDTH // 2 - alert.get_width() // 2,
DISPLAY_HEIGHT - alert.get_height() - 15))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
return [0, 0]
if event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
return scores
score = [0, 0]
P1 = Paddle(PADDLE_GAP, DISPLAY_HEIGHT / 2,
DISPLAY_HEIGHT / 4, PADDLE_GIRTH, pygame.K_w, pygame.K_s)
P2 = Paddle(DISPLAY_WIDTH - PADDLE_GAP, DISPLAY_HEIGHT / 2,
DISPLAY_HEIGHT / 4, PADDLE_GIRTH, pygame.K_UP, pygame.K_DOWN)
ball = Ball(DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2, BALL_RADIUS, BALL_START_VEL, 0)
game_exit = False # Exits the main loop if this is True.
add_power = int(time())
power = [] # Will be appended every x seconds.
# Input Handing loop
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True # This allows the X in the corner to close the window.
elif event.type == pygame.KEYDOWN: # Everything in this elif statement has key input handling
if event.key == P1.move_up:
P1.vel -= PADDLE_SPEED
elif event.key == P1.move_down:
P1.vel += PADDLE_SPEED
elif event.key == P2.move_up:
P2.vel -= PADDLE_SPEED
elif event.key == P2.move_down:
P2.vel += PADDLE_SPEED
elif event.type == pygame.KEYUP: # Event handling when key is lifted.
if event.key == P1.move_up:
P1.vel += PADDLE_SPEED
elif event.key == P1.move_down:
P1.vel -= PADDLE_SPEED
elif event.key == P2.move_up:
P2.vel += PADDLE_SPEED
elif event.key == P2.move_down:
P2.vel -= PADDLE_SPEED
# Move Paddles and Ball
P1.move()
P2.move()
ball.move()
ball.collision(P1, P2)
# Create PowerUp every ten seconds
if (int(time()) - START_TIME) % 10 == 0:
if add_power != int(time()):
power.append(PowerUp(ball))
add_power = int(time())
# Check ball Collision with PowerUps
for i in power:
i.check_passive(ball)
i.check_active(ball)
if i.expired:
power.remove(i)
# Check if there is a goal
if ball.goal():
P1.reset()
P2.reset()
if ball.x > DISPLAY_WIDTH:
score = [score[0] + 1, score[1]]
else:
score = [score[0], score[1] + 1]
score = end_of_game(score)
# Checks which player scored, increases their score and gives them the ball to start the next round
if ball.x > DISPLAY_WIDTH:
ball.reset()
draw()
start_round(ball, 10)
else:
ball.reset()
draw()
start_round(ball, -10)
power = [] # Clears the arena of any unused powerUps.
# Update the game
draw()
clock.tick(FPS)
pygame.quit()
quit()
if __name__ == '__main__':
main()
|
c0d019032a6cd01633a5b5d95591e5e3f5515c18 | hellwarrior-2/codewarskatas | /delet_ocurrences_nth.py | 1,415 | 4 | 4 | #Exercise 6 kyu
#Delete occurrences of an element if it occurs more than n times
#Enough is enough!
#Alice and Bob were on a holiday. Both of them took many pictures
#of the places they've been, and now they want to show Charlie their
#entire collection. However, Charlie doesn't like this sessions, since
#the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times.
#He tells them that he will only sit during the session if they show the
#same motive at most N times. Luckily, Alice and Bob are able to encode
#the motive as a number. Can you help them to remove numbers such that
#their list contains each number only up to N times, without changing the order?
#Task
#Given a list lst and a number N, create a new list that contains each
#number of lst at most N times without reordering. For example if N = 2,
#and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next
#[1,2] since this would lead to 1 and 2 being in the result 3 times,
#and then take 3, which leads to [1,2,3,1,2,3].
#Example
#delete_nth ([1,1,1,1],2) # return [1,1]
#delete_nth ([20,37,20,21],1) # return [20,37,21]
def delete_nth(order, max_e):
ans = []
[ans.append(i) for i in order if ans.count(i)< max_e]
return ans
#test cases
print(delete_nth([20,37,20,21], 1)) #should equals [20,37,21]
print(delete_nth([1,1,3,3,7,2,2,2,2], 3)) #should equals [1, 1, 3, 3, 7, 2, 2, 2])
|
6ea6e432f9fdd0b08e4f6e4e423ee68d8dfc4e58 | WilliamKulha/learning_python | /looping_lists/pizzas.py | 483 | 4.34375 | 4 | pizzas = ['Margherita', 'Sicilian', 'Neopolitan']
for pizza in pizzas:
print(pizza)
for pizza in pizzas:
print(f"Oh my god! Have you tried their {pizza} pizza?? It's to die for!\n")
print("\nMan I really love pizza!")
friends_pizzas = pizzas[:]
pizzas.insert(0, 'Meat Lovers')
friends_pizzas.insert(0, 'Supreme')
print(f"Here's the original list: {pizzas}\nHere's the friends list:{friends_pizzas}")
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
|
19a0215529eeb6f5f22994b5c2ae40be41e7c862 | CrtomirJuren/pygame-projects | /array_backed_grid/array_backed_grid_oop_2.py | 2,860 | 4 | 4 | """Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
class cube(object):
"""
"""
w = 500 #set pixel screen width
rows = 20 #set number of rows
def __init__(self,start,dirnx=1,dirny=0,color=RED):
self.pos = start
self.dirnx = 1
self.dirny = 0
self.color = color
def move(self,dirnx,dirny):
"""
move cube, by adding new direction to previous position
"""
self.dirnx = dirnx
self.dirny = dirny
self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)
def draw(self,surface,eyes=False):
"""
drawing: convert x,y grid position to pixel position
"""
dis = self.w // self.rows #distance between x and y values
#variables for easy coding
i = self.pos[0] # row
j = self.pos[1] # column
#draw just a little bit less, so we draw inside of the square. and we dont cover grid.
pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))
#draw eyes
if eyes:
centre = dis//2
radius = 3
circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1
circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2
pygame.draw.circle(surface, BLACK, circleMiddle, radius)
pygame.draw.circle(surface, BLACK, circleMiddle2, radius)
def drawGrid(w,rows,surface):
"""
This function draws a square grid on main display
"""
#distance between grid lines
sizeBtwn = w // rows
x = 0
y = 0
#create grid by drawing lines
for l in range(rows):
x = x + sizeBtwn
y = y + sizeBtwn
#vertical lines
pygame.draw.line(surface, WHITE, (x,0), (x,w))
#horizontal lines
pygame.draw.line(surface, WHITE, (0,y), (w,y))
def redrawWindow(surface):
global rows, width, s
#background
surface.fill(BLACK)
#draw grid
drawGrid(width, rows, surface)
#update display
pygame.display.update()
def main():
global width, rows, s
#create game display
width = 500
rows = 20
win = pygame.display.set_mode((width, width)) #square display
clock = pygame.time.Clock()
flag = True
FPScount = 0
print(FPScount)
while flag:
#pygame.time.delay(50)
clock.tick(10) #game max speed 10 FPS
s.move()
redrawWindow(win)
FPScount += 1
print(f'FPScount:{FPScount}')
#rows = 0
#w = 0
#h = 0
#cube.rows = rows
#cube.w = w
main()
pygame.quit()
sys.exit() |
5a49402162b5e6f00e4fe5df8c3e753decc41939 | i-m-alok/ProblemvsAlgorithm | /Problem2/problem2.py | 2,333 | 4.0625 | 4 | def find_pivot(arr):
# count=0
start=0
end=len(arr)-1
while start <= end:
# count+=1
# print(count)
mid= ( start + end ) // 2
#if mid+1 is less than mid it means pivot is arr[mid]
if arr[mid] > arr[mid + 1]:
return mid+1
#if start is less than mid, they are is sequence and need to shift start
if arr[start] <= arr[mid]:
start=mid+1
#else need to shift end
else:
end=mid-1
def binarySearch(arr, start, end, x):
while start <= end:
mid = start + (end - start) // 2
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
start = mid + 1
# If x is smaller, ignore right half
else:
end = mid - 1
# If we reach here, then the element
# was not present
return -1
def rotated_array_search(arr,value):
if len(arr)==0:
return -1
if len(arr)==1:
if arr[0]==value:
return 0
return -1
pivot = find_pivot(arr)
get = binarySearch(arr, 0, pivot-1, value)
if get == -1:
get = binarySearch(arr, pivot, len(arr)-1, value)
return get
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
print("______________________________TEST CASE 1__________________________")
test_function([[6, 7, 8, 9, 10, 11, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
print("______________________________TEST CASE 2__________________________")
test_function([[1, 2, 3, 4,5,6,7,0], 10])
test_function([[-1, -2, -3, -4, 0, 1, 2, 3], 0])
print("______________________________TEST CASE 3__________________________")
test_function([[0, -1], 1]) #edge cases
test_function([[1], 1]) #edge cases
test_function([[], 0]) #edge case
|
82487afd9df120a41346622f187bd61582425027 | jgneshbpatel/Python | /PrimeNumber.py | 675 | 4.09375 | 4 | #FileName: PrimeNumbers.py
#Defining function to get prime numbers till provided number
def func(n):
primeNumbers=[]
for x in range(n+1):
i=1
count = 0
while i<=x:
if x%i==0:
#print ('x is:', x)
#print ('i is:', i)
count = count + 1
i=i+1
else:
i = i+1
if count==2:
primeNumbers.append(x)
#print ('prime number:', x)
print (primeNumbers)
#calling function
p = int(input('Enter Number to get prime numbers till that number:'))
func(p)
|
0dbf9880f2da2d2688bc0f52155641991b8f3dfb | fooSynaptic/exam | /Coding/find_mid.py | 276 | 3.609375 | 4 | #py3
import random
arr = [random.randint(0,50) for i in range(100)]
print(arr[len(arr)//2])
def findmid(arr):
fast, slow = 0, 0
while fast < len(arr):
slow += 1
fast += 2
#print(slow ,fast)
return arr[slow]
print("res:",findmid(arr)) |
ceb493998373c96c18b3aba20b0f58b3d96cdc9c | daniel-reich/ubiquitous-fiesta | /KExMohNcKkJYeTE2E_18.py | 184 | 3.796875 | 4 |
def is_orthogonal(first, second):
if len(first)==2:
return first[0]*second[0]+first[1]*second[1]==0
else: return first[0]*second[0]+first[1]*second[1]+first[2]*second[2]==0
|
f41ccb3b5e4dc9113c92bca4b931e917bc86d821 | Guikaio/algorithms | /python/Sequencial/exc2.py | 653 | 4.28125 | 4 | #2.Faca um programa que receba tres notas, calcule e mostre a media aritmetica entre elas.
print("********************SEQUENCIAL*************************")
print("********************Programa*2*************************")
print("************Calculo da média aritmética. **************")
print("*******************************************************")
num1_typed = input("Digite a primeira nota: " )
num2_typed = input("Digite a segunda nota: " )
num3_typed = input("Digite a terceira nota: ")
res_type = float(num1_typed) + float(num2_typed) + float(num3_typed)
print('A media aritmetica das tres notas são %s' % format(float(res_type/3), ".1f")) |
52c3980cfc3e1623f4c4f6a52f01047c4bf5c432 | rafaelmm82/learning | /datacamp/case_study_hacker_statistics.py | 1,656 | 4.25 | 4 | """
Application of initial functions, packages and libraries associated with
datascience using python, course:
"Intermediate Python for Data Science"
This project concerns on simulate a random walk through the floors stages on
Empire State Building, by rolling a virtual dice
code conducted by: datacamp
codede by: rafael magalhaes (github @rafaelmm82)
"""
# Importing the essentials
import numpy as np
import matplotlib.pyplot as plt
# setting the initial seed to random numbers
np.random.seed(123)
all_walks = []
# Simulate random walk 500 times
for i in range(500):
random_walk = [0]
# at each walk trhow 100 times
for x in range(100):
step = random_walk[-1]
dice = np.random.randint(1, 7)
# to go down once
if dice <= 2:
step = max(0, step - 1)
# to go up once
elif dice <= 5:
step = step + 1
# to go up ramdomly
else:
step = step + np.random.randint(1, 7)
# chances to fallin down to zero
if np.random.rand() <= 0.001:
step = 0
random_walk.append(step)
# all the simulated walks
all_walks.append(random_walk)
# Create and plot all walks
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()
# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]
# Plot histogram of ends, display plot
plt.clf()
plt.hist(ends)
plt.show()
# probability to be at least at 60th floor
num_60_floor = len(ends[ends >= 60])
probability_60_or_greater = (num_60_floor / len(ends)) * 100
print(probability_60_or_greater)
|
64fea56b6c0e81f643e2d490f0ecf709482305d0 | babilonio/CodingGame | /twoegg.py | 507 | 3.953125 | 4 |
#A building has N floors. One of the floors is the highest floor an egg can be dropped from without breaking.
#If an egg is dropped from above that floor, it will break. If it is dropped from that floor or below, it will be completely undamaged and you can drop the egg again.
#You are given two identical eggs, find the minimal number of drops it will take in the worst case to find out the highest floor from which an egg will not break.
n = int(input())
r=0
d=1
while n>=d:
r+=1
d+=r
print(r)
|
42e019ddb2d388374706174ff0c46456accd2380 | gabriellaec/desoft-analise-exercicios | /backup/user_344/ch48_2019_04_05_01_39_10_703847.py | 251 | 3.59375 | 4 | mes=['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro']
n=[1,2,3,4,5,6,7,8,9,10,11,12]
a=input('Qual numero mes? ')
i=0
while i<len(n):
if mes[i]==n[i]:
print(n[i])
i+=1
|
6018f7656cdbd52c7decec68a02cba4f50fa2508 | ootz0rz/tinkering-and-hacking | /2021/LeetCode/AlgoIII/1231 Divide Chocolate v2.py | 3,826 | 3.828125 | 4 | # https://leetcode.com/problems/divide-chocolate/
"""
we want to optimize for the biggest chunk we can make from any slicing
of sweetness into k+1 slices, such that the chunk is also the smallest
from all the other chunks in that current slicing
if k = 0, then there is only 1 slice with min sweetness = sum(sweetness)
if k = 1, and sweetness is evenly divisible, then we know that both
slices should be sum(sweetness)/2 each
generalizing this a bit, if k = n, and sweetness is equally divisible
into n+1 slices, then each slice should be sum(sweetness)/k+1
we also know that the min for any slice is min_sweet = min(sweetness),
which is the smallest/least-sweet any of our slices can be
this gives us our search space [min_sweet, sum(sweetness)/k+1]
we can then binary search through this space... choosing a pivot
such that pivot = (sum(sweetness)/k+1) - (min_sweet) // 2
we then start iterating through sweetness from front to back, creating
accumulating slices in size until they are at least pivot in sweetness
if we are able to make enough slices for k+1 people, we're good...
otherwise this value fails
if it works, we search above until we find the largest value that works
if it doesn't work, we search below
"""
from typing import *
debug = False
MAX_SWEET = 2**31-1
class Solution:
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
num_peeps = k + 1
min_sweet = min(sweetness)
max_sweet = sum(sweetness) // num_peeps
return _maximizeSweetness(sweetness, num_peeps, min_sweet, max_sweet)[1]
def _maximizeSweetness(sweetness: List[int], num_peeps: int, min_sweet: int, max_sweet: int) -> List[int]:
global debug
if min_sweet > max_sweet:
return [-1, -1]
sweetness_target = min_sweet + (max_sweet - min_sweet) // 2
# get chunks
idx = 0
num_chunks = 0
cur_chunk_val = 0
smallest_chunk = MAX_SWEET
while idx < len(sweetness):
cur_sweet = sweetness[idx]
cur_chunk_val = cur_chunk_val + cur_sweet
if cur_chunk_val >= sweetness_target:
if cur_chunk_val <= smallest_chunk:
smallest_chunk = cur_chunk_val
num_chunks = num_chunks + 1
cur_chunk_val = 0
idx = idx + 1
# do we have enough chunks?
if num_chunks < num_peeps:
if min_sweet == max_sweet:
# we don't...but nothing left to search either
return [num_chunks, smallest_chunk]
# check left side to see if we can get things working
left = _maximizeSweetness(sweetness, num_peeps, min_sweet, sweetness_target-1)
if left[0] >= num_peeps:
return left
else:
return [num_chunks, smallest_chunk]
if num_chunks >= num_peeps:
# we have at least as many chunks as peeps
# we need to check the right hand side and see if there's another better value
right = _maximizeSweetness(sweetness, num_peeps, sweetness_target+1, max_sweet)
if right[0] >= num_peeps:
return right
else:
return [num_chunks, smallest_chunk]
if __name__ == '__main__':
debug = True
s = Solution()
# r = s.maximizeSweetness([1, 2, 3], 0)
# print(f'{r} == {sum([1, 2, 3])}')
# r = s.maximizeSweetness([1, 2, 2, 1, 2, 2, 1, 2, 2], 2)
# assert r == 5
# r = s.maximizeSweetness([5,6,7,8,9,1,2,3,4], 8)
# print(f'{r} == {1}')
r = s.maximizeSweetness([1,2,3,4,5,6,7,8,9], 5)
assert r == 6
r = s.maximizeSweetness([87506,32090,9852,96263,52415,67669,10703,27,98672,48664], 1)
assert r == 225735
# r = _get_chunks([1, 2, 2, 1, 2, 2, 1, 2, 2], 6)
# print(f'num_peeps={2+1} num: {r[0]} smallest: {r[1]}')
# r = s.maximizeSweetness([1, 2, 2, 1, 2, 2, 1, 2, 2], 2)
# print(f'{r}')
|
01239082b1edd108cd72e351a9be7a6c85090422 | yaodeshiluo/python_cookbook | /1_12.py | 677 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 序列中出现次数最多的元素
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
words_counter = Counter(words)
top_three = words_counter.most_common(3)
print top_three
print words_counter['eyes'] # Counter对象就是一个字典
# print words_counter
more_words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes']
words_counter.update(more_words)
print words_counter
|
fffa1e7215495b0189420275b56c2abbc60803e4 | eduardoquerido/turtle_graphics | /desenhos/spectral_harmonograph/spectrahamonograph.py | 27,491 | 3.796875 | 4 | # ------------------ First section: import statements -----------------
import math
import random
import turtle
from tkinter import *
# ------------------ Second section: global variables -----------------
firstWindow = None
secondWindow = None
errorWindow = None
# ------------------ Third section: function definitions --------------
# ------------------ GUI functions-------------------------------------
def nextProgram():
global Next
global xentry
global yentry
global xPens
global yPens
global firstWindow
xPens = int(xentry.get())
yPens = int(yentry.get())
if 0 <= xPens <= 3 and 0 <= yPens <= 3:
firstWindow.destroy()
secondGUI()
else:
firstWindow.destroy()
errorGUI()
def firstGUI():
global quit
global Next
global xentry
global yentry
global firstWindow
firstWindow = Tk()
firstWindow.title("Welcome to the Turtle Harmonograph")
firstWindow.config(bg="RosyBrown")
label = Label(firstWindow)
label["text"] = "Welcome to the Turtle Harmonograph Generator!"
label["bg"] = "RosyBrown"
label["fg"] = "LightYellow"
label["relief"] = GROOVE
label["padx"] = 10
label["pady"] = 5
label.grid(row=0, column=0)
priminstr = Label(firstWindow)
priminstr["bg"] = "RosyBrown"
priminstr["fg"] = "LightYellow"
priminstr[
"text"
] = """This program will create a harmonograph
based on your preferences. Let's get started!
How many pendulums would you like?
Pick 1, 2, or 3 for both the x and y
directions and then press Next to proceed."""
priminstr["justify"] = CENTER
priminstr["relief"] = SUNKEN
priminstr["pady"] = 5
priminstr["padx"] = 15
priminstr.grid(row=1, column=0)
# entryframe
entryframe = Frame(firstWindow)
entryframe["bg"] = "RosyBrown"
entryframe.grid(row=2, column=0)
# x pendulums label
xlabel = Label(entryframe)
xlabel["bg"] = "RosyBrown"
xlabel["fg"] = "LightYellow"
xlabel["text"] = "# of X-axis Pendulums:"
xlabel["justify"] = LEFT
xlabel.grid(row=0, column=0)
# x pendulums entry
xentry = Entry(entryframe)
xentry["bg"] = "LightYellow"
xentry["fg"] = "RosyBrown"
xentry["justify"] = LEFT
xentry.grid(row=0, column=1)
# y pendulums label
ylabel = Label(entryframe)
ylabel["bg"] = "RosyBrown"
ylabel["fg"] = "LightYellow"
ylabel["text"] = "# of Y-axis Pendulums:"
ylabel["justify"] = LEFT
ylabel.grid(row=1, column=0)
# y pendulums entry
yentry = Entry(entryframe)
yentry["bg"] = "LightYellow"
yentry["fg"] = "RosyBrown"
yentry["justify"] = LEFT
yentry.grid(row=1, column=1)
# Next button
Next = Button(entryframe)
Next["bg"] = "LightYellow"
Next["fg"] = "RosyBrown"
Next["text"] = "Next"
Next["relief"] = RAISED
Next["command"] = nextProgram
Next.grid(row=2, column=0)
# Quit button
quit = Button(entryframe)
quit["bg"] = "LightYellow"
quit["fg"] = "RosyBrown"
quit["text"] = "Quit"
quit["relief"] = RAISED
quit["command"] = quitProgram
quit.grid(row=2, column=1)
firstWindow.mainloop()
def quitProgram():
global quit
global firstWindow
firstWindow.destroy()
def errorGUI():
global errorButt
global errorWindow
errorWindow = Tk()
errorWindow.title("Error!")
errorWindow.config(bg="RosyBrown")
errorLabel = Label(errorWindow)
errorLabel["bg"] = "LightYellow"
errorLabel["fg"] = "RosyBrown"
errorLabel["relief"] = SUNKEN
errorLabel["text"] = "Error! variable(s) out of range. Press Quit and run again!"
errorLabel.grid(row=0, column=0)
errorButt = Button(errorWindow)
errorButt["text"] = "Quit"
errorButt["command"] = errorQuit
errorButt.grid(row=1, column=0)
errorWindow.mainloop()
def errorQuit():
global errorButt
global errorWindow
errorWindow.destroy()
def Quit2():
global quit2
global secondWindow
secondWindow.destroy()
def runProgram():
global secondWindow
global xPens
global yPens
global run
global freqEntryx1
global freqEntryx2
global freqEntryx3
global ampEntryx1
global ampEntryx2
global ampEntryx3
global phaseEntryx1
global phaseEntryx2
global phaseEntryx3
global freqEntryy1
global freqEntryy2
global freqEntryy3
global ampEntryy1
global ampEntryy2
global ampEntryy3
global phaseEntryy1
global phaseEntryy2
global phaseEntryy3
global f1
global f2
global f3
global f4
global f5
global f6
global a1
global a2
global a3
global a4
global a5
global a6
global p1
global p2
global p3
global p4
global p5
global p6
if xPens == 1:
f1 = int(freqEntryx1.get())
a1 = int(ampEntryx1.get())
p1 = int(phaseEntryx1.get())
if xPens == 2:
f1 = int(freqEntryx1.get())
a1 = int(ampEntryx1.get())
p1 = int(phaseEntryx1.get())
f2 = int(freqEntryx2.get())
a2 = int(freqEntryx2.get())
p2 = int(phaseEntryx2.get())
if xPens == 3:
f1 = int(freqEntryx1.get())
a1 = int(ampEntryx1.get())
p1 = int(phaseEntryx1.get())
f2 = int(freqEntryx2.get())
a2 = int(ampEntryx2.get())
p2 = int(phaseEntryx2.get())
f3 = int(freqEntryx3.get())
a3 = int(ampEntryx3.get())
p3 = int(phaseEntryx3.get())
if yPens == 1:
f4 = int(freqEntryy1.get())
a4 = int(ampEntryy1.get())
p4 = int(phaseEntryy1.get())
if yPens == 2:
f4 = int(freqEntryy1.get())
a4 = int(ampEntryy1.get())
p4 = int(phaseEntryy1.get())
f5 = int(freqEntryy2.get())
a5 = int(ampEntryy2.get())
p5 = int(phaseEntryy2.get())
if yPens == 3:
f4 = int(freqEntryy1.get())
a4 = int(ampEntryy1.get())
p4 = int(phaseEntryy1.get())
f5 = int(freqEntryy2.get())
a5 = int(ampEntryy2.get())
p5 = int(phaseEntryy2.get())
f6 = int(freqEntryy3.get())
a6 = int(ampEntryy3.get())
p6 = int(phaseEntryy3.get())
secondWindow.destroy()
def Randomize():
global secondWindow
global randomize
global xPens
global yPens
global f1
global f2
global f3
global f4
global f5
global f6
global a1
global a2
global a3
global a4
global a5
global a6
global p1
global p2
global p3
global p4
global p5
global p6
if xPens == 1:
f1 = random.randrange(0, 10)
a1 = random.randrange(0, 250)
p1 = random.randrange(0, 2 * 3)
if xPens == 2:
f1 = random.randrange(0, 10)
a1 = random.randrange(0, 250)
p1 = random.randrange(0, 2 * 3)
f2 = random.randrange(0, 10)
a2 = random.randrange(0, 250)
p2 = random.randrange(0, 2 * 3)
if xPens == 3:
f1 = random.randrange(0, 10)
a1 = random.randrange(0, 250)
p1 = random.randrange(0, 2 * 3)
f2 = random.randrange(0, 10)
a2 = random.randrange(0, 250)
p2 = random.randrange(0, 2 * 3)
f3 = random.randrange(0, 10)
a3 = random.randrange(0, 250)
p3 = random.randrange(0, 2 * 3)
if yPens == 1:
f4 = random.randrange(0, 10)
a4 = random.randrange(0, 250)
p4 = random.randrange(0, 2 * 3)
if yPens == 2:
f4 = random.randrange(0, 10)
a4 = random.randrange(0, 250)
p4 = random.randrange(0, 2 * 3)
f5 = random.randrange(0, 10)
a5 = random.randrange(0, 250)
p5 = random.randrange(0, 2 * 3)
if yPens == 3:
f4 = random.randrange(0, 10)
a4 = random.randrange(0, 250)
p4 = random.randrange(0, 2 * 3)
f5 = random.randrange(0, 10)
a5 = random.randrange(0, 250)
p5 = random.randrange(0, 2 * 3)
f6 = random.randrange(0, 10)
a6 = random.randrange(0, 250)
p6 = random.randrange(0, 6)
secondWindow.destroy()
def secondGUI():
global secondWindow
global xPens
global yPens
global quit2
global run
global randomize
global freqEntryx1
global freqEntryx2
global freqEntryx3
global ampEntryx1
global ampEntryx2
global ampEntryx3
global phaseEntryx1
global phaseEntryx2
global phaseEntryx3
global freqEntryy1
global freqEntryy2
global freqEntryy3
global ampEntryy1
global ampEntryy2
global ampEntryy3
global phaseEntryy1
global phaseEntryy2
global phaseEntryy3
global f2
global f3
global a2
global a3
global p2
global p3
global f5
global f6
global a5
global a6
global p5
global p6
secondWindow = Tk()
secondWindow.title("Pendulum Variables")
secondWindow.config(bg="RosyBrown")
entrydirections = Label(secondWindow)
entrydirections[
"text"
] = """Please enter the desired values
for the Frequency, Amplitudes, and
Phases of the Pendulums, or press
randomize to generate random values!
Ranges:
1<Frequency<10
0<Amplitude<300 (sum of x or y values cannot exceed 500)
0<Phases<2*pi"""
entrydirections["bg"] = "RosyBrown"
entrydirections["fg"] = "LightYellow"
entrydirections["relief"] = GROOVE
entrydirections["justify"] = CENTER
entrydirections.grid(row=0, column=0)
ventry = Frame(secondWindow)
ventry["bg"] = "RosyBrown"
ventry.grid(row=1, column=0)
if xPens == 1:
# label
freqLabelx1 = Label(ventry)
freqLabelx1["text"] = "Fequency for x-axis Pendulum 1:"
freqLabelx1["bg"] = "RosyBrown"
freqLabelx1["fg"] = "LightYellow"
freqLabelx1.grid(row=0, column=0)
# entry
freqEntryx1 = Entry(ventry)
freqEntryx1["bg"] = "LightYellow"
freqEntryx1["fg"] = "RosyBrown"
freqEntryx1.grid(row=0, column=1)
# lbel
ampLabelx1 = Label(ventry)
ampLabelx1["text"] = "Amplitude:"
ampLabelx1["bg"] = "RosyBrown"
ampLabelx1["fg"] = "LightYellow"
ampLabelx1.grid(row=0, column=2)
# entry
ampEntryx1 = Entry(ventry)
ampEntryx1["bg"] = "LightYellow"
ampEntryx1["fg"] = "RosyBrown"
ampEntryx1.grid(row=0, column=3)
# label
phaseLabelx1 = Label(ventry)
phaseLabelx1["text"] = "Phases:"
phaseLabelx1["bg"] = "RosyBrown"
phaseLabelx1["fg"] = "LightYellow"
phaseLabelx1.grid(row=0, column=4)
# entry
phaseEntryx1 = Entry(ventry)
phaseEntryx1["bg"] = "LightYellow"
phaseEntryx1["fg"] = "RosyBrown"
phaseEntryx1.grid(row=0, column=5)
f2 = 0
f3 = 0
a2 = 0
a3 = 0
p2 = 0
p3 = 0
if xPens == 2:
# label
freqLabelx1 = Label(ventry)
freqLabelx1["text"] = "Fequency for x-axis Pendulum 1:"
freqLabelx1["bg"] = "RosyBrown"
freqLabelx1["fg"] = "LightYellow"
freqLabelx1.grid(row=0, column=0)
# entry
freqEntryx1 = Entry(ventry)
freqEntryx1["bg"] = "LightYellow"
freqEntryx1["fg"] = "RosyBrown"
freqEntryx1.grid(row=0, column=1)
# lbel
ampLabelx1 = Label(ventry)
ampLabelx1["text"] = "Amplitude:"
ampLabelx1["bg"] = "RosyBrown"
ampLabelx1["fg"] = "LightYellow"
ampLabelx1.grid(row=0, column=2)
# entry
ampEntryx1 = Entry(ventry)
ampEntryx1["bg"] = "LightYellow"
ampEntryx1["fg"] = "RosyBrown"
ampEntryx1.grid(row=0, column=3)
# label
phaseLabelx1 = Label(ventry)
phaseLabelx1["text"] = "Phases:"
phaseLabelx1["bg"] = "RosyBrown"
phaseLabelx1["fg"] = "LightYellow"
phaseLabelx1.grid(row=0, column=4)
# entry
phaseEntryx1 = Entry(ventry)
phaseEntryx1["bg"] = "LightYellow"
phaseEntryx1["fg"] = "RosyBrown"
phaseEntryx1.grid(row=0, column=5)
# label
freqLabelx2 = Label(ventry)
freqLabelx2["text"] = "Fequency for x-axis Pendulum 2:"
freqLabelx2["bg"] = "RosyBrown"
freqLabelx2["fg"] = "LightYellow"
freqLabelx2.grid(row=1, column=0)
# entry
freqEntryx2 = Entry(ventry)
freqEntryx2["bg"] = "LightYellow"
freqEntryx2["fg"] = "RosyBrown"
freqEntryx2.grid(row=1, column=1)
# lbel
ampLabelx2 = Label(ventry)
ampLabelx2["text"] = "Amplitude:"
ampLabelx2["bg"] = "RosyBrown"
ampLabelx2["fg"] = "LightYellow"
ampLabelx2.grid(row=1, column=2)
# entry
ampEntryx2 = Entry(ventry)
ampEntryx2["bg"] = "LightYellow"
ampEntryx2["fg"] = "RosyBrown"
ampEntryx2.grid(row=1, column=3)
# label
phaseLabelx2 = Label(ventry)
phaseLabelx2["text"] = "Phases:"
phaseLabelx2["bg"] = "RosyBrown"
phaseLabelx2["fg"] = "LightYellow"
phaseLabelx2.grid(row=1, column=4)
# entry
phaseEntryx2 = Entry(ventry)
phaseEntryx2["bg"] = "LightYellow"
phaseEntryx2["fg"] = "RosyBrown"
phaseEntryx2.grid(row=1, column=5)
f3 = 0
a3 = 0
p3 = 0
if xPens == 3:
# label
freqLabelx1 = Label(ventry)
freqLabelx1["text"] = "Fequency for x-axis Pendulum 1:"
freqLabelx1["bg"] = "RosyBrown"
freqLabelx1["fg"] = "LightYellow"
freqLabelx1.grid(row=0, column=0)
# entry
freqEntryx1 = Entry(ventry)
freqEntryx1["bg"] = "LightYellow"
freqEntryx1["fg"] = "RosyBrown"
freqEntryx1.grid(row=0, column=1)
# lbel
ampLabelx1 = Label(ventry)
ampLabelx1["text"] = "Amplitude:"
ampLabelx1["bg"] = "RosyBrown"
ampLabelx1["fg"] = "LightYellow"
ampLabelx1.grid(row=0, column=2)
# entry
ampEntryx1 = Entry(ventry)
ampEntryx1["bg"] = "LightYellow"
ampEntryx1["fg"] = "RosyBrown"
ampEntryx1.grid(row=0, column=3)
# label
phaseLabelx1 = Label(ventry)
phaseLabelx1["text"] = "Phases:"
phaseLabelx1["bg"] = "RosyBrown"
phaseLabelx1["fg"] = "LightYellow"
phaseLabelx1.grid(row=0, column=4)
# entry
phaseEntryx1 = Entry(ventry)
phaseEntryx1["bg"] = "LightYellow"
phaseEntryx1["fg"] = "RosyBrown"
phaseEntryx1.grid(row=0, column=5)
# label
freqLabelx2 = Label(ventry)
freqLabelx2["text"] = "Fequency for x-axis Pendulum 2:"
freqLabelx2["bg"] = "RosyBrown"
freqLabelx2["fg"] = "LightYellow"
freqLabelx2.grid(row=1, column=0)
# entry
freqEntryx2 = Entry(ventry)
freqEntryx2["bg"] = "LightYellow"
freqEntryx2["fg"] = "RosyBrown"
freqEntryx2.grid(row=1, column=1)
# lbel
ampLabelx2 = Label(ventry)
ampLabelx2["text"] = "Amplitude:"
ampLabelx2["bg"] = "RosyBrown"
ampLabelx2["fg"] = "LightYellow"
ampLabelx2.grid(row=1, column=2)
# entry
ampEntryx2 = Entry(ventry)
ampEntryx2["bg"] = "LightYellow"
ampEntryx2["fg"] = "RosyBrown"
ampEntryx2.grid(row=1, column=3)
# label
phaseLabelx2 = Label(ventry)
phaseLabelx2["text"] = "Phases:"
phaseLabelx2["bg"] = "RosyBrown"
phaseLabelx2["fg"] = "LightYellow"
phaseLabelx2.grid(row=1, column=4)
# entry
phaseEntryx2 = Entry(ventry)
phaseEntryx2["bg"] = "LightYellow"
phaseEntryx2["fg"] = "RosyBrown"
phaseEntryx2.grid(row=1, column=5)
# label
freqLabelx3 = Label(ventry)
freqLabelx3["text"] = "Fequency for x-axis Pendulum 3:"
freqLabelx3["bg"] = "RosyBrown"
freqLabelx3["fg"] = "LightYellow"
freqLabelx3.grid(row=2, column=0)
# entry
freqEntryx3 = Entry(ventry)
freqEntryx3["bg"] = "LightYellow"
freqEntryx3["fg"] = "RosyBrown"
freqEntryx3.grid(row=2, column=1)
# lbel
ampLabelx3 = Label(ventry)
ampLabelx3["text"] = "Amplitude:"
ampLabelx3["bg"] = "RosyBrown"
ampLabelx3["fg"] = "LightYellow"
ampLabelx3.grid(row=2, column=2)
# entry
ampEntryx3 = Entry(ventry)
ampEntryx3["bg"] = "LightYellow"
ampEntryx3["fg"] = "RosyBrown"
ampEntryx3.grid(row=2, column=3)
# label
phaseLabelx3 = Label(ventry)
phaseLabelx3["text"] = "Phases:"
phaseLabelx3["bg"] = "RosyBrown"
phaseLabelx3["fg"] = "LightYellow"
phaseLabelx3.grid(row=2, column=4)
# entry
phaseEntryx3 = Entry(ventry)
phaseEntryx3["bg"] = "LightYellow"
phaseEntryx3["fg"] = "RosyBrown"
phaseEntryx3.grid(row=2, column=5)
# ypens
if yPens == 1:
# label
freqLabely1 = Label(ventry)
freqLabely1["text"] = "Fequency for y-axis Pendulum 1:"
freqLabely1["bg"] = "RosyBrown"
freqLabely1["fg"] = "LightYellow"
freqLabely1.grid(row=xPens, column=0)
# entry
freqEntryy1 = Entry(ventry)
freqEntryy1["bg"] = "LightYellow"
freqEntryy1["fg"] = "RosyBrown"
freqEntryy1.grid(row=xPens, column=1)
# lbel
ampLabely1 = Label(ventry)
ampLabely1["text"] = "Amplitude:"
ampLabely1["bg"] = "RosyBrown"
ampLabely1["fg"] = "LightYellow"
ampLabely1.grid(row=xPens, column=2)
# entry
ampEntryy1 = Entry(ventry)
ampEntryy1["bg"] = "LightYellow"
ampEntryy1["fg"] = "RosyBrown"
ampEntryy1.grid(row=xPens, column=3)
# label
phaseLabely1 = Label(ventry)
phaseLabely1["text"] = "Phases:"
phaseLabely1["bg"] = "RosyBrown"
phaseLabely1["fg"] = "LightYellow"
phaseLabely1.grid(row=xPens, column=4)
# entry
phaseEntryy1 = Entry(ventry)
phaseEntryy1["bg"] = "LightYellow"
phaseEntryy1["fg"] = "RosyBrown"
phaseEntryy1.grid(row=xPens, column=5)
f5 = 0
f6 = 0
a5 = 0
a6 = 0
p5 = 0
p6 = 0
if yPens == 2:
# label
freqLabely1 = Label(ventry)
freqLabely1["text"] = "Fequency for y-axis Pendulum 1:"
freqLabely1["bg"] = "RosyBrown"
freqLabely1["fg"] = "LightYellow"
freqLabely1.grid(row=xPens, column=0)
# entry
freqEntryy1 = Entry(ventry)
freqEntryy1["bg"] = "LightYellow"
freqEntryy1["fg"] = "RosyBrown"
freqEntryy1.grid(row=xPens, column=1)
# lbel
ampLabely1 = Label(ventry)
ampLabely1["bg"] = "RosyBrown"
ampLabely1["fg"] = "LightYellow"
ampLabely1["text"] = "Amplitude:"
ampLabely1.grid(row=xPens, column=2)
# entry
ampEntryy1 = Entry(ventry)
ampEntryy1["bg"] = "LightYellow"
ampEntryy1["fg"] = "RosyBrown"
ampEntryy1.grid(row=xPens, column=3)
# label
phaseLabely1 = Label(ventry)
phaseLabely1["bg"] = "RosyBrown"
phaseLabely1["fg"] = "LightYellow"
phaseLabely1["text"] = "Phases:"
phaseLabely1.grid(row=xPens, column=4)
# entry
phaseEntryy1 = Entry(ventry)
phaseEntryy1["bg"] = "LightYellow"
phaseEntryy1["fg"] = "RosyBrown"
phaseEntryy1.grid(row=xPens, column=5)
# label
freqLabely2 = Label(ventry)
freqLabely2["text"] = "Fequency for y-axis Pendulum 2:"
freqLabely2["bg"] = "RosyBrown"
freqLabely2["fg"] = "LightYellow"
freqLabely2.grid(row=xPens + 1, column=0)
# entry
freqEntryy2 = Entry(ventry)
freqEntryy2["bg"] = "LightYellow"
freqEntryy2["fg"] = "RosyBrown"
freqEntryy2.grid(row=xPens + 1, column=1)
# lbel
ampLabely2 = Label(ventry)
ampLabely2["text"] = "Amplitude:"
ampLabely2["bg"] = "RosyBrown"
ampLabely2["fg"] = "LightYellow"
ampLabely2.grid(row=xPens + 1, column=2)
# entry
ampEntryy2 = Entry(ventry)
ampEntryy2["bg"] = "LightYellow"
ampEntryy2["fg"] = "RosyBrown"
ampEntryy2.grid(row=xPens + 1, column=3)
# label
phaseLabely2 = Label(ventry)
phaseLabely2["text"] = "Phases:"
phaseLabely2["bg"] = "RosyBrown"
phaseLabely2["fg"] = "LightYellow"
phaseLabely2.grid(row=xPens + 1, column=4)
# entry
phaseEntryy2 = Entry(ventry)
phaseEntryy2["bg"] = "LightYellow"
phaseEntryy2["fg"] = "RosyBrown"
phaseEntryy2.grid(row=xPens + 1, column=5)
f6 = 0
a6 = 0
p6 = 0
if yPens == 3:
# label
freqLabely1 = Label(ventry)
freqLabely1["text"] = "Fequency for y-axis Pendulum 1:"
freqLabely1["bg"] = "RosyBrown"
freqLabely1["fg"] = "LightYellow"
freqLabely1.grid(row=xPens, column=0)
# entry
freqEntryy1 = Entry(ventry)
freqEntryy1["bg"] = "LightYellow"
freqEntryy1["fg"] = "RosyBrown"
freqEntryy1.grid(row=xPens, column=1)
# lbel
ampLabely1 = Label(ventry)
ampLabely1["text"] = "Amplitude:"
ampLabely1["bg"] = "RosyBrown"
ampLabely1["fg"] = "LightYellow"
ampLabely1.grid(row=xPens, column=2)
# entry
ampEntryy1 = Entry(ventry)
ampEntryy1["bg"] = "LightYellow"
ampEntryy1["fg"] = "RosyBrown"
ampEntryy1.grid(row=xPens, column=3)
# label
phaseLabely1 = Label(ventry)
phaseLabely1["text"] = "Phases:"
phaseLabely1["bg"] = "RosyBrown"
phaseLabely1["fg"] = "LightYellow"
phaseLabely1.grid(row=xPens, column=4)
# entry
phaseEntryy1 = Entry(ventry)
phaseEntryy1["bg"] = "LightYellow"
phaseEntryy1["fg"] = "RosyBrown"
phaseEntryy1.grid(row=xPens, column=5)
# label
freqLabely2 = Label(ventry)
freqLabely2["text"] = "Fequency for y-axis Pendulum 2:"
freqLabely2["bg"] = "RosyBrown"
freqLabely2["fg"] = "LightYellow"
freqLabely2.grid(row=xPens + 1, column=0)
# entry
freqEntryy2 = Entry(ventry)
freqEntryy2["bg"] = "LightYellow"
freqEntryy2["fg"] = "RosyBrown"
freqEntryy2.grid(row=xPens + 1, column=1)
# lbel
ampLabely2 = Label(ventry)
ampLabely2["text"] = "Amplitude:"
ampLabely2["bg"] = "RosyBrown"
ampLabely2["fg"] = "LightYellow"
ampLabely2.grid(row=xPens + 1, column=2)
# entry
ampEntryy2 = Entry(ventry)
ampEntryy2["bg"] = "LightYellow"
ampEntryy2["fg"] = "RosyBrown"
ampEntryy2.grid(row=xPens + 1, column=3)
# label
phaseLabely2 = Label(ventry)
phaseLabely2["text"] = "Phases:"
phaseLabely2["bg"] = "RosyBrown"
phaseLabely2["fg"] = "LightYellow"
phaseLabely2.grid(row=xPens + 1, column=4)
# entry
phaseEntryy2 = Entry(ventry)
phaseEntryy2["bg"] = "LightYellow"
phaseEntryy2["fg"] = "RosyBrown"
phaseEntryy2.grid(row=xPens + 1, column=5)
# label
freqLabely3 = Label(ventry)
freqLabely3["text"] = "Fequency for y-axis Pendulum 3:"
freqLabely3["bg"] = "RosyBrown"
freqLabely3["fg"] = "LightYellow"
freqLabely3.grid(row=xPens + 2, column=0)
# entry
freqEntryy3 = Entry(ventry)
freqEntryy3["bg"] = "LightYellow"
freqEntryy3["fg"] = "RosyBrown"
freqEntryy3.grid(row=xPens + 2, column=1)
# lbel
ampLabely3 = Label(ventry)
ampLabely3["text"] = "Amplitude:"
ampLabely3["bg"] = "RosyBrown"
ampLabely3["fg"] = "LightYellow"
ampLabely3.grid(row=xPens + 2, column=2)
# entry
ampEntryy3 = Entry(ventry)
ampEntryy3["bg"] = "LightYellow"
ampEntryy3["fg"] = "RosyBrown"
ampEntryy3.grid(row=xPens + 2, column=3)
# label
phaseLabely3 = Label(ventry)
phaseLabely3["text"] = "Phases:"
phaseLabely3["bg"] = "RosyBrown"
phaseLabely3["fg"] = "LightYellow"
phaseLabely3.grid(row=xPens + 2, column=4)
# entry
phaseEntryy3 = Entry(ventry)
phaseEntryy3["bg"] = "LightYellow"
phaseEntryy3["fg"] = "RosyBrown"
phaseEntryy3.grid(row=xPens + 2, column=5)
# buttons
run = Button(ventry)
run["text"] = "Run!"
run["command"] = runProgram
run.grid(row=xPens + yPens, column=0)
randomize = Button(ventry)
randomize["text"] = "Randomize!"
randomize["command"] = Randomize
randomize.grid(row=xPens + yPens, column=2)
quit2 = Button(ventry)
quit2["text"] = "Quit"
quit2["command"] = Quit2
quit2.grid(row=xPens + yPens, column=5)
secondWindow.mainloop()
# ------------------ Fourth section: script elements ------------------
firstGUI()
def harmonograph(
f1, p1, a1, f2, p2, a2, f3, p3, a3, f4, p4, a4, f5, p5, a5, f6, p6, a6
):
wn = turtle.Screen()
wn.bgcolor("darkcyan")
ronald = turtle.Turtle()
ronald.color("goldenrod")
ronald.speed(10)
def Pendulum1(t):
return a1 * math.sin(f1 * float(t / 30) + p1) * math.exp(-0.01 * float(t / 30))
def Pendulum2(t):
return a2 * math.sin(f2 * float(t / 30) + p2) * math.exp(-0.01 * float(t / 30))
def Pendulum3(t):
return a3 * math.sin(f3 * float(t / 30) + p3) * math.exp(-0.01 * float(t / 30))
def Pendulum4(t):
return a4 * math.sin(f4 * float(t / 30) + p4) * math.exp(-0.01 * float(t / 30))
def Pendulum5(t):
return a5 * math.sin(f5 * float(t / 30) + p5) * math.exp(-0.01 * float(t / 30))
def Pendulum6(t):
return a6 * math.sin(f6 * float(t / 30) + p6) * math.exp(-0.01 * float(t / 30))
ronald.up()
ronald.goto(
Pendulum1(0) + Pendulum2(0) + Pendulum3(0),
Pendulum4(0) + Pendulum5(0) + Pendulum6(0),
)
ronald.down()
print(
"Pendulum 1 has a frequency "
+ str(f1)
+ ", a phase "
+ str(p1)
+ ", and an amplitude "
+ str(a1)
)
print(
"Pendulum 2 has a frequency "
+ str(f2)
+ ", a phase "
+ str(p2)
+ ", and an amplitude "
+ str(a2)
)
print(
"Pendulum 3 has a frequency "
+ str(f3)
+ ", a phase "
+ str(p3)
+ ", and an amplitude "
+ str(a3)
)
print(
"Pendulum 4 has a frequency "
+ str(f4)
+ ", a phase "
+ str(p4)
+ ", and an amplitude "
+ str(a4)
)
print(
"Pendulum 5 has a frequency "
+ str(f5)
+ ", a phase "
+ str(p5)
+ ", and an amplitude "
+ str(a5)
)
print(
"Pendulum 6 has a frequency "
+ str(f6)
+ ", a phase "
+ str(p6)
+ ", and an amplitude "
+ str(a6)
)
for t in range(10000):
targetX = Pendulum1(t) + Pendulum2(t) + Pendulum3(t)
targetY = Pendulum4(t) + Pendulum5(t) + Pendulum6(t)
ronald.goto(targetX, targetY)
harmonograph(f1, p1, a1, f2, p2, a2, f3, p3, a3, f4, p4, a4, f5, p5, a5, f6, p6, a6)
# GUIMain()
|
aa6882d3278ceb70c485c83266786dda9bf572df | karsevar/Crash_Course_Python- | /CCpython_ch9_part2.py | 9,597 | 4.40625 | 4 | ##Modifying an attribute's value through a method:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""print a statement showing the car's mileage."""
print("this car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""set the odometer reading to the given value."""
self.odometer_reading = mileage
my_new_car = Car("audi", "a4",2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()
#Setting the odometer to a specified value. Or rather keeping the odometer
#from being rolled back.
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""print a statement showing the car's mileage."""
print("this car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer.")
my_new_car = Car("subaru","wrx sti", 2003)
my_new_car.update_odometer(26000)
my_new_car.read_odometer()
#OK now let's try to roll back the odometer of the defined
#Subaru car.
my_new_car.update_odometer(12000)#It actually worked!!!
##Incrementing an attribute's value through a method:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""print a statement showing the car's mileage."""
print("this car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""set the odometer reading to the given value."""
self.odometer_reading = mileage
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_used_car = Car("subaru","outback",2013)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23000)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
##Inheritance:
#Using the Car class from earlier as the parent class for the ElectricCar class.
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
super().__init__(make, model, year)
my_tesla = ElectricCar("tesla","model s", 2016)
print(my_tesla.get_descriptive_name())
##Defining Attributes and methods for the child class:
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
my_tesla = ElectricCar("tesla","model s", 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
##Overriding methods from the parent class:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""print a statement showing the car's mileage."""
print("this car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""set the odometer reading to the given value."""
self.odometer_reading = mileage
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
def fill_gas_tank(self):
"""prints gas tank is being filled"""
print("gas tank is being filled!!!")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
def fill_gas_tank(self):
"""Electronic cars don't have a gas tank."""
print("This car doesn't need a gas tank")#this overrides the
#fill_gas_tank method within the parent class Car.
my_tesla = ElectricCar("tesla","model s", 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()#The parent method has been overwritten.
my_old_car = Car("toyota","mr2","1987")
print(my_old_car.get_descriptive_name())
my_old_car.fill_gas_tank()#The fill_gas_tank() method remains the same
#for objects called by the Car() parent class.
##Instances and attributes:
class Battery():
"""A simple attempt to model a battery for an electric car"""
def __init__(self, battery_size=70):
"""Initialize batter attribute."""
self.battery_size = battery_size
def describe_battery(self):
"""print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar("tesla","model s",2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
##Expanding on the Battery class:
class Battery():
"""A simple attempt to model a battery for an electric car"""
def __init__(self, battery_size=70):
"""Initialize batter attribute."""
self.battery_size = battery_size
def describe_battery(self):
"""print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
def get_range(self):
"""print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "this car can go approximately " + str(range)
message += " mils on a full charge."
print(message)
my_tesla = ElectricCar("tesla","model s",2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
##Importing classes:
##Importing a single class:
#module has been creates that stores a copy of the Car class. This class has
#been renamed Car2 as to descrease confusion.
from car import Car2
my_new_car = Car2("audi","a4",2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
##Storing multiple classes in a module:
#from car import ElectricCar2
#my_tesla = ElectricCar2("tesla","model s", 2016)
#print(my_tesla.get_descriptive_name())
#my_tesla.battery.describe_battery()
#my_tesla.battery.get_range()
##importing multiple classes from a module:
#from car import Car2
my_beetle = Car("volkswagen","beetle",2016)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar("tesla","roadster",2016)
print(my_tesla.get_descriptive_name())
##Importing an entire module:
#import car
#my_beetle = car.Car("volkswage","beetle",2016)
#print(my_beetle.get_descriptive_name())
#my_tesla = car.ElectricCar2("tesla","roadster",2016)
#rint(my_tesla.get_descriptive_name())
##Importing a module into a module:
#Creating a electriccar and battery module and removing the ElectricCar2
#and Battery2 classes from the car module.
from car import Car2
from electric_car import ElectricCar2
my_beetle = Car2("volkswage","beetle",2016)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar("tesla","roadster",2016)
print(my_tesla.get_descriptive_name())
##the python standard library:
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages["jen"] = "python"
favorite_languages["sarah"] = "c"
favorite_languages["edward"] = "ruby"
favorite_languages["phil"] = "python"
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
|
99b92b8bd2b42df98e09a722f64ab12bb18bb44b | AIGW/1807 | /02.04day/02-保护对象属性.py | 297 | 3.546875 | 4 | class Dog():
def __init__(self):
self.__age = 0 #私有方法
def sleep(self):
print('sleep')
def setAge(self,age):
if age > 15 or age < 1:
print("年龄不符合")
else:
self.__age = age
def getAge(self):
return self.__age
hsq = Dog()
hsq.setAge(10)
print(hsq.getAge())
|
36dd370370d89bdfe80ff50d51c1b29a5669d2d3 | pierreforstmann/mpc | /pg_update.py | 1,481 | 3.53125 | 4 | #
# pg_update.py
#
# Python code to update PG table
#
# $ python3 pg_update.py
#
# Copyright Pierre Forstmann 2023
#------------------------------------------------------------------------------------------------
import psycopg2
import argparse
import pg_connect
def update_item(p_item: int, p_price: float, p_brand: str):
conn = pg_connect.connection
cur = conn.cursor()
try:
cur.execute("""
SELECT item
FROM public.items
WHERE item = %s
""", [p_item])
ret = cur.fetchone();
if (ret == None):
print("Error: item ", p_item, " not found")
return False
cur.execute("""
UPDATE public.items
SET price=%s, brand = %s
WHERE item = %s
""", (p_price, p_brand, p_item))
conn.commit()
cur.close()
except (Exception, psycopg2.Error) as error:
print("Error in UPDATE", error)
return False
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--item", required=True, help="""item number""")
parser.add_argument("-p", "--price", required=True, help="""item price""")
parser.add_argument("-b", "--brand", required=True, help="""brand name""")
update_item(
parser.parse_args().item,
parser.parse_args().price,
parser.parse_args().brand)
|
8df7a6b7614b597594982392c5f6937cfcca3768 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3986/codes/1592_1800.py | 156 | 3.6875 | 4 | a=int(input("valor de a: "))
b=int(input("valor de b: "))
c=int(input("valor de c: "))
l= ((a ** 2)+ (b ** 2) + (c ** 2)) / (a + b + c)
print(round(l, 7))
|
6754cbe7918fe67883ea2e86029a29bc6af7a14d | henriquebraga/katas | /katas/fizzbuzz.py | 658 | 3.828125 | 4 | # not multiple: return own number
#multiple of 3: return fizz
#multiple of 5: return buzz
from functools import partial
multiple_of = lambda base, num : num % base == 0
multiple_of_3 = partial(multiple_of, 3)
multiple_of_5 = partial(multiple_of, 5)
def robot(pos):
say = str(pos)
if multiple_of_3(pos):
say = 'fizz'
if multiple_of_5(pos):
say = 'buzz'
if multiple_of_3(pos) and multiple_of_5(pos):
say = 'fizzbuzz'
return say
#Tests
assert all(robot(pos) == 'fizz' for pos in (3, 6, 9))
assert all(robot(pos) == 'buzz' for pos in (5, 10, 20))
assert all(robot(pos) == 'fizzbuzz' for pos in (15, 30, 45))
|
d7e57caa33a190d0146e89ded586bf2b8245e6b6 | CNikiforuk/CS3130 | /ass1/main.py | 1,566 | 4.125 | 4 | #!/usr/bin/env python3
import sys
import db
################--Description--#################
#Basic employee database example main run file.
################-----Author-----#################
#Carlos Nikiforuk
ID, FIRST, LAST, DEPT = range(4) #FIELD defines, 0-4
MAXNAMESIZE = 11 #Max name size, for first and last.
def main():
if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:
print("usage: {0} <db file>".format(sys.argv[0]))
exit()
infile = sys.argv[1] #check usage
try: #check specified file, prompt for creation
open(infile,'r')
except FileNotFoundError:
print("Input file does not exist.")
ans = input("Would you like to create it as a new database? (y/n)? ")
if(ans == 'y'):
open(infile, 'x')
else:
exit()
except Exception as e:
print("Error: ",e)
db1 = db.database(infile) #instantiate database class
cont = True
while(cont):
choice = db.displayMenu()
if (choice == '1'): #add employee
db1.addEmployee()
elif(choice == '2'): #search for employee
db1.findEmployee()
elif(choice == '3'): #remove employee
db1.removeEmployee()
elif(choice == '4'): #show employees
db1.showEmployees()
elif(choice == '5'): #quit
cont = False
if(choice != '5'):
input("\nPress enter to continue...")
main()
|
1be45e0e94498939c1dafe1d91eae8354ea4411b | derek-damron/tictactoe | /tictactoe/tictactoeboard.py | 4,584 | 3.828125 | 4 | from copy import copy
class tictactoeboard:
"""Current board stored as a dictionary with the following keys:
```
11 | 12 | 13
------------
21 | 22 | 23
------------
31 | 32 | 33
```
Where the shorthand is:
- First number is the row starting at the top
- Second number is the column starting at the left
Possible values are:
- `' '`: No piece
- `'X'`: X-side piece
- `'O'`: O-side piece
"""
def __init__(self):
self.board = {'11': ' ',
'12': ' ',
'13': ' ',
'21': ' ',
'22': ' ',
'23': ' ',
'31': ' ',
'32': ' ',
'33': ' '}
self.current_move = 'X'
self.previous_move = None
self.history = []
self.outcome = None
def __str__(self):
return ' %s | %s | %s \n-----------\n %s | %s | %s \n-----------\n %s | %s | %s ' % (self.board['11'],
self.board['12'],
self.board['13'],
self.board['21'],
self.board['22'],
self.board['23'],
self.board['31'],
self.board['32'],
self.board['33'])
def move(self, position):
if self.outcome is not None:
raise ValueError('Board is finished')
if position not in self.board.keys():
raise ValueError('Invalid position')
if self.board[position] != ' ':
raise ValueError('Piece already at that position')
self.board[position] = self.current_move
self.history.append(copy(self.board))
if self.is_win():
self.outcome = self.current_move + ' ' + 'win'
elif not self.are_moves_left():
self.outcome = 'Draw'
self.switch_sides()
def available_moves(self):
return [k for (k,v) in self.board.items() if v == ' ']
def are_moves_left(self):
if len(self.available_moves()) > 0:
return True
else:
return False
def is_win(self):
# Row win conditions
if self.board['11'] != ' ' and \
self.board['11'] == self.board['12'] and \
self.board['11'] == self.board['13']:
return True
if self.board['21'] != ' ' and \
self.board['21'] == self.board['22'] and \
self.board['21'] == self.board['23']:
return True
if self.board['31'] != ' ' and \
self.board['31'] == self.board['32'] and \
self.board['31'] == self.board['33']:
return True
# Column win conditions
if self.board['11'] != ' ' and \
self.board['11'] == self.board['21'] and \
self.board['11'] == self.board['31']:
return True
if self.board['12'] != ' ' and \
self.board['12'] == self.board['22'] and \
self.board['12'] == self.board['32']:
return True
if self.board['13'] != ' ' and \
self.board['13'] == self.board['23'] and \
self.board['13'] == self.board['33']:
return True
# Diagonal win conditions
if self.board['11'] != ' ' and \
self.board['11'] == self.board['22'] and \
self.board['11'] == self.board['33']:
return True
if self.board['13'] != ' ' and \
self.board['13'] == self.board['22'] and \
self.board['13'] == self.board['31']:
return True
# No win conditions
return False
def switch_sides(self):
if self.current_move == 'X':
self.previous_move = 'X'
self.current_move = 'O'
else:
self.previous_move = 'O'
self.current_move = 'X' |
e7d526fb9a88fcbb22ca7d1f22b8a4871b0b4a75 | liusu042/gbase_tools | /del_utf8_to_fixed_len_gbk/check_length_for_lines.py | 676 | 3.875 | 4 | #!/usr/bin/env python
# encoding:utf8
# @FileName: check_length_for_lines.py
# @Author: liulizeng@gbase.cn
# @CreateDate: 2017-12-03
# @Description: check length of each line.
import sys
def check_length_for_lines(filename):
result = {}
with open(filename) as f:
for line in f:
lineLength = len(line.rstrip('\n'))
result[lineLength] = result.get(lineLength, 0) + 1
return result
if __name__ == "__main__":
if len(sys.argv) < 2:
print "usage: python %s filename" % sys.argv[0]
sys.exit(1)
result = check_length_for_lines(sys.argv[1])
for k in result:
print "length of %d lines is %d." % (result[k], k)
|
725acc81315e8fb43ec4ebf5b569b044f7e4bf4d | Programwithurwashi/calculator | /calculator.py | 886 | 4.1875 | 4 | def addition(first,second):
return first+second
def Substraction(first,second):
return first-second
def Multiplication(first,second):
return first*second
def division(first,second):
return first/second
print('''Enter the operation to be performed:
1> Addition
2> Subtraction
3> Multiplication
4> Division''')
first = float(input("Enter first number: "))
second = float(input("Enter second number: "))
choice=input("Enter the Operator")
if choice == '+':
print(first, "+", second, "=", addition(first,second))
elif choice == '-':
print(first, "-", second, "=", Substraction(first,second))
elif choice == '*':
print(first, "*", second, "=", Multiplication(first,second))
elif choice == '/':
print(first, "/", second, "=", division(first,second))
else:
print("Invalid Input") |
ff18af7b701d78c27f64b7cbabae36e06928bd11 | sbsreedh/Design-1 | /minStack.py | 1,641 | 3.78125 | 4 | #Time Complexity : pop:O(1), top:O(1) , push:O(1), getMin: O(1)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode :Yes
# Any problem you faced while coding this :In calculating space and time complexity, I am not sure about the complexities I have mentioned above
# Your code here along with comments explaining your approach
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack=list() #initialize stack using list
def push(self, x: int) -> None:
#obtain element with minimum value
minVal=self.getMin()
#check if the minimum value exits and the number to be pushed on stack is lesser than the minimum value obtained.
if minVal is None or x< minVal:
minVal=x# if x is lesser then min value, we update the min value
self.stack.append((x,minVal))# appens the list with the min value at index 1.
def pop(self) -> None:
if len(self.stack) !=0:#check if the stack is non empty
self.stack.pop()#pop the element present at top of the stack
def top(self) -> int:
return self.stack[-1][0]# return the top most element in the stack
def getMin(self) -> int:
if len(self.stack) !=0:
return self.stack[-1][1]# return the element in index 1 as it conatins min value as we push min value to the index 1 in a tuple
else:
return None
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
111abfac7d6c3e7a8d7edefe80277d27a7cdbda3 | alihaiderrizvi/Leetcode-Practice | /all/48-Rotate Image/solution.py | 517 | 3.625 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
lst = []
for z in matrix:
lst.append([])
for i in range(len(matrix)-1,-1,-1):
for j in range(len(matrix)):
lst[j].append(matrix[i][j])
for u in range(len(lst)):
for v in range(len(lst)):
matrix[u][v] = lst[u][v]
|
37a835ffcd86af6d674ebacb81b5d3dc768f0f2c | poob/RealPython | /Chapter 7/Assignment solutions/remove_files.py | 667 | 3.671875 | 4 | # 7.2 remove_files.py
# Remove JPG files from multiple folders based on file size
import os
path = "C:/Real Python/Course materials/Chapter 7/Practice files/little pics"
for currentFolder, subfolders, fileNames in os.walk(path):
for fileName in fileNames:
fullPath = os.path.join(currentFolder, fileName)
# check if file is a JPG
checkJPG = fileName.lower().endswith(".jpg")
# check if size is less than 2Kb
checkSize = os.path.getsize(fullPath) < 2000
if checkJPG and checkSize: # both conditions must be True
print 'Deleting "{}"...'.format(fileName)
os.remove(fullPath)
|
343010e27049fa17b6f88df88d8a6727adc84441 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/1282.py | 253 | 4.0625 | 4 | def word_count(passage):
'''
Counts occurrences of each unique word in a phrase.
1 input (string) --> 1 output (dictionary)
'''
words = passage.split()
return {word : words.count(word)
for word in set(words)}
|
ac1b8ccd68d22114100a86530788e86deb7b9558 | sapnashetty123/python-ws | /labquest/q_17.py | 93 | 3.890625 | 4 | inp = input("entr the sen:")
if inp.endswith("y"):
inp=inp.replace("y","ies ")
print(inp) |
b3a9b9517fc34cfe121ff18536ce9f7701eef0b7 | aksh0001/algorithms-journal | /questions/trees_graphs/SortedArrayToBST.py | 2,049 | 4.125 | 4 | """
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never
differ by more than 1.
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
Approach: Binary midpoint insertion approach
@author a.k
"""
from data_structures.trees.utils import pretty_print_tree, TreeNode
from typing import List
def sortedArrayToBST(nums: List[int]) -> TreeNode:
"""
Given a sorted array of numbers, creates a height-balanced tree and returns root of new tree.
:param nums: array of numbers
:return: root of new tree
"""
return insert(nums, 0, len(nums) - 1)
# Binary midpoint insertion routine
def insert(A: List[int], lo: int, hi: int) -> TreeNode:
"""
Inserts elements and returns root of new tree.
@Algorithm: Cannot insert in any sorted, serial order. Must insert in a "shuffled" manner. How?
- Well, think of mid of array as pivot (root). Left of this pivot must be in the left subtree
and the right of the pivot must be in the right subtree.
- Now... we know the left of the pivot must go on the left. But, again, we cannot process the elements
in a serial fashion; therefore, like above, we recursively insert left/right based on the midpoint approach.
:param A: list of numbers
:param lo: lower endpoint interval
:param hi: higher endpoint interval
:Time: O(N)
:Space: O(N)
:return: root of resulting tree
"""
if lo > hi:
return None
mid = (lo + hi) // 2
root = TreeNode(A[mid])
root.left, root.right = insert(A, lo, mid - 1), insert(A, mid + 1, hi)
return root
if __name__ == '__main__':
test1 = [-10, -3, 0, 5, 9]
test2 = [-6, -2, -1, 1, 6, 21, 22]
pretty_print_tree(sortedArrayToBST(test1))
|
c482764ac04193e229e5b450d584b763670a2a42 | MrZhangzhg/nsd_2018 | /nsd1807/python1/day03/mtable.py | 511 | 4.0625 | 4 | # for i in range(3): # [0, 1, 2] 外层循环控制打印哪一行
# for j in range(i + 1): # [0] [0, 1] [0, 1, 2] 内层循环控制行内打印几次
# print('hello', end=' ') # 多个hello打印到同一行
# print() # 每一行结尾需要打印回车,否则就成为一行了
################################
for i in range(1, 10): # [1, 2, 3, 4, 5, 6, 7, 8, 9]
for j in range(1, i + 1): # [1], [1, 2], [1, 2 ,3]
print('%sX%s=%s' % (j, i, i * j), end=' ')
print()
|
f9f084e89606ca8d011ac6cf3e5a0c451f6b229c | elodeepxj/PythonFirstDemo | /test1/Ex4.py | 214 | 3.5625 | 4 | # -*- coding:utf-8 -*-
print map(str,(1,2,3,4))
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax +n
return ax
return sum
f = lazy_sum(1,3,5,7,9)
print f() |
3f40786702b9431fe55778db2971b17dbc92cbb3 | brunv/pyCrashCourse | /09 - Classes/importando_classes.py | 2,184 | 4.0625 | 4 | # Para estar de acordo com a filosofia de Python, quanto menos entulhados
# estiverem seus arquivos, melhor será. Para ajudar, Python permite
# armazenar classes em módulos e então importar classes em seu programa
# principal.
# É uma boa prática incluir um docstring no nível de módulo que descreve
# rapidamente o conteúdo desse módulo. Portanto, escreva uma docstring
# para cada módulo que criar.
#
# Importando uma única classe:
#
from car import Car
my_new_car = Car('audi', 'r8', 2017)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 230
my_new_car.read_odometer()
# Podemos armazenar tantas classes quantas forem necessárias em um único
# módulo, embora cada classe deva estar, de algum modo, relacionada com
# outra classe. Exemplo: automobile.py
from automobile import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
#
# Importando várias classes de um mesmo módulo:
#
from automobile import Car, ElectricCar
my_beetle = Car('volkswagen', 'beetle', 2015)
print(my_beetle.get_descriptive_name())
my_old_tesla = ElectricCar('tesla', 'roadster', 2015)
print(my_old_tesla.get_descriptive_name())
#
# Importando um módulo completo:
#
import automobile
my_porsche = automobile.Car('porsche', '911', 2001)
print(my_porsche.get_descriptive_name())
my_bmw = automobile.ElectricCar('bmw', 'i3', 2019)
print(my_bmw.get_descriptive_name())
# Importando todas as classes de um módulo: 'from nome_módulo import * '
# Essa abordagem não é recomendada por dois motivos: não fica claro quais
# as classes do módulo que estão sendo usadas; pode resultar em confusão
# com nomes presentes no arquivo.
# Se precisar importar muitras classes de um módulo, é melhor importar o
# módulo todo e usar a sintaxe nome_do_módulo.nome_da_classe. Você não
# verá todas as classes usadas no início do arquivo, mas verá claramente
# em que lugares o módulo é utilizado no programa. |
8939d0981234c6f0630482dcc8d17e361262e566 | mrshahalam/New-Python-programme | /instagrame.py | 1,988 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
# Defining the scrapeInstagram() with the soup1 as the argument
def scrapeInstagram(soup1):
# Creating empty list called insta_Data for saving the scrapped results
insta_Data = []
# Looping through the <meta> tags with attribute propety as og:description
for meta in soup1.find_all(name="meta", attrs={"property": "og:description"}):
# Fetching and splitting the value stored in content attribute of meta tag
# and saving them in insta_Data List
insta_Data = meta['content'].split()
# When the above line is executed insta_Data[] will be as follows
# ['No. of Followers (For e.g. 50K)', 'Followers,', 'No. of Following (For e.g. 100)', 'Following,',
# 'No. of Posts (For e.g. 150)', 'Posts', '-', .........]
# Fetching the required results (Followers, Following, Posts) as per the indices
# and storing them in respective variables
followers = insta_Data[0]
following = insta_Data[2]
posts = insta_Data[4]
# Printing the results
print("\nINSTAGRAM USERNAME : ", insta_User)
print("\nNo OF POSTS : ", posts)
print("\nNo OF FOLLOWERS : ", followers)
print("\nNo OF FOLLOWING : ", following)
# Driver Code
if __name__ == '__main__':
# Prompting the user to enter the INSTAGRAM USERNAME
insta_User = input("\nENTER INSTAGRAM USERNAME : ")
# Storing the complete URL with user-input INSTAGRAM USERNAME
insta_URL = "https://www.instagram.com/" + insta_User
# Sending request to the above URL and storing the response in insta_Page
insta_Page = requests.get(insta_URL)
# Specifying the desired format of the insta_Page using html.parser
# html.parser allows Python to read the components of the insta_Page rather
# than treating it as a string
soup = BeautifulSoup(insta_Page.text, "html.parser")
# Calling the scrapeInstagram() with soup as the argument
scrapeInstagram(soup)
|
8ff9cb6587e1f5b0f142f963a45fe5e920da9d43 | michael86/Python-Projects | /hangman/functions.py | 2,812 | 3.96875 | 4 | class HmFunctions:
def show_length(self, word): # This returns the length of the word as under scores _ _ _
length = ""
for letter in range(0, len(word)):
length += '_ '
return length
# This checks that the user input doesn't contain a number
def check_for_digits(self, word):
return any(word.isdigit() for char in word)
# This checks if the letter is in the word.
def check_letters(self, word, letter):
return letter in word
# This checks the new guess and sends back a new dict
def update_correct_letters(self, letter, word):
placements = {}
for i in range(0, len(word)):
if word[i] == letter:
placements[i] = letter
return placements
# This returns a new string with the correct letters: C _ R _
def update_readable_length(self, letters, word):
updated_word = ''
updated = False
for i in range(0, len(word)):
for k, v in letters.items():
if k == i:
updated_word += v + ' '
updated = not updated
if not updated:
updated_word += '_ '
else:
updated = not updated
return updated_word
# This checks to see if the word is complete.
def check_win(self, letters, _word):
word = self.update_readable_length(letters, _word)
if '_' in word:
return False
else:
return True
def announce_win(self):
# this block can be converted to a function not DRY
print('WINNER!!!!!')
play_again = input('Do you want to play again: ')
if 'y' not in play_again.lower():
return False
else:
return True
def show_help(self, guess, correct_letters, word, counter, guessed_letters):
# Convert this block to function, just cause messy..
if guess.lower() == 'quit':
print('quitting')
return True
elif guess.lower() == 'view':
print(self.update_readable_length(correct_letters, word))
elif guess.lower() == 'help':
print('Quit: quit ')
print('View: view the correct letters so far.')
print('Count: view your total number of guesses so far.')
print('Letters: Show all the letters you\'ve tried so far.')
elif guess.lower() == 'count':
print(f'So far you\'ve had {counter} guesses.')
elif guess.lower() == 'letters':
letters = ''
for i in range(len(guessed_letters)):
letters += guessed_letters[i] + ' '
print(f'Your guessed letters so far are: {letters}')
else:
print('Ermmmm you drunk? 😁')
|
ade0f65774d105c56f0b2306189084482acea8c0 | SakuraSa/MyLeetcodeSubmissions | /Symmetric Tree/Accepted-13463407.py | 1,616 | 4.125 | 4 | #Author : sakura_kyon@hotmail.com
#Question : Symmetric Tree
#Link : https://oj.leetcode.com/problems/symmetric-tree/
#Language : python
#Status : Accepted
#Run Time : 240 ms
#Description:
#Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#For example, this binary tree is symmetric:
#```
# 1
# / \
# 2 2
# / \ / \
#3 4 4 3
#```
#But the following is not:
#```
# 1
# / \
# 2 2
# \ \
# 3 3
#```
####Note:###
#Bonus points if you could solve it both recursively and iteratively.
#confused what `"{1,#,2,3}"` means? [> read more on how binary tree is serialized on OJ.](#)
####OJ's Binary Tree Serialization:###
#The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
#Here's an example:
#```
# 1
# / \
# 2 3
# /
# 4
# \
# 5
#```
#The above binary tree is serialized as `"{1,2,3,#,#,4,#,#,5}"`.
#Show Tags
#TreeDepth-first Search
#Code :
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root, other=None):
other = other or root
if other == root == None:
return True
if (not root) or (not other):
return False
if root.val != other.val:
return False
return self.isSymmetric(root.left, other.right) and self.isSymmetric(root.right, other.left)
|
9e2320a54316116768af7f8212a9d6fd334ca13a | Impact-coder/CodeChef | /First and Last Digit (FLOW004).py | 177 | 3.578125 | 4 | # cook your dish here
N = int(input())
for i in range (0,N):
x = input()
x = list(x)
first, last = int(x[0]),int(x[len(x)-1])
print(first + last)
|
220135567db04ce33ea20daa37e19585310fc2d7 | shahidshabir055/python_programs | /personClass.py | 678 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 11:20:12 2020
@author: eshah
"""
class person():
def __init__(self,name,age,height,grade):
self.name=name
self.age=age
self.height=height
self.grade=grade
def isEligible(self):
if(self.grade>7.5):
return True
else:
return False
#shahid=person("shahid",21,6.2,7.8)
class student(person):
def __init__(self,name,age,height,grade,rollno):
super(student,self).__init__(name,age,height,grade)
self.rollno=rollno
syed=student("shahid",45,6.4,7.9,"17bcs055")
print(syed.__dict__)
print(syed.isEligible())
|
4ee22cd1bc61688846aacf3a62780a48659fae24 | HCDigitalScholarship/FastBridge | /FastBridgeApp/text.py | 6,167 | 3.734375 | 4 | class Text(object):
"""A Text object for storing all the data and getting sections nicely"""
def __init__(self, name : str, sections : dict, words : list, section_linkedlist : dict, subsections : int, language : str, local_def: bool = False, local_lem: bool = False):
self.name = name
self.sections = sections
self.words = words
self.section_linkedlist = section_linkedlist
self.subsections = subsections
self.language = language
self.local_def = local_def
self.local_lem = local_lem
def get_section(self, range_start, range_end):
"""
Converts the human section citation of 1-3 sections to the keys of the section dictionary, and retrives the indices for self.words that the sections correspond to.
"""
print(range_start, "start")
print(range_end, "end")
if range_start == "start":
internal_range_start = range_start
elif range_start.count(".") == 0 and self.subsections == 1:
#for things with one level and 1 level is expected
internal_range_start = range_start
elif range_start.count(".") == 0 and self.subsections == 2:
#for things with one level and 2 level was expected
internal_range_start = range_start + ".1"
elif range_start.count(".") == 0 and self.subsections == 3:
#for things with one level and 3 level was expected
internal_range_start = range_start + ".1.1"
elif range_start.count(".") == 1 and self.subsections == 2:
print("start of depth 2, as expected")
#for things with two levels, and two were given
internal_range_start = range_start
print(internal_range_start)
elif range_start.count(".") == 1 and self.subsections == 3:
#for things with three levels, and two were given
internal_range_start = range_start + ".1"
elif range_start.count(".") == 2 and self.subsections == 3:
internal_range_start = range_start
if range_end == "end" or range_end == "start":
internal_range_end = range_end
elif range_end.count(".") == 0 and self.subsections == 1:
#for input with one level and 1 level is expected
internal_range_end = range_end
elif range_end.count(".") == 0 and self.subsections == 2:
#for input with one level and 2 level was expected
try:
internal_range_end = self.section_linkedlist[next_section(range_end) + ".1"]
#this should make a search for 1.1 - 1 become a search for 1.1 - 2.1(previous section). If the section has a letter (ie, 2b), this will convert it to 2c. If 2c does not exist, it will fail and go below
except Exception as e:
to_increment = range_end[:-1] #remove the letter
self.section_linkedlist[next_section(to_increment) + ".1"]
elif range_end.count(".") == 0 and self.subsections == 3:
#for things with one level and 3 level was expected
try:
internal_range_end = self.section_linkedlist[next_section(range_end) + ".1.1"]
except Exception as e:
to_increment = range_end[:-1] #remove the letter
self.section_linkedlist[next_section(to_increment) + ".1.1"]
elif range_end.count(".") == 1 and self.subsections == 2:
print("end of depth 2, as expected")
#for things with two levels, and two were given
internal_range_end = range_end
print(internal_range_end)
elif range_end.count(".") == 1 and self.subsections == 3:
#for things with three levels, and two were given
range_end = range_end.split(".")
try:
internal_range_end = self.section_linkedlist[".".join(range_end[0], next_section(range_end[1]), ".1")]
except Exception as e:
internal_range_end = self.section_linkedlist[".".join(range_end[0], next_section(range_end[1][:-1]), ".1")]
elif range_end.count(".") == 2 and self.subsections == 3:
internal_range_end = range_end
#start ends up being the end of the previous section + 1
#print(internal_range_start, " starting place")
#print(internal_range_end, " ending place")
#print(self.sections[self.section_linkedlist[internal_range_start]] +1)
#print(self.sections[internal_range_end] +1)
#print((self.sections[self.section_linkedlist[internal_range_start]] + 1, (self.sections[internal_range_end]+1)))
print(self.sections[internal_range_end]) #should be the end list index
print(self.section_linkedlist[internal_range_start])
return (self.sections[self.section_linkedlist[internal_range_start]] + 1, (self.sections[internal_range_end]+1))
def get_words(self, user_start, user_end):
"""
Convienent wrapper method. Gets the correct sublist of TITLES, based on user's selection.
"""
#text will usually be a text class that is our target text, for this early demo/figuring things out phase we will not use one, it is hardcoded to Ovid Met 1.
#really: Text.text_list(), a method to return the text list if present and error other wise
start, end = self.get_section(user_start, user_end)
#print(start, end)
tmp = self.words
if end == -1:
end = len(tmp)
wordlist = [tmp[i] + (self.name,) for i in range(start, end)] #adds the source text
return wordlist
def next_section(section):
"""Handles the case where a section has letters in it. This should only be used in the cases where: input with one level and 2 level was expected and with one level and 3 level was expected """
working_section = section.split(".") #so 1.1 = [1, 1], 2b.1 = [2b, 1], and 2b = [2b]
try:
target = str(int(working_section[0]) + 1)
except ValueError: #invalid conversion
target = f"{working_section[0][:-1]}{chr(ord(working_section[0][-1]) + 1)}"
return target
|
22c4878fc6031610778981d89d0b24ac4aa38a62 | suacalis/VeriBilimiPython | /Ornek16_3.py | 360 | 3.671875 | 4 | '''
Örnek 16.3: Girilen iki sayının toplamını yapan programda eğer kullanıcı sayı
haricinde bir karakter girer ise program, hata mesajı yerine 'sayı giriniz!'
uyarısı vermelidir.
'''
def topla(a,b):
try:
return(a + b)
except: #bir hata olursa
print ("sayı giriniz!")
#Ana program
print (topla(5, 3))
print (topla(5, 'a')) |
da3949bcf3ba4f32cdb92ab24764f71d96634c44 | vinceajcs/all-things-python | /algorithms/dp/knapsack01.py | 1,761 | 4.15625 | 4 | def naive(weights, values, capacity, n):
"""Given a list of weights and values of n items to be placed in a knapsack,
determine the max value of items in the knapsack given its capacity.
"""
if n == 0 or capacity == 0:
return 0
# weight of nth item is > capacity, thus item cannot be included
if weights[n - 1] > capacity:
return naive(weights, values, capacity, n - 1)
else:
# case 1: include current item in the knapsack, then find max value given capacity - weight of current item
include = values[n - 1] + naive(weights, values, capacity - weights[n - 1], n - 1)
# case 2: exlcude current item from the knapsack, find max value given remaining items
exclude = naive(weights, values, capacity, n - 1)
# find max of two cases
return max(include, exclude)
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
n = len(weights)
# max value should be 220 (items with values of 100 and 120, weights 20 and 30, respectively)
print(naive(weights, values, capacity, n))
# DP solution
def knapsack(weights, values, W):
"""Given a list of weights and values of n items to be placed in a knapsack,
determine the max value of items in the knapsack given its capacity W.
"""
n = len(weights)
dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)]
# bottom up
for i in range(n + 1):
for w in range(W + 1):
if weights[i - 1] <= w:
include = values[i - 1] + dp[i - 1][w - weights[i - 1]]
exclude = dp[i - 1][w]
dp[i][w] = max(include, exclude)
else:
dp[i][w] = dp[i - 1][w]
return dp[-1][-1]
print(knapsack(weights, values, capacity))
|
4970ca102bc967e7f3d6e3ea98ec71daa8bba5e5 | GabrielSalazar29/Exercicios_em_python_udemy | /Exercicios Seção 07 parte 1/ex016.py | 943 | 4 | 4 | """
Faça um programa que leia um vetor de 5 posições para números reais e, depois, um
código inteiro. Se o código for zero, finalize o programa; se for 1, mostre o vetor na ordem
direta; se for 2, mostre o vetor na ordem inversa. Caso, o código for diferente de 1 e 2
escreva uma mensagem informando que o código é inválido.
"""
vetor = []
for c in range(5):
vetor.append(float(input(f"Digite o numero da posição {c}: ")))
while True:
print("=" * 20)
op = int(input("Digite 0 para sair.\n"
"Digite 1 para mostrar o vetor na ordem direta.\n"
"Digite 2 para mostrar o vetor na ordem inversa.\n"
"OPÇÃO: "))
print("=" * 20)
if op == 0:
print("Encerrando...")
break
elif op == 1:
vetor.sort()
print(vetor)
elif op == 2:
vetor.reverse()
print(vetor)
else:
print("O código é inválido")
|
60c272a4e6aeb1fbd4d3b1379ba15e0605c120d5 | jbischof/algo_practice | /epi3/queues.py | 1,804 | 3.9375 | 4 | """Queue problems."""
from collections import deque
class QueueWithMax(object):
"""Queue class with fast access to max.
Brute force: Scan the collection every time max() method is called.
Time: O(N), Space: O(1)
q = [4, 8, 5, 2, 7, 2, 1, 4]
This queue has max of 8. However, once first two elements popped, max will
revert to 7. Alternatively, higher value could be added to right.
Idea: Maintain a parallel BST with all the data in the deque. Then when
values are pushed or popped they can also be removed from the BST. In this
case max operation reduces to log(N) time, but push and pop are increased
to log(N) time.
Idea: Element with a greater value to the right can never be returned as the
max. Therefore could maintain a parallel queue of max values that could be
pushed and popped as well. For example, in the existing queue only [8, 7, 4]
could ever be the max. If 8 were popped, then this also could be popped
from max queue to yield 7. If 11 were added to the queue, all elements could
be removed and 11 added. Note that this list must always be decreasing.
Note: I am using a list implementation for simplicity, but this does incur
O(N) pops.
Max operation:
Time: O(1), Space: O(N)
"""
def __init__(self):
self.queue = []
self.max_queue = []
def push(self, x):
self.queue.append(x)
while self.max_queue and self.max_queue[-1] < x:
self.max_queue.pop()
self.max_queue.append(x)
def extend(self, x):
for k in x:
self.push(k)
def pop(self):
if self.queue[0] == self.max_queue[0]:
self.max_queue.pop(0)
return self.queue.pop(0)
def max(self):
return self.max_queue[0]
|
69ce87a46294d44d789c7a5725b9cb3d80ef4cfe | DanielKenji/personal | /trash/ReajusteSalarial.py | 307 | 3.578125 | 4 | salario = float(input("Digite seu salário "))
print("Digite a porcentagem do seu aumento. Por exemplo, para 20% de aumento, ")
aumento = float(input("Digite 20, sem o sinal de porcentagem. "))
reajuste = (aumento*salario)/100
print("seu salário era R$",salario,"e passa a ser R$",salario+reajuste)
input() |
f009d8455cdd977561c7bc147d86b28b7a404297 | Jerome-Celle/BricaBrac | /tri.py | 526 | 3.671875 | 4 | fichierInput = input('Le nom du fichier à trier?\n')
delimiteur = input('Le delimiteur de fin de fonction?\n')
ofiInput = open(fichierInput, 'r')
ofiOutput = open('fichierOutput.txt', 'w')
tableauFonction= []
text = ofiInput.read()
ofiInput.close()
fonction = ""
for y in range(len(text)):
fonction = fonction + text[y]
if text[y:y+9] == "// change" or (y+1)==len(text):
tableauFonction.append(fonction)
fonction =""
tableauFonction.sort()
for fonction in tableauFonction:
ofiOutput.write(fonction)
ofiOutput.close() |
8f8b384e7c68a4294f1b27bb62448e1d1bc35bf9 | piotrbartnik/pythonCodewars | /16.py | 200 | 3.890625 | 4 | # returns position of capital letter
def capitals(word):
i = 0
result = []
while i < len(word):
if word[i].isupper():
result.append(i)
i += 1
return result
capitals('CodEWaRs') |
aae219d377dd4579932250cca41a0b0a6a871458 | lingyun666/algorithms-tutorial | /lintcode/Tree/IsBalanced/balancedTree.py | 1,557 | 3.875 | 4 | # coding: utf8
'''
LintCode:http://www.lintcode.com/zh-cn/problem/balanced-binary-tree/
93. 平衡二叉树
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
'''
# 这题跟求最大二叉树的深度类似, 采用递归的方式求树的深度, 终止条件可以加入一个判断, 如果在递归当中发现了左右子树的高度差超过了 1, 可以返回 -1
# 这样在后续的递归就可以不用再继续判断. 已经有了 -1 就已经知道这棵树不平衡
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
return self.maxDepth(root) != -1
def maxDepth(self, node):
if node == None:
return 0
left_depth = self.maxDepth(node.left)
right_depth = self.maxDepth(node.right)
if left_depth == -1 or right_depth == -1 or abs(left_depth - right_depth) > 1:
return -1
return max(left_depth, right_depth) + 1 |
cc2b45d9f65126dfa2b773e6757c95b0b5ed3c49 | cheriesyb/cp1404practicals | /prac_02/files.py | 268 | 3.953125 | 4 |
# 1
output_file = open("name.txt", 'w')
user_name = input("What is your name?")
print(user_name, file=output_file)
output_file.close()
# 2
input_file = open("name.txt", 'r')
user_name = input_file.read().strip()
print("Your name is", user_name)
input_file.close()
|
1394dd1e015c63371f61da6f4a07db2c5a4f56c3 | what-name/misc-python | /WeatherGetter/WeatherGetter.py | 333 | 3.75 | 4 | # Load API Key from APIKey file
apiKeyFile = open("APIKey")
apiKey = apiKeyFile.read()
# Ask for city's name
print("Which city do you want the weather for?")
city = input()
# FIXME validate that input is a string
def getWeather(city):
# FIXME make API call
print("Nice and shiny weather we have today in", city)
getWeather(city) |
9ef86ae54fdc9532893f6bd085937ae5479c3308 | animeshchittora/D-Straverse | /Web_crawler.py | 1,322 | 3.703125 | 4 | #!/usr/bin/env python
import requests
print("Welcome to Web crawler")
print("press 1 for subdomains traversal 2 for directory traversal")
number = input("Enter your choice : ")
if(number==1):
def request(url):
try:
return requests.get("http://"+url)
except requests.exceptions.ConnectionError:
pass
target_url = raw_input("Enter your URL: ----> ")
with open("/home/ani/Downloads/subdomains-wodlist.txt","r") as wordlist_file: #Subdomain_list-Path
for line in wordlist_file:
word = line.strip()
test_url = word+"."+target_url
response = request(test_url)
if response:
print("[+] Discovered Domains ---->> "+test_url)
elif(number==2):
def request(url):
try:
return requests.get("http://"+url)
except requests.exceptions.ConnectionError:
pass
target_url = raw_input("Enter your URL: ----> ")
with open("/home/ani/Downloads/files-and-dirs-wordlist.txt","r") as wordlist_file: #Directory_list-path
for line in wordlist_file:
word = line.strip()
test_url = target_url+"/"+word
response = request(test_url)
if response:
print("[+] Discovered Domains ---->> "+test_url)
|
2ae892d03e1850e78c8cc6fdbc161b6008477e7b | Sapnavishnoi/KBC-game | /kbc/kbc.py | 3,676 | 3.890625 | 4 | print("*************************************************************************************************")
print("welcometo my KBC game")
print("**************************************************************************************************")
money =[1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1250000,2500000,5000000,10000000]
#function to print the money
def win_money(correct_answer):
print(money[correct_answer-1])
if money[correct_answer-1]==10000:
print("Congrats!you completed first level.")
elif money[correct_answer-1]==320000:
print("Congrats! you completed second level.")
elif money[correct_answer-1]==10000000:
print("Congrats!!!!!you win 1 croer rupyee.")
def start():
#Questions which is going to ask
question=[
"who is the first person to reach mount everest?",
"who is the first person to reach north pole?",
"who is the first person to reach south pole?",
"which is the religion of the world?",
"which is the first country to print book?",
"which is the first country to issue paper currency?",
"which is the first country to commence competitive examination in civil services?",
"who is the first president of the U.S.A?",
"who is the first prime minister of Britain?",
"who is the Governor General of the United Nations?",
"The author of Business @ speed of Thought is?",
"who among the following is the author of the book india Remembered?"
"who among the following wrote the poem subh-e-Azadi?",
"who wrote Devdas?",
"who said 'Man is a political animal ?",
]
# Options for questions are?
first_option=[
"Shepra Tensing,Edmund Hillary","Robert Peary",
"Amundsen","Hinduism",
"china","china",
"china","George Washington","George Washington",
"Trigveli(Norway)","Dick Fransis",
"jk Rowling","Sahir Ludhiyavi",
"bibbutibhushan Bandopadhyay","Socrates",
]
second_option=[
"Rajesh sharma","Rahesh sharma",
"Rajesh sharma","Muslim",
"India","India",
"India","Robert Walpole","Robert walpole",
"Robert Walpole","john Gray","Robert Dallek",
"Faiz Ahmed Faiz","saratchandra chattopadhyay","plato",
]
third_option=[
"charles hillary","charles hillary",
"charles hillary","sikh",
"USA","USA",
"USA","Henry Waterloo","Henry Waterloo",
"Henry Waterloo","Bill Gates","Pamela Mountbatten",
"Muhammad Iqbal","Kalidasa","Dante",
]
fourth_option=[
"Johan don","Johan don",
"Johan don","Christian",
"UK","UK",
"UK", "George Bush", "George Bush","George Bush",
"David Baldexi","Stephen HawKING",
"Maulana abul kalam", "surdas",
"Aristotle",
]
all_option=[
first_option,second_option,
third_option,fourth_option
]
#iterate till you don't get wrong answer
wrong_answer=False
#counting to know on which level the user
correct_answer=0
#List for keeping record of answers of above question
ans_key=[0,0,0,0,0,0,0,0,1,0,2,2,1,1,3,2]
#Game start
while(wrong_answer!=True):
#variable used for question from list
stage=0
#prints the question from the list
print("Q."+question[stage])
#print options
for Number,option in enumerate(all_option):
print (str(Number+1)+". "+option[stage])
#Take input of the user
answer=int(input("Please ,tell your answer "))
key = (ans_key[stage]+1)
#check ,the answer is correct or not
if key == answer:
print("Congrats!your answer is right: Rs", end="")
correct_answer+=1
win_money(correct_answer)
else:
print("Sadly...your answer is wrong")
correct_answer=0
wrong_answer=True
#check it is the last level or not
if(correct_answer==15):
break
stage+=1
start() |
e532573ac3d7d6a53d71864b8c4fbce2622efc08 | nikhilchoudhari/Pythonex | /py1.py | 284 | 3.875 | 4 | hrs = input("Enter Hours:")
rph = input("Enter rate per hours:")
h = float(hrs)
hh = int(hrs)
r = float(rph)
#rr = float(rph)*1.5
if h <= 40:
print ("The total pay is:", h*r)
else:
#hh = int(hrs)
rr = 0
for i in range (40,hh):
rr += 1.5*r
print ((40*r)+rr) |
c1c6138dc3585c45c120045827fda60bcfa94311 | ahmettkarad/Python_Learning | /Başlangıç/bb.py | 719 | 3.84375 | 4 | musteriAdi = 'ahmet'
musteriSoyadi = 'karadas'
musteriadsoyad = musteriAdi + ' ' + musteriSoyadi
mustericinsiyet = 'erkek'
musterikimlikno = '10000'
musteriyasi = 21
print(musteriadsoyad)
print(mustericinsiyet)
print ( musterikimlikno)
print("ahmet\nkaradaş")
print("Muhammed\t\t\tKaradaş")
print("merhaba Ahmet\'in dünyası")
print("""
Malazgirt Meydan Muharebesi, 26 Ağustos 1071 tarihinde,
Büyük Selçuklu Hükümdarı Alparslan ile Bizans İmparatoru
IV. Romen Diyojen arasında gerçekleşen muharebedir.
Alp Arslan'ın zaferi ile sonuçlanan Malazgirt Muharebesi
""")
a1= 5
a2= 6
a3= 67
a4= "Altındağ Mehmet Akif Ersoy Lisesi"
print(a4)
x1,x2, = 5,50
print(x1)
pi=3.14
print( pi)
print( "pi değeri" + str(pi))
print( "{} pi dğerinin iki katı = {}".format(pi,(pi*2))) |
be9400b863f346a7792309b3175c6b1dd87c4e9d | RomanAleksejevGH/Python | /03112020.py | 5,774 | 3.75 | 4 | import math
def perimetr(): #Roman Aleksejev, 03.11.2020, Задача 2.
print('Вычислить периметр треугольника.')
while True:
try:
a=int(input('Введите сторону "а": '))
b=int(input('Введите сторону "b": '))
c=int(input('Введите сторону "c": '))
print('Периметр треугольника: ',a+b+c)
break
except ValueError:
print('Неверное значение! Рестарт...')
perimetr()
def cenapr(): #Roman Aleksejev, 03.11.2020, Задача 3.
print('Вычислить цену со скидкой.')
while True:
try:
pr=float(input('Введите цену товара: '))
dis=float(input('Введите цену скидки: '))
qa=int(input('Введите количество товара: '))
va=float((pr-pr*(dis/100.0))*qa)
print('Общая стоимость: ',round(va,2))
break
except ValueError:
print('Неверное значение! Рестарт...')
cenapr()
def tips(): #Roman Aleksejev, 03.11.2020, Задача 4.
print('Вычислить на чай с каждого.')
while True:
try:
pr=float(input('Введите цену товара: '))
tip=float(input('Введите % чаевых: '))
qa=int(input('Введите количество друзей: '))
va=float((pr/qa)+(pr*(tip/100.0))/qa)
print('Каждый заплатит: ',round(va,2))
break
except ValueError:
print('Неверное значение! Рестарт...')
tips()
def dist(): #Roman Aleksejev, 03.11.2020, Задача 5.
print('Вычислить дистанцию.')
while True:
try:
pr=float(input('Введите скорость: '))
tip=float(input('Введите время в минутах: '))
va=float(pr*(tip/60))
print('Дистанция: ',round(va,2))
break
except ValueError:
print('Неверное значение! Рестарт...')
dist()
def gip(): #Roman Aleksejev, 03.11.2020, Задача 6.
print('Вычислить гипотенузу треугольника.')
while True:
try:
a=float(input('Введите сторону "а": '))
b=float(input('Введите сторону "b": '))
va=math.hypot(a,b)
print('Каждый заплатит: ',round(va,2))
break
except ValueError:
print('Неверное значение! Рестарт...')
gip()
def con(): #Roman Aleksejev, 03.11.2020, Задача 7.
print('Конверсия времени.')
while True:
try:
a=int(input('Введите минуты: '))
b=a//60
c=round(a%60,2)
print('Время: ',b,':',c)
break
except ValueError:
print('Неверное значение! Рестарт...')
con()
def conn(): #Roman Aleksejev, 03.11.2020, Задача 8.
print('Конвертация в двроичную и 16-ю систему из десятичной.')
while True:
try:
a=int(input('Введите число: '))
b=bin(a)
c=hex(a)
print('Число ',a,'в двоичной системе:',b,'в 16-й системе:',c)
break
except ValueError:
print('Неверное значение! Рестарт...')
conn()
def fuel(): #Roman Aleksejev, 03.11.2020, Задача 9.
print('Вычислить расход топлива на 100км.')
while True:
try:
a=float(input('Введите количество топлива: '))
b=float(input('Введите пройденный путь в километрах: '))
va=a/b*100.0
print('Расход на 100км: ',round(va,2))
break
except ValueError:
print('Неверное значение! Рестарт...')
fuel()
def restart():
while True:
print('Задача 1 - Периметр треугольника.')
print('Задача 2 - Вычислить цену со скидкой.')
print('Задача 3 - Вычислить на чай с каждого.')
print('Задача 4 - Вычислить дистанцию.')
print('Задача 5 - Вычислить гипотенузу треугольника.')
print('Задача 6 - Конверсия времени.')
print('Задача 7 - Конвертация в двроичную и 16-ю систему из десятичной.')
print('Задача 8 - Вычислить расход топлива на 100км.')
flag=input('Выбирите задачу: ')
if flag=='1':
perimetr()
break
elif flag=='2':
cenapr()
break
elif flag=='3':
tips()
break
elif flag=='4':
dist()
break
elif flag=='5':
gip()
break
elif flag=='6':
con()
break
elif flag=='7':
conn()
break
elif flag=='8':
fuel()
break
else:
break
restart()
while True:
r=input('Еще раз? [y/n]')
if r=='y':
restart()
else:
break
|
874c3e2a808c69d9f135c40f5d3ab93126b31a00 | Isabel-Cumming-Romo/Classify-Falls-ML | /nn_mySGD.py | 4,905 | 3.734375 | 4 | import random # for w's initalizations
import numpy # for all matrix calculations
import math # for sigmoid
import scipy
import pandas as pd
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + numpy.exp(-x))
def sigmoidGradient(z):
#Parameters: z (a numerical input vector or matrix)
#Returns: vector or matrix updated by
return numpy.multiply(sigmoid(z), (1-sigmoid(z)))
def square(x):
return numpy.power(x, 2)
def computeCost(X, y, h, m):#Paramters: X, y, h (the hypothesis/prediction from the neural network), m (number of training examples)
J=numpy.sum(numpy.square(y-h))
s=numpy.shape(h)
J=J/s[0]
#Return final cost: J= J + regTerm
return J
def computeGradient(upper_grad, w, X):
# Return W_grad, h_grad
#Params: upper_gradient (ie the gradient received from the layer above), W (the weight of one layer),
#X (training data)
W_grad = numpy.matmul(numpy.transpose(X), upper_grad)
h_grad = numpy.matmul(upper_grad, numpy.transpose(w))
return W_grad, h_grad
input_layer_size=21
layer_hidden_one_size=20
layer_hidden_two_size=30
output_layer_size=1
#initialize lambda
lam=1
#initialize max number of iterations
max_iter=5
data = pd.read_csv("CapstoneData_FE.csv", low_memory=False);
data=numpy.random.permutation(data)
#this is the number of features in the training matrix being read in (in the MATLAB code, is 256)
num_features=21;
#this is the number of samples (i.e. rows)
x_num_rows=600;
output = data[0:599, 21]; #the class labels are the last column of the csv file
input=data[0:599, 0:21];
test=data[600:647, :]
# Initialize weights to random numbers: w_1, w_2, w_3 ...# TO DO: make sure the initialization numbers are small (between 0 and 1)
w_1= numpy.matrix(numpy.random.random((input_layer_size, layer_hidden_one_size))) #
w_2= numpy.matrix(numpy.random.random((layer_hidden_one_size, layer_hidden_two_size)))
w_3= numpy.matrix(numpy.random.random((layer_hidden_two_size, output_layer_size)))
step=0
batch_size=50
lossHistory = []
for epoch in range(50):
count=0
for i in range(12):
X=input[count:(count+batch_size -1), :]
y=input[count:(count+batch_size -1), :]
m_W1=0
v_W1=0
m_W2=0
v_W2=0
m_W3=0
v_W3=0
#Forward propagation
layer1_activation=X;
#print("X: " + str(numpy.shape(X)))
z_2 = numpy.dot(layer1_activation, w_1)
#print("z_2: " + str(numpy.shape(z_2)))
layer2_activation= sigmoid (z_2)
z_3= numpy.dot(layer2_activation, w_2)
#print("z_3: " + str(numpy.shape(z_3)))
layer3_activation = sigmoid(z_3)
z_4= numpy.dot(layer3_activation, w_3)
#print("z_4: " + str(numpy.shape(z_4)))
h = sigmoid(z_4)
#print("h: " + str(numpy.shape(h)))
cost=computeCost(X, y, h, x_num_rows)
lossHistory.append(cost)
#print("Iteration " + str(i))
#print("Cost is " + str(cost))
#Back Propagation
output_layer_gradient = 2*numpy.subtract(h, y)/x_num_rows
W3_gradient, layer2_act_gradient = computeGradient(output_layer_gradient, w_3, layer3_activation)
layer2_z_gradient = numpy.multiply(layer2_act_gradient, sigmoidGradient(z_3))
W2_gradient, layer1_act_gradient = computeGradient(layer2_act_gradient, w_2, layer2_activation)
#Input layer
layer1_z_gradient = numpy.multiply(layer1_act_gradient, sigmoidGradient(z_2))
W1_gradient, throwAway = computeGradient(layer1_z_gradient, w_1, X)
# w_1 += numpy.dot(layer1_activation, W1_gradient)
# w_2 += numpy.dot(layer2_activation, W2_gradient)
# w_3 += numpy.dot(layer3_activation, W3_gradient)
step = step+1 #step + 1
m_W1 = (0.9 * m_W1 + 0.1 * W1_gradient)
v_W1 = (0.999 * v_W1 + 0.001 * numpy.square(W1_gradient))
w_1 = w_1 - 0.01 * numpy.divide((m_W1/(1-(0.9**step))), numpy.sqrt(v_W1/(1-(0.999**step)) + 1e-8))
m_W2 = (0.9 * m_W2 + 0.1 * W2_gradient)
v_W2 = (0.999 * v_W2 + 0.001 * numpy.square(W2_gradient))
w_2 = w_2 - 0.01 * numpy.divide((m_W2/(1-(0.9**step))), numpy.sqrt(v_W2/(1-(0.999**step)) + 1e-8))
m_W3 = (0.9 * m_W3 + 0.1 * W3_gradient)
v_W3 = (0.999 * v_W3 + 0.001 * numpy.square(W3_gradient))
w_3 = w_3 - 0.01 * numpy.divide((m_W3/(1-(0.9**step))), numpy.sqrt(v_W3/(1-(0.999**step)) + 1e-8))
count=count+batch_size
layer1_activation=X;
z_2 = numpy.dot(layer1_activation, w_1)
layer2_activation= sigmoid (z_2)
z_3= numpy.dot(layer2_activation, w_2)
layer3_activation = sigmoid(z_3)
z_out= numpy.dot(layer3_activation, w_3)
h = sigmoid(z_out)
cost=computeCost(X, y, h, x_num_rows)
h[h >= 0.5]=1
h[h < 0.5]=0
print("Cost is " + str(cost))
print("Actual: " + str(y))
print("Predicted: " + str(h))
plt.figure(figsize=(12, 9))
plt.subplot(311)
plt.plot(lossHistory)
#plt.subplot(312)
# plt.plot(H, '-*')
# plt.subplot(313)
# plt.plot(x, Y, 'ro') # training data
# plt.plot(X[:, 1], Z, 'bo') # learned
plt.show()
# print("w_1:")
# print(w_1)
# print("w_2:")
# print(w_2)
# print("w_3:")
# print(w_3)
|
6baccb270aca97314cc96c226a6edad62f59a4b1 | adamcasey/Interview-Prep-With-Python | /isPalindrome.py | 3,050 | 4.40625 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-.
Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
'''
import math
class IsPalindrome_Solution:
def isPalindrome_brute(self, x: int) -> bool:
# First check if negative number
if x < 0:
return False
numString = str(x)
# Next check for odd/even length input
if len(numString) % 2 == 0:
leftIndex = rightIndex = math.floor(len(numString) // 2)
leftIndex -= 1
else:
# Everything starts in the middle of the list
middleIndex = math.floor(len(numString) // 2)
leftIndex = middleIndex - 1
rightIndex = middleIndex + 1
# Make an array of each digit
digitList = []
for eachNum in numString:
digitList.append(eachNum)
# Start at the middle index and go 'outwards' to check that each number matches
while leftIndex >= 0 and rightIndex <= len(numString) - 1:
if numString[leftIndex] != numString[rightIndex]:
return False
else:
leftIndex -= 1
rightIndex += 1
return True
def isPalindrome_better(self, x: int) -> bool:
'''
Special cases:
As discussed above, when x < 0, x is not a palindrome.
Also if the last digit of the number is 0, in order to be a palindrome, \
the first digit of the number also needs to be 0.
Only 0 satisfy this property.
'''
if x < 0 or (x % 10 == 0 and x != 0):
return False
revertedNum = 0
while x > revertedNum:
revertedNum = revertedNum * 10 + x % 10
# Don't forget to use '//' or else you'll get a decimal
x //= 10
'''
When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
For example when the input is 12321, at the end of the while loop we get x = 12, \
revertedNumber = 123, since the middle digit doesn't matter in palidrome(it will \
always equal to itself), we can simply get rid of it.
If either of these are True, it returns True
If both are False, it returns False
'''
return x == revertedNum or x == revertedNum // 10
palindromeConst = IsPalindrome_Solution()
test_Num = 12345654321
print("{} is a Palindrome: {}".format(test_Num, palindromeConst.isPalindrome_brute(test_Num)))
print("{} is a Palindrome: {}".format(test_Num, palindromeConst.isPalindrome_better(test_Num)))
|
e8dbf7870b09b82748a2ac609edf15410caadc3b | korzair74/Homework | /Homework_4-23/Classes.py | 721 | 4.0625 | 4 | """
Build three classes, two of which must inherit from the first and employ
polymorphism. Between the three classes, there must be at least 5 methods,
3 instance attributes, 1 class attribute, and the parent class should
have a dunder init. If you want you can add dunder str and dunder repr
to each class.
"""
class Member:
def __init__(self, char_name, level, char_class, guild='Omen'):
self.char_name = char_name
self.level = level
self.char_class = char_class
self.guild = guild
def rank(self):
print("I am here to server")
class Officer(Member):
def rank(self):
print("I am here to lead")
class Leader(Officer, Member):
def rank(self):
print("Serve me well")
|
04a98004e523f2acf8b2eafe912c6e930987749c | eganjam/MOOCs | /Coursera_UniversityOfMichigan_PythonForInfomatics/02c_ExtractHourlyDistributionOfEmails.py | 840 | 3.921875 | 4 | # prompt for the file
fname = raw_input("Enter file name: ")
# press enter to use the default file
if len(fname) < 1 : fname = "mbox-short.txt"
# open the file
fh = open(fname)
count = 0
counts = {}
# for loop to go through each email and extract
# the hour in which that email was sent
for line in fh:
if line.startswith('From'):
if not line.startswith('From:'):
count += 1
line = line.split()
#print line
line = line[5]
line = line.split(":")
hour = line[0]
counts[hour] = counts.get(hour, 0) + 1
#print counts.items()
lst = list()
for key, val in counts.items():
lst.append((key,val))
lst.sort(reverse = False)
# list the hour and the number of emails sent
for val,key in lst:
print "Hour: %s Emails sent: %s" %(val, key)
|
870b5fa8ef7faa9efd0a4ddf1a5ef8d6f6c2f461 | mainadwitiya/Data-Structures | /python_codes/dynamic_prog/fibo.py | 204 | 3.609375 | 4 |
#memoization
def fibn(n):
memo={0:1,1:1}
def helper(n):
if n not in memo:
memo[n]=helper(n-1)+helper(n-2)
print(memo)
return memo[n]
return helper(n)
z=10
result=fibn(z)
print(result) |
31081d8a3c8cb2579d5fca1abbf67dd9995c8da4 | rayankikavitha/InterviewPrep | /Tries/Trie_implementation.py | 2,577 | 4.03125 | 4 | import unittest
class TrieNode:
def __init__(self, letter):
self.letter=letter
self.isTerminal=False
self.children={} # dictionary to store key as child letter, value as pointer address to node
self.positions=[] # to store the order of the incoming text
class Trie(TrieNode):
# Implement a trie and use it to efficiently store strings
def __init__(self):
self.root_node=TrieNode('')
self.wordcount = 0
def __contains__(self,word):
curr_node = self.root_node
for letter in word:
if letter not in curr_node.children:
return False
curr_node = curr_node.children[letter]
if not curr_node.isTerminal:
return 'prefix of existing word'
else:
return 'word already present'
def add_word(self, word):
status = self.__contains__(word)
print status
if not status:
current_node = self.root_node
for char in word:
if char not in current_node.children:
current_node.children[char]=TrieNode('')
current_node = current_node.children[char]
current_node.isTerminal=True
self.wordcount += 1
return 'new word '+ str(self.wordcount)
elif status == 'prefix of existing word':
current_node = self.root_node
for char in word:
current_node = current_node.children[char]
current_node.isTerminal = True
self.wordcount +=1
status = 'word already present'
else:
return status
# Tests
class Test(unittest.TestCase):
def test_trie_usage(self):
trie = Trie()
result = trie.add_word('catch')
self.assertTrue(result, msg='new word 1')
result = trie.add_word('cakes')
self.assertTrue(result, msg='new word 2')
result = trie.add_word('cake')
self.assertTrue(result, msg='prefix of existing word')
result = trie.add_word('cake')
self.assertFalse(result, msg='word already present')
result = trie.add_word('caked')
self.assertTrue(result, msg='new word 3')
result = trie.add_word('catch')
self.assertFalse(result, msg='all words still present')
result = trie.add_word('')
self.assertTrue(result, msg='empty word')
result = trie.add_word('')
self.assertFalse(result, msg='empty word present')
unittest.main(verbosity=2) |
5ce3b9ffee8d6bba45458397c75bc2d86d6fa646 | Superbeet/LeetCode | /Non-leetcode/Reverse_String.py | 653 | 3.75 | 4 | # class Solution:
# # @param s, a string
# # @return a string
# def reverseWords(self, s):
# words = s.split()
# words.reverse()
# return " ".join(words)
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
res = ""
size = len(s)
j = size
for i in xrange(size-1, -1, -1):
if s[i] == " ":
j = i
elif i==0 or s[i-1]==" ":
if res:
res += " "
res += s[i:j]
return res
s = "hello world"
sol = Solution()
print sol.reverseWords(s) |
417810a0395d79b3dde73003e09f2c3d6af83d55 | zhouhaosame/leetcode_zh | /offer/36_二叉搜索树与双向链表.py | 2,270 | 3.953125 | 4 | """
def Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List(root):
很明显,这个需要将树的指针都重新改变,正好左右子树就是双向指针啊
if not root:
return root
def reverse(node):
if node:
if not node.left and not node.right:
return node,node
else:
left_start,left_end=reverse(node.left)
right_start,right_end=reverse(node.right)
left_end.right=node
node.left=left_end
node.right=right_start
right_start.left=node
return left_start,right_end
start,end=reverse(root)
return start,end
这种解法明显是错误的,没有考虑只有一个孩子为空的情况
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def Convert(pRootOfTree):
# write code here
if not pRootOfTree:
return pRootOfTree
def contact(node):
if not node or (not node.left and not node.right):
return node,node
else:
left_head,left_tail=contact(node.left)
right_head,right_tail=contact(node.right)
if not left_head:
node.right=right_head
right_head.left=node
node.left=None#一定要加上这一行啊,因为不加上的话,node的左边或者右边仍然指向一些东西,可能导致死循环
return node,right_tail
if not right_head:
left_tail.right=node
node.left=left_tail
node.right=None#############
return left_head,node
#因为最前面已经考虑了左右孩子都为空的情况,所以上述两个if只有一个会执行
left_tail.right=node
node.left=left_tail
node.right=right_head
right_head.left=node
return left_head,right_tail
return contact(pRootOfTree)
from binary_tree import stringToTreeNode
nums=[10,6,14,4,8,12,16]
root=stringToTreeNode(nums)
head,tail=Convert(root)
while(head):
print(head.val)
head=head.right
while(tail):
print(tail.val)
tail=tail.left
|
878bda9c5415ac85b0c4095bdf3a02d837d7ecc4 | Elisa-Vitoria/AtividadesDeLPC | /atv.1.py | 202 | 3.5 | 4 | # ETE PORTO DIGITAL
# LPC - Introdução a Python
# Prof. Cloves Rocha
# Estudante: Elisa Vitória
# Turma: 1°B
#1. Faça um Programa que mostre a mensagem "Olá mundo" na tela.
print('\033[35mOlá, mundo!\033[m') |
3b0cf11c65077075da455aab745a378263ef7e7f | seven320/AtCoder | /test/99.py | 135 | 3.640625 | 4 | # encoding: utf-8
for i in range(1, 10):
for j in range(1, 10):
print(" {:02}".format(i * j), end = "")
print("")
|
bb32f5bb718f30780946f0c7c20ed18dfa4c09ca | EithanHollander/ProjectEulerAnswers | /solution_57.py | 877 | 3.84375 | 4 | from fractions import Fraction
if __name__ == '__main__':
previous_denominator, current_denominator, previous_numerator, current_numerator = 1, 2, 1, 3
temp_denominator, temp_numerator = 0, 0
counter_of_expansions = 0
amount_of_exceeding = 0
while counter_of_expansions < 1000:
if len(str(current_numerator)) > len(str(current_denominator)):
amount_of_exceeding += 1
counter_of_expansions += 1
# Taking care of denominator
temp_denominator = current_denominator
current_denominator = 2 * current_denominator + previous_denominator
previous_denominator = temp_denominator
# Taking care of numerator
temp_numerator = current_numerator
current_numerator = 2 * current_numerator + previous_numerator
previous_numerator = temp_numerator
print(amount_of_exceeding) |
61ef536003edebfb3b31452bfb1bd04a877fe257 | dragonslice/nxdom | /languages/utils.py | 1,313 | 3.875 | 4 | VOWELS = 'aeiouy'
TRIPLE_SCORES = {}
def word_groups(word):
"""
>>> list(word_groups('weight'))
['w', 'ei', 'ght']
>>> list(word_groups('Eightyfive'))
['ei', 'ght', 'y', 'f', 'i', 'v', 'e']
"""
index = 0
word = word.lower()
while index < len(word):
# Find some consonants.
start = index
while index < len(word) and word[index] not in VOWELS:
index += 1
if index > start:
yield word[start:index]
# Find some vowels.
start = index
while index < len(word) and word[index] in VOWELS:
index += 1
if index > start:
yield word[start:index]
def word_triples(word):
"""
>>> list(word_triples('weight'))
['^wei', 'weight', 'eight$']
>>> list(word_triples('eightyfive'))
['^eight', 'eighty', 'ghtyf', 'yfi', 'fiv', 'ive', 've$']
"""
groups = ['^'] + list(word_groups(word)) + ['$']
for start in range(len(groups) - 2):
yield ''.join(groups[start:start + 3])
def word_score(word, triple_scores):
triples = list(word_triples(word))
result = 0.0
for triple in triples:
result += triple_scores.get(triple, 0.0)
return result / len(triples)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
e9102d5aa24ddee817c2fd36ec3d06ba28c01616 | hustsong/leetcode | /python/680. Valid Palindrome II.py | 423 | 3.546875 | 4 | class Solution:
def validPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i <= j:
if s[i] == s[j]:
i += 1
j -= 1
continue
pivot = len(s) // 2 + len(s) % 1
return s[i + 1:j + 1] == s[i + 1:j + 1][::-1] or s[i:j] == s[i:j][::-1]
return True
s = "abca"
sol = Solution()
print(sol.validPalindrome(s))
|
27470b0f2a286d48019ce911f16df7fb58acce28 | severinson/uibdoc-python | /scientific-solutions.py | 2,113 | 3.53125 | 4 | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
'''
last task from basic.
'''
import random
def flip():
if random.random() < 0.5:
return 0 # heads
else:
return 1 # tails
def sample():
count = 0
outcome = flip()
while outcome == 0:
count += 1 # equivalent to count = count + 1
outcome = flip()
return count
samples = np.fromiter((sample() for _ in range(100000)), dtype=int)
plt.hist(samples, bins=20)
plt.show()
'''
task: create a beautiful plot of x against x^2 for 0 <= x < 10. Use
numpy.linspace to find values of x and numpy.power to compute the
square of x. Save this figure to disk.
'''
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (6, 6)
plt.rcParams['figure.dpi'] = 200
samples = 100
x = np.linspace(0, 10, samples)
y = np.power(x, 2)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0, 10)
plt.ylim(0, 100)
plt.title('dat plot')
plt.savefig('dat_plot.png', dpi='figure')
plt.show()
'''
task: Use scipy.optimize.curve_fit to fit a curve of the form
"y=a+bx", where a and b are coefficients to this data:
x = [1, 2, 3, 4]
y = [13.46688604, 18.58857204, 20.51804834, 27.6660338]
First, plot the given x and y data. Second, fit parameters (a, b) to
the data, third plot the given x and y together with the fit
curve. Use np.linspace to find values of x.
'''
from scipy.optimize import curve_fit
x = [1, 2, 3, 4]
y = [13.46688604, 18.58857204, 20.51804834, 27.6660338]
f = lambda x, a, b: a + b*x
p, _ = curve_fit(f, x, y)
print(p)
plt.figure()
plt.plot(x, y)
t = np.linspace(1, 4, 100)
plt.plot(t, [f(x, *p) for x in t])
plt.show()
'''
task: use pandas.read_csv to read the csv file "scatter.csv", print it
to terminal, and then plot its "x" column against its "y" column using
pyplot.
'''
# code used to generate the data
# n = 100
# x = np.linspace(0, 1, n)
# y = np.log2(x) + np.random.randn(n)
# df = pd.DataFrame({'x': x, 'y': y})
# df.to_csv('scatter.csv', index=False)
# read and plot it
df = pd.read_csv('scatter.csv')
plt.scatter(df['x'], df['y'])
plt.show()
|
b37df0668f2e8887416e0558acffa61955260ef6 | KwameKert/algorithmDataStructures | /smallestDifference/code/__init__.py | 862 | 3.796875 | 4 |
#finding the smallest difference from two arrays
def smallestDifference(firstList, secondList):
#sorting both arrays
firstList.sort()
secondList.sort()
smallestPair = []
idxOne = 0
idxTwo = 0
current = float("inf")
smallest = float("inf")
#loop through both arrays till the end of its range
while idxOne < len(firstList) and idxTwo < len(secondList):
firstNumber = firstList[idxOne]
secondNumber = secondList[idxTwo]
current = abs(firstNumber - secondNumber)
if firstNumber < secondNumber:
idxOne += 1
elif firstNumber > secondNumber:
idxTwo += 1
else:
return [firstNumber, secondNumber]
if smallest > current:
smallest = current
smallestPair = [firstNumber, secondNumber]
return smallestPair
|
f69bfc08f80d3600fe429184a7a59892c6aa1dae | tofuriouz/snakify_final | /snakify/unit 1/two_timestamps.py | 271 | 3.65625 | 4 | # Read an integer:
# a = int(input())
# Read a float:
# b = float(input())
# Print a value:
# print(a, b)
a = int(input())
b = int(input())
c = int(input())
x = int(input())
y = int(input())
z = int(input())
s = (a*3600 + b*60 + c)
t = (x*3600 + y*60 + z)
print(t - s)
|
44e207e3fccebd95833b268a05f8d2783c7bff6d | eaudeweb/edw.utils | /edw/utils/iter.py | 307 | 3.890625 | 4 | from collections import Iterable
def is_iter(v):
"""Returns True only for non-string iterables.
>>> is_iter('abc')
False
>>> is_iter({'a': 1, 'b': 2, 'c': 3})
True
>>> is_iter(map(lambda x: x, 'abc'))
True
"""
return not isinstance(v, str) and isinstance(v, Iterable)
|
c5108c50fc4b003bdfa0bb89c2fda6fd5593095c | arturbs/Programacao_1 | /prologo/Converte_Temperatura/convtemp.py | 173 | 3.5625 | 4 | fahr = float(input())
cels = (fahr - 32) * (5.0/9)
kel = cels + 273.15
print ("Fahrenheit: %0.3f F" %fahr)
print ("Celsius: %0.3f C" %cels)
print ("Kelvin: %0.3f K" %kel)
|
665584e93525945e0fdc46996acf3c14a8607684 | Akards/Medusa | /Medusa/matrix/multiplication.py | 1,716 | 3.59375 | 4 | import numpy as np
import multiprocessing as mp
from functools import partial
def multiply(A, B, proc_num):
"""
Multiplies 2D numpy matrices A and B using n total processes.
Args:
A (np.array): a 2D matrix
B (np.array): a 2D matrix
proc_num (int): number of processors
Returns:
The product of A*B
"""
if A.ndim != 2:
raise Exception("Must provide 2-dimensional matrix. Matrix A has {} dimensions".format(A.ndim))
if B.ndim != 2:
raise Exception("Must provide 2-dimensional matrix. Matrix B has {} dimensions".format(B.ndim))
if A.shape[1] != B.shape[0]:
raise Exception("A ({}x{}) and B ({}x{}) row number does not match column number".format(A.shape[1], A.shape[0], B.shape[1], B.shape[0]))
# Create a manager, and give it a zeroed list with the size of the result
manager = mp.Manager()
C = manager.list([0 for n in range(A.shape[0]*B.shape[1])])
# Add all slice indices for Multiprocessing to map later
slices = [row_num for row_num in range(A.shape[0])]
if proc_num > len(slices):
proc_num = len(slices)
B_t = np.transpose(B) # Transpose for row-major order traversal
pool = mp.Pool(proc_num)
mult = partial(multiply_row, A, B_t, C)
pool.map_async(mult, slices)
pool.close()
pool.join()
C = np.array(C).reshape(A.shape[0], B.shape[1])
return C
def multiply_row(A, B, C, row):
for j in range(B.shape[0]):
C[row*B.shape[0] + j] += np.dot(A[row], B[j])
def main():
A = np.array([[1, 2, 3, 4, 5] for i in range(5)])
B = np.array([[i%2] for i in range(1, 6)])
C = multiply(A, B, 5)
print(C)
if __name__ == '__main__':
main()
|
11b45d85ed41053eda8d25545bf4ba1ce0093b1e | MrJustPeachy/CodingChallenges | /Kattis/Difficulty - 1/Difficulty - 1.3/spavanac.py | 402 | 3.75 | 4 | data = input().strip().split()
hours = int(data[0])
minutes = int(data[1])
hourTime = 0
minuteTime = 0
if minutes >= 45:
hourTime = hours
minuteTime = minutes - 45
else:
if hours > 0:
hourTime = hours - 1
else:
hourTime = 23
minuteDiff = minutes - 45
minuteFixed = 60 + minuteDiff
minuteTime = minuteFixed
print(str(hourTime) + ' ' + str(minuteTime)) |
e2589d8a260908e6aa58aed3af79b7762183a043 | yckfowa/Automate_boring_stuff | /Ch.08/Sandwich_maker.py | 1,276 | 4.03125 | 4 | import pyinputplus as pyip
price_list = {'breads': {'wheat': 5, 'white': 3, 'sourdough': 6},
'main': {'chicken': 7, 'turkey': 10, 'ham': 5, "tofu": 3},
'cheeses': {'cheddar': 3, 'Swiss': 4, 'mozzarella': 3}}
def main():
total = 0
print("Welcome to SubWaiyi, please make your order ")
bread_choice = pyip.inputMenu(['wheat', 'white', 'sourdough'], prompt='What types of bread do you prefer?' + "\n")
total += price_list['breads'][bread_choice]
main_choice = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'], prompt="Choices of main?" + '\n')
total += price_list['main'][main_choice]
cheese_choice = pyip.inputYesNo("Would you like any cheese?:")
if cheese_choice == 'yes':
cheese_select = pyip.inputMenu(['cheddar', 'Swiss', 'mozzarella'])
total += price_list['cheeses'][cheese_select]
pyip.inputYesNo("Do you want mayo, mustard, lettuce, or tomato (free of charge):")
elif cheese_choice == "no":
pyip.inputYesNo("Do you want mayo, mustard, lettuce, or tomato (free of charge):")
response = pyip.inputInt("How many sandwiches do you want: ", min=1)
print(f"The total price would be ${response * total} dollars")
exit()
if __name__ == "__main__":
main()
|
3a9c70d2e1bda14652f62095272d5a7067f00455 | SphericalPendulum/Pendulum-Art-2.0 | /plot_or_animate2D.py | 2,379 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
num_layers = int(input("Enter the number of paint layers you plan to add: "))
# get filenames
filenames = []
for i in range(num_layers):
filename = input(f'Enter the name of data file #{i+1}: ')
filenames.append(filename)
# load data from files
times, xs, ys = [], [], []
for i in range(num_layers):
droptime, dropx, dropy = np.loadtxt(filenames[i],usecols=(0,1,2),unpack=True)
times.append(droptime)
xs.append(dropx)
ys.append(dropy)
# get colors for each curve
colors = []
for i in range(num_layers):
color = input(f'Enter the color of line number #{i+1} (ex: white or #ddeeff): ')
colors.append(color)
# get information about background
bg_color = input("Enter the background color of the painting (ex: black or #221100): ")
x_width = float(input("Enter horizontal width of art: "))
y_width = float(input("Enter vertical height of art: "))
# let user show or hide the axis
hide_axis = input("Do you want to hide the axis? [y/n] ")
while hide_axis not in ['y', 'Y', 'n', 'N']:
hide_axis = input("Do you want to hide the axis? [y/n] ")
if hide_axis in ['y', 'Y']:
axis_off = True
else:
axis_off = False
# function to plot the paint paths
def plot_lines(t, xs, ys, colors, bg_color, num_layers, x_width, y_width, off):
ax.clear()
ax.set_facecolor(bg_color)
ax.set_xlim(-x_width/2, x_width/2)
ax.set_ylim(-y_width/2, y_width/2)
if off:
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
for i in range(num_layers):
ax.plot(xs[i][0:t], ys[i][0:t], color=colors[i])
# handler to animate plot
def animate(t):
plot_lines(t, xs, ys, colors, bg_color, num_layers, x_width, y_width, axis_off)
# let user choose if they want to see a plot or animation
response = "continue"
while response not in ['P', 'A']:
response = input("Do you want to plot or animate the results? (Enter P to plot, A to animate): ")
fig,ax = plt.subplots(figsize=(8,8*y_width/x_width))
if response == 'P':
plot_lines(len(times[0]), xs, ys, colors, bg_color, num_layers, x_width, y_width, axis_off)
elif response == 'A':
Ntimes = range(0,len(times[0]),40)
anim = animation.FuncAnimation(fig, animate,frames=Ntimes,interval=1,blit=False,repeat=False)
plt.show()
|
ec0bf55690e538ad7baff00c34b0ee3deb83ad61 | Try-Try-Again/lpthw | /ex1-22/ex19_drill3.py | 164 | 3.5625 | 4 | def bedtime(devin):
print(f"The last one in bed's a {devin}-baby!")
races = ["blue", "red", "green", "purple", "orange"]
for race in races:
bedtime(race)
|
2ca5b0fe35dbfb6789be92fce4ddee2e1e09fc70 | Saptarshidas131/NPTEL | /Joy of Comuting using Python/assignments/2019JOC_Assignments/W4PA3.py | 2,071 | 4.65625 | 5 | '''
You all have used the random library of python. You have seen in the screen-cast of how powerful it is.
In this assignment, you will sort a list let's say list_1 of numbers in increasing order using the random library.
Following are the steps to sort the numbers using the random library.
Step 1: Import the randint definition of the random library of python. Check this page if you want some help.
Step 2: Take the elements of the list_1 as input.
Step 3: randomly choose two indexes i and j within the range of the size of list_1.
Step 4: Swap the elements present at the indexes i and j. After doing this, check whether the list_1 is sorted or not.
Step 5: Repeat step 3 and 4 until the array is not sorted.
Input Format:
The first line contains a single number n which signifies the number of elements in the list_1.
From the second line, the elements of the list_1 are given with each number in a new line.
Output Format:
Print the elements of the list_1 in a single line with each element separated by a space.
NOTE 1: There should not be any space after the last element.
Example:
Input:
4
3
1
2
5
Output:
1 2 3 5
Explanation:
The first line of the input is 4. Which means that n is 4, or the number of elements in list_1 is 4. The elements of list_1 are 3, 1, 2, 5 in this order.
The sorted version of this list is 1 2 3 5, which is the output.
NOTE 2: There are many ways to sort the elements of a list. The purpose of this assignment is to show the power of randomness, and obviously it's fun.
'''
from random import randint
n = int(input())
arr = []
for i in range(n):
x = int(input())
arr.append(x)
sorted = True
while(sorted):
j = randint(0,n-1)
i = randint(0,n-1)
arr[i],arr[j] = arr[j],arr[i]
for k in range(0,n-1):
if (arr[k] > arr[k+1]):
sorted = False
if(sorted):
break
else:
sorted = True
for i in range(n):
if(i==n-1):
print(arr[i])
else:
print(arr[i],end=" ")
|
06df8705e59d0d3b4921b77748d76f9d46846e97 | BastiennM/Jeu-du-pendu | /brouillon/program.py | 1,404 | 3.5 | 4 | # coding=utf-8
import random
# jeu du pendu
# fichier de mots dans liste
liste = []
fichier = open("liste.txt", "rt")
for x in fichier:
liste.append(x.rstrip("\n"))
mot = liste[random.randint(0, len(liste) - 1)]
# liste contenant les caractères du mot
mot_l = list(mot)
# liste des caractères cachés soit _
mot_c = []
for i in range(len(mot_l)):
mot_c.append("_")
essai = 10
print(" Trouvez le mot codé.")
pts = 50
print('Vous commencez avec 48 points, essayez de les conservers')
a = "_"
while a in mot_c:
if essai > 0:
print("\n Il vous reste %d essais" % essai)
# lettre remplace _
print(mot_c)
choix = input(">>>")
# majuscule
b = choix.capitalize()
if choix in mot_l or b in mot_l:
print("Vous conservez les 50 points")
for x in range(len(mot_l)):
# remplacer les _ par rapport au nombre de caractère
if choix == mot_l[x] or b == mot_l[x]:
mot_c[x] = mot_l[x]
else :
pts = pts-2
print("Il vous reste", pts, "points")
essai -= 1
else:
print("\n Vous n'aviez plus assez d'essais pour continuer. "
"\n Le mot était « %s »"
"\n Vous avez perdu !!" % mot)
break
if a not in mot_c:
print("\n Bravo vous avez trouvé le mot « %s » !!!" % mot)
|
2e536de7dfa7d7c2d9b8a5e3ab8d3a7419160983 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/plltam005/question4.py | 832 | 4.125 | 4 | """Drawing a graph
Tameryn Pillay
16 April 2014"""
import math
def graph():
"""Plotting the graph from the equation given"""
function = input("Enter a function f(x):\n")
for y_axis in range(10,-11,-1):
for i in range (-10,11):
x = i
y = round(eval(function))
if (y - math.floor(y)) >= 0.25:
y= math.ceil(y)
else:
y = math.floor(y)
if y_axis == y:
print('o',end="")
elif y_axis == i == 0 and y!=0:
print("+",end="")
elif y_axis == 0 and y!=0:
print("-",end="")
elif i == 0:
print("|",end="")
else:
print(" ",end="")
print()
graph() |
851f58cf8a2c5d262b8cb9e71048260047e1f3bb | daniel-reich/ubiquitous-fiesta | /jzCGNwLpmrHQKmtyJ_16.py | 151 | 3.703125 | 4 |
def sum_digits(n):
return n%10 + sum_digits(int(n/10)) if n else 0
def parity_analysis(num):
return (sum_digits(num) % 2 == 0) == (num % 2 == 0)
|
a035bf938f692950f945e652b0e29915a8dfeed3 | stevekutz/python_iter_sort | /HackerRank/tuples.py | 696 | 4.21875 | 4 | """
Task
Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of
hast(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer,
, denoting the number of elements in the tuple.
The second line contains space-separated integers describing the elements in tuple
.
Output Format
Print the result of
.
Sample Input 0
2
1 2
"""
import hashlib
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
tup = ()
for x in integer_list:
tup+=(x,)
print(hash(tup)) |
32612ba620b9e64608f64637ff17cf95f090562c | ecaterinacatargiu/FP | /Backtracking/o.py | 60 | 3.671875 | 4 |
x = 10
def f(y):
y+=1
z = f(x)
print("x=", x, "z= ", z) |
c0daf0c0096d2e0cb19eb5ae4dd36c5b91f52a9a | schnitzlMan/ProjectEuler | /Aufg6.py | 127 | 3.59375 | 4 |
totalSum = 0
for i in range (101):
print(i)
for j in range(i):
totalSum += i*j
totalSum *=2
print(totalSum)
|
fa39c25efc9c60a0ec364264fec82a409f911edd | vitords/ProjectEuler | /009.py | 410 | 3.5 | 4 | # Special Pythagorean triplet
# Problem 9
# Brute force, but works...
result = 0
for c in range(100, 500):
for b in range(100, c):
for a in range(100, b):
if a**2 + b**2 == c**2:
if a + b + c == 1000:
result = a * b * c
break
else:
continue
break
else:
continue
break
print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.