blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
bd432f53037d74b956cbfa99284981f7e4d13e04 | runopti/parity_experiment | /results/test/experiment1-2016-07-03-23:36:15/getData.py | 948 | 3.65625 | 4 | import numpy as np
np.random.seed(0)
def createTargetData(digit_list):
""" generate len(digit_list) vector, whose i th element is the
corresponding parity upto the ith element of the input."""
sum_ = 0
parity_list = []
# check the first digit
sum_ = digit_list[0]
if sum_ % 2 == 0:
parity_list.append(0)
else:
parity_list.append(1)
# main for loop
for i in range(len(digit_list)):
if i == 0:
continue
else:
sum_ += digit_list[i]
if sum_ % 2 == 0:
parity_list.append(0)
else:
parity_list.append(1)
return parity_list
def createInputData(n):
""" generate a list of digits 0/1"""
digit_list = []
for i in range(n):
digit_list.append(np.random.randint(2))
return digit_list
#data = createInputData(10)
#parity = createTargetData(data)
#print(data)
#print(parity)
|
0a0c101703b97b8a12ee170093947afd4638c1fa | slourdenadin/Python-ASRBD | /script.py | 972 | 3.765625 | 4 | #!/usr/bin/pyton.3.6
'''
texte = "je suis du texte"
print (texte * 3)
txt= "HEllo! Wolrd!!!"
print (len(txt))
print (txt[1])
print (txt[0:5])
print("bonjour %s je m'appelle " % ("Medhi"))
text = "je suis du \"texte\""
print(text)
maListe=["1er","deuxieme","troisieme"]
secondList = maListe[:]
maListe[0]="toto"
print (secondList)
maListe = range(15)
print(maListe)
Liste = list(range(10))
liste.extend(maListe)
print(liste)
monTuple=()
print (type(monTuple))
monTuple = ("toto",)
print (type(monTuple))
monTuple[0] = "error"
monDico={}
monDico["name"]="Medhi"
monDico["height"]="1m90"
print (monDico)
def ma_function():
print("salut les gens")
ma_function()
def ma_function(param):
print(param)
ma_function("hey")
def somme(a,b):
return a+b
somme = somme(1,5)
print (somme)
a= "salut"
c= 5
def test():
b="test"
print (c)
test()
print(a)
print(b)
valeur=input("Enter your value")
random.choice([1,2,3,4,5])
'''
i=1
While i < 10:
|
fc9754350bacea837273841d8bd7523b49721793 | Miloxing/test | /tongxunlu.py | 1,186 | 3.734375 | 4 | print('欢迎进入通讯录程序\n1:查询联系人资料\n2:插入新的联系人\n3:删除已有联系人\n4:退出通讯录程序\n')
mingdan=dict()
while 1:
get=int(input('请输入相关的指令代码:'))
if get == 4:
print('感谢使用通讯录程序')
break
elif get == 2:
name=input('请输入联系人姓名:')
if name not in mingdan:
mingdan[name]=input('请输入用户联系电话:')
else:
print('您输入的姓名在通讯录中已存在-->>%s'%(name+mingdan[name]))
x=input('是否修改用户资料(YES/NO):')
if x == 'YES':
mingdan[name]=input('请输入用户联系电话:')
elif get == 1:
name=input('请输入联系人姓名:')
if name not in mingdan:
print('没有这个联系人')
else:
print(name+':'+mingdan[name])
elif get == 3:
name=input('请输入联系人姓名:')
if name not in mingdan:
print('没有这个联系人')
else:
del mingdan[name]
print('联系人已删除') |
3368770258469eacad4a73cefbd20daa8da78ee1 | to-olx/team-3-rm-recommendations-app | /recommenders/collaborative_based.py | 5,293 | 3.546875 | 4 | """
Collaborative-based filtering for item recommendation.
Author: Explore Data Science Academy.
Note:
---------------------------------------------------------------------
Please follow the instructions provided within the README.md file
located within the root of this repository for guidance on how to use
this script correctly.
NB: You are required to extend this baseline algorithm to enable more
efficient and accurate computation of recommendations.
!! You must not change the name and signature (arguments) of the
prediction function, `collab_model` !!
You must however change its contents (i.e. add your own collaborative
filtering algorithm), as well as altering/adding any other functions
as part of your improvement.
---------------------------------------------------------------------
Description: Provided within this file is a baseline collaborative
filtering algorithm for rating predictions on Movie data.
"""
# Script dependencies
import pandas as pd
import numpy as np
import pickle
import copy
from surprise import Reader, Dataset
from surprise import SVD, NormalPredictor, BaselineOnly, KNNBasic, NMF
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
# Importing data
movies_df = pd.read_csv('resources/data/movies.csv',sep = ',',delimiter=',')
ratings_df = pd.read_csv('resources/data/ratings.csv')
ratings_df.drop(['timestamp'], axis=1,inplace=True)
# We make use of an SVD model trained on a subset of the MovieLens 10k dataset.
model=pickle.load(open('resources/models/SVD_rm.pkl', 'rb'))
def prediction_item(item_id):
"""Map a given favourite movie to users within the
MovieLens dataset with the same preference.
Parameters
----------
item_id : int
A MovieLens Movie ID.
Returns
-------
list
User IDs of users with similar high ratings for the given movie.
"""
# Data preprosessing
reader = Reader(rating_scale=(0.0, 5.0))
load_df = Dataset.load_from_df(ratings_df[['userId', 'movieId', 'rating']],reader)
a_train = load_df.build_full_trainset()
predictions = []
for ui in a_train.all_users():
predictions.append(model.predict(iid=item_id,uid=ui, verbose=False))
return predictions
def pred_movies(movie_list):
"""Maps the given favourite movies selected within the app to corresponding
users within the MovieLens dataset.
Parameters
----------
movie_list : list
Three favourite movies selected by the app user.
Returns
-------
list
User-ID's of users with similar high ratings for each movie.
"""
# Store the id of users
id_store=[]
# For each movie selected by a user of the app,
# predict a corresponding user within the dataset with the highest rating
for i in movie_list:
predictions = prediction_item(item_id = i)
predictions.sort(key=lambda x: x.est, reverse=True)
# Take the top 10 user id's from each movie with highest rankings
for pred in predictions[:10]:
id_store.append(pred.uid)
# Return a list of user id's
return id_store
# !! DO NOT CHANGE THIS FUNCTION SIGNATURE !!
# You are, however, encouraged to change its content.
def collab_model(movie_list,top_n=10):
"""Performs Collaborative filtering based upon a list of movies supplied
by the app user.
Parameters
----------
movie_list : list (str)
Favorite movies chosen by the app user.
top_n : type
Number of top recommendations to return to the user.
Returns
-------
list (str)
Titles of the top-n movie recommendations to the user.
"""
indices = pd.Series(movies_df['title'])
movie_ids = pred_movies(movie_list)
df_init_users = ratings_df[ratings_df['userId']==movie_ids[0]]
for i in movie_ids:
df_init_users=df_init_users.append(ratings_df[ratings_df['userId']==i])
# Getting the cosine similarity matrix
cosine_sim = cosine_similarity(np.array(df_init_users), np.array(df_init_users))
idx_1 = indices[indices == movie_list[0]].index[0]
idx_2 = indices[indices == movie_list[1]].index[0]
idx_3 = indices[indices == movie_list[2]].index[0]
# Creating a Series with the similarity scores in descending order
rank_1 = cosine_sim[int((idx_1-len(indices))*-1/25)]
rank_2 = cosine_sim[int((idx_2-len(indices))*-1/25)]
rank_3 = cosine_sim[int((idx_3-len(indices))*-1/25)]
# Calculating the scores
score_series_1 = pd.Series(rank_1).sort_values(ascending = False)
score_series_2 = pd.Series(rank_2).sort_values(ascending = False)
score_series_3 = pd.Series(rank_3).sort_values(ascending = False)
# Appending the names of movies
listings = score_series_1.append(score_series_1).append(score_series_3).sort_values(ascending = False)
recommended_movies = []
# Choose top 50
top_50_indexes = list(listings.iloc[1:50].index)
# Removing chosen movies
top_indexes = np.setdiff1d(top_50_indexes,[idx_1,idx_2,idx_3])
for i in top_indexes[:top_n]:
recommended_movies.append(list(movies_df['title'])[i])
return recommended_movies |
a72b8412d9b2ca109436ac39d7dc3dcc021a8d75 | jsvn91/example_python | /eg/getting_max_from_str_eg.py | 350 | 4.15625 | 4 | # Q.24. In one line, show us how you’ll get the max alphabetical character from a string.
#
# For this, we’ll simply use the max function.
#
print (max('flyiNg'))
# ‘y’
#
# The following are the ASCII values for all the letters of this string-
#
# f- 102
#
# l- 108
#
# because y is greater amongst all y- 121
#
# i- 105
#
# N- 78
#
# g- 103
|
7196477329330b8797f00a744ee2ae7d55ea32e5 | decadenza/SecurFace | /database.py | 964 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: Pasquale Lafiosca
# Date: 20 July 2017
#
import os
import sqlite3 as sql
class Database:
def __init__(self,p):
if not os.path.exists(os.path.dirname(p)): #if folder does not exists
os.makedirs(os.path.dirname(p)) #create it
self.conn = sql.connect(p) #open connection (creates file if does not exist)
self.cursor = self.conn.cursor()
self.cursor.execute("CREATE TABLE IF NOT EXISTS 'users' ( \
'id' INTEGER PRIMARY KEY AUTOINCREMENT, \
'name' TEXT UNIQUE, \
'pwd' TEXT \
);")
def query(self,q,args=None):
if args:
self.cursor.execute(q,args) #execute query and return result
else:
self.cursor.execute(q)
self.conn.commit() #apply changes
return self.cursor
def __del__(self):
self.conn.close() #close database connection
|
a8491883d0cb47411b30397e87e84b98cd281368 | t0mm4rx/ft_linear_regression | /functions.py | 1,035 | 3.515625 | 4 | """
This module contains useful functions used globally.
"""
import numpy as np
import pandas as pd
from typing import Tuple
def prepare_data(data: pd.DataFrame) -> Tuple[float, float]:
"""Normalize data, so both axis have a similar scale."""
max_km = data["km"].max()
max_price = data["price"].max()
data["km"] = data["km"] / max_km
data["price"] = data["price"] / max_price
return (max_km, max_price)
def predict(theta0: float, theta1: float, kilometrage: float) -> float:
"""Returns an estimated price prediction for given weights and kilometrage."""
return theta0 + theta1 * kilometrage
def get_weights() -> Tuple[float, float]:
"""Get weights from the disk, if the weights don't exist, we create the file with null weights."""
try:
thetas = np.load("weights.npy")
return (thetas[0], thetas[1])
except:
save_weights(0, 0)
return (0, 0)
def save_weights(theta0: float, theta1: float) -> None:
"""Save weights to disk."""
np.save("weights", np.array([theta0, theta1]))
print("Weigths saved on this disk.") |
f52112864ac6ebb6d9ca47c1538c9d98a49bac32 | yopiyama/Tools | /mybase64.py | 2,621 | 3.515625 | 4 | #!/usr/bin/env python
#coding:utf-8
""" Base64 Script """
import inspect
def str_to_bin(text):
""" str -> binary """
bin_text = ""
for i in text:
i_bin = format(ord(i), "b")
bin_text += (i_bin if len(i_bin) == 8 else ("0" * (8 - len(i_bin))) + i_bin)
return bin_text
def bin_to_str(bin_text):
""" binary -> str """
text = chr(int(bin_text, 2))
return text
def split_n(text, n):
""" split n """
return [text[i: i+n] for i in range(0, len(text), n)]
def convert(text):
""" convert by rule """
dictionary = {"000000":"A", "000001":"B", "000010":"C", "000011":"D", "000100":"E", "000101":"F", "000110":"G", "000111":"H", "001000":"I", "001001":"J", "001010":"K", "001011":"L", "001100":"M", "001101":"N", "001110":"O", "001111":"P", "010000":"Q", "010001":"R", "010010":"S", "010011":"T", "010100":"U", "010101":"V", "010110":"W", "010111":"X", "011000":"Y", "011001":"Z", "011010":"a", "011011":"b", "011100":"c", "011101":"d", "011110":"e", "011111":"f", "100000":"g", "100001":"h", "100010":"i", "100011":"j", "100100":"k", "100101":"l", "100110":"m", "100111":"n", "101000":"o", "101001":"p", "101010":"q", "101011":"r", "101100":"s", "101101":"t", "101110":"u", "101111":"v", "110000":"w", "110001":"x", "110010":"y", "110011":"z", "110100":"0", "110101":"1", "110110":"2", "110111":"3", "111000":"4", "111001":"5", "111010":"6", "111011":"7", "111100":"8", "111101":"9", "111110":"+", "111111":"/"}
conv_text = ""
mode = inspect.currentframe().f_back.f_code.co_name
if mode == "encode":
text_list = split_n(text, 6)
for i in text_list:
conv_text += dictionary[i]
else:
for i in text:
conv_text += [k for k, v in dictionary.items() if v == i][0]
return conv_text
def encode(text):
""" base64 encode function """
bin_text = str_to_bin(text)
print(bin_text)
if len(bin_text) % 6 != 0:
bin_text += ("0" * (6 - len(bin_text) % 6))
conv_text = convert(bin_text)
if len(conv_text) % 4 != 0:
print(len(conv_text) % 4)
conv_text = conv_text + ("=" * (4 - len(conv_text) % 4))
return conv_text
def decode(text):
""" base64 decode function """
text = text.replace("=", "")
bin_text = convert(text)
print(bin_text)
if len(bin_text) % 8 != 0:
bin_text = bin_text[:-(len(bin_text) % 8)]
bin_list = split_n(bin_text, 8)
conv_text = ""
for i in bin_list:
conv_text += bin_to_str(i)
return conv_text
def main():
""" main function """
text = input("text >>> ")
mode = input("encode (e) or decode (d) >>> ")
if mode == "e" or mode == "encode":
print(encode(text))
elif mode == "d" or mode == "decode":
print(decode(text))
if __name__ == "__main__":
main()
|
4b16c70b8cbf99dcefd01d144e6e1479e88a3dfd | AntonioCR99/Programaci-n-avanzada | /escribecsv.py | 1,671 | 3.609375 | 4 | # Escritura de archivo texto plano
# Modulo para trabajar con el sistema operativo
import os
# Modulo para trabajar con archivos csv
import csv
# Se declara clase Contacto
# <<clase Contacto>> sirve para poblar una lista que perimte manejar en memoria los datos.
# La lista se vaciía al archivo csv final del programa
class Contacto():
def __init__(self, USUARIO, NOMBRE, CORREO):
self.USUARIO = USUARIO
self.NOMBRE = NOMBRE
self.CORREO = CORREO
# Lista para trabajar con los contactos
Contactos = []
# Se cargan dos elementos
Contactos.append(Contacto('master', 'Jose Ruiz', 'jose.ruiz@hotmail.com'))
Contactos.append(Contacto('student', 'Alma Perez', 'almitarules@hotmail.com'))
# En el programa final, la lista se carga a partir del archivo csv
# Se guarda en la variable <<ruta>> la ruta absoluta, del directorio actual de trabajo (cwd)
ruta = os.path.abspath(os.getcwd())
archivo_trabajo = ruta+"\\contactos.csv"
archivo_respaldo = ruta+"\\contactos.bak"
# Determinar si el archivo de trabajo existe
if os.path.exists(archivo_trabajo):
# Si el archivo existe, entonces verifica si hay respaldo y lo borra
if os.path.exists(archivo_respaldo):
os.remove(archivo_respaldo)
# Se establece el archivo de datos, como respaldo
os.rename(archivo_trabajo,archivo_respaldo)
# Se genera archivo csv
f = open(archivo_trabajo, "w+")
# Escritura de encabezados de archivo csv
f.write("USUARIO|NOMBRE|CORREO\n")
# Se escribe en el archivo csv, a partir de la lista de objetos
for elemento in Contactos:
f.write(f'{elemento.USUARIO}|{elemento.NOMBRE}|{elemento.CORREO}\n')
# Se cierra archivo csv
f.close() |
5935356da274001c362f979a7405c61f71cdef0b | Zhaokun1997/2020T1 | /comp9321/labs/week2/activity_2.py | 1,596 | 4.4375 | 4 | import sqlite3
import pandas as pd
from pandas.io import sql
def read_csv(csv_file):
"""
:param csv_file: the path of csv file
:return: a dataframe out of the csv file
"""
return pd.read_csv(csv_file)
def write_in_sqlite(data_frame, database_file, table_name):
"""
:param data_frame: the dataframe which must be written into the database
:param database_file: where the database is stored
:param table_name: the name of the table
"""
cnx = sqlite3.connect(database_file) # make a connection
sql.to_sql(data_frame, name=table_name, con=cnx, index=True)
def read_from_sqlite(database_file, table_name):
"""
:param database_file: where the database is stored
:param table_name: the name of the table
:return: a dataframe
"""
cnx = sqlite3.connect(database_file)
return sql.read_sql('select * from ' + table_name, cnx)
if __name__ == '__main__':
table_name = "Demographic_Statistics"
database_file = 'Demographic_Statistics.db' # name of sqlite db file that will be created
csv_file = 'Demographic_Statistics_By_Zip_Code.csv'
# read data from csv file
print("Reading csv file...")
loaded_df = read_csv(csv_file)
print("Obtain data from csv file successfully...")
# write data (read from csv file) to the sqlite database
print("Creating database...")
write_in_sqlite(loaded_df, database_file, table_name)
print("Write data to database successfully...")
# make a query
print("Querying the database")
queried_df = read_from_sqlite(database_file, table_name)
|
449e11de328f39c61ad66d664df6af960fbb14de | Zhaokun1997/2020T1 | /comp9321/labs/week3/activity_3.py | 1,187 | 3.828125 | 4 | import pandas as pd
def print_data_frame(data_frame, print_columns=True, print_rows=True):
if print_columns:
print(",".join(data_frame.columns))
if print_rows:
for index, row in data_frame.iterrows():
print(",".join([str(row[column]) for column in data_frame]))
def data_cleaning(data_frame):
data_frame['Place of Publication'] = data_frame['Place of Publication'].apply(
lambda x: 'London' if 'London' in x else x.replace('-', ' '))
new_date = data_frame['Date of Publication'].str.extract(r'^(\d{4})', expand=False)
new_date = pd.to_numeric(new_date)
new_date = new_date.fillna(0)
data_frame['Date of Publication'] = new_date
return data_frame
if __name__ == '__main__':
csv_file = 'Books.csv'
df = pd.read_csv(csv_file)
df = data_cleaning(df)
# Replace the spaces with the underline character ('_')
# Because panda's query method does not work well with column names which contains white spaces
df.columns = [c.replace(' ', '_') for c in df.columns]
# query
df = df.query('Date_of_Publication > 1866 and Place_of_Publication == "London"')
print_data_frame(df, True, True)
|
81873fbcbd1279ebe655ce86aa9dd35803bd1d41 | Lioheart/Alien-Invaders | /alien_invasion.py | 1,834 | 3.515625 | 4 | """
Wyświetla okno PyGame
"""
import pygame as pygame
from pygame.sprite import Group
import game_functions as gf
from button import Button
from game_stats import GameStats
from scoreboard import Scoreboard
from settings import Settings
from ship import Ship
def run_game():
"""
Inicjalizacja gry
"""
# Utworzenie obiektu ekranu
pygame.init() # Inicjalizacja ustawienia tła - wymagane
ai_set = Settings()
screen = pygame.display.set_mode(
(ai_set.screen_width, ai_set.screen_height)) # Ustawienia okna (w nawiasie rozmiar)
pygame.display.set_caption("Inwazja obcych")
# Utworzenie przycisku Uruchom grę
play_button = Button(ai_set, screen, 'Uruchom grę')
# Utworzenie egzemplarza przeznaczonego do przechowywania danych statystycznych dotyczących gry oraz utworzenie
# egzemplarza Scoreboard
stats = GameStats(ai_set)
sb = Scoreboard(ai_set, screen, stats)
# Utworzenie statku kosmicznego, grupy pocisków oraz grupy obcych
ship = Ship(screen, ai_set)
aliens = Group()
bullets = Group()
# Utworzenie floty obcych
gf.create_fleet(ai_set, screen, ship, aliens)
# Rozpoczęcie pętli głównej gry
while True:
gf.check_events(ai_set, screen, stats, sb, play_button, ship, aliens, bullets) # Sprawdzanie zdarzeń klawiatury
if stats.game_active:
ship.update() # Uaktualnienie położenia statku
gf.update_bullets(bullets, aliens, ai_set, screen, ship, stats, sb) # Ustalanie liczby pocisków na ekranie
gf.update_aliens(ai_set, aliens, ship, stats, screen, bullets, sb) # Uaktualnienie położenia każdego obcego
gf.update_screen(ai_set, screen, ship, bullets, aliens, play_button, stats, sb) # Odświeżanie ekranu
if __name__ == '__main__':
run_game()
|
1c7206129917825245706ef49a83cb50fe51b893 | hanok2/national_pastime | /utils/utilities.py | 1,132 | 3.875 | 4 | import random
import heapq
class PriorityQueue:
def __init__(self):
self.elements = []
def empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
def get(self):
return heapq.heappop(self.elements)[1]
def clamp(val, minimum, maximum):
return max(minimum, min(val, maximum))
def insert_into(dictionary, key, value):
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(value)
def insert_once(dictionary, key, value):
if key not in dictionary:
dictionary[key] = value
def pick_from_sorted_list(sorted_list):
"""Pick from a sorted list, with lower indices more likely to be picked."""
if len(sorted_list) >= 3:
# Pick from top three
if random.random() < 0.6:
choice = sorted_list[0]
elif random.random() < 0.9:
choice = sorted_list[1]
else:
choice = sorted_list[2]
elif sorted_list:
choice = list(sorted_list)[0]
else:
choice = None
return choice |
ebd1beec3027159b644104cbb2efc334f13b0c69 | hanok2/national_pastime | /baseball/manager.py | 1,124 | 3.75 | 4 | import random
from career import ManagerCareer
from strategy import Strategy
class Manager(object):
"""The baseball-manager layer of a person's being."""
def __init__(self, person, team):
"""Initialize a Manager object."""
self.person = person # The person in whom this manager layer embeds
person.manager = self
self.career = ManagerCareer(manager=self)
self.team = team
self.strategy = Strategy(owner=self)
def decide_position_of_greatest_need(self):
"""Return the team's position of greatest need in the opinion of this manager, given their
strategy and other concerns.
"""
# TODO FLESH THIS OUT
positions = ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF')
positions_already_covered = {p.position for p in self.team.players}
try:
return next(p for p in positions if p not in positions_already_covered)
except StopIteration:
if self.strategy.hitting_is_more_important:
return random.choice(positions[1:])
else:
return 'P' |
33c871d344b9fad6b7eddc12caa8338290e22fd3 | hanok2/national_pastime | /events/__init__.py | 1,477 | 3.71875 | 4 | import random
class Event(object):
"""A superclass that all event subclasses inherit from."""
def __init__(self, cosmos):
"""Initialize an Event object."""
self.year = cosmos.year
if self.year < cosmos.config.year_worldgen_begins: # This event is being retconned; generate a random day
self.month, self.day, self.ordinal_date = cosmos.get_random_day_of_year(year=self.year)
self.time_of_day = random.choice(['day', 'night'])
self.date = cosmos.get_date(ordinal_date=self.ordinal_date)
else:
self.month = cosmos.month
self.day = cosmos.day
self.ordinal_date = cosmos.ordinal_date
self.time_of_day = cosmos.time_of_day
self.date = cosmos.date
# Also request and attribute an event number, so that we can later
# determine the precise ordering of events that happen on the same timestep
self.event_number = cosmos.assign_event_number(new_event=self)
class Fate(Event):
"""A catch-all event that can serve as the reason for anything in the cosmos that was forced to happen
by top-down methods in the greater simulation (usually ones that are in service to population maintenance).
"""
def __init__(self, cosmos):
"""Initialize a Retirement object."""
super(Fate, self).__init__(cosmos=cosmos)
def __str__(self):
"""Return string representation."""
return "Fate" |
e4070ff2588f938c67c53480a12309c62db79a52 | hanok2/national_pastime | /people/body.py | 10,826 | 3.875 | 4 | import random
from random import normalvariate as normal
# TODO implement dynamics of aging
class Body(object):
"""A person's body."""
def __init__(self, person):
"""Initialize a Body object.
Objects of this class hold people's physical attributes, most of which will
be baseball-centric. Even if a person never plays a game of baseball in the
simulation, their body will still be generated, since they may have children
that will inherit their physical attributes, and also to support the targeted
narrative of potentially great baseball players who never had any interest in
actually playing the game, and thus never were.
"""
self.person = person # The person to which this body belongs
# Prepare all the attributes that we'll be setting momentarily; these will
# be instantiated as Feature attributes (that extend Float)
self.age_of_physical_peak = None
self.lefty = False # Left-handed
self.righty = False # Right-handed
self.left_handed = None # 1.0 if lefty, else 0.0 (represented as a float so that we can cast to Feature)
self.right_handed = None
self.hustle = None
self.height = None
self.weight = None
self.adult_height = None
self.bmi = None # Body mass index
self.coordination = None
self.coordination_propensity = None
self.reflexes_propensity = None
self.agility_propensity = None
self.jumping_propensity = None
self.footspeed_propensity = None
self.reflexes = None
self.agility = None
self.vertical = None # Maximum jumping height in inches
self.vertical_reach = None # Max height (in feet) a person can reach while standing with arm stretched upward
self.full_speed_seconds_per_foot = None
self.full_speed_feet_per_second = None
self.speed_home_to_first = None
# If you have parents, inherit physical attributes
if False: # TODO delete after inheritance implemented
# if self.person.mother:
self._init_inherit_physical_attributes()
# Otherwise, generate them from scratch
else:
self._init_generate_physical_attributes()
def _init_inherit_physical_attributes(self):
"""Inherit physical attributes from this person's parents."""
config = self.person.cosmos.config
mother, father = self.person.biological_mother, self.person.biological_father
parents = (mother.body, father.body)
# Handedness
if random.random() < config.heritability_of_handedness:
takes_after = random.choice(parents)
self.left_handed = Feature(value=takes_after.left_handed, inherited_from=takes_after)
self.right_handed = Feature(value=takes_after.right_handed, inherited_from=takes_after)
# Hustle
if random.random() < config.heritability_of_hustle:
takes_after = random.choice(parents)
inherited_hustle = takes_after.hustle
mutated_hustle = normal(inherited_hustle, config.hustle_mutation_sd)
self.hustle = Feature(value=mutated_hustle, inherited_from=takes_after)
else:
pass # TODO SET UP GENERATING FROM NOTHING
def _init_generate_physical_attributes(self):
"""Generate physical attributes for this person."""
# Prepare these now, for speedier access
config = self.person.cosmos.config
year = self.person.cosmos.year
male = self.person.male
# Determine age of physical peak, i.e., baseball prime
self.age_of_physical_peak = config.determine_age_of_physical_peak()
# Determine handedness
self.lefty = True if random.random() < config.chance_of_being_left_handed else False
self.righty = not self.lefty
self.left_handed = 1.0 if self.lefty else 0.0
self.right_handed = 1.0 if self.righty else 0.0
# Determine hustle
self.hustle = config.determine_hustle()
# Determine adult height this person will attain, in inches
if male:
self.adult_height = normal(
config.adult_male_height_mean(year=year), config.adult_male_height_sd(year=year)
)
else:
self.adult_height = normal(
config.adult_female_height_mean(year=year), config.adult_female_height_sd(year=year)
)
# Determine this person's BMI TODO BMI INCREASES AS ADULTHOOD PROGRESSES
if male:
self.bmi = normal(
config.young_adult_male_bmi_mean(year=year), config.young_adult_male_bmi_sd(year=year)
)
else:
self.bmi = normal(
config.young_adult_female_bmi_mean(year=year), config.young_adult_female_bmi_sd(year=year)
)
# Determine propensities for coordination, reflexes, agility, jumping...
self.coordination_propensity = config.determine_coordination_propensity()
self.reflexes_propensity = config.determine_reflexes_propensity(
coordination_propensity=self.coordination_propensity
)
self.agility_propensity = config.determine_agility_propensity()
self.jumping_propensity = config.determine_jumping_propensity() # Number of inches added/subtracted to base
# ...and finally footspeed propensity, which is a bit more convoluted to compute
primitive_coordination = config.determine_primitive_coordination(bmi=self.bmi) if self.bmi > 24 else 1.0
adult_coordination = primitive_coordination * self.coordination_propensity
primitive_footspeed = config.determine_primitive_footspeed(
coordination=adult_coordination, height=self.adult_height
)
self.footspeed_propensity = config.determine_footspeed_propensity(primitive_footspeed=primitive_footspeed)
# Finally, fit these potentials to the person's current age
self.develop()
def develop(self):
"""Develop due to aging."""
config = self.person.cosmos.config
# Update height
if self.person.male:
percentage_of_adult_height_attained = (
config.male_percentage_of_eventual_height_at_age(age=self.person.age)
)
else: # Female
percentage_of_adult_height_attained = (
config.female_percentage_of_eventual_height_at_age(age=self.person.age)
)
self.height = percentage_of_adult_height_attained * self.adult_height
# Calculate weight (by using BMI and new height)
self.weight = (self.bmi/703.) * self.height**2
# Evolve propensities according to their curves
offset_from_typical_prime = config.typical_age_of_physical_peak - self.age_of_physical_peak
age_to_fit_to_curve = self.person.age + offset_from_typical_prime
self.coordination_propensity *= config.coordination_propensity_curve(age=age_to_fit_to_curve)
self.reflexes_propensity = config.reflexes_propensity_curve(age=age_to_fit_to_curve)
self.agility_propensity = config.agility_propensity_curve(age=age_to_fit_to_curve)
self.jumping_propensity = config.jumping_propensity_curve(age=age_to_fit_to_curve)
self.footspeed_propensity = config.footspeed_propensity_curve(age=age_to_fit_to_curve)
# Determine coordination, which is correlated to BMI
primitive_coordination = config.determine_primitive_coordination(bmi=self.bmi) if self.bmi > 24 else 1.0
self.coordination = primitive_coordination * self.coordination_propensity
# Determine reflexes, which is correlated to coordination
primitive_reflexes = config.determine_primitive_reflexes(
coordination=self.coordination, reflexes_propensity=self.reflexes_propensity
)
self.reflexes = config.determine_reflexes(primitive_reflexes=primitive_reflexes)
# Determine agility, which is correlated to coordination and height (with 5'6 somewhat arbitrarily
# being the ideal height for agility)
primitive_agility = config.determine_primitive_agility(
coordination=self.coordination, height=self.adult_height
)
self.agility = primitive_agility * self.agility_propensity
# Determine jumping ability, which is correlated to coordination and height (with 6'6 somewhat
# arbitrarily being the ideal height for jumping)
primitive_jumping = config.determine_primitive_jumping(coordination=self.coordination, height=self.height)
base_vertical = config.determine_base_vertical(primitive_jumping=primitive_jumping)
self.vertical = base_vertical + self.jumping_propensity # Notice the plus sign
self.vertical = config.clamp_vertical(vertical=self.vertical)
# Determined vertical (max. height of jump) and vertical reach (how high they can reach while
# standing flat on the ground)
self.vertical_reach = config.determine_vertical_reach(height=self.height)
# Determine footspeed, which is correlated to coordination and height (with 6'1 somewhat arbitrarily
# being the ideal height for footspeed) -- we do this by generating a 60-yard dash time and then
# dividing that by its 180 feet to get a full-speed second-per-foot time, which is used frequently
# in the on-field simulation
primitive_footspeed = config.determine_primitive_footspeed(coordination=self.coordination, height=self.height)
self.full_speed_seconds_per_foot = config.determine_full_speed_seconds_per_foot(
primitive_footspeed=primitive_footspeed, footspeed_propensity=self.footspeed_propensity
)
# Finally, full-speed feet per second isn't derived from self.full_speed_seconds_per_foot, because
# it's a measure of full speed on the base paths, and so it assumes 20 feet of acceleration have
# already occurred (JOR 03-28-16: I think)
self.full_speed_feet_per_second = config.determine_full_speed_feet_per_second(
primitive_footspeed=primitive_footspeed
)
class Feature(float):
"""A feature representing a person's physical attribute and metadata about that."""
def __init__(self, value, inherited_from):
"""Initialize a Feature object.
@param value: A float representing the value of the physical attribute.
@param inherited_from: The parent from whom this memory capability was
inherited, if any.
"""
super(Feature, self).__init__()
self.inherited_from = inherited_from
def __new__(cls, value, inherited_from):
"""Do float stuff."""
return float.__new__(cls, value) |
a85d00e5d21027f79b7d4f6211f46304e0ed30f7 | xyz-09/codinggames | /easy/py/easy-power-of-thor-episode-1.py | 941 | 3.84375 | 4 |
# EASY: https://www.codingame.com/training/easy/power-of-thor-episode-1
import sys
import math
# Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders.
# light_x: the X position of the light of power
# light_y: the Y position of the light of power
# initial_tx: Thor's starting X position
# initial_ty: Thor's starting Y position
light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()]
# game loop
while True:
remaining_turns = int(input()) # The remaining amount of turns Thor can move. Do not remove this line.
moveWE = light_x - initial_tx
moveSN = initial_ty - light_y
initial_tx += 1 if moveSN == 0 or moveWE > 0 else - 1 if moveWE < 0 else 0
initial_ty += 1 if moveWE == 0 or moveSN < 0 else - 1 if moveSN > 0 else 0
print(("N" if moveSN > 0 else 'S' if moveSN < 0 else '') + ('E' if moveWE > 0 else 'W' if moveWE < 0 else '')) |
6beb87732a05a21be5686c6d29395c58c4a0563b | mrjoechen/PythonFromZero | /init/26/lambda_test.py | 319 | 3.734375 | 4 | def add(x, y):
return x + y
print(add(1, 2))
a = lambda x,y : x+y
print(a(1, 2))
alist = list(filter(lambda x:True if x % 3 == 0 else False, range(100)))
print(alist)
adict = {1:'a', 2:'b', 3:'c'}
for a in adict.items():
print(a[1])
alam = lambda item:item[1]
for a in adict.items():
print(alam(a))
|
2a6a4a1db387fc79ff44912175cb4d27b7e29c15 | Sharonbosire4/hacker-rank | /Python/Contests/Project Euler/euler_007/python_pe_007/__main__.py | 1,104 | 3.546875 | 4 | from __future__ import print_function
import sys
class PE_007:
def __init__(self, max_size=100000):
self.primes = []
self.collect_primes(max_size)
def find_prime(self, index):
if len(self.primes) == index:
collect_primes(index*2)
if index < 1 or index >= len(self.primes):
return 1
return self.primes[index-1]
def collect_primes(self, max_primes):
# Initialize the sieve and primes list.
sieve = list(True for _ in range(0, max_primes))
self.primes = []
# Generate the sieve.
for i in range(len(sieve)):
for j in range(i*2+2, len(sieve), i+2):
sieve[j] = False
# Store results of the sieve into the primes list.
for i in range(len(sieve)):
if sieve[i] == True:
self.primes.append(i+2)
def main():
T = int(input())
input_data = [int(x) for x in sys.stdin.readlines()[:T]]
primer = PE_007()
for line in input_data:
print(primer.find_prime(line))
if __name__ == '__main__':
main()
|
44dddcfb5d819b565d4168e0df67951609b648e9 | Sharonbosire4/hacker-rank | /Python/Contests/week_of_code_36/acid_naming/__main__.py | 558 | 3.65625 | 4 | import sys
from enum import Enum
class Acid(Enum):
NON_METAL = 'non-metal acid'
POLYATOMIC = 'polyatomic acid'
NOT_ACID = 'not an acid'
def name_acid(text: str) -> Acid:
hydro = text.startswith('hydro')
poly = text.endswith('ic')
if hydro and poly:
return Acid.NON_METAL
elif poly:
return Acid.POLYATOMIC
return Acid.NOT_ACID
def main():
lines = [line.strip() for line in sys.stdin.readlines()][1:]
for line in lines:
print(name_acid(line).value)
if __name__ == '__main__':
main()
|
b5ef32acae6f59590e4cd373b2368eb4414bf12f | Sharonbosire4/hacker-rank | /Python/Algorithms/Warmup/Staircase/python_staircase/__main__.py | 392 | 4.125 | 4 | from __future__ import print_function
import sys
def staircase(height):
lines = []
for n in range(height):
string = ''
for i in range(height):
string += '#' if i >= n else ' '
lines.append(string)
return reversed(lines)
def main():
T = int(input())
for line in staircase(T):
print(line)
if __name__ == '__main__':
main()
|
9596f6ca7ea898f08d603b81be5a3608fa45d9ea | SHARADDUHOON/sharad-1st-day | /main.py | 607 | 4.09375 | 4 | print("hello world\nhello world \nhello world")
print("Day 1 - String Manipultion")
print("Concactenation is done with "+"sign,")
print('eg = print("hello" + "world")')
print("New line will be created by using a backslash and n")
print("hello"+" "+ input("wht is your name?\n"))
print(len(input(" what is your name?")))
a = (int(input("enter a no")))
b = (int(input("enter a no")))
temp=a
a=b
b=temp
print(a)
print(b)
print("Welcome to the Band Name Generator")
x=input("Enter the city in which you are born? \n")
y=input("Enter the name of your favourite pet?\n")
print(" the name of the band is",x+" "+ y) |
dc903ba5999763753228f8d9c2942718ddd3fe69 | magicmitra/obsidian | /discrete.py | 1,190 | 4.46875 | 4 | #----------------------------------------------------------------------------------
# This is a function that will calculate the interest rate in a discrete manner.
# Wirh this, interest is compounded k times a year and the bank will only add
# interest to the pricipal k times a year.
# The balance will then be returned.
# Author: Erv
#-----------------------------------------------------------------------------------
from decimal import *
constant_one = 1
# Formula : B(t) = P(1 + (r/k)) ** kt
# B = balance
# P = principal
# r = interest rate
# k = times compounded
# t = time in years
def discrete_calculate():
# prompt the user for values
principal = float(input("Enter the principal amount: $"))
time = int(input("Enter the time in years: "))
rate = float(input("Enter the interest rate in percentage form (Ex. 5.2): "))
compound = int (input("How many times a year is the interest compounded? "))
# calculate the balance
rate = rate * 0.01
exponent = compound * time
fraction = rate / compound
meta_balance = (fraction + constant_one) ** exponent
balance = principal * meta_balance
balance = round(balance, 2)
return "balance will be $" + str(balance)
|
7ec45e973a15a4a72ff5cd017832cec2d8efec3c | gitKrystan/LearnPython | /solver.py | 2,384 | 3.828125 | 4 | import argparse
def validity(word, rack_list):
rack_test = list(rack_list)
w_rd = ""
for l in word:
if l in rack_test:
rack_test.remove(l)
w_rd += l
elif "*" in rack_test:
rack_test.remove("*")
w_rd += "*"
else:
return False, ""
return True, w_rd
def score(word, scores):
total = 0
for l in word:
total += scores[l]
return total
def wordFormat(word1, word2):
if word1 == word2:
return word1
else:
return word1 +" ("+word2+")"
def wordCompare(word1, word2):
#If one word contains more * than the other, it sorts lower
#If one word contains more letters than the other, it sorts lower
if word1.count("*") > word2.count("*"):
return 1
elif word1.count("*") < word2.count("*"):
return -1
else:
if len(word1) > len(word2):
return 1
elif len(word1) < len(word2):
return -1
else:
return 0
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10, "*": 0}
print "SCRABBLE SOLVER V0.1"
#Construct the word list
SOWPODS_file = open("sowpods.txt", "r")
SOWPODS_raw = SOWPODS_file.readlines()
SOWPODS_file.close()
#Clean up the word list
SOWPODS = [word.strip().lower() for word in SOWPODS_raw]
#Get the rack
parser = argparse.ArgumentParser()
parser.add_argument("rack")
args = parser.parse_args()
rack = args.rack.lower()
print "You've input:", rack
rack_list = list(rack)
#Find valid words and score them
wordScores = {}
for word in SOWPODS:
valid, w_rd2score = validity(word, rack_list)
if valid:
wordScore = score(w_rd2score, scores)
if wordScores.has_key(wordScore):
wordScores[wordScore].append(wordFormat(word,w_rd2score))
else:
wordScores[wordScore] = [wordFormat(word,w_rd2score)]
#Print words by score
#valid_scores = sorted(wordScores.values(), reverse=True)
allScores = sorted(wordScores, reverse=True)
for i in allScores:
print "\n" + str(i) + ":"
for word in sorted(wordScores[i], wordCompare):
print word
if not allScores:
print "Exchange some letters!" |
6692e4cfda720450ad1e6e7f7de95e85eeb02e8a | BrianDouglas/bucketFill | /test.py | 313 | 3.53125 | 4 | from arrayFill import *
canvas = create2dArray(int(input("Specify number of Columns: ")), int(input("Specify number of Rows: ")))
print2dArray(canvas)
canvas = diag2dArray(canvas)
print2dArray(canvas)
fillBucket(canvas,int(input("Specify Y coord: ")),int(input("Specify X coord: ")),0,2)
print2dArray(canvas) |
2e2e07b1851ffde8d853cbf8ff5a08f41c4e3c60 | haocs/leetcode | /python/2-add-two-numbers.py | 791 | 3.625 | 4 | # source: https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry = 0
result = ListNode(0)
ptr = result
p1 = l1
p2 = l2
while p1 or p2:
v1 = 0
v2 = 0
if p1:
v1 = p1.val
p1 = p1.next
if p2:
v2 = p2.val
p2 = p2.next
s = v1 + v2 + carry
carry = s / 10
ptr.next = ListNode(s % 10)
ptr = ptr.next
if carry:
ptr.next = ListNode(1)
return result.next
|
5ebb13b8d29cc1592e24bbc742d5e1610debc5c3 | haocs/leetcode | /python/15-3sum.py | 943 | 3.703125 | 4 | # source: https://leetcode.com/problems/3sum/
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def twoSum(nums, l, r, target): # -> pairs
sums = []
while l < r:
if nums[l] + nums[r] == target:
sums.append([nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
elif nums[l] + nums[r] > target:
r -= 1
else:
l += 1
return sums
nums.sort()
sums = []
for i in range(len(nums)):
if i == 0 or nums[i] != nums[i-1]:
num = nums[i]
for pair in twoSum(nums, i+1, len(nums) - 1, -num):
sums.append([num] + pair)
return sums
|
5e5997eee1736e29f142e996daac201864e0e263 | haocs/leetcode | /python/87-scramble-string.py | 1,062 | 3.59375 | 4 | # source: https://leetcode.com/problems/scramble-string/
class Solution(object):
def __init__(self):
self.cache = {} # str -> bool
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
"""
for a string AB, it's scramble string is BA
"""
#print((s1, s2))
if len(s1) != len(s2):
return False
if s1 == s2:
return True
s1s2 = s1 + '&' + s2
s2s1 = s2 + '&' + s1
if s1s2 in self.cache:
return self.cache[s1s2]
if s2s1 in self.cache:
return self.cache[s2s1]
isScramble = False
for i in range(1, len(s1)):
if (self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:])) or \
(self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i])):
isScramble = True
break
self.cache[s1s2], self.cache[s2s1] = isScramble, isScramble
return isScramble
|
48eb6175bfb5cd98001d480ddf060d01677e20ac | ajay-8192/competitive_program | /Algos/EulerTotient_Algo.py | 328 | 3.5 | 4 | def gcd(a, b):
if (a == 0):
return b
return gcd(b % a, a)
def phi(n):
result = 1
for i in range(2, n):
if (gcd(i, n) == 1):
result+=1
return result
def main():
for n in range(1, 11):
print("phi(",n,") = ",phi(n), sep = "")
if __name__ == "__main__":
main()
|
abe55ef8d442b221121d22ee7d4fd3a5916fb49c | Bharat0550/Mini-Projects | /Display Calender_month_year.py | 124 | 3.515625 | 4 | # To display the calender of any month and year
import calendar
print(calendar.month(2021, 9))
print(calender.month(2077,1)
|
097a63c09d55dc17208b953b948229ccc960c751 | Onyiee/DeitelExercisesInPython | /circle_area.py | 486 | 4.4375 | 4 | # 6.20 (Circle Area) Write an application that prompts the user for the radius of a circle and uses
# a method called circleArea to calculate the area of the circle.
def circle_area(r):
pi = 3.142
area_of_circle = pi * r * r
return area_of_circle
if __name__ == '__main__':
try:
r = int(input("Enter the radius of the circle: "))
area = circle_area(r)
print(area)
except ValueError:
print(" You need to enter a value for radius")
|
bccd0d8074473316cc7eb69671929cf14ea5c1ac | Onyiee/DeitelExercisesInPython | /Modified_guess_number.py | 1,472 | 4.1875 | 4 | # 6.31 (Guess the Number Modification) Modify the program of Exercise 6.30 to count the number of guesses
# the player makes. If the number is 10 or fewer, display Either you know the secret
# or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret!
# If the player makes more than 10 guesses, display You should be able to do better! Why should it
# take no more than 10 guesses? Well, with each “good guess,” the player should be able to eliminate
# half of the numbers, then half of the remaining numbers, and so on.
from random import randint
count = 1
def ten_or_less_message(count):
if count == 10:
return "Aha! You know the secret!"
random_message = randint(1, 2)
if random_message == 1:
return "You got lucky!"
if random_message == 2:
return "You know the secret"
def greater_than_ten_message():
return "You should be able to do better!"
def modified_guess_game(guessed_number):
global count
random_number = randint(1, 10)
guessed_number = int(guessed_number)
if guessed_number == random_number and count <= 10:
print(ten_or_less_message(count))
if guessed_number == random_number and count > 10:
print(greater_than_ten_message())
count += 1
if guessed_number != random_number:
modified_guess_game(input("Guess a number between 1 and 10: "))
print(modified_guess_game(input("Guess a number between 1 and 10: ")))
|
69a5b4659af04434e43c9f243ce1f5dedfae28d5 | SIlverAries12/Level-zero-coding-challenges | /python_level_0.5.py | 122 | 3.625 | 4 |
def area (a,b,c):
s = 0.5*(a + b + c)
output = (s*((s-a)*(s-b)*(s-c))) ** 0.5
print(str(output))
area(3, 4, 5) |
d047baac4b4a5df847345e204f0a66e248edea7c | pappyhammer/pattern_discovery | /tools/signal.py | 3,682 | 4 | 4 | import numpy as np
def smooth_convolve(x, window_len=11, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd integer
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
t=linspace(-2,2,0.1)
x=sin(t)+randn(len(t))*0.1
y=smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
"""
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
s = np.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]]
# print(len(s))
if window == 'flat': # moving average
w = np.ones(window_len, 'd')
else:
w = eval('np.' + window + '(window_len)')
y = np.convolve(w / w.sum(), s, mode='valid')
return y
def gaussblur1D(data, dw, dim):
n_times = data.shape[dim]
if n_times % 2 == 0:
kt = np.arange((-n_times / 2) + 0.5, (n_times / 2) - 0.5 + 1)
else:
kt = np.arange(-(n_times - 1) / 2, ((n_times - 1) / 2 + 1))
if dim == 0:
fil = np.exp(-np.square(kt) / dw ** 2) * np.ones(data.shape[0])
elif dim == 1:
fil = np.ones(data.shape[1]) * np.exp(-np.square(kt) / dw ** 2)
elif dim == 2:
fil = np.zeros((data.shape[0], data.shape[1], data.shape[2]))
for i in np.arange(n_times):
fil[:, :, i] = np.ones((data.shape[0], data.shape[1])) * np.exp(-np.square(kt[i]) / dw ** 2)
tfA = np.fft.fftshift(np.fft.fft(data, axis=dim))
b = np.real(np.fft.ifft(np.fft.ifftshift(tfA * fil), axis=dim))
return b
def gauss_blur(data, dw):
"""
2D gaussian filter in Fourier domainon 2 first dimensions
:param data:
:param dw:
:return:
"""
n_x, n_y = data.shape
if n_x % 2 == 0:
kx = np.arange((-n_x / 2) + 0.5, (n_x / 2) - 0.5 + 1)
else:
kx = np.arange(-(n_x - 1) / 2, ((n_x - 1) / 2 + 1))
if n_y % 2 == 0:
ky = np.arange((-n_y / 2) + 0.5, (n_y / 2) - 0.5 + 1)
else:
ky = np.arange(-(n_y - 1) / 2, ((n_y - 1) / 2 + 1))
k_x, k_y = np.meshgrid(kx, ky)
kr_ho = np.sqrt(np.square(k_x) + np.square(k_y))
fil = np.exp(-np.square(kr_ho) / dw ** 2)
# b = np.zeros(n_x, n_y)
# tfa = np.zeros(n_x, n_y)
tfA = np.fft.fftshift(np.fft.fft2(data))
b = np.real(np.fft.ifft2(np.fft.ifftshift(tfA * fil)))
return b
def norm01(data):
min_value = np.min(data)
max_value = np.max(data)
difference = max_value - min_value
data -= min_value
if difference > 0:
data = data / difference
return data |
ddd5fba066bf1ac38c9aabd333ba8c9cb56c17b9 | pappyhammer/pattern_discovery | /tools/loss_function.py | 9,525 | 3.515625 | 4 | import numpy as np
import pattern_discovery.tools.trains as trains_module
def loss_function_with_sliding_window(spike_nums, time_inter_seq, min_duration_intra_seq, spike_train_mode=False,
debug_mode=False):
"""
Return a float from 0 to 1, representing the loss function.
If spike_nums is perfectly organized as sequences (meaning that for each spike of a neuron n, the following
spikes of other neurons (on the next lines) are the same for each given spike of n.
Sequences are supposed to go from neurons with max index to low index
:param spike_nums: np.array of 2 dim, first one (lines) representing the neuron numbers and 2nd one the time.
Binary array. If value at one, represents a spike.
:param time_inter_seq: represent the maximum number of times between two elements of a sequences
:param min_duration_intra_seq: represent the min number of times between two elements of a sequences,
could be negative
:param spike_train_mode: if True, then spike_nums should be a list of array, each list representing the spikes
of a neuron
:return:
"""
loss = 0.0
# size of the sliding matrix
sliding_size = 3
s_size = sliding_size
nb_neurons = len(spike_nums)
if nb_neurons <= s_size:
return Exception(f"number of neurons are too low, min is {s_size+1}")
if spike_train_mode:
min_time, max_time = trains_module.get_range_train_list(spike_nums)
rev_spike_nums = spike_nums[::-1]
else:
max_time = len(spike_nums[0, :])
rev_spike_nums = spike_nums[::-1, :]
# max time between 2 adjacent spike of a sequence
# correspond as well to the highest (worst) loss for a spike
max_time_inter = time_inter_seq - min_duration_intra_seq
# nb_spikes_total = np.sum(spike_nums)
if spike_train_mode:
nb_spikes_used = 0
for cell_index in np.arange(s_size, nb_neurons-s_size):
# multiplying the number of spikes by sliding_window size * 2, in order to count the maximum number
# of times a spike could be counted
nb_spikes_used += len(spike_nums[cell_index]) * (s_size * 2)
for i in np.arange(s_size):
nb_spikes_used += (len(spike_nums[i]) + len(spike_nums[-(i + 1)])) * (i + 1)
else:
nb_spikes_used = np.sum(spike_nums[s_size:-s_size, :]) * (s_size * 2)
for i in np.arange(s_size):
nb_spikes_used += (np.sum(spike_nums[i, :]) + np.sum(spike_nums[-(i + 1), :])) * (i + 1)
worst_loss = max_time_inter * nb_spikes_used
# if debug_mode:
# print(f'nb_neurons {nb_neurons}, worst_loss {worst_loss}')
for n, neuron in enumerate(rev_spike_nums):
if n == (nb_neurons - (sliding_size + 1)):
break
if spike_train_mode:
n_times = neuron
else:
n_times = np.where(neuron)[0]
# next_n_times = np.where(rev_spike_nums[n+1, :])[0]
# if len(n_times) == len(next_n_times):
# if np.all(np.diff(n_times) == np.diff(next_n_times)):
# continue
# mask allowing to remove the spikes already taken in consideration to compute the loss
# mask_next_n = np.ones((sliding_size, max_time_inter*sliding_size), dtype="bool")
# will contain for each neuron of the sliding window, the diff value of each spike comparing to the first
# neuron of the seq
mean_diff = dict()
for i in np.arange(1, sliding_size + 1):
mean_diff[i] = []
# we test for each spike of n the sliding_size following seq spikes
for n_t in n_times:
start_t = n_t + min_duration_intra_seq
start_t = max(0, start_t)
# print(f'start_t {start_t} max_time {max_time}')
if (start_t + (max_time_inter * sliding_size)) < max_time:
if spike_train_mode:
seq_mat = []
for cell_index in np.arange(n, (n + sliding_size + 1)):
cell_time_stamps = rev_spike_nums[cell_index]
end_t = start_t + (max_time_inter * sliding_size)
# selecting spikes in that interval [start_t:end_t]
spikes = cell_time_stamps[np.logical_and(cell_time_stamps >= start_t, cell_time_stamps < end_t)]
# copy might not be necessary, but just in case
seq_mat.append(np.copy(spikes))
else:
seq_mat = np.copy(rev_spike_nums[n:(n + sliding_size + 1),
start_t:(start_t + (max_time_inter * sliding_size))])
else:
if spike_train_mode:
seq_mat = []
for cell_index in np.arange(n, (n + sliding_size + 1)):
cell_time_stamps = rev_spike_nums[cell_index]
# selecting spikes in that interval [start_t:end_t]
spikes = cell_time_stamps[cell_time_stamps >= start_t]
# copy might not be necessary, but just in case
seq_mat.append(np.copy(spikes))
else:
seq_mat = np.copy(rev_spike_nums[n:(n + sliding_size + 1),
start_t:])
# print(f'len(seq_mat) {len(seq_mat)} {len(seq_mat[0,:])}')
# Keeping only one spike by neuron
# indicate from which time we keep the first neuron, the neurons spiking before from_t are removed
if spike_train_mode:
from_t = min_time
else:
from_t = 0
if spike_train_mode:
first_neuron_t = seq_mat[0][0]
else:
selection = np.where(seq_mat[0, :])[0]
if len(selection) > 0:
first_neuron_t = selection[0]
else:
first_neuron_t = 0
for i in np.arange(1, sliding_size + 1):
if spike_train_mode:
bool_array = (seq_mat[i] >= from_t)
n_true = seq_mat[i][bool_array]
if len(n_true) > 1:
mask = np.ones(len(seq_mat[i]), dtype="bool")
value_sup_indices = np.where(bool_array)[0]
mask[value_sup_indices[1:]] = False
# removing all the spikes found after except the first one
seq_mat[i] = seq_mat[i][mask]
else:
n_true = np.where(seq_mat[i, from_t:])[0]
# n_true is an array of int
if len(n_true) > 1:
# removing the spikeS after
n_true_min = n_true[1:]
seq_mat[i, n_true_min] = 0
# removing the spikes before
if from_t > 0:
if spike_train_mode:
bool_array = seq_mat[i] < from_t
t_before = seq_mat[i][bool_array]
if len(t_before) > 0:
mask = np.ones(len(seq_mat[i]), dtype="bool")
value_sup_indices = np.where(bool_array)[0]
mask[value_sup_indices] = False
# removing all the spikes found
seq_mat[i] = seq_mat[i][mask]
else:
t_before = np.where(seq_mat[i, :from_t])[0]
if len(t_before) > 0:
seq_mat[i, t_before] = 0
if len(n_true > 0):
# keeping the diff between the spike of the neuron in position i from the neuron n first spike
mean_diff[i].append((n_true[0] + from_t) - first_neuron_t)
from_t = n_true[0] + min_duration_intra_seq
from_t = max(0, from_t)
# seq_mat is not used so far, but could be used for another technique.
# we add to the loss_score, the std of the diff between spike of the first neuron and the other
for i in np.arange(1, sliding_size + 1):
if len(mean_diff[i]) > 0:
# print(f'Add loss mean {np.mean(mean_diff[i])}, std {np.std(mean_diff[i])}')
loss += min(np.std(mean_diff[i]), max_time_inter)
# then for each spike of the neurons not used in the diff, we add to the loss the max value = max_time_inter
# print(f'n+i {n+i} len(np.where(rev_spike_nums[n+i, :])[0]) {len(np.where(rev_spike_nums[n+i, :])[0])}'
# f' len(mean_diff[i]) {len(mean_diff[i])}')
# nb_not_used_spikes could be zero when a neuron spikes a lot, and the following one not so much
# then spikes from the following one will be involved in more than one seq
if spike_train_mode:
nb_not_used_spikes = max(0, (len(rev_spike_nums[n + i]) - len(mean_diff[i])))
else:
nb_not_used_spikes = max(0, (len(np.where(rev_spike_nums[n + i, :])[0]) - len(mean_diff[i])))
# if nb_not_used_spikes < 0:
# print(f'ERROR: nb_not_used_spikes inferior to 0 {nb_not_used_spikes}')
# else:
loss += nb_not_used_spikes * max_time_inter
# print(f"loss_score n {loss}")
# loss should be between 0 and 1
return loss / worst_loss
|
e40e37b0133967a13836699f678471a364a324e2 | rhjohnstone/random | /euler_580_v4.py | 1,928 | 3.65625 | 4 | # count the number of Hilbert numbers that are NOT squarefree
# because these can be directly constructed, instead of checking every Hilbert number for the squarefree property
# a Hilbert number (4k+1) squared is also a Hilbert number
# for m(4k+1) to be a Hilbert number, m must also be a Hilbert number
import time
power = 9
N = 10**power
start = time.time()
num_hilbert_numbers_less_than_N = (N+2)/4
max_possible_hilbert_number = int(N**.5)
max_k = (max_possible_hilbert_number-1)/4
used_square_factors = [] # to avoid counting Hilbert numbers with multiple square factors
num_non_squarefree_hilbert_numbers = 0
for k in xrange(1,max_k+1):
test = 4*k+1
test_square = test**2
multiple_of_test_square = test_square
while (multiple_of_test_square<N):
not_yet_used = True
for factor in used_square_factors:
if (multiple_of_test_square%factor==0):
not_yet_used = False
break
if not_yet_used:
num_non_squarefree_hilbert_numbers += 1
multiple_of_test_square += 4*test_square
used_square_factors.append(test_square)
answer = num_hilbert_numbers_less_than_N-num_non_squarefree_hilbert_numbers
tt = time.time()-start
print "\nTotal less than 10^{}:".format(power), answer
print "Time taken: {} s\n".format(round(tt,2))
"""
Total less than 10^1: 3
Time taken: 1.4e-05 s
Total less than 10^2: 23
Time taken: 2.6e-05 s
Total less than 10^3: 232
Time taken: 2.9e-05 s
Total less than 10^4: 2324
Time taken: 0.0001 s
Total less than 10^5: 23265
Time taken: 0.000788 s
Total less than 10^6: 232710
Time taken: 0.007783 s
Total less than 10^7: 2327192
Time taken: 0.08449 s
Total less than 10^8: 23272089
Time taken: 0.894421 s
Total less than 10^9: 232721183
Time taken: 8.79501 s
Total less than 10^10: 2327212928
Time taken: 89.999935 s
Total less than 10^11: 23272130893
Time taken: 1007.300136 s
"""
|
17a98a8108322114e8c6c2b688103d728edbaa56 | rhjohnstone/random | /euler_581.py | 1,407 | 3.640625 | 4 | import math
import numpy as np
def primes_up_to_N(N):
x = np.arange(3,N+1,2)
lenx = len(x)
for i in xrange(int(np.sqrt(N))-1):
a = x[i]
if (a==0):
continue
else:
x[np.arange(a/2-1+a,lenx,a)] = 0
x = x[np.where(x>0)]
x = np.insert(x,0,2)
return x
def is_square(apositiveint):
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen:
return False,0
seen.add(x)
return True,x
def n_root_given_k_p(k,p):
discrim = 1+8*k*p
square,root = is_square(discrim)
if square:
return (-1+root)/2
else:
return 0
max_prime = 10**8
primes = primes_up_to_N(max_prime)
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
n = 12400
print primes((n*(n+1))/2)
"""
max_k = 10**8
max_a = 10**8
for a in xrange(1,max_a):
prime = 47+2*a
if prime not in primes:
continue
for q in xrange(1,prime):
for k in xrange(max_k):
discrim = 1+8*(k*prime+q)
square,root = is_square(discrim)
if square:
print "n =", (-1+root)/2
"""
|
67713e5baf078dfc305085081c7d393bba19d680 | Caleb-Ellis/CS50x | /pset6/sentiments/test.py | 240 | 3.65625 | 4 | import nltk
from nltk.tokenize import TweetTokenizer
s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
tknzr = TweetTokenizer()
tokens = tknzr.tokenize(s)
tokens = [str.lower() for str in tokens]
print(tokens[1])
print(tokens) |
3b26b40c9619c6b0eee0a36096688aeb57819f10 | Subharanjan-Sahoo/Practice-Questions | /Problem_34.py | 810 | 4.15625 | 4 | '''
Single File Programming Question
Your little brother has a math assignment to find whether the given number is a power of 2. If it is a power of 2 then he has to find the sum of the digits. If it is not a power of 2, then he has to find the next number which is a power of 2. He asks for your help to validate his work. But you are already busy playing video games. Develop a program so that your brother can validate his work by himself.
Example 1
Input
64
Output
Yes
10
Example 2
Input
133
Output
NO
'''
def math(input1):
if (int(input1) & (int(input1) - 1)) == 0 :#% 2 == 0:
sumyes = 0
print('Yes')
for i in range(len(input1)):
sumyes = int(input1[i]) + sumyes
print(sumyes)
else:
print('NO')
input1 = input()
math(input1) |
0bbb5802a3cfb9cd06a9a458bc77403689dad0ca | Subharanjan-Sahoo/Practice-Questions | /Problem_33.py | 1,040 | 4.375 | 4 | '''
Write a program to calculate and return the sum of distances between the adjacent numbers in an array of positive integers
Note:
You are expected to write code in the find TotalDistance function only which will receive the first parameter as the number of items in the array and second parameter as the array itself. You are not required to take input from the console
Example
Finding the total distance between adjacent items of a list of 5 numbers
Input input1: 5
input2: 10 11 7 12 14
Output
12
Explanation
The first parameter (5) is the size of the array. Next is an array of integers. The total of distances is 12 as per the calculation below
11-7-4
7-12-5
12-14-2 Total distance 1+4+5+2= 12
'''
def findTotalDistance(input1):
input2 = list(map(int,input().strip().split(" ")))[:input1]
sum = 0
for i in range(input1):
for j in range(input1):
if i+1 == j:
sum = (abs(input2[i] - input2[j])) + sum
return sum
input1 = int(input())
print(findTotalDistance(input1)) |
565c480183eca3b0e75cd60eb72c92b7cf6909de | Subharanjan-Sahoo/Practice-Questions | /Problem_14.py | 363 | 3.75 | 4 | def numdiv(input1):
First = []
Second = []
input2 = list(map(int, input("Enter the Elements: ").strip().split(",")))[:input1]
input3 = int(input("Enter the number: "))
First = input2[:input3]
Second = input2[input3:]
Combine = Second + First
print(Combine)
input1 = int(input("Enter the no of elements: "))
numdiv(input1) |
461225afe709aa1b1f4233177376ffee74692506 | Subharanjan-Sahoo/Practice-Questions | /Problem_2.py | 919 | 3.984375 | 4 | # Most use Vowel in the String
def FindMostFrequentVowel(str):
a=0
e=0
x=0
o=0
u=0
for i in range(len(str)):
if str[i] == "a" or str[i] == "A":
a = a+1
elif str[i] == "e" or str[i] == "E":
e= e+1
elif str[i] == "i" or str[i] == "I":
x= x+1
elif str[i] == "o" or str[i] == "O":
o= o+1
elif str[i] == "u" or str[i] == "u":
u= u+1
if (a > e) and (a > x) and (a > o) and (a > u):
print ('a')
elif (e > a) and (e > x) and (e > o) and (e > u):
print ('e')
elif (x > e) and (x > a) and (x > o) and (x > u):
print ('i')
elif (o > e) and (o > x) and (o > a) and (o > u):
print ('o')
elif (u > e) and (u > x) and (u > o) and (u > a):
print ('u')
str = input("Enter the String: ")
FindMostFrequentVowel(str) |
9fbe0aabf82ee6efb8730d98edfedfbf88b45a75 | Subharanjan-Sahoo/Practice-Questions | /InfyTQ Question/Problem_9.py | 270 | 3.859375 | 4 | def OddEven(input1):
a = 0
b = 0
for i in range(len(input1)):
if i % 2 == 0:
a = a + int(input1[i])
else:
b = b + int(input1[i])
print(str((b - a))[1:])
input1 = input("Enter the number: ")
OddEven(input1) |
97c1bac183bf1c744eb4d1f05b6e0253b1455f10 | Subharanjan-Sahoo/Practice-Questions | /Problem_13.py | 733 | 4.21875 | 4 | '''
Write a function to find all the words in a string which are palindrome
Note: A string is said to be a palindrome if the reverse of the string is the same as string. For example, "abba" is a palindrome, but "abbe" is not a palindrome.
Input Specification:
input1: string
input2: Length of the String
Output Specification:
Retum the number of palindromes in the given string
Example 1:
inputt: this is level 71
input2: 16
Output 1
'''
def palondrom(input1):
input2 =list(input("input the string: ").strip().split(" "))[:input1]
count = 0
for i in input2:
if i == i[::-1]:
count = count + 1
print(count)
input1 =int(input("Enter the number of Word: "))
palondrom(input1) |
6bd590a16c53b37ddc7d2d484e58fad08c1ce2ce | shivaram93/datasciencecoursera | /Booleans and If Statements-153.py | 1,130 | 4.03125 | 4 | ## 1. Booleans ##
cat=True
dog=False
print(cat)
type(cat)
## 2. Boolean Operators ##
print(cities)
first_alb = (cities[0] == "Albuquerque")
second_alb = (cities[1] == "Albuquerque")
last_element_index = len(cities) - 1
first_last = (cities[0] == cities[last_element_index])
## 3. Booleans with "Greater Than" ##
print(crime_rates)
first_500=crime_rates[0]>500
first_749=crime_rates[0]>=749
leng=len(crime_rates)-1
first_last=crime_rates[0]>=crime_rates[leng]
## 4. Booleans with "Less Than" ##
print(crime_rates)
second_500=crime_rates[1]<500
second_371=crime_rates[1]<=371
second_last=crime_rates[1]<=crime_rates[len(crime_rates)-1]
## 5. If Statements ##
result = 0
if(cities[2] == "Anchorage"):
result=1
## 6. Nesting If Statements ##
both_conditions = False
if(crime_rates[0]>500):
if(crime_rates[0]>300):
both_conditions=True
## 7. If Statements and For Loops ##
five_hundred_list=[]
for row in crime_rates:
if(row>500):
five_hundred_list.append(row)
## 8. Find the Highest Crime Rate ##
print(crime_rates)
highest=0
for row in crime_rates:
if(row>highest):
highest=row |
4a92944af852b227c6a6d491eaa514d7906f8266 | otherness/sec-code-snippets | /byte-to-hex.py | 459 | 3.8125 | 4 | #!/usr/local/bin/python
byte_list = [['09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09', '09'], ['54', '68', '65', '20', '4d', '61', '67', '69', '63', '20', '57', '6f', '72', '64', '73', '20']]
byte_list.reverse()
print "ANSWER in hex:", byte_list
#convert byte array to string
ans_string = ""
for block in byte_list:
for byte in block:
ans_string+=byte
print "ANSWER in ASCII:", ans_string.decode('hex')
|
ae0109f998da6415824a245c51fd5c3b3188424e | MaxwellAllee/PythonPractice | /third_day/carGame.py | 638 | 3.96875 | 4 | command = ""
carStatus = False
while True:
command = input("> ").lower()
if command == "start":
if carStatus:
print("Car is already started")
else:
carStatus = True
print("Car started...")
elif command == "stop":
if carStatus:
print("Car stopped ..")
carStatus = False
else:
print("Car is not running")
elif command == "help":
print("""
start - to start the car
stop - to stop the car
quite - to quite the game
""")
elif command == "quit":
break
else:
print("sorry I don know")
|
53a43a6b8d98c3742033417b172ad84bc25c0d30 | rbbastos/Weather_Processing_App | /db_operations.py | 4,626 | 3.625 | 4 | """Module: Creates a DBOperations class with functions."""
import sqlite3
import urllib.request
import datetime
from scrape_weather import WeatherScraper
class DBOperations():
"""This class contains working with db functions."""
def create_db(self):
"""Create the table in db."""
try:
connection = sqlite3.connect("weather.sqlite")
cur = connection.cursor()
print("create_db - Opened the db successfully.")
except Exception as e:
print("Error opening DB:", e)
try:
cur = connection.cursor()
# dropTableStatement = "DROP TABLE samples"
# cur.execute(dropTableStatement)
cur.execute("""create table if not exists samples
(id integer primary key autoincrement not null,
sample_date text not null,
location text not null,
min_temp real not null,
max_temp real not null,
avg_temp real not null);""")
print("create_db - Table created successfully.")
except Exception as e:
print("Error creating table:", e)
try:
cur.execute("""create unique index idx_positions_sample_date \
ON samples (sample_date);""")
connection.commit()
print("create_db - Index created successfully.")
except Exception as e:
print("Index already exists:", e)
connection.close()
def process(self, my_Dictionary):
"""Populate the table with dictionary received."""
self.create_db()
myLocation = "Winnipeg"
for d in my_Dictionary.keys():
try:
sample_date = d
except Exception as e:
print("Error mean:", e)
for v in my_Dictionary.values():
# values = v.values()
# values = list(v.values())
try:
if my_Dictionary[sample_date]["max"] != 'M' and \
my_Dictionary[sample_date]["max"] != 'E':
max_temp = float(my_Dictionary[sample_date]["max"])
except Exception as e:
print("Error max:", e)
try:
if my_Dictionary[sample_date]["min"] != 'M' and \
my_Dictionary[sample_date]["min"] != 'E':
min_temp = float(my_Dictionary[sample_date]["min"])
except Exception as e:
print("Error min:", e)
try:
if my_Dictionary[sample_date]["mean"] != 'M' and \
my_Dictionary[sample_date]["mean"] != 'E':
avg_temp = float(my_Dictionary[sample_date]["mean"])
except Exception as e:
print("Error mean:", e)
try:
location = myLocation
except Exception as e:
print("Error:", e)
connection = sqlite3.connect("weather.sqlite")
# print("process - Opened the db successfully.")
cur = connection.cursor()
try:
cur.execute("""replace into samples
(sample_date, location, min_temp, max_temp, avg_temp)
values (?,?,?,?,?)""", (sample_date, location, min_temp, max_temp,
avg_temp))
connection.commit()
connection.close()
# print("process - added sample successfully.")
except Exception as e:
print("Error:", e)
self.print_infos()
def print_infos(self):
"""Print the information for checking purpose."""
connection = sqlite3.connect("weather.sqlite")
cur = connection.cursor()
connection.commit()
connection.close()
def query_infos(self, fromYear, toYear):
"""Query db according to user input."""
connection = sqlite3.connect("weather.sqlite")
cur = connection.cursor()
toYear = int(toYear) + 1
dictOuter = {}
for row in cur.execute("select * from samples where \
sample_date between ? and ?",
(str(fromYear)+'%', str(toYear)+'%')):
print(f"row {row}")
myMonth = datetime.datetime.strptime(row[1], '%Y/%m/%d').month
dictOuter.setdefault(myMonth, []).append(row[5])
print(dictOuter)
return dictOuter
connection.commit()
connection.close()
|
d30504a329fd5bcb59a284b5e28b89b6d21107e3 | lada8sztole/Bulochka-s-makom | /1_5_1.py | 479 | 4.1875 | 4 | # Task 1
#
# Make a program that has some sentence (a string) on input and returns a dict containing
# all unique words as keys and the number of occurrences as values.
# a = 'Apple was sweet as apple'
# b = a.split()
a = input('enter the string ')
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print(word_count(a))
|
cdc0c71ee2fd47586fca5c145f2c38905919cff5 | lada8sztole/Bulochka-s-makom | /1_6_3.py | 613 | 4.25 | 4 | # Task 3
#
# Words combination
#
# Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string.
#
# For example, the program obtained the word ‘hello’, so it should print 5 random strings(words)
# that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ …
#
# Tips: Use random module to get random char from string)
import random
from itertools import permutations
a = input('sentence ')
b = list(permutations(a))
i = 0
while i<5:
print(''.join(b[random.randint(0, len(b))]))
i+=1
|
687a269e6625f81a45a3dda760e8d202b3f5d61e | dxcv/Contrarian | /Codes/Debug/Rename 3-1.py | 1,559 | 3.625 | 4 | import os; path = os.getcwd()
os.chdir("Result")
file_name_list = os.listdir()
# for old_file_name in file_name_list:
# if "-" not in old_file_name:
# print(old_file_name)
# splitted_file_name = old_file_name.split()
# splitted_file_name.insert(-1, "3-1")
# new_file_name = " ".join(splitted_file_name)
# try:
# os.rename(old_file_name, new_file_name)
# except FileExistsError:
# pass
# elif "6-1 " in old_file_name:
# print(old_file_name)
# splitted_file_name = old_file_name.split()
# splitted_file_name.remove("6-1")
# new_file_name = " ".join(splitted_file_name)
# try:
# os.rename(old_file_name, new_file_name)
# except FileExistsError:
# pass
# for old_file_name in file_name_list:
# if "3-1 " in old_file_name:
# splitted_file_name_list = old_file_name.split()
# index_of_3_1 = splitted_file_name_list.index("3-1")
# splitted_file_name_list[index_of_3_1], splitted_file_name_list[index_of_3_1+1] \
# = splitted_file_name_list[index_of_3_1+1], splitted_file_name_list[index_of_3_1]
# new_file_name = " ".join(splitted_file_name_list)
# try:
# os.rename(old_file_name, new_file_name)
# print("把%s重命名为%s" % (old_file_name, new_file_name))
# except FileExistsError:
# pass
for old_file_name in file_name_list:
if "3-1" in old_file_name:
os.remove(old_file_name)
os.chdir(path) |
85a540b820796e70d969ecf8d89ebf0a163969bb | laravignotto/books_exercises | /Data_Science_Essentials_in_Python/ex_3-1_broken_link_detector.py | 933 | 3.828125 | 4 | '''
Given a URL address, this program returns the broken links in the
page.
This works faster than the solution in the book by making asynchronous
requests with grequests (https://github.com/spyoungtech/grequests)
'''
import grequests
from urllib.request import urlopen
from bs4 import BeautifulSoup
#get the url
page_url = input("Which web page do you want to analyze? ")
try:
page = urlopen(page_url)
except:
print("Cannot open %s" % page_url)
quit()
#get all the hlinks
soup = BeautifulSoup(page, features="lxml")
links = [(link["href"]) for link in soup.find_all("a") if link.has_attr("href")]
# This will notify about and print broken links
def exception_handler(request, exception):
print("This link might be broken:")
print(exception)
# Create a set of unsent Requests:
rs = (grequests.get(u) for u in links)
# Send them all at the same time:
grequests.map(rs, exception_handler=exception_handler)
|
434b88f21162613faf3efdbd3deb3812b46788c8 | malay190/Assignment_Solutions | /assignment4/ass4_1.py | 142 | 4 | 4 | #Que.Find the length of tuples
x=int(input("enter any number"))
y=int(input("enter any number"))
t=(1,2,"a",1.2,9,x,y)
print(t)
print(len(t))
|
dbd3eb8899b9049bef93836c194b4046070d4ce8 | malay190/Assignment_Solutions | /assignment18/ass18_1.py | 937 | 4.09375 | 4 | #Q1. Create a dict with name and mobile number.Define a GUI interface using tkinter and pack the label and create a scrollbar
#to scroll the list of keys in the dictionary.
import tkinter
from tkinter import *
import sys
dic={"rahul":95943053548,"mohit":84593745722,"malay":94524592345,"rajan":87654322678,"nihal":7564565503,"rahul":856453545343,"satyam":8435340034554,"rajan":9845384754,"gurdeep":94954378758,"aman":83458439877,"nikhil":6345666764,"mukesh":85422422455,"deepak":84735822}
root=Tk()
root.title("window")
root.geometry("250x250")
root.resizable(True,True)
root.minsize(200,200)
root.maxsize(300,300)
root.configure(background="Beige")
f=Frame()
f.pack(side=LEFT)
label=Label(f,text="MY LIST")
label.pack()
s=Scrollbar(f)
s.pack(side=RIGHT,fill=Y)
l=Listbox(f,yscrollcommand=s.set)
for x in dic:
l.insert(END,x)
l.pack(side=LEFT,fill=BOTH)
s.config(command=l.yview())
root.mainloop()
|
5438b1928dc780927363d3d7622ca0d00247a5c2 | malay190/Assignment_Solutions | /assignment9/ass9_5.py | 599 | 4.28125 | 4 | # Q.5- Create a class Expenditure and initialize it with expenditure,savings.Make the following methods.
# 1. Display expenditure and savings
# 2. Calculate total salary
# 3. Display salary
class expenditure:
def __init__(self,expenditure,savings):
self.expenditure=expenditure
self.savings=savings
def total_salary(self):
print("your expenditure is ",self.expenditure)
print("your saving is",self.savings)
salary=self.expenditure+self.savings
print("your salary is",salary)
a=expenditure(int(input("enter your expenditure:")),int(input("enter your savings:")))
a.total_salary() |
8fd0a4330efa1c12a7e10a3f554cd610e98d03e3 | malay190/Assignment_Solutions | /assignment11/ass11_1.py | 410 | 3.75 | 4 | #Q1. Create a threading process such that it sleeps for 5 seconds and then prints out a message.
#method-1
import threading
from threading import Thread
import time
def display():
print("child thread:",threading.current_thread().getName())
bt=time.time()
time.sleep(3)
print("child thread:",threading.current_thread())
et=time.time()
print("total time taken:",et-bt)
t=Thread(target=display)
t.start() |
40ffc248e21edc12a7ca63fb6746fb0836508580 | malay190/Assignment_Solutions | /assignment11/ass11_4.py | 286 | 3.8125 | 4 | #Q4. Call factorial function using thread.
import threading
from threading import Thread
import time
class factorial(Thread):
def run(self):
n=int(input("enter any number:"))
fact=1
for i in range(1,n+1):
fact = fact * i
print("factorial:",fact)
t=factorial()
t.start() |
7e34f98134d443a2ad9655cad2ff12e5a6d9ca14 | malay190/Assignment_Solutions | /assignmrnt7/ass7_3.py | 137 | 4.15625 | 4 | #Q.3- Print multiplication table of 12 using recursion.
def rec(x,y):
if y<=10:
t=x*y
print(t)
y+=1
rec(x,y)
rec(12,1)
|
d4c987322a7e4c334bfb78920c52009101a1ba13 | malay190/Assignment_Solutions | /assignment6/ass6_4.py | 291 | 4.15625 | 4 | #Q.4- From a list containing ints, strings and floats, make three lists to store them separately
l=[1,'a',2,3,3.2,5,8.2]
li=[]
lf=[]
ls=[]
for x in l:
if type(x)==int:
li.append(x)
elif type(x)==float:
lf.append(x)
elif type(x)==str:
ls.append(x)
print(li)
print(lf)
print(ls)
|
e0802d175e1bac66ec466e4d22374d5ef5632c6a | malay190/Assignment_Solutions | /assignmrnt7/ass7_2.py | 368 | 4.0625 | 4 | #Q.2- Write a function “perfect()” that determines if parameter number is a perfect number.
#Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
def perfect(num):
sum=0
for x in range(1,num):
if num%x==0:
sum=sum+x
if sum==num:
print(num,":is a perfect number")
for x in range(1,1001):
perfect(x)
|
72a8086b765c8036b7f30853e440550a020d7602 | bradger68/daily_coding_problems | /dailycodingprob66.py | 1,182 | 4.375 | 4 | """Assume you have access to a function toss_biased()
which returns 0 or 1 with a probability that's not 50-50
(but also not 0-100 or 100-0). You do not know the bias
of the coin.
Write a function to simulate an unbiased coin toss.
"""
import random
unknown_ratio_heads = random.randint(1,100)
unknown_ratio_tails = 100-unknown_ratio_heads
def coin_toss(tosses):
heads_count = 0
tails_count = 0
weighted_probabilities = unknown_ratio_heads * ['Heads'] + unknown_ratio_tails * ['Tails']
for x in range(tosses):
toss = random.choice(weighted_probabilities)
if toss == 'Heads':
heads_count += 1
else:
tails_count += 1
ratio_tails = (tails_count / tosses) * 100
ratio_heads = (heads_count / tosses) * 100
print(str(heads_count) + " of the " + str(tosses) + " tosses were heads. That is " + str(ratio_heads) + " percent.")
print(str(tails_count) + " of the " + str(tosses) + " tosses were tails. That is " + str(ratio_tails) + " percent.")
print("The unknown probability of getting heads was " + str(unknown_ratio_heads) +". How close were you?")
coin_toss(10000)
|
c604721615c9c30eaa2c089e980a445cace69b93 | bradger68/daily_coding_problems | /dailycodingprob70.py | 981 | 4.09375 | 4 | """A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return 28."""
def find_nth_perfnum(n):
temporary_sum = 0
for digit in str(n):
temporary_sum += int(digit)
return (n * 10) + (10- temporary_sum)
print(find_nth_perfnum(1))
print(find_nth_perfnum(2))
print(find_nth_perfnum(19))
# The following function just verifies whether or not
# an integer is perfect or not. It does not find
# the nth perfect number. I originally started
# coding it out like this but realized there was
# an easier way to do it after looking at solution
# from github user Vineetjohn
def is_perfect(number):
number = str(number)
digits = []
for digit in number:
digits.append(int(digit))
sum_of_digits = sum(digits)
if sum_of_digits == 10:
return True
print(is_perfect(19))
print(is_perfect(28))
print(is_perfect(52))
|
6292484e4b091e497ef7ecc221d6ba3f1b8cb39f | azakordonets/HandyScripts | /Python/Tasks solving/test3.py | 1,455 | 4.0625 | 4 | # def main():
# text = raw_input("Please type yor text: ")
# #example of count of big letters
# big_letters_amount = []
# for char in text:
# if char >= "A" and char <= "Z":
# big_letters_amount.append(char)
# print "amount of big letters in text is %s" % len(big_letters_amount)
# sentences = 0 #write code here
# words = 0 #write code here
# numbers = 0 #write code here
# print "numbers: %s, words: %s, sentences: %s" % (numbers, words, sentences)
# if __name__ == '__main__':
# main()
# input = raw_input()
def define_value(array):
for el in array:
if el[0].isalnum():
return float(el)
def define_currency(array):
for el in array:
if el == "USD":
return el
break
if el == "EUR":
return el
break
def convert_value(x,currency):
result = 0
if currency == 'USD':
result = float(x*1.21)
currency = "EUR"
if currency == 'EUR':
result = float(x*0.81)
currency = 'USD'
else:
print "Wrong currency"
return 0
leftover = round(float(result%1)*100,2)
if leftover !=0.0:
return "Result is %s %s %s cents" %(int(result),currency,int(leftover))
else:
return "Result is %s %s " %(int(result),currency)
def main():
# input = raw_input("Please enter number and currency\n")
input = "100 EUR"
values_dict = input.split(" ")
print convert_value(define_value(values_dict),define_currency(values_dict))
# 2857.1
print float((28571 * 100.0)/1000)
if __name__ == "__main__":
main()
|
8a3413b2ee61cc85927b812d71e3a697afb73f37 | wooght/HandBook | /python/w_math/base_array.py | 2,412 | 3.796875 | 4 | # -*- coding: utf-8 -*-
#
# @method : python list,tuple,dict
# @Time : 2017/11/17
# @Author : wooght
# @File : base_array.py
# 词条:reverse [rɪˈvɜ:s] 颠倒
import random
from math import *
from echo import f
f('基础方法')
n = random.randrange(1, 5)
print(n)
n = random.random()
print(n)
print(floor(10 * n))
print(ceil(10 * n))
print(round(10 * n))
n = random.randint(1, 9)
print(n)
f('元祖tuple')
arr = (1, 4, 2, 7)
print(sorted(arr, reverse=True)) # reverse 颠倒
print(arr[1]) # tuple不能重新赋值
f('list 列表')
arr = [5, 3, 8, 9, 1, 4, 2]
print(arr)
print(sorted(arr))
arr[1] = 100
print(arr)
print(arr[:2])
print(arr[:4:2]) # 每隔2个元素取值
arr2 = arr
arr2[:4:2] = [88, 99]
print(arr)
print('choice:', random.choice(arr)) # 随机取值
print('100 index:', arr.index(100)) # 值的索引
arr.append(77) # 追加新元素
print(arr)
print(len(arr))
arr.insert(1, 1010) # 插入新元素
print(arr)
arr.pop(-1)
print(arr)
sl = slice(1, 5, 2)
print(arr[sl]) # 等同于 arr[1:5:2]
arr = [
[1, 2, 3],
[4, 7, 6]
]
print(arr)
print(arr[1][-1])
print(sorted(arr[1]))
for i in arr:
print(i)
print(4 in arr[1])
f('dict 字典')
arr = {9, 3, 8, 1}
print(arr)
print(sorted(arr, reverse=True)) # sorted 排序返回list
arr = {
'a3': 3,
'a2': 2,
'a1': 1,
'a4': -5
}
# 字典元素的迭代
for key, i in arr.items():
print(key, i)
print(arr)
print(arr['a4'])
print(sorted(arr)) # 对索引进行排序
print(sorted(arr.items())) # items 键值对 键排序
print(sorted(arr.keys())) # 对索引进行排序
print(sorted(arr.items(), key=lambda d: d[1], reverse=False)) # items 键值对 值排序
print(list(arr.values())) # values 组成的列表
for i in arr.values():
print(i)
for i in arr.keys():
print(i)
for i in arr:
print(i)
for i in arr.items():
print(i)
print(-5 in arr)
print(-5 in arr.values())
print('a2' in arr)
print(arr.get('a4'))
del arr['a1']
print(arr)
arr.pop('a2') # 删除指定的key对应的元素
print(arr)
arr['a2'] = 101
print(arr)
f('enumerate')
arr = [1, 2, 3, 4]
for i in arr:
print(i)
# enumerate 将列表元素分解成 下标,值
for i, n in enumerate(arr):
print('索引/下标:', i, ',对应值:', n)
f('zip')
a = [1, 2, 3]
b = [2, 3, 4]
arr = zip(a, b) # 将对应的元素打包成元祖,并将这些元祖组成列表
for i, j in arr:
print(i, j)
|
c4f5f260a9b0a650c5bdd7c2d2f9fce665938380 | guyguyguyguyguyguyguy/emergent_scopes | /simple/composition_behaviours.py | 10,809 | 3.59375 | 4 | from __future__ import annotations
from abc import abstractclassmethod, abstractmethod, ABC
import random
import numpy as np
from itertools import combinations
from typing import List, Tuple
from operator import add
import helper
import agent
def in_bounds(agent: agent.Agent) -> None:
"""
Keep agent in boundaries of canvas
"""
if agent.pos[0] - agent.radius < 0:
agent.pos[0] = agent.radius
agent.v[0] = -agent.v[0]
if agent.pos[0] + agent.radius > agent.model.width:
agent.pos[0] = agent.model.width-agent.radius
agent.v[0] = -agent.v[0]
if agent.pos[1] - agent.radius < 0:
agent.pos[1] = agent.radius
agent.v[1] = -agent.v[1]
if agent.pos[1] + agent.radius > agent.model.height:
agent.pos[1] = agent.model.height-agent.radius
agent.v[1] = -agent.v[1]
class Behaviour(ABC):
@abstractmethod
def step(self, agent) -> None:
pass
class RandMov(Behaviour):
"""
RandMove provides agents with behaviour representing random movement.
Takes an agents current position and returns a new position depending on agents step size
"""
def __init__(self) -> None:
self.step_size = random.randint(1, 10)
@staticmethod
def collide(agent: agent.Agent, other_agents: List[agent.Agent]) -> None:
"""Detect and handle any collisions between the Particles.
When two Particles collide, they do so elastically: their velocities
change such that both energy and momentum are conserved.
agent (Agent) : agent that function was called by
other_agents (List) : list of other agents involved in collision
"""
def change_velocities(p1, p2) -> None:
"""
Particles p1 and p2 have collided elastically: update their
velocities.
"""
m1, m2 = p1.radius**2, p2.radius**2
M = m1 + m2
r1, r2 = np.array(p1.pos), np.array(p2.pos)
d = np.linalg.norm(r1 - r2)**2
v1, v2 = np.array(p1.v), np.array(p2.v)
u1 = v1 - 2*m2 / M * np.dot(v1-v2, r1-r2) / d * (r1 - r2)
u2 = v2 - 2*m1 / M * np.dot(v2-v1, r2-r1) / d * (r2 - r1)
p1.v = u1
p2.v = u2
# For some reason it doesnt really work and its so sad, but other one seems to work
def change_velocities_2(p1, p2) -> None:
dist = helper.distance(p1, p2)
distance_vec = np.array(p1.pos) - np.array(p2.pos)
norm = distance_vec/(dist)
k = np.array(p1.v) - np.array(p2.v)
p = 2 * (norm * k) / (p1.radius + p2.radius)
p1.v = np.array(p1.v) + p * p2.radius * norm * 0.1
p2.v = np.array(p2.v) - p * p1.radius * norm * 0.1
# We're going to need a sequence of all of the pairs of particles when
# we are detecting collisions. combinations generates pairs of indexes
# into the self.particles list of Particles on the fly.
pairs = combinations([agent, *other_agents], 2)
for i,j in pairs:
change_velocities(i, j)
# change_velocities_2(i, j)
#Todo: Not sure this works properly?
def step(self, agent: agent.Agent) -> None:
"""
Move agent that this instance belong to by a random vector, scaled by step size
"""
move_vector = np.array(random.sample([-0.5, 0, 0.5], 2))
# Idea to scale velocity by agent 'weight' (radius)
scaled_vel = move_vector * (1/agent.radius)
agent.v = scaled_vel + agent.v
agent.pos = agent.v + agent.pos
if shared_pos := [x for x in agent.model.agents if x is not agent and helper.distance(agent, x) < agent.radius]:
self.collide(agent, shared_pos)
agent.pos = agent.v + agent.pos
in_bounds(agent)
class Adhesion(Behaviour):
"""
Agents with this behaviour stick together
Possibilities:
-> can only attach n number of others
-> Have some sort of intrinsic directionality (top, bottom, sides)
- Can only connect to side (or something else)
"""
def __init__(self) -> None:
self.strength = random.randint(1, 4)
@staticmethod
def attract(agent: agent.Agent, other_agents: List[agent.Agent]) -> None:
"""
Other agents in a close radius to the agent that also have the adhesive behaviour are drawn together
agent (Agent) : agent that function was called by
other_agents (List) : list of other agents involved in collision
"""
# Works, but not when one agent is placed (found) inside another
# Also does not work too well when there are more than 3 balls next to each other
def change_velocities(p1, p2):
distance_vector = np.array(p1.pos) - np.array(p2.pos)
move_vector = 0.1 * distance_vector
p1.pos = p1.pos - move_vector
p2.pos = p2.pos + move_vector
if (dist := helper.distance(p1, p2)) <= (p1.radius + p2.radius):
overlap = 0.5 * (dist - p1.radius - p2.radius)
p1.pos[0] -= overlap * (p1.pos[0] - p2.pos[0]) / dist
p1.pos[1] -= overlap * (p1.pos[1] - p2.pos[1]) /dist
p2.pos[0] += overlap * (p1.pos[0] - p2.pos[0]) / dist
p2.pos[1] += overlap * (p1.pos[1] - p2.pos[1]) /dist
pairs = combinations([agent, *other_agents], 2)
for i, j in pairs:
change_velocities(i, j)
def attracting_neighbours(self, agent: agent.Agent) -> List[agent.Agent]:
attractors = []
if len(agents := agent.model.agents) > 1:
for a in [other for other in agents if agent is not other]:
distance = self.strength + agent.radius + a.radius
if helper.distance(agent, a) <= distance:
if any([isinstance(b, type(self)) for b in a.behaviours]):
attractors.append(a)
return attractors
# Function to ensure only n number of agents are attracted to each agent
# -> Possibly want to add some sort of polarity to the agent such that can only be attracted on certain side
# -> Thinking of lipposaccharides forming a single-layer membrane
# Repuled by other attracted agent by distance of agent radius (should attract it to other side)
# Todo: NEEDS WERK!
def attraction_constraints(self, agent: agent.Agent) -> None:
bound_others = [x for x in agent.model.agents if x is not agent and helper.distance(agent, x) <= (x.radius + agent.radius + self.strength) and any([isinstance(b, type(self)) for b in x.behaviours])]
# Kinda works, for now
while len(bound_others) > 2:
repelled_agent = bound_others.pop()
move_vec = -repelled_agent.v
repelled_agent.pos += move_vec
# If distance is less than diameter of agent and radius of x, y then we want them to move away from each other
# Works but attraction ruins things
try:
x, y = bound_others
if helper.distance(x, y) < (agent.radius*2 + x.radius + y.radius - 5):
third_point = agent.pos + np.array([0, agent.radius])
x_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(x.pos), np.array(third_point))
y_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(y.pos), np.array(third_point))
# Now they all circulate, but need to make them repel each other such that only two can be bound
x_move_vec = x.pos + np.array([np.sin(x_angle + (np.pi/2)), np.cos(x_angle + (np.pi/2))])
y_move_vec = y.pos + -np.array([np.sin(x_angle + (np.pi/2)), np.cos(x_angle + (np.pi/2))])
x.pos = x_move_vec
y.pos = y_move_vec
except:
return
# For tests
# Why does this work?
def circulate(self, agent: agent.Agent) -> None:
bound_others = [x for x in agent.model.agents if x is not agent and helper.distance(agent, x) <= (x.radius + agent.radius + self.strength)]
for x in bound_others:
third_point = agent.pos + np.array([0, agent.radius])
x_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(x.pos), np.array(third_point))
x_move_vec = x.pos + np.array([np.sin(x_angle + (np.pi/2)), np.cos(x_angle + (np.pi/2))])
x.pos = x_move_vec
def step(self, agent: agent.Agent) -> None:
"""
Checks if near agents have this behviour:
-> If so, move closer to this agent (based on strength)
-> Don't get stuck inside other agent
-> If another agent is already attracted, be reuplsed to other side
"""
self.attract(agent, self.attracting_neighbours(agent))
# self.attraction_constraints(agent)
# self.circulate(agent)
in_bounds(agent)
class Linking(Behaviour):
"""
Linking class to make 'membranes'
"""
def __init__(self) -> None:
self.left = False
self.right = False
@staticmethod
def links(agent: agent.Agent, angle: float) -> tuple[np.ndarray, np.ndarray]:
centre = agent.pos
_angle = (np.pi - angle)/2
right = centre + np.array([agent.radius*np.cos(_angle), agent.radius*np.sin(_angle)])
left = centre + np.array([agent.radius*np.cos(np.pi - _angle), agent.radius*np.sin(np.pi - _angle)])
return right, left
def link(self, agent: agent.Agent) -> None:
if not self.right and (linking_neighs := [x for x in agent.model.agents if helper.distance_pos(x.pos, right_link := self.right_link(agent)) < x.radius]):
print('Am here')
linking_neigh = linking_neighs.pop()
distance_vector = np.array(agent.pos) - np.array(right_link)
move_vector = 0.1 * distance_vector
agent.pos = agent.pos - move_vector
if (dist := helper.distance(agent, linking_neigh)) <= (agent.radius + linking_neigh.radius):
overlap = 0.5 * (dist - agent.radius - linking_neigh.radius)
agent.pos[0] -= overlap * (agent.pos[0] - linking_neigh.pos[0]) / dist
agent.pos[1] -= overlap * (agent.pos[1] - linking_neigh.pos[1]) /dist
linking_neigh.pos[0] += overlap * (agent.pos[0] - linking_neigh.pos[0]) / dist
linking_neigh.pos[1] += overlap * (agent.pos[1] - linking_neigh.pos[1]) /dist
self.right = True
def step(self, agent: agent.Agent) -> None:
self.link(agent)
|
4e94c69fbf7dd24a64dccd3e429b3569eb608fc2 | yahoo17/LearningNotes | /python_demo/demo5.py | 963 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'a test module'
__author__ ='Michael Yan'
import sys
def test():
args=sys.argv
if len(args)==1:
print('Hello world')
elif len(args)==2:
print('Hello ,%s'%args[1])
else:
print("tooo many arguments")
if __name__=='__main__':
test()
class Student(object):
def __init__(self,name,score):
self.__name=name
self.score=score
def print_score(self):
print('%s: %s' % (self.__name, self.score))
def set_score(self,score):
self.score=score
#有些时候,你会看到以一个下划线开头的实例变量名,
# 比如_name,这样的实例变量外部是可以访问的,
# 但是,按照约定俗成的规定,当你看到这样的变量时,
# 意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
a=Student("yanhao",99)
a.print_score()
a.__name=100
a.print_score() |
1bf5e323ccfa2ab78392e670907066dd56d2072c | Nishant183/lp1 | /lp1/PN/LP1/4/knn_05.py | 1,708 | 3.765625 | 4 | import matplotlib.pyplot as plt
import math
import sys
#using points: is a dictionary of lists of point belonging to region 0 and 1
#using p: the point entered by the user
#using k=3 : as default nearest number of neighbours
#func - clissify the points using euclidean distances
def classify(points,p,k=3):
dist = []
for i in points:
for j in points[i]:
e_dist = math.sqrt((j[0]-p[0])**2 + (j[1]-p[1])**2)
dist.append((e_dist,i))
dist = sorted(dist)[:k]
#declaring two regions of points and initialising to zero
region_1=0
region_2=0
#dividing points into regions
for x in dist:
if x[1]==0:
region_1 = region_1 + 1
elif x[1]==1:
region_2 = region_2 + 1
return 1 if region_1>region_2 else 2
#func - main
def main():
points_1 = [(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7),(1,2)]
points_2 = [(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2),(2,5)]
points = {0:[(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7),(1,2)],1:[(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2),(2,5)]}
#region 1 points
X1=[]
Y1=[]
for i in points_1:
X1.append(i[0])
for j in points_1:
Y1.append(j[1])
print X1
print Y1
#region 2 points
X2=[]
Y2=[]
for i in points_2:
X2.append(i[0])
for j in points_2:
Y2.append(j[1])
print X2
print Y2
#get input from the user
x=raw_input('Enter the x coordinate of the point: ')
y=raw_input('Enter the y coordinate of the point: ')
#type cast
x= float(x)
y= float(y)
p=(x,y)
k=3 #predefined
print 'The point',p,'belongs to region:',classify(points,p,k)
#plot points
plt.scatter(X1,Y1)
plt.scatter(X2,Y2)
plt.plot(x,y,'g^')
plt.show()
if __name__ == '__main__':
main()
|
8704750b30ff7fe865eec661e1f6661649bd98fd | appfr3d/AdventOfCode2017 | /Day 12/day12b.py | 853 | 3.625 | 4 | def connectedWith(index):
for n in range(0,len(pipes[index])):
if pipes[index][n] not in groups[-1]:
groups[-1].append(pipes[index][n])
connectedWith(pipes[index][n])
puzzle = open('day12Input.txt', 'r')
pipes = []
for line in puzzle:
# remove unwanted data
line = line.replace(' <-> ', ' ').replace(', ', ' ').replace('\n', '')
pipe = line.split(' ')
# Loop and add values
pipes.append([int(pipe[n]) for n in range(1, len(pipe))])
# initialize values
groups = []
groups.append([])
connectedWith(0)
# for each program (after zero)
for program in range(1,len(pipes)):
# assume that it is not in a group
inGroup = False
# check if it is in a group
for i in range(0,len(groups)):
# if not, make a new group
if program in groups[i]:
inGroup = True
if not inGroup:
groups.append([])
connectedWith(program)
print(len(groups)) |
37932064c09b48f69c8e56460948e0593410b0b9 | appfr3d/AdventOfCode2017 | /Day 6/day6.py | 627 | 3.609375 | 4 | from copy import deepcopy
puzzle = [4, 10, 4, 1, 8, 4, 9, 14, 5, 1, 14, 15, 0, 15, 3, 5];
previous = [puzzle]
seenBefore = False
count = 0
while not seenBefore:
# print(previous)
count = count + 1;
p = deepcopy(puzzle)
maxValue = max(p)
maxIndex = p.index(maxValue)
p[maxIndex] = 0
for i in range(1,maxValue+1):
index = (maxIndex+i)%len(p)
p[index] = p[index] + 1
# print(previous)
if p not in previous:
previous.append(deepcopy(p))
else:
seenBefore = True
previous.append(deepcopy(p))
puzzle = p
# Part a
print(count)
# Part b
loopSize = len(previous) - previous.index(previous[-1]) - 1
print(loopSize) |
fbf5c89020b88cd90dbd965950a4822ef00c330e | koffe0522/designpattern | /Main.py | 393 | 3.84375 | 4 | from iterator.book import Book, BookShelf
def startMain():
bookShelf = BookShelf()
bookShelf.append(Book(name="Aroun d the World in 80 days"))
bookShelf.append(Book(name="Bible"))
bookShelf.append(Book(name="Cinderella"))
bookShelf.append(Book(name="Daddy-Long-Legs"))
for book in bookShelf:
print(book.getName())
if __name__ == '__main__':
startMain()
|
dd4a53b4417f5315c9f879a1f331b459780408f7 | UmaViswa/OOPS-Assignment | /Class_example.py | 870 | 3.875 | 4 | class math_operations(object):
class_attribute_example="Something"
def __init__(self,a,b):
#print ("Called constructor of math operations")
self.a=a
self.b=b
def addition(self):
sumof = self.a + self.b
#print(sumof)
return sumof
def subtraction(self):
subof = self.a - self.b
#print(subof)
return subof
def multiplication(self):
mulof = self.a * self.b
#print(mulof)
return mulof
def division(self):
divof = self.a / self.b
#print(divof)
return divof
if __name__ == '__main__':
n1 = 3
n2 = 5
M = math_operations(a=1,b=2)
print (M.class_attribute_example)
A = M.addition()
print (A)
S = M.subtraction()
print (S)
MU = M.multiplication()
print(MU)
D = M.division()
print(D)
|
fb3cb37c4ac52c966ebe55dfee1111b0a9da2fdc | boaventura16/Boaventura16 | /Estudos/Desafio019.py | 624 | 3.953125 | 4 | c = 0
lista = list()
while True:
print('='*30)
n = int(input('Digite um número: '))
lista.append(n)
r = input('Quer Continuar? [S/N]: ').upper().strip()
c += 1
if r not in 'SN':
print('Opção invalida.')
r = input('Quer continuar? [S/N]: ')
if r == 'N':
if 5 in lista:
print('='*30)
print(f'O número 5 está na lista.')
else:
print('='*30)
print('O número 5 não está na lista;')
break
print(f'Você digitou {c} números.')
print(f'Os números em ordem decrescente são: {sorted(lista, reverse=True)}')
|
a0e6389d6fcd10b9e8f2d5883c791205ff9e33d0 | boaventura16/Boaventura16 | /Estudos/Desafio028.py | 265 | 3.890625 | 4 | estado = dict()
brasil = list()
for c in range(0, 3):
estado['uf'] = input('Unidade Federativa: ')
estado['sigla'] = input('Sigla do estado: ')
brasil.append(estado.copy())
for e in brasil:
for v in e.values():
print(v, end=' ')
print()
|
e42f5c255e8fa3deb966b3cc39f39f3f4c65fa76 | boaventura16/Boaventura16 | /Estudos/Desafio021.py | 373 | 3.90625 | 4 | ex = input('Digite uma expressão matematica:\n')
lista = []
for simb in ex:
if simb == '(':
lista.append('(')
elif simb == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
break
if len(lista) == 0:
print('Sua expressão está correta.')
else:
print('Sua expressão está errada.')
|
fab286c962d89de446548c23754e33b19809e8ad | boaventura16/Boaventura16 | /Estudos/#Desafio 007.py | 126 | 3.734375 | 4 | #Desafio 007
n1 = int(input('Nota 1: '))
n2 = int(input('Nota 2: '))
m = (n1+n2)/2
print('A media do aluno é: {}'.format(m))
|
57fd96cb2a00a6dd36d2ae683de83cb661717d3c | Aniket762/Hack-Gujarat- | /Unity_to_python_socket/Unity_to_python_socket/Udp_Server_File.py | 1,210 | 3.71875 | 4 | import socket
# Here we define the UDP IP address as well as the port number that we have
# already defined in the client python script.
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 1234
# declare our serverSocket upon which
# we will be listening for UDP messages
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# One difference is that we will have to bind our declared IP address
# and port number to our newly declared serverSock
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
print('socket listensing ... ')
while True:
data, addr = serverSock.recvfrom(1024)
print ("Message: ", data.decode("utf-8"),"Adrees is ",addr)
# list = data.decode("utf-8").split(' ') # cominda data in string so we split into list on basis of space
# value1 = float(list[0])
# value2 = float(list[1])
# UpdateValue = str(value1) + " " + str(value2) + " " # +str(value3)
# # c.sendall(UpdateValue.encode("utf-8"))#then encode and send that string back to unity
# print(UpdateValue)
UpdateValue="Hello client"
serverSock.sendto(UpdateValue.encode("utf-8"), (addr))
print("Message sent ")
# serverSock.sendto(UpdateValue.encode("utf-8"), (UDP_IP_ADDRESS, UDP_PORT_NO)) |
c6d0f553a3b5297eb49d2fecde49e51d2e9fe641 | ColemanHaley/JSALT2019-FST-lab | /fstutils.py | 5,067 | 4.09375 | 4 | def remove_epsilons(string, epsilon='@_EPSILON_SYMBOL_@'):
"""Removes the epsilon transitions from the string along a path from hfst.
Args:
string (str): The string (e.g. input path, output form) from which the epsilons should be deleted.
epsilon (str, optional): The epsilon string to remove. Defaults to the default setting in hfst,
'@_EPSILON_SYMBOL_@'. Pass this only if you've redefined the epsilon symbol string in hfst.
Returns:
str: The desired string, without epsilons
"""
return string.replace('@_EPSILON_SYMBOL_@', '')
def lookup(transducer, string):
"""Returns the output for an input in an hfst transducer, sans any epsilons or weights.
Args:
transducer (HfstTransducer): the HfstTransducer in which lookup should be performed.
string (str): The string (input form) to be looked up in the HfstTransducer.
Returns:
str: The output of string in transducer
"""
results = transducer.lookup(string)
if not results:
raise FstPathNotFound("The string " + string + " was not found in the transducer")
return [remove_epsilons(r[0]) for r in results]
def test_fst(transducer, expected):
"""Tests whether an FST produces all output as provided in expected
Args:
transducer (HfstTransducer): The HfstTransducer to use for testing
expected (dict): This is a dictionary where the key is a word form and the
value returned is a list of analyses for that key given the fst
"""
error_count = 0
pass_count = 0
for key in expected:
results = lookup(transducer, key)
for item in results:
if item not in expected[key]:
print("Your grammar output '" + item + "' given the input '" + key + "' instead of '" + expected[key] + "'")
error_count += 1
error_percent = float(error_count) / len(expected.keys())
print("There were " + str(error_count) + " errors")
print("Your error percent is" + str(error_percent))
if error_count == 0:
print("PASSED!!!!")
return True
else:
return False
def pairs(transducer):
"""Enumerates all possible input-output pairs in an hfst transducer. Best suited to be printed.
Args:
transducer (HfstTransducer): the HfstTransducer to enumerate.
Returns:
str: all possible input-output pairs in transducer, pretty printed
"""
pairs = ''
results = transducer.extract_paths(output='dict')
for input,outputs in results.items():
pairs += remove_epsilons(input) + ":\n"
for output in outputs:
out = remove_epsilons(output[0])
pairs += " " + out + "\n"
return pairs
def read_test_file(filepath):
"""
Read in the test file specified where each line is a target input to the
transducer. The left token is the input to the transducer and the right token
is the output from the transducer.
"""
expected_output = {}
with open(filepath) as tst_file:
for line in tst_file:
line = line.split(" ")
line = [piece.strip() for piece in line]
expected_output[line[0]] = line[1]
return expected_output
class FstPathNotFound(Exception):
pass
class Definitions:
"""A utility class for creating Set FSTs for reuse in FST regex.
(Set FST, e.g., [a|i|u|e|o])
For example, we might wish to replace V with all the vowels of our language in a regex. This
is not possible natively with hfst, but we achieve it using string manipulations. Simply
add your desired replacement sets and desired names to the constructor dictionary, then call
the replace method of the resulting object on a regex string before passing it to hfst.
"""
def __init__(self, definitions):
"""
Args:
definitions (dict): dictionary with keys of Fst set names, and values of regex sets.
"""
self.defs = definitions
for fstname, regex in self.defs.items():
replaced = True
while replaced:
replaced = False
for fstname2, regex2 in self.defs.items():
if fstname != fstname2:
result = regex.replace(fstname2, regex2)
if result != regex:
self.defs[fstname] = result
regex = result
replaced = True
break
def replace(self, string):
"""Replaces all defined set names occuring in regex string with corresponding set.
Args:
string (str): string in which we wish to replace defined FST names with corresponding FSTs.
Returns:
str: The original string with the defined FSTs substituted in place of their names.
"""
for i, j in self.defs.items():
string = string.replace(i, j)
return string
|
68c281e253778c4c3640a5c67d2e7948ca8e150a | farahhhag/Python-Projects | /Grade & Attendance Calculator (+Data Validation).py | 2,363 | 4.21875 | 4 | data_valid = False
while data_valid == False:
grade1 = input("Enter the first grade: ")
try:
grade1 = float(grade1)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade1 <0 or grade1 > 10:
print("Grade should be in between 0 to 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
grade2 = input("Enter the second grade: ")
try:
grade2 = float(grade2)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade2 <0 or grade2 > 10:
print("Grade should be in between 0 to 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
total_class = input("Enter the number of total class: ")
try:
total_class = int(total_class)
except:
print("Invalid input. Only numbers are accepted.")
continue
if total_class <= 0:
print("The number of total class can't be less than 0")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
absences = input("Enter the number of total absences: ")
try:
absences = int(absences)
except:
print("Invalid input. Only numbers are accepted.")
continue
if absences <=0 or absences > total_class:
print("The number of absences can't be less than 0 or greater than the number of total classes")
continue
else:
data_valid = True
avg_grade = (grade1 + grade2) / 2
attendance = (total_class - absences) / total_class
print("Average Grade:", round(avg_grade, 2))
print("Attendance Rate:", str(round((attendance * 100),2))+"%")
if (avg_grade >= 6.0 and attendance >= 0.8):
print("The student has been approved")
elif(avg_grade < 6.0 and attendance < 0.8):
print("The student has failed because the attendance rate is lower than 80% and the average grade is lower than 6.0")
elif(attendance >= 0.8):
print("The student has failed because the average grade is lower than 6.0")
else:
print("The student has failed because the attendance rate is lower than 80%")
|
6e85b53b38083b361d3d6d3a43b2b6fbc9d82ba9 | farahhhag/Python-Projects | /Age Comparison.py | 226 | 4.21875 | 4 | my_age = 26
your_age = int( input("Please type your age: ") )
if(my_age > your_age):
print("I'm older than you")
elif(my_age == your_age):
print("We are the same age")
else:
print("You're older than me")
|
5e86a0009b9772cdb7db30b4fe9c30fa188b81c3 | TaehoLi/Elementary-Python | /list_tuple/listcat.py | 125 | 3.765625 | 4 | list1 = [1, 2, 3, 4, 5]
list2 = [10, 11]
listadd = list1 + list2
print(listadd)
listmulti = list2 * 3
print(listmulti)
|
85a6a8a1a40d384a727b0c51dd1f8d1a66e4cb0a | TaehoLi/Elementary-Python | /decorator/localfunc.py | 171 | 3.75 | 4 | def calcsum(n):
def add(a,b):
return a+b
sum = 0
for i in range(n+1):
sum = add(sum, i)
return sum
print('~10 =', calcsum(10))
|
3de5bc62ff32f07ca9ced0af29f66b3616d791c9 | TaehoLi/Elementary-Python | /list_tuple/listreplace.py | 100 | 3.609375 | 4 | nums = [0,1,2,3,4,5,6,7,8,9]
nums[2:5] = [20,30,40]
print(nums)
nums[6:] = [90,91]
print(nums)
|
92f70d0e38bc2ac662888167e7b93dc544fe5e39 | TaehoLi/Elementary-Python | /graphic/askstring.py | 507 | 3.640625 | 4 | from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog
main = Tk()
def btnclick():
name = tkinter.simpledialog.askstring("질문", "이름을 입력하시오")
age = tkinter.simpledialog.askinteger("질문", "나이를 입력하시오")
if name and age:
tkinter.messagebox.showwarning("환영", str(age) + "세 " + name + "님 반갑습니다.")
btn = Button(main, text="클릭", foreground="Blue", command = btnclick)
btn.pack()
main.mainloop()
|
07ce2b737b3702cb761caf5cd0571c09de096150 | sahirabibi/pong | /paddle.py | 719 | 4.0625 | 4 | # create paddle class in order to generate paddles for Pong
from turtle import Turtle
class Paddle(Turtle):
def __init__(self, position):
super().__init__()
self.shape("square")
self.penup()
self.setheading(90)
self.color("white")
self.shapesize(stretch_len=5)
self.setposition(position)
def move_up(self):
self.forward(20)
def move_down(self):
self.setheading(90)
self.backward(20)
class Walls(Turtle):
def __init__(self, position, length):
super().__init__()
self.shape("square")
self.color("white")
self.shapesize(stretch_len=length)
self.setposition(position)
|
87fa091ab9c42b1bf8bb44125810496358f49e08 | dlewis2017/PyGame | /board.py | 645 | 3.578125 | 4 | import pygame
from spritesheet import spritesheet
from pygame.locals import *
import numpy
"""1 is water, 2 is ship, 3 is HIT, 4 is miss, 5 is opponent ship"""
class Board(object):
def __init__(self):
self.Matrix = [[1 for x in range(10)] for y in range(10)]
self.opp_ship_spaces = 10
def setSpace(self,x,y,new):
current_space = self.Matrix[y][x]
if new == 3 and current_space == 5:
self.Matrix[y][x] = new
self.opp_ship_spaces -= 1
else:
self.Matrix[y][x] = new
def getSpace(self,x,y):
return self.Matrix[y][x]
def checkWin(self):
if self.opp_ship_spaces == 0:
return True
else:
return False
|
82f5a480a9535f15d17700480c94782aed2a34ba | 5l1v3r1/robots1 | /xcommandx.py | 746 | 3.5625 | 4 | import sys
def spl(string, length):
return ' '.join(string[i:i+length] for i in xrange(0,len(string),length))
def binS2int(string):
# print string
num=0
count=1
for i in range (0,8):
num += int(string[i])*(128/count)
count=count*2
return num
fname="beepboop.txt"
f=open(fname)
lines=f.readlines()
f.close()
final=""
for line in lines:
line=line.replace("beep",".")
line=line.replace("boop","-") #this is backwards, but wanted to test
#line=line.replace(" ","")
line=line.replace("/","")
line=line.replace("\n"," ")
line=line.replace("\r"," ")
#print line
final += line
print final
print "##########"
#next=spl(final,8)
#y=next.split(" ")
#for x in y:
# a=binS2int(x)
# print str(a)
# print chr(a)
|
2506f6e4867d35f16b8fb00293236b7dd00d5cb8 | BR610/calculator-2 | /calculator_pre.py | 1,476 | 4.09375 | 4 | def calculator_pre():
"""pre-fix calculator, takes in input and performs requested operations"""
input_lst2 = []
input_op = raw_input("Please enter your choice: ")
input_lst = input_op.split(" ")
if input_lst[0] == "q" or input_lst[0] == "quit":
return "Quitting function"
else:
try:
for l in input_lst[1:]:
l = float(l)
input_lst2.append(l)
except:
return "Invalid input"
l2 = ['+', '-', '*', '/', 'square', 'cube', 'pow', 'mod']
if input_lst[0] !in l2:
return "Invalid entry"
if input_lst[0] == "+" and len(input_lst2) == 2:
return add(input_lst2[0], input_lst2[1])
elif input_lst[0] == "-" and len(input_lst2) == 2:
return subtract(input_lst2[0], input_lst2[1])
elif input_lst[0] == "*" and len(input_lst2) == 2:
return multiply(input_lst2[0], input_lst2[1])
elif input_lst[0] == "/" and len(input_lst2) == 2:
return divide(input_lst2[0], input_lst2[1])
elif input_lst[0] == "square" and len(input_lst2) == 1:
return square(input_lst2[0])
elif input_lst[0] == "cube" and len(input_lst2) == 1:
return cube(input_lst2[0])
elif input_lst[0] == "pow" and len(input_lst2) == 2:
return pow(input_lst2[0], input_lst2[1])
elif input_lst[0] == "mod" and len(input_lst2) == 2:
return mod(input_lst2[0], input_lst2[1])
else:
return "Mismatched inputs"
|
95c0cfdf0cac0422afe0bbe8c76a4c766b696b84 | DieusGD/Proyecto-web-python | /Practicas/DatosEnListas.py | 1,565 | 3.96875 | 4 |
def datSim(): #esta es una lista DatoSimple
cuenta = int(input("cuantos datos deseas procesar? \n"))
datos = []
conteo=1
while conteo <= cuenta:
dato = input("dato a procesar: \n")
datos.append(dato)
conteo = conteo + 1
else:
print(datos)
def datMed(): #este es un diccionario.Define solo el valor
dato = {}
cuenta = int(input("cantidad de datos: \n"))
conteo=1
key= 1
while conteo <= cuenta:
valor = input("dato: ")
dato[key] = valor
key = key + 1
conteo = conteo + 1
else:
print(dato)
def datDob(): #Define el ide y el valor del dato
cant = int(input("cuantos datos se procesaran?"))
cont = 0
datos = ([])
while cont < cant:
ide = str(input("ingresa el id: \n"))
val = str(input("ingresa el valor del dato: "))
cont = cont + 1
dato = [ide, val]
datos.append(dato)
print(datos)
def datCarac(): #Da distintos valores a un mismo dato
nom = str(input("Valor del Dato: "))
cant = int(input("cantidad de caracteristicas: "))
cont = 0
caracts = []
while cont < cant:
caract = str(input("caracteristica:"))
caracts.append(caract)
cont = cont + 1
product = {
"name":nom,
"datos":caracts
}
print(product.values())
def a1():
locations = {
(56.334, 5776):"Tokyo",
(30.6, 45634,6):"USA"
}
busq = str(input("tokio o Usa?: \n"))
if busq.lower() == "tokio":
print(locations)
# %%
|
985d57c54dceec13b20e89aa4904c1f0263474cc | tintin10q/RandomPythonProjects | /btw.py | 460 | 4.0625 | 4 | #
#
# done = False
#
# while done is not True:
# number_input = input("Give a price:")
# try:
# number_input = int(number_input)
# if number_input <= 0:
# print('Number needs to be more then 0')
# else:
# print("Price with btw is:", number_input * 1.21)
# done = True
# except ValueError:
# print("Please enter a number!")
def add_up(x, y):
return x + y
print(add_up(10))
|
ac18a73fbbabb18d704701f3b379a370b2bd69e9 | besnik/pycon2017-closures | /python/09_closure_over_func.py | 918 | 3.59375 | 4 | # closure over function
def counter(func):
count = 0
def inc_count():
func()
nonlocal count
count += 1
print(" Called", count, "times")
return inc_count
def hello():
print("Hi PyCon")
inc = counter(hello)
inc()
inc()
inc()
# closures over func
def create_logic(func):
def when(a,b):
if not (callable(a) and callable(b)):
raise TypeError("Expecting callable for input parameters")
return func(a,b)
return when
_and = create_logic(lambda x,y: x() and y())
_or = create_logic(lambda x,y: x() or y())
validate1 = lambda: True
validate2 = lambda: False
print(_and(validate1, validate1))
print(_and(validate2, validate1))
# more complex composition
is_valid = _and(
lambda: _or(validate1, validate2),
lambda: _and(validate1, validate1)
)
print(is_valid)
# and
# / \
# or and
# / \ / \
# v1 v2 v1 v1
|
a36be10c97b7e350aa41cb95df56e33af380febd | ivangonekrazy/colorgame | /solver/cell.py | 858 | 3.71875 | 4 | class Cell(object):
""" Stores the possible Pieces for any given Cell. """
def __init__(self, height):
self.height = height
self.colors = list("RGBPYO")
self.proposal = None
def set_color(self, color):
if not color in self.colors:
raise Exception("color already eliminated from this cell")
if self.proposal:
raise Exception("This cell already has a proposal.")
self.proposal = color
self.colors = []
def remove_possible(self, color):
if color in self.colors:
self.colors.remove(color)
@property
def possibilities(self):
return self.colors
def __repr__(self):
if self.proposal:
return "%s|( %s )" % (self.height, self.proposal)
return "%s|{%s}" % (self.height, "".join(self.colors))
|
c68084826badc09dd3f037098bfcfbccb712ee15 | kayazdan/exercises | /chapter-5.2/ex-5-15.py | 2,923 | 4.40625 | 4 | # Programming Exercise 5-15
#
# Program to find the average of five scores and output the scores and average with letter grade equivalents.
# This program prompts a user for five numerical scores,
# calculates their average, and assigns letter grades to each,
# and outputs the list and average as a table on the screen.
# define the main function
# define local variables for average and five scores
# Get five scores from the user
# find the average by passing the scores to a function that returns the average
# display grade and average information in tabular form
# as score, numeric grade, letter grade, separated by tabs
# display a line of underscores under this header
# print data for all five scores, using the score,
# with the result of a function to determine letter grade
# display a line of underscores under this table of data
# display the average and the letter grade for the average
# Define a function to return the average of 5 grades.
# This function accepts five values as parameters,
# computes the average,
# and returns the average.
# define a local float variable to hold the average
# calculate the average
# return the average
# Define a function to return a numeric grade from a number.
# This function accepts a grade as a parameter,
# Uses logical tests to assign it a letter grade,
# and returns the letter grade.
# if score is 90 or more, return A
# 80 or more, return B
# 70 or more, return C
# 60 or more, return D
# anything else, return F
# Call the main function to start the program
def main():
average = 0
score1 = 0
score2 = 0
score3 = 0
score4 = 0
score5 = 0
score1 = int(input("Score one: "))
score2 = int(input("Score two: "))
score3 = int(input("Score three: "))
score4 = int(input("Score four: "))
score5 = int(input("Score five: "))
find_average(score1, score2, score3, score4, score5)
average = find_average(score1, score2, score3, score4, score5)
get_letter_grade(average)
letter_grade = get_letter_grade(average)
print(" ")
print("Average Grade: ", '\t', "Letter Grade: ")
print("__________________________________________")
print(average, '\t', " ", letter_grade)
def find_average(score1, score2, score3, score4, score5):
average = 0.0
all_score = score1 + score2 + score3 + score4 + score5
average = all_score/5
return average
def get_letter_grade(average):
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >= 70:
return "C"
elif average >= 60:
return "D"
else:
return "F"
main()
|
ed61c43c7ab9b7ea26b890a00a08d2ed52ba3e47 | kayazdan/exercises | /chapter-3/exercise-3-1.py | 1,209 | 4.65625 | 5 | # Programming Exercise 3-1
#
# Program to display the name of a week day from its number.
# This program prompts a user for the number (1 to 7)
# and uses it to choose the name of a weekday
# to display on the screen.
# Variables to hold the day of the week and the name of the day.
# Be sure to initialize the day of the week to an int and the name as a string.
# Get the number for the day of the week.
# be sure to format the input as an int
nmb_day = input("What number of the day is it?: ")
int_nmb_day = int(nmb_day)
# Determine the value to assign to the day of the week.
# use a set of if ... elif ... etc. statements to test the day of the week value.
if int_nmb_day == 1:
print("Monday")
elif int_nmb_day == 2:
print("Tuesday")
elif int_nmb_day == 3:
print("Wednesday")
elif int_nmb_day == 4:
print("Thursday")
elif int_nmb_day == 5:
print("Friday")
elif int_nmb_day == 6:
print("Saturday")
elif int_nmb_day == 7:
print("Sunday")
else:
print("Out of range")
# use the final else to display an error message if the number is out of range.
# display the name of the day on the screen.
|
06e879dd6a2657fc014a95194c21d46ade187750 | joaolucas1337/Calculadora-em-python | /Calculadora.py | 909 | 4.09375 | 4 | def soma(n1, n2):
return n1 + n2
def subtracao(n1, n2):
return n1 - n2
def multiplicacao(n1, n2):
return n1 * n2
def divisao(n1, n2):
return n1 / n2
cont = True
while cont:
n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
calculo = (input('Digite qual operação deseja realizar (+, -, * ou /): '))
if calculo == '+':
print('O resultado é {}'.format(soma(n1, n2)))
elif calculo == '-':
print('O resultado é {}'.format(subtracao(n1, n2)))
elif calculo == '*':
print('O resultado é {}'.format(multiplicacao(n1, n2)))
elif calculo == '/':
print('O resultado é {}'.format(divisao(n1, n2)))
else:
print('Operação inválida')
opcao = input('eseja continuar [S,N]: ')
if opcao.upper() == 'N':
cont = False
|
32df186638244d5e02772da98c81b58a7f311c6d | adhikarchaudhary12/oop_python | /decorator3.py | 294 | 3.71875 | 4 | #decorating function with parameters
def smart_divide(func):
def inner(a,b):
if b == 0:
print("Cannot divide by zero")
return None
return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b
result = divide(6,2)
print(result) |
bfed62786fe29f26293669c97b39f2f58d153030 | adhikarchaudhary12/oop_python | /class_example6.py | 179 | 3.84375 | 4 | #object copying
import copy
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
p=Point(1,2)
q = copy.copy(p)
q.x = 2
print(p==q)
print(p.x)
print(q.x) |
228027932cf3a8efa42d8824053a6131b372e963 | nandhakumarv5858/Nandha | /prime number.py | 192 | 4.21875 | 4 | prime=int(input("Enter your number\n"))
if prime>1:
for i in range(prime):
if (prime % 2)==0:
print(prime,"is not a prime number")
break
else:
print(prime," It is a prime number")
|
233fee092f2443c9f5a7afa6b9e3ff5f6947f22f | PointerFLY/LeetCode-Python3 | /6_zigzag_conversion.py | 778 | 3.515625 | 4 | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
rows = [''] * numRows
str_idx = 0
i = 0
down = True
while str_idx < len(s):
rows[i] += s[str_idx]
if down:
i += 1
if i == numRows - 1:
down = False
else:
i -= 1
if i == 0:
down = True
str_idx += 1
str_ = ''
for row in rows:
str_ += row
return str_
s = Solution()
assert s.convert('PAYPALISHIRING', 3) == 'PAHNAPLSIIGYIR'
assert s.convert('AB', 1) == 'AB' |
3f93cce60f09f0174fa3dcfa141f279a16926457 | iggirex/pythonHardWay | /ex2.py | 246 | 3.890625 | 4 | print "I will now count my chickens"
print "Roosters", 100 - 25 * 3 / 4
print "Now I will count the eggs"
print float(3 + 2 + 1 - 5 + 40 % 2)
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", float(3 + 2.5)
|
627396617109d519b142a2e8299ba0d0e9890e90 | Luk390/Alien-Game | /ship.py | 1,202 | 3.796875 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Manages the ship"""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.settings = ai_game.settings
# Load the ship image to the rect
self.image = pygame.image.load('images/BEER.bmp')
self.rect = self.image.get_rect()
# Start each new ship at the bottom center of the screen
self.rect.midbottom = self.screen_rect.midbottom
# Movement flag
self.moving_right = False
self.moving_left = False
# Ship's position as decimal value
self.x = float(self.rect.x)
def update(self):
"""Update the ship's position based on the movement flag"""
if self.moving_right:
if self.rect.right < self.settings.screen_width - 10:
self.x += self.settings.ship_speed
if self.moving_left:
if self.rect.left > 5:
self.x -= self.settings.ship_speed
# Update ship position
self.rect.x = self.x
def blitme(self):
# Draw the ship at its current location
self.screen.blit(self.image, self.rect)
def center_ship(self):
"""Center ship"""
self.rect.midbottom = self.screen_rect.midbottom
self.x = float(self.rect.x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.