blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
cff98347a9adc9f299d5e93756929493cda00947 | JayWelborn/HackerRank-problems | /python/algorithms/warmup/staircase.py | 135 | 3.796875 | 4 | n = int(input().strip())
spaces = n-1
hashes = 1
for _ in range(n):
print(' '*spaces + '#'*hashes)
spaces -= 1
hashes += 1 |
943e13af596fcf5c20d097d208b4e1ac25ec9dfb | GregHacob/Notebooks | /palindromic.py | 1,095 | 3.640625 | 4 | import re
class Palindromic():
def __init__(self, st):
st = st.lower()
st = self.removeSpecialChars(st)
self.st = st
def longestPalindromic(self):
palindromic = [0]*len(self.st)
length = len(self.st)
#special cases when the string is empty, has 1, or 2 characters
if length == 0:
return None
elif length == 1:
return self.st
elif length == 2:
if self.st[0] == self.st[1]:
return self.st
else:
return None
for i in range(1,len(self.st)-1):
if i<=length-i:
c_range = i
else:
c_range = length - i - 1
count = 0
for j in range(1,c_range+1):
if self.st[i-j] == self.st[i+j]:
count+=1
else:
break
palindromic[i] = count
max_v = max(palindromic)
#special case when there are no palindromes
if max_v == 0:
return None
max_v_index = palindromic.index(max_v)
return self.st[max_v_index-max_v:max_v_index+max_v+1]
def removeSpecialChars(self, string):
return re.sub("[^a-z]","", string) |
83d6f34077482a6fb508c3ccc7382881c7b7e08d | abdodjman/Break_time | /Take a breake.py | 957 | 3.5625 | 4 | import webbrowser
import time
#import datetime
#now = datetime.datetime.now()
# person = input("Enter your name ")
# print ("Hello " , person , " this is your breake timer")
#print ("current time is: " + (now.strftime(" %H:%M:%S %d-%m-%Y \n")) )
print ("current time is : " + time.ctime() )
#print (now.strftime("%Y-%m-%d %H:%M:%S \n"))
total_breaks = 3
break_count = 0
print("the program will start shortly \n")
print ("if you want to Exit press e or press anykey to continue ")
answer = raw_input()
if answer == "e":
print ("thank you goodbye")
else:
print ("the break counter will start \n")
while (break_count < total_breaks):
time.sleep(5)
webbrowser .open("https://www.youtube.com/watch?v=ZPNgL1Ss7fU", new = 2 )
break_count += 1
if (break_count == 3):
print (" i hope you enjoyed your bracks ")
|
8590266a2a865e9e643c74ebf59850bd25fcedf6 | mgborgman/PDX_Code_Guild | /online_store/database.py | 637 | 3.75 | 4 | __author__ = 'Matt Borgman'
import sqlite3
import store
conn = sqlite3.connect('user_db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(name text, email text)''')
conn.commit()
# def get_users():
# for len(store.better_buy.list_of_customers):
# user_info = store.better_buy.list_of_customers.pop()
# return user_info
# user_info = store.better_buy.list_of_customers
user_info = [['matt','mgborgman@gmail.com'],['ashley','ashley@gmail.com']]
c.executemany('INSERT INTO users VALUES (?,?)', user_info)
c.execute('SELECT * FROM users')
rows = c.fetchall()
for row in rows:
print(row)
conn.close() |
9d47e469e9390f37859a228986cc28c614799d46 | VIDHYASHANMUGAMKA/level3 | /range.py | 100 | 3.8125 | 4 | num = int(input(" "))
if ((num > 0) and (num < 10)):
print("yes")
else:
print("no")
|
0421de4832d0f42054bec425f33640059fb6d1c7 | Emanuelvss13/ifpi-ads-algoritimos2020 | /cap_07_iteracao/Lista_Fábio_03/fabio_iteracao_Q04_ProgresaoGeo.py | 540 | 3.90625 | 4 | def main():
a = int(input('Digite o A0: '))
limite = int(input('Digite o Limite: '))
razao = int(input('Digite a Razão: '))
termo = 1
if a < 0 and limite < 0:
while a > limite:
print(f'termo {termo}º = {a}')
a *= razao
termo += 1
a += 1
else:
while a < limite:
print(f'termo {termo}º = {a}')
a *= razao
termo += 1
print(f'O limite é: {limite}')
main() |
dcdf99dcdae1966f276cf4990f1662f4bcfe4099 | jackieallam/day83_tic_tac_toe | /main.py | 3,203 | 4.03125 | 4 | from player import Player
from game import Game
import art
import os
def game_intro():
""" Displays the game intro and provides a choice of 1 or 2 player game. """
print(art.title)
print("Welcome to Tic Tac Toe.\n")
while True:
amount = input("One or Two Player game? (Type 1 or 2): ")
if amount in ["1", "2"]:
break
else:
print("Sorry, that's not a valid number.")
continue
return int(amount)
def set_player_names(num_players):
""" Get names of players and assign markers for each. Adds computer as 2nd player if 1 Player selected.
Returns the list of 2 players. """
markers = ["X", "O"]
players_list = []
for n in range(num_players):
new_player = Player(input(f"Player {markers[n]}, what is your name? "), markers[n])
players_list.append(new_player)
if num_players == 1:
computer_player = Player("Computer", markers[1])
players_list.append(computer_player)
return players_list
def display_scores(heading):
""" Display the current player scores taking a header as an argument. """
print(heading)
for player in players:
print(f"{player.name}: {player.score}")
print(f"Ties: {draw_count}")
print("\n")
def play_again():
""" Checks if players wish to continue. """
while True:
next_game = input("Would you like to play again? Y/N ").upper()
if next_game in ["Y", "N"]:
if next_game == "N":
os.system("clear")
print(art.title)
display_scores("\nFinal scores:")
print("\nThank you for playing! Goodbye.")
return False
else:
return True
else:
print("Please enter only Y or N.")
continue
how_many_players = game_intro()
# Initialize players and their states
players = set_player_names(how_many_players)
starting_player = players[0]
non_start_player = players[1]
active_player = starting_player
passive_player = non_start_player
draw_count = 0
session_active = True
while session_active:
game_over = False
game = Game(starting_player)
game.display_board(game.markers)
print(f"{game.starting_player.name} starts!")
# Reset active player according to new starting player
active_player, passive_player = starting_player, non_start_player
while not game_over:
position = game.choose_position(active_player)
game.update_board(position, active_player.marker)
if game.check_for_win(active_player):
print(f"{active_player.name} is the winner!")
active_player.score += 1
game_over = True
elif game.move_count == 9:
print("It's a draw!")
draw_count += 1
game_over = True
if game_over:
display_scores("\nCurrent scores:")
# Switch active player for turns
active_player, passive_player = passive_player, active_player
# Switch starting player for new game
starting_player, non_start_player = non_start_player, starting_player
if not play_again():
session_active = False
|
11e4ed64a92982a857382188ca67ba0f8d3e9fb9 | nyangeDix/amateur_py | /amateur_py/intro to python/classes/vote_details.py | 728 | 3.546875 | 4 | #Lists
candidates = []
candidates.append("Dickson")
candidates.append("Scaver")
candidates.append("Flora")
candidates.append("Sanderson")
print(candidates)
for candidate in candidates:
print ("\t- " + candidate)
#Dictionary
Voi_candidates = {
'Mwangea' : 'Dickson',
'Kaloleni' : 'Scaver',
'Kariokor' : 'Flora',
'Mazeras' : 'Sanderson'
}
for region, Voi_candidate in Voi_candidates.items():
print(region + " - " + Voi_candidate)
def animals(**entry):
animal_lists = {}
for key, value in entry.items():
animal_lists[key] = value
return animal_lists
my_animals = animals(reptile = 'lizard', carnivore = 'Lion', herbivorous = 'Cow')
print(my_animals) |
fa4ac6fb1b946d671d0feda71afa627fc4b52f99 | srajan3012/linear-regression | /sigtuple/min_notes.py | 1,425 | 3.78125 | 4 | #code
problem = '''John's wallet has one drawback. His wallet can contain no more than M notes or coins.
So from his total salary , his boss pays him his max salary by the M notes possible.
Tell John how much money will he have to lose.
Input: 3
1712 4
1023 2
2341 3
Output:
12
3
241
'''
notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1]
def get_max_note(salary):
for note in notes:
if salary - note >= 0:
return note # assuming notes is sorted, return first largest note
return 0 # No note can be drawn. remaining_salary cannot be further reduced
def get_cost(remaining_salary, num_notes):
# loose no money, entire salary covered with num_notes
if salary == 0:
return 0
# cannot keep any more notes, John has to loose remaining_salary
if num_notes == 0:
return remaining_salary
# get_max_note that John can keep without exceeding his salary. Number of notes that John can hold reduces by one
return get_cost(remaining_salary - get_max_note(salary), num_notes - 1)
T = int(input())
for i in range(T):
salary, num_notes = map(int, raw_input().strip().split())
print get_cost(salary,num_notes)
|
bfce07bc04c6133d3ea97dbfadc1ff829387014a | ArastunM/Covid-Alarm | /retrieve_data.py | 4,551 | 3.71875 | 4 | """This module is used to retrieve external data"""
import json
import logging
import requests
import uk_covid19
from uk_covid19 import Cov19API, exceptions
def from_config(*args):
"""Used to retrieve values form configuration file"""
with open('config.json') as json_file:
data = json.load(json_file)
for arg in args:
try:
data = data[arg]
except KeyError:
return
return data
# defining logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(from_config('log_file', 'format'))
file_handler = logging.FileHandler(from_config('log_file', 'file_name'))
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
def get_covid():
"""Formatting requested covid data"""
data_list, keys = request_covid()
if data_list:
# assigning variable values from requested data
location = data_list[0][keys[0]]
today_cases = data_list[0][keys[1]]
total_cases = data_list[0][keys[2]]
total_deaths = data_list[1][keys[3]]
death_rate = int(data_list[1][keys[4]])
per_change = int((int(today_cases) / int(data_list[1][keys[1]])) * 100)
daily_report = ''
if death_rate >= 50:
daily_report = f'A notable change detected as rate of deaths within a month ' \
f'of positive tests reached {death_rate / 100.000}%. \n'
daily_report += f'Today in {location}, {today_cases} new cases were recorded, ' \
f'a {per_change}% of yesterday\'s cases. \n'
daily_report += f'A total of {total_cases} cases and ' \
f'{total_deaths} deaths have been recorded'
return daily_report
else:
# logging the error if the request was not successful
logger.error('COVID REPORT NOT RETRIEVED')
def get_news():
"""Formatting requested news data"""
data_list = request_news()
if data_list:
articles = data_list['articles']
return articles[0]['title']
else:
# logging the error if the request was not successful
logger.error('NEWS REPORT NOT RETRIEVED')
def get_weather():
"""Formatting requested weather data"""
data_list = request_weather()
if data_list:
# assigning variable values from requested data
location = data_list['name']
temp_list = data_list['main']
weather_type = data_list['weather'][0]['description'].lower()
visibility = int(data_list['visibility']) / 1000
temp = []
for temps in temp_list.values():
temp.append(int(temps) - 273)
return f'Today in {location} its {temp[0]}°C, ranging from {temp[1]} to {temp[2]}. ' \
f'Weather type is {weather_type} and visibility is {visibility}km'
else:
# logging the error if the request was not successful
logger.error('WEATHER REPORT NOT RETRIEVED')
def request_covid():
"""Requesting covid data"""
location = from_config('retrieve', 'covid', 'location')
data = from_config('retrieve', 'covid', 'data_type')
api = Cov19API(filters=location, structure=data)
try: # checking if the request was successful
retrieved = api.get_json()
return retrieved['data'], list(data.keys())
except uk_covid19.exceptions.FailedRequestError:
return
def request_news():
"""Requesting news data"""
base_url = from_config('retrieve', 'news', 'path')
api_key = from_config('retrieve', 'news', 'key')
country = from_config('retrieve', 'news', 'country')
complete_url = base_url + "country=" + country + "&apiKey=" + api_key
try: # checking if the request was successful
response = requests.get(complete_url).json()
if response['status'] == 'ok' and response['totalResults'] != 0:
return response
except json.decoder.JSONDecodeError:
return
def request_weather():
"""Requesting weather data"""
base_url = from_config('retrieve', 'weather', 'path')
api_key = from_config('retrieve', 'weather', 'key')
city_name = from_config('retrieve', 'weather', 'city')
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url).json()
if response['cod'] == 200: # checking if the request was successful
return response
|
0f0c5283097f368d0226d94d5aab9afcacd04f1a | vijayashok99/Protothon1 | /Calculator using lambda.py | 354 | 4.15625 | 4 | a=float(input("Enter the float"))
b=float(input("Enter the float"))
o=input("Enter the operation to be performed[+,-,*,/,^]")
dict={"+":(lambda a,b:a+b),"-":(lambda a,b:a-b),"*":(lambda a,b:a*b),"/":(lambda a,b:a/b),"+":(lambda a,b:a+b),"^":(lambda a,b:a**b),}
try:
print(dict[o](a,b))
except ZeroDivisionError:
print("Float not divisible by 0")
|
b8920da107f7da5927b761ee0dd97a2bf9571882 | ladin157/ML-Learning | /workflow/pipeline_manage.py | 3,266 | 3.828125 | 4 | # Scikit-learn's Pipeline class is designed as a manageable way to apply a series of data transformations followed by the application of an estimator. In fact, that's really all it is:
#
# Pipeline of transforms with a final estimator.
#
# That's it. Ultimately, this simple tool is useful for:
#
# Convenience in creating a coherent and easy-to-understand workflow
# Enforcing workflow implementation and the desired order of step applications
# Reproducibility
# Value in persistence of entire pipeline objects (goes to reproducibility and convenience)
#
# So let's have a quick look at Pipelines. Specifically, here is what we will do.
#
# Build 3 pipelines, each with a different estimator (classification algorithm), using default hyperparameters:
#
# Logisitic Regression
# Support Vector Machine
# Decision Tree
# To demonstrate pipeline transforms, will perform:
#
# feature scaling
# dimensionality reduction, using PCA to project data onto 2 dimensional space
# We will then end with fitting to our final estimators.
#
# Afterward, and almost completely unrelated, in order to make this a little more like a full-fledged workflow (it still isn't, but closer), we will:
#
# Followup with scoring test data
# Compare pipeline model accuracies
# Identify the "best" model, meaning that which has the highest accuracy on our test data
# Persist (save to file) the entire pipeline of the "best" model
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from sklearn import tree
# load and split the data
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
# construct some pipelines
pipe_lr = Pipeline(
[('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', LogisticRegression(random_state=42))])
pipe_svm = Pipeline([('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', svm.SVC(random_state=42))])
pipe_dt = Pipeline(
[('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', tree.DecisionTreeClassifier(random_state=42))])
# list of pipelines for ease of iteration
pipelines = [pipe_lr, pipe_svm, pipe_dt]
# dictionary of pipelines and classifier types for ease of reference
pipe_dict = {0: 'Logistic Regression', 1: 'Support Vector Machine', 2: 'Decision Tree'}
# fit the pipelines
for pipe in pipelines:
pipe.fit(X_train, y_train)
# compare accuracies
for idx, val in enumerate(pipelines):
print('%s pipeline test accuracy: %.3f' % (pipe_dict[idx], val.score(X_test, y_test)))
# identity the most accurate model on test data
best_acc = 0.0
best_clf = 0
best_pipe = ''
for idx, val in enumerate(pipelines):
score = val.score(X_test, y_test)
if score > best_acc:
best_acc = score
best_pipe = val
best_clf = idx
print('Classifier with best accuracy: %s' % pipe_dict[best_clf])
# save pipeline to file
joblib.dump(best_pipe, 'best_pipeline.pkl', compress=1)
print('Save %s pipeline to file.' % pipe_dict[best_clf])
|
021c60a86ca5cf776a6b9c620d16ba6dda6c8003 | salmonofdoubt/TECH | /PROG/PY/list/list1.py | 1,113 | 4.1875 | 4 | #!/usr/bin/python
import sys
# Gather code in a main() function
def main():
#r = raw_input("ready to call list function? (Y)\n")
#if r == 'y' or r == 'Y':
listfunc() #calls string, takes its return value...
#else: #...in 'text' and prints it.
#print 'bye..'
def listfunc():
print 'Called listfunc'
colors = ['red', 'blue', 'green']
print len(colors), colors
if 'blue' in colors:
print "found 'blue'"
i = 0
while i < len(colors):
print colors[i]
i = i + 2
colors.append('white') # append elem at end
colors.insert(1, 'gray') # insert elem at index 0
colors.extend(['silver', 'brown']) # add list of elems at end
print colors
print colors.index('silver') #5
colors.remove('blue') #search and remove that element
if 'blue' not in colors:
print "'blue' not found"
colors.pop(1) # simply removes anything on position 1
print colors
return # return to calling fct
if __name__ == '__main__':
main()
|
9edc9376c63c4c17e7cad688caa1cde127dce948 | Nathan-Moignard/HashCode2021 | /src/read.py | 1,530 | 3.515625 | 4 | from typing import Tuple, List, Union
t_begin = int
t_end = int
t_time = int
t_roads = Tuple[t_begin, t_end, t_time, str]
t_car = List[str]
class Inputfile:
def __init__(self, adress):
self.time = 0
self.intersection = 0
self.street_number = 0
self.car_number = 0
self.points = 0
self.car: List[t_car] = []
self.streets: List[t_roads] = []
self.get(adress)
def read_file(self, adress):
f = open(adress)
txt = f.readlines()
separation = []
for k in txt:
separation.append(k.rsplit())
f.close()
return separation
def add_road(self, line):
temp: t_roads = (int(line[0]), int(line[1]), int(line[3]), line[2])
self.streets.append(temp)
def add_car(self, line):
temp: t_car = []
for k in line[1:]:
temp.append(k)
self.car.append(temp)
def first_line_info(self, f_line):
if len(f_line) != 5:
print("NO good first line")
return
self.time = int(f_line[0])
self.intersection = int(f_line[1])
self.street_number = int(f_line[2])
self.car_number = int(f_line[3])
self.points = int(f_line[4])
def get(self, adress):
mfile = self.read_file(adress)
self.first_line_info(mfile[0])
for i in range(1, self.street_number + 1):
self.add_road(mfile[i])
for line in mfile[self.street_number + 1:]:
self.add_car(line) |
727f074f4e4b8a723f211e82e8db3b971d6df892 | naweiss/picoCTF2018 | /Cryptography/Safe RSA/solution/solve.py | 885 | 4.21875 | 4 | #!/usr/bin/python2
#https://stackoverflow.com/a/358134
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x)) / n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
# Don't use e=3 it's bad !!!
# Just compute cube root of c to find m
e = 3L
c = 2205316413931134031046440767620541984801091216351222789180582564557328762455422721368029531360076729972211412236072921577317264715424950823091382203435489460522094689149595951010342662368347987862878338851038892082799389023900415351164773L
m = find_invpow(c, e)
print(hex(m)[2:-1].decode('hex')) |
d0c3b4fcb607c8f7223ec204bf3296fbbd9f8053 | anilkumar0470/git_practice | /Terralogic_FRESH/while_loop_1.py | 1,947 | 4.15625 | 4 | # # class and objects
# # class is a collection of methods(functions) and attributes(varibles) and it user defined datatype
#
# # functions
#
#
# # syntax
#
# # definition
# # self is instance of class and which is used to carry the data between the methods
#
#
# # instance variables
# # class variables
#
# class Student:
# c = "lalli"
# def __init__(self, name, loc):
# self.name = name
# self.loc = loc
#
# def display(self):
# print(self.name + self.loc)
# print(self.c)
#
# def set_class_variable(self, new_name):
# self.c = new_name
#
#
# # s1 = Student("Lalli", "bang")
# # s1.set_class_variable("Love")
# # s1.display()
# #
# # s2 = Student("Anil", "bnfdfd")
# #
# # s2.display()
#
#
#
#
#
# # functions :
# # functions are used to write once and use many times
# # two parts
# # function defintion
# # calling function
#
# # syntax
#
# # addition of two numbers
#
# # def sample(a,b , c,d ):
# # print(a,b,c,d)
# # sample(10, "madhavre","rtrtrtr","aaaaattrtrtr")
#
# # default arguments
#
# def sample(name, age, loc=None):
#
# print("name :", name)
# print("age:", age)
# if loc:
# print("loc", loc)
#
# # sample("ssss", 23, "bang")
# # sample("ssss", 23)
#
# # def addition(a = 10, b = 20):
# # print(a + b)
# #
# # addition(20, 90)
#
# # postion arguments is not matter in matter
#
# def sample(a, b, c):
# print(a,b,c)
#
#
# # * args **kwargs
# *args -- tuple
# **
#
#
# def addition(**kwargs):
# print(type(kwargs))
# for i in kwargs:
# print(i)
# addition(name="anil", loc="fff")
#
#
#
# # write a function to check prime number
# # 10,20
# # fibanoacci series
#
a = "madhav"
l =[]
letter = input("enter a character to find the index")
for i in a :
l.append(i)
flag = False
for k in a :
if k == letter:
print(l.index(letter))
l.remove(letter)
flag = True
if not flag:
print("invalid")
|
0c91b49ba3d4efcfaf2029bb4a1c08d401389e3d | a546662002/SC-projects | /stanCode Projects/hangman_game/complement.py | 1,618 | 4.625 | 5 | """
File: complement.py
Name: Charlie Liu
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""
def main():
"""
step 1 - input dna data
step 2 - transfer into capital letter
step 3 - find the complement of import dna data and print the complement data
"""
dna_data = input('Please give me a DNA strand and I\'ll find the complement : ')
dna = dna_data.upper()
print('The complement of ' + str(dna) + ' is ' + build_complement(dna))
def build_complement(dna):
"""
find the complement of the input dna data
The complement of A is T
The complement of T is A
The complement of C is G
The complement of G is C
:param dna: is string, the import of dna data
:return: is string, the complement of the import dna data
"""
ans = ''
for i in dna: # for character in the dna data
if i == 'A': # if one of the dna data is A
ans += 'T' # the complement of A is T
elif i == 'T': # if one of the dna data is T
ans += 'A' # the complement of T is A
elif i == 'C': # if one of the dna data is C
ans += 'G' # the complement of C is G
elif i == 'G': # if one of the dna data is G
ans += 'C' # the complement of G is C
return ans
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
main()
|
4a9c909e111bada789b7d1bd99ee4a9a19a6bd54 | roedoejet/unit_selection_tts | /spanish_transcriber.py | 13,743 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import re
def ltsRules(text):
'''
Description:
This function runs a series of replacement rules to convert from letters to sounds
given the phonetics of Chilean Spanish.
Input:
text(str): any string in Spanish
Output:
a list of phones for the input text
'''
phones = []
# letter sets
letsets = {'LNS': ('l', 'n', 's'),
'DNSR': ('d', 'n', 's', 'r'),
'EI': ('e', 'i', 'é', 'í'),
'AEIOUt': ('á', 'é', 'í', 'ó', 'ú'),
'V': ('a', 'e', 'i', 'o', ''),
'C': ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'ñ', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'y', 'z'),
'noQ': ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'ñ', 'p', 'r', 's',
't', 'v', 'w', 'x', 'y', 'z'),
'AV': ('a', 'e', 'i', 'o', '', 'á', 'é', 'í', 'ó', 'ú'),
'SN': ('p', 't', 'k', 'n', 'm', 'ñ'),
'LN': ('l', 'n'),
'LR': ('l', 'r') }
letters = list(text)
for let in range(0, len(letters)):
if letters[let] != '#' and letters[let] != ' ':
# Get a window of context for each letter
c_let = letters[let] # Current letter
p_let = letters[let-1] # Previous letter
pp_let = letters[let-2] # Previous previous letter
n_let = letters[let+1] # Next letter
nn_let = letters[let+2] # Next next letter
# This is inspired by Festival
# replace Q
if c_let == 'q' and n_let == 'u' and n_let == 'a': phones.append('k')
elif c_let == 'q' and n_let == 'u': phones.append('k')
elif c_let == 'u' and p_let == 'q': pass
elif c_let == 'q': phones.append('k')
# u vowel with g
elif c_let == 'u' and p_let == 'g' and n_let == 'i': pass
elif c_let == 'u' and p_let == 'g' and n_let == 'e': pass
elif c_let == 'u' and p_let == 'g' and n_let == 'í': pass
elif c_let == 'u' and p_let == 'g' and n_let == 'é': pass
# stress for written stress marks
elif c_let == 'á': phones.append('aS')
elif c_let == 'é': phones.append('eS')
elif c_let == 'í': phones.append('iS')
elif c_let == 'ó': phones.append('oS')
elif c_let == 'ú': phones.append('uS')
elif c_let == 'ü': phones.append('u')
# semivowels
elif c_let == 'u' and n_let in letsets['AV']: phones.append('uSC')
elif c_let == 'u' and p_let in letsets['AV']: phones.append('uSV')
elif c_let == 'i' and n_let in letsets['AV']: phones.append('iSC')
elif c_let == 'i' and pp_let in letsets['noQ']: phones.append('iSV')
# y as vowel and w
elif c_let == 'y' and n_let == '#': phones.append('i')
elif c_let == 'y' and n_let in letsets['C']: phones.append('i')
elif c_let == 'w' and n_let == 'u': phones.append('uSC')
elif c_let == 'w': phones.append('u')
# fricatives
elif c_let == 's' and p_let in letsets['AV'] and n_let in letsets['C']: phones.append('h')
elif c_let == 's' and p_let in letsets['AV'] and n_let == '#': phones.append('h')
elif c_let == 'c' and p_let == 's' and n_let in letsets['EI']: pass
elif c_let == 'c' and n_let in letsets['EI']: phones.append('s')
elif c_let == 'g' and n_let in letsets['EI']: phones.append('x')
elif c_let == 'g': phones.append('g')
elif c_let == 'j': phones.append('x')
# keep z cause we'll need it to get stress
elif c_let == 'z' and p_let in letsets['AV'] and n_let in letsets['C']: phones.append('hz')
elif c_let == 'z' and p_let in letsets['AV'] and n_let == '#': phones.append('hz')
elif c_let == 'z': phones.append('s')
# affricates
elif c_let == 'c' and n_let == 'h': phones.append('ch')
elif c_let == 'h' and p_let == 'c': pass
elif c_let == 'l' and n_let == 'l': phones.append('ll')
elif c_let == 'l' and p_let == 'l': pass
elif c_let == 'y' and p_let in letsets['LN']: phones.append('ll')
elif c_let == 'y' and p_let == '#': phones.append('ll')
elif c_let == 'l' and n_let == 'l' and p_let in letsets['LN']: phones.append('ll')
elif c_let == 'l' and p_let == 'l' and pp_let in letsets['LN']: pass
# unvoiced stops
elif c_let == 'p' and n_let == 's': pass
elif c_let == 'c': phones.append('k')
# voiced stops
elif c_let == 'v' and p_let == '#': phones.append('b')
elif c_let == 'v' and p_let in letsets['SN']: phones.append('b')
elif c_let == 'v' and n_let in letsets['LR']: phones.append('b')
elif c_let == 'v' and p_let in letsets['LR']: phones.append('b')
# approximants
elif c_let == 'b' and p_let in letsets['AV'] and n_let in letsets['AV']: phones.append('bA')
elif c_let == 'v' and p_let in letsets['AV'] and n_let in letsets['AV']: phones.append('bA')
elif c_let == 'd' and p_let in letsets['AV'] and n_let in letsets['AV']: phones.append('dA')
elif c_let == 'g' and p_let in letsets['AV'] and n_let in letsets['AV']: phones.append('gA')
elif c_let == 'r' and p_let in letsets['AV'] and n_let in letsets['AV']: phones.append('rA')
elif c_let == 'y': phones.append('llA')
# nasals
elif c_let == 'ñ': phones.append('ny')
# laterals
elif c_let == 'l' and n_let == 'l' and nn_let == '#': phones.append('l')
elif c_let == 'l' and p_let == 'l' and n_let == '#': pass
elif c_let == 'l' and n_let == 'l': phones.append('llA')
elif c_let == 'l' and p_let == 'l': pass
# vibrants
elif c_let == 'r' and n_let == 'r': phones.append('rr')
elif c_let == 'r' and p_let == 'r': pass
elif c_let == 'r' and p_let == '#': phones.append('rr')
elif c_let == 'r' and p_let in letsets['LNS']: phones.append('rr')
elif c_let == 'x': phones += ['k','s']
# get rid of h
elif c_let == 'h': pass
# else
else: phones.append(c_let)
return phones
def syllabify(phones):
'''
Description:
This function inserts syllable boundaries '-' for a list of phones
given the phonetics of Chilean Spanish. Rules are looking only for general
cases, and probably can't cope with loans or proper names.
Input:
phones(list): a list of phones in Spanish
Output:
a list of phones with syllable boundaries for the input text
'''
syllables = []
phones = ['#','#']+phones+['#','#']
sylsets = {'V': ('aS', 'iS', 'uS', 'eS', 'oS', 'a', 'i', 'u', 'e', 'o',
'iSC', 'uSC', 'iSV', 'uSV'),
'VV': ('aS', 'iS', 'uS', 'eS', 'oS', 'a', 'i', 'u', 'e', 'o'),
'IUT': ('iS', 'uS'),
'C': ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'ch',
'l', 'm', 'n', 'ny', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'y', 'z','bA', 'dA', 'gA','llA', 'rA'),
'CC': ('bl', 'br', 'kl', 'kr', 'ks', 'dr', 'fl', 'fr', 'gl',
'gr', 'pl', 'pr', 'tl', 'tr'),
'H': ('ia', 'ie', 'io', 'ua', 'ue', 'uo', 'ai', 'ei', 'oi', 'au',
'eu', 'ou', 'iu', 'ui','iaS', 'ieS', 'ioS', 'uaS', 'ueS', 'uoS',
'aSi', 'eSi', 'oSi', 'aSu', 'eSu', 'oSu', 'iuS', 'uiS') }
for let in range(0, len(phones)):
if phones[let] != '#':
c_let = phones[let]
p_let = phones[let-1]
pp_let = phones[let-2]
n_let = phones[let+1]
nn_let = phones[let+2]
# consonant clusters
if c_let+n_let in sylsets['CC'] and n_let in sylsets['V']: syllables.append('-')
# hiatus
elif c_let+n_let in sylsets['H'] and p_let in sylsets['IUT']: syllables.append('-')
# two strong vowels
elif c_let in sylsets['VV'] and p_let in sylsets['VV']: syllables.append('-')
# break other CC not allowed
elif c_let in sylsets['C'] and p_let in sylsets['C'] and pp_let in sylsets['V']: syllables.append('-')
# usual CV
elif c_let in sylsets['C'] and p_let in sylsets['V'] and n_let in sylsets['V']: syllables.append('-')
syllables.append(c_let)
return syllables
def stress(syllables):
'''
Description:
This function assigns stress when it corresponds to the vowel of a word,
given Spanish rules
Input:
syllables(list): a list of phones and syllable boundaries
Output:
a list of phones with syllable boundaries and stress for the input text
'''
stressed = []
syllables = ['#','#']+syllables+['#','#']
strsets = {'notNSV': ('p', 't', 'k', 'b', 'd', 'g', 'bA', 'dA', 'gA', 'f', 'hz',
'x', 'ch', 'll', 'm', 'ny', 'l', 'llA', 'rA', 'r', 'rr'),
'V': ('a', 'e', 'i', 'o', 'u'),
'C': ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'ny', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'y', 'z','bA', 'dA', 'gA','llA', 'rA'),
'VNS': ('n', 's', 'a', 'i', 'u', 'e', 'o')}
strVow = {'a': 'aS',
'e': 'eS',
'i': 'iS',
'o': 'oS',
'u': 'uS'}
lastSyl = False
plastSyl = False
c = 0
S = False
if '-' in syllables:
# We are counting syllables from the end of the word
for let in reversed(list(range(0, len(syllables)))):
if syllables[let] == '-':
c += 1
if c == 1 and lastSyl == False:
lastSyl = True
elif c == 2:
plastSyl = True
# Words that are stressed in the last syllable
if syllables[let] == '-' and lastSyl == True and not plastSyl:
lastSyl = let
c =+ 1
last = ['#','#']+syllables[let:]
for l in reversed(list(range(0, len(last)))):
if last[l] != '#':
c_let = last[l]
p_let = last[l+1]
pp_let = last[l+2]
n_let = last[l-1]
nn_let = last[l-2]
if c_let in strsets['V'] and p_let in strsets['C'] and n_let in strsets['notNSV'] and nn_let == '#':
stressed.append(strVow[c_let])
S = True
else: stressed.append(c_let)
# Words that are stressed in the previous to last syllable
elif syllables[let] == '-' and plastSyl == True:
plastSyl = let
plast = ['#','#']+syllables[let:lastSyl]+['#','#']
for l in reversed(list(range(0, len(plast)))):
if plast[l] != '#':
c_let = plast[l]
p_let = plast[l+1]
pp_let = plast[l+2]
n_let = plast[l-1]
nn_let = plast[l-2]
if c_let in strsets['V'] and stressed[0] in strsets['VNS']:
stressed.append(strVow[c_let])
S = True
else: stressed.append(c_let)
# 2 syllabe words
elif '-' not in syllables[:let+1] and syllables[let] != '#':
syl = []
for n in syllables[:let+1]:
if n in 'aeuio' and S != True:
syl.append(n+'S')
else:
syl.append(n)
stressed += list(reversed(syl))
break
stressed += list(reversed(syllables[:plastSyl]))
stressed = list(reversed(stressed))
else:
stressed = syllables
# Get rid of extra symbols
stressed_phones = []
for n in stressed:
if n == 'hz': stressed_phones.append('s')
elif n == '-': pass
elif n == '#': pass
else: stressed_phones.append(n)
return stressed_phones
def transcribe(text):
'''
Description:
This function runs a text processing pipeline to obtain a full phonetic transcription
of a given text in Spanish.
Input:
text(str): any string in Spanish
Output:
a list of phones and stress assignment for the input text
'''
# Step 1: lower case
# '##' are silence phones that will be used as boundaries latter
text = '##'+text.lower()+'##'
# Step 2: text normalization
# TODO: currently, we are not supporting text normalization
# Step 3: LTS rules
phones = ltsRules(text)
# Step 4: Syllabification
syllables = syllabify(phones)
# Step 5: stress assignment
# The stress assignment is only run if the word doesn't have the stress mark written
if not re.findall('[áéúíó]', text):
stressed = stress(syllables)
return stressed
# In this case, syllable marks are only used to assign stress and then removed
return ' '.join(syllables).replace('-','').split()
|
40c7acadaaf47ffc4aec9125c846d2131981e55d | siddheshsule/100_days_of_code_python_new | /day_23/player.py | 740 | 3.90625 | 4 | from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
LEVEL_NUM = 1
class Player(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.shape("turtle")
self.setheading(90)
self.go_to_start()
def move_player(self):
self.forward(MOVE_DISTANCE)
def go_to_start(self):
self.goto(STARTING_POSITION)
def is_at_finish_line(self):
if self.ycor() > FINISH_LINE_Y:
return True
else:
return False
def game_over(self):
self.goto(0,0)
self.write("GAME OVER", align = "center", font = "courtier")
|
d2acacd2b2cf03a88b15c0dafb8316d1f2ec1874 | ravenqueen44/Python | /test.py | 174 | 3.703125 | 4 | print("rohini")
print("vikram")
answer=input("what is potato")
print(answer)
julie=input("how old are you")
if julie=='15':
print("my brother is 15")
|
b44d9071f6fed338e017f5146f4fb11c368e190b | AsmisAlan/TrabajoFinal | /control/Control_persona.py | 2,498 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 23:02:27 2015
@author: Franco
"""
import random
class Control():
def __init__(self,roll):
self.lista = []
self.roll = roll
def get_roll(self):
return self.roll
def control_agregar(self,nuevo):
control = True
for Persona in self.lista:
if (nuevo.get_DNI() == Persona.get_DNI()):
control = False
break
if (control):
self.lista.append(nuevo)
return control
def obtener(self,pos ):
return self.lista[pos]
def obtener_pos_dni(self,dni):
pos = 0
for Persona in self.lista:
if (dni == Persona.get_DNI()):
return pos
pos+=1
def tamanio(self):
return len(self.lista)
def ListaNombres(self):
lista_aux = []
for Persona in self.lista:
lista_aux.append(Persona.get_nombre()+' '+ Persona.get_apellido())
return lista_aux
def obtener_por_dni(self , DNI):
for Persona in self.lista:
if (DNI == Persona.get_DNI()):
return Persona
return None
def obtener_Random(self):
if( self.tamanio() > 0):
return random.choice(self.lista)
def cantidad_mascotas(self,lista_mascota): #puede mejorarce capas :P
paseadores_aptos = []
control = 0
for paseador in self.lista :
paseadores_aptos.append(0)
for mascota in lista_mascota.lista:
if(mascota.get_paseador() == paseador.get_DNI()):
paseadores_aptos[control] +=1
control +=1
return paseadores_aptos
def direcciones(self,lista_mascota):
direcciones = '|'
lista_aux = []
lista_aux.append("-32.4769132,-58.2309826")
espacio_verder = ['Club Regatas Uruguay Concepcion del Uruguay', 'Plaza Urquiza Concepcion del Uruguay','Costanera la Fraternidad Concepcion del Uruguay']
for mascota in lista_mascota :
cliente = self.obtener_por_dni(mascota.get_dueño())
try:
lista_aux.index(cliente)
except:
lista_aux.append(cliente.get_direc())
lista_aux.append(random.choice(espacio_verder))
return direcciones.join(lista_aux)
|
98cbf48342fede0771e30faa38c8178c947b595d | vkabc/leetcode | /151.py | 206 | 3.578125 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
A = s.split()
A = A[::-1]
ans = ""
for x in A:
ans += x
ans += " "
return ans[:-1]
|
297f0faad619c09fe3a9ad06270301e88b037f5b | Qkessler/100daysofPython-files | /days/67-69-pyperclip/practice/practice_day2.py | 826 | 3.6875 | 4 | import pyperclip
from time import strftime
# The script for day 2 will be a persistent clipboard app.
# I guess the steps to go through are the following:
# DONE : 1. Get the string copied by the user.
# DONE : 2. Store it in a database(in my case I will be using a file).
# TODO : 3. Get the script to be running everytime.
def get_last():
with open('clipboard.log', 'r') as f:
lines = f.readlines()
if len(lines) == 0:
return None
return lines[-1].strip().split(':')[-1]
def persistent_clipboard():
copied = pyperclip.paste()
time = strftime('%d/%m/%y %T')
if get_last().strip() != copied:
with open('clipboard.log', 'a+') as f:
to_write = f'{time}: {copied}\n'
f.write(to_write)
if __name__ == '__main__':
persistent_clipboard()
|
54fdc9658248db4e3b20de31283ae23f3030aaa6 | kopok2/Algorithms | /DynamicProgramming/NonDecreasingNDigits.py | 468 | 3.515625 | 4 | # coding=utf-8
"""Non decreasing n-digits dynamic programming solution Python implementation."""
def ndnd(n):
dp = [[0] * 10 for x in range(n + 1)]
for i in range(10):
dp[1][i] = 1
for digit in range(10):
for l in range(2, n + 1):
for x in range(digit + 1):
dp[l][digit] += dp[l - 1][x]
cnt = 0
for i in range(10):
cnt += dp[n][i]
return cnt
if __name__ == "__main__":
print(ndnd(3))
|
d46d2fddc090d5e8ed0f92285959a1607e87ca0f | GabrielleLynn/cs161-lab-1-gabrielle-williams | /programming_project_3.py | 1,602 | 4.09375 | 4 | #convert/calculate information about gasoline and gasoline usage
#assign values to variables
#get user input for # of gals of gas
gal_gas = input("Enter number of gallons of gasoline: ")
#conver input from str to int becuase dealing with float later
gal_gas = float(gal_gas)
#liters per gallon
ltr_p_gal = 3.78541
#gals of gas per barrel of oil
oil_barrel = 19.5
#lbs of c02 produced per gal of gas
c02_produced = 20
#BTU energy per gal of gas
BTU_energy_gas = 115000
#BTU energy per gal of ethanol
BTU_energy_ethanol = 75700
#price of gas per gal
gas_price_p_gal = 3.00
#a. number of liters produced per gal_gas
liters_produced = gal_gas * ltr_p_gal
print(liters_produced, "Liters per ", gal_gas, " gallon(s) of gasoline.")
#b. number of barrels needed to produce gal_gas
barrels_needed = gal_gas / oil_barrel#19.5
print(barrels_needed, " barrels required to make ", gal_gas, "gallons of gasoline.")
#c. number of lbs of c02 produced from 1 gal gas
lbs_c02 = gal_gas * c02_produced
print(lbs_c02, " pounds of c02 produced from ", gal_gas, " gallon(s) of gasoline.")
#d. equivalent energy amnt of ethanol gals
eth_gal = BTU_energy_gas / BTU_energy_ethanol
print(eth_gal, " gallons of ethanol is the energy equivilant of ", gal_gas, "gallon(s) of gasonline")
#e. price of gal_gas
cost = gal_gas * gas_price_p_gal
print("The cost of ", gal_gas, " gallon(s) of gasoline is: ", cost)
#it runs and gives me results but i'm not sure how to check if the results are correct...
#should i be checking the math by working it out on paper? |
3e4c0aacb3b0ac0ac16bc8326dfafe8f1f3e08a5 | daniel-reich/turbo-robot | /fRjfrCYXWJAaQqFXF_6.py | 704 | 4.34375 | 4 | """
A _Primorial_ is a product of the first `n` prime numbers (e.g. `2 x 3 x 5 =
30`). `2, 3, 5, 7, 11, 13` are prime numbers. If `n` was `3`, you'd multiply
`2 x 3 x 5 = 30` or Primorial = `30`.
Create a function that returns the Primorial of a number.
### Examples
primorial(1) ➞ 2
primorial(2) ➞ 6
primorial(8) ➞ 9699690
### Notes
N/A
"""
def check(n):
if n == 1:
return False
if n == 2:
return True
prime = True
for i in range(2, n):
if n%i == 0:
prime = False
return prime
def primorial(n):
l = []
for i in range(1, 50):
if check(i):
l.append(i)
count = 1
for i in range(n):
count *= l[i]
return count
|
593630354d6decd2a26f577b300c75536c8e329c | voyagerw/exercise | /myScripts/Hot100/101.对称二叉树.py | 1,966 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 递归,时间空间复杂度均为O(n)
# def isSymmetric(self, root: TreeNode) -> bool:
# def helper(node1, node2):
# # 如果同时到达树底,返回True
# if not node1 and not node2:
# return True
# # 如果左右子树形状不同,返回False
# if not node1 or not node2:
# return False
# # 判断节点值是否相同,左子树左节点和右节点、右节点和左节点是否相同
# if node1.val != node2.val:
# return False
# return helper(node1.left, node2.right) and helper(node1.right, node2.left)
#
# if not root:
# return True
# return helper(root.left, root.right)
# 迭代
def isSymmetric(self, root: TreeNode) -> bool:
if not root or (not root.left and not root.right):
return True
# 使用队列保存节点
queue = [root.left, root.right]
while queue:
# 从队列中取出两个节点
left = queue.pop(0)
right = queue.pop(0)
# 如果两个节点同时为空则继续循环,只有一个为空则跳出循环
if not left and not right:
continue
if not left or not right:
return False
# 比较两个节点值是否相同
if left.val != right.val:
return False
# 将左节点的左节点,右节点的右节点放入队列
queue.append(left.left)
queue.append(right.right)
# 将左节点的右节点,右节点的左节点放入队列
queue.append(left.right)
queue.append(right.left)
return True
|
41b5df4ddc2f41c2f736ba951dd135a7a0678352 | saumya-bhasin/DataStructures | /Arrays/anagram.py | 441 | 3.75 | 4 | #find if two strings are anagram
def anagram(s1,s2):
s1=s1.replace(' ','')
s2=s2.replace(' ','')
d={}
for i in s1:
if i in d:
d[i]+=1
else:
d[i]=1
for i in s2:
if i in d:
d[i]-=1
else:
d[i]=1
for i in d:
if d[i]!=0:
return False
return True
print anagram("abc","cba")
print anagram("abc","cbac") |
e7729ee7e2bed854990b5eb230eca727f23cb12a | ckchiruka/Small-Projects | /Python Code/functions4.py | 336 | 3.734375 | 4 | #!/usr/bin/python3
def main():
testfunc(1, 2, 3, 42, 43, 45, 46)
#asterisk is special, since it allows for any number of optional arguments
def testfunc(this, that, other, *args):
print(this, that, other)
#args gives us a tuple, which is immutable
for n in args: print(n, end = ' ')
if __name__ == "__main__": main()
|
71c9c45239b950f65003e741f06ebc6e385ade38 | CarlosMacaneta/Basic-Python | /Projecto1/basico/Exercicio5.py | 699 | 3.65625 | 4 | import random
from time import sleep
from operator import itemgetter
jogador1 = random.randrange(1, 6)
jogador2 = random.randrange(1, 6)
jogador3 = random.randrange(1, 6)
jogador4 = random.randrange(1, 6)
jogadores = {"jogador1": jogador1,
"jogador2": jogador2,
"jogador3": jogador3,
"jogador4": jogador4
}
print("Valores sorteados:")
for k, v in jogadores.items():
print(f"\tO {k} tirou {v}")
sleep(1)
print(20*"-=")
print("Ranking dos jogadores")
resultados = {}
resultados = sorted(jogadores.items(), key=itemgetter(1), reverse=True)
for i, v in enumerate(resultados):
print(f"\t{i+1}º lugar: {v[0]} com {v[1]}")
sleep(1)
|
16f61e89702c578ed2b7ecf1ed3d7dddbe75c870 | anyl92/TIL | /07_covid home/200317_Collection/example#3/python/after.py | 370 | 3.796875 | 4 | def forward():
print('move forward')
def left():
print('move left')
def right():
print('move right')
def backward():
print('move backward')
def move(key):
if(key == 'w'):
forward()
elif(key == 'a'):
left()
elif(key == 'd'):
right()
elif(key == 's'):
backward()
key = 's'
move(key)
|
cbf8710aaf5cabd0f8a30f7c7c00826b5ab06415 | Krugger1982/24_1_squirrel | /odometr.py | 178 | 3.59375 | 4 | def odometer(A):
S = 0
for i in range(0, len(A), 2):
if i == 0:
S += A[i] * A[i+1]
else:
S += A[i] * (A[i+1]-A[i-1])
return S
|
39ab11f9c936f3a8ea9be48043d3d8b2d5529af3 | kshiv29/PandasEx | /G4G DataTypes/stringsg4g.py | 1,426 | 4.40625 | 4 | # Python Program to Access
# characters of String
# shivkumary a d a v
# 012345678910111213
String1 = "shivkumaryadav"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
# Python Program for
# Escape Sequencing
# of String
# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)
# Escaping Doule Quotes
String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)
# Printing Paths with the
# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)
# Printing Geeks in HEX
String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)
# Using raw String to
# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)
|
c2ae89b21ad7622842cb56cb84bf629b85f272bc | Ansarkapanov/tetris-update | /tetris.py | 6,614 | 4.0625 | 4 | from Tkinter import *
from random import randint
class Game:
#variables for board design
rowNumber = 15; colNumber = 10
emptyColor = "light sea green"
cellSize = 30
#variables to keep track of falling piece
fallingPiece = []
fallingPieceColor = ""
pieceX = 0; pieceY = 0
#creates root
root = Tk()
root.resizable(width=0, height=0)
#creates canvas
canvasWidth = cellSize*(colNumber+3)
canvasHeight = cellSize*(rowNumber+3)
canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
canvas.pack()
def __init__(self):
#creates initial board, draws board, initializes pieces
self.canvas.delete(ALL)
self.createBoardAndPieces()
self.drawGame()
#creates new falling piece and drops it
self.newFallingPiece()
self.drop()
self.root.bind("<Key>", self.keyPressed)
self.root.mainloop()
#clears canvas and draws game
def redrawAll(self):
#erase existing items
self.canvas.delete(ALL)
self.drawGame()
#initial method to draw an empty game and board
def drawGame(self):
self.drawBackground()
self.drawBoard()
#creates the background
def drawBackground(self):
self.canvas.create_rectangle(0, 0, self.canvasWidth, self.canvasHeight, fill="black")
self.canvas.create_text(10*self.cellSize, 17.25*self.cellSize, text="Score: "+str(self.score), fill="white")
#creates initial board filled with emptyColor, initializes pieces
def createBoardAndPieces(self):
self.isGameOver = False
self.score = 0
self.board = []
for row in range(self.rowNumber):
currRow = []
for col in range(self.colNumber):
currRow.append(self.emptyColor)
self.board.append(currRow)
#initializes pieces and colors
iPiece = [
[ True, True, True, True]
]
jPiece = [
[ True, False, False ],
[ True, True, True]
]
lPiece = [
[ False, False, True],
[ True, True, True]
]
oPiece = [
[ True, True],
[ True, True]
]
sPiece = [
[ False, True, True],
[ True, True, False ]
]
tPiece = [
[ False, True, False ],
[ True, True, True]
]
zPiece = [
[ True, True, False ],
[ False, True, True]
]
self.tetrisPieces = [ iPiece, jPiece, lPiece, oPiece, sPiece, tPiece, zPiece ]
self.tetrisPieceColors = [ "red", "yellow", "magenta", "pink", "cyan", "green", "orange" ]
#draw board, with colors based on location in board
def drawBoard(self):
for row in range(self.rowNumber):
for col in range(self.colNumber):
self.drawCell(col, row, self.board[row][col])
#takes in position and draws a cell on the board at the indices
def drawCell(self, x, y, color):
#aligns x and y with position on canvas
x = (x+1.5)*self.cellSize
y = (y+1.5)*self.cellSize
#draws outer border and then inner color
self.canvas.create_rectangle(x, y, x+self.cellSize, y+self.cellSize, fill="black")
self.canvas.create_rectangle(x+1, y+1,
x+self.cellSize-1, y+self.cellSize-1,
fill=color)
#picks random falling pieces
def newFallingPiece(self):
#gets random piece and corresponding color
random = randint(0, len(self.tetrisPieces)-1)
self.fallingPiece = self.tetrisPieces[random]
self.fallingPieceColor = self.tetrisPieceColors[random]
#gets starting cells for new piece
self.pieceY = self.colNumber/2 - len(self.fallingPiece[0])/2
self.pieceX = 0
self.redrawAll()
self.drawFallingPiece()
#draws new falling piece based on boolean values of piece
def drawFallingPiece(self):
#draws piece
for row in range(len(self.fallingPiece)):
for col in range(len(self.fallingPiece[row])):
if self.fallingPiece[row][col] == True:
self.drawCell(self.pieceY+col, self.pieceX+row, self.fallingPieceColor)
#moves falling piece if move is legal, redraws and draws falling piece again
def moveFallingPiece(self, drow, dcol):
if self.moveIsLegal(self.fallingPiece, self.pieceX+drow, self.pieceY+dcol):
self.pieceX += drow
self.pieceY += dcol
#redraws moved piece and board
self.redrawAll()
self.drawFallingPiece()
return True
return False
#checks if move is legal
def moveIsLegal(self, piece, x, y):
#checks piece at x, y for legal move
for row in range(len(piece)):
for col in range(len(piece[row])):
#checks if move out of range of canvas
if x+row not in range(self.rowNumber) or y+col not in range(self.colNumber):
return False
#checks if board filled at that position
if piece[row][col] == True and self.board[x+row][y+col] != self.emptyColor:
return False
return True
def rotateFallingPiece(self):
testPiece = zip(*self.fallingPiece[::-1])
if self.moveIsLegal(testPiece, self.pieceX, self.pieceY):
self.fallingPiece = testPiece
self.redrawAll()
self.drawFallingPiece()
def drop(self):
delay = 500
#if piece cannot move down further, place on board
if not self.moveFallingPiece(1, 0):
self.placeFallingPiece()
self.newFallingPiece()
#if new falling piece immediately illegal
if not self.moveIsLegal(self.fallingPiece, self.pieceX, self.pieceY):
self.isGameOver = True
#create replay screen
self.gameOver()
return
self.canvas.after(delay, self.drop)
#changes board to include piece
def placeFallingPiece(self):
for row in range(len(self.fallingPiece)):
for col in range(len(self.fallingPiece[row])):
if self.fallingPiece[row][col] == True:
self.board[self.pieceX+row][self.pieceY+col] = self.fallingPieceColor
self.removeFullRows()
#called after new piece placed to remove full rows
def removeFullRows(self):
fullRows = 0
emptyRow = [self.emptyColor]*self.colNumber
for row in self.board:
#checks for full rows
if row.count(self.emptyColor) == 0:
#deletes full rows and inserts empty row into board
fullRows += 1
self.board.remove(row)
self.board.insert(0, emptyRow)
#change score
self.score += fullRows**2
self.redrawAll()
def gameOver(self):
self.canvas.create_rectangle(3*self.cellSize, 3*self.cellSize,
self.canvasWidth-3*self.cellSize, 8*self.cellSize, fill="white")
self.canvas.create_text(6.5*self.cellSize, 4*self.cellSize,
text="Game Over.")
self.canvas.create_text(6.5*self.cellSize, 5*self.cellSize,
text="Press 'r' to restart.")
#keyboard commands
def keyPressed(self, event):
if self.isGameOver == True:
if event.char == "r":
self.canvas.delete(ALL)
self.__init__()
else:
if event.keysym == 'Left':
self.moveFallingPiece(0, -1)
elif event.keysym == 'Down':
self.moveFallingPiece(1, 0)
elif event.keysym == 'Right':
self.moveFallingPiece(0, 1)
elif event.keysym == 'Up':
self.rotateFallingPiece()
game = Game()
|
5296f155473c0c8456fcf3ef81e948bcdd5e0402 | nickcedwards/MSSMLimits | /crossing.py | 316 | 3.96875 | 4 | def crossing(x1, x2, y1, y2, y1p, y2p):
dx = x2-x1
dy = y2-y1
dyp = y2p - y1p
xc = x1 + float(y1-y1p)*dx/(dyp-dy)
yc = y1 + float(y1-y1p)/(dyp-dy) * dy / dx
print x1, x2, y1, y2, y1p, y2p, "xing:", xc, yc
crossing(1, 2, 1, 2, 1.5, 1.5)
crossing(1, 2, 1, 2, 2, 1)
crossing(1, 2, 1, 2, 3, 3)
|
482d30cad429d5e59df200945bdef6653fcbcd71 | BartlomiejRasztabiga/advent-of-code-2020 | /day8/day8-a.py | 881 | 3.578125 | 4 | class Instruction:
def __init__(self, string):
parts = string.split(' ')
self.op = parts[0]
self.arg = parts[1]
def is_nop(self):
return self.op == 'nop'
def is_acc(self):
return self.op == 'acc'
def is_jmp(self):
return self.op == 'jmp'
def __str__(self):
return f"{self.op} {self.arg}"
with open('input.txt') as f:
lines = [x.strip() for x in f.readlines()]
instructions = list(map(lambda x: Instruction(x), lines))
acc = 0
i = 0
visited_indexes = set()
while i < len(instructions):
if i in visited_indexes:
break
visited_indexes.add(i)
instruction = instructions[i]
if instruction.is_nop():
i += 1
if instruction.is_acc():
acc += int(instruction.arg)
i += 1
if instruction.is_jmp():
i += int(instruction.arg)
print(acc)
|
8bb11d7feeb691bdc3ac3d1cfaaa852757eb485f | AbsurdMantis/Stuff | /Banco.py | 640 | 3.796875 | 4 | #tentei implementar por array mas infelizmente numpy não funcionou, vou por var, se possível na aula poderia me mostrar a implementação por array numPy?
#moneylist = money[1, 2, 5, 10, 20, 50, 100, 200]
inputmoney = float(input("Insira a quantidade de dinheiro que se deseja sacar"))
money1 = 1
money2 = 2
money5 = 3
money10 = 10
money20 = 20
money50 = 50
money100 = 100
money200 = 200
out = []
if inputmoney > 0:
i1 = inputmoney/money1
i2 = inputmoney/money2
i5 = inputmoney/money5
i10 = inputmoney/money10
i20 = inputmoney/money20
i50 = inputmoney/money50
i100 = inputmoney/money100
i200 = inputmoney/money200
out.append()
|
6b2356250228e604e310d6678ccef5cb2743bb55 | JimHaughwout/teaching_tools | /misc/parse.py | 272 | 3.734375 | 4 | #!/usr/bin/python
def parse_them(items):
for item in items:
if item[0:3] == '$99':
print "Yes: %r" % item
else:
print "No: %r" % item
items = ['$99avc','$99perpound', '$9', 'a', 'xyz123']
parse_them(items)
print items[99]
|
3db94bbe10088aaf17ced22d9d7a8bd3f5348ef3 | Bogdan1726/CursorLectures | /OOP_part2/named_tuple.py | 567 | 4.1875 | 4 | """
Класс collections.namedtuple позволяет создать тип данных, ведущий себя как кортеж, с тем дополнением,
что каждому элементу присваивается имя, по которому можно в дальнейшем получать доступ:
"""
import collections
Article = collections.namedtuple('Article', ['topic', 'author', 'language', 'likes', 'rate'])
python = Article('Python', 'John', 'EN', 2345, 4.25)
print(python[3])
print(python.rate)
print(python.topic)
|
d0acbedc5bb827cb51646b6392d5fdafaac5e571 | AstroHeyang/-offer | /020-包含min函数的栈/stack.py | 792 | 3.71875 | 4 | class Stack:
def __init__(self):
self.stack = []
self.stack_min = []
def push(self, num):
self.stack.append(num)
if not self.stack_min:
self.stack_min.append(num)
else:
if num >= self.stack_min[-1]:
self.stack_min.append(self.stack_min[-1])
else:
self.stack_min.append(num)
def pop(self):
if not self.stack:
return None
else:
self.stack_min.pop()
return self.stack.pop()
def min(self):
if not self.stack_min:
return None
else:
return self.stack_min[-1]
def top(self):
if not self.stack:
return None
else:
return self.stack[-1]
|
c8f3e613db5b9261ced54760a81549a53c7efedd | Kristinboyd/core-problem-set-recursion | /part-1.py | 962 | 4 | 4 | # There are comments with the names of
# the required functions to build.
# Please paste your solution underneath
# the appropriate comment.
# factorial
def factorial(n):
# Base case
while n >= 0:
if n == 0:
return 1
else:
return n * factorial(n-1)
raise ValueError
# reverse
def reverse(text):
if len(text) == 0:
return text
else:
return reverse(text[1:]) + text[0]
# bunny
def bunny(count):
if (count == 0):
return 0
else:
return 2 + bunny (count - 1)
# is_nested_parens
def is_nested_parens(parens):
stack = []
for paren in parens:
if paren == '(':
stack.append(paren)
else:
if not stack:
return False
else:
top = stack[-1]
if paren == ')' and top == '(':
stack.pop()
if not stack:
return True
else:
return False
|
8eb4a0ccbfea836322d8218d7d15f5226106d425 | Leticiamkabu/globalCode-18 | /advPython/lambda.py | 664 | 4.1875 | 4 | #def is_even(): num = input('>Enter a number: ')
# if num % 2 == 0:
# return 'True'
#print(is_even())
#items = [1,2,3,4]
#squares = list(map((lambda x: x ** 2), items)) #bring list for python3
#print(squares)
numbers = [1,56,234,87,4,76,42,69,90,135]
#using function
#def is_even2():
# for number in numbers:
# if number%2 == 0:
# print(number)
#is_even2()
#using lambda
showList = list(map((lambda arg: arg), numbers)) #map ... used to print all elements
print(showList)
is_even = list(filter((lambda arg: arg%2 == 0), numbers)) #filer...to get a subset of elements
print(is_even)
is_odd = list(filter(lambda x: arg%2 != 0, number))
|
4b8f142c4f9ace8ab99cc12b8528e59eeded04f1 | andhy-gif/diya_challenge1 | /membuatpiramid.py | 99 | 3.6875 | 4 | bil=int(input('masukkan angka anda:'))
for i in range(1,bil):
hasil =str(i)*i
print(hasil)
|
4c94a8949fe9fe29052e4926e38904e25b3ce4cd | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4254/codes/1585_1446.py | 292 | 3.59375 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seus erros
comprados = float(input("Quantos litros comprados?"))
michael = comprados * 1/3
print( round ( michael , 3 ) ) |
0fe5779941a73226d2466f50537fc3b5be03b01e | 2877992943/add_match_scrawl_project | /code_crawl/crawl1.py~ | 818 | 3.53125 | 4 | #!/usr/bin/env python3
# encoding=utf-8
from urllib.request import urlopen
from bs4 import BeautifulSoup
link0="http://www.pythonscraping.com/pages/page1.html"
link1="http://www.tripmh.com/cityroad.html"
"""
#########link
try:
html=urlopen(link1)
if html is None:
print 'url not exist'
except HTTPError as e:
print e
else:
print 1
############
"""
"""
html=urlopen(link0)
bsObj=BeautifulSoup(html.read())
print (bsObj)
"""
def getTitle(url):
try:
html=urlopen(url)
except HTTPError as e:
return None
try:
bsObj=BeautifulSoup(html.read())
title=bsObj.body.h1
print '.....',bsObj
except AttributerError as e:
return None
return title
if __name__=='__main__':
title=getTitle(link0)
if title==None:
print ('no title')
else:print (title)
|
f9b9a2a664eb32f2c902b7e4845335612f84db6e | louisbyrne89/sigs | /sigs-django/code/solar_models/solar_models/hourly_models.py | 9,066 | 3.625 | 4 | from math import pi, sin, cos, acos
class BaseSolarModels:
def __init__(self, unit="radians"):
self.unit = unit
def store_angle(self, value, current_unit):
if self.unit == current_unit:
return value
if self.unit == "radians" and current_unit == "degrees":
return self.to_radians(value)
elif self.unit == "degrees" and current_unit == "radians":
return self.to_degrees(value)
else:
return None
def to_radians(self, deg):
return deg * pi / 180
def to_degrees(self, rad):
return rad * 180 / pi
class DeclinationAngleModel(BaseSolarModels):
def __init__(self, day_number, unit="radians"):
super().__init__(unit)
self.day_angle_in_radians = self.day_angle_in_radians_formula(day_number)
self.day_number = day_number
def run(self):
return self.declination_angle_formula()
def declination_angle_formula(self):
f1 = 0.006918
f2 = 0.399912 * cos(self.day_angle_in_radians)
f3 = 0.070257 * sin(self.day_angle_in_radians)
f4 = 0.006758 * cos(2 * self.day_angle_in_radians)
f5 = 0.000907 * sin(2 * self.day_angle_in_radians)
f6 = 0.002697 * cos(3 * self.day_angle_in_radians)
f7 = 0.00148 * sin(3 * self.day_angle_in_radians)
return self.store_angle(f1 - f2 + f3 - f4 + f5 - f6 + f7, "radians")
def day_angle_in_radians_formula(self):
return 2 * pi * ((self.day_number - 1)/ 365)
class HourAngleModel(BaseSolarModels):
def __init__(self, day_number, latitude, longitude, local_time, unit="radians"):
super().__init__(unit=unit)
self.local_time = local_time
self.latitude = self.store_angle(latitude, "degrees")
self.longitude = self.store_angle(longitude, "degrees")
def run(self):
return self.hour_angle_formula()
def hour_angle_formula(self):
local_solar_time = self.local_solar_time_formula()
return self.store_angle(15 * (12 - local_solar_time), "degrees")
def local_solar_time_formula(self):
# Assumed Ls is 0. Therefore need to use GMT
if self.unit == "radians":
latitude = self.to_degrees(self.latitude)
else:
latitude = self.latitude
ET = self.equation_of_time_formula()
return self.local_time + (ET / 60) + (4 / 60) * (self.longitude)
def equation_of_time_formula(self):
B = self.B_formula(self.day_number)
f1 = 9.87 * sin(2 * B)
f2 = 7.53 - cos(B)
f3 = 1.5 * cos(B)
return f1 - f2 - f3
def B_formula(self):
return (360 * (self.day_number - 81)) / 365
class SunsetHourAngleModel(BaseSolarModels):
def __init__(self, declination_angle, latitude, unit="radians"):
super().__init__(unit=unit)
self.declination_angle = declination_angle
self.longitude = self.store_angle(longitude, "degrees")
def run(self):
return self.sunset_hour_angle_formula()
def sunset_hour_angle_formula(self):
return tan(self.declination_angle) * tan(self.latitude)
class HourlyExtraterrestrialRadiationModel(BaseSolarModels):
def __init__(self, day_number, declination_angle, w1, w2, unit="radians"):
super().__init__(day_number, unit=unit)
self.latitude = self.store_angle(latitude, "degrees")
self.w1 = w1
self.w2 = w2
def run(self)
self.eccentricity_formula()
return self.hourly_extraterrestrial_radiation_model()
def hourly_extraterrestrial_radiation_model(self):
Isc = 1.361 # Kw/M**2
formula_part_1 = ((12 * 3.6) / pi) * Isc * E0
formula_part_2 = (sin(self.latitude) * cos(self.declination_angle)) * ((sin(self.w2) - sin(self.w1)))
formula_part_3 = (pi * (self.w2 - self.w1))/180)) * (sin(self.latitude) * sin(self.declination_angle))
return formula_part_1 * (formula_part_2 - formula_part_3)
def eccentricity_formula(self):
self.E0 = 1 + 0.0033 * cos(((2 * pi * self.day_number) / 365))
class LiuJordanModel(BaseSolarModels):
def __init__(self, hour_angle, sunset_hour_angle, unit="radians"):
super().__init__(unit)
self.hour_angle = hour_angle
self.sunset_hour_angle = sunset_hour_angle
def run(self):
return self.lj_model()
def lj_model(self):
numerator = cos(self.hour_angle) - cos(self.sunset_hour_angle)
demoninator = sin(self.sunset_hour_angle) - (((pi * self.sunset_hour_angle)/180) * cos(self.sunset_hour_angle))
return (pi/24) * (numerator / denominator)
class ErbsModel(SolarModels):
def __init__(self, Io, unit="radians"):
super().__init__(unit)
Ih = 0 #TODO: get Ih from django model
self.Mt = Io / Ih
def erbs_model(Io):
if Mt <= 0.22:
return 1 - 0.09 * Mt
elif Mt > 0.22 and Mt > 0.8:
return 0.9511 - (0.1604 * Mt) + (4.388 * Mt**2) - (16.638 * Mt**3) + (12.336 * Mt**4)
else:
return 0.165
class PerezModel(SolarModels):
def a1_formula(self):
return max([0, cos(self.incidence_angle)])
def a2_formula(self):
return max([cos(85), cos(self.zenith_angle)])
def delta_formula(self, Id, Io):
return (1 / cos(self.zenith_angle) * (Id/Io))
def F1_formula(self):
return max)([0, ])
def F2_formula(self):
def perez_model(self, Id, F1, F2, a1):
a1 = a1_formula()
a2 = a2_formula()
return Id * ((1 + cos(self.tilt) + (a1/a2) + sin(self.tilt)))
class SolarModels:
def __init__(self, latitude, day_number, longitude=None, tilt=None, panel_angle=None, local_time=None):
self.latitude = latitude
self.latitude_radians = self.to_radians(latitude)
self.longitude = longitude
if self.longitude is not None:
self.longitude_radians = self.to_radians(longitude)
self.day_number = day_number
self.tilt = tilt
if self.tilt is not None:
self.tilt_radiians = self.to_radians(tilt)
self.panel_angle = panel_angle
if self.panel_angle is not None:
self.panel_angle_radians = self.to_radians(panel_angle)
self.local_time = local_time
# ----------------------------------------------------
# Erbs model formula
# ----------------------------------------------------
def zenith_angle_formula(self):
self.declination_angle_formula()
self.hour_angle_formula()
f1 = sin(self.latitude_radians) * sin(self.declination_angle_radians)
f2 = cos(self.latitude_radians) * cos(self.declination_angle_radians) * cos(self.hour_angle_radians)
self.zenith_angle = 1 / cos(f1 + f2)
self.zenith_angle_radians = self.zenith_angle * 180 / pi
# def incidence_angle_facing_equator_formula(day_number, local_time, latitude, longitude):
# declination_angle = declination_angle_formula(day_number)
# hour_angle = hour_angle_formula(local_time, day_number, longitude)
# f1 = sin(declination_angle) * sin(latitude)
# f2 = cos(declination_angle) * cos(latitude) * cos(hour_angle)
# return f1 + f2
def incidence_angle_all_directions_formula(self):
f1 = sin(self.latitude_radians) * sin(self.declination_angle_radians) * cos(self.tilt_radians)
f2 = cos(self.latitude_radians) * sin(self.declination_angle_radians) * sin(self.tilt_radians) * cos(self.panel_angle_radians)
f3 = cos(self.latitude_radians) * cos(self.declination_angle_radians) * cos(self.tilt_radians) * cos(self.hour_angle_radians)
f4 = sin(self.latitude_radians) * cos(self.declination_angle_radians) * sin(self.tilt_radians) * cos(self.hour_angle_radians) * cos(self.panel_angle_radians)
f5 = cos(self.declination_angle_radians) * sin(self.tilt_radians) * sin(self.hour_angle_radians) * sin(self.panel_angle_radians)
self.incidence_angle_radians = acos(f1 - f2 + f3 + f4 + f5)
self.incidence_angle = self.incidence_angle * 180 / pi
def solar_azimuth_angle_formula(self):
return (sin(self.declination_angle_radians) * sin(latitude)) + (cos(self.declination_angle_radians) + cos(self.latitude_radians) + cos(self.hour_angle_radians))
def surface_solar_azimuth_angle_formula(self):
return self.solar_azimuth_angle_radians - self.incidence_angle_radians
# ----------------------------------------------------
# Liu and Jordan model
# ----------------------------------------------------
# clearness_dict = {
# "bin_1": {
# "F11":
# "F12":
# "F13":
# "F21":
# "F22":
# "F23":
# },
# "bin_2": {
# },
# "bin_3": {
# },
# "bin_4": {
# },
# "bin_5": {
# },
# "bin_6": {
# },
# "bin_1": {
# },
# "bin_1": {
# },
# }
|
719cd5f8ba1fc88fb7bd38f2e2cb27960b3adad6 | manikshakya/RestaurantManagementSystem | /rms/classes2/Admin.py | 3,753 | 3.65625 | 4 | from classes2.db import DB
# Admin Class for managing Admin related operation
class Admin:
# Admin class constructor for initalizaing the object
def __init__(self, id=None, name=None, password=None):
# Database Class object for communication with database; will be used down in the function
self._db = DB()
# Id of admin used for database primary key
self.id = id
# name of admin
self.name = name
# password of admin
self.password = password
# login function for the admin class; It true if name and password matches otherwise returns false
def login(self):
query = "SELECT * FROM admin where admin_name=%s and password=%s"
db = DB()
values = (self.name, self.password)
result = db.fetch(query, values)
if result:
self.id = result[0][0]
self.name = result[0][1]
self.password = result[0][2]
return True
return False
def login(self, name, password):
query = "update admin set logged_in='no' where logged_in='yes'"
db = DB()
values = (self.name, self.password)
self.name = name
self.password = password
query = "SELECT * FROM admin where admin_name=%s and password=%s"
db = DB()
values = (self.name, self.password)
result = db.fetch(query, values)
if result:
self.id = result[0][0]
self.name = result[0][1]
self.password = result[0][2]
return True
return False
# Change password function for admin; It returns nothing
def changePwd(self, newPwd):
query = """UPDATE `admin` SET `password`= %s WHERE id = %s;"""
values = (newPwd, self.id)
self._db.execute(query, values)
# Function that updates the restaurent information in the database; It returns nothing
def updateRestaurentDetail(self, name, address, contact):
query = """UPDATE `rest_info` SET `name`= %s, `address`= %s, `contact`= %s WHERE id = %s;"""
values = (name, address, contact, 1)
self._db.execute(query, values)
# It is a static function of admin class that is use get the Restaurent
# information from the database; It returns the restaurent information
@staticmethod
def getRestDetails():
query = "SELECT * FROM rest_info where id=%s"
db = DB()
values = (1,)
result = db.fetch(query, values)
return result
# It is a static function that Counts the Number of order from the database; It returns the value of orders count
@staticmethod
def getOrdersCounts():
query = "SELECT Count(id) FROM `order`"
db = DB()
result = db.fetch(query)
return result[0][0]
# It is a static function that calculate the sum of total sales; It returns the value of total sale
@staticmethod
def getTotalSale():
query = "SELECT SUM(product.selling_price*product_order.quantity) FROM product_order JOIN product ON product_order.product_id=product.id;"
db = DB()
result = db.fetch(query)
if result:
return result[0][0]
return None
# It is a static function that calculate the sum of profit i.e.
# For each order calculate the profit for individual product and then sum it; It returns the value of total profit
@staticmethod
def getTotalProfit():
query = "SELECT SUM((product.selling_price-product.price)*product_order.quantity) FROM product_order JOIN product ON product_order.product_id=product.id;"
db = DB()
result = db.fetch(query)
if result:
return result[0][0]
return None
|
32a5dcdc355638419bdff8f6f812dd02569a7ef8 | adityaraaz01/opencv | /12 TrackBar.py | 1,152 | 3.9375 | 4 | '''
Date: 31-05-2020. Aditya Raj.
Level = Beginners.
Objective = Learn to add Trackbars in an OpenCV window by using cv::createTrackbar
'''
import numpy as np
import cv2
def nothing(x): #callback function
print(x)
# To createe a black image, window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('B', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('R', 'image', 0, 255, nothing)
'''
While switch = 0, the image will be black
When switch = 1, image color changes corresponding to the [b,g,r]
'''
switch = '0 : OFF\n 1 : ON'
cv2.createTrackbar(switch, 'image', 0, 1, nothing)
while(1):
cv2.imshow('image', img)
k = cv2.waitKey(1)
if k == 27:
break
b = cv2.getTrackbarPos('B', 'image')
g = cv2.getTrackbarPos('G', 'image')
r = cv2.getTrackbarPos('R', 'image')
s = cv2.getTrackbarPos(switch, 'image')
if s == 0:
img[:] = 0
else:
img[:] = [b, g, r]
cv2.destroyAllWindows()
cv2.waitKey(0),
cv2.destroyAllWindows() |
1166a432d872fa09433ddcb117716165aab302b4 | Honestpuck/xworld2017 | /animals/animal.py | 2,346 | 3.9375 | 4 | #!/usr/bin/python
'''
Port of BASIC game to Python. Attempts to guess the animal you are thinking of.
'''
import sys
import io
Q_POS = 0
Y_POS = 1
N_POS = 2
last_answer = '' # Was the last answer Y or N
last_question = '' # index of the last question asked
next_index = 1 # 1 + number of entries in our array
another = True
questions = [["Does it live in the water", "Dolphin", "Koala"]]
def ask(curr_question):
'''
Ask a question
'''
global last_answer
global last_question
asking = questions[curr_question]
print asking[Q_POS]
last_answer = io.getch()
last_question = curr_question
if last_answer[0] == 'Y':
if type(asking[Y_POS]) == int: # we are pointing to another Q
ask(asking[Y_POS])
else:
guess(Y_POS, asking)
else:
if type(asking[N_POS]) == int: # we are pointing to another Q
ask(asking[N_POS])
else:
guess(N_POS, asking)
def give_up(my_guess):
'''
Give up and get the info on the new animal
'''
global last_answer
global last_question
global next_index
global questions
print "I give up. Well done!! What is the answer?"
answer = sys.stdin.readline()
answer = answer.strip
print "What is a question to decide between a", my_guess, "and a", answer
new_question = sys.stdin.readline()
new_question = new_question.strip()
print "Is the answer for", answer, "'Y' or 'N'?"
new_answer = io.getch()
# now to save info
if last_answer[0] == 'Y':
questions[last_question][Y_POS] = next_index
else:
questions[last_question][N_POS] = next_index
if new_answer[0] == 'Y':
questions.append([new_question.strip(), answer, my_guess])
else:
questions.append([new_question.strip(), my_guess, answer])
next_index = next_index + 1
def guess(pos, animal):
'''
We think we know the answer
'''
print "Are you thinking of a", animal[pos]
an_answer = io.getch()
if an_answer[0] == 'Y':
print "Fantastic!! I'm getting pretty good at this!"
else:
give_up(animal[pos])
if __name__ == "__main__":
while another:
ask(0)
print "Would you like another game?"
more = io.getch()
if more[0] == 'N':
another = False
|
6e99e9dd9e9cd5a171df078e15b7d650bc3cfb26 | AaronBecker/project-euler | /euler024.py | 607 | 3.84375 | 4 | from itertools import permutations
def euler24():
"""http://projecteuler.net/problem=24
A permutation is an ordered arrangement of objects. For example, 3124 is
one possible permutation of the digits 1, 2, 3 and 4. If all of the
permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3,
4, 5, 6, 7, 8 and 9?
"""
return ''.join(sorted(permutations("0123456789"))[10 ** 6 - 1])
|
7075fb751711721fe588a83a27a23bf7c9f2ceb4 | qhrong/Leetcode | /Reverse Words in a String III.py | 193 | 3.578125 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
A = s.split(' ')
reverse = []
for i in A:
reverse.append(i[::-1])
return ' '.join(reverse) |
347b0cbf66e088c6f7bac450d9adb0865cf857b1 | me-and/project-euler | /pe069.py | 2,505 | 3.640625 | 4 | #!/usr/bin/env python3
'''
Totient maximum
Euler's Totient function, φ(n) [sometimes called the phi function], is used to
determine the number of numbers less than n which are relatively prime to n.
For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively
prime to nine, φ(9)=6.
n Relatively Prime φ(n) n/φ(n)
2 1 1 2
3 1,2 2 1.5
4 1,3 2 2
5 1,2,3,4 4 1.25
6 1,5 2 3
7 1,2,3,4,5,6 6 1.1666...
8 1,3,5,7 4 2
9 1,2,4,5,7,8 6 1.5
10 1,3,7,9 4 2.5
It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10.
Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
'''
from collections import deque
from sys import argv
from prime import primes
from sequence import MonatonicIncreasingSequence
# From Wikipedia: Euler's product formula: φ(n) = n * Π_{p|n}(1-1/p), where p|n
# denotes the prime numbers dividing n. For example:
#
# φ(36) = φ(2^2 * 3^2) = 36 * (1 - ½) * (1 - ⅓) = 36 * ½ * ⅔ = 12
#
# However, taking this further (at the suggestion of the Project Euler overview
# solution for this problem):
#
# φ(n) = n * Π_{p|n}(1-1/p)
#
# => n/φ(n) = 1/Π_{p|n}(1-1/p) = Π_{p|n}(p/(p-1))
#
# To calculate n/φ(n), then, it is only necessary to consider p|n, not n
# directly, and therefore the exponents in the prime factorisation of n are
# irrelevant. Further, note that p/(p-1) is monotonically decreasing as p
# increases for p > 1.
#
# Consider n, and a prime q that doesn't divide n. It follows that q*n/φ(q*n) =
# n/φ(n) * q/(q-1), and thus that q*n/φ(q*n) > n/φ(n).
#
# Given these facts, we know that if n_k is the product of the k smallest
# primes, then for all n < n_k, n/φ(n) < n_k/φ(n_k).
#
# Finally, then, the solution is simply the largest product of consecutive
# primes starting from 2 that fits within the given maximum.
def prime_product():
product = 1
for prime in primes:
product *= prime
yield product
prime_products = MonatonicIncreasingSequence(prime_product())
# Based in part on the tail recipe in the Python itertools documentation.
def last(iterable):
'''Return the final element of an iterator'''
return deque(iterable, maxlen=1)[0]
if __name__ == '__main__':
try:
maximum = int(argv[1])
except IndexError:
maximum = 1000000
print(last(prime_products.range(maximum)))
|
d9c00dfda304c685efcd320708b0920ebeaa7896 | Dhruvish09/PYTHON_TUT | /List/extend().py | 186 | 4.1875 | 4 |
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
# Add List1 to List2 now
List2.extend(List1)
print(List2)
|
e634708444ba096d4b0e613a2bbe397ceb999b2d | nkrishnappa/100DaysOfCode | /Python/Day-#8/4-Prime-Number-Check.py | 1,526 | 4.375 | 4 | # Prime Number - The number which only divisible by itself and 1
"""
https://en.wikipedia.org/wiki/Prime_number
You need to write a function that checks whether if the number passed into it is a prime number or not.
e.g. 2 is a prime number because it's only divisible by 1 and 2.
But 4 is not a prime number because you can divide it by 1, 2 or 4.
Example Input 1
73
Example Output 1
It's a prime number.
Example Input 2
75
Example Output 2
It's not a prime number.
"""
# brute-force
# def prime_checker(number: int) -> bool:
# for num in range(2, number):
# if number % num == 0:
# print("It's not a prime number.")
# return False
# print("It's a prime number")
# return True
# Improve
'''
If a number n is not a prime, it can be factored into two factors a and b:
n = a * b
Now a and b can't be both greater than the square root of n, since then the product a * b would be greater than sqrt(n) * sqrt(n) = n.
So in any factorization of n, at least one of the factors must be smaller than the square root of n,
and if we can't find any factors less than or equal to the square root, n must be a prime.
'''
import math
def prime_checker(number: int) -> bool:
for num in range(2, math.ceil(math.sqrt(number))+1):
if number % num == 0:
print("It's not a prime number.")
return False
print("It's a prime number")
return True
#Do NOT change any of the code below👇
n = int(input("Check this number: "))
prime_checker(number=n)
|
cb869127b38b11f267aad6b04ba053125fda8636 | TheHugz1997/Projet_Abalone | /src/check_loop.py | 3,991 | 3.984375 | 4 | from copy import deepcopy
from strategy import StrategyConfiguration
MEMORY_SIZE = 10 # Change the memory size of the lists
class CheckLoop:
"""
Saved the move/board and check is the game is looping
"""
def __init__(self):
self.__pointer = 0
self.__move_mem = [None] * MEMORY_SIZE
self.__board_mem = [None] * MEMORY_SIZE
def append(self, move, board):
"""
Append a move and a board in the memory
Parameters :
move (StrategyConfiguration): Move to add on the memory
board (list): Board to add on the memory
"""
if MEMORY_SIZE == 0:
return
if self.__pointer < MEMORY_SIZE:
self.__move_mem[self.__pointer] = move
self.__board_mem[self.__pointer] = deepcopy(board)
self.__pointer += 1
else:
self._shift_mem()
self.__move_mem[MEMORY_SIZE - 1] = move
self.__board_mem[MEMORY_SIZE - 1] = deepcopy(board)
def _shift_mem(self):
"""
Shift the list if the memory is full
"""
if MEMORY_SIZE == 0:
return
for i in range(1, MEMORY_SIZE):
self.__move_mem[i - 1] = self.__move_mem[i]
self.__board_mem[i - 1] = self.__board_mem[i]
self.__move_mem[MEMORY_SIZE - 1] = None
self.__board_mem[MEMORY_SIZE - 1] = None
def is_looping(self, move, board):
"""
Check if the game is looping
Parameters:
move (StrategyConfiguration): Move to check
board (list): Board to check
Returns:
Return True if it's looping, False otherwise
"""
if self.__pointer == 0:
return False
for i in range(0, self.__pointer):
if (self.__board_mem[i] == board) and (self.__move_mem[i] == move):
return True
return False
if __name__ == '__main__':
strategy_1 = StrategyConfiguration([1, 2], 'SW', 150)
strategy_1_copy = StrategyConfiguration([1, 2], 'SW', 150)
strategy_2 = StrategyConfiguration([2, 3], 'SE', 100)
strategy_3 = StrategyConfiguration([3, 6], 'SE', 120)
board1 = [
["W", "W", "W", "W", "W", "X", "X", "X", "X"],
["W", "W", "W", "W", "W", "W", "X", "X", "X"],
["E", "E", "W", "W", "W", "E", "E", "X", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "X", "E", "E", "B", "B", "B", "E", "E"],
["X", "X", "X", "B", "B", "B", "B", "B", "B"],
["X", "X", "X", "X", "B", "B", "B", "B", "B"]
]
board1_copy = [
["W", "W", "W", "W", "W", "X", "X", "X", "X"],
["W", "W", "W", "W", "W", "W", "X", "X", "X"],
["E", "E", "W", "W", "W", "E", "E", "X", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "X", "E", "E", "B", "B", "B", "E", "E"],
["X", "X", "X", "B", "B", "B", "B", "B", "B"],
["X", "X", "X", "X", "B", "B", "B", "B", "B"]
]
board2 = [
["W", "W", "W", "W", "W", "X", "X", "X", "X"],
["W", "W", "W", "W", "W", "W", "X", "X", "X"],
["E", "E", "W", "W", "W", "E", "E", "X", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "X", "E", "E", "B", "B", "B", "E", "E"],
["X", "X", "X", "B", "E", "B", "B", "B", "B"],
["X", "X", "X", "X", "E", "B", "B", "B", "B"]
]
board3 = [
["W", "W", "W", "W", "W", "X", "X", "X", "X"],
["W", "W", "W", "W", "W", "W", "X", "X", "X"],
["E", "E", "W", "W", "W", "E", "E", "X", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "X"],
["E", "E", "E", "E", "E", "E", "E", "E", "E"],
["X", "E", "E", "W", "E", "E", "E", "E", "E"],
["X", "X", "E", "W", "B", "B", "B", "E", "E"],
["X", "X", "X", "B", "E", "B", "B", "B", "B"],
["X", "X", "X", "X", "E", "B", "B", "B", "B"]
]
checkloop = CheckLoop()
checkloop.append(strategy_1, board1)
checkloop.append(strategy_2, board2)
checkloop.append(strategy_3, board3)
print(checkloop.is_looping(strategy_1_copy, board1))
print(checkloop.is_looping(strategy_2, board2))
print(checkloop.is_looping(strategy_3, board3))
|
de40722cbf7f3de3ebf1fe26537bce01415f838e | BrownDSI/a2 | /music1030/cleaning/integration.py | 1,991 | 3.515625 | 4 | from collections import Counter
import time
from typing import List
import pandas as pd
def jaccard_similarity(a: str,
b: str,
token='letter',
k=1) -> float:
"""Takes in two strings and computes the Jaccard similarity of them.
Consider ignoring case and removing punctuation
Note: We will only be testing that fuzzy_match works correctly.
"""
# TODO: Task 10
# YOUR CODE HERE
pass
def fuzzy_match(spotify_df: pd.DataFrame,
lastfm_df: pd.DataFrame) -> List:
"""Takes in the spotify and lastfm dataframes and returns
a list of songs with similar song names and artist names
"""
# TODO: Task 10
# YOUR CODE HERE
pass
##############
# TEST CASES #
##############
def test_jaccard():
assert jaccard_similarity('a', 'b') == 0
assert jaccard_similarity('c', 'c') == 1
assert jaccard_similarity('C', 'c') == 1
assert jaccard_similarity('ace', 'acd') == 2 / 4
# Consider using bigrams instead of letters
assert jaccard_similarity('ace', 'acd', k=2) == 1 / 3
def test_fuzzy_match():
spotify_df = (pd.read_csv('data/solutions/spotify.csv')
.sort_values('song_name')
.iloc[1000:1100])
lastfm_df = (pd.read_csv('data/solutions/lastfm_t6.csv')
.sort_values('song_name')
.iloc[1700:1800])
similar_songs = fuzzy_match(spotify_df, lastfm_df)
assert isinstance(similar_songs, list)
assert ('sippin’ on fire', 'sipping on fire') in similar_songs
if __name__ == '__main__':
spotify_df = pd.read_csv('data/solutions/spotify.csv')
lastfm_df = pd.read_csv('data/solutions/lastfm_t6.csv')
# TODO: Task 10
# Write your data from Fuzzy Match to data/similar_songs.csv
print("Fuzzy match started")
start2 = time.time()
# YOUR CODE HERE
end2 = time.time()
print("Fuzzy match took", (end2 - start2) / 60, "minutes")
|
8c5af0c55b336fbf820baad1e7450cffcb787d22 | frclasso/turma1_Python_Modulo2_2019 | /Cap01_Elementos_sintaxe_especifica/02_list_comprehensions/07_maths.py | 143 | 3.578125 | 4 | #!/usr/bin/env python3
S = [x**2 for x in range(10)]
V = [2**i for i in range(13)]
M = [x for x in S if x % 2 == 0]
print(S)
print(V)
print(M) |
730597873d8c99f1233002e389b6d4cee21fd73a | shmuel19-meet/yl1201718 | /lab5/lelz.py | 964 | 3.953125 | 4 |
from turtle import *
import random
colormode(255)
class Square(Turtle):
def __init__(self,size):
Turtle.__init__(self)
self.shapesize(size)
self.shape("square")
def random(self):
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
self.color(r, g, b)
class Rectangle(Turtle):
def __init__(self,size):
Turtle.__init__(self)
self.shapesize(size)
self.shape("Rectangle")
yee = Rectangle(6)
square1 = Square(5)
square1.random()
#square1.random((random.randint(0,255), random.randint(0,255), random.randint(0,255)))
begin_poly()
for i in range(6):
pendown()
forward(20)
right(60)
end_poly()
register_shape("my_hex",get_poly())
class Hexagon(Turtle):
def __init__(self,size,speed,color):
Turtle.__init__(self)
self.shapesize(size)
self.speed(speed)
self.color(color)
self.shape("my_hex")
hexa = Hexagon(2, 4,"Green")
for i in range(6):
hexa.pendown()
hexa.forward(80)
hexa.right(60)
mainloop() |
8f0b425d1265a383b3b43ac4b352757a30e1c3bc | FourLineCode/ctf | /picoCTF/based/script.py | 148 | 3.796875 | 4 | #!/usr/bin/python3
import sys
string = sys.argv[1]
l = string.split()
s = ''
for i in l:
# convert octal to text
s += chr(int(i, 8))
print(s) |
8760a21579b557eacffa07944ae75236a902e2a2 | thanhnotes/PythonTechmaster | /Chap2 - Hoc nhanh cu phap/Chap2 - Homework/03_IfElse_hw2.py | 381 | 4.15625 | 4 | # Tinh chi so BMI
weight = float(input("Enter your weight (in pounds): "))
height = float(input("Enter your height (in inches): "))
BMI = (weight * 0.45359237) / (height * 0.0254)
if BMI < 18.5:
print("Underweight")
elif 18.5 < BMI < 25.0:
print("Normal")
elif 25.0 < BMI < 30.0:
print("Overweight")
else:
print("Obese")
#This is command line
print("Say hello!") |
92ac1215bdeed483ec4c669878bbd82b146a13c7 | 0xch25/Data-Structures | /2.Arrays/Problems/Staircase.py | 341 | 3.96875 | 4 | '''
https://www.hackerrank.com/challenges/staircase/problem?h_r=next-challenge&h_r%5B%5D%5B%5D=next-challenge&h_r%5B%5D%5B%5D=next-challenge&h_v=zen&h_v%5B%5D%5B%5D=zen&h_v%5B%5D%5B%5D=zen&isFullScreen=true&h_r=next-challenge&h_v=zen
'''
def staircase(n):
for i in range(1, n + 1):
print(' ' * (n - i) + '#' * i)
n=7
staircase(n) |
78a94e407616c844bef618c8be60937a712aa411 | nonnikb/verkefni | /Lokapróf/Midterm/Midterm 2/Dæmi 3.py | 428 | 4.15625 | 4 | def make_sublists(a_list):
result = [[]]
for i in range(len(a_list)):
for j in range(i, len(a_list)):
result.append(a_list[i:j+1])
return result
# Main program starts here
def main():
listi = input("Enter a list separated with commas: ").split(',')
sub_lists = make_sublists(listi)
print(sorted(sub_lists))
# This should be the last statement in your main program/function
main() |
bac642d40743d7c1d0bc47405eb47c7a647f7262 | herealways/Data-Structures-and-Algorithms-Exercise | /Section 4 Soloving Coding Problems/mock_google_interview.py | 388 | 3.578125 | 4 | # [1, 2, 3, 9] -> 8
# [1, 2, 4, 4] -> 8
def GetMatchingPair(arr, match_num):
complement_set = set()
for i in arr:
if i in complement_set:
return (i, match_num - i)
else:
complement_set.add(match_num - i)
return False
if __name__ == "__main__":
print(GetMatchingPair([1, 2, 3, 9], 8))
print(GetMatchingPair([1, 2, 4, 4], 8))
|
c74c65937cf23be415c42cd93c54bf2394de6312 | chauhan14344/LetsUpgrade-Assignment | /Assignment 2/Empty_list.py | 299 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
# Python program to remove empty List from List
sample_list = ['ABC',123, [], "xyz", []]
new_list = [ele for ele in sample_list if ele != []]
print ("List after removing empty list : " + str(new_list))
# In[ ]:
# In[ ]:
# In[ ]:
|
758272a225e86bc04c147a312a0927faad73b19e | VPatel5/CS127 | /errorChecking.py | 260 | 4.09375 | 4 | # Name: Vraj Patel
# Email: vraj.patel24@myhunter.cuny.edu
# Date: November 08, 2019
# This program
age = int(input("Enter your age: "))
while age < 0:
print("You entered a negative number. Please try again")
age = int(input("Enter your age: "))
print("You entered:", age)
|
4127119b93c76dc8044d4c5950164ce419eb06db | preethika2308/code-kata | /set102.py | 53 | 3.515625 | 4 | kj=int(input())
while(kj%2==0):
kj=kj//2
print(kj)
|
fb7feb3dfb9f7e94aefc8e9924953d60b31efa67 | photonicDog/ramseytheoryresearch | /annealing + hill climb/annealing.py | 4,629 | 3.625 | 4 | """
This file "annealing.py" was made by Jackie Wedgwood for the University of Portsmouth.
This constitutes the simulated annealing algorithm of this project.
Associated files/folders:
graph.txt: adjacency list of initial graph
best.txt: adjacency list of best currently found graph
Notes:
This algorithm is more detailed in the report, and uses terminology from
said report. Details can be found in Chapter 4.2.
Run folders are designated as: run[index]-[genetic run index]-[final 5-clique count].
Imported module uses:
The "networkx" module is used for graph functionality and computation.
The "random" module is used to generate a random number when deciding
whether to transition to a neighbour state.
The "math" module is used for the natural exponent function.
The "decimal" module is used for the Decimal type for accurate calculations
during the annealing process.
"""
import networkx as nx
import random
import math
from decimal import Decimal
"""
give_K5_cliques(G):
one argument:
G, the graph to have its 5-clique count found
return:
the 5-clique count of G
This enumerates all the cliques of a graph and its complement and filters the list
by 5-cliques. The length of both lists are summed and returned.
"""
def give_K5_cliques(G):
C = [x for x in list(nx.clique.enumerate_all_cliques(G)) if len(x)==5]
Gc = nx.complement(G)
Cc = [x for x in list(nx.clique.enumerate_all_cliques(Gc)) if len(x)==5]
return(len(C)+len(Cc))
"""
annealing(G1, temp):
two arguments:
G1, the initial state
temp, the current temperature of the system
return:
the new active state (graph)
This gets a new graph with a random swapped edge which becomes the neighbour state,
and checks to see if it has less cliques. If it does, it becomes the new active state,
and is checked against the best recorded graph. If not, a value using the formula
exp(cliques difference/temp) is calculated, and measured against a random number between
0 and 1. If it is higher, it becomes the new active state anyway, otherwise nothing changes.
"""
def annealing(G1, temp):
nodes = list(G1.nodes())
random.shuffle(nodes)
node1 = nodes.pop()
node2 = nodes.pop()
G2 = change_edge(G1.copy(),node1,node2)
cliques1 = give_K5_cliques(G1)
cliques2 = give_K5_cliques(G2)
if cliques2 < cliques1:
write_best(G2)
return(G2)
else:
write_best(G1)
annealing = math.exp((cliques1 - cliques2) / temp)
if annealing > random.random():
return(G2)
else:
return(G1)
"""
find_new_graph(G):
one argument:
G, the initial graph in graph.txts
return:
the final result of this simulated annealing run
This checks to see if the system has cooled yet, and comprises the main loop
of the algorithm. It sets the temperature to 5, and starts the loop. If the
temperature has reached 0, it breaks loop and returns, otherwise it goes
through the annealing() function and the temperature decreases by the cooling
rate of 0.00001, and loops again.
"""
def find_new_graph(G):
temp = Decimal(5)
while temp <= 0:
G = annealing(G, temp)
temp -= Decimal(0.00001)
return(G)
"""
change_edge(G,node1,node2):
three arguments:
G, the graph being modified
node1, the first node
node2, the second node
return:
the modified graph
Two nodes of a graph are taken and it is checked if they contain an edge
together. If they do, that edge is removed, otherwise it is created. The
new graph is returned.
"""
def change_edge(G,node1,node2):
if G.has_edge(node1,node2) == True:
G.remove_edge(node1,node2)
else:
G.add_edge(node1,node2)
return(G)
"""
write_best(G):
one argument:
G, the graph to be compared to the current best
no return
The best graph is read from a file, and the 5-clique count of it and G are
found. If G has a higher 5-clique count, it overwrites best.txt and becomes
the new best saved graph
"""
def write_best(G):
best = nx.read_adjlist("graphs/best.txt")
if give_K5_cliques(G) < give_K5_cliques(best):
nx.write_adjlist(G,"graphs/best.txt")
"""
main():
no arguments
no return
Reads the initial graph and starts the main algorithm loop
"""
def main():
G = nx.read_adjlist("graphs/graph.txt")
while True:
G = find_new_graph(G)
# main call
main() |
85d761ce9c56d5af270bc66a3ef59be194a9ae1b | Aasthaengg/IBMdataset | /Python_codes/p02401/s528100480.py | 347 | 3.78125 | 4 | def solve(a, op, b):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a // b
return None
if __name__ == '__main__':
while True:
a, op, b = input().split()
if op == '?': break
print(solve(int(a), op, int(b))) |
5e326ea25fb6b80bcf1ab1026e4f1292b699b806 | gabrielreiss/URI | /1036.py | 579 | 3.59375 | 4 | #Leia 3 valores de ponto flutuante e efetue o cálculo das raízes da equação de Bhaskara.
# Se não for possível calcular as raízes, mostre a mensagem correspondente
# “Impossivel calcular”, caso haja uma divisão por 0 ou raiz de numero negativo.
a = float(input())
b = float(input())
c = float(input())
r1 = float()
r2 = float()
delta = b**2 - 4*a*c
if 2*a == 0 or delta<0:
print("Impossivel calcular")
else:
r1 = (-b + delta ** (1/2))/(2*a)
r2 = (-b - delta ** (1/2))/(2*a)
print('R1 = {:.5f}'.format(r1))
print('R2 = {:.5f}'.format(r2))
|
23f6c70508dcacbad1d7b4595877215143defd38 | DaviNakamuraCardoso/Use-a-Cabeca-Aprenda-a-Programar | /Code/HoteldeCachorroscomObjetos/dog_hotel.py | 4,784 | 4.03125 | 4 |
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return 'Eu sou uma pessoa e meu nome é ' + self.name
class DogWalker(Person):
def __init__(self, name):
Person.__init__(self, name)
def walk_the_dogs(self, dogs):
for dog_name in dogs:
dogs[dog_name].walk()
class Dog:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def bark(self):
if self.weight > 29:
print(self.name, 'diz WOOF WOOF')
else:
print(self.name, 'diz woof woof')
def human_years(self):
years = int(self.age) * 7
return years
def walk(self):
print(self.name, 'está andando')
def __str__(self):
return "Eu sou um cachorro chamado " + self.name
class ServiceDog(Dog):
def __init__(self, name, age, weight, handler):
Dog.__init__(self, name, age, weight)
self.handler = handler
self.is_working = False
def walk(self):
if self.is_working:
print(self.name, 'está ajudando', self.handler, 'a passear.')
else:
Dog.walk(self)
def bark(self):
if self.is_working:
print(self.name, 'diz: "Eu não posso latir, estou trabalhando."')
else:
Dog.bark(self)
class FrisbeeDog(Dog):
def __init__(self, name, age, weight):
Dog.__init__(self, name, age, weight)
self.frisbee = None
def bark(self):
if self.frisbee != None:
print(self.name, 'diz: "Eu não posso latir, tenho um frisbee na boca."')
else:
Dog.bark(self)
def catch(self, frisbee):
self.frisbee = frisbee
print(self.name, 'pegou um frisbee', frisbee.color )
def give(self):
if self.frisbee != None:
frisbee = self.frisbee
self.frisbee = None
print(self.name, 'devolve o frisbee', frisbee.color)
return frisbee
else:
print(self.name, 'não tem um frisbee.')
return None
def walk(self):
if self.frisbee != None:
print(self.name, 'diz: "Eu não posso andar, tenho um frisbee na boca."')
else:
Dog.walk(self)
def __str__(self):
str = 'Eu sou um cachorro chamado ' + self.name
if self.frisbee != None:
str = str + ' e eu tenho um frisbee'
return str
class Frisbee:
def __init__(self, color):
self.color = color
def __str__(self):
return 'O frisbee diz: "Eu sou um frisbee ' + self.color + '"'
class Hotel:
def __init__(self, name):
self.name = name
self.kennel = {}
def check_in(self, dog):
if isinstance(dog, Dog):
self.kennel[dog.name] = dog
print(dog.name, 'fez checkin no', self.name)
else:
print('Desculpe, apenas cachorros são permitidos no Hotel.')
def check_out(self, dog):
if dog.name in self.kennel:
temp = self.kennel[dog.name]
del self.kennel[dog.name]
print(dog.name, 'fez checkout com sucesso.')
return temp
else:
print('Desculpe,', dog.name, 'não está no hotel.')
return None
def bark_time(self):
for dog_name in self.kennel:
dog = self.kennel[dog_name]
dog.bark()
def walk_time(self):
for dog_name in self.kennel:
dog = self.kennel[dog_name]
dog.walk()
def hire_walker(self, walker):
if isinstance(walker, DogWalker):
self.walker = walker
else:
print('Desculpe, contratamos apenas Dog Walkers')
def walk_with_dogs(self):
if self.walker != None:
self.walker.walk_the_dogs(self.kennel)
class Cat():
def __init__(self, name):
self.name = name
def meow(self):
print(self.name, 'diz: "Meow."')
def test_code():
codie = Dog('Codie', 12, 38)
jackson = Dog('Jackson', 9, 12)
sparky = Dog('Sparky', 2, 14)
rody = ServiceDog('Rody', 8, 38, 'Joseph')
rody.is_working = True
dude = FrisbeeDog('Dude', 5, 20)
frisbee = Frisbee('vermelho')
dude.catch(frisbee)
kitty = Cat('Kitty')
hotel = Hotel('Doggie Hotel')
hotel.check_in(codie)
hotel.check_in(jackson)
hotel.check_in(sparky)
hotel.check_in(dude)
hotel.check_in(rody)
hotel.check_in(kitty)
hotel.bark_time()
joe = DogWalker('Joe')
hotel.hire_walker(joe)
hotel.walk_with_dogs()
hotel.check_out(codie)
hotel.check_out(jackson)
hotel.check_out(sparky)
hotel.check_out(dude)
hotel.check_out(kitty)
test_code()
|
addea3297f97a8516f35fb9a674b76b4d707389b | asikurr/Python-learning-And-Problem-Solving | /16.Chapter sixteen - Error Handling/error_errorRaise.py | 303 | 3.875 | 4 | # Syntex error
# Type error
# Name error
# function error
# index error
# indentation error
# Value Error
# Attribute Error
# Key Error
# Raise Error
def add(a,b):
if type(a) == int and type(b) == int:
return a+b
raise TypeError('Sorry you input wrong type value.')
print(add('3',4))
|
a2f76ba44ba904978f940de4021c0c71bc0064f9 | kondratYNN/OverOne | /kkk.py | 291 | 3.5 | 4 | def is_pol(text):
pol = text[:: -1]
if text == pol:
return True
else:
return False
def cred_card(number):
text = str(number)
last = text[-4:]
length = len(text) - 4
return '*' * length + last
print(cred_card(123445678))
print(is_pol('123321'))
|
5717f878025e9d8b532d9334ac4e4808685e57d3 | Albert-B-B/SygdomSim | /Main.py | 7,720 | 3.71875 | 4 | # -*- coding: utf-8 -*-
#Program simulates the spreading of a dissease
import tkinter as tk
from random import randrange
import sys
import time
import ParameterHandler as config
import random
import math
import matplotlib.pyplot as plt
#Initializes settings
args = sys.argv
config.initializeConfig(args)
#Parameters of canvas height and width
widthCanvas = config.getVal("-width")
heightCanvas = config.getVal("-height")
#Sets up tkinter canvas
root = tk.Tk()
canvas = tk.Canvas(root,height=heightCanvas,width=widthCanvas,background="grey")
canvas.pack()
#Tracks time
loop_factor = 0
#Arrays to store how many people are en each state at each iteration
dataHealthy = []
dataSick = []
dataDead = []
dataImune = []
dataTempImune = []
#Class representing one agent
class person:
def __init__(self,status,x,y,color):
#0 for non contaminated and 1 for infected.
self.status = status
#Coordinates of person in xy plane
self.x = x
self.y = y
self.color = color
self.TimeOfMovement = 0
self.healthyTime = 0 #How much time person has left as temporarily imune
#Updates direction traveled
def move(self):
#What angle it need to travel
Angle = randrange(0,360)
#How much time until it changes direction
TOM = randrange(config.getVal("-turnIntervalMin"),config.getVal("-turnIntervalMax"),1)
SPEED = config.getVal("-speed")
#Translates this into how fast it should travel in each direction
Movementx = math.cos(math.radians(Angle))*SPEED
Movementy = math.sin(math.radians(Angle))*SPEED
#Stops dead people moving
if self.status == 2:
Movementx = 0
Movementy = 0
return Movementx, Movementy, TOM
#Draws the agent on tkinter canvas
def draw(self):
r = config.getVal("-squareLength") #Radius of square drawn
canvas.create_rectangle(self.x-r, self.y-r, self.x+r, self.y+r, fill=self.color) #Draws the square
#See if persons direction should change
if self.TimeOfMovement <= 0:
self.Movex, self.Movey, self.TimeOfMovement = self.move()
#Moves person in the choosen direction
elif self.TimeOfMovement > 0:
self.x += self.Movex * loop_factor
self.y += self.Movey * loop_factor
self.TimeOfMovement -= loop_factor
#Makes sure people don't move out of bounds
self.x = self.x % widthCanvas
self.y = self.y % heightCanvas
else:
print("Error: TimeOfMovement below threshold")
#So you can print object interformation
def __str__(self):
return "Status: {} Position: {},{} Color: {}".format(self.status,self.x,self.y,self.color)
def spread(self, folk):
spreadType = config.getVal("-spreadType") #How it spreads from each person currently only one option
spreadRadius = config.getVal("-spreadRadius") #How cole people need to be to spread dissease
#Chances of changing into different state 1.
deathChance = config.getVal("-chanceDeath")
imunityChance = config.getVal("-chanceImune")
healthyChance = config.getVal("-chanceHealthy")
if self.status == 1:
#Checks for every other person if they are so close as to spread disease to.
for i in folk:
if spreadType == 0:
if i.status == 0 and math.sqrt((self.x-i.x)**2+(self.y-i.y)**2) <= spreadRadius:
#Does makes it so it doesn't imeadieately spread from the person
i.status = -1
#Checks for how a persons state changes
if random.random() < deathChance*loop_factor:
self.status = -2
self.TimeOfMovement = 0
elif random.random() < imunityChance*loop_factor:
self.status = -3
elif random.random() < healthyChance*loop_factor:
self.status = 4
self.color = "yellow"
self.healthyTime = random.randint(config.getVal("-tempImuneMin"),config.getVal("-tempImuneMax"))
#Handles the result of spreading
def resolveSpread(self):
#Makes people sick
if self.status == -1:
self.status = 1
self.color = config.getVal("-sickColor")
#Person died
elif self.status == -2:
self.status = 2
self.color = config.getVal("-deathColor")
#Person became permanantly imune
elif self.status == -3:
self.status = 3
self.color = config.getVal("-imuneColor")
#Person is temporarily imune and we remove some of the time left as temporary imunity
elif self.status == 4:
self.healthyTime -= 1*loop_factor
if self.healthyTime <= 0:
self.status = 0
self.color = config.getVal("-healthyColor")
#Not yet added feuture
class ManInBlack(person):
pass
#Array that saves every person object
people = []
numPep = config.getVal("-pop") #Number of people
#Adds initial healthy people at random locations
for i in range(numPep):
people.append(person(0,random.randint(0, widthCanvas),random.randint(0,heightCanvas),"blue"))
#Adds initial sick people in random locations
for i in range(config.getVal("-randInitialSick")):
people.append(person(1,random.randint(0, widthCanvas),random.randint(0,heightCanvas),"blue"))
#Spreads disease troughout the entire population
def spreadPop():
global people
for i in people:
i.spread(people)
for i in people:
i.resolveSpread()
#Saves how many people are at each state at time of calling
def recordData():
global dataHealthy
global dataSick
global dataDead
global dataImune
global dataTempImune
statusCount = [0,0,0,0,0]
for i in people:
statusCount[i.status] += 1
dataHealthy.append(statusCount[0])
dataSick.append(statusCount[1])
dataDead.append(statusCount[2])
dataImune.append(statusCount[3])
dataTempImune.append(statusCount[4])
#Shows a plot of the data about states
def showData():
points = list(range(len(dataHealthy))) # Number of observations
#Adds a curve for each state measured
plt.plot(points,dataHealthy,"b",points,dataSick,"r",points,dataDead,"k",points,dataImune,"cyan",points,dataTempImune,"y")
plt.savefig("graf.png")
plt.show()
#Main loop
done = False #Tracks if main loop should end
while True:
canvas.delete("all") #Clears canvas
canvas.create_rectangle(0, 0, heightCanvas, widthCanvas, fill="grey") #draws a grey background
start_time = time.time() #Saves time when iteration started
#Draws each person but canvas is not updated
for person in people:
person.draw()
#Updates canvas
canvas.pack()
root.update_idletasks()
root.update()
spreadPop() #Spreads dissease troughout population
loop_factor = (time.time() - start_time) #Calculates how long calculations took
recordData() #Saves the number of people in each state
#Checks if program need to end
if done:
break
#Checks if anyone is infected if no one is the program exists
done = True
for person in people:
if person.status==1:
done = False
break
#counts the number of dead people
dead = 0
for i in people:
if i.status == 2:
dead += 1
showData() #Shows graph
print("Dead: " + str(dead)) # prints number of people
input("Time stop") #Input to stop program from exiting
root.destroy() #Closes window with tkinter canvas |
981ebe5fcce1f482230307d8af8dbb2d0248f0a3 | saumya-singh/CodeLab | /HackerRank/Implementation/Modified_Kaprekar_Number.py | 1,118 | 3.703125 | 4 | #https://www.hackerrank.com/challenges/kaprekar-numbers/problem
import sys
def kaprekarNumber(a, b):
#print("entered")
list1 = []
for i in range(a, b+1):
#print("i-----", i)
digit_count = 0
num = i
while num != 0:
digit_count += 1
num = num//10
#print("digit_count", digit_count)
square = i * i
#print("square-------", square)
#square_copy = square
count = 0
r = 0
while (count < digit_count):
digit = square % 10
square = square // 10
r = r + digit * (10 ** count)
count += 1
l = square
#print("l-------", l)
#print("r-------", r)
if l + r == i:
list1.append(i)
return list1
if __name__ == "__main__":
a = int(input().strip())
b = int(input().strip())
ans_list = kaprekarNumber(a, b)
if len(ans_list)==0:
print("INVALID RANGE")
else:
l = " ".join([str(i) for i in ans_list])
print(l) |
3482c6f0728681da77886cfc95457f699e2510d8 | alexk101/dimensionality_reduction_measures | /Test_Umap/Test1/plot_mnist_example.py | 989 | 3.84375 | 4 | """
UMAP on the MNIST Digits dataset
--------------------------------
A simple example demonstrating how to use UMAP on a larger
dataset such as MNIST. We first pull the MNIST dataset and
then use UMAP to reduce it to only 2-dimensions for
easy visualisation.
Note that UMAP manages to both group the individual digit
classes, but also to retain the overall global structure
among the different digit classes -- keeping 1 far from
0, and grouping triplets of 3,5,8 and 4,7,9 which can
blend into one another in some cases.
"""
import umap
from sklearn.datasets import fetch_openml
import numpy
mnist = fetch_openml("mnist_784", version=1)
reducer = umap.UMAP(random_state=42)
embedding = reducer.fit_transform(mnist['data'])
output = open(r"/home/alexk101/Documents/Research_2020/tests/Test_Umap/Test1/UMAP_2D.txt","w")
output.write("70000 2 \n")
numpy.savetxt("/home/alexk101/Documents/Research_2020/tests/Test_Umap/Test1/UMAP_2D.txt",embedding)
output.close()
print("Test Complete")
|
50ad479d2ff02f03c2caab36e2a2306d1df13026 | threadstonesecure/aws_dynamo_db_python | /src/04_query_and_scane.py | 1,224 | 3.609375 | 4 | # https://pynamodb.readthedocs.io/en/latest/batch.html
# Query Filters
# You can query items from your table using a simple syntax:
from project_setting import User
from datetime import datetime
for item in User.query('2', User.first_name.startswith('a')):
print("Query returned item {0}".format(item))
# Additionally, you can filter the results before they are returned using condition expressions:
for item in User.query('3', User.first_name == 'Subject', User.birthday > datetime(1990, 1, 1)):
print("Query returned item {0}".format(item))
# DynamoDB only allows the following conditions on range keys:
# ==, <, <=, >, >=, between, and startswith.
# DynamoDB does not allow multiple conditions using range keys.
# Scan Filters
# Scan filters have the same syntax as Query filters, but support all condition expressions:
for item in User.scan(User.last_name.startswith('Re') & (User.birthday > datetime(1991, 2, 1))):
print(item)
# Limiting results
# Both Scan and Query results can be limited to a maximum number of items using the limit argument.
for item in User.query('66', User.first_name.startswith('Mi'), limit=5):
print("Query returned item {0}".format(item))
# TODO 上面例子待测试
|
d90205216850485130f96368955e4205252f2350 | puneetb97/Python_course | /day2/bmi_cal_hindi.py | 297 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 18:32:46 2019
@author: Puneet
"""
# my height and weight
my_height = float(input('\u0932\u0951\u092C\u093E\u0908:'))
my_weight = int(input('\u0935\u091C\u0928:'))
# calculate bmi value
bmi_value = (my_weight/my_height)/my_height
print(bmi_value) |
22c4a9ec609e30ffac362ed12529a6a80a5da002 | thecocce/random-generate | /states.py | 12,915 | 3.640625 | 4 | import pygame
import random
import sprites
import settings
import resources
import templates
# State template class
class States(object):
# Initialize the states class
def __init__(self):
self.done = False
self.next = None
self.quit = False
self.previous = None
# Level template class
class Level(States):
# Initialize the game state
def __init__(self):
States.__init__(self)
# If quit on exit is true, the game will reset instead of going to the next level when exiting
self.quit_on_exit = False
# Function that generates a level randomly
def generate_level(self):
# Creating the solution path list
level = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
row = 0
# Placing the entrance randomly
col = random.randint(0, 3)
level[row][col] = 1
while True:
direction = random.randint(1, 5)
previous = (row, col)
if direction == 1 or direction == 2:
col -= 1
elif direction == 3 or direction == 4:
col += 1
else:
row += 1
if col < 0:
col += 1
row += 1
if col > 3:
col -= 1
row += 1
if row > 3:
break
if previous[0] < row:
level[previous[0]][previous[1]] = 2
level[row][col] = 3
elif level[row][col] == 0:
level[row][col] = 1
# Place the outer walls
border_top = sprites.Wall(0, 0, 66*32, 32)
border_left = sprites.Wall(0, 0, 32, 66*32)
border_bottom = sprites.Wall(0, 65*32, 66*32, 32)
border_right = sprites.Wall(65*32, 0, 32, 66*32)
self.walls.add(border_top)
self.walls.add(border_left)
self.walls.add(border_bottom)
self.walls.add(border_right)
# Generating the level
current_template = None
level_x = 32
level_y = 32
exit = True
for rows in level:
for cols in rows:
# Switching to the correct template
if cols == 0:
current_template = templates.templates_all[random.randrange(0, len(templates.templates_all))]
if cols == 1:
current_template = templates.templates_lr[random.randrange(0, len(templates.templates_lr))]
elif cols == 2:
current_template = templates.templates_tlbr[random.randrange(0, len(templates.templates_tlbr))]
elif cols == 3:
current_template = templates.templates_tlr[random.randrange(0, len(templates.templates_tlr))]
temp_level_x = level_x
temp_level_y = level_y
# Randomly flip the template
if random.randint(0, 1) == 1:
for flip in current_template:
flip.reverse()
# Creating the level
for temp_rows in current_template:
for temp_cols in temp_rows:
if temp_cols == 1:
w = sprites.Wall(temp_level_x, temp_level_y, 32, 32)
self.walls.add(w)
if temp_cols == -1:
if exit:
w = sprites.Wall(temp_level_x, temp_level_y, 32, 64, settings.green)
self.exits.add(w)
exit = False # Place exit in first room place
if cols != 0:
# Player starting position at last room made, -1 position, if room is part of solution path
self.player_x = temp_level_x
self.player_y = temp_level_y
if temp_cols == 2:
w = sprites.Wall(temp_level_x, temp_level_y, 32, 32, image=resources.ladder)
self.ladders.add(w)
temp_level_x += 32
temp_level_x = level_x
temp_level_y += 32
level_x += 16 * 32
level_x = 32
level_y += 16 * 32
for x in level:
print(x)
# Starting the Level state
def init_level(self):
# Sprite groups
self.exits = pygame.sprite.Group()
self.walls = pygame.sprite.Group()
# PLayer position variables
self.player_x = 0
self.player_y = 0
# Generate the level
self.generate_level()
# Creating an instance of the player
self.player = sprites.Player(self.player_x, self.player_y, self.walls)
self.max_y_offset = (66 - 20) * 32
# We blit surfaces to the world surface, then blit the world surface to the game display
self.world_surface = pygame.Surface((66*32, 66*32))
# Camera variables
self.cam_x_offset = 0
self.cam_y_offset = self.max_y_offset
self.camera = sprites.Camera(self.player)
# Place the camera at the game's exit
for cam_start in self.exits:
self.camera.rect.x, self.camera.rect.y = (cam_start.rect.x, cam_start.rect.y)
break
# Screen shake variables
self.shake_amount = 10
# Common events function
def events(self, event):
if event.type == pygame.QUIT:
self.quit = True
if event.type == pygame.KEYDOWN:
# Player jumping
if event.key == pygame.K_SPACE:
if self.player.jumping and not self.player.ghost_jump:
self.player.test_for_jump()
else:
self.player.jump()
# Go to next level if player is standing within the exit
if event.key == pygame.K_w and self.player.in_exit:
if not self.quit_on_exit:
self.done = True
else:
self.quit = True
if event.key == pygame.K_g:
self.player.boost = not self.player.boost
# Common updates function
def updates(self):
self.camera.update()
# Horizontal Camera scrolling
self.cam_x_offset = self.camera.rect.center[0] - settings.display_width / 2
self.cam_x_offset = max(0, self.cam_x_offset)
self.cam_x_offset = min(((66 - 25) * 32, self.cam_x_offset))
# Vertical Camera scrolling
self.cam_y_offset = self.camera.rect.center[1] - settings.display_height / 2
self.cam_y_offset = max(0, self.cam_y_offset)
self.cam_y_offset = min(self.max_y_offset, self.cam_y_offset)
# Slowly stop screen shake
if self.shake_amount > 0:
self.shake_amount -= 0.5
# If player is out of view, reset the game
if self.player.rect.top > 64 * 32:
self.startup()
# Common draws function
def draws(self, screen):
self.world_surface.fill(settings.white)
# Draw the player, walls and exits
self.exits.draw(self.world_surface)
self.walls.draw(self.world_surface)
self.player.draw(self.world_surface)
#self.camera.draw(self.world_surface)
# Blit the world surface to the main display
# If shake amount is more than 0, blit the world at a random location between
# negative and positive shake amount, instead of 0, 0
if self.shake_amount > 0:
screen.blit(self.world_surface, (random.randint(int(-self.shake_amount), int(self.shake_amount))-self.cam_x_offset,
random.randint(int(-self.shake_amount), int(self.shake_amount))-self.cam_y_offset))
else:
screen.blit(self.world_surface, (0-self.cam_x_offset, 0-self.cam_y_offset))
# Test if the player is within an exit's boundaries
def test_for_exits(self, player):
for exits in self.exits:
if exits.rect.colliderect(player.rect):
self.player.in_exit = True
break
else:
self.player.in_exit = False
# Menu state
class Menu(States):
# Initialize the menu state
def __init__(self):
States.__init__(self)
self.next = "level_1"
self.startup()
# Font rendering function
def render_text(self, msg, color, size, dest_surf, pos):
font = pygame.font.Font(settings.font_file, size)
font_surf = font.render(msg, False, color)
font_rect = font_surf.get_rect()
font_rect.center = pos
dest_surf.blit(font_surf, font_rect)
# Cleaning up the menu state
def cleanup(self):
pass
# Starting the menu state
def startup(self):
self.play_color = settings.orange
self.quit_color = settings.black
self.selected = "play"
# State event handling
def get_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
self.selected = "play"
if event.key == pygame.K_s:
self.selected = "quit"
if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
if self.selected == "play":
self.done = True
if self.selected == "quit":
pygame.quit()
quit()
# Update the menu state
def update(self, display):
self.draw(display)
if self.selected == "play":
self.play_color = settings.orange
else:
self.play_color = settings.black
if self.selected == "quit":
self.quit_color = settings.orange
else:
self.quit_color = settings.black
# Menu state drawing
def draw(self, screen):
screen.fill((255, 255, 255))
self.render_text("PLAY", self.play_color, 75, screen, (400, 325))
self.render_text("QUIT", self.quit_color, 75, screen, (400, 400))
# Level 1 state
class Level_1(Level):
# Initialize the game state
def __init__(self):
Level.__init__(self)
self.next = "level_2"
# Cleaning up the game state
def cleanup(self):
pass
# Starting the game state
def startup(self):
# Initializing the common level variables
self.init_level()
# State event handling
def get_event(self, event):
self.events(event)
# Update the game state
def update(self, display):
self.player.update()
self.updates()
self.test_for_exits(self.player)
self.draw(display)
# game state drawing
def draw(self, screen):
self.draws(screen)
# Level 2 state
class Level_2(Level):
# Initialize the game state
def __init__(self):
Level.__init__(self)
self.next = "menu"
# Cleaning up the game state
def cleanup(self):
pass
# Starting the game state
def startup(self):
# Initializing the common level variables
self.init_level()
# State event handling
def get_event(self, event):
self.events(event)
# Update the game state
def update(self, display):
self.player.update()
self.updates()
self.test_for_exits(self.player)
self.draw(display)
# game state drawing
def draw(self, screen):
self.draws(screen)
# Level 3 state
class Level_3(Level):
# Initialize the game state
def __init__(self):
Level.__init__(self)
self.next = "menu"
# Cleaning up the game state
def cleanup(self):
pass
# Starting the game state
def startup(self):
# Initializing the common level variables
self.init_level()
# State event handling
def get_event(self, event):
self.events(event)
# Update the game state
def update(self, display):
self.player.update()
self.updates()
self.test_for_exits(self.player)
self.draw(display)
# game state drawing
def draw(self, screen):
self.draws(screen)
# List of all levels (used for randomizing level order)
def setup_list():
return [Level_1(), Level_2(), Level_3()]
level_list = setup_list()
|
1007e743805b43d67c9c04ba5e85f2d390ba1067 | Boissineau/challenge-problems | /Amazon/PowerOfTwo.py | 470 | 3.703125 | 4 | class Solution(object):
def isPowerOfTwo(self, n):
def div(self, n):
if n <= 0: return False
while(n % 2 == 0): n /= 2
return n == 1
if n <= 0: return False
return !(n & (n-1))
if n == 1: return True
if n % 2 != 0 or n == 0: return False
return div(self, n/2)
return div(self, n) |
7e22bd38db2c9d671b39f3aae884c48021c76fb0 | Matthew1996i/Exercicios_Uri | /1036.py | 407 | 3.609375 | 4 | import math
entrada = input().split(" ")
a,b,c = entrada
a = float(a)
b = float(b)
c = float(c)
if (a != 0):
delta = pow(b,2) - (4*a*c)
if(delta > 0):
x1 = (-b + math.sqrt(delta))/(2*a)
x2 = (-b - math.sqrt(delta))/(2*a)
print("R1 = %.5f" %x1)
print("R2 = %.5f" %x2)
elif(delta < 0):
print("Impossivel calcular")
else:
print("Impossivel calcular")
|
d20d2960e5f5c30bbf89fadc23b649a702abd68e | mgorgei/codeeval | /Medium/c54 Cash Register.py | 2,065 | 4.0625 | 4 | '''CASH REGISTER
The goal of this challenge is to design a cash register program. You will be
given two float numbers. The first is the purchase price (PP) of the item. The
second is the cash (CH) given by the customer. Your register currently has the
following bills/coins within it:
'PENNY': .01,
'NICKEL': .05,
'DIME': .10,
'QUARTER': .25,
'HALF DOLLAR': .50,
'ONE': 1.00,
'TWO': 2.00,
'FIVE': 5.00,
'TEN': 10.00,
'TWENTY': 20.00,
'FIFTY': 50.00,
'ONE HUNDRED': 100.00
The aim of the program is to calculate the change that has to be returned to the
customer.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. The input
file contains several lines. Each line is one test case. Each line contains two
numbers which are separated by a semicolon. The first is the Purchase price (PP)
and the second is the cash(CH) given by the customer. eg.
15.94;16.00
17;16
35;35
45;50
OUTPUT SAMPLE:
For each set of input produce a single line of output which is the change to be
returned to the customer. In case the CH < PP, print out ERROR. If CH == PP,
print out ZERO. For all other cases print the amount that needs to be returned,
in terms of the currency values provided. The output should be sorted in
highest-to-lowest order (DIME,NICKEL,PENNY). eg.
NICKEL,PENNY
ERROR
ZERO
FIVE
'''
def f(test='15.94;16.00'):
test = [float(x) for x in test.rstrip().split(';')]
purchase_price = test[0]
cash = test[1]
if cash < purchase_price:
return 'ERROR'
if cash == purchase_price:
return 'ZERO'
result = ""
change = round(cash - purchase_price, 2)
words = ['ONE HUNDRED', 'FIFTY', 'TWENTY', 'TEN', 'FIVE', 'TWO', 'ONE',
'HALF DOLLAR', 'QUARTER', 'DIME', 'NICKEL', 'PENNY']
value = [100.0,50.0,20.0,10.0,5.0,2.0,1.0,.50,.25,.1,.05,.01]
while change > 0.00:
for ch in range(len(words)):
if change >= value[ch]:
result += words[ch] + ','
change = round(change - value[ch], 2)
break
print(result[:-1])
|
a73ed18ce796559e8389086391384a68e0f4f3be | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_136/2857.py | 716 | 3.578125 | 4 | import sys
def input_generator():
for line in sys.stdin:
for token in line[:-1].split(' '):
if token != '' or token:
yield token
myin = input_generator()
def calcBestTime(C, F, X):
rate = 2.0
minTime = X / rate
tElapsed = 0
while True:
tElapsed += C / rate
rate += F
curTime = tElapsed + (X / rate)
if curTime > minTime:
return minTime
else:
minTime = curTime
if __name__ == '__main__':
tests = int(myin.next())
for t in range(tests):
minTime = calcBestTime(float(myin.next()), float(myin.next()), float(myin.next()))
print 'Case #' + str(t+1) + ': ' + str(minTime)
|
e8b022bd755fc17708a16493a70502eb3e15b60a | marlondocouto/PythonProgramming | /assignment3.py | 717 | 4.53125 | 5 | #assignment3.py
#Calculates the cost per square inch of a circular pizza
import math #makes math library available
def cost_square():
#introduction to program
print("This program computes the cost per square inch of a pizza.")
print()
#inputs are diameter and price of pizza:
diameter=int(input("Enter the diameter of the pizza (in inches): "))
price=int(input("Enter the price of the pizza (in cents): "))
#processing of input:
cost_square=price/(((diameter/2)**2)*math.pi)
print()
#output message:
print("The cost per square inch is", round(cost_square,2))
print()
input("Press the <Enter> key to shut down the program")
cost_square()
|
02ccf97881a8a7cc4fb62e159cf0c2f15858fe9b | chaerui7967/K_Digital_Training | /Python_KD_basic/HW/1_채길호_0520.py | 1,507 | 3.59375 | 4 | # 1번 1)문제
for i in range(5, 0, -1):
for j in range(i):
print('☆', end='')
print()
# 다른 방법
for i in range(5): print('*' * (5-i))
# 1번 2)문제
for i in range(6):
for j in range(5, i, -1):
print(' ', end="")
for z in range(i*2-1):
print('☆', end='')
print()
# 다른 방법
for i in range(1, 6):
char = '*' * (2*i -1)
print(f'{char : ^9s}') # ^9s 중앙 정렬 9자 문자열
# 다른 방법
for i in range(1,6):
print(' '*(5-i) + '*'*(2*i-1))
# 2번 문제
an = input('숫자 입력 : ')
while True:
if an == "7":
print('7 입력! 종료')
break
an = input('다시 입력 : ')
# 다른 방법
userInput = int(input('숫자 입력 : '))
while (userInput != 7):
userInput = int(input('다시 입력 : '))
print('7 입력! 종료')
# 3번 문제
mo, s, c = 10000, 2000, 0
while mo > 0:
c += 1
print(f'노래를 {c}곡 불렀습니다.')
if mo > 0:
mo -= s
if mo == 0:
print('잔액이 없습니다. 종료합니다.')
break
else:
print(f'현재 {mo}원 남았습니다.')
#다른 방법
f, balance, numSong = 2000, 10000, 0
while (balance >0):
numSong += 1
print(f'노래를 {numSong}곡을 불렀습니다.')
if balance > 0:
balance -= f
if balance == 0:
print('잔액이 없습니다. 종료합니다.')
break
else: print(f'현재 {balance}원 남았습니다.')
|
96ed40b932a8a921be3a7ff2173ca49eda21d1d4 | Nikhil8595/python-programs | /new student.py | 98 | 3.5 | 4 | a="Nikhil","hello"
print(a[0:6:3])
#print(a.split())
a=('hello,world')
a=a.split()
print(a) |
8c05745166b9bab15226d52d404ebf87ea233395 | wanglinjie/coding | /leetcode/poweroffour.py | 838 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# date:20160516
'''Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
不使用循环或者递归的情况,可以判断数num中有几个1,以及1所在位置
4的幂中只有一个1,而且1所在的位置应该是奇数位上
'''
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return True
result = 1
while result < num:
result = result << 2
if result == num:
return True
return False
so = Solution()
if so.isPowerOfFour(64):
print "True"
else:
print "False" |
24b151b34bcc789c898b5a9fefa30bcb34fe7373 | shahidshabir055/python_programs | /findpairs.py | 580 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 11:08:32 2019
@author: eshah
"""
#PF-Assgn-34
def find_pairs_of_numbers(num_list,n):
#Remove pass and write your logic here
pairs=0
for i in range(0,len(num_list)-1):
for j in range(i+1,len(num_list)):
#print(num_list[i])
#print(num_list[j])
if(num_list[i]+num_list[j]==n):
pairs=pairs+1
if(pairs!=0):
return pairs
else:
return 0
num_list=[1,2,3,4,5,6]
n=6
print(find_pairs_of_numbers(num_list,n)) |
d43ad30504a5de193cc1be7462fd1c4978cf8a25 | eric496/leetcode.py | /hash_table/966.vowel_spellchecker.py | 3,013 | 4.53125 | 5 | """
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
For a given query word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.
Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow"
Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
Example: wordlist = ["yellow"], query = "yellow": correct = "yellow"
Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)
Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match)
In addition, the spell checker operates under the following precedence rules:
When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
When the query matches a word up to capitlization, you should return the first such match in the wordlist.
When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
If the query has no matches in the wordlist, you should return the empty string.
Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].
Example 1:
Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]
Note:
1 <= wordlist.length <= 5000
1 <= queries.length <= 5000
1 <= wordlist[i].length <= 7
1 <= queries[i].length <= 7
All strings in wordlist and queries consist only of english letters.
"""
class Solution:
def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
case, vowel = {}, {}
for w in wordlist:
lower, devow = w.lower(), self.devowel(w.lower())
if lower not in case:
case[lower] = w
if devow not in vowel:
vowel[devow] = w
wordset = set(wordlist)
res = []
for q in queries:
lower, devow = q.lower(), self.devowel(q.lower())
if q in wordset:
res.append(q)
elif lower in case:
res.append(case[lower])
elif devow in vowel:
res.append(vowel[devow])
else:
res.append("")
return res
def devowel(self, s: str) -> str:
res = []
for c in s:
if c in list("aeiou"):
res.append("#")
else:
res.append(c)
return "".join(res)
|
6675713ff572942df922d199a57a0bfa467cd643 | sfitzsimmons/Exercises | /DistanceFrom17.py | 287 | 4.21875 | 4 | # this exercise wants me to write a program that determines the difference between a given number and 17.
given_number = int(input("Enter a number: "))
difference = abs(given_number - 17)
print(f"The difference between your number ({given_number}) and 17 is: {difference}.")
|
131d7e618c3d02b01ab5fee5e04dd18fb133431a | hsn-ylmz/Python-Projects | /Cancer(wdbc)/wdbc_artifical_neural_network.py | 2,164 | 3.6875 | 4 | # Artificial Neural Network Approach
import numpy as np
import pandas as pd
dataset = pd.read_csv('D:/Cancer/wdbc.csv', header = None)
X = dataset.iloc[:,2:].values
y = dataset.iloc[:, 1]
# Encoding Categorical Data
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
y = labelencoder.fit_transform(y)
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# Importing Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the Artificial Neural Network
classifier = Sequential()
# Adding the input layer and first hidden layer
classifier.add(Dense(10, input_shape=(30,), kernel_initializer = 'uniform', activation = 'relu'))
# Adding the second hidden layer
classifier.add(Dense(5, kernel_initializer = 'uniform', activation = 'relu'))
# Adding the output layer
classifier.add(Dense(1, kernel_initializer = 'uniform', activation = 'sigmoid'))
# Compiling the Artificial Neural Network
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics=['accuracy'])
# Fitting the Artificial Neural Network to the trainig set
classifier.fit(X_train, y_train, batch_size = 50, epochs = 100)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Accuracy of test set
score = classifier.evaluate(X_test, y_test)
print("\n%s: %.2f%%" % (classifier.metrics_names[1], score[1]*100))
# Makig the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
weights = classifier.get_weights()
# Visualising Model
from keras.utils.vis_utils import plot_model
plot_model(classifier, to_file='D:/Cancer/model_plot.png', show_shapes=True, show_layer_names=True)
# Visualising Network
from ann_visualizer.visualize import ann_viz
ann_viz(classifier, title="wdbc_cancer_ann_model")
|
d533ef5f993248b72d12d3d14df6f9fb1252f024 | pudasainishushant/python_session | /question_3.py | 529 | 4.40625 | 4 | """
Q3 . Create a function that converts a date formatted as mm//dd/yyyy to yyyyddmm.
example ----> input 07/09/2020 to 20200907
"""
def date_converter(input_format_date):
revered_date = input_format_date.split("/")[::-1]
final_date = "".join(revered_date)
return final_date
input_date = "07/09/2020"
converted_date = date_converter(input_date)
print(converted_date)
# paragraph = "Suzan is reading Python. He want to learn Python. He is a good learner."
# sentences = paragraph.split(" ")
# print(sentences) |
e5fd6edb81c16a0355648f7c1c4b9473c8fbc968 | root-z/exercises | /bst.py | 4,475 | 4.21875 | 4 | """
Implementation of Binary Search Tree.
"""
class BSTreeNode:
def __init__(self, value):
self._value = value
self._left = None
self._right = None
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
@property
def left(self):
return self._left
@left.setter
def left(self, value):
self._left = value
@property
def right(self):
return self._right
@right.setter
def right(self, value):
self._right = value
class BSTree:
"""
BST
"""
def __init__(self):
self.root = None
def insert(self, node: BSTreeNode):
"""
insert a node to the tree
"""
if self.root is None:
self.root = node
else:
self.insert_node(self.root, node)
def print_tree(self):
"""
print the tree
"""
self.print_subtree(self.root)
def print_subtree(self, node: BSTreeNode, indent=0):
"""
class method for printing tree
"""
if node is not None:
print(indent*' ' + str(node.value))
self.print_subtree(node.left, indent+2)
self.print_subtree(node.right, indent+2)
def insert_num(self, num):
"""
inserting element to the tree. creates a new node
"""
self.insert(BSTreeNode(num))
def insert_node(self, root: BSTreeNode, new: BSTreeNode):
if root < new:
if root.right is None:
root.right = new
new.previous = root
else:
self.insert_node(root.right, new)
else: # new > old, assuming no equal
if root.left is None:
root.left = new
new.previous = root
else:
self.insert_node(root.left, new)
def find(self, num):
"""
find node that contains the given value
"""
curr = self.root
while True:
if curr.value == num:
return curr
elif curr.value < num:
if curr.right is None:
raise Error('not found')
else:
curr = curr.right
else:
if curr.left is None:
raise Error('not found')
else:
curr = curr.left
def delete(self, node: BSTreeNode):
"""
delete existing node
"""
if self.root == node:
self.root = None
return
curr = self.root
previous = None
while True:
if curr is None:
raise Error('Not found!')
if curr < node:
previous = curr
curr = curr.right
left = False
elif curr > node:
previous = curr
curr = curr.left
left = True
else:
if curr.left is None:
curr = curr.right
elif curr.right is None:
curr = curr.left
else: # have both left and right
last_left, last_previous = find_last_left(curr.right)
if last_left == curr.right:
curr.right.left = curr.left
curr = curr.right
else:
last_previous.left = last_left.right
last_left.right = curr.right
last_left.left = curr.left
curr = last_left
break
if left:
previous.left = curr
else:
previous.right = curr
def find_last_left(node):
curr = node
previous = None
while True:
if curr.left is None:
return (curr, previous)
else:
previous = curr
curr = curr.left
if __name__ == '__main__':
t = BSTree()
t.insert_num(1)
t.insert_num(2)
t.print_tree()
x = t.find(2)
print(x.value)
t.delete(x)
t.print_tree()
|
8f353f1f466989a38b45405eaec53da7a38d3d2c | 190330228/Sample | /date.py | 175 | 3.90625 | 4 | import datetime
dt = datetime.datetime.now()
time = dt.strftime("%H:%M:%S")
to = datetime.date.today()
print("The current time is ",time)
print("The current Date is ",to) |
272b4beb90499301a1d9f9544e942628c3a0c9d5 | mws19901118/Leetcode | /Code/Lowest Common Ancestor of a Binary Tree.py | 934 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root is p or root is q: #If root is none or root is p or q, return itself.
return root
left = self.lowestCommonAncestor(root.left, p, q) #Get the LCA of p and q in the tree whose root is the left child of current root.
right = self.lowestCommonAncestor(root.right, p, q) #Get the LCA of p and q in the tree whose root is the right child of current root.
if left and right: #If root is not the LCA of p and q, either p or q must be none.
return root
else:
return left if left else right
|
1b7f5ead5f24c952574b392e73c939bcb474ea5f | project-cemetery/python-functional-programming | /01-func.py | 94 | 3.5 | 4 | def func(lst, n):
l = list(lst)
for i in range(n):
l.append(i)
return l
|
f02ef9ed03b7254f6e1ac9bc5d405b0a356a23c5 | asterter5/Universidad | /1. Primero/Algorismica/practica4/inversio.py | 351 | 3.546875 | 4 | def inversio():
print "Aquest programa calcula el temps (en anys) en el que\nuna inversio cualsevol tarda en doblarse."
temps = 0
inv = 1
apr = input("Introdueix el interes de la teva inversio (en %): ")
while (inv < 2):
inv = inv * (1 + (apr/100.0))
temps = temps + 1
print "El temps que tarda la inversio en doblarse es ", temps, " anys."
|
ed3be2d45b317f389bfb2ed3225d5f464d126e7e | sidv/Assignments | /Aneena/Aug11/greatest_amoung4.py | 484 | 4.03125 | 4 | #greatest amoung four
num1=int(input("Enter the first number\n"))
num2=int(input("Enter the second number\n"))
num3=int(input("Enter the third number\n"))
num4=int(input("Enter the fourth number\n"))
if num1 > num2 and num1 > num3 and num1 > num4:
print(str(num1)+"is greater")
elif num2 > num1 and num2 > num3 and num2 > num4:
print(str(num2)+"is greater")
elif num3 > num1 and num3 > num2 and num3 > num4:
print(str(num3)+"is greater")
else:
print(str(num4)+"is greater")
|
06f5a9e66d642ba9313916bf8ea0689d34a270be | KBerUX/OODPy | /testingboard.py | 309 | 3.703125 | 4 | given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
print("printing total 6")
total6 = 0
i = 0
while given_list3[i] < 0:
total6 += given_list3[i]
i += 1
print(total6)
total10 = 0
i = 0
while i < len(given_list3):
if given_list3[i] <= 0:
total10 += given_list3[i]
i += 1
print(total10)
|
6e2ad42d67db0407cc3e1e7d0e5257c8b7ad29fb | adyant/talee | /ReverseLL.py | 1,261 | 3.984375 | 4 | '''
Created on Jul 27, 2016
@author: adyant
'''
class ListNode:
def __init__(self,data,next=None):
self.data = data
self.next = next
def get_Data(self):
return str(self.data)
def get_next(self):
return self.next
def set_next(self,new_next):
self.next = new_next
class LinkedList(object):
def __init__(self,head=None):
self.head = head
def append(self, data):
if not self.head:
n = ListNode(data)
self.head = n
else:
n = self.head
while n.next != None:
n = n.next
newnode = ListNode(data)
n.next = newnode
def printll(self):
n = self.head
while n:
print n.data
n = n.next
def reverse(self,start):
curr = start
prev = None
next = None
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
if __name__ == '__main__':
mylist = LinkedList()
elements = [1,2,3,4,5]
for elem in elements:
mylist.append(elem)
mylist.head = mylist.reverse(mylist.head)
mylist.printll() |
2900c1027684ffcc2db180401b69fce1beed3b17 | giladgressel/python-201 | /03_file-input-output/03_02_words_analysis.py | 226 | 3.953125 | 4 | # Read in all the words from the `words.txt` file.
# Then find and print:
# 1. The shortest word (if there is a tie, print all)
# 2. The longest word (if there is a tie, print all)
# 3. The total number of words in the file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.