blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
c8e6ec74ebe6821c2723eb2d928307d25a6e4f51 | MichalMianowski/python-workouts | /Credit_card/credit_card.py | 1,272 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 13:04:14 2019
@author: MM
Program finds the smallest monthly payment to the cent such that we can pay off
the debt (from credit card) within a year.
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
Monthly interest rate = (Annual interest rate) / 12.0
Monthly payment lower bound = Balance / 12
Monthly payment upper bound = (Balance x (1 + Monthly interest rate)^12) / 12.0
"""
balance = input("input the outstanding balance on the credit card")
annualInterestRate = input("input annual interest rate as a decimal")
monPayment = 0
remBalance = balance
monInterestRate = annualInterestRate/12.0
lowPayBound = balance/12
upPayBound = (balance * (1+monInterestRate)**12)/12.0
while 0 < remBalance or remBalance< -0.2:
remBalance = balance
monPayment = round((lowPayBound + upPayBound)/2 , 2)
for month in range(12):
monBalance = remBalance - monPayment
remBalance = monBalance + (monInterestRate*monBalance)
if remBalance > 0:
lowPayBound = monPayment
elif remBalance <-0.2:
upPayBound = monPayment
print("Lowest Payment:", monPayment) |
9e2b9eb7c954abff284c955b9e17164ac5e5aa42 | shivamkalra111/Tkinter-GUI | /Radio.py | 1,027 | 3.703125 | 4 | from tkinter import *
from PIL import ImageTk, ImageTk
root = Tk()
root.title('Learn GUI')
root.iconbitmap('C:\\Users\\ealihks\\Desktop\\My Own Work\\GUI Application\\Tkinter\\icon.ico')
#r = IntVar()
#r.set('2')
toppings = [
("Pepperoni", "Pepperoni"),
("Cheeze", "Cheeze"),
("Mushroom", "Mushroom"),
("Onion", "Onion")
] # text, topping
pizza = StringVar()
pizza.set("Pepperoni")
for text, topping in toppings:
Radiobutton(root, text = text, variable = pizza, value = topping).pack(anchor = W)
def clicked(value):
mylabel = Label(root, text = value)
mylabel.pack()
#Radiobutton(root, text = 'Option 1', variable = r, value = 1, command = lambda: clicked(r.get())).pack()
#Radiobutton(root, text = 'Option 2', variable = r, value = 2, command = lambda: clicked(r.get())).pack()
#mylabel = Label(root, text = pizza.get())
#mylabel.pack()
mybutton = Button(root, text = 'Click me!', command = lambda: clicked(pizza.get()))
mybutton.pack()
root.mainloop() |
bfdc04cc351afa2e477ca89515390d46d4efdd2c | ayadirihem/calculator_terminal | /Calculator.py | 464 | 3.828125 | 4 | import re
def calcul():
while True:
print(" Hello human how can we help you today !!")
num = input(">> ")
fonct = re.sub('[a-z,A-Z,;#!():$§£&]', '', num)
s = eval(fonct)
print("=> Resultat:", s)
print("----Do you want to calculate another thing ? Y/N")
resp = input()
if resp == 'N' or resp == 'n':
print('Thank you for visiting us ! GoodBy human ')
break
calcul()
|
f1420207de3e14acf638ca560d2ed4c69a7506a1 | Essilia/PyTest | /Test/prctice.py | 612 | 3.6875 | 4 | # name=["一一","二二","三三"]
# socre=["99","100","98"]
# num=0
# name1=input("请输入姓名:")
# for i in range(3):
# if i == num and name1 == name[num]:
# print(name1+"的成绩是:"+socre[num])
# num=num+1
# d = {"一一":"99","二二":"100","三三":"98"}
# name2 = input("请输入姓名:")
# # if name2 in d:
# # print(d[name2])
# # else:
# # print(d.get(name2,"查询的用户不存在"))
# if name2 in d:
# d.pop(name2)
# print("删除成功!"+"\n"+str(d))
# s=set([1,2,3,[1,2,3]])
# print(s)
l=[1,2,3]
l.insert(1,7)
print(abs(-100))
print(max(1,2,3,4)) |
4ac0d689929e0f861789903d3da67beaac2073aa | anahiquintero99/Ejercicios-de-python | /ejercicio8.py | 303 | 3.890625 | 4 | def degrees():
degreesc = int(input('Ingresa grados celsious: '))
degreesf = (degreesc * (9/5) ) + 32
degreesc = (degreesf - 32 ) * (5/9)
print(f' {degreesf} farenheit = {degreesc} celsious')
if __name__ == "__main__":
print('Convierte grados celsious a fahrenheit')
degrees()
|
36dfd1f58d19e168b957a2224e959f491629dc11 | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/marc_charbo/lesson09/mailroom_v5_oo.py | 3,072 | 3.890625 | 4 | import donor as Donor
import donors_data as DonorData
DONOR_LIST = {'Jim':[25.00, 150.00, 2000.00, 100000.00],'Linda':[10000.25],'Bob':[5.03, 100.01, 6.00]}
def initial_donor_set():
return [Donor.Donor('Jim', [25.00, 150.00, 2000.00, 100000.00]), Donor.Donor('Linda', [10000.25]),
Donor.Donor('Bob', [5.03, 100.01, 6.00])]
donor_db = DonorData.DonorData(initial_donor_set())
def send_letter():
"""write thank you note to all users in donor list"""
donor_db.save_letters()
def quit():
print('Existing program\n')
return 'quit'
def create_report():
""" prints donnation report on sreen.
for each user their name, sum of donnations, number of times they donnated
and avg donnation amount is displayed.
"""
print (donor_db.print_report())
print('-- End Report --\n')
def send_email(selection,amount):
""" sends thank you email to donor with their name and donation amount"""
print('-- Sending Email --\n')
print ('Thank you {} for you generous ${:.2f} donation'.format(selection,amount))
print('-- Email Sent --\n')
def send_thank_you():
""" donnor dict handling function"""
selection = input('Enter a donors name or list to see all donors: ')
if selection == 'list':
print('Here is the list of donors in the database')
print (donor_db.print_donor_names())
else:
donor = donor_db.find_donor(selection)
if donor is not None:
print ('{} was found in the database'.format(donor))
else:
donor = donor_db.add_donor(selection)
print('{} was added to the database'.format(selection))
try:
amount = input('Please enter a donation amount: ')
amount = float(amount)
donor.donate(amount)
send_email(selection,amount)
except ValueError as e:
print('error with task running program\n {}'.format(e))
print('Returning to main menu\n')
return
def prompt_user():
""" function which displays main menu and prompts user to enter selection"""
print('Please select one of three options: ')
print('1- Send a Thank You')
print('2- Create a Report')
print('3- Send letters to everyone')
print('4- Quit')
selection = input('Enter your selection: ')
return int(selection)
dispatch_dict = {1: send_thank_you, 2: create_report, 3: send_letter, 4: quit}
def run():
""" function which runs program"""
print ("Welcome to Donation Manager")
while True:
try:
if dispatch_dict[prompt_user()]() == 'quit':
break
except KeyError as e:
print('{} select not available please chose between menu options\n'.format(e))
continue
except ValueError as e:
print('{} select not available please chose between menu options\n'.format(e))
def main():
try:
run()
except Exception as e:
print ('error with task running program\n {}'.format(e))
if __name__ == "__main__":
main() |
571fb2b78bf6319fbb3916ce7ce33cca1747ac86 | zarkoblagojevic00/games_sales_analysis | /games_sales_analysis/src/classifiers/logistic_regression.py | 3,019 | 3.9375 | 4 | import numpy as np
import matplotlib.pyplot as plt
class LogisticRegression:
def __init__(self, learning_rate=0.1, epochs=100, threshold=0.5):
self.learning_rate = learning_rate
self.epochs = epochs
self.threshold = threshold
self.coefficients = [] # column_vector
def fit(self, x, y, verbose=False):
cost_history = self.__do_gradient_descent(x, y)
if verbose:
self.__show_details(cost_history)
def predict(self, x):
return self.predict_proba(x) > self.threshold
def predict_proba(self, x):
x_biased = np.insert(x, 0, 1, axis=1)
return self.__predict_probability(x_biased)
def __do_gradient_descent(self, x, y):
x_biased = np.insert(x, 0, 1, axis=1)
self.coefficients = np.random.normal(loc=0, scale=0.01, size=(x_biased.shape[1], 1))
cost_history = []
for epoch in range(self.epochs):
cost_history.append(self.__calculate_cost(x_biased, y))
self.__update_coefficients(x_biased, y)
return cost_history
# ----- Inspired by Andrew Ng's Intro to Machine Learning course on Coursera -----
# Logistic Regression cannot be optimized by Sum of squared errors (SSE)
# because sigmoid function introduces non-linearity (cost function is not convex)
# Function used for calculating cost has the following form: {note that h(x) = predict(x)}
# when y = 1 => cost(h(x), y) = -log(h(x))
# when y = 0 => cost(h(x), y) = -log(1 - h(x))
# written as one equation :
# cost(h(x), y) = -y * log(h(x)) - (1-y) * log(1 - h(x))
#
# COST = 1/m * sum[cost(h(x), y)] (sum over m samples, m = num of samples)
def __calculate_cost(self, x, y):
y_t = y.transpose()
predicted = self.__predict_probability(x)
sample_size = len(y)
cost = (-y_t @ np.log(predicted) - (1 - y_t) @ np.log(1 - predicted)) / sample_size
return cost[0]
def __update_coefficients(self, x, y):
gradient = self.__calculate_gradient(x, y)
self.coefficients -= self.learning_rate * gradient
# Gradiant calculated by formula: 1/m * sum[(h(x)-y) * x] (over m samples)
def __calculate_gradient(self, x, y):
errors = self.__calculate_errors(x, y)
sample_size = len(y)
return x.transpose() @ errors / sample_size
def __calculate_errors(self, x, y):
return self.__predict_probability(x) - y
def __predict_probability(self, x):
linear_predict = x @ self.coefficients
return self.__sigmoid(linear_predict)
def __sigmoid(self, x):
return 1. / (1. + np.exp(-x))
def __show_details(self, cost_history):
for epoch in range(self.epochs):
print(f'Epoch: {epoch: 3d} Cost: {cost_history[epoch]}')
plt.plot(range(self.epochs), cost_history)
plt.title('Cost function over epochs')
plt.xlabel(f'Epochs({self.epochs})')
plt.ylabel('Cost')
plt.show()
|
d853c7b7db065295b7b39bd97169c9caffaf5b2a | WuLC/LeetCode | /Algorithm/Python/889. Construct Binary Tree from Preorder and Postorder Traversal.py | 912 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# Created on Sun Aug 19 2018 15:55:10
# Author: WuLC
# EMail: [email protected]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# recursive
class Solution(object):
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNode
"""
if len(pre)==0:
return None
root = TreeNode(pre[0])
s1, s2 = set(), set()
idx = 0
while idx < len(post)-1:
s1.add(pre[idx+1])
s2.add(post[idx])
if s1==s2:
break
idx += 1
root.left = self.constructFromPrePost(pre[1:idx+2], post[:idx+1])
root.right = self.constructFromPrePost(pre[idx+2:], post[idx+1:-1])
return root |
f90a00d72d4579cbca20709142387e62cdd9b4b7 | hanzohasashi33/Competetive_programming | /HackerEarth/Array1D/Prasun_The_Detective.py | 427 | 3.6875 | 4 | # Write your code here
'''
import re
mess1 = input()
mess1 = re.sub(r"[^\w\s]", '', mess1)
mess1 = mess1.replace(" ",'')
mess2 = input().replace(" ",'')
mess2 = re.sub(r"[^\w\s]",'', mess2)
if(set(mess1).issubset(set(mess2))==True):
print ("YES")
else :
print ("NO")
'''
mess=input()
mesr=input()
mess=mess.lower()
mesr=mesr.lower()
if(set(mesr).issubset(set(mess))==True):
print("YES")
else:
print("NO")
|
65df4ca4ec70340571c7874dbcee07c6f1e071d8 | marinecollet/Sudoku | /BackTracking.py | 2,914 | 4.1875 | 4 | from Cell import *
class BackTracking:
"""Back tracking algorithm to solve the sudoku"""
def __init__(self, puzzle):
self.puzzle = puzzle
self.box_size = 3
self.height = len(self.puzzle)
self.width = len(self.puzzle[0])
self.solved_puzzle = []
self.number_of_element = self.width * self.height - 1 # -1 because we begin at 0
self.current_index_of_puzzle = 0
self.need_to_backward = False
def get_row(self, row_number):
return self.puzzle[row_number]
def get_column(self, column_number):
return [row[column_number] for row in self.puzzle]
def get_box(self, row_number, column_number):
"""Return an array of the internal_box size already defined"""
internal_box = [[0 for col in range(self.box_size)] for row in range(self.box_size)]
row_start_box = (row_number // self.box_size) * self.box_size
column_start_box = (column_number // self.box_size) * self.box_size
for i in range(0, self.box_size):
internal_box[i] = self.puzzle[row_start_box + i][column_start_box:column_start_box + self.box_size]
return internal_box
def initialize_game(self):
"""Initialize the cells in a new list"""
for row in range(0, self.height):
for col in range(0, self.width):
self.solved_puzzle.append(Cell(row, col, self.get_box(row, col), self.puzzle, self.get_value(row, col)))
def set_cell(self):
"""Find a new value for the current cell if not valid got backward in the list"""
current_cell = self.solved_puzzle[self.current_index_of_puzzle]
current_cell.puzzle = self.puzzle
current_cell.internal_box = self.get_box(current_cell.row_number, current_cell.column_number)
new_cell_value = current_cell.set_cell_value(self.need_to_backward)
if new_cell_value != 0:
self.need_to_backward = False
else:
self.need_to_backward = True
self.puzzle[current_cell.row_number][current_cell.column_number] = current_cell.value
current_cell.puzzle = self.puzzle
current_cell.internal_box = self.get_box(current_cell.row_number, current_cell.column_number)
def change_cell(self):
"""Go forward or backward in the list of cells"""
if self.need_to_backward:
self.current_index_of_puzzle -= 1
else:
self.current_index_of_puzzle += 1
def solve(self):
self.set_cell()
self.change_cell()
def run_solve(self):
"""Run the algorithm until the end of the grid is reached"""
while self.current_index_of_puzzle < self.number_of_element:
self.solve()
def get_value(self, row_number, column_number):
"""Return the value of a cell according to its row and column"""
return self.puzzle[row_number][column_number]
|
4ede2f897724ca773fc9f10e0d4748bf60d86f06 | steelfury/Homework | /main.py | 495 | 4.09375 | 4 | ## Program to check for Coronavirus symptoms and advise actions
is_temperature_high_string = input ("Do you have a high temperature? (Yes/No) ")
## Selection
if is_temperature_high_string == "Yes":
print("Please contact 111.nhs.uk")
else:
is_cough_continuous_string = input ("Do you have a continuous cough? (Yes/No) ")
## Nested selection
if is_cough_continuous_string == "Yes":
print("Please contact 111.nhs.uk")
else:
print("You do not have the main Coronavirus symptoms")
|
1ebd617e7474b66cdf6be544c45e45d8dd5b8a8b | JoneNash/improve_code | /LeetCode/718_Maximum_Length_of_Repeated_Subarray.py | 572 | 3.6875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: leidelong
@contact: [email protected]
@time: 2018/11/28 7:07 PM
@info: 最长公共子序列问题
"""
#DP方法
def findLength( A, B):
dp = [[0 for _ in range(len(B) + 1)] for _ in range(len(A) + 1)]
for i in range(1, len(A) + 1):
for j in range(1, len(B) + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
print dp
return max(max(row) for row in dp)
if __name__ == '__main__':
A=[1,2,3,4,5,7,8,10,11]
B=[1,2,3,4,7,9,10,11]
print findLength(A,B) |
3ce68f33956a0f04e726d60bc3d6538967ae4553 | pokalaanirudh/concrete_strength-analysis-using-Regeression | /Part D.py | 1,748 | 3.75 | 4 | import keras
from keras.models import Sequential
from keras.layers import Dense
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import statistics
import numpy as np
dataframes = pd.read_csv("/home/pokala/coursera/concrete_data.csv")
mean_sq_er_list=[] # list for mean squared error
def model():
dataset= dataframes.values
predictor = dataset[:,0:8]
target = dataset[:,8]
norm_predictor = (predictor - predictor.mean()) / predictor.std()
predictor_train , predictor_test , target_train , target_test = train_test_split(norm_predictor , target , test_size=0.30)
n_cols= predictor.shape[1] # the shape of input layer
# model of neural network
model = Sequential()
model.add(Dense(10,activation="relu",input_shape=(n_cols,)))
model.add(Dense(10,activation="relu"))
model.add(Dense(10,activation="relu"))
model.add(Dense(1))
# training and testing the model
model.compile(optimizer="adam", loss="mean_squared_error")
model.fit(predictor_train,target_train,epochs=100)
result = model.predict(predictor_test)
# for computing the mean squared error between predicted and actual value
x=mean_squared_error(target_test,result)
mean_sq_er_list.append(x)
# for repeating the step 1,2,3 50 times
for i in range(50):
model()
# the final mean and standard deviation of the 50 mean squared error
mean_D= statistics.mean(mean_sq_er_list)
standard_deviation_D = statistics.stdev(mean_sq_er_list)
mean_B =290.56716899224227
mean_difference = mean_B - mean_D
mean_difference=131.68554169780589
mean_D=158.88162729443638
|
7b0cfb4e79e3f55eeb9250a8c5fa3ad8c8c0dc5c | pallavipsap/leetcode | /205_isomorphic_strings.py | 1,975 | 3.6875 | 4 | # May 29 2020
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
#time complexity : O(N) where N is the length of s or t: considering we go ahead only if both are same
if len(s) != len(t): return False
'''
dict = {}
for i in range(len(s)):
#print(dict.items())
if t[i] in dict.values():
if s[i]!=list(dict.keys())[list(dict.values()).index(t[i])]:
return False
# making sure value is same for repeated value in s
if s[i] in dict:
print(dict[s[i]])
print('1st',s[i],t[i])
if dict[s[i]]!=t[i]:
print('OUT')
return False
else:
dict[s[i]]=t[i]
print(dict)
return True
'''
dict = {}
# chars in s as keys, chars in t as values
for i in range(len(s)):
# if key is present in dict
# check if dict's value matches with current value "s"
if s[i] in dict:
if dict[s[i]] != t[i]: # values do not match the current
print(dict)
return False # eg. t = "eggg" s = "addw" , last letter g (key) is already present but value does not match with w
# before entering new key, check if value exists
else:
if t[i] in dict.values(): # if new key is not present in dict, but new value is already present, means value is linked to another key
return False # eg. t = "lat" s = "foo" gives false
else: # key is not present, value is not present, link both as usual
dict[s[i]] = t[i]
return True
|
120b0c8f52440cda36d2b28e8902d7b4f7a4205c | kennlebu/ShoppingListApp | /tests/user_tests.py | 1,812 | 4.21875 | 4 | import unittest
from app.user import User
class UserTests(unittest.TestCase):
""" Tests for the user class """
def test_user_creation(self):
""" Tests whether a user is created and stored successfully """
user = User('kennlebu', 'password', 'Kenneth', 'Lebu')
assert user
self.assertEqual(user.username, 'kennlebu', msg='Username should be kennlebu')
self.assertEqual(user.lastname, 'Lebu', msg='Lastname should be Lebu')
def test_create_shopping_list(self):
""" Tests whether a shopping list is created successfully """
user = User('kennlebu', 'password', 'Kenneth', 'Lebu')
user.create_shopping_list('Sunday shopping', '15/10/2017', user.username)
self.assertEqual(len(user.shopping_lists), 1, msg="There should be one shopping list created")
self.assertEqual(user.shopping_lists[0].username, 'kennlebu',
msg='User of the shopping list should be kennlebu')
def test_delete_shopping_list(self):
""" Tests whether a shopping list is deleted successfully """
user = User('kennlebu', 'password', 'Kenneth', 'Lebu')
user.create_shopping_list('Sunday shopping', '15/10/2017', user.username)
self.assertEqual(len(user.shopping_lists), 1, msg="There should be one shopping list created")
# Deleting a shopping list that does not exist
user.delete_shopping_list('Monday shopping')
self.assertEqual(user.delete_shopping_list('Monday shopping'), 'No such shopping list',
msg="There should not be a shopping list called Monday shopping")
user.delete_shopping_list('Sunday shopping')
self.assertEqual(len(user.shopping_lists), 0, msg="There should not be any shopping lists")
|
283df911af273088d2e358de20fcd6c4c7c50887 | jasontruong93/InCollege-Kansas | /test_main.py | 1,988 | 3.53125 | 4 | import csv
import os.path
import pytest
from csv import writer
import main as m
import student as s
# To test password verfication. In Terminal run: pytest test_main.py
class TestClass:
# Tests if requirements for a valid password are satisfied within main.checkPass()
# Validates if Less than 8 characters
def test_checkPass_lessthan8(self):
assert m.checkPass("1$A") == False # 3 chars
assert m.checkPass("1$Abcde") == False # 7 char
assert m.checkPass("1$Abcdef") == True # 8 char
# Validates if More than 12 characters
def test_checkPass_morethan12(self):
assert m.checkPass("1$Abcdefghijk") == False # 13 characters
assert m.checkPass("1$Abcdefghij") == True # 12 characters
assert m.checkPass("1$Abcdefghi") == True # 11 characters
# Validates if it includes an Uppercase letter
def test_checkPass_noUpper(self):
assert m.checkPass("1$abcdefg") == False # Does not include an Uppercase letter
assert m.checkPass("1$Abcdefg") == True # Does include an Uppercase letter
# Validates if it includes a digit char
def test_checkPass_noDigit(self):
assert m.checkPass("$Abcdefgh") == False # Does not include a digit char
assert m.checkPass("$Abcd5efgh") == True # Does include a digit char
# Validates if it includes a non-alphabetic char
def test_checkPass_noNonAlpha(selfs):
assert m.checkPass("1Abcdefgh") == False # Does not include a non-alphabetic char
assert m.checkPass("1Abc$defgh") == True # Does include a non-alphabetic char
# Validates a complete correct password
def test_checkPass_correctRequirments(self):
assert m.checkPass(
"1$Abcdefg") == True # At least 8 characters, Less than or equal to 12 characters, Includes an Uppercase letter, Includes a digit char, Includes a non-alphabetic char
assert m.checkPass("test") == False
|
0bd796ae00849f6f2382a8380888c71e364a6201 | syoung/s3lib | /notes/agua/private/bin/test/python/pizza/dict1.py | 207 | 4 | 4 | mydictionary={'keyname':'somevalue'}
for key, value in mydictionary.iteritems():
print "key %s: value %s" % (key, value)
#for key in mydictionary:
#print "key %s: value %s" % (key, mydictionary[key]) |
fbc79740ac3ac6485773073ac70762adb08aa694 | codeAligned/codingChallenges | /codewars/counting_duplicates.py | 283 | 3.5625 | 4 | # https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/solutions/python
import collections
def duplicate_count(text):
print(text)
c = collections.Counter(text.upper())
results = []
for key in c:
if c[key] > 1: results.append(key)
return len(results) |
f3ba5ae707e45f289e684807913280976776610c | piastrepiano/Pre-AP-Computer-Science-1 | /3apcs3rd/guessingGame.py | 592 | 4.03125 | 4 | def main():
keep_going = True
import random
print('Hello! What is your name?')
my_name = input()
number = random.randint(1, 9)
print('Well, ' + my_name + ', I am thinking of a number between 1 and 9.')
while keep_going:
print('Take a guess.')
guess = input()
guess = int(guess)
if guess == number:
print("Well guessed,", my_name, "!")
keep_going = False
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
main()
|
6ecf6e2deac1964334c39f82cc797b67584eed6d | mengfa/note | /list/rob.py | 715 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# File Name: rob
# Description :
# Author : LvYang
# date: 2019/3/25
# Change Activity: 2019/3/25:
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int[2,1,1,2]
"""
d = 0
s = 0
for i in range(len(nums)):
if i%2 == 0:
print(nums[i])
s = s+nums[i]
print(s)
else:
print(nums[i])
d = d + nums[i]
print(d)
if s > d:
return s
else:
return d
nums = [2,1,1,2]
so = Solution()
a=so.rob(nums)
print(a) |
0bd3301196b6f5a33b5332a065f28b67ae69d606 | ederst/exercism-python | /hamming/hamming.py | 193 | 3.546875 | 4 | def distance(strand_a: str, strand_b: str) -> int:
if len(strand_a) != len(strand_b):
raise ValueError("Invalid input.")
return sum(x != y for x, y in zip(strand_a, strand_b))
|
7b2e5e13efdf1733d635643a63be2177c74f72dd | lyf1006/python-exercise | /5.if语句/5.4/checkname_ten.py | 376 | 3.78125 | 4 | current_users = ['Mary','Lily','admin','Jack','Tom']
new_users = ['John','qingqian','mary','xiaoxiannv','Tom']
for user in new_users:
#列表解析,实现忽略大小写的比较
if user.lower() in [current_user.lower() for current_user in current_users]:
print("该用户名已被占用,请更换。")
else:
print("设置用户名成功。") |
ec383a9dd2ddab7f0c2e4859c06c925c20896a58 | weepwood/CodeBase | /Python/Exercise/三角形.py | 491 | 3.515625 | 4 | # 计算三角形边长及面积
import math
a = float(input("请输入三角形a边长="))
b = float(input("请输入三角形b边长="))
c = float(input("请输入三角形c边长="))
if not a <= 0 and b > 0 and 0 < c < a + b and b + c > a and a + c > b:
long = a + b + c
h = long / 2
s = math.sqrt(h * (h - a) * (h - b) * (h - c))
print('三角形边长为:', long)
print('三角形面积为:', str.format("{0:2.1f}", s))
else:
print('无法构成三角形')
|
bab85445a4ecd67d7660e9a92cad5ff1d22d855d | LichaDC/GitProgramming | /Código Dallas/Código Dallas Google Drive/Python 3/Excepciones.py | 741 | 3.84375 | 4 | #1)
#print(14/0)
#DEMS CDIGO
#Como salta el error, el cdigo no se sigue ejecutando
#try:
# print(14/0)
#except:
# print("Hay un error al dividir")
#try:
# print(14/0)
#except ZeroDivisionError:
# print("No se puede dividir por 0")
#try:
# tupla = (1,3,3,4,5)
# print (tupla[10])
#except ZeroDivisionError:
# print("Hay un error al dividir")
#try:
# tupla = (1,3,3,4,5)
# print (tupla[10])
#except ZeroDivisionError:
# print("Hay un error al dividir")
#except IndexError:
# print("No existe ese elemento")
try:
tupla = (1,3,3,4,5)
print (tupla[10])
except Exception as error: #Prestar atencin a las maysculas
print ("No se pudo ejecutar, por", error)
print ("esto va al final")
|
b57816fd6ddeadad93ef2de7b2fa23a36ff688c9 | Lammatian/ADS | /structures/linkedlist.py | 3,842 | 3.984375 | 4 | class LinkedList(object):
"""Implementation of linked list with standard methods"""
_title = "Linked list"
class Node(object):
"""Single node of the linked list with a value"""
def __init__(self, val):
"""
Initialise a node
:param val: data held in the node
:type val: T
"""
self.val = val
self.next = None
def __init__(self, vals=[]):
"""
Initialise a linked list given an array of values
:param vals: values for the list
:type vals: T[]
"""
self.length = len(vals)
if not vals:
self.head = None
return
self.head = LinkedList.Node(vals[0])
dummy = self.head
for v in vals[1:]:
self.head.next = LinkedList.Node(v)
self.head = self.head.next
self.head = dummy
self.iter = self.head
def __iter__(self):
"""Iterator"""
self.iter = self.head
return self
def __next__(self):
"""For iterator"""
if not self.iter:
raise StopIteration
else:
prev = self.iter
self.iter = self.iter.next
return prev
def __repr__(self):
"""Return representation of the linked list"""
return "LinkedList([" + ','.join([str(n.val) for n in self]) + "])"
def __str__(self):
"""Return str(self)"""
return ' -> '.join([str(n.val) for n in self])
def lookup(self, n):
"""
Find the n-th value in the list
Returns an error if n is out of bounds of the linked list
:param n: index to get
:type n: int
"""
if n > self.length-1:
raise IndexError("index out of range")
else:
dummy = self.head
for i in range(n):
dummy = dummy.next
return dummy.val
def insert(self, val, p):
"""
Insert a value to a new node after the given node p
:param val: value to be inserted
:param p: predecessor node
:type val: T
:type p: Node
"""
current_successor = p.next
p.next = LinkedList.Node(val)
p.next.next = current_successor
self.length += 1
def insertFirst(self, val):
"""
Insert a value at the beginning of the list
:param val: value to be inserted
:type val: T
"""
new_head = LinkedList.Node(val)
new_head.next = self.head
self.head = new_head
self.length += 1
def remove(self, p):
"""
Remove a node after the given node if it exists
:param p: predecessor node
:type p: Node
"""
if p.next:
p.next = p.next.next
self.length -= 1
def removeFirst(self):
"""Remove the first node of the list if it exists"""
if self.head:
self.head = self.head.next
self.length -= 1
def delete(self, target):
"""
Delete the first value val if it can be found in the list
:param target: value to be deleted
:type target: T
"""
dummy = self.head
if self.head.val == target:
self.head = self.head.next
self.length -= 1
else:
while self.head.next:
if self.head.next.val == target:
self.head.next = self.head.next.next
self.length -= 1
break
self.head = self.head.next
self.head = dummy |
626c10ddd8e15f67099a3b1c19fce6489cea4a62 | rksam24/MCA | /Sem 1/oops/string.py | 2,364 | 4.46875 | 4 | def main():
#option
print("""1.Number of Words in String
2.Reverse of String
3.Reverse each word of String
4.Largest word in String""") #used multiline string to print the option
option() #calling function to select option
def option():
print() #for next line
#select choice
ch=int(input('Enter your choice from above option: ')) # take the input from user for option
if ch<=4:
str=input("Enter the String: ") # take the input from user as string
if ch==1:
length(str) # calling the function to print no of in string
elif ch==2:
reverse(str) #calling the functiion to print revverse of string
elif ch==3:
wordReverse(str)
''' calling the function to reverse each word in the string
ex: i/p my name is Rohit. o/p: ym eman is tihot
'''
else:
largeWord(str) # calling the function to print largest word in the string
else:
print("Invalide Option, please try again") # print the statement when select option is not valid
def length(str):
print("Number of Words in String:", len(str.split()))
"""split string into list with split() then find the number of element in list with len()
then print the number of word in string """
def reverse(str):
print("Reverse of String:", str[::-1])
#reverse the string with slicing and print it
def wordReverse(str):
word=str[::-1].split()
#reverse the string with slicing then split into list
RW="" #create empty string RW
for i in word:
RW=i+" "+RW
"""
ex:word=['my','name','is','rohit']
then using for loop first time i=my then RW=i+' '+'RW.
ex: if RW='n' then are RW=my n
"""
print("Reverse each word of String:", RW)
#print the value of RW which each word reverse in string
def largeWord(str):
x=str.split() # split the string str into list then assign it to x
largestWord ='' # create a string
for i in x: #looping to find out the largest number in list
if len(i) > len(largestWord):
largestWord=i
#checking if length of a word if more then next word if yes then assign that word to largestWord if not then goto next word
print("Largest word in String:",largestWord)
#print the largest word which we get from for loop
main()
|
fcaf68afae031a902293ba1055aea7d80fb23e3e | chanheum/python_study | /알고리즘 기본/재귀/factorial(recursive_func).py | 226 | 3.984375 | 4 | def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(4))
print(factorial(5))
print(factorial(6))
|
53ea516c8f362c42de78f0250d2ac3d516c44993 | hrithiksagar/Competetive-Programming | /Python/Chapter 6 Conditional expressions/Practice set 1.py | 906 | 3.890625 | 4 | """
1. WAP to find greatest of four Numbers entered by user:
2. WAp to find out weather a student is pass or fail, iof it requires total 40% and atleast 33%
in each sub, to pass. Assume 3 Sub and take marks as an input from user
3. A spam comment is defined as a text contanising following keywords:
"Make a lot of money", "Buy now","Suscribe this", "Click this",
WAP to detect these spams
4. WAP to find wheater a given udername contains less than 10 characters or not
5. WAP which finds out wheater a given name is present in a list or not
"""
#1 sol
num1 = int(input("Enter Number 1: "))
num2 = int(input("Enter Number 2: "))
num3 = int(input("Enter Number 3: "))
num4 = int(input("Enter Number 4: "))
if num1>num4:
f1 = num1
else:
f1 = num4
if num2>num3:
f2 = num2
else:
f2= num1
if f1>f2:
print("Greatest number is: "f1)
else:
print("Greatest number is: "f2)
|
3d20ce52ba44167d704bb7f1720450e4ed2d8d17 | libaoming/python---lottery | /lottery.py | 690 | 3.8125 | 4 | import random
# menu
def menu():
user_enter = get_user_number()
lottery_number = create_lottery_numbers()
match_numbers = user_enter.intersection(lottery_number)
print("you got {}, you won ${}!".format(len(match_numbers),100**len(match_numbers)))
# User can pick 6 numbers
def get_user_number():
number_csv = input("enter 6 number, separated by commas: ")
number_list = number_csv.split(",")
integer_set = {int(num) for num in number_list}
return integer_set
# lottery calculate 6 random numbers (between 1 and 20)
def create_lottery_numbers():
values = set()
while len(values) < 6:
values.add(random.randint(1,20))
return values
menu()
|
33527cf4b2fbd20632614cc285252a4a053ab88d | marktheawesome/computer-programin-1 | /mad-lib/mad_lib.py | 4,798 | 3.890625 | 4 | import time
print("ready to playt Mad Libs?")
time.sleep(1)
print ('If you are readay press the Enter key')
input()
print(' Give me an adjective, plese ')
adjective = input()
print(' Now a noun ')
noun = input()
print(' I need a plural_noun. ')
plural_noun = input()
print(' How about a female in the room. ')
person_in_the_room_female = input()
print(' I need another adjective. ')
adjective_2 = input()
print(' Article of clothing? ')
article_of_clothing = input()
print(' A secound noun. ')
noun_2 = input()
print(' A city plese. ')
a_city = input()
print(' Another plural noun. ')
plural_noun_2 = input()
print(' Give me an adjective, plese ')
adjective_6 = input()
print(' Part of the body, plese. ')
part_of_the_body = input()
print(' Pick a letter fo the alphabet. ')
letter_of_the_alphabet = input()
print(' Name a clebrity. ')
celebrity = input()
print(' Plural noun, plese. ')
plural_noun_3 = input()
print(' One last adjective!!! ')
adjective_3 = input()
print(' What is your favorit place? ')
a_place = input()
print(" We're getting close. i can see it coming together. ")
time.sleep(3)
print(" Another part of the body ")
part_of_the_body_2 = input()
print(' I lied. More adjectives!!!!!!!!! ')
adjective_4 = input()
print('Honestly last adjective.')
adjective_5 = input()
print(' verb? ')
verb = input()
print(' Plural noun. ')
plural_noun_4 = input()
print(' Last I need a number. ')
number = input()
#print(' there are many ')
#+ adjective +
#' ways to choose a '
#+ noun +
#'to read. First, you could ask for recommendations from you friends and '
#+ plural_noun +
#". Just don't ask Aunt"
#+ person_in_the_room_female +
#" - She only reads "
#+ adjective_2 +
#' books with '
#+ article_of_clothing +
#'-ripping goddesses on the cover. If your friends and family are no help, try checking out the '
#+ noun_2 +
#"Review in the "
#+ a_city +
#"times. if the "
#+plural_noun_2 +
#"featured there are too "
#+ adjective_6 +
#"for your taste, try something a little more low-"
#+ part_of_the_body +
#", like "
#+ letter_of_the_alphabet +
#': The'
#+ celebrity +
#'magazing, or'
#+ plural_noun_3 +
#'Magazie. You could aslo choose a book the '
#+ adjective_3 +
#'-fashioned way. Head to your local libary or '
#+ a_place +
#"and bowse the shelves until something catches your "
#+ part_of_the_body_2 +
# ". Or, you could save yourdelf a whole lot of "
# + adjective_4 +
# 'trouble and log on to www.bookish.com, the '
# + adjective_5 +
# 'new website to '
# + verb +
# "for books! With all the time you'll sve not having to search for "
# + plural_noun_4 +
# ",you can read "
# + number+
# "more books!"
time.sleep(1.2)
print('I will need some time to put this together.')
time.sleep(5)
print('There are many ' + adjective + ' ways to choose a ' + noun + ' to read.')
print("First, you could ask for recommendations from you friends and " + plural_noun + ".")
print("Just don't ask Aunt " + person_in_the_room_female + " - She only reads " + adjective_2 + ' books with ' + article_of_clothing + '-ripping goddesses on the cover.')
print('If your friends and family are no help, try checking out the ' + noun_2 + " review in the " + a_city + " times.")
print('If the ' + plural_noun_2 + " featured there are too " + adjective_6 + " for your taste, try something a little more low- " + part_of_the_body + ", like " + letter_of_the_alphabet + ': The ' + celebrity + ' magazing, or ' + plural_noun_3 + ' Magazie. ')
print('You could aslo choose a book the ' + adjective_3 + '-fashioned way.')
print('Head to your local libary or ' + a_place + " and bowse the shelves until something catches your " + part_of_the_body_2 + '.')
print("Or, you could save yourdelf a whole lot of " + adjective_4 + 'trouble and log on to www.bookish.com, the ' + adjective_5 + 'new website to ' + verb + "for books!")
print("With all the time you'll sve not having to search for " + plural_noun_4 + ",you can read " + number+ " more books!")
time.sleep(30)
print("Did you like the game? On a scale of 1-5 five being the best what would you give?")
rating = input()
if rating == '5':
print("Glade you really enjoyed it. Thank you!")
elif rating =='4' :
print ("Glade you enjoyed it. Thank you for playing!")
elif rating == '3':
print("Thank you for playing, good luck with your project.")
elif rating == '2':
print("thank you for your honesty. I'll do better next time")
elif rating =='1':
print("I didnt think it was that bad. You are just jealous.")
else:
print ("you can't follow simple directions. pick a number 1,2,3,4,5. That's it.I don't even trust you DON'T try agian!")
|
566798cc310b460e5a14b42bb65edfb5b2e2884c | BenjaminStanelle/Basic-Python-Operations | /num.py | 726 | 3.890625 | 4 | #Benjamin Stanelle 1001534907
def main():
my_List=[]
num_Elements= int(input("Enter the number of elements in the list: "))
for x in range(num_Elements):
value= float(input("Enter a new element for the list: "))
my_List.append(value)
print("Original List: ",my_List)
min=my_List[0]
max=my_List[0]
total=0
average=0
for x in my_List:
if x < min:
min=x
if x > max:
max=x
total+= x
average=total/len(my_List)
print("The min is: ",format(min, '.2f'))
print("The max is: ",format(max, '.2f'))
print("The total is: ",format(total, '.2f'))
print("The average is: ",format(average, '.2f'))
main() |
7b935097494ff1af70c6fffaa3de067d86ff0c72 | VimalMinsariya/euler-project | /math/grad_turtle.py | 454 | 3.84375 | 4 | import turtle
import sys
print(sys.version) #한글은 문제 없지요
turtle.setworldcoordinates(0,-2560,2560,0)
bob = turtle.Turtle()
bob.speed(0)
turtle.colormode(255)
bob.right(90)
for r in range(255):
bob.setposition(0,-r * 10)
for g in range(255):
bob.color(r,g,0)
bob.setx(g*10)
bob.begin_fill()
for i in range(4):
bob.forward(10)
bob.right(90)
bob.end_fill()
turtle.done()
|
5591269eefe68078c0ff327cb1ea6da3f807f133 | Trietptm-on-Coding-Algorithms/prog | /python/python_features/src/algorithms/sorting_algorithms.py | 1,219 | 3.953125 | 4 | import random
import sys
"""
Function listing
cli()
gen_list(size, range_of_numbers)
execute_sort(selection_name)
void()
usage()
"""
def bubble_sort(list_of_numbers):
index = 0
is_sorted = False
length = len(list_of_numbers)
def swap(a,b):
list_of_numbers[a], list_of_numbers[b] = (list_of_numbers[b], list_of_numbers[a])
while index != length-1:
if list_of_numbers[index] > list_of_numbers[index+1]:
swap(index,index+1)
index = 0
else:
index += 1
return list_of_numbers
def gen_list(size, range_of_numbers):
if size < 1:
raise Exception("Size of numbers is less than 1")
if range_of_numbers < 1:
raise Exception("Size of range is less than 1")
list_of_numbers = []
while len(list_of_numbers) != size:
list_of_numbers.append( random.randint(0,range_of_numbers) )
return list_of_numbers
def execute_sort(selection):
if selection == "bubble":
return bubble_sort
else:
print("Sort Selection not found.")
return void
|
49c8c5504bf0d1932ef3f7b3a294e7577fd1be7b | antoni-g/programming-dump | /vgg/manhattan.py | 875 | 4.25 | 4 | # The following method get the manhatten distance betwen two points (x1,y1) and (x2,y2)
def manhattan_distance(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
def convert(l):
try:
l[0] = float(l[0])
l[1] = float(l[1])
except ValueError:
print("An input character was not a number.")
exit()
# Enter your code here. Read input from STDIN. Print output to STDOUT
point1AsAString = input().strip()
point2AsAString = input().strip()
# Need to parse each point and find the distance between them using the supplied manhattan_distance method
l1=point1AsAString.split(" ")
l2=point2AsAString.split(" ")
# verify
if (len(l1) != 2 or len(l2) != 2):
print ("Invalid number of arguments for coordinates. Need x and y space separated with one point per line")
exit()
#convert and verify
convert(l1)
convert(l2)
print(manhattan_distance(l1[0],l1[1],l2[0],l2[1]))
|
4e433635c064fb9dd08a39ebc491d1396eaaf543 | mzfr/Competitive-coding | /Arrays/search-in-sorted-matrix/solution1.py | 676 | 3.8125 | 4 | mat = [ [10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50] ]
def bin_search(arr,low, high, x):
"""recursive function for binary search
"""
if high>= low:
mid = (low+high)//2
if arr[mid] == x:
return mid
if x < arr[mid]:
return bin_search(arr, low, mid-1, x)
if x > arr[mid]:
return bin_search(arr, mid+1, high, x)
else:
return -1
x = 39 # Element to find
i = 0
for row in mat:
find = bin_search(row, 0, len(row)-1, x)
if find == -1:
i += 1
else:
print("Element at %d %d" % (i+1, find+1))
break
|
e83d43f4f1e3e4dc7e0a4434ee3b827c23330f87 | elobejko/fcc-arithmetic-formatter | /arithmetic_arranger.py | 1,414 | 3.84375 | 4 | def arithmetic_arranger(problems, print_res = False):
if(len(problems) > 5):
return "Error: Too many problems."
firstLine = ""
secondLine = ""
thirdLine = ""
space = " "
count = 0
resultsLine = ""
r = 0
for problem in problems:
eq = problem.split()
count +=1
#Only + and - operators are accepted
if (eq[1] == "*" or eq[1] == "/"):
return "Error: Operator must be '+' or '-'."
#Number cannot be longer than four digits
if(len(eq[0]) > 4 or len(eq[2]) > 4):
return "Error: Numbers cannot be more than four digits."
#No spaces after last problem
if(count == len(problems)):
space = ""
#Number can contain inly digits
try:
x = int(eq[0])
y = int(eq[2])
except ValueError:
return "Error: Numbers must only contain digits."
#Calculate results
if print_res:
if(eq[1]== "+"):
r = x + y
else:
r = x - y
maxlen = max(len(eq[0]), len(eq[2]))
firstLine = firstLine + eq[0].rjust(maxlen + 2) + space
secondLine = secondLine + eq[1] + eq[2].rjust(maxlen + 1) + space
thirdLine = thirdLine + (maxlen + 2) * "-" + space
resultsLine = resultsLine + str(r).rjust(maxlen + 2) + space
arranged_problems = firstLine + "\n" + secondLine + "\n" + thirdLine
if print_res:
arranged_problems = arranged_problems + "\n" + resultsLine
return arranged_problems |
af6b07c5b6fa839531397e767d3e8d8694c061e4 | NichHarris/leet-code | /stringMult.py | 1,388 | 3.9375 | 4 | # https://leetcode.com/problems/multiply-strings/submissions/
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
product = int(num1)*int(num2)
return str(product)
# OR
# # https://leetcode.com/problems/multiply-strings/submissions/
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# product = int(num1)*int(num2)
# return str(product)
numbers = { "0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9}
num1Int = num2Int = i = j = 0
for char in num1:
if (len(num1) - i) == 1:
num1Int += numbers[char]
else:
num1Int += numbers[char]*pow(10,(len(num1)-1-i))
i += 1
for char in num2:
if (len(num2) - j) == 1:
num2Int += numbers[char]
else:
num2Int += numbers[char]*pow(10,(len(num2)-1-j))
j += 1
return str(num1Int*num2Int) |
9dcc589ddaba8570a623246818ccbc5f957c086a | Larkiskek/Astro | /botton.py | 4,597 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 13:55:48 2020
@author: Филипп
"""
import pygame as pg
pg.init()
class Botton():
"""Класс кнопки.
"""
def __init__(self, screen, coords, width, height, color, text):
self.screen = screen
"""Холст, на котором размещается кнопка."""
self.coords = coords
"""Координаты верхнего левого угла кнопки на экране."""
self.height = height
"""Высота кнопки."""
self.width = width
"""Ширина кнопки."""
self.color = color
"""Цвет кнопки."""
self.text = text
"""Текст кнопки."""
self.font = pg.font.SysFont("dejavusansmono", 25)
"""Шрифт текста кнопки."""
def draw(self):
"""Функция, отрисовывающая кнопку.
"""
ltop_corner = (self.coords[0] - int(self.width / 2),
self.coords[1] - int(self.height / 2))
pg.draw.rect(self.screen, self.color, (ltop_corner[0], ltop_corner[1],
self.width, self.height))
botton_text = self.font.render(self.text, True, (255, 255, 255))
self.screen.blit(botton_text, (ltop_corner[0], self.coords[1]))
def click(self, mouse_coord):
"""
Функция, регистрирующая нажатие на кнопку.
Parameters
----------
mouse_coord : list
Координаты мыши при щелчке.
Returns
-------
bool
Произошло ли нажатие на кнопку.
"""
if (mouse_coord[0] >= self.coords[0] - self.width / 2) & (
mouse_coord[0] <= self.coords[0] + self.width / 2) & (
mouse_coord[1] >= self.coords[1] - self.height / 2) & (
mouse_coord[1] <= self.coords[1] + self.height / 2):
return True
else:
return False
class Botton_image():
"""Класс кнопки. Использует изображение для отображения кнопки.
"""
def __init__(self, screen, coords, filename, botton_form):
self.screen = screen
"""Холст, на котором размещается кнопка."""
self.image = pg.image.load(filename).convert_alpha()
"""Изображение кнопки."""
self.coords = coords
"""Координаты верхнего левого угла изображения кнопки на экране."""
self.rad = self.image.get_width()/2
"""Радиус кнопки, если она круглая."""
self.width = self.image.get_width()
"""Ширина кнопки."""
self.height = self.image.get_height()
"""Высота кнопки."""
self.botton_form = botton_form
"""Форма кнопки: круглая или прямоугольная."""
def draw(self):
"""Функция, отрисовывающая кнопку.
"""
self.rect = self.image.get_rect(center=(self.coords[0], self.coords[1]))
self.screen.blit(self.image, self.rect)
def click(self, mouse_coord):
"""
Функция, регистрирующая нажатие на кнопку.
Parameters
----------
mouse_coord : list
Координаты мыши при щелчке.
Returns
-------
bool
Произошло ли нажатие на кнопку.
"""
if self.botton_form == "circle":
if (mouse_coord[0] - self.coords[0])**2 + (mouse_coord[1] - self.coords[1])**2 <= self.rad**2:
return True
else:
return False
if self.botton_form == "rect":
if (mouse_coord[0] >= self.coords[0] - self.width / 2) & (
mouse_coord[0] <= self.coords[0] + self.width / 2) & (
mouse_coord[1] >= self.coords[1] - self.height / 2) & (
mouse_coord[1] <= self.coords[1] + self.height / 2):
return True
else:
return False
|
9137fdc6ea3c62947f299d4a9738eb07979921a1 | sergiogbrox/guppe | /Seção 5/exercicio09.py | 175 | 3.78125 | 4 | sal = float(input("Salário: "))
emp = float(input("Empréstimo: "))
if emp > sal*20/100:
print('Empréstimo não concedido.')
else:
print('Empréstimo concedido.')
|
16408f816740635a8149f24b257fe29c401f0790 | vinay26-01/python | /search in lists.py | 300 | 3.5 | 4 | def search(n,data,s):
c=0
for i in range(n):
if data[i]==s:
c+=1
if c==2:
return i
else:
return False
n=int(input())
data=list(map(int,input().split()))
s=int(input())
search=search(n,data,s)
print(search)
|
baa226d19742480c225965a16e51e6faaaefc216 | carloxlima/curso_python | /exercicio031.py | 426 | 3.734375 | 4 | km = float(input("Digite a distancia da sua viagem em KM : "))
media= 200
preço1= 0.50
preço2= 0.45
print("O valor da sua viagem é de {} reias.".format(km * preço1) if km <= media else "O valor da sua viagem é de {:.2f} reias.".format(km * preço2))
if km <= media:
print("O valor da sua viagem é de {} reias.".format(km * preço1))
else:
print("O valor da sua viagem é de {:.2f} reias.".format(km * preço2)) |
ac1362c79177c1ebb9ff18a37e8614f7bf2b90e1 | aidardarmesh/leetcode | /Problems/112. Path Sum.py | 1,034 | 3.859375 | 4 | from typing import *
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
stack = []
stack.append((root, sum))
res = False
while stack:
node, sum = stack.pop()
sum -= node.val
if not node.left and not node.right:
res = res or sum == 0
if node.right:
stack.append((node.right, sum))
if node.left:
stack.append((node.left, sum))
return res
s = Solution()
a = TreeNode(5)
a.left = TreeNode(4)
a.right = TreeNode(8)
a.left.left = TreeNode(11)
a.right.left = TreeNode(13)
a.right.right = TreeNode(4)
a.left.left.left = TreeNode(7)
a.left.left.right = TreeNode(2)
a.right.right.right = TreeNode(1)
assert s.hasPathSum(a, 22) == True |
4ba4f4b547b3d2b3cec78ea8e693a8f15bca1340 | parasshaha/Python- | /manualfromkeys.py | 637 | 3.75 | 4 | def fromkeysss(input_dict,output_dict_values):
result_dict={}
keys_list=[]
if type(output_dict_values)==list or type(output_dict_values)==tuple:
keys_list=input_dict.keys()
values_length=len(output_dict_values)
for i in range(len(keys_list)):
if i < values_length:
result_dict[keys_list[i]]=output_dict_values[i]
else:
result_dict[keys_list[i]]=None
else:
result_dict=dict.fromkeys(input_dict,output_dict_values)
return result_dict
def main():
d={1:2,2:3,4:5}
z=input("Enter the value for updating or creating new dictionary")
outt=fromkeysss(d,z)
print d
print outt
if __name__ == '__main__':
main()
|
5d5ceb211550f6975c1cb5b168f94bf5e44dccd6 | Zerl1990/python_algorithms | /problem_solving/cracking_the_code_interview/trees_graphs/tree_node.py | 660 | 3.921875 | 4 | import os
import sys
class TreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
if not self.left and not self.right:
return str(self.value)
string = str(self.left)
string = string + '-' + str(self.value) + '-'
string = string + str(self.right)
return string
# Root
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
# Second childs
it = root.left
it.left = TreeNode(4)
it.right = TreeNode(5)
it = root.right
it.left = TreeNode(6)
it.right = TreeNode(7)
|
5d0ac8f59a7e6f4605ceb95ac30686dc3c20a398 | brookebon05/OOP_Work | /CarClass.py | 409 | 3.65625 | 4 | class Car:
def __init__(self, year1, make1):
self.__year_model = year1
self.__make = make1
self.__speed = 0
def accelerate(self):
self.__speed += 5
# return print("Speed was set to: ", self.__speed)
def brake(self):
self.__speed -= 5
# return print("Speed was set to: ", self.__speed)
def get_speed(self):
return self.__speed
|
7487dbffe552e370c2332e48cba5ffce34b1092f | SORARAwo4649/Learning_EffectivePython | /Section1/Item4.py | 2,082 | 3.78125 | 4 | # Cスタイルフォーマット文字列とstr.formatは使わずf文字列で埋め込む
print('Cスタイルフォーマットによる記述')
# 2進数と16進数を整数文字列に変換-Cスタイルフォーマット
# ※非推奨
a = 0b10111011
b = 0xc5f
print('Binary is %d, hex is %d' % (a, b))
print('###############################')
# 組み込みのformatとstr.format
print('組み込みformatによる記述')
# 数値を3桁で区切る、小数点第2位までにする
a = 1234.5678
formatted = format(a, ',.2f')
print(formatted)
# センタリング
b = 'my string'
formatted = format(b, '^20s')
print('*', formatted, '*')
# 複数の値をまとめてフォーマットする
key = 'my_var'
value = 1.234
formatted = '{} = {}'.format(key, value)
print(formatted)
print('###############################')
# フォーマット済み文字列 ※推奨
print('フォーマット済み文字列による記述 ※推奨')
key = 'my_var'
value = 1.234
formatted = f'{key} = {value}'
print(formatted)
# f-stringのブレースホルダ
formatted = f'{key!r:<10} = {value:.2f}'
print(formatted)
'''
・Cスタイルフォーマットの問題2
文字列にフォーマットする前に値を修正しないといけない場合に、
読んで理解するのが難しいこと(p12)
'''
# f-stringによる問題2の解決
pantry = [
('avocados', 1.25),
('bananas', 2.5),
('cherries', 15)
]
for i, (item, count) in enumerate(pantry):
# Cスタイルフォーマット
old_style = '#%d: %-10s = %d' % (
i + 1,
item.title(),
round(count)
)
print(f'old_style = {old_style}')
# 組み込みformat
new_style = '#{}: {:<10s} = {}'.format(
i+1,
item.title(),
round(count)
)
print(f'new_style = {new_style}')
# f-string
f_string = f'#{i+1}: {item.title():<10s} = {round(count)}'
print(f'f_string = {f_string}')
print('#####')
# assert 条件式, 条件式がFalseの場合に出力するメッセージ
assert old_style == new_style == f_string
|
c2bef44b115c0f3dabc9f4a0374f7a82d31c83bb | Heroinblackberry/Blackberry3 | /Python/2.py | 227 | 3.90625 | 4 | def StrRevers(string):
index = len(string);
output = "Output:";
output = output + str(sorted(string));
print output;
print u'These Numbers will be in ascending order.';
input_st = raw_input();
StrRevers(input_st); |
3a1180d1384b9e6cf6d65d34a835aa44f649dd36 | KodeBlog/Python-3 | /06-tuples/app.py | 1,359 | 3.609375 | 4 | attributes = ('id','name','username','email','password')
print(type(attributes))
print(attributes)
#Code commented because it raises an exception
"""attributes = ('id','name','username','email','password')
attributes[3] = 'created_at'"""
attributes = ('id','name','username','email','password')
attr = list(attributes)
attr[3] = 'created_at'
attributes = tuple(attr)
print(type(attributes))
print(attributes)
attributes = ('id','name','username','email','password')
print(f'the second item is {attributes[1]}')
attributes = ('id','name','username','email','password')
#Code commented because it raises an exception
"""print(f'the second item is {attributes[9]}')"""
attributes = ('id','name','username','email','password')
print('created_at' in attributes)
attributes = ('id','name','username','email','password')
for attribute in attributes:
print(attribute)
values = ('1','Natasha','katie','[email protected]')
(id,name,username,email) = values
print('user details\n')
print(f'id: {id}')
print(f'name: {name}')
print(f'username: {username}')
print(f'email: {email}')
values = ('1','Natasha','katie','[email protected]')
print(len(values))
letters = ('alef','bet','gimel','dalet','he','vav','zayin','chet','tet','yod','kaf')
print('the original tuple is ')
print(letters)
print('the sorted tuple is')
letters = tuple(sorted(letters))
print(letters) |
be17fbce400b8fd59f7df88a2df6d83a8b96ba07 | dongho108/CodingTestByPython | /boostcamp/ex/hash/1.py | 342 | 3.59375 | 4 | def solution(participant, completion):
answer = ''
participant.sort()
completion.sort()
# print(participant, completion)
for i in range(len(completion)):
if participant[i] != completion[i]:
return participant[i]
return participant[-1]
print(solution(["leo", "kiki", "eden"], ["eden", "kiki"])) |
0b5d86b64acb7fa7f46ca6bdd2ba74c71c959126 | legoyda/pythontutorexrss | /Площа прям трикутника.py | 222 | 3.6875 | 4 | b = int(input('Ведіть довжину бічної сторони>>'))
h = int(input('Ведіть довжину висоти>>'))
s = 1/2*b*h
print('Площа прямокутного трикутника =',s) |
5c1e47e9dafcff4cc8b285436f3efc4b358213c3 | C-Begley/university_work | /first_year/Workspace/CS1PX/Unit 14/Lab Files/example3.py | 347 | 3.703125 | 4 |
import Tkinter
def display():
messageLabel.configure(text="Hello World!")
top = Tkinter.Tk()
messageLabel = Tkinter.Label(top,text="")
messageLabel.grid()
showButton = Tkinter.Button(top,text="Show",command=display)
showButton.grid()
quitButton = Tkinter.Button(top,text="Quit",command=top.destroy)
quitButton.grid()
Tkinter.mainloop()
|
648560dcc0e207768a37fe8798041752e661d961 | dynnah/LuizaCode | /Python-Exercises/desafio04-loop.py | 239 | 4.09375 | 4 | for number in range(0,101):
if number%3 == 0 and number%5 == 0:
print("Dedezinha Querida")
elif number%3 == 0:
print("Dedezinha")
elif number%5 == 0:
print("Querida")
else:
print(f"{number}") |
4d0a317fca5f1f5a099241689734a6ad3ed3f6f0 | kmad1729/python_notes | /metaprogramming/practice_code/code_1.py | 1,995 | 3.90625 | 4 | 'very basic building blocks in code'
delim = '*' * 20
class A:
def method1(self, *args):
print("this is method1")
print("the are args ", args)
def print_foo(self):
print("foo")
def uppercase_all(*args):
print('args -->', args)
return list(map(str.upper, args))
def func_with_default_kwargs(x, debug = False, names = None):
print('x -->', x)
print('debug -->', debug)
print('names -->', names)
return "This is what i return! from func_with_default_kwargs"
def func_with_star_args(*args, **kwargs):
print('args is a tuple of position args -->', args)
print("kwargs is dict of keyword args -->", kwargs)
def func_python3_with_star(x, y, *, block = True):
print("you cannot call this function with positional kwarg")
print("x --> ", x)
print("y --> ", y)
print("block --> ", block)
######
print(delim)
print("this is a standalone statement")
print(delim)
a = A()
a.method1('hi','hello',1,3)
print(delim)
print(uppercase_all('foo', 'FO.{}DAScc'))
print(delim)
print(func_with_default_kwargs(10))
print(func_with_default_kwargs(10, names = 'ram raavan rahim'.split()))
print(func_with_default_kwargs(11, debug = True, names = 'foo bar'.split()))
print(delim)
func_with_star_args(10, 20, 30, 40, a = 1, b = 2, c = 3)
print(delim)
args1 = (1, 3, 5, 7, 9)
kwargs1 = {'x' : 24, 'y' : 25, 'z' : 26}
func_with_star_args(*args1, **kwargs1)
print(delim)
print("only in python3, '*' in arguments")
func_python3_with_star(y = 20, x = 10, block = 'foo')
try:
print("calling function with block as positional arg!!")
func_python3_with_star(10, 20, 30)
except TypeError as e:
print("called the function with block as positional argument, got this exception -->")
print('{', e, '}')
print(delim)
def sum_with_start(*args, initial_sum = 20):
return initial_sum + sum(args)
print(sum_with_start(*range(10)))
print(sum_with_start(*range(10), initial_sum = 0))
s = sum_with_start(*range(10))
print(delim)
|
be0bf4e5ff576bc9014c19b7aab9a858be8e5cfc | ybarros7/AgendaADS | /funcoes.py | 2,330 | 4 | 4 | import csv
# Mensagem de Bem Vindo e Opcoes ao Usuario
def bemvindo():
print('\n')
print("Bem Vindo a Agenda")
print("Selecione uma Opcao")
print("1 Adicionar um novo contato")
print("2 Listar os contatos da agenda")
print("4 Para procurar contatos na agenda")
print("5 Remover um contato")
print("9 Para encerrar programa")
# Funcoes do processo
def adicionar():
print("Adicionar um registro")
agenda = open("agendatelefonica.csv", 'a')
nome = input("Nome do Contato:")
telefone = input("Digite o telefone:")
print("Contato salvo com nome:", nome, " e numero", telefone)
agenda.write(nome)
agenda.write(",")
agenda.write(telefone)
agenda.write("\n")
agenda.close()
def deletar():
with open("agendatelefonica.csv") as agenda:
reader = csv.reader(agenda, delimiter=',')
lista = list(reader)
listar(0)
nome = str("")
while nome not in ([row[0] for row in lista]):
nome = input("Digite o nome do contato que você deseja deletar: ")
lista.pop([row[0] for row in lista].index(nome))
with open("agendatelefonica.csv", "w", newline="") as f:
writer = csv.writer(f)
for row in lista:
writer.writerow(row)
print("Contato removido")
nome = input("\n Pressione qualquer tecla para continuar: ")
def listar(x):
print("Lista de Contatos")
print("[Nome][Telefone]")
with open("agendatelefonica.csv") as agenda:
reader = csv.reader(agenda)
lista = list(reader)
for row in reader:
print("Nome : {} >>>>>> Telefone: {}".format(row[0],row[1]))
print("Listado correctamente")
if x==1:
a = input("\n Digite qualquer tecla para continuar: ")
return len(lista)
def falha():
print("Opcao Incorreta")
def buscar():
name = input("Digite o nome para procurar: ")
with open("agendatelefonica.csv") as agenda:
reader = csv.reader(agenda, delimiter=',')
test = None
for row in reader:
if name in row:
test = ("Nome: {} >>>>>> Telefone {} ".format(row[0], row[1]))
if test is not None:
print(test)
else:
print("Contato não encontrato")
name = input("\n Pressione qualquer tecla para continuar.")
|
611c7f5b12f729cfd095784cdd044bca2fc19041 | ctc316/algorithm-python | /Lintcode/Ladder_37_BB/medium/59. 3Sum Closest.py | 888 | 3.796875 | 4 | class Solution:
"""
@param numbers: Give an array numbers of n integer
@param target: An integer
@return: return the sum of the three integers, the sum closest target.
"""
def threeSumClosest(self, numbers, target):
n = len(numbers)
if n < 3:
return
numbers.sort()
closest = 0
distance = float("inf")
for i in range(n - 2):
remain = target - numbers[i]
left = i + 1
right = n - 1
while left < right:
dist = remain - numbers[left] - numbers[right]
if abs(dist) < distance:
distance = abs(dist)
closest = numbers[i] + numbers[left] + numbers[right]
if dist > 0:
left += 1
else:
right -= 1
return closest |
2d07a7742bb6b3a1b9eef1b40b37959e4711c480 | sbacchus91/compound-interest | /sbacchus_hw_5_15_5.py | 2,346 | 3.78125 | 4 | """
Shane Bacchus
Class: CS 521 - Fall 1
Date:10/10
Homework Problem # 5
Description of Problem (just a 1-2 line summary!):
Compound interest recursive and nonrecursive implementation
"""
def calc_compound_interest(principal_float,interest_float,years):
"""Future Value Calculated Non-Recursively"""
final_calculation = principal_float*(interest_float)**years
return final_calculation
def calc_compound_interest_recursive(principal_float, interest_float, years):
"""Future Value Calculated Recursively"""
if years == 0:
return principal_float
else:
return calc_compound_interest_recursive(principal_float * interest_float, interest_float, years-1)
if __name__ == "__main__":
while True:
try:
principle = input("Please enter your principle (no commas): ")
interest = input("Please enter your interest rate per year: ")
years = input("Please enter the number of years to calculated the compound interest: ")
# Check if conversions work, else go to except
principle_float = float(principle)
interest_float = float(interest)
final_interest_float = 1+(interest_float/100.0)
years = int(years)
non_recursive_return = calc_compound_interest(principle_float,final_interest_float,years)
print("Non-Recusrive Ending Value is {:,.2f}".format(non_recursive_return))
recursive_return = calc_compound_interest_recursive(principle_float, final_interest_float, years)
print("Recusrive Ending Value is {:,.2f}".format(recursive_return))
# Check if both returns rounded to 4 are equal
non_recursive_return_rounded = round(non_recursive_return,4)
recursive_return_rounded = round(recursive_return,4)
if non_recursive_return_rounded == recursive_return_rounded:
print("Both function outputs are equal when rounded to 4 decimal points")
else:
print("Both function outputs are not equal when rounded to 4 decimal points")
break
except ValueError: print("You did enter the expected values. Please enter again") |
6aa12b355a09b9d9e850f8fbf4cfa04428272b0a | 0x000613/Outsourcing | /Python/2020-06-04-문자열뒤집기/reverse.py | 96 | 4.03125 | 4 | s = str(input())
s_reverse = ''
for char in s:
s_reverse = char + s_reverse
print(s_reverse) |
9e0446fe563f92ace3773b2584917f994c495156 | Samuel2402/python-demo | /Practice/attributes_practice/class_example_2.py | 1,479 | 3.796875 | 4 | ### Actuall ###
class Student():
class_ = "student"
def __init__(self,name,age,test_1,test_2,test_3):
self.name = name
self.age = age
self.test_1 = test_1
self.test_2 = test_2
self.test_3 = test_3
def calcaverage(self):
return int((self.test_1 + self.test_2 + self.test_3)/3)
John = Student("John","24", 78, 65, 82)
print(John.calcaverage())
#class Student():
# def __init__(self,name,age,test_1,test_2,test_3):
# self.name = name
# self.age = age
# self.test_1 = test_1
# self.test_2 = test_2
# self.test_3 = test_3
#class john(Student):
# def __init__(self,test_1,test_2,test_3):
# Student.__init__(self)
# self.test_1 = test_1
# self.test_2 = test_2
# self.test_3 = test_3
#john = Student("John", '24', '33', '45', '42')
#jane = Student("jane", '25', '43', '44', '40')
#jack = Student("Jack", "27", '40', '37', '35')
#john_test1 = int(getattr(john, "test_1"))
#john_test2 = int(getattr(john, 'test_2'))
#john_test3 = int(getattr(john, 'test_3'))
#john_total_score = john_test1 + john_test2 + john_test3
#john_avg_total_score = (john_total_score)/3
#print(int(john_avg_total_score))
#test_1 = int(input("Enter test-1 score: " ))
#test_2 = int(input("Enter test-2 score: " ))
#test_3 = int(input("Enter test-3 score: " ))
#print(setattr(john, "age", '35'))
#print(getattr(john, 'age'))
#print(hasattr(john, "address"))
|
0fead01ff50a3b933e0ded597f607a377d08960c | iheb1919/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 272 | 3.578125 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
if my_list and type(my_list) == list:
scores, weights = 0, 0
for score, weight in my_list:
scores += score * weight
weights += weight
return scores/weights
return 0
|
a4b55e94244227ef003bdb3c40f9ab3d6f1218b4 | RahulRao23/tic-tac-toe | /program.py | 13,177 | 3.890625 | 4 | from tkinter import *
root = Tk()
root.geometry('900x900')
# frame for the game board
frame = LabelFrame(root, borderwidth=4, bg='#EA7773')
frame.grid(row=1, column=1,padx=20, pady=20, sticky=N)
# frame for the options
frame_options = LabelFrame(root, borderwidth=4, bg='#EA7773')
frame_options.grid(row=1, column=2,padx=20, pady=20)
r = IntVar()
players = 1 # If players = 1 then X's turn or O's turn
tracker = [None] * 9 # Array to store values
rounds = 0 # Keeps count of the rounds completed
p1_points = 0 # Player 1 points
p2_points = 0 # Player 2 points
# function to change player after each turn
def change_player():
global players
if players == 1:
players = 0
label_turn = Label(root, text='Player 2 turn', font=('bold', 15), bg='#AE1438', fg='white', padx=20, pady=20)
label_turn.grid(row=0, column=1, padx=20, pady=20)
else:
players = 1
label_turn = Label(root, text='Player 1 turn', font=('bold', 15), bg='#AE1438', fg='white', padx=20, pady=20)
label_turn.grid(row=0, column=1, padx=20, pady=20)
# function to decide the winner of the game and print it in the window
def winner():
if rounds < r.get():
start()
else:
if p1_points > p2_points:
winner_label = Label(root, text='PLAYER 1 WINS THE GAME', font=('Bold', 25), padx=20, pady=20)
winner_label.grid(row=3, column=1, padx=20)
label = Label(root, text='Don\'t forget to reset scores before starting the next game', font=('Bold', 15), padx=20, pady=20)
label.grid(row=4, column=1, padx=20)
elif p1_points < p2_points:
winner_label = Label(root, text='PLAYER 2 WINS THE GAME', font=('Bold', 25), padx=20, pady=20)
winner_label.grid(row=3, column=1, padx=20)
label = Label(root, text='Don\'t forget to reset scores before starting the next game', font=('Bold', 15), padx=20, pady=20)
label.grid(row=4, column=1, padx=20)
elif p1_points == p2_points:
winner_label = Label(root, text='DRAW MATCH', font=('Bold', 25), padx=20, pady=20)
winner_label.grid(row=3, column=1, padx=20)
label = Label(root, text='Don\'t forget to reset scores before starting the next game', font=('Bold', 15), padx=20, pady=20)
label.grid(row=4, column=1, padx=20)
button_1 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_2 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_3 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_4 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_5 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_6 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_7 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_8 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_9 = Button(frame, text='', font=('Bold', 10), bg='red', width=10, height=4, borderwidth=2, padx=20, pady=20, state='disabled')
button_1.grid(row=0, column=0, padx=(20, 5), pady=(20, 5))
button_2.grid(row=0, column=1, padx=5, pady=(20, 5))
button_3.grid(row=0, column=2, padx=(5, 20), pady=(20, 5))
button_4.grid(row=1, column=0, padx=(20, 5), pady=5)
button_5.grid(row=1, column=1, padx=5, pady=5)
button_6.grid(row=1, column=2, padx=(5, 20), pady=5)
button_7.grid(row=2, column=0, padx=(20, 5), pady=(5, 20))
button_8.grid(row=2, column=1, padx=5, pady=(5, 20))
button_9.grid(row=2, column=2, padx=(5, 20), pady=(5, 20))
# function to decide the increment the points of the winner in each round
def conditions():
global p1_points, p2_points
if (tracker[0] == tracker[1] == tracker[2] == 1) \
or (tracker[3] == tracker[4] == tracker[5] == 1) \
or (tracker[6] == tracker[7] == tracker[8] == 1) \
or (tracker[0] == tracker[3] == tracker[6] == 1) \
or (tracker[1] == tracker[4] == tracker[7] == 1) \
or (tracker[2] == tracker[5] == tracker[8] == 1) \
or (tracker[0] == tracker[4] == tracker[8] == 1) \
or (tracker[2] == tracker[4] == tracker[6] == 1):
p1_points += 1
# print('player 1 points: '+ str(p1_points))
# print('player 2 points: '+ str(p2_points))
# print('total rounds done: '+ str(rounds))
# print('***********END***********')
winner()
elif (tracker[0] == tracker[1] == tracker[2] == 0) \
or (tracker[3] == tracker[4] == tracker[5] == 0) \
or (tracker[6] == tracker[7] == tracker[8] == 0) \
or (tracker[0] == tracker[3] == tracker[6] == 0) \
or (tracker[1] == tracker[4] == tracker[7] == 0) \
or (tracker[2] == tracker[5] == tracker[8] == 0) \
or (tracker[0] == tracker[4] == tracker[8] == 0) \
or (tracker[2] == tracker[4] == tracker[6] == 0):
p2_points += 1
# print('player 1 points: '+ str(p1_points))
# print('player 2 points: '+ str(p2_points))
# print('total rounds done: '+ str(rounds))
# print('***********END***********')
winner()
else:
for i in range(9):
if tracker[i] == None:
break
else:
if rounds < r.get():
# print('player 1 points: '+ str(p1_points))
# print('player 2 points: '+ str(p2_points))
# print('total rounds done: '+ str(rounds))
# print('***********END***********')
start()
else:
winner()
# function to display the entered value in the game board
def update(button, val):
if button == 1:
button_1 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_1.grid(row=0, column=0, padx=(20, 5), pady=(20, 5))
elif button == 2:
button_2 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_2.grid(row=0, column=1, padx=5, pady=(20, 5))
elif button == 3:
button_3 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_3.grid(row=0, column=2, padx=(5, 20), pady=(20, 5))
elif button == 4:
button_4 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_4.grid(row=1, column=0, padx=(20, 5), pady=5)
elif button == 5:
button_5 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_5.grid(row=1, column=1, padx=5, pady=5)
elif button == 6:
button_6 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_6.grid(row=1, column=2, padx=(5, 20), pady=5)
elif button == 7:
button_7 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_7.grid(row=2, column=0, padx=(20, 5), pady=(5, 20))
elif button == 8:
button_8 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_8.grid(row=2, column=1, padx=5, pady=(5, 20))
elif button == 9:
button_9 = Button(frame, text=val, font=('Bold', 44), bg='#A3CB37', width=3, borderwidth=2, padx=7, state='disabled')
button_9.grid(row=2, column=2, padx=(5, 20), pady=(5, 20))
# function to check current player
def click(players, button):
if players == 1:
tracker[button-1] = 1
# print(tracker)
update(button, 'X')
conditions()
change_player()
else:
tracker[button-1] = 0
# print(tracker)
update(button, 'O')
conditions()
change_player()
# function to create the game board
def start():
global rounds
# print('***********START***********')
# print('Total rounds: '+ str(r.get()))
rounds += 1
for i in range(9):
tracker[i] = None
button_1 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 1))
button_2 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 2))
button_3 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 3))
button_4 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 4))
button_5 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 5))
button_6 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 6))
button_7 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 7))
button_8 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 8))
button_9 = Button(frame, text='', font=('Bold', 10), bg='#A3CB37', width=10, height=4, borderwidth=2, padx=20, pady=20, command=lambda: click(players, 9))
button_1.grid(row=0, column=0, padx=(20, 5), pady=(20, 5))
button_2.grid(row=0, column=1, padx=5, pady=(20, 5))
button_3.grid(row=0, column=2, padx=(5, 20), pady=(20, 5))
button_4.grid(row=1, column=0, padx=(20, 5), pady=5)
button_5.grid(row=1, column=1, padx=5, pady=5)
button_6.grid(row=1, column=2, padx=(5, 20), pady=5)
button_7.grid(row=2, column=0, padx=(20, 5), pady=(5, 20))
button_8.grid(row=2, column=1, padx=5, pady=(5, 20))
button_9.grid(row=2, column=2, padx=(5, 20), pady=(5, 20))
# function to reset all the values before new game
def reset():
global p1_points, p2_points, rounds
rounds = 0
p1_points = 0
p2_points = 0
# Radiobuttons to select number of rounds in a game
Radiobutton(frame_options, text='1 rounds', variable=r, value=1, font=('bold', 20)).grid(row=0, column=0, padx=20, pady=10)
Radiobutton(frame_options, text='3 rounds', variable=r, value=3, font=('bold', 20)).grid(row=1, column=0, padx=20, pady=10)
Radiobutton(frame_options, text='5 rounds', variable=r, value=5, font=('bold', 20)).grid(row=2, column=0, padx=20, pady=10)
Radiobutton(frame_options, text='7 rounds', variable=r, value=7, font=('bold', 20)).grid(row=3, column=0, padx=20, pady=10)
# start button
option_btn = Button(frame_options, text='Start Game', font=('bold', 20), bg='#AE1438', fg='white', padx=20, pady=15, command=start)
# reset button
reset_btn = Button(frame_options, text='Reset Score', font=('bold', 20), bg='#AE1438', fg='white', padx=15, pady=15, command=reset)
option_btn.grid(row=4, column=0, padx=20, pady=10)
reset_btn.grid(row=5, column=0, padx=20, pady=10)
root.mainloop() |
21bb6650cc0049487c5b41f73dbdaf3cad2f9f28 | MariosTserpes/Azure-SparkCore-for-Data-Engineers | /joins_transforms.py | 3,366 | 3.59375 | 4 | '''
Filter & Join Transformations
'''
spark = pyspark.sql.SparkSession.builder.appName('DEng3').getOrCreate()
races_df = spark.read.parquet("races")\
.withColumnRenamed("name", "race_name")
circuits_df = spark.read.parquet("circuits")\
.filter("circuit_id < 70")\
.withColumnRenamed("name", "circuit_name")
races_filtered_df = races_df.filter(races_df["race_year"] == 2019) #pythonic way
#races_filtered_df = races_df.filter("race_year = 2019") #sequel way
race_circuits_df = circuits_df\
.join(races_df, circuits_df.circuit_id == races_df.circuit_id, "inner")\
.select(circuits_df.circuit_name, circuits_df.location, circuits_df.country, races_df.race_name, races_df.round)
'''
Outer joins: Left, Right, Full outer
'''
#Right Outer Join
race_circuits_df = circuits_df\
.join(races_df, circuits_df.circuit_id == races_df.circuit_id, "right")\
.select(circuits_df.circuit_name, circuits_df.location, circuits_df.country, races_df.race_name, races_df.round)
'''
Semi, Anti, Cross Joins
'''
#A. SEMI JOIN is very similar to inner join. So you will get the records which satisfy the condition on both tables.
#Hint: THE DIFFERENCE is that we are only given the columns from the left side of the join which is the left data frame
race_circuits_df = circuits_df\
.join(races_df, circuits_df.circuit_id == races_df.circuit_id, "semi")\
.select(circuits_df.circuit_name, circuits_df.location, circuits_df.country)
#B. ANTI JOIN is the opposite of Semi join. Will give you everything from the left table WHICH IS NOT FOUND on the right frame
#C. CROSS JOIN gives you a Cartesian Product.It is going to take every record from the left to the record joint on the right and will give you te product of the two.
#HINT: The difference is in the syntax: .croosJoin() instead of .join()
'''
Join Race and Results parquet
'''
drivers_df = spark.read.parquet("drivers")\
.withColumnRenamed("number", "driver_number")\
.withColumnRenamed("name", "driver_name")\
.withColumnRenamed("nationality", "driver_nationality")
constructors_df = spark.read.parquet("constructors")\
.withColumnRenamed("name", "team")
circuits_df2 = spark.read.parquet("circuits")\
.withColumnRenamed("location", "circuit_location")
races_df2 = spark.read.parquet("races")\
.withColumnRenamed("name", "race_name")\
.withColumnRenamed("race_timestamp", "race_date")
results_df = spark.read.parquet("results")\
.withColumnRenamed("time", "race_time")
races_circuits_df2 = races_df2\
.join(circuits_df2, circuits_df2.circuit_id == races_df2.circuit_id, "inner")\
.select(races_df2.race_id, races_df2.race_year, races_df2.race_name, circuits_df2.circuit_location)
race_results_df = results_df\
.join(races_circuits_df2, results_df.race_id == races_circuits_df2.race_id)\
.join(drivers_df, results_df.driver_id == drivers_df.driver_id)\
.join(constructors_df, results_df.constructor_id == constructors_df.constructor_id)
final_df = race_results_df.select(
"race_year", "race_name", "circuit_location", "driver_name",
"driver_number", "driver_nationality", "team", "grid", "fastest_lap",
"race_time", "points"
)\
.withColumn("created_date", pyspark.sql.functions.current_timestamp())
query_1 = final_df.filter("race_year == 2020 and race_name == 'Abu Dhabi Grand Prix'")\
.orderBy(final_df.points.desc()) |
a67fdc53d88b6ec548e1ac941a62961985f409d6 | TonyJenkins/python-workout | /31-pig-latin-translation-of-a-file/pig_latin_file.py | 574 | 3.78125 | 4 | #!/usr/bin/env python3
"""
Exercise 31: Pig Latin Translation of a File
Obfuscate a file using the simple "Pig Latin" rules.
"""
def pig_latin(word):
if word[0] in 'aeiou':
return word + 'way'
else:
return word[1:] + word[0] + 'way'
def pig_latin_file(filename):
with open(filename) as in_file:
return ' '.join(
[
pig_latin(word)
for line in in_file
for word in line.split()
])
if __name__ == '__main__':
print (pig_latin_file('rev_eli.txt'))
|
02239835f9a694af548dc728c4182752cb666f06 | D-HAC/solutions | /Fall-2016-17/week3_disemvoweler/disemvowel_lambda.py | 735 | 3.84375 | 4 | # Just does basic disemvoweling.
disemvowel = lambda s: ''.join([(lambda v: '' if v in 'aeiou' else v)(v) for v in list(s)])
# print(disemvowel('Yet another one line solution.'))
# Proper disemvoweling!
disemvowelWithVowels = lambda s: [''.join([(lambda v: '' if v in 'aeiou' else v)(v) for v in list(s)]), ''.join([(lambda v: v if v in 'aeiou' else '')(v) for v in list(s)])]
# [print(s) for s in disemvowelWithVowels('Yet another one line solution. Who said python had to be easy!')]
# But why not evaluate and print all in one line too?
[print(s) for s in (lambda s: [''.join([(lambda v: '' if v in 'aeiou' else v)(v) for v in list(s)]), ''.join([(lambda v: v if v in 'aeiou' else '')(v) for v in list(s)])])('Lambdas are fun!')]
|
bbe52c76145eb226791df544a29c72d92d195d83 | Bedrock02/Interview-Practice | /Array_Strings/permutations.py | 649 | 3.984375 | 4 | '''
Find all possible permuations
Approach
For every character in word
build
start collection with one character
for every other character possible
a + find_permutations(given_string - a)
b +
c +
d +
a
b
c
d
'''
def find_permutations(given_string):
collection = []
def get_permutations(input, prepend=''):
if len(prepend) == len(given_string):
collection.append(prepend)
return
for index, char in enumerate(input):
newInput = input[:index] + input[index+1:]
get_permutations(newInput, prepend=prepend + char)
get_permutations(given_string)
return collection
|
037f5896026fe6289fdf294721c312b21bfc7f86 | Jane11111/Leetcode2021 | /208.py | 1,076 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021-04-21 16:14
# @Author : zxl
# @FileName: 208.py
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root_dic = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
dic = self.root_dic
for s in word:
if s not in dic:
dic[s] = {}
dic = dic[s]
dic['end'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
dic = self.root_dic
for s in word:
if s not in dic:
return False
dic = dic[s]
return 'end' in dic
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
dic = self.root_dic
for s in prefix:
if s not in dic:
return False
dic = dic[s]
return True |
9e90eef62ca4da81201813f532e697d7785bc118 | Nateque123/python_tutorials | /chapter4_func/functions.py | 264 | 4 | 4 | # Function example
def add_two(a,b):
return a+b
num1 = int(input("Enter 1t number: "))
num2 = int(input("Enter 2nd number: "))
print(add_two(num1,num2))
# fname = input("Enter first name: ")
# lname = input("Enter last name: ")
# print(add_two(fname,lname)) |
c23ebaed2b0cad852a5ae734f452fe5b3e9e2d4f | KeKe115/Python_Practice | /func-let3.py | 315 | 3.734375 | 4 | # 引数に関数を要求する関数を定義
def calc_5_3(func):
return func(5, 3)
# 引数に掛け算を行う無名関数を指定する
result = calc_5_3( lambda a, b: a * b )
print(result)
# 引数に足し算を行う無名関数を指定する
result = calc_5_3( lambda a, b: a + b )
print(result)
|
cb8ef152d318d9ab1d17255895c3e26f0d8f0113 | Baljeet-Singh-Original/Practice-Questions. | /DSA Step 5/Finding Max and Min in a single Scan.py | 226 | 4.125 | 4 |
arr1 = [5,4,3,6,24,2,45,32,89]
max1 = arr1[0]
min1 = arr1[0]
for i in arr1:
if i > max1:
max1 = i
elif i < min1:
min1 = i
print("The largest element is ", max1)
print("The smallest element is ", min1)
|
640b81c47e6b3edeb00f50214407145889cce84f | juliansilvit/gpccodes | /Codigos estudiantes por lenguaje/PY/Bryann Valderrama/Strings/anagramsPattern.py | 1,092 | 3.578125 | 4 | from sys import stdout
NO_OF_CHARS = 256
def compare(arr1, arr2):
global NO_OF_CHARS
for i in range(NO_OF_CHARS):
if arr1[i] != arr2[i]:
return False
return True
def anagramsSearch(pat, txt):
global NO_OF_CHARS
M = len(pat)
N = len(txt)
countP = [0 for x in range(NO_OF_CHARS)]
countTW = [0 for x in range(NO_OF_CHARS)]
for i in range(M):
countP[ord(pat[i])] += 1
countTW[ord(txt[i])] += 1
for i in range(M, N):
if compare(countP, countTW):
stdout.write(
f'Encontrado en indice {i-M} | Anagrama: {txt[i-M:i]}\n')
countTW[ord(txt[i])] += 1
countTW[ord(txt[i-M])] -= 1
if compare(countP, countTW):
stdout.write(
f'Encontrado en indice {N-M} | Anagrama: {txt[N-M:N]}\n')
# String
txt = 'lalan'
# *-------- Una Palabra --------*
stdout.write('Una Palabra\n')
pat = 'la'
anagramsSearch(pat, txt)
# *-------- Lista de Palabras --------*
stdout.write('Lista de Palabras\n')
pat = ['la', 'na', 'a']
for i in pat:
anagramsSearch(i, txt)
|
d3053dd10523b97b8277afb78dc8f71028981bc9 | zVelto/Python-Basico | /aula3/aula3.py | 272 | 3.671875 | 4 | """
str -string
"""
print('Essa é uma "string" (str).')
print("Essa é uma 'string' (str).")
print("Esse é meu \"texto\" (str).") # Caractere de escape
print('Esse é meu \'texto\' (str).') # Caractere de escape
print(r'Esse é meu \n (str).') # Caractere de escape
|
67a5c198bbab91cf23a6be1aa91f04cb85aa83fe | bleckfox/passKeeper | /passKeeper.py | 4,379 | 3.5 | 4 | # Создание файла учетных записей
import shelve
import QuestandAnsw
########################################
''' Создаю функцию, в ней пишу код добавления новых учетных записей.
Введенные значения записываю как ключ и значение соответственно в файл.
'''
def add_account():
while True:
add_account = input('Хотите добавить аккаунт?\n'
'Да (добавить)\n'
'Enter (не добавлять)\n').lower()
if add_account == 'да':
account = input('Введите логин: ')
password = input('Введите пароль: ')
Account_File[account] = password
print('---------------------------')
elif add_account != 'да':
print('---------------------------')
break
########################################
''' Тоже самое только удаляю данные из файла.
Удаляю ключ, а вместе с ним удаляется значение.
'''
def pop_account():
while True:
pop_account = input('Хотите удалить аккаунт?\n'
'Да (удалить)\n'
'Enter (не удалять)\n').lower()
if pop_account == 'да':
account = input('Введите логин: ')
Account_File.pop(account, 'Такого логина уже нет')
print('Аккаунт успешно удалён.')
elif pop_account != 'да':
print('---------------------------')
break
########################################
'''Выбираем аккаунт из списка'''
########################################
def choose_login():
while True:
print('---------------------------')
print(list(Account_File.keys()))
print('---------------------------')
choose_login = input('Выберите логин: ')
if choose_login in Account_File.keys():
print(str(Account_File[choose_login]))
print('---------------------------')
elif choose_login == '':
print('Идем дальше.')
print('---------------------------')
break
elif choose_login not in Account_File.keys():
print('///////////////////////////')
print('Такого логина нет.')
print('///////////////////////////')
continue
#######################################
# #
#######################################
Account_File = shelve.open('Account')
user_dict = {}
final_dict = {}
answer = QuestandAnsw.answ()
#Проверка пользователя для доступа к базе учетных записей(файлу).
while True:
test = input('Введите ответ на вопрос или Enter, чтобы выйти: ')
if test == answer:
while True:
choose_login()
#подключаю написанные выше функции
add_account()
pop_account()
stop = input('Хотите закрыть программу? ')
if stop == 'да':
break
elif test == '':
print('Выход из общего цикла')
break
elif test != answer:
test = input('Попробуйте ещё раз: ')
print('---------------------------')
continue
Account_File.close()
exit_input = input('Нажмите Enter чтобы закрыть окно. ')
del exit_input
|
73fba64e92d326033c213ba0cfd620068b9cab47 | SupriyoDam/DS-450-python | /Graph/check if undirected graph is cyclic using disjoint set.py | 968 | 3.875 | 4 | from collections import defaultdict
from DisjointSetData import Disjoint
class Graph:
def __init__(self, n):
self.graph = defaultdict(list)
self.n = n
def addEdge(self, starting_vertex, end_vertex):
self.graph[starting_vertex].append(end_vertex)
self.graph[end_vertex].append(starting_vertex)
def isCyclic(self):
disjoint = Disjoint(self.n)
visited = [False] * self.n
for u in list(self.graph):
visited[u] = True
for neighbour in self.graph[u]:
if visited[neighbour] == False:
res = disjoint.union(u, neighbour)
if res == False:
return True
return False
if __name__ == "__main__":
g = Graph(6)
g.addEdge(0, 5)
g.addEdge(0, 1)
g.addEdge(1, 2)
# g.addEdge(4, 1)
g.addEdge(3, 2)
g.addEdge(3, 4)
res = g.isCyclic()
print(f"Graph is cyclic ? {res}") |
70397ce356880ded90b035b78a239a2d07d3761d | yafiimo/python-practice | /main.py | 3,794 | 3.828125 | 4 | from functools import reduce
# Check if a value is classified as a boolean primitive. Return true or false.
def booWho(x):
return True if type(x) == bool else False
print('booWho:', booWho(False), booWho(25))
# Create a function that looks through an array and returns the first element
# in the array that passes a truth test
def findElement(arr, func):
return next((x for x in arr if func(x)), 'undefined')
print('findElement:', findElement([1,2,3], lambda x: x > 10))
# Truncate a string if it is longer than the given maximum string length
def truncateString(string, num):
return string[0:num] + '...' if len(string) > num else string
print('truncateString:', truncateString('A-tisket a-tasket A green and yellow basket', 8), truncateString('A-tisket', 10))
# repeat a string num times
def repeatString(string, num):
if num <= 0:
return ''
return string + repeatString(string, num - 1)
print('repeatString:', repeatString('yo', 4))
# confirm the ending of a string
def confirmEnding(string, end):
return string[len(string) - len(end):] == end
print('confirmEnding:', confirmEnding('calculate', 'ulate'))
# Return an array consisting of the largest number from each provided sub-array
def largestOf(arr):
largest = []
for i in range(len(arr)):
largest.append(reduce(lambda num1, num2: num2 if num2 > num1 else num1, arr[i]))
return largest
print('largestOf:', largestOf([[1,2,3], [66, 8, 100]]))
# convert to celsius
def convertToCelsius(celsius):
fahrenheit = (celsius) * (9/5) + 32
return fahrenheit
print('convertToCelsius:', convertToCelsius(-30))
# return the factorial of a number
def factorialise(num):
if num == 1:
return 1
return num * factorialise(num - 1)
print('factorialise:', factorialise(5))
# reverse a string
def reverseString(string):
# could use string[::-1]
return ''.join(list(reversed(string)))
print('reverseString:', reverseString('hello'))
# return length of longest word in a string
def longestWord(string):
words = string.split(' ')
longest = ''
for w in words:
if len(w) > len(longest):
longest = w
return len(w)
print('longestWord:', longestWord('this is a sentence'))
# title case a sentence
def titleCase(string):
words = string.lower().split(' ')
updatedSentence = []
for w in words:
updatedSentence.append(w.replace(w[0], w[0].upper()))
return ' '.join(updatedSentence)
print('titleCase:', titleCase('hello there mY naMe is mo'))
# copy each element of the first array into the second array
# starting from index n
def frankenSplice(arr1, arr2, n):
return arr2[:n] + arr1 + arr2[n:]
print('frankenSplice:', frankenSplice([1,2,3], [100,200,300,400,500], 2))
# remove falsy values
def removeFalsy(arr):
# return list(filter(lambda x: x, arr))
# or
return [x for x in arr if x]
print('removeFalsy:', removeFalsy([1,2,0,False,True]))
# Return the lowest index at which a value (second argument) should be
# inserted into an array (first argument) once it has been sorted
def getIndexToIns(arr, num):
sortedArr = sorted(arr)
return next((i for i,x in enumerate(sortedArr) if num <= x), len(arr))
print('getIndexToIns:', getIndexToIns([9, 8, 7, 6, 5], 7))
# Return true if the string in the first element of the array contains all of
# the letters of the string in the second element of the array.
def mutation(arr):
string = arr[0].lower()
substr = arr[1].lower()
matches = True
for x in substr:
if x not in string:
matches = False
break
return matches
print('mutation:', mutation(['hello', 'who']), mutation(['hello', 'he']))
def chunkArrayInGroups(arr, size):
newArr = []
for x in range(0, len(arr), size):
subArr = arr[x:x+size]
newArr.append(subArr)
return newArr
print(chunkArrayInGroups([1,2,3,4,5,6,7], 2)) |
03b223972a5326d5ddecbc61fdc7a990faa6b760 | PrathushaKoouri/Binary-Search-4 | /88_H-Index2(Binary Search).py | 1,123 | 3.59375 | 4 | '''
Accepted on leetcode(275)
Time - O(logn), space O(1)
We have to give output as maximum number of papers with maximum citations which should match and rest of the papers should have less than the maximum citations mentioned above.
'''
class Solution:
def hIndex(self, citations) -> int:
# 1. Initialize our variables
low = 0
high = len(citations) - 1
n = len(citations)
# 2. Do binary search and return if H-index is found
while low <= high:
mid = low + (high - low) // 2 # Calculating mid
diff = n - mid # difference of number of papers and the mid index
midVal = citations[mid] # value of mid
if midVal == diff: # if both are equal then we can say that it is maximum and return
return diff
elif midVal < diff: # as the midVal is still less look towards right half
low = mid + 1
else: # as the midVal is greater look towards left half
high = mid - 1
# 3. return using our low
return n - low
|
df4c430b4d8697b4ae2059ed587a84f7102bcd25 | maxherre/Python38_Projects | /Exercise_4_Divisors.py | 529 | 4.3125 | 4 | '''
from www.practicepython.org
completed on 30.10.2020
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
(If you don’t know what a divisor is, it is a number that divides evenly into another number.
For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
'''
__author__ = 'maxisui'
num = int(input("Please chose a number: "))
div = list(range(1, num + 1))
a = []
for elements in div:
if num % elements == 0:
a.append(elements)
print(a) |
adfc759e97a2c9187502740b6af006b86d3bc682 | mohammad-javed/python-pcap-course | /020-035-string-methods/string_fix_answer.py | 197 | 3.921875 | 4 | txt = ",$,, chocolate banana ice-cream..."
# Add more options in the strip()
txt = txt.strip(",$ .")
# Clear any whitespaces left and print the outcome
txt = " ".join(txt.split())
print(txt)
|
9b0d6a22e95dca52295ef125408a921307506fb7 | primaayunda/Send-email | /emailscript.py | 1,165 | 3.6875 | 4 | # getpass used to make user's password invisible
# smtplib is a a library taht provided by python
import getpass
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mimetext because you will only send a text message
sender = str(input("Please input your username: "))
password = getpass.getpass('Please input your password: ')
receiver = []
relist = open ("receiver_list.txt", "r")
for i in relist:
receiver.append(i.replace("\n", ""))
# this program will make your receiver_list.txt read as a list
message = MIMEMultipart()
message ['From'] = sender
message ['To'] = i
message ['Subject'] = str(input("Input your mail subject: "))
body = str(input("Input your mail body: "))
message.attach(MIMEText(body, 'plain'))
# we will use gmail, so the host in this script uses smtp.gmail.com
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, password)
print("Login success")
for email in receiver:
server.sendmail(sender, email, message.as_string())
print("Email has been sent to ", email)
# looping your script so that it can send a message to each recipient
server.quit() |
0ebd435de3950d05ab32efcc45c338d0e0c88972 | Ayush-mega-coder/Basic-Python-Projects | /employeeperfo.py | 351 | 3.640625 | 4 | work_hours=[('ayush',100),('mayank',200),('jose',400)]
def employee_check(work_hours):
current_max=0
employee_of_month=''
for employee,hours in work_hours:
if hours>current_max:
current_max=hours
employee_of_month=employee
else:
pass
return(employee_of_month,current_max)
|
c03a12c67d0b3b25fe0e45bb6dce5f9c1419f9db | Nithanth/Graduate-Algorithm- | /Array/056. Merge Intervals.py | 1,216 | 4.15625 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
"""
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __str__(self):
return "[" + str(self.start) +","+str(self.end)+"]"
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return []
intervals.sort(key=lambda x:x.start)
tail=0
for interval in intervals:
if interval.start>intervals[tail].end:
tail+=1
intervals[tail]=interval
else:
intervals[tail].end=max(intervals[tail].end, interval.end)
return intervals[:tail+1]
if __name__ == "__main__":
intervals = Solution().merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)])
for interval in intervals:
print(interval)
|
59326d2c6e41e4ebead938d87f6b7690dd7a11f7 | matiferna/twitterBot | /usage.py | 2,661 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 19:36:32 2019
@author: edoardottt
This file has a method called print_usage that brings as input a number (the error code).
It prints the appropriate error code and error message.
Then It quits.
This file is under MIT License.
"""
import sys
def print_usage(a):
if a==0:
print('')
print('Usage: python twitterbot.py -u [value] {-h [value OR values separated by comma] OR -s OR -m}')
print('')
print('-u or --username: ')
print('')
print(" It's your twitter username(e-mail)")
print('')
print('-h or --hashtags:')
print('')
print(" It's/They are the hashtag[s] you want to 'follow'")
print('')
print(' If you want to insert multiple hashtags you have to separated them by comma:')
print('')
print(' e.g. -h climatechange,techtips,python')
print('')
print('-s or --stat:')
print('')
print(' If you want to see your stats account.')
print('')
print(' Insert only -u [value] -s')
print('')
print('-m or --mine:')
print('')
print(" If you want to 'follow' your feed's tweets.")
print('')
print(' Insert only -u [value] -m')
print('')
print('example:')
print('')
print('To start the bot searching for some words:')
print(' python twitterbot.py -u [email protected] -h trend,topics,twitter')
print('To start the bot with your feed:')
print(' python twitterbot.py -u [email protected] -m')
print('To see your account bot statistics')
print(' python twitterbot.py -u [email protected] -s')
print('----------------------------------')
print('https://www.edoardoottavianelli.it')
print('----------------------------------')
elif a==1:
print('Error n.1:')
print('Invalid Credentials.')
elif a==2:
print('Error n.2:')
print('Make sure that your Firefox window are in Desktop mode.')
elif a==3:
print('Error n.3:')
print('Execute "pip install selenium" on command line.')
elif a==4:
print('Error n.4:')
print('Execute "python -m pip install -U matplotlib" on command line.')
elif a==5:
print('Error n.5:')
print('Noone database detected.')
print('Execute the initdb.py file by typing in your command line:')
print('python init_db.py')
sys.exit()
|
9122ad3d58de7a4f3a95a01ce38e358a7858073c | jiwon73/lecture_4_1 | /lecture_4/try_except.py | 170 | 3.515625 | 4 | try:
a,b=input('두수를 넣으세요').split()
result=(int(a)/int(b))
print(result)
except:
print('대입한 두수가 정확한지 확인하시오')
|
7f4155d2ae465c1116c48e88425b9a3cb9617d15 | HeyMam/Sparta_Algoritm | /week_3/08_queue.py | 1,574 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, value):
new_node = Node(value)
if self.is_empty():
self.head = new_node
self.tail = new_node
return
self.tail.next = new_node
self.tail = new_node
return
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
return
return_node = self.head
self.head = return_node.next
return return_node
def peek(self):
if self.is_empty():
print("Queue is empty.")
return
return self.head
def is_empty(self):
return self.head is None
def print(self):
if self.is_empty():
return
current = self.head
print("[", sep='', end='')
while current is not None:
print(current.data, sep='', end=' ')
current = current.next
print("\b]")
return
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.enqueue(40)
q.enqueue(50)
q.print()
print("Dequeue:", q.dequeue().data)
print("Dequeue:", q.dequeue().data)
print("Peek:", q.peek().data)
print("Dequeue:", q.dequeue().data)
q.enqueue(60)
q.enqueue(70)
print("Dequeue:", q.dequeue().data)
print("Dequeue:", q.dequeue().data)
print("Peek:", q.peek().data)
print("Dequeue:", q.dequeue().data)
print("Dequeue:", q.dequeue().data)
q.dequeue()
q.peek()
|
e32357d3b076671de52e834f17a88a51efae1b85 | xuysang/learn_python | /书籍/你也能看懂的python算法书/二分法.py | 383 | 3.859375 | 4 | numbers = [1,3,5,6,7,8,13,14,15,17,18,24,30,43,56]
head,tail = 0, len(numbers)
search = int(input("enter a number to search:"))
while tail - head > 1:
mid = (head+tail)//2
if search < numbers[mid]:
tail = mid
elif search > numbers[mid]:
head = mid
elif search == numbers[mid]:
ans = mid
break
else:
if search == numbers[head]:
ans = head
else:
ans = -1
print(ans) |
4863d0e1014c11bb7736a4f6da70255cba30ad0a | Andrecdec/exercicios_variaveis_e_tipos_de_dados | /Ex_43_sec_4.py | 960 | 3.96875 | 4 | '''
Seção 4 - exercício 43
Escreva um programa de ajuda para vendedores . A partir de um valor lido, mostre:
- O total a pagar com desconto de 10%;
- O valor de cada parcela, no parcelamento de 3x sem juros;
- A comissão do vendedor, no caso da venda ser a vista(5% sobre o valor com desconto);
- A comissão do vendedor, no caso da venda ser parcelada (5% sobre o valor total).
'''
valor_lido = float(input('Insira aqui o valor total da compra:'))
total_c_desconto = valor_lido - valor_lido*0.1
parcela = valor_lido/3
comissao_vista = 0.05*total_c_desconto
comissao_parcela = 0.05*valor_lido
print(f'O total a pagar com desconto de 10% é R${total_c_desconto:.2f}.')
print(f'O valor de cada parcela, no parcelamento de 3x sem juros é R${parcela:.2f}.')
print(f'A comissão do vendedor, no caso da venda ser a vista é R${comissao_vista:.2f}.')
print(f'A comissão do vendedor, no caso da venda ser parcelada é R${comissao_parcela:.2f}.')
|
08156950d028967e278b99e799b841902367044e | wei-Z/Python-Machine-Learning | /self_practice/Chapter 10 Predicting Continuous Target Variables with Regression Analysis.py | 13,027 | 3.75 | 4 | # Predicting Continuous Target Variable with Regression Analysis
# Explore the Housing Dataset
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data', header=None, sep='\s+')
df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', \
'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
df.head()
# Visualizing the important characteristics of a dataset
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='whitegrid', context='notebook')
cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']
sns.pairplot(df[cols], size=2.5)
plt.show()
'''
In the following code, we will use Numpy's corrcoef function on the five feature columns that
we previously visualized in the scatterplot matrix, and we will use seaborn's heatmap function
to plot the correlation matrix array as a heat map.
'''
import numpy as np
cm = np.corrcoef(df[cols].values.T)
sns.set(font_scale=1.5)
hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size':15}, yticklabels=cols, xticklabels=cols)
plt.show()
# Implementing an ordinary least squares linear regression model
# Solving regression for regression parameters with gradient descent
class LinearRegressionGD(object):
def __init__(self, eta=0.001, n_iter=20):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(1+X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
output = self.net_input(X)
errors = (y-output)
self.w_[1] += self.eta * X.T.dot(errors)
self.w_[0] += self.eta * errors.sum()
cost = (errors**2).sum() / 2.0
self.cost_.append(cost)
return self
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return self.net_input(X)
'''
To see our LinearRegressionGD regressor in action, let's use the RM(number of rooms)
variable from the Housing Data Set as the explanatory variable to train a model that can
predict MEDV (the housing prices). Furthermore, we will standardize the variable for
better convergence of the GD algorithm. '''
X = df[['RM']].values
y = df['MEDV'].values
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
sc_y = StandardScaler()
X_std = sc_x.fit_transform(X)
y_std = sc_y.fit_transform(y)
lr = LinearRegressionGD()
lr.fit(X_std, y_std)
plt.plot(range(1, lr.n_iter+1), lr.cost_)
plt.ylabel('SSE')
plt.xlabel('Epoch')
plt.show()
'''
Now let's visualize how well the linear regression line fits the training data. To to
so, we will define a simple helper function that will plot a scatterplot of the training
samples and add the regression line:'''
def lin_regplot(X, y, model):
plt.scatter(X, y, c='blue')
plt.plot(X, model.predict(X), color='red')
return None
'''
Now we will use this lin_regplot function to plot the number of rooms against
house pricces:'''
lin_regplot(X_std, y_std, lr)
plt.xlabel('Average number of rooms [RM] (standardized)')
plt.ylabel('Price in $1000\'s [MEDV] (standardized)')
plt.show()
num_rooms_std = sc_x.transform([5.0])
price_std = lr.predict(num_rooms_std)
print "Price in $1000's: %.3f" % \
sc_y.inverse_transform(price_std)
print 'Slope: %.3f' % lr.w_[1]
print 'Intercept: %.3f' % lr.w_[0]
# Estimating the coefficient of a regression model via scikit-learn
from sklearn.linear_model import LinearRegression
slr = LinearRegression()
slr.fit(X, y)
print 'Slope: %.3f' % slr.coef_[0]
print 'Intercept: %.3f' % slr.intercept_
lin_regplot(X, y, slr)
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000\'s [MEDV]')
plt.show()
# Fitting a robust regression model using RANSAC
from sklearn.linear_model import RANSACRegressor
ransac = RANSACRegressor(LinearRegression(),
max_trials=100,
min_samples=50,
residual_metric=lambda x: np.sum(np.abs(x), axis=1),
residual_threshold=5.0,
random_state=0)
ransac.fit(X, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
line_X = np.arange(3, 10, 1)
line_y_ransac = ransac.predict(line_X[:, np.newaxis])
plt.scatter(X[inlier_mask], y[inlier_mask], c='blue', marker='o', label='Inliers')
plt.scatter(X[outlier_mask], y[outlier_mask], c='lightgreen', marker='s', label='Outliers')
plt.plot(line_X, line_y_ransac, color='red')
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000\'s [MEDV]')
plt.legend(loc='upper left')
plt.show()
print 'Slope: %.3f' % ransac.estimator_.coef_[0]
print 'Intercept: %.3f' % ransac.estimator_.intercept_
# Evaluating the performance of linear regression models
from sklearn.cross_validation import train_test_split
X = df.iloc[:, :-1].values
y = df['MEDV'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
slr = LinearRegression()
slr.fit(X_train, y_train)
y_train_pred = slr.predict(X_train)
y_test_pred = slr.predict(X_test)
'''Using the following code, we will now plot a residual plot where we simply substract
the true target variables from our predicted responses:'''
plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data')
plt.scatter(y_test_pred, y_test_pred - y_test, c='lightgreen', marker='s', label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0, xmin=-10, xmax=50, lw=2, color='red')
plt.xlim([-10, 50])
plt.show()
# MSE
from sklearn.metrics import mean_squared_error
print 'MSE train: %.3f, test: %.3f' % (mean_squared_error(y_train, y_train_pred), mean_squared_error(y_test, y_test_pred))
#R^2
from sklearn.metrics import r2_score
print 'R^2 train: %3f, test: %.3f' % (r2_score(y_train, y_train_pred), r2_score(y_test, y_test_pred))
# Using regularized methods for regression
'''A Ridge Regression model can be initialized as follows:'''
from sklearn.linear_model import Ridge
ridge = Ridge(alpha=1.0)
'''Note that the regularization strength is regulated by the parameter alpha, which is
similar to the parameter lambda. Likewise, we can initialize a LASSO regressor from
the linear_model submodule:'''
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=1.0)
'''Lastly, the ElasticNet implementation allows us to vary the L1 to L2 ratio'''
from sklearn.linear_model import ElasticNet
lasso = ElasticNet(alpha=1.0, l1_ratio=0.5)
'''For example, if we set l1_ratio to 1.0, the ElasticNet regressor would be equal to LASSO regression.'''
# Turning a linear regression model into a curve-polynomial regression
'''1. Add a second degree polynomial term:'''
from sklearn.preprocessing import PolynomialFeatures
X = np.array([258.0, 270.0, 294.0,
320.0, 342.0, 368.0,
396.0, 446.0, 480.0, 586.0])[:, np.newaxis]
y = np.array([236.4, 234.4, 252.8,
298.6, 314.2, 342.2,
360.8, 368.0, 391.2,
390.8])
lr = LinearRegression()
pr = LinearRegression()
quadratic = PolynomialFeatures(degree=2)
X_quad = quadratic.fit_transform(X)
'''2. Fit a simple linear regression model for comparison:'''
lr.fit(X, y)
X_fit = np.arange(250, 600, 10)[:, np.newaxis]
y_lin_fit = lr.predict(X_fit)
'''3. Fit a multiple regression model on the transformed feature for polynomial regression'''
pr.fit(X_quad, y)
y_quad_fit = pr.predict(quadratic.fit_transform(X_fit))
plt.scatter(X, y, label='training points')
plt.plot(X_fit, y_lin_fit, label='linear fit', linestyle='--')
plt.plot(X_fit, y_quad_fit, label='quadratic fit')
plt.legend(loc='upper left')
plt.show()
y_lin_pred = lr.predict(X)
y_quad_pred = pr.predict(X_quad)
print 'Training MSE linear: %.3f, quadratic: %.3f' % (mean_squared_error(y, y_lin_pred), mean_squared_error(y, y_quad_pred))
print 'Training R^2 linear: %.3f, quadratic: %.3f' % (r2_score(y, y_lin_pred), r2_score(y, y_quad_pred))
# Modeling nonlinear relationships in the Housing Dataset
'''By executing the following code, we will model the relationship between house prices and LSTAT
(percent lower status of the population) using second degree(quadratic) and third degree (cubic)
polynomials and compare it to a linear fit'''
X = df[['LSTAT']].values
y = df['MEDV'].values
regr = LinearRegression()
# create polynomial features
quadratic = PolynomialFeatures(degree=2)
cubic = PolynomialFeatures(degree=3)
X_quad = quadratic.fit_transform(X)
X_cubic = cubic.fit_transform(X)
# linear fit
X_fit = np.arange(X.min(), X.max(), 1)[:, np.newaxis]
regr = regr.fit(X, y)
y_lin_fit = regr.predict(X_fit)
linear_r2 = r2_score(y, regr.predict(X))
# quadratic fit
regr = regr.fit(X_quad, y)
y_quad_fit = regr.predict(quadratic.fit_transform(X_fit))
quadratic_r2 = r2_score(y, regr.predict(X_quad))
# cubic fit
regr = regr.fit(X_cubic, y)
y_cubic_fit = regr.predict(cubic.fit_transform(X_fit))
cubic_r2 = r2_score(y, regr.predict(X_cubic))
# plot results
plt.scatter(X, y, label='training points', color='lightgray')
plt.plot(X_fit, y_lin_fit, label='linear (d=1), $R^2=%.2f$)' % linear_r2, color='blue', lw=2, linestyle=':')
plt.plot(X_fit, y_quad_fit, label='quadratic (d=2), $R^2=%.2f$)' % quadratic_r2, color='red', lw=2, linestyle='-')
plt.plot(X_fit, y_cubic_fit, label='cubic (d=3), $R^2=%.2f$)' % cubic_r2, color='green', lw=2, linestyle='--')
plt.xlabel('% lower status of the population [LSTAT]')
plt.ylabel('Price in $1000\'s [MEDV]')
plt.legend(loc='upper right')
plt.show()
'''
In addition, polynomial features are not always the best choice for modeling nonlinear
relationships. For example, just by looking at the MEDV-LSTAT scatterplot, we could
propose that a log transformation of the LSTAT feature variable and the square root of
MEDV may project the data onto a linear feature space suitable for a linear regression
fit. Let's test this hypothesis by executing the following code:
'''
# transform features
X_log = np.log(X)
y_sqrt = np.sqrt(y)
# fit features
X_fit = np.arange(X_log.min()-1, X_log.max()+1, 1)[:, np.newaxis]
regr = regr.fit(X_log, y_sqrt)
y_lin_fit = regr.predict(X_fit)
linear_r2 = r2_score(y_sqrt, regr.predict(X_log))
# plot results
plt.scatter(X_log, y_sqrt,
label='training points',
color='lightgray')
plt.plot(X_fit, y_lin_fit,
label='linear (d=1), $R^2=%.2f$' % linear_r2,
color='blue',
lw=2)
plt.xlabel('log(% lower status of the population [LSTAT])')
plt.ylabel('$\sqrt{Price \; in \; \$1000\'s [MEDV]}$')
plt.legend(loc='lower left')
plt.show()
# Dealing with nonlinear relationships using random forests
# Decision tree regression
from sklearn.tree import DecisionTreeRegressor
X = df[['LSTAT']].values
y = df['MEDV'].values
tree = DecisionTreeRegressor(max_depth=3)
tree.fit(X, y)
sort_idx = X.flatten().argsort()
lin_regplot(X[sort_idx], y[sort_idx], tree)
plt.xlabel('% lower status of the population [LSTAT]')
plt.show()
# Random forest regression
'''Now, let's use all the features in the Housing Dataset to fit a random forest
regression model on 60 percent of the samples and evaluate its performance
on the remaining 40 percent.'''
X = df.iloc[:, :-1].values
y = df['MEDV'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)
from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor(n_estimators=1000, criterion='mse', random_state=1, n_jobs=-1)
forest.fit(X_train, y_train)
y_train_pred = forest.predict(X_train)
y_test_pred = forest.predict(X_test)
print 'MSE train: %.3f, test: %.3f' % (mean_squared_error(y_train, y_train_pred), mean_squared_error(y_test, y_test_pred))
print 'R^2 train: %.3f, test: %.3f' % (r2_score(y_train, y_train_pred), r2_score(y_test, y_test_pred))
'''Lastly, let's also take a look at the residuals of the prediction:'''
plt.scatter(y_train_pred,
y_train_pred - y_train,
c='black',
marker='o',
s=35,
alpha=0.5,
label='Training data')
plt.scatter(y_test_pred,
y_test_pred - y_test,
c='lightgreen',
marker='s',
s=35,
alpha=0.7,
label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0, xmin=-10, xmax=50, lw=2, color='red')
plt.xlim([-10, 50])
plt.show() |
ff003e28056c2b87db86631a75b7960b5e543db9 | YaelChen/BankAccount | /2 Bank account.py | 788 | 3.96875 | 4 | class BankAccount:
bank_name = "PayPy"
def __init__(self, _balance=0):
self._balance = _balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def print_balance(self):
print(f"The current balance is {self._balance}")
def main():
yael = BankAccount(100000)
michal = BankAccount(100)
itay = BankAccount()
yael.withdraw(300)
michal.deposit(150)
itay.deposit(150)
yael.print_balance()
michal.print_balance()
itay.print_balance()
# yael.bank_name = "Bankont"
print(f"{BankAccount.bank_name} has a lot of customers. Yael is a customer of {yael.bank_name}.")
if __name__ == '__main__':
main()
|
469ce6b4daf42c8898ea6fddceeb288754962e56 | AAlpenstock/UpUp | /Personal work window/knowledge/change_str_to_list.py | 378 | 3.59375 | 4 | """
转以空格为分隔符的字符串为两层列表嵌套
"""
import re
def change_str():
with open('./str_origin.txt','r',encoding='UTF-8') as fp:
str_1 = fp.read()
str_1 = re.split('\n',str_1)
# for i in range(len(str_1)):
# str_1[i] = [str_1]
print(str_1)
return str_1
if __name__ == '__main__':
change_str()
|
5b0a079a4b5554a65be2bd881021bf2508202829 | qlhai/Algorithms | /data_structure_py3/sort/bubble_sort.py | 467 | 3.90625 | 4 | def bubble_sort(data):
for i in range(len(data)):
for j in range(1, len(data)-i):
if data[j-1] > data[j]:
data[j-1], data[j] = data[j], data[j-1]
def bubble_sort_opt(data):
for i in range(len(data)):
found = False
for j in range(1, len(data)-i):
if data[j-1] > data[j]:
data[j-1], data[j] = data[j], data[j-1]
found = True
if not found:
break |
9b5f91d8280b5fdfd2751839749f1308b94b103a | Shiv2157k/leet_code | /revisited/math_and_strings/math/square_root_x.py | 1,829 | 4.0625 | 4 |
class SquareRoot:
def results(self, x: int) -> int:
"""
Approach: Pocket Calculator
Time Complexity: O(1)
Space Complexity: O(1)
:param x:
:return:
"""
from math import e, log
if x < 2:
return x
left = int(e**(0.5 * log(x)))
right = left + 1
return left if right * right > x else right
def result(self, x: int) -> int:
"""
Approach: Binary Search 2 to x // 2
Time Complexity: O(log N)
Space Complexity: O(1)
:param x:
:return:
"""
# base case
if x < 2:
return x
left, right = 0, x // 2
while left <= right:
# to prevent overflow
pivot = left + (right - left) // 2
num = pivot * pivot
if num < x:
left = pivot + 1
elif num > x:
right = pivot - 1
else:
return pivot
return right
def result_(self, x: int):
"""
Approach: Newton's Method
Formulae: x(k + 1) = 1/2[x(k) + x / x(k)]
Time Complexity: O()
Space Complexity: O()
:param x:
:return:
"""
if x < 2:
return x
x0 = x
x1 = (x0 + x / x0) / 2
while abs(x0 - x1) >= 1:
x0 = x1
x1 = (x0 + x / x0) / 2
return int(x1)
if __name__ == "__main__":
square_root = SquareRoot()
print(square_root.result(4))
print(square_root.result_(4))
print(square_root.results(4))
print(square_root.result(16))
print(square_root.result_(16))
print(square_root.results(16))
print(square_root.result(300))
print(square_root.result_(300))
print(square_root.results(300)) |
c63c03245a5cabcb1fab67abd42ca924c6ad3ce6 | Rsj-Python/project | /py_codewars/有效扩号.py | 307 | 4.03125 | 4 | def valid_parentheses(string):
a = 0
for i in string:
if i == '(':
a += 1
if i == ')':
a -= 1
if a < 0:
return a
return a == 0
print(valid_parentheses('())((())()'))
|
338d82e2efbf6cf59850d216af33da8c8df8aeeb | jdixosnd/jsonl-to-conll | /jsonl_to_conll/io.py | 355 | 3.5 | 4 | import json
def json_to_text(jsons, output_filename):
with open(output_filename, "w") as f:
for each_json in jsons:
for line in each_json:
f.writelines(" ".join(line) + "\n")
def read_jsonl(filename):
result = []
with open(filename, "r") as f:
for line in f.readlines():
result.append(json.loads(line))
return result
|
02dfdd8bd4982167a5b3e38ac41f3d0dee99d67b | tuxedocat/gym | /aoj/course/alds1_1_a.py | 422 | 4 | 4 | def insertion_sort(arr):
for i in range(len(arr)):
key = arr[i]
j = i - 1
while (j >= 0) and (arr[j] > key):
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(" ".join(map(str, arr)))
return arr
def main():
N = input()
arr = [int(i) for i in input().strip().split()]
sorted = insertion_sort(arr)
if __name__ == '__main__':
main()
|
1688167f57a0c9237462c7c08400c38048821199 | pbldmngz/codewars | /kyu7/disemvowel_trolls.py | 129 | 3.640625 | 4 | def disemvowel(string):
return "".join([x for x in string if x not in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U", ]]) |
65456f2d0fa4994f6cc924d5605e9286011e09f6 | AhsanUrRehmanSiddiqui/Classification | /Classification/k-NN.py | 2,150 | 3.53125 | 4 | import pandas as pd
import csv
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn import neighbors
from sklearn import datasets
iris_data = datasets.load_iris()
print ('Keys:', iris_data.keys())
print ('-' * 20)
print ('Data Shape:', iris_data.data.shape)
print ('-' * 20)
print ('Features:', iris_data.feature_names)
print ('-' * 20)
#
# #iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor' #clean species labels
# #iris_data.loc[iris_data['class'] == 'Iris-setossa', 'class'] = 'Iris-setosa'
# X, y = iris_data.data, iris_data.target
#
# #define the model
# knn = neighbors.KNeighborsClassifier(n_neighbors=5, weights='uniform')
#
# #fit/train the new model
# knn.fit(X,y)
#
# #What species has a 2cm x 2cm sepal and a 4cm x 2cm petal?
# X_pred = [2, 2, 4, 2]
# output = knn.predict([X_pred,]) #use the model we just created to predict
#
# print ('Predicted Species:', iris_data.target_names[output])
# print ('Options:', iris_data.target_names)
# print ('Probabilities:', knn.predict_proba([X_pred, ]))
# print(output)
## load the iris data into a DataFrame
## Specifying column names.
iris_data = datasets.load_iris()
col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
## map each iris species to a number with a dictionary and list comprehension.
iris_class = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}
#iris_data['species_num'] = [iris_class[i] for i in iris_data.species]
## Create an 'X' matrix by dropping the irrelevant columns.
#X = iris_data.drop(['species', 'species_num'], axis=1)
#y = iris_data.species_num
X, y = iris_data.data, iris_data.target
## Split data into training and testing sets.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
## Instantiate the model with 5 neighbors.
knn = KNeighborsClassifier(n_neighbors=5)
## Fit the model on the training data.
knn.fit(X_train, y_train)
## See how the model performs on the test data.
print(knn.score(X_test, y_test))
print(knn.predict(X_test))
print("End of code") |
4d719ef3cdb24443243637bb7ebbf88771d6922b | dev-danilosilva/lambda_py | /tests/test_math_functions.py | 3,119 | 3.765625 | 4 | import unittest
import lambda_py.math as m
class TestMathFunctions(unittest.TestCase):
def test_if_sum_2_is_commutative(self):
func = m.sum2
x = 4
y = 5
self.assertTrue(func(x)(y) == func(y)(x))
def test_if_sum_2_result_of_the_function_is_the_sum_of_two_values(self):
func = m.sum2
x = 4
y = 5
self.assertTrue(func(x)(y) == func(y)(x))
def test_if_sum_3_result_of_the_function_is_the_sum_of_three_values(self):
func = m.sum3
x = 4
y = -5
z = 3
result = x + y + z
self.assertTrue(result == func(x)(y)(z))
def test_if_sum_4_result_of_the_function_is_the_sum_of_three_values(self):
func = m.sum4
w = 34
x = 4
y = -5
z = 3
result = w + x + y + z
self.assertTrue(result == func(w)(x)(y)(z))
def test_if_sum_5_result_of_the_function_is_the_sum_of_five_values(self):
func = m.sum5
v = 1000
w = 0
x = 4
y = 5
z = -3
result = v + w + x + y + z
self.assertTrue(result == func(v)(w)(x)(y)(z))
def test_if_sum_6_result_of_the_function_is_the_sum_of_six_values(self):
func = m.sum6
u = 234
v = 1000
w = 0
x = 4
y = -5
z = 3
result = u + v + w + x + y + z
self.assertTrue(result == func(u)(v)(w)(x)(y)(z))
def test_if_sum_7_result_of_the_function_is_the_sum_of_seven_values(self):
func = m.sum7
t = -45
u = 234
v = 1000
w = 0
x = 4
y = 5
z = 3
result = t + u + v + w + x + y + z
self.assertTrue(result == func(t)(u)(v)(w)(x)(y)(z))
def test_if_sum_8_result_of_the_function_is_the_sum_of_three_values(self):
func = m.sum8
s = 23
t = 5
u = 234
v = 1000
w = 0
x = 4
y = 5
z = 3
result = s + t + u + v + w + x + y + z
self.assertTrue(result == func(s)(t)(u)(v)(w)(x)(y)(z))
def test_if_the_power_of_2_by_2_is_4(self):
self.assertEqual(m.power(2)(2), 4)
def test_if_the_power_of_4_by_2_is_16(self):
self.assertEqual(m.power(4)(2), 16)
def test_if_the_power_of_1000_by_0_is_1(self):
self.assertEqual(m.power(1000)(0), 1)
def test_if_the_interger_division_of_100_by_40_is_20(self):
self.assertEqual(m.int_div(10)(2), 5)
def test_if_the_interger_division_of_100_by_40_is_20(self):
self.assertEqual(m.int_div(100)(40), 2)
def test_if_the_absolute_value_of_a_positive_number_is_equal_to_itself(self):
x = 30
self.assertEqual(m.absolute(x), x)
def test_if_the_absolute_value_of_a_negative_number_is_equal_to_the_oposite_of_this_number(self):
x = -30
self.assertEqual(m.absolute(x), -x)
def test_if_the_mod_of_10_by_5_is_0(self):
self.assertTrue(m.mod(10)(5) == 0)
def test_if_the_mod_of_100_by_40_is_20(self):
self.assertTrue(m.mod(100)(40) == 20) |
48e2d850a9a1c43ab4f79390f3728bdc9f071673 | Ash0492/BinarySearch | /lastOccur.py | 445 | 3.53125 | 4 | def LastOccur(l,x):
low=0
high=len(l)-1
while low<=high:
mid=(low+high)//2
if l[mid] > x:
high =mid-1
elif l[mid]<x:
low=mid+1
else:
if mid==len(l)-1 or l[mid]!= l[mid+1]:
return mid
else:
low=mid+1
return -1
l=[5,10,10,10,10,20,20]
print(10, LastOccur(l,10))
print(20, LastOccur(l,20))
print(25, LastOccur(l,25))
|
a8c2a8200a9a4115ce7645e3c4af1860ccc77b0c | ardaunal4/My_Python_Lessons | /Statistics/central_limit_theorem.py | 523 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
x = np.random.random_integers(10,size=100000)
mean_sample = []
for i in range(10000):
sample_number = random.randrange(5, 10) # It generates a random number in an given interval (5, 10)
samples = random.sample(list(x), sample_number) # It takes sample_number times value from the x
mean_of_samples = np.mean(samples) # Takes means of samples
mean_sample.append(mean_of_samples)
plt.hist(mean_sample, bins = 50, color = 'blue')
plt.show() |
182bbbb65732746b62369d9fefa1380ec9659024 | seattlegirl/leetcode | /maximum-product-of-three-numbers.py | 1,275 | 3.9375 | 4 | #coding=utf-8
"""
给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入: [1,2,3]
输出: 6
示例 2:
输入: [1,2,3,4]
输出: 24
注意:
给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
即先将数组排序,我们假设数组够长,那么可能数组最左边三个是绝对值比较大的三个负数,数组最大值肯定要求正数,
那么则有两种可能:取最右边三个或者最左边两个乘最右边一个 ,最后比较这两种情况取最大值即为所要求的值
"""
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#排序,reverse为正,则从大到小排序,若为False,则从小到大排序
nums.sort(reverse=True)
#将最大的三个数相乘
res1=nums[0]*nums[1]*nums[2]
#最大的数和最小的两个数相乘
res2=nums[0]*nums[-1]*nums[-2]
#返回两者中最大的值
return max(res1,res2)
if __name__ == "__main__":
print Solution().maximumProduct([1,2,3])
|
18271a7a7af378e9a056508cb37af4e6d5da0500 | Anisha7/CS2.1 | /code/sorting.py | 8,163 | 4.1875 | 4 | #!python
from sorting_iterative import is_sorted, bubble_sort, selection_sort, insertion_sort
from sorting_recursive import split_sort_merge, merge_sort, quick_sort
from sorting_integer import counting_sort, bucket_sort
# def is_sorted(items):
# """Return a boolean indicating whether given items are in sorted order.
# Running time: O(N) Why and under what conditions?
# Memory usage: O(1) Why and under what conditions?"""
# # TODO: Check that all adjacent items are in order, return early if not
# if (items == None): return True
# prev = None
# for i in range(0,len(items)):
# if prev == None:
# prev = items[i]
# if (items[i] < prev):
# return False
# prev = items[i]
# return True
# def bubble_sort(items):
# """Sort given items by swapping adjacent items that are out of order, and
# repeating until all items are in sorted order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Repeat until all items are in sorted order
# # TODO: Swap adjacent items that are out of order
# for i in range(len(items)):
# # moves the largest item at the end each time
# for j in range(len(items)):
# if (j < len(items)-1 and items[j] > items[j+1]):
# items[j], items[j+1] = items[j+1], items[j]
# return items
# def selection_sort(items):
# """Sort given items by finding minimum item, swapping it with first
# unsorted item, and repeating until all items are in sorted order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Repeat until all items are in sorted order
# # TODO: Find minimum item in unsorted items
# # TODO: Swap it with first unsorted item
# for i in range(len(items)):
# # find min element
# temp = i
# for j in range(i, len(items)):
# if (items[temp] > items[j]):
# temp = j
# # swap
# items[i], items[temp] = items[temp], items[i]
# return items
# def insertion_sort(items):
# """Sort given items by taking first unsorted item, inserting it in sorted
# order in front of items, and repeating until all items are in order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Repeat until all items are in sorted order
# # TODO: Take first unsorted item
# # TODO: Insert it in sorted order in front of items
# for i in range(len(items)):
# # chosen item = items[i]
# # swap item with prev until prev is less than item
# j = i # track item index
# while (j > 0 and items[j] < items[j-1]):
# items[j-1], items[j] = items[j], items[j-1]
# j -= 1
# return items
# def merge(items1, items2):
# """Merge given lists of items, each assumed to already be in sorted order,
# and return a new list containing all items in sorted order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Repeat until one list is empty
# # TODO: Find minimum item in both lists and append it to new list
# # TODO: Append remaining items in non-empty list to new list
# result = []
# while (len(items1) != 0 and len(items2) != 0):
# if (items1[0] > items2[0]):
# result.append(items2[0])
# items2 = items2[1:]
# else:
# result.append(items1[0])
# items1 = items1[1:]
# if (len(items1) > 0):
# result += items1
# if (len(items2) > 0):
# result += items2
# return result
# def split_sort_merge(items):
# """Sort given items by splitting list into two approximately equal halves,
# sorting each with an iterative sorting algorithm, and merging results into
# a list in sorted order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Split items list into approximately equal halves
# mid = len(items)//2
# upper = items[:mid]
# lower = items[mid:]
# # TODO: Sort each half using any other sorting algorithm
# upper.sort()
# lower.sort()
# # TODO: Merge sorted halves into one list in sorted order
# result = merge(upper,lower)
# items = result
# return items
# def merge_sort(items):
# """Sort given items by splitting list into two approximately equal halves,
# sorting each recursively, and merging results into a list in sorted order.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Check if list is so small it's already sorted (base case)
# if (len(items) < 2):
# return items
# # TODO: Split items list into approximately equal halves
# mid = len(items)//2
# upper = items[:mid]
# lower = items[mid:]
# # TODO: Sort each half by recursively calling merge sort
# upper = merge_sort(upper)
# lower = merge_sort(lower)
# # TODO: Merge sorted halves into one list in sorted order
# result = merge(upper,lower)
# items = result
# return items
def random_ints(count=20, min=1, max=50):
"""Return a list of `count` integers sampled uniformly at random from
given range [`min`...`max`] with replacement (duplicates are allowed)."""
import random
return [random.randint(min, max) for _ in range(count)]
def test_sorting(sort=bubble_sort, num_items=20, max_value=50):
"""Test sorting algorithms with a small list of random items."""
# Create a list of items randomly sampled from range [1...max_value]
items = random_ints(num_items, 1, max_value)
print('Initial items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
# Change this sort variable to the sorting algorithm you want to test
# sort = bubble_sort
print('Sorting items with {}(items)'.format(sort.__name__))
items = sort(items)
print('Sorted items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
def main():
"""Read command-line arguments and test sorting algorithms."""
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 0:
script = sys.argv[0] # Get script file name
print('Usage: {} sort num max'.format(script))
print('Test sorting algorithm `sort` with a list of `num` integers')
print(' randomly sampled from the range [1...`max`] (inclusive)')
print('\nExample: {} bubble_sort 10 20'.format(script))
print('Initial items: [3, 15, 4, 7, 20, 6, 18, 11, 9, 7]')
print('Sorting items with bubble_sort(items)')
print('Sorted items: [3, 4, 6, 7, 7, 9, 11, 15, 18, 20]')
return
# Get sort function by name
if len(args) >= 1:
sort_name = args[0]
# Terrible hack abusing globals
if sort_name in globals():
sort_function = globals()[sort_name]
else:
# Don't explode, just warn user and show list of sorting functions
print('Sorting function {!r} does not exist'.format(sort_name))
print('Available sorting functions:')
for name in globals():
if name.find('sort') >= 0:
print(' {}'.format(name))
return
# Get num_items and max_value, but don't explode if input is not an integer
try:
num_items = int(args[1]) if len(args) >= 2 else 20
max_value = int(args[2]) if len(args) >= 3 else 50
# print('Num items: {}, max value: {}'.format(num_items, max_value))
except ValueError:
print('Integer required for `num` and `max` command-line arguments')
return
# Test sort function
test_sorting(sort_function, num_items, max_value)
if __name__ == '__main__':
main() |
7f405cddbbf6484346ea4cbc9d35cf63ba73c219 | AruzhanSakenova/python2021 | /w7/tsis7.py | 3,462 | 3.5 | 4 | import pygame
import math
pygame.init()
width, height = (900, 660) #x,y
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Functions')
WHITE=(255,255,255)
BLACK=(0,0,0)
RED=(255,0,0)
BLUE=(0,0,255)
pi = math.pi
running= True
while running:
# Even loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(WHITE)
pygame.display.flip()
for x in range(90, 741, 120): #сетка по верт
if x != 570:
pygame.draw.line(screen, BLACK, (x, 50), (x, 610))
else:
pygame.draw.line(screen, BLACK, (x, 50), (x, 90))
pygame.draw.line(screen, BLACK, (x, 150), (x, 610))
for x in range(150, 811, 120): #большие сверх низ
pygame.draw.line(screen, BLACK, (x, 50), (x, 85))
pygame.draw.line(screen, BLACK, (x, 610), (x, 575))
for x in range(120, 811, 30): #средние сверх низ
pygame.draw.line(screen, BLACK, (x, 50), (x, 75))
pygame.draw.line(screen, BLACK, (x, 610), (x, 585))
for x in range(105, 811, 15): #маленькие свер низ
pygame.draw.line(screen, BLACK, (x, 50), (x, 60))
pygame.draw.line(screen, BLACK, (x, 610), (x, 600))
for y in range(90, 571, 60): #сетка по гор
pygame.draw.line(screen, BLACK, (50, y), (850, y))
for y in range(90, 571, 30): #сред слев справ
pygame.draw.line(screen, BLACK, (50, y), (80, y))
pygame.draw.line(screen, BLACK, (820,y), (850, y))
for y in range(90, 571, 15): #сред слев справ
pygame.draw.line(screen, BLACK, (50, y), (65, y))
pygame.draw.line(screen, BLACK, (835,y), (850, y))
for x in range(90, 810):
sin_y1 = 240 * math.sin((x - 90) / 120 * pi)
sin_y2 = 240 * math.sin((x - 89) / 120 * pi)
pygame.draw.aalines(screen, RED, False, [(x, 330 + sin_y1), ((x + 1), 330 + sin_y2)])
for x in range(90, 810, 2):
cos_y1 = 240 * math.cos((x - 90) / 120 * pi)
cos_y2 = 240 * math.cos((x - 89) / 120 * pi)
pygame.draw.aalines(screen, BLUE, False, [(x, 330 + cos_y1),((x + 1),330 + cos_y2)])
f1 = pygame.font.Font(None, 25)
s= f1.render('sin x', False, RED)
f2 = pygame.font.SysFont(None, 25)
c = f2.render('cos x', False, BLUE)
screen.blit(s, (555, 105))
screen.blit(c, (555, 125))
for x in range(600, 620): #линия кос
pygame.draw.line(screen, RED, (x, 113), (x, 113))
for x in range(600, 620): #линия син
pygame.draw.line(screen, BLUE, (x, 133), (x, 133))
osx = ['-3п', ' 5п', '-2п', ' 3п', '-п ', ' п ', ' 0 ', ' п ', ' п ', ' 3п', ' 2п', ' 5п', ' 3п']
osy = [' 1.00', ' 0.75', ' 0.50', ' 0.25', ' 0.00', '-0.25', '-0.50', '-0.75', '-1.00']
f3=pygame.font.Font(None, 25)
for x in range(90, 850, 60):
screen.blit(f3.render(osx[(x -85) // 60], False, BLACK), (x - 10, 610))
for y in range(90, 620, 60):
screen.blit(f3.render(osy[(y - 90) // 60], False, BLACK), (5, (y - 10)))
pygame.draw.rect(screen, BLACK, (50, 50, 800, 560), 3)
pygame.draw.line(screen, BLACK, (50, 330), (850, 330), 3)
pygame.draw.line(screen, BLACK, (450, 50), (450, 610), 3)
pygame.draw.line(screen, BLACK, (50, 90), (850, 90))
pygame.draw.line(screen, BLACK, (50,570), (850, 570))
pygame.draw.line(screen, BLACK, (90, 50), (90, 610))
pygame.draw.line(screen, BLACK, (810, 50), (810, 610))
pygame.quit() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.