blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
|---|---|---|---|---|---|---|
c19bcf90ac65cff5f8855d1507bbe7c24b6d59bb
|
esn89/azlyricgrabber
|
/urlchecker.py
| 2,088
| 3.53125
| 4
|
#!/usr/bin/python2.7
import requests
import sys
from lxml import html
# this is just an URL for testing, please remove
urlheader = "http://search.azlyrics.com/search.php?q="
def generateURL(artist, title):
"""Generates an URL based on the user's artist and song title
Args:
artist -- artist of the song
title -- title of the song
Returns:
0 -- if the song and artist cannot be found
1 -- if the song and artist can be found
url - the url that was generated based on user input
"""
# Strip the leading and trailing whitespace. Put "+" in between
# useful whitespaces.
artist = artist.lstrip().rstrip().replace(" ", "+")
title = title.lstrip().rstrip().replace(" ", "+")
# Generate the full url
url = urlheader + artist + "+" + title
return checkURL(url), url
def checkURL(url):
"""Checks the validity of the URL generated from artist and title
Args:
url -- the generated URL from generateURL(artist, title)
Returns:
0 -- if the song and artist does not exist
1 -- if the song and artist exists
"""
haslyrics = 0
try:
page = requests.get(url)
except requests.exceptions.RequestException as e:
print e
sys.exit(1)
tree = html.fromstring(page.text)
listofresults = tree.xpath('//div[@class="panel-heading"]/b')
# Sometimes when input is vague, www.azlyrics.com returns a lot of possible
# matches such as "Artist results", "Album results" and "Song results".
# I only need "Song Results".
# Do not give user the option to filter by artist/album. It forces them to
# enter much stricter input
for l in listofresults:
if 'Artist' in l.text or 'Album' in l.text:
haslyrics = 0
return haslyrics
message = tree.xpath('//div[@class="alert alert-warning"]/text()')
if message:
# Lyrics can't be found
response = message[0]
if "Sorry" in response:
haslyrics = 0
else:
haslyrics = 1
return haslyrics
|
e61128196cc9b688198b89bba1d32e7ff993884f
|
antonioqc/Programacion1920
|
/primerTrimestre/introduccion_programacion_python/2alternativas_py/ej19alt.py
| 1,004
| 4
| 4
|
# Programa: ej19alt.py
# Propósito: Escribe un programa que pida un número entero entre uno y doce e
# imprima el número de días que tiene el mes correspondiente.
#
# Autor: Antonio Quesada
# Fecha: 23/10/2019.
#
# Variables a usar:
# * num
#
# Algoritmo:
# Leer numero de mes como entero
# Si es el 1,3,5,7,8,10,12 el mes tiene 31 días
# Si es el 2 el mes tiene 28 o 29 días
# Si es el 4,6,9,11 el mes tiene 31 días
# Si no mostrará un mensaje de error ("Mes incorrecto")
#Petición de datos.
num = int(input("Introduce un número entre uno y doce que corresponda a un mes del año: "))
print("------------------------------------------------------------------------------------")
#Proceso y salida.
if num == 1 or num == 3 or num == 5 or num == 7 or num == 8 or num == 10 or num == 12:
print("El mes tiene 31 días")
elif num == 4 or num == 6 or num == 9 or num == 11:
print("El mes tiene 30 días")
elif num == 2:
print("El mes tiene 28 o 29 días")
else:
print("Mes incorrecto")
|
cc66757e63c735a55f543b9914ed76bc3f73cc86
|
alexandradecarvalho/artificial-intelligence
|
/python-programming/sortingAlgorithms.py
| 3,693
| 4.09375
| 4
|
#1 - Function that, given a list of numbers, executes selection sort
def numSelectionSort(lista):
if len(lista) > 1:
potencial_trader = min(lista[1:])
if potencial_trader < lista[0]:
lista[lista.index(potencial_trader)], lista[0] = lista[0], potencial_trader
return [lista[0]] + numSelectionSort(lista[1:])
elif len(lista) == 1:
return [lista[0]]
else:
return []
#2 - Function that, given a list of numbers, executes bubble sort
def numBubbleSort(lista):
if lista:
swapped = 0
for x in range(0, len(lista)-1):
if lista[x] > lista[x+1] :
lista[x], lista[x+1] = lista[x+1], lista[x]
swapped = 1
if swapped:
return numBubbleSort(lista)
else:
return lista
else:
return []
#3 - Function that, given a list of numbers, executes quick sort
def numQuickSort(lista):
if len(lista)>1:
pivot = lista[-1]
res = [pivot]
for element in lista:
if element > pivot:
res.append(element)
elif element != pivot:
res.insert(0,element)
pivot_idx = res.index(pivot)
return numQuickSort(res[:pivot_idx]) + [pivot] + numQuickSort(res[pivot_idx+1:])
elif len(lista) == 1:
return [lista[0]]
else:
return []
#4 - Function that, given a list, executes selection sort
def selectionSort(lista, order):
if len(lista) > 1:
potencial_trader = lista[1]
for x in lista[1:]:
if order(x,potencial_trader):
potencial_trader = x
if order(potencial_trader,lista[0]):
lista[lista.index(potencial_trader)], lista[0] = lista[0], potencial_trader
return [lista[0]] + selectionSort(lista[1:], order)
elif len(lista) == 1:
return [lista[0]]
else:
return []
#5 - Function that, given a list, executes bubble sort
def bubbleSort(lista, order):
if lista:
swapped = 0
for x in range(0, len(lista)-1):
if not order(lista[x],lista[x+1]) :
lista[x], lista[x+1] = lista[x+1], lista[x]
swapped = 1
if swapped:
return bubbleSort(lista, order)
else:
return lista
else:
return []
#6 - Function that, given a list, executes quick sort
def quickSort(lista, order):
if len(lista)>1:
pivot = lista[-1]
res = [pivot]
for element in lista:
if order(element,pivot):
res.insert(0,element)
elif element != pivot:
res.append(element)
pivot_idx = res.index(pivot)
return quickSort(res[:pivot_idx], order) + [pivot] + quickSort(res[pivot_idx+1:], order)
elif len(lista) == 1:
return [lista[0]]
else:
return []
if __name__ == "__main__":
print("Testing the numerical algorithms: [64,25,12,22,11] ")
print("SELECTION SORT: " + str(numSelectionSort([64,25,12,22,11])))
print("BUBBLE SORT: " + str(numBubbleSort([64,25,12,22,11])))
print("QUICK SORT: " + str(numQuickSort([64,25,12,22,11])))
print()
print("Testing the generic algorithms: ['goncalo',64,25,12,22,'alexa',11] ")
lesser = lambda x, y: x < y if type(x) == type(y) else True if type(x) == int else False
print("SELECTION SORT: " + str(selectionSort(['goncalo',64,25,12,22,'alexa',11], lesser)))
print("BUBBLE SORT: " + str(bubbleSort(['goncalo',64,25,12,22,'alexa',11], lesser)))
print("QUICK SORT: " + str(quickSort(['goncalo',64,25,12,22,'alexa',11], lesser)))
|
feb7fc1bcaa9d4fb9694969bee9706b15e89a382
|
yemre-aydin/VS-Code-Python
|
/01_python_giris/0408_list_operasyonlari.py
| 280
| 4.15625
| 4
|
"""
listem =[2,4,6,8]
temp=listem[1]
listem[1]=listem[2]
listem[2]=temp
listem[1],listem[2]=listem[2],listem[1]
print(listem)
"""
#slice
url="www.azizbektas.com"
print(url[-3:])
print(url[0:3])
#iterable
print(url[0])
print(url[1])
print(url[2])
print(url[3])
print(url[4])
|
b5187cd59c3cf45cfb2de457c86de9111eda62a1
|
chrisnorton101/myrpg
|
/battlescript.py
| 2,379
| 3.640625
| 4
|
from Classes.characters import *
from Classes.abilities import *
import time
player = player
enemy = beg_enemies[random.randrange(0,4)]
def battle():
print("A {} has attacked!".format(enemy.name))
time.sleep(1)
running = True
while running:
print("==================")
player.choose_action()
choice = int(input("\nAction: ")) - 1
if choice == 0:
dmg = player.deal_dmg()
enemy.take_dmg(dmg)
print("\nYou attacked for {} points of damage!".format(dmg))
time.sleep(1)
elif choice == 1:
player.choose_ability()
ability_choice = int(input("Ability: ")) - 1
ability = player.abilities[ability_choice]
ability_dmg = ability.generate_dmg()
current_sta = player.get_sta()
if ability.cost > current_sta:
print("You don't have enough stamina!")
continue
player.reduce_sta(ability.cost)
enemy.take_dmg(ability_dmg)
print("\n{} deals {} points of damage!".format(ability.name, ability_dmg))
time.sleep(1)
else:
print("\nMake a proper selection!")
time.sleep(1)
continue
if enemy.get_hp() > 0:
enemy_dmg = enemy.deal_dmg()
player.take_dmg(enemy_dmg)
print("\nThe Enemy Attacked for {} points of damage!".format(enemy_dmg))
time.sleep(1)
print("==================")
print("Enemy HP: {}/{}".format(enemy.get_hp(), enemy.max_hp))
print("{} HP: {}/{}".format(player.name, player.get_hp(), player.max_hp))
print("Player Stamina: {}/{}".format(player.get_sta(), player.max_sta))
time.sleep(1)
elif enemy.get_hp() == 0:
print("You have defeated the Enemy!")
running = False
player.exp_gain(enemy.exp)
print("=================")
print("You gained {} experience!".format(enemy.exp))
print("Player Exp: {}/{}".format(player.exp, player.lvl_exp))
print("Level {}".format(player.lvl))
elif player.get_hp() == 0:
print("You have been defeated!")
running = False
|
2bff56880662b264b4e478114f96544931dbd869
|
benamoreira/PythonExerciciosCEV
|
/desafio058.py
| 246
| 3.859375
| 4
|
from random import randint
numpc = randint(0,10)
print(numpc)
chute = 0
contachute = 0
while chute != numpc:
chute = int(input('Qual seu paupite?'))
contachute += 1
print('Voçê precisou de {} chutes para acertar!'.format(contachute))
|
89a210fc77841d194ffe0dab78765499ba7eef2d
|
wdahl/Newtons-Method
|
/newtons_method.py
| 510
| 3.671875
| 4
|
import math
def f(x):
return .5 + math.sin(x) - math.cos(x)
def div_f(x):
return math.cos(x) + math.sin(x)
x0 = 1
converges = False
count = 1
while count <= 4:
x1 = x0 - f(x0)/div_f(x0)
print(f'Iternation {count}:')
print(f'x0 = {x0}')
print(f'x1 = {x1}')
print(f'f(x0) = {f(x0)}')
print(f'f\'(x0) = {div_f(x0)}')
print(f'|(x1-x0)/x1| = {abs((x1 - x0)/x1)}')
x0 = x1
count += 1
if(converges):
print("Soultion found!")
else:
print("Did not converge!")
|
878eef66a416529e61f2b572e411dc26b4571c9a
|
suarezluis/DB_ClassRepo
|
/fkumi/COSC1336 - Programming Fundamentals I/Programming Assignments/Program 11/Program11-Template.py
| 2,445
| 3.640625
| 4
|
#***************************************************************
#
# Developer: <Your full name>
#
# Program #: <Assignment Number>
#
# File Name: <Program11.py>
#
# Course: COSC 1336 Programming Fundamentals I
#
# Due Date: <Due Date>
#
# Instructor: Fred Kumi
#
# Chapter: <Chapter #>
#
# Description:
# <An explanation of what the program is designed to do>
#
#***************************************************************
BASE_YEAR = 1903
#***************************************************************
#
# Function: main
#
# Description: The main function of the program
#
# Parameters: None
#
# Returns: Nothing
#
#**************************************************************
def main():
# Local dictionary variables
year_dict = {}
count_dict = {}
developerInfo()
# Open the file for reading
input_file = open('Program11.txt', 'r')
# End of the main function
#***************************************************************
#
# Function: main
#
# Description: The main function of the program
#
# Parameters: None
#
# Returns: Nothing
#
#**************************************************************
def showResults(year_dict, count_dict):
# Receive user input
year = int(input('Enter a year in the range 1903-2019: '))
# Print results
if year == 1904 or year == 1994:
print("The world series wasn't played in the year", year)
elif year < 1903 or year > 2019:
print('The data for the year', year, \
'is not included in our database.')
else:
winner = year_dict[year]
wins = count_dict[winner]
print('The team that won the world series in ', \
year, ' is the ', winner, '.', sep='')
print('They have won the world series', wins, 'times.')
# End of showResults
#***************************************************************
#
# Function: developerInfo
#
# Description: Prints Programmer's information
#
# Parameters: None
#
# Returns: Nothing
#
#**************************************************************
def developerInfo():
print('Name: <Put your full name here>')
print('Course: Programming Fundamentals I')
print('Program: Eleven')
print()
# End of the developerInfo function
# Call the main function.
main()
|
c7de2f1e63870846a3b30b2fdb30172c1be8b217
|
matheuscordeiro/random-problems
|
/Cracking the Coding Interview/Cap 1/1.6-string-compression.py
| 425
| 3.921875
| 4
|
#!/usr/local/bin/python3
# String compression
def string_compression(s):
before = ''
final = ''
count = 0
for key, character in enumerate(s):
if character != before:
if key != 0:
final = f'{final}{count}{before}'
count = 1
before = character
else:
count += 1
final = f'{final}{count}{before}'
if len(final) >= len(s):
return s
else:
return final
print(string_compression('aabbbcc'))
|
4e1f19ae1becc203ce35103f0817da22cb2c43c2
|
LalithK90/LearningPython
|
/privious_learning_code/String/String title() Method.py
| 407
| 4.125
| 4
|
str = "this is string example....wow!!!"
print(str.title())
# Description
#
# The method title() returns a copy of the string in which first characters of all the words are capitalized.
# Syntax
#
# Following is the syntax for title() method −
#
# str.title();
#
# Parameters
#
# NA
#
# Return Value
#
# This method returns a copy of the string in which first characters of all the words are capitalized.
|
68d46b305a23614954d5821032a32bbaad56e611
|
baiyang0223/python
|
/testunittest/testcls.py
| 954
| 3.515625
| 4
|
'''
@Author: Baiy
@Date: 2018-11-11 21:35:41
@LastEditors: Baiy
@LastEditTime: 2018-11-11 22:06:57
@Email: [email protected]
@Company: Horizon Hobot
@Description: python中cls方法和self方法
'''
class A(object):
a = 'a'
@staticmethod
def foo1(name):
print('hello', name)
def foo2(self, name):
print('hello', name)
@classmethod
def foo3(cls, name):
print('hello', name)
class B(object):
b = 'b'
@staticmethod
def foo1(name):
print('hello-1', name)
def foo2(self, name):
print('hello-2', name)
@classmethod
def foo3(cls, name):
print(cls)
print('hello-3', name)
print(cls.b) # 可通过cls来直接访问内部参数,甚至不需要定义对象
cls().foo2(name) # 可通过cls()方法直接来访问类内部方法
b = B()
B.foo3("nihao")
print(B.foo3)
print("=========" * 10)
print(b)
b.foo3("nibuhao")
print(b.foo3)
|
573ddd641ec68b75a15c9369d22abe4f57670629
|
NikilReddyM/python-codes
|
/itertools.permutations().py
| 215
| 3.71875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 20:38:29 2017
@author: HP
"""
from itertools import permutations
a = input().split()
for i in permutations(sorted(a[0]),int(a[1])):
print(''.join(i))
|
c83ded3eb546fe151ea46e56e01f7917efe2bb0c
|
awatimc/python-programming
|
/a.py
| 274
| 3.890625
| 4
|
userinput = input()
count ={"UPPER":0,"LOWER":0}
for i in userinput:
if userinput.isupper():
count["UPPER"]+=1
elif userinput.islower():
count["LOWER"]+=1
else:
pass
print("Upper case letter",count["UPPER"])
print("LOWER case letter",count["LOWER"])
|
5550c76a7aab923312db91d112a9f20f540bbd47
|
marcvifi10/Curso-Python
|
/Python 1/2 - Condicionales/18 - Estructura if-elif-else/Estructura if-elif-else.py
| 289
| 4.21875
| 4
|
# Condicionales
numero = int(input("Entra un numero: "))
if numero > 0:
print("\nEl numero es positivo!!!")
elif numero < 0:
print("\nEl numero es negativo!!!")
elif numero == 0:
print("\nEl numero es igual a 0")
else:
print("ERROR!!!")
print("\nFIN DEL PROGRAMA!!!")
|
ed2bf6994d7983ae389d7bd19a9878695fd6b913
|
fabianrmz/python-course
|
/basic-funcions/slicing.py
| 199
| 4.25
| 4
|
# slicing
x = "computer"
print(x[1:4])
# 1 to 6 in a step of 2
print(x[1:6:2])
# 3 to the end of string
print(x[3:])
# 0 to end by a step of -1
print(x[::-1])
# last item of string
print(x[-1])
|
3e8b6f5203e35b6558a2fe91a23e600d4b919d46
|
MindongLab/PyHokchew
|
/pyhokchew/utils.py
| 435
| 3.859375
| 4
|
import unicodedata
def normalise(s) -> str:
"""
Normalise the Foochow Romanized string, by replacing combining characters with a combined character.
['e', '̤', '́', 'u', '̤', 'k'] normalize ---> ['é', '̤', 'ṳ', 'k']
:param s: The original string to be normalized.
:return: string
"""
return unicodedata.normalize('NFKC', s)
def denormalise(s) -> str:
return unicodedata.normalize('NFKD', s)
|
f93a554347d9222d8ad438168a7dc5cea1d7bee9
|
julissaf/Python-Code-Samples-6
|
/Problem2NumList10.py
| 162
| 3.546875
| 4
|
#Julissa Franco
#03/14/2019
#Create a number list L using a while loop
L=[]
counter=0
while counter < 11:
L.append(counter)
counter += 1
print(L)
|
ac349eb4da08279d11d242bf2bb67556729f4393
|
zeirn/Exercises
|
/Week 4 - Workout.py
| 815
| 4.21875
| 4
|
x = input('How many days do you want to work out for? ') # This is what we're asking the user.
x = int(x)
# These are our lists.
strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings']
cardio = ['Running', 'Swimming', 'Biking', 'Jump rope']
workout = []
for d in range(0, x): # This is so that 'd' (the day) stays within the range of 0 and whatever x is.
# 'z' and 'z2' are the exercises in the lists.
z = strength[d % len(strength)] # The number of days divided by the length of the number of items in the
z2 = cardio[d % len(cardio)] # list strength/cardio. z is the answer to the first equation. z2 is answer to other.
workout.append(z + ' and ' + z2) # This adds these two answers to the end of the workout list.
print('On day', d+1, (workout[d]))
|
c3719ad3e54f8ba02b24d884a79d39e6d94030b1
|
316513979/thc
|
/Clases/Programas/Tarea05/Problema9L.py
| 149
| 3.640625
| 4
|
def divisibilidad(a):
i=1
L=[]
while 1<=i and i<=a:
r=a%i
if r == 0:
L.append (i)
i=i+1
return L
|
f74b51feceef66761df0439c6e5610fc1eb5ab55
|
bosea949/Reinforcement-Learning
|
/Bandits algorithms/exp3.py
| 2,055
| 3.578125
| 4
|
import random
import math
def categorical_draw(probs):
z = random.random()
cum_prob = 0.0
for i in range(len(probs)):
prob = probs[i]
cum_prob += prob
if cum_prob > z:
return i
return len(probs) - 1
class Exp3():
def __init__(self,weights,learning_rate):
self.weights = weights
self.learning_rate=learning_rate
return
def initialize(self, n_arms):
self.weights = [1.0 for i in range(n_arms)]
return
def select_arm(self):
n_arms = len(self.weights)
total_weight=sum(self.weights)
probs = [0.0 for i in range(n_arms)]
for arm in range(n_arms):
probs[arm] = (self.weights[arm] /total_weight)
return categorical_draw(probs)
def update(self, chosen_arm, reward):
n_arms = len(self.weights)
total_weight = sum(self.weights)
prob_chosen_arm = (self.weights[chosen_arm] /total_weight)
chosen_arm_reward = 1-((1-reward)/prob_chosen_arm)
"The if and else in the for loop is the indicator part"
for arm in range(n_arms):
if arm ==chosen_arm:
growth_factor = math.exp(self.learning_rate*chosen_arm_reward)
"Scaling down the weights if python considers the new weight as infinity"
if self.weights[arm] * growth_factor==math.inf:
self.weights=[math.exp(-400)*self.weights[arm] for arm in range(n_arms)]
else:
growth_factor = math.exp(self.learning_rate)# For other arms its just the learning rate(Due to the indicator function)
"Scaling down the weights if python considers the new weight as infinity"
if self.weights[arm] * growth_factor==math.inf:
self.weights=[math.exp(-400)*self.weights[arm] for arm in range(n_arms)]
self.weights[arm] = self.weights[arm] * growth_factor
"Scaling down the weights if python considers the total weight as infinity"
if sum(self.weights)==math.inf:
self.weights=[math.exp(-400)*self.weights[arm] for arm in range(n_arms)]
|
0f1a3a75169e0fc6c2397bcc8516c5656b926123
|
mike-hmg/learnpythehardway
|
/exercises/ex9.py
| 470
| 3.984375
| 4
|
## Exercise #9
days = "Mon Tue Wed Thu Fri Sat Sun"
# \n denotes new line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print ("Here are the days: ", days)
print ("Here are the months", months)
# 3 double quotes lets everything work multiline
print ("""
Theres something going on here.
With the three double quotes
we'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
### Remember python3 likes the parenthesis()
|
e6aaf45f5f393393e6c1cfc3d0c6388e7d6dbfed
|
Zahidsqldba07/codesignal-46
|
/findSubStrings.py
| 4,488
| 3.953125
| 4
|
'''
Input:
words: ["Apple",
"Melon",
"Orange",
"Watermelon"]
parts: ["a",
"mel",
"lon",
"el",
"An"]
Expected Output:
["Apple",
"Me[lon]",
"Or[a]nge",
"Water[mel]on"]
'''
'''
iterate through words find out if parts are in it
iterate through parts find out if parts are in parts
replace instaces of parts within parts with []
'''
def wordInWord(word,part):
index = word.find(part)
length = len(part)
#word = word[index:index+1]
if(index>-1):
returnThis=word[0:index] + "[" + part + "]" + word[index + length:len(word)]
return returnThis
else:
return None
# return word
def partInWord(word):
index = word.find('[')
index2=word.find(']')
if(index>-1):
returnthis=word[index:index2]
return returnthis
else:
return None
def findSubstrings(words, parts):
newWords = []
maxLength=0
for i in words:
currentWord = []
partsInWord = {}
#partsInWordIndex = []
#count=-1
for j in parts:
#count+=1
if i == 'televise' and j == 'ise':
a = 1
word=wordInWord(i,j)
if word != None:
currentWord.append(word)
if(partsInWord.get(word.index(j)) == None or len(partsInWord[word.index(j)])<len(j) ):
partsInWord[word.index(j)]=j
#partsInWordIndex.append()
# countMax=count(p for p in currentWord if len(p) == maxLength)
# newWords.append(max(currentWord, key=len))
partsInWordSorted = sorted(partsInWord, key=partsInWord.get, reverse=False) #partsInWord.items() #.values() #sorted(partsInWord, key=partsInWord.__getitem__) #sorted(partsInWord.items(), key=lambda kv: kv[1])
#partsInWordSorted2=list(partsInWordSorted)
if(len(partsInWord)>0):
# maxWord=max(partsInWord, key=len)
# maxLength = len(maxWord)
maxLength= max(len(v) for k, v in partsInWord.items())
#smallestIndex = min(index(v) for k, v in partsInWord.items())
#smallestIndex = min(partsInWord.items().All(f= > len(f) = maxLength))
listPartsInWord = list(partsInWord.values())
shortPartsInWord = [x for x in listPartsInWord if len(x) == maxLength]
indexOfShortPartsInWord = [i.index(x) for x in shortPartsInWord]
smallestIndex = min(indexOfShortPartsInWord)
#smallestIndex = all(str(i.index(f)) in f for f in shortPartsInWord)
# max(stats.items(), key=operator.itemgetter(1))[0]
# maxLength=len(maxWord)-1-maxWord.index('[')-
for j in partsInWordSorted:
if i == 'televise':
a=1
if len(partsInWord[j]) == maxLength and i.index(partsInWord[j]) == smallestIndex:
appendWord=wordInWord(i,partsInWord[j])
if appendWord != None:
newWords.append(appendWord)
break
else:
newWords.append(i)
#newWords.append(max(currentWord,key=len))
# values=currentWord.index(max(currentWord,key=len))
# print(values)
#newWords.append(currentWord[values.index(min(values))])
# else:
# newWords.append(i)
#return wordInWord("Melon","lon")
return newWords
# print(findSubstrings)
#
# def findSubstrings(words, parts):
# returnthis =[]
# for i in words:
# # partsIndex={}
# wordsInParts=set()
# word = ""
# for j in parts:
# for b in wordsInParts:
# index = b.index(j)
#
# if j in i:
# # index=i.index(j)
# #print(index)
# # partsIndex.update(index,j)
# wordsInParts.add(j)
#
# print(partsIndex)
# words=["Apple",
# "Melon",
# "Orange",
# "Watermelon"]
# parts= ["a",
# "mel",
# "lon",
# "el",
# "An"]
words= ["neuroses",
"myopic",
"sufficient",
"televise",
"coccidiosis",
"gules",
"during",
"construe",
"establish",
"ethyl"]
parts= ["aaaaa",
"Aaaa",
"E",
"z",
"Zzzzz",
"a",
"mel",
"lon",
"el",
"An",
"ise",
"d",
"g",
"wnoVV",
"i",
"IUMc",
"P",
"KQ",
"QfRz",
"Xyj",
"yiHS"]
output=findSubstrings(words, parts)
print(output)
expected = ["neuroses",
"myop[i]c",
"suff[i]cient",
"telev[ise]",
"cocc[i]diosis",
"[g]ules",
"[d]uring",
"construe",
"est[a]blish",
"ethyl"]
|
f3080b02323a1793589bc7d72751220dbc3c61d5
|
MrHamdulay/csc3-capstone
|
/examples/data/Assignment_6/clleli002/question2.py
| 1,427
| 3.828125
| 4
|
"""basic vector calculations in 3 dimensions
Elizabeth Cilliers
20/04/2014"""
def vcalc():
InputVectorA = input ("Enter vector A:\n")
vectorA = InputVectorA.split (" ")
InputVectorB = input ("Enter vector B:\n")
vectorB = InputVectorB.split (" ")
#Addition
answer=[]
for i in range(len(vectorA)):
elemA= eval(vectorA[i])
elemB= eval(vectorB[i])
add=elemA+elemB #add elements in vectors
answer.append (add) #add answer to the list
print("A+B =", answer)
#DotProduct
count=0
for i in range(len(vectorA)):
elemA= eval(vectorA[i])
elemB= eval(vectorB[i])
answer=elemA*elemB #multiply the value of each corresponding element together
count= count+answer #add this to count
print("A.B =", count)
#Norm
count=0
for i in range(len(vectorA)):
elemA= eval(vectorA[i])
elemAsqr=elemA**2 #square element
count=count+elemAsqr #add this count
answer=count**0.5 #squareroot total of count
f_answer='{0:0.2f}'.format(answer) #put it to 2 decima places
print("|A| =",f_answer)
count=0
for i in range(len(vectorB)):
elemB= eval(vectorB[i])
elemBsqr=elemB**2
count=count+elemBsqr
answer=count**0.5
f_answer= '{0:0.2f}'.format(answer)
print("|B| =",f_answer)
vcalc()
|
a3d89cf93c38e1f4e8de147ebbc514d10c4e9ca8
|
ericachesley/guessing-game
|
/game.py
| 4,142
| 4.0625
| 4
|
"""A number-guessing game."""
# Put your code here
from random import randint
def round(name, mini, maxi, guesses):
number = randint(mini, maxi)
print(f"\nOk, {name}, I'm thinking of a number between {mini} and {maxi}. You have {guesses} guesses. Can you guess my number?")
count = 0
while count < guesses:
guess = generateGuess(mini, maxi)
count += 1
if evaluateGuess(number, guess):
print (f"You guessed my number in {count} tries, {name}!")
return count
print(f"Oh no! You're out of guesses. My number was {number}. Better luck next time.\n")
return 10000
def generateGuess(mini, maxi):
while True:
guess = input("What's my number? ")
try:
guess = int(guess)
except ValueError:
print("Please guess an integer.")
continue
if guess < mini or guess > maxi:
print("Your guess is out of range. Pick a number between 1 and 100, please.")
continue
break
return guess
def evaluateGuess(number, guess):
if guess == number:
return True
elif guess < number:
print ("Too low.")
else:
print ("Too high.")
return False
def setParameters():
print("")
while True:
mini = input("What would you like the bottom of the range to be? ")
try:
mini = int(mini)
except ValueError:
print ("Please choose an integer.")
continue
break
while True:
maxi = input("What would you like the top of the range to be? ")
try:
maxi = int(maxi)
except ValueError:
print ("Please choose an integer.")
continue
if maxi <= mini:
print("The top of your range needs to be higher than the bottom.")
continue
break
while True:
guesses = input("How many guesses would you like? ")
try:
guesses = int(guesses)
except ValueError:
print ("Please choose an integer.")
continue
if guesses <= 0:
print ("Please choose a positive integer.")
continue
break
return [mini, maxi, guesses]
def computerTurn(mini, maxi, guesses):
print(f"\nMy turn! Think of a number between {mini} and {maxi} for me to guess in {guesses} guesses.")
input("Hit enter when you've got your number. ")
print("")
count = 0
while count < guesses:
guess = int((mini+maxi)/2)
count += 1
while True:
feedback = input(f"Is your number {guess}? [a] Yes, [b] Too high, [c] Too low. ")
if feedback == 'a':
print(f"Hooray! I got your number in {count} guesses.")
return count
elif feedback == 'b':
maxi = guess - 1
break
elif feedback == 'c':
mini = guess + 1
break
else:
print ("Sorry, I didn't get that. Please type either a, b, or c?")
print ("Aw shucks. I ran out of guesses.\n")
return 10000
def playAgain():
while True:
again = input("Would you like to keep playing? [y/n] ")
if again == "n":
return False
elif again == "y":
return True
else:
print("Please respond with 'y' or 'n' only.")
def main():
print("\nWelcome to my number guessing game!")
name = input("What's your name? ")
param = setParameters()
userBest = 10000
computerBest = 10000
while True:
score = round(name, param[0], param[1], param[2])
if score < userBest:
userBest = score
if userBest != 10000:
print(f"\nYour best score is {userBest}.")
score = computerTurn(param[0], param[1], param[2])
if score < computerBest:
computerBest = score
if computerBest != 10000:
print(f"\nMy best score is {computerBest}.")
if not playAgain():
print("Goodbye!\n")
return
main()
|
b5317d17aae9f6322773736897fcffd4c17695c0
|
Unst1k/GeekBrains-PythonCourse
|
/DZ4/DZ4-4.py
| 838
| 4.09375
| 4
|
# Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования
# в исходном списке. Для выполнения задания обязательно использовать генератор.
from random import randint
numbers = [randint(1, 10) for i in range(1, 16)]
print(f'\nСписок случайных чисел с повторами от 1 до 15: {numbers}')
result_numbers = [i for i in numbers if numbers.count(i) == 1]
print(f'\nСписок чисел, у которых не было повторов: {result_numbers}')
|
4de32a5c4d1e84ae597dfe51d2e5f8f55f37f5ea
|
Dmdv/CS101
|
/Unit6/fibonacci.py
| 211
| 3.921875
| 4
|
__author__ = 'dmitrijdackov'
dic = {0:0, 1:1}
def fibonacci(n):
if n in dic:
return dic[n]
value = fibonacci(n - 1) + fibonacci(n-2)
dic[n] = value
return value
print (fibonacci(36))
|
28810b100bf3be3f5f20a587a8457ded1a7036a4
|
sharonsabu/pythondjango2021
|
/file/file_read.py
| 312
| 3.671875
| 4
|
f=open("demo","r")
lst=[]
#to print all in demo
for lines in f:
print(lines)
#to append into list
lst.append(lines.rstrip("\n")) #rstrip is used to remove \n from right side of output and if \n is in left side lstrip is used
print(lst)
#to avoid duplicates (convert into set)
st=set(lst)
print(st)
|
5ac2c0302065ce8f55e3728d186a109eab658e96
|
matusino221/AdventofCode_2020
|
/day5.py
| 3,999
| 3.921875
| 4
|
import math
import re
import sys
def read_file(filename):
try:
with open(filename) as f:
content = f.readlines()
# I converted the file data to integers because I know
# that the input data is made up of numbers greater than 0
content = [info.strip() for info in content]
except:
print('Error to read file')
sys.exit()
return content
def is_valid(content):
result = True
try:
# byr (Birth Year) - four digits; at least 1920 and at most 2002.
byr = re.search("[0-9]{4}", content['byr'])
# if (int(byr.group()) < 1920) or (int(byr.group()) > 2002):
if not 1920 <= int(byr.group()) <= 2002:
result = False
# iyr (Issue Year) - four digits; at least 2010 and at most 2020.
iyr = re.search("[0-9]{4}", content['iyr'])
# if (int(iyr.group()) < 2010) or (int(iyr.group()) > 2020):
if not 2010 <= int(iyr.group()) <= 2020:
result = False
# eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
eyr = re.search("[0-9]{4}", content['eyr'])
# if (int(eyr.group()) < 2020) or (int(eyr.group()) > 2030):
if not 2020 <= int(eyr.group()) <= 2030:
result = False
# hgt (Height) - a number followed by either cm or in:
hgt = re.search("^[0-9]+(cm|in)$", content['hgt'])
# If cm, the number must be at least 150 and at most 193.
if hgt:
if "cm" in hgt.group():
hgt_ = hgt.group()[:-2]
# if (int(hgt_) <= 150) or (int(hgt_) >= 193):
if not 150 <= int(hgt_) <= 193:
result = False
# If in, the number must be at least 59 and at most 76.
if "in" in hgt.group():
hgt_ = hgt.group()[:-2]
# if (int(hgt_) <= 59) or (int(hgt_) >= 76):
if not 59 <= int(hgt_) <= 76:
result = False
else:
result = False
# hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
hcl = re.search("^#([a-f]|[0-9]){6}$", content['hcl'])
if not hcl:
result = False
# ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
ecl = re.search("(amb)|(blu)|(brn)|(gry)|(grn)|(hzl)|(oth)", content['ecl'])
if not ecl:
result = False
# pid (Passport ID) - a nine-digit number, including leading zeroes.
pid = re.search("^[0-9]{9}$", content['pid'])
if not pid:
result = False
# cid (Country ID) - ignored, missing or not.
# ignored
except:
result = False
return result
if __name__ == "__main__":
input_data = read_file("day5input.txt")
# F means "front"
# B means "back"
# L means "left"
# R means "right"
print("-----------------------------PART1-----------------------------------")
# first letter indicates whether the seat is in the front (0 through 63) or the back (64 through 127)
boarding_pass = []
for seat in input_data:
row = [0, 127]
column = [0, 7]
for char in seat:
if char == 'F':
row[1] = row[0] + ((row[1] - row[0]) // 2)
if char == "B":
row[0] = row[1] - ((row[1] - row[0]) // 2)
if char == 'R':
column[0] = column[1] - ((column[1] - column[0]) // 2)
if char == 'L':
column[1] = column[0] + ((column[1] - column[0]) // 2)
seat_id = row[0] * 8 + column[0]
boarding_pass.append(seat_id)
print(max(boarding_pass))
print("-----------------------------PART2-----------------------------------")
free_seats = list(range(0, 128 * 8 - 1))
[free_seats.remove(seat) for seat in boarding_pass]
[print(free_seat) for free_seat in free_seats if
not free_seat - 1 in free_seats and not free_seat + 1 in free_seats]
|
72251039560f19ab0a3ab2f7bfb52f8c18fe399f
|
Paupau18me/EjerciciosPatitoPython2021
|
/Sesion intrductoria/p2130.py
| 323
| 3.546875
| 4
|
cad = input()
cad_aux = cad.split()
vowels = ['a', 'e', 'i', 'o', 'u']
vow = ''
cons = ''
for i in range(len(cad_aux)):
if cad_aux[i][0] in vowels:
vow = vow + cad_aux[i]+ ' '
else:
cons = cons + cad_aux[i]+ ' '
print(vow[:-1])
print(cons[:-1])
print(cad)
print('Espacios en blanco:',len(cad_aux)-1)
|
96b199caae8336c5aa38c52fa0aac87e55d5d067
|
Sanjeev589/HackerRank
|
/Python/Lists.py
| 1,152
| 4.53125
| 5
|
'''
Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the list.
7. reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above.
Iterate through each command in order and perform the corresponding operation on your list.
'''
if __name__ == '__main__':
N = int(input())
li=[]
for i in range(0,N):
fun=input()
fun_s=fun.split()
if fun_s[0]=="insert":
li.insert(int(fun_s[1]),int(fun_s[2]))
elif fun_s[0]=="print":
print(li)
elif fun_s[0]=="remove":
li.remove(int(fun_s[1]))
elif fun_s[0]=="append":
li.append(int(fun_s[1]))
elif fun_s[0]=="sort":
li.sort()
elif fun_s[0]=="pop":
li.pop()
elif fun_s[0]=="reverse":
li.reverse()
|
bd3e5e0ed17443bbd5d2f22792a9f5df9e5d7982
|
raga22/etl-airflow
|
/init_db.py
| 1,139
| 3.546875
| 4
|
import sqlite3
from sqlite3 import Error
#Constant DB
DBDISASTER = r"/home/pratama/project/week1/dags/db/disaster.db"
#Constant table
TBLDISASTER = """ CREATE TABLE IF NOT EXISTS disaster (
id integer NOT NULL PRIMARY KEY,
keyword text NULL,
location text NULL,
text text NULL,
target int
); """
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
finally:
print("success create table")
conn.close()
# create a database connection
conn = create_connection(DBDISASTER)
# create tables
if conn is not None:
# disaster
create_table(conn, TBLDISASTER)
else:
print("Error! cannot create the database connection.")
|
2be4dbd5b2fe600562951a01fed971fcaa280611
|
UAECETian/SelfLearning
|
/LC4 Median of Two Arrays/main.py
| 426
| 3.84375
| 4
|
from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums3 = sorted(nums1 + nums2)
if len(nums3) % 2 != 0:
return nums3[len(nums3) // 2]
else:
return (nums3[len(nums3) // 2] + nums3[len(nums3) // 2 - 1]) / 2
temp = Solution()
list = temp.findMedianSortedArrays([1,2,3,4,4,4],[4,5,6,7])
print(list)
|
30d865d647eaba0056c8a534c768639480f22c77
|
ggsant/pyladies
|
/iniciante/Mundo 03/Anotações das Aulas e Desafios/Aula 03 - 18/Código 05 - Variáveis Compostas (Listas - Parte 2).py
| 1,526
| 4.125
| 4
|
galera = list() # Cria uma nova lista vazia "galera"
dado = list() # Cria uma nova lista vazia "dado"
totmai = totmen = 0 # Cria duas variáveis simples "totmai" e "totmen" com valor 0
for c in range(0, 3): # Cria um laço "for" que será executado 3 vezes (números de 0 a 2)
dado.append(str(input('Nome: '))) # Adiciona a string digitada ao final da lista "dado"
dado.append(int(input('Idade: '))) # Adiciona o número inteiro digitado ao final da lista "dado"
galera.append(dado[:]) # Adiciona uma cópia da lista "dado" atual ao final da lista composta "galera"
""" NOTA: Lembrar sempre de usar "lista[:]" ao invés de "lista[]" para fazer uma cópia da lista em questão. """
dado.clear() # Esvazia a lista "dado"
print(galera) # Exibe todos os itens digitados no laço "for" anterior, guardados na lista composta "galera"
for pessoa in galera: # Para cada "pessoa" na lista composta "galera"...
if pessoa[1] >= 21: # Se o índice [1] (idade) atual for maior ou igual a 21...
print(f'{pessoa[0]} é maior de idade.') # Exibe que o índice [0] (nome) da "pessoa" atual é maior de idade
totmai += 1 # Acrescenta 1 à variável simples "totmai"
else: # Senão...
print(f'{pessoa[0]} é menor de idade.') # Exibe que o índice [0] (nome) da "pessoa" atual é menor de idade
totmen += 1 # Acrescente 1 à variável simples "totmen"
print(f'Temos {totmai} maiores e {totmen} menores de idade.') # Exibe os números finais de "totmai" e "totmen"
|
b0ba63c6016e748fc61eb12bf1d2ed3efe9546c9
|
ozkanparlakkilic/PythonExercises
|
/IleriSeviyeModuller/dövizHesaplama.py
| 993
| 3.609375
| 4
|
import requests
import sys
from bs4 import BeautifulSoup
url = "https://www.doviz.com/"
response = requests.get(url)
html_icerigi = response.content
soup = BeautifulSoup(html_icerigi,"html.parser")
values = soup.findAll("span",{"class":"value"})
kullanici_para_miktari = float(input("Paranızı giriniz : "))
if kullanici_para_miktari < 0:
sys.stderr.write("Geçerli bir miktar giriniz !!!")
sys.stderr.flush()
sys.exit()
gram_altin = values[0].text
dolar = values[1].text
euro = values[2].text
gram_altin = gram_altin.replace(",",".")
dolar = dolar.replace(",",".")
euro = euro.replace(",",".")
print("Gram altının fiyatı : {}".format(gram_altin))
print("Doların Ederi : {}".format(dolar))
print("Euronun Ederi : {}".format(euro))
print("************************************")
print("Paranızın dolar karşılığı : {}".format(kullanici_para_miktari / float(dolar)))
print("Paranızın euro karşılığı : {}".format(kullanici_para_miktari / float(euro)))
|
f646c6c0dec112ccf6ee17f8162916f4731f8025
|
RahulAnand-raone/Acadview-Python
|
/day4.py
| 2,219
| 4
| 4
|
l=[1,2,3,4,5]
l.append(6) #to insert 1 value in list
l.extend([7,8,9]) #add list in list
l+[10,11,12] # add list
l.insert(0,0) #add element from oth index
l.pop() #del last element from the list
l.pop(1) #delete 1st index from the list
l.clear #to empty the list
l.sort(reverse=True) #sort in reverse order
l[-1::-1] #to sort in reverse
a=[1,2,3]
b=a #copy element
b==a #check if true or not
c=b.copy #copy element of b ,in case of change in b, c will not change
b[1]=3 #change the element in b
print a #it will also be changed when you changes b
d=c.copy()
d==c #
d is c #
#code to print square of elements
a=[0,1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
a[i]=i*i
print(a[i])
print([i**2 for i in range(10)]) #to print square of elements in range 0-10
#conditions for if elif and else statement
a=10
if a>10:
print("if block")
elif a==10:
print("elif block")
else:
print("else block")
#output= elif block
#code to input student marks nd categorige his grade acoording to marks
l=[]
for i in range(int(input("How many students data do you want to enter:\n"))):
a=input("Enter name:\n")
b=int(input("Enter marks:\n"))
grade=''
if b>=81 and b<=100:
grade="A+"
elif b>=70 and b<=80:
grade=-"A"
else
grade="R"
l.append([a,grade])
print(l)
#to print ascii value
#ord("a")
#chr(97)
#code to change to ascii value
a='abcdefghijklmnopqrstuvwxyz'
l=list(a)
for i in l:
print(ord(i))
#2nd method
import string
for i in string.ascii_lowercase:
print(ord(i))
#code to print in order of ([1,'a'],[1,'b'],[1,'c'],......)
[print([i,j]) for i in [1,2,3,4,5] for j in ['a','b','c']]
#code to print even no. in given range
l=[x for x in range(0,20) if x%2==0]
print(l)
#
dict_comp={x:chr(65+x) for x in range(1,11)}
print(dict_comp)
#
set_comp={x**3 for x in range(10) if x%2==0}
print(set_comp)
#has attribute
hasattr(str,'__iter__') #True
hasattr(str,'__iter') #False
#generator expression
from sys import getsizeof
my_comp=[x*5 for x in range(1000)]
my_gen=[x*5 for x in range(1000)]
print(getsizeof(my_comp))
print(getsizeof(my_gen))
#to sort duplicate element nd calculate length nd show output as[0,len(l)]
#for hw
|
01fdf47c6c58c51a197ccbb4e6206b04c82b610e
|
erenkulaksiz/changeString
|
/changestr.py
| 1,729
| 3.78125
| 4
|
# Mode 0 : word mode
# Mode 1 : i cant name this mode but it changes wOrDs LiKe ThIs
# Mode 2 : setup
mode = 1
# Word for mode 0
word = "bruh"
def reverse(args):
return not args
def main():
if mode == 0:
#since python does not have switch case, i should use if else statement
print("Starting mode",mode)
rf = open("readfile.txt", "r+")
wf = open("writefile.txt", "w+")
rfstr = str(rf.read())
endstr = ''
wordsayar = 0
a = ''
for i in rfstr:
if ' ' in i:
endstr += ' '
elif '\n' in i:
endstr += '\n'
else:
wordsayar += 1
if str(wordsayar) in a:
wordsayar = 0
a = ''
a = ''.join(str(wordsayar))
if wordsayar == 1:
endstr += word
wf.write(endstr)
print(endstr)
print("Success")
elif mode == 1:
print("Starting mode",mode)
rf = open("readfile.txt", "r+")
wf = open("writefile.txt", "w+")
rfstr = str(rf.read())
endstr = ''
isputletter = False
for i in rfstr:
if ' ' in i:
endstr += ' '
else:
isputletter = reverse(isputletter)
if isputletter:
endstr += i.lower()
else:
endstr += i.upper()
wf.write(endstr)
print(endstr)
print("Success")
elif mode == 2:
print("Setup")
rf = open("readfile.txt", "r+")
wf = open("writefile.txt", "w+")
else:
print("Invalid mode")
sys.exit()
if __name__ == "__main__":
main()
|
1c0c27da1a5ffd2ada1e238f96d4179c01990331
|
RuzimovJavlonbek/anvar.nazrullayevning-mohirdev.uz-platformasidagi-dasturlash.asoslari.python-kursidagi-amaliyotlar
|
/sariq_dev/darslar/10_dars_uy_ishi_5_.py
| 96
| 3.765625
| 4
|
a = float(input("a="))
if a < 0:
print(" Manfiy son")
else:
print(" Musbat son")
input()
|
1478d70c3b3b288e70abce6700e7ebfe587976dd
|
fadim21-meet/meetyl1
|
/meetinturtle.py
| 1,125
| 4.28125
| 4
|
import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
#draw the M
turtle.goto (-200,-100+200)
turtle.goto (-200+50,-100)
turtle.goto (-200+100,-100+200)
turtle.goto (-200+100,-100)
turtle.penup()
#draw the E
turtle.forward (100)
turtle.pendown ()
turtle.goto (0,100)
turtle.goto (100,100)
turtle.goto (0,100)
turtle.goto (0,0)
turtle.goto (100,0)
turtle.goto (0,0)
turtle.goto (0,-100)
turtle.goto (100,-100)
turtle.penup()
#draw the E
turtle.forward (50)
turtle.pendown ()
turtle.goto (150,100)
turtle.goto (250,100)
turtle.goto (150,100)
turtle.goto (150,0)
turtle.goto (250,0)
turtle.goto (150,0)
turtle.goto (150,-100)
turtle.goto (250,-100)
turtle.penup()
#draw the T
turtle.forward (150)
turtlr.pendown ()
turtle.goto (250,100)
turtle
# ...and end it before the next line.
turtle.mainloop()
# turtle.mainloop() tells the turtle to do all
# the turtle commands above it and paint it on the screen.
# It always has to be the last line of code!
|
f4f47a9aff66dbee2b675bdeff9023267403460a
|
GunjanAS/Partial-Sensing
|
/agent1.py
| 12,067
| 3.6875
| 4
|
import pandas as pd
import numpy as np
from math import sqrt
import heapq
from matplotlib import pyplot
from copy import deepcopy
def create_grid(p, dim):
'''
:param p: probability with which a node is blocked
:param dim: dimension of the matrix
:return: a 2d list denoting grid where 1 = traversable node, 0 = non traversable
This function generates a random grid by taking into account probability 'p' and dimension 'dim'
'''
## initialise a grid with all 0. 0 = cell blocked, 1 = cell unblocked
grid = [[0 for i in range(dim)] for j in range(dim)]
## Loop over inputted dimension
for i in range(dim):
for j in range(dim):
actual_prob = np.random.random_sample() ## generating a random number
if actual_prob > p: ## if the generated random number > p, assign it 1 (meaning it is
grid[i][j] = 1 ## traversable.
else:
grid[i][j] = 0
grid[0][0] = 1 ## start node and end node is always traversable.
grid[dim - 1][dim - 1] = 1
return grid
def print_grid(grid):
for row in grid:
for e in row:
print(e, end=" ")
print()
# print_grid(create_grid(0.4, 5))
class Node:
'''
A node class that stores 5 things for a node - position, parent, g(n), h(n), f(n)
'''
def __init__(self, parent=None, position=None):
'''
This function initalises a node by setting parent , position and heuristic values as 0
:param parent: parent of the current code
:param position: position of the current code
'''
self.parent = parent
self.position = position
self.g = 0
self.f = 0
self.h = 0
def __eq__(self, node):
'''
This function is overload for == operator in python. It is used to compare if two nodes are equal.
:param node: node to compare with
:return: 1 if two self and node is equal, otherwise 0
'''
if (self.position[0] == node.position[0] and self.position[1] == node.position[1]) :
return True
else:
return False
def __lt__(self, other):
'''
This function is overload for < operator in python. It is used to compare if one node is less than other.
:param other: node to compare with
:return: 1 if self's f value is less than other's f value, otherwise 0
'''
return self.f < other.f
def generate_children(grid, knowledge_grid, fringe, visited_list, current, all_moves, end_node,is_gridknown):
'''
This function uses a grid (be it grid or knowledge) and generates all valid children of the current node.
:param grid: the original actual grid
:param knowledge_grid: the knowledge grid
:param fringe: list of nodes in the priority queue
:param visited_list: a dictionary of nodes already visited
:param current: current node in the queue
:param all_moves: array of all valid moves
:param end_node: end position/node in the grid
:param is_gridknown: parameter to switch between grid and knowledge grid
:return: array of relevant children
'''
current_x, current_y = current.position
relevant_children = []
dim = len(grid)
for a_move in all_moves: ## looping over all valid moves
child_x = current_x + a_move[0]
child_y = current_y + a_move[1]
if child_x > dim-1 or child_x < 0 or child_y > dim-1 or child_y < 0: ## condition to check if node is in within
## boundaries of the grid
continue
children_node = Node(current, (child_x, child_y)) ## initalising children node with current
## as parent and child_x, child_y as position
if(is_gridknown=="No"): ## isgridknown checks whether to we have grid
## loaded in the memory, if not we use knowledge
## grid
grid_for_pathcalculation = knowledge_grid
else:
grid_for_pathcalculation = grid
if (grid_for_pathcalculation[child_x][child_y] != 0) and (visited_list.get(children_node.position) != "Added" ): ## condition to check is current node
## is not blocked and current node is
## not in visited list
children_node.g = current.g + 1 ## assigining current g = g(parent) + 1
children_node.h = abs(children_node.position[0] - end_node.position[0]) + abs( ## using manhattan distance as our heuristic
children_node.position[1] - end_node.position[1])
children_node.f = children_node.g + children_node.h ## f(n) = g(n) + f(n)
relevant_children.append(children_node)
return relevant_children
def search(grid, fringe,knowledge_grid, start_position, end_position,is_gridknown):
'''
:param grid: the original actual grid
:param fringe: list of all processed nodes
:param knowledge_grid: the knowledge grid
:param start_position: start position in grid
:param end_position: end position in grid
:param is_gridknown: parameter to switch between grid and knowledge grid
:return: the path from start node to end node
'''
startNode = Node(None, start_position)
endNode = Node(None, end_position)
fringe=[]
visited_nodes = {}
already_fringed = {} ## a hashmap to keep track of fringed nodes and its lowest cost
already_fringed[startNode.position] = startNode.f
heapq.heappush(fringe,(startNode.f,startNode)) ## pushing start node in fringe
all_moves = [[1, 0], ## defined all moves -
[0, 1], ##[1,0] - move right
[-1, 0], ## [0,1] - move down
[0, -1]] ## [0,-1] - move up
## [-1,0] - move left
path = []
while fringe: ## while fringe is not empty
current = heapq.heappop(fringe) ## popping node from fringe
current=current[1]
visited_nodes[current.position]="Added" ## assigning current node to visited
if current.position== endNode.position:
i = current
while(i is not None): ## traversing path if current=goal to get the path from start to goal
path.append(i.position)
i = i.parent
return "Solvable", path
children = generate_children( ## otherwise generate children
grid, knowledge_grid, fringe, visited_nodes, current, all_moves, endNode,is_gridknown)
if children:
for node in children:
if node.position in already_fringed: ## checking if the children is already fringed,
if already_fringed[node.position] > node.f: ## if yes update and push the moinimum cost one
already_fringed[node.position] = node.f ## otherwise ignore the child
heapq.heappush(fringe, (node.f, node))
else:
heapq.heappush(fringe, (node.f, node)) ## if the child is not already fringed, push it
already_fringed[node.position] = node.f ## to priority queue and assign in the hashmap
return "Unsolvable", path
def main(dim,is_gridknown,density,grid):
'''
This function execuated repeated A* algorithm and uses above functions to do so.
:return: None
'''
fringe=[]
bumps=0
#grid = create_grid(density, dim) ## create a grid with entered density and dim values.
# assuming unblocked for all cells
knowledge_grid = [[1 for _ in range(dim)] for _ in range(dim)] ## intialise knowledge grid to all 1's
im = None
# print_grid(grid)
start = (0, 0)
end = (dim-1, dim-1)
all_moves = [[1, 0],
[0, 1],
[-1, 0],
[0, -1]]
for a_move in all_moves:
child_x = start[0] + a_move[0]
child_y = start[1] + a_move[1]
if (child_x > dim-1 or child_x < 0 or child_y > dim-1 or child_y < 0):
continue
else:
if(grid[child_x][child_y] == 0):
knowledge_grid[child_x][child_y] = 0 ## update the knowledge grid with field of view
ll, path = search(grid,fringe, knowledge_grid, start, end,is_gridknown)
final_path=[]
if(ll!="Unsolvable" and is_gridknown=="No"):
while(len(path) > 1 and ll!="Unsolvable"):
count=0
flag=0
# traverse the path obtained from search function to see if blocked cell exists or not.
# If blocked cell exists, run search function again to calculate the path
# Continue in this while loop -1) either path returned is 0 that means nothing left in fringe and no path to reach goal 2) or path exists to reach goal
for i in path[::-1]:
count+=1
for a_move in all_moves:
child_x = i[0] + a_move[0]
child_y = i[1] + a_move[1]
if (child_x > dim-1 or child_x < 0 or child_y > dim-1 or child_y < 0):
continue
else:
if(grid[child_x][child_y] == 0):
knowledge_grid[child_x][child_y] = 0
elif(grid[child_x][child_y] == 1):
knowledge_grid[child_x][child_y] = 2
final_path.append((i[0],i[1]))
if(grid[i[0]][i[1]] == 0): # blocked in grid
bumps+=1
final_path.pop()
knowledge_grid[i[0]][i[1]] = 0 # updating knowledge_grid
new_start_position = path[path.index(i)+1][0], path[path.index(i)+1][1]
ll, path = search(grid, fringe, knowledge_grid,
new_start_position, end, is_gridknown)
finalresult=ll
break
if(count==len(path)):
print("Solved")
flag=1
# print("final_path",final_path)
break
if(flag==1):
return final_path, knowledge_grid,bumps
break
if(ll=="Unsolvable"):
print("Unsolvable")
return [],knowledge_grid,bumps
if(flag!=1):
# print("finalresult",finalresult)
return [],knowledge_grid,bumps
elif(is_gridknown=="Yes"):
print(ll)
print("path",path)
else:
print("Unsolvable")
return [],knowledge_grid,bumps
# for (i, j) in final_path:
# grid[i][j] = 2
# pyplot.figure(figsize=(dim, dim))
# pyplot.imshow(grid)
# pyplot.grid()
# pyplot.xticks(size=14, color="red")
# pyplot.show()
|
43d540f0d64460c41d97defb78367518db407215
|
mwesthelle/artificial-neural-network
|
/artificial_neural_network/base_model.py
| 392
| 3.5625
| 4
|
from abc import ABC, abstractmethod
from typing import Iterable, List
class BaseModel(ABC):
@abstractmethod
def fit(self, data_iter: Iterable[List[str]], labels: List[str]):
"""
Train model using data_iter
"""
@abstractmethod
def predict(self, test_data: Iterable[List[str]]):
"""
Return predictions given some test_data
"""
|
065dd388ddd934d8eb982dfe4ef34653bc18add7
|
Beelthazad/PythonExercises
|
/EjerciciosBasicos/ejercicio4.py
| 834
| 4.03125
| 4
|
def esPar(numero):
if numero%2 != 0:
return bool(0)
else:
return bool(1)
def esMultiplo(num1, num2):
num3 = num1/num2
if float(num3).is_integer() == bool(1):
print(num1,"es múltiplo de", num2)
else:
print(num1,"no es múltiplo de", num2)
num = int(input("Introduce un numero a comprobar... el resultado es un booleano :p\n"))
print(esPar(num))
res = int(input("Introduce el primer número\n"))
res2 = int(input("Introduce el segundo número\n"))
esMultiplo(res, res2)
# Sean a y b dos números enteros tales que a != 0. Diremos que "a" divide a "b" o "a" es divisor de "b" si
# existe un número entero q tal que b = a * q.
# Por tanto...
# a divide a b ⇐⇒ b = aq; q ∈Z⇐⇒ b es múltiplo de a
# Podemos, a partir de nuestra premisa, deducir que si b/a = q y q es un número entero.
|
f62ee904e1d813890815d0c9aed20c29b86fd2cb
|
jordanyoumbi/Python
|
/liste/items.py
| 525
| 4
| 4
|
# methode Items permet d' acceder au clé et valeur d' un dictionnaire plus facilement
#cet Exemple va nous permettre d' afficher la clé et la valeur des elements dans un dictionnaire
# Pour cela ontilisaera une boucle pour
fruits = {
"banane":9,
"orange":15,
"kiwi":4
}
# nous venon de definir le dictionnaire et maintenant nous allons exploiter les clés (fruit) et valeur (number) des elements de ce dictionaire à l' aide de items()
for fruit, number in fruits.items():
print(fruit)
print(number)
|
6e8a20e8e262cdb063fea8e15fbf55904d3b069f
|
harishsakamuri/python-files
|
/basic python/looping1.py
| 145
| 3.78125
| 4
|
a=input()
for i in a:
if i == "b":
print(a.index(i))
for i in range(0,len(a)):
if a[i] == "b":
print(i)
|
d91e7a23a32b01bf17a7611b933e051ec41ea539
|
rafaelperazzo/programacao-web
|
/moodledata/vpl_data/5/usersdata/67/2926/submittedfiles/atm.py
| 187
| 3.59375
| 4
|
# -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
a=input("Digite o valor:")
c20=a/20
c10=a%20/10
b=int(c20)
c=int(c10)
print(b)
print(c)
|
95a6d6cc14cf4ccc8034b48c2b0febd831ba9f6e
|
Minta-Ra/CS50x_2021
|
/Pset_6/MarioMore/mario.py
| 605
| 4.15625
| 4
|
while True:
while True:
try:
# Get height from the user
height = int(input("Height: "))
break
# If I get ValueError
except ValueError:
# Ask again for an input - continue returns the control to the beginning of the while loop
continue
if height > 0 and height < 9:
for i in range(height):
# Print left pyramid
print(" " * (height - i - 1) + "#" * (i + 1), end=" ")
# Print right pyramid
print("#" * (i + 1))
# Break while statement
break
|
5c40f1b8d3a0938c3da996a64b7e5c93c8cb0d29
|
vishnurapps/MachineLearningEndavour
|
/02_simple_linear_regression/Simple_Linear_Regression.py
| 1,753
| 3.90625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 5 22:31:06 2018
@author: vishnu
"""
"""
Simple linear regression deals with equations of the form y = b0 + b1x, where b0 is the y intercept
and b1 is the slope of the line. Here y is the dependent variable and x is the independent variable
The best fit line is calculated using the Ordinary Least Squares. Best fit line is the line having the
smallest Ordinary Least Squares.
"""
#Importing Libraries that are required for preprocessing
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#Splitting the dataset into training set and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#Fitting simple linear regression to training set
from sklearn.linear_model import LinearRegression
#Here the simple linear regression model learns our data. The machine name is regressor, which is of type Simple Linear Regression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#Predecting the test results
y_pred = regressor.predict(X_test)
#Visualising the training set data
plt.scatter(X_train, y_train, color = "red")
plt.plot(X_train, regressor.predict(X_train), color = "blue")
plt.title("Salary vs Experience (Train data)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
#Visualising the test set data
plt.scatter(X_test, y_test, color = "red")
plt.plot(X_train, regressor.predict(X_train), color = "blue")
plt.title("Salary vs Experience (Test data)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
|
e9e52647125379c5bd0ecf1d8ffd87b8c8dbf46b
|
orengoa0459/CSC-121
|
/CSC-121-Python/Module2/OrengoAnthony_M2Lab/OrengoAnthony_game_functions.py
| 8,911
| 4.59375
| 5
|
import random
# This program is a version of the "Rock", "Paper", "Scissors" game, using the python
#console. The user will have the option to play a 1, 2, or 3 round game. The winner will
#be display to the user upon completion of the game.
# Date 05/31/2021
# CSC121- M2Lab Code Modularizing
# Anthony Orengo
#Pseudocode
#1. Import Random class.
#2. Declare and initialize global constants/function variables to track score, round number, and result.
#3. Define functions mainMenu, displayInvalidMessage, gameOne, two, and three,rockPaperScissors, and choiceStrings
#4. The mainMenu function will contain a layout of the main menu using the print function.
#5. The displayInvalidOption function will return the string .
#6. Define functions rockPaperScissors, and choiceStrings. ChoiceString will require a parameter to be passed (computers choice/players choice)
#The choice number will determine what option was chose(Ex: if player chooses 1 and 1 represents rock, "rock" will be returned from choiceString function)
#The rockPaperScissors function will determine the result of who won the round. This function will consist of two parameters (computer, player) and will
#Determine if the cpu or player won or if they tied. Nested loops will be required to accomplish this by eliminating possiblities.
#7: Depending on the game, the round will continue until either player reaches the desired score. The "score tracker" variables will need to be
#incremented along with the "roundNum" variable
#8: The winner/loser will be displayed to the user upon completion of the round(s).
# Global constants
COMPUTER_WINS = 1
PLAYER_WINS = 2
TIE = 0
INVALID = 3
ROCK = 1
PAPER = 2
SCISSORS = 3
#Display Menu Options----------------------------------------------------
def mainMenu():
print(
"***********************\n"+
"Rock, Paper, Scissors \n"+
"***********************\n"+
"1. 1 Round\n" +
"2. 2 Rounds\n"+
"3. 3 Rounds\n"+
"4. Exit\n"+
"***********************")
#END Display Menu Options-------------------------------------------------
#Display Invalid Option----------------------------------------------------
def displayMessageInvalid():
return "Invalid option! Try Again!"
#END Invalid Menu Option-------------------------------------------------
#gameOne------------------------------------------------------------------
def gameOne():
result = TIE
while result==TIE:
# Get computer number
computer = random.randint(1, 3)
# Get player number
player = input('Enter:\n'
'1 for rock\n' \
'2 for paper\n'
'3 for scissors --> ')
#Determine if input is a digit
if player.isdigit():
player = int(player)
#Diplay choices to user
print ('Computer chose:', choiceString(computer))
print ('You chose:', choiceString(player))
#Determine the winner of the round
result = rockPaperScissors(computer, player)
if result == TIE:
print('\nYou made the same choice as ' \
'the computer. Starting over')
if (result == COMPUTER_WINS):
print ('\nThe computer wins the game')
elif result == PLAYER_WINS:
print ('\nYou win the game')
else:
print ('\nYou made an invalid choice. No winner')
else:
print("Invalid Option!Try Again!")
#End gameOne------------------------------------------------------------------
#gameTwo------------------------------------------------------------------
def gameTwo():
#Declare and initialize variables to tracke score,round number, and result
cpuScore = 0
playerScore = 0
result = TIE
roundNum = 1
#While loop is used to run as many rounds as needed until either opponent wins.
while cpuScore < 2 and playerScore < 2:
# Get computer number
computer = random.randint(1, 3)
print("Round: ", roundNum)
# Get player number
player = input('Enter:\n'
'1 for rock\n' \
'2 for paper\n'
'3 for scissors --> ')
#Determine if input is a digit
if player.isdigit():
player = int(player)
print ('Computer chose:', choiceString(computer))
print ('You chose:', choiceString(player))
result = rockPaperScissors(computer, player)
if result == TIE:
print('\nYou made the same choice as ' \
'the computer. Starting over')
if (result == COMPUTER_WINS):
print ('\nThe computer wins round: ' , roundNum)
cpuScore += 1
roundNum +=1
elif result == PLAYER_WINS:
print ('\nYou won round: ' , roundNum)
playerScore += 1
roundNum +=1
else:
print ('\nYou made an invalid choice. No winner')
# Determine final winner
if playerScore >= 2 or cpuScore >= 2:
if playerScore > cpuScore:
print("You won the game! Great Job!")
else:
print("You Lost! The computer wins!")
else:
print("Invalid Option!Try Again!")
#End gameTwo------------------------------------------------------------------
#gameThree------------------------------------------------------------------
def gameThree():
#Declare and initialize variables to tracke score,round number, and result
cpuScore = 0
playerScore = 0
result = TIE
roundNum = 1
#While loop is used to run as many rounds as needed until either opponent wins.
while cpuScore < 3 and playerScore < 3:
# Get computer number
computer = random.randint(1, 3)
# Get player number
player = input('Enter:\n'
'1 for rock\n' \
'2 for paper\n'
'3 for scissors --> ')
if player.isdigit():
player = int(player)
print ('Computer chose:', choiceString(computer))
print ('You chose:', choiceString(player))
result = rockPaperScissors(computer, player)
if result == TIE:
print('\nYou made the same choice as ' \
'the computer. Starting over')
if (result == COMPUTER_WINS):
print ('\nThe computer wins round: ' , roundNum)
cpuScore += 1
roundNum +=1
elif result == PLAYER_WINS:
print ('\nYou won round: ' , roundNum)
playerScore += 1
roundNum +=1
else:
print ('\nYou made an invalid choice. No winner')
# Determine final winner
if playerScore >= 3 or cpuScore >= 3:
if playerScore > cpuScore:
print("You won the game! Great Job!")
else:
print("You Lost! The computer wins!")
else:
print("Invalid Option!Try Again!")
#End gameThree------------------------------------------------------------------
def rockPaperScissors(computer, player):
if(computer == player):
return TIE
if computer == ROCK:
if player == PAPER:
return PLAYER_WINS
elif player == SCISSORS:
return COMPUTER_WINS
else:
return INVALID
elif computer == PAPER:
if player == ROCK:
return COMPUTER_WINS
elif player == SCISSORS:
return PLAYER_WINS
else:
return INVALID
else: #computer chose scissors
if player == ROCK:
return PLAYER_WINS
elif player == PAPER:
return COMPUTER_WINS
else:
return INVALID
# The choiceString function displays a choice in string format
def choiceString(choice):
if choice == ROCK:
return 'rock'
elif choice == PAPER:
return 'paper'
elif choice == SCISSORS:
return 'scissors'
else:
return 'something went wrong'
if __name__ == "__main__":
main()
|
dc8989b59adada18c1aa31bcfad34c5f6d6e3915
|
apetri/GoogleJam
|
/src/fileFixIt/fileFixIt.py
| 1,222
| 3.796875
| 4
|
#!/usr/bin/env python
import sys
class DirectoryTree(object):
def __init__(self):
self.root = dict()
#Add a directory to the path
def mkdir(self,path):
#Split path into single directories
directories = path.split("/")[1:]
#Initial step
node = self.root
nof_mkdir = 0
#Cycle over directories
for d in directories:
if not (d in node):
#Create a directory
node[d] = dict()
nof_mkdir += 1
#Walk on the next node
node = node[d]
#Return the number of mkdir to the user
return nof_mkdir
#####################
#########Main########
#####################
line = lambda : sys.stdin.readline().strip("\n")
def main():
#Number of test cases
ntest = int(line())
#Cycle over test cases
for t in range(ntest):
#Read N,M
n,m = [int(c) for c in line().split(" ")]
#Add the N directories to the directory tree data structure
tree = DirectoryTree()
for i in range(n):
path = line()
tree.mkdir(path)
#Create the M directories, keeping track of the number of mkdir commands
nof_mkdir = 0
for i in range(m):
path = line()
nof_mkdir += tree.mkdir(path)
sys.stdout.write("Case #{0}: {1}\n".format(t+1,nof_mkdir))
if __name__=="__main__":
main()
|
1bbcf31f6fd90fa73f6ec155eae6b4c41c6af593
|
skybohannon/python
|
/w3resource/string/49.py
| 351
| 3.8125
| 4
|
# 49. Write a Python program to count and display the vowels of a given text.
def count_vowels(s):
vowels = "aeiouAEIOU"
vcount = len([letter for letter in s if letter in vowels])
vlist = [letter for letter in s if letter in vowels]
print(vcount)
print(vlist)
count_vowels("The quick brown fox jumped over the lazy red doge.")
|
064c5360530bb50f17aaa8bc37f76e64d0f5009a
|
MasterKali06/Hackerrank
|
/Problems/medium/Implementation/extra_long_factorial.py
| 400
| 4.25
| 4
|
'''
Calculate and print the factorial of a given integer.
n! = n * n-1 * n-2 .... 3 * 2 * 1
'''
def extraLongFactorials(n):
len = n
final_res = 0
res = n
if n == 1 or n == 2:
res = n
else:
for i in range(len - 1):
next_op = n - 1
res = res * (next_op)
n -= 1
i += 1
print(res)
extraLongFactorials(3)
|
4bacb68250c5f1ff732a73415f2fc30877941daa
|
xiaoku521/xiaolaodi
|
/generate_fruit.py
| 397
| 3.5625
| 4
|
lst = [ 'apple', 'orange', 'banana' ]
num = 6 # 多少个水果
import random
s = ''
for i in range(num):
w = random.choice(lst) # 随机在lst中选一个元素
if i % 3 == 0: # 百分号%代表模
s += ' ' + w.upper()
if i % 3 == 1:
s += ' ' + w.title()
if i % 3 == 2:
s += ' ' + w
fruit = s.strip()
print(fruit)
|
ffce7103d3329c3dafcb7b7ad63c2a0b2d657e02
|
syurskyi/Python_Topics
|
/070_oop/008_metaprogramming/examples/Abstract Classes in Python/a_001.py
| 2,812
| 4.3125
| 4
|
# An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods
# hat must be created within any child classes built from your abstract class. A class which contains one or abstract
# methods is called an abstract class. An abstract method is a method that has declaration but not has
# any implementation. Abstract classes are not able to instantiated and it needs subclasses to provide implementations
# for those abstract methods which are defined in abstract classes. While we are designing large functional units
# we use an abstract class. When we want to provide a common implemented functionality for all implementations
# of a component, we use an abstract class. Abstract classes allow partially to implement classes when it completely
# implements all methods in a class, then it is called interface.
#
# Why use Abstract Base Classes :
# Abstract classes allow you to provide default functionality for the subclasses. Compared to interfaces abstract
# classes can have an implementation. By defining an abstract base class, you can define a common
# Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where
# a third-party is going to provide implementations, such as with plugins in an application, but can also help you
# when working on a large team or with a large code-base where keeping all classes in your head at the same time
# is difficult or not possible.
#
# How Abstract Base classes work :
# In python by default, it is not able to provide abstract classes, but python comes up with a module which provides
# the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by marking methods
# f the base class as abstract and then registering concrete classes as implementations of the abstract base.
# A method becomes an abstract by decorated it with a keyword @abstractmethod. For Example
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod
class Polygon(ABC):
# abstract method
def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 4 sides")
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
# I have 3 sides
# I have 4 sides
# I have 5 sides
# I have 6 sides
|
1bfa8a330385f87a9b8b6a6011962bb0f9ecea85
|
hsmwm/python_test
|
/list.py
| 1,090
| 3.796875
| 4
|
# #从'don't panic!'中获取'on tap'
# phrase="don't panic!"
# plist=list(phrase)#转换成list
# for i in range(4):#连续删除四次最后的单词
# plist.pop()
# #print(plist)#don't pa
# plist.pop(0)#删除第一位 on't pa
# plist.remove("'")#ont pa
# plist.extend(([plist.pop(),plist.pop()]))#追加两个先a再p 做到交换pa
# #print(plist)
# plist.insert(2,plist.pop(3))#再索引2的前边插入3
# new_phrase=''.join(plist)#转换成字符串
# print(plist)#打印老的列表
# print(new_phrase)#打印新的字符串
# #从'don't panic!'中获取'on tap'
phrase="don't panic!"
plist=list(phrase)#转换成list
for i in range(4):#连续删除四次最后的单词
plist.pop()
#print(plist)#don't pa
plist.pop(0)#删除第一位 on't pa
plist.remove("'")#ont pa
plist.extend(([plist.pop(),plist.pop()]))#追加两个先a再p 做到交换pa
#print(plist)
#plist.insert(2,plist.pop(3))#再索引2的前边插入3
plist.remove(' ')
plist.insert(2,' ')
new_phrase=''.join(plist)#转换成字符串
print(plist)#打印老的列表
print(new_phrase)#打印新的字符串
|
ac69169a9b04cecce544f813795e4e2546608c8f
|
RahulDV/Compiler
|
/fpj626_dantuluri/Block.py
| 921
| 3.59375
| 4
|
class Block:
def __init__(self, block_name=None):
self.block_name = block_name
self.instructions = []
self.next_blocks = []
self.visited = False
self.revisited = False
def get_block_name(self):
return self.block_name
def set_block_name(self, block_name):
self.block_name = block_name
def get_instructions(self):
return self.instructions
def add_instructions_to_list(self, instruction):
self.instructions.append(instruction)
def get_next_blocks(self):
return self.next_blocks
def add_next_block(self, block):
self.next_blocks.append(block)
def get_visited(self):
return self.visited
def set_visited(self, visited):
self.visited = visited
def get_revisited(self):
return self.revisited
def set_revisited(self, revisited):
self.revisited = revisited
|
45027e03744c66f33d68cdcbb2ca604d4b761c85
|
luomingmao/Python_Follish
|
/Others/continue.py
| 176
| 3.9375
| 4
|
#!/usr/bin/python
#File name: continue.py
while True:
s = input('Enter something:')
if s == 'quit':
break
if len(s) < 3:
continue
print('Input is ofsufficient length')
|
e4a2daf03e497405d6f3d970d6ad02ac0f633822
|
QuantumApostle/InterviewProblems
|
/leetcode/searchRange.py
| 1,323
| 3.671875
| 4
|
def searchRange(A, target):
if len(A) == 0:
print [-1, -1]
return
if len(A) == 1:
if A[0] == target:
print [0, 0]
return
else:
print [-1, -1]
return
if target < A[0] or target > A[-1]:
print [-1, -1]
return
upBound = len(A) - 1
lowBound = 0
midPoint = 0
flag = False
while upBound >= lowBound:
midPoint = (upBound + lowBound) // 2
print upBound, lowBound, midPoint
if A[midPoint] == target:
flag = True
break
if A[midPoint] > target:
upBound = midPoint - 1
else:
lowBound = midPoint + 1
print midPoint
print 'test'
if flag == False:
print [-1, -1]
return
lowBound = midPoint
upBound = midPoint
while A[lowBound] == target:
lowBound -= 1
print "lb", lowBound
if lowBound < 0 or A[lowBound] != target:
lowBound += 1
break
while A[upBound] == target:
upBound += 1
print "ub", upBound
if upBound > len(A) - 1 or A[upBound] != target:
upBound -= 1
break
print [lowBound, upBound]
if __name__ == "__main__":
A = [1,4]
target = 4
searchRange(A, target)
|
6ed689dd8d34e54c443f326cb4c132ea21154251
|
harman666666/Algorithms-Data-Structures-and-Design
|
/Algorithms and Data Structures Practice/LeetCode Questions/MOST IMPORTANT PROBLEMS/1458. Max Dot Product of Two Subsequences.py
| 2,038
| 3.859375
| 4
|
'''
1458. Max Dot Product of Two Subsequences
Hard
308
8
Add to List
Share
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty
subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from
the original array by deleting some (can be none) of the characters
without disturbing the relative positions of the remaining
characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
'''
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
'''
index i, and j:
maximum dot product to index i and j for each array.
'''
ROWS = len(nums1)
COLS = len(nums2)
OPT = [[0 for _ in range(COLS) ] for _ in range(ROWS) ]
OPT[0][0] = nums1[0] * nums2[0]
for i in range(1, ROWS):
OPT[i][0] = max(OPT[i-1][0], nums1[i]*nums2[0])
for j in range(1, COLS):
OPT[0][j] = max(OPT[0][j-1], nums1[0]*nums2[j])
for i in range(1, ROWS):
for j in range(1, COLS):
OPT[i][j] = max(nums1[i]*nums2[j],
OPT[i-1][j-1] + nums1[i]*nums2[j],
OPT[i][j-1],
OPT[i-1][j])
return OPT[-1][-1]
|
685783d2b43c13a2b9326b51d07f7b2c144c3cda
|
sconde/data-structure-and-algorithms-nanodegree
|
/02-data-structures/xx-projects/problem_5.py
| 3,017
| 3.8125
| 4
|
"""
Problem 5: Blockchain
"""
import hashlib
import time
import pprint
class Block(object):
def __init__(self, data, timestamp, previous_hash=0):
self.timestamp = timestamp
self.data = data
self.prev = None
self.previous_hash = previous_hash
self.hash = self.calc_hash(data)
@staticmethod
def calc_hash(data, encoding='utf-8'):
"""
calculate the hash
@param data:
@param encoding:
@return:
"""
sha = hashlib.sha256()
sha.update(
data.encode(encoding)
)
return sha.hexdigest()
class BlockChain(object):
def __init__(self):
self.tail = None
def append(self, data, timestamp):
"""
Append block to the end of the list
@param timestamp:
@param data:
@return:
"""
if self.tail is None:
self.tail = Block(data, timestamp)
return
new_block = Block(data, self.tail.timestamp, previous_hash=self.tail.hash)
new_block.prev = self.tail
self.tail = new_block
def size(self):
this_block = self.tail
this_size = 0
while this_block:
this_size += 1
this_block = this_block.prev
return this_size
def to_list(self):
this_list = []
this_block = self.tail
while this_block:
this_list.append(
[
this_block.data, this_block.timestamp, this_block.previous_hash
]
)
this_block = this_block.prev
return this_list
blockchain = BlockChain()
print(blockchain.size()) # 0
pprint.pprint(blockchain.to_list()) # []
blockchain.append('1st Block', time.time())
print(blockchain.size())
# 1
pprint.pprint(blockchain.to_list())
# [['my balance: 0 | cash flow: +10 | final balance: 10', 1564306421.0008988, '5e5a93abe59f9e92b38e00ebc7a50c50f902f5a8
# 210d327590a36ffb25a831d9']]
blockchain.append('second block', time.time())
blockchain.append('third block', time.time())
blockchain.append('fourth block', time.time())
blockchain.append('final block', time.time())
print(blockchain.size())
# 5
pprint.pprint(blockchain.to_list())
# [['my balance: 145 | cash flow: +5 | final balance: 150', 1564306378.6235423, '43841086a72ab23dacc07ac04341357ed73
# 51a07f8c8f0df92056cd439f49302'], ['my balance: 20 | cash flow: +125 | final balance: 145', 1564306378.6235056, '597f
# 549af039dbb1c79d5e4ae5c347189cf7b8bafc12011f44b0cc06692ade9e'], ['my balance: 35 | cash flow: -15 | final balance: 20'
# , 1564306378.623468, '6da8edd2d3d03bfa69810f7390ce55a64bab5102b79e37c973a4bed4be303e77'], ['my balance: 10 |
# cash flow: +25 | final balance: 35', 1564306378.6234293, 'ed240a001a354b3ee5f36db5ccdbcac1235806a106907feaedd9db02c
# 6ee7dfc'], ['my balance: 0 | cash flow: +10 | final balance: 10', 1564306378.6233213, '5e5a93abe59f9e92b38e00ebc7a50
# c50f902f5a8210d327590a36ffb25a831d9']]
|
1e7bc9a775d0c2aa79472a97bc48aa92e9ab7620
|
CaineSilva/Python2ObfCCompiler
|
/test_files/factorielle.py
| 580
| 3.9375
| 4
|
def nothing():
s = "Nothing"
print(s)
def factorielle(n) :
if n==1 or n==0 :
return 0
else :
return factorielle(n-1)
def factorielle_while(n) :
result = 1
i = 1
while i < n :
result *= i+1
i += 1
return result
def factorielle_for(n) :
result = 1
for i in range(1,n) :
result *= i+1
return result
n=5
f1 = factorielle(n)
f2 = factorielle_for(n)
f3 = factorielle_while(n)
if f1 == f2 and f1 == f3 :
print("Great it works !")
else :
print("Not working :(")
|
bdf65f9571001154765656df7ff404e8d87e2976
|
sezgincekerekli/sezginCekerekli
|
/sezginCekerekli.py
| 185
| 3.53125
| 4
|
import json
dosya = open("sezginCekerekli.json", "r")
json_dosya= json.load(dosya)
print("kimlik : " ,json_dosya["kimlik"])
# Fill in this file with the code from parsing JSON exercise
|
7fff7c2a0d06bff960e9442cd044d9e7727859cb
|
wenjie711/Leetcode
|
/python/094_BT_In_TVL.py
| 746
| 3.71875
| 4
|
#!/usr/bin/env python
#coding: utf-8
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root):
result = []
if(root == None):
return result
if(root.left != None):
left = self.inorderTraversal(root.left)
for p in left:
result.append(p)
result.append(root.val)
if(root.right != None):
right = self.inorderTraversal(root.right)
for p in right:
result.append(p)
return result
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n1.left = n3
n1.right = n2
s = Solution()
print(s.inorderTraversal(n1))
|
da43801efd7c40696be8162a7cbce129aee07f51
|
fakontello/py_algo
|
/Python_algorytms/Lesson_08/Lesson_08_ex_1.py
| 622
| 3.703125
| 4
|
# 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было?
graph = [
[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]
]
# n * (n - 1) / 2
b = 0
for i in range(len(graph)):
# длину графа умножить на количество единиц в одном элементе и разделить на два
b = int(((i + 1) * i) / 2)
print(f'Количетво рукопожатий для 4 друзей равно {b}')
|
92ade505d4f5f2d13f647c4f13f947ec39f97a75
|
JiageWang/Note
|
/MachineLearning/LinearRegression/线性回归.py
| 3,528
| 3.6875
| 4
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class LinearRegression(object):
def __init__(self):
self.theta = None
self.loss_list = []
def fit(self, X, y, lr=0.001, iters=1000):
"""train the model with input X and y"""
# add bias if X without bias
if np.sum(X[:, -1] - np.ones(X.shape[0])) != 0:
X = np.hstack((X, np.ones((X.shape[0], 1))))
self.X = X
self.y = y
self.sample_num = self.X.shape[0]
self.feature_num = self.X.shape[1] - 1
theta = np.random.randn(self.X.shape[1], 1)
for i in range(iters):
# compute and record the loss
y_pred = X @ theta
error = y_pred - y
loss = np.sum(error**2) / (2 * self.sample_num)
print("At iter {0}, loss = {1}".format(i + 1, loss))
self.loss_list.append(loss)
# upgrade theta through gradient descent
grad = X.T @ error / self.sample_num
theta = theta - lr * grad
# record the final theta
self.theta = theta
print("Final theta: {0}".format(theta))
def predict(self, X):
return X @ self.theta
def plot_data(self):
"""plot the data distribute and the decision plane"""
fig = plt.figure()
if self.feature_num == 1:
ax = fig.add_subplot(111)
ax.scatter(self.X[:, 0], self.y[:, 0])
x_ = np.array([self.X.min(), self.X.max()])
y_ = self.theta[0] * x_ + self.theta[1]
ax.plot(x_, y_, label="decision plane", c='r')
plt.title("Data distribution")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
elif self.feature_num == 2:
ax = fig.add_subplot(111, projection='3d')
ax.scatter(self.X[:, 0], self.X[:, 1], self.y[:, 0])
x_ = np.linspace(self.X[:, 0].min(), self.X[:, 0].max(), 100)
y_ = np.linspace(self.X[:, 1].min(), self.X[:, 1].max(), 100)
x_, y_ = np.meshgrid(x_, y_)
z_ = self.theta[0, 0] * x_ + self.theta[1, 0] * y_
ax.plot_surface(x_, y_, z_)
plt.show()
else:
print("unable to show data in high dimentional space")
def plot_loss(self):
fig = plt.figure()
ax = fig.add_subplot(111)
x_ = range(len(self.loss_list))
y_ = self.loss_list
ax.plot(x_, y_)
plt.xlabel("iters")
plt.ylabel("loss")
plt.show()
# def plot_theta(self):
# if self.feature_num == 1:
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# w = self.theta[0, 0]
# b = self.theta[1, 0]
# range_w = np.linspace(w - 5, w + 5, 100)
# range_b = np.linspace(b - 5, b + 5, 100)
# w_, b_ = np.meshgrid(range_w, range_b)
# ax.plot_surface(w_, b_, loss)
# plt.show()
if __name__ == "__main__":
# read data from txt
data = pd.read_csv('./ex1data1.txt', header=None)
#data = pd.read_csv('./ex1data2.txt', header=None)
data = (data - data.mean()) / data.std()
data = data.values
X = data[:, :-1]
y = data[:, -1:]
print(X.shape)
print(y.shape)
# train model
lg = LinearRegression()
lg.fit(X, y, lr=0.01, iters=1000)
lg.plot_data()
lg.plot_loss()
# lg.plot_theta()
|
47a5f436f649316f839653a080c1ea95cf86b516
|
unutulmaz/foodfie_flask
|
/Analysis/Notifications/test.py
| 1,064
| 3.734375
| 4
|
# from sklearn import neural_network.
#
# class Python:
#
# vips = 'aa'
#
# def __init__(self, name, age):
# self.name = name
# self.age = age
#
# def print_data(self):
# print(self.name, self.age)
#
# @classmethod
# def print_class(cls):
# print(Python.vips)
#
#
# class Python3(Python):
#
# def __init__(self, name, age, company):
# Python.__init__(self, name, age)
# self.company = company
#
#
# def print_python3(self):
# Python.print_class()
#
#
# a = Python3(5,10, 15)
# a.print_data()
# a.print_class()
# a.print_python3()
# Python.print_class()
#
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import Imputer
# Importing the dataset
df = pd.read_csv('Data.csv')
X = df.iloc[:, :-1].values
y = df.iloc[:, 3].values
imputer = Imputer(missing_values = 'Nan', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
|
77e3c9796a823e66d4f7a456df7d043a8552af65
|
shivam675/Quantum-CERN
|
/venv/Lib/site-packages/examples/coins/coins.py
| 1,070
| 3.6875
| 4
|
#!/usr/bin/python
#
# 100 coins must sum to $5.00
#
# That's kind of a country-specific problem, since depending on the
# country there are different values for coins. Here is presented
# the solution for a given set.
#
from constraint import Problem, ExactSumConstraint
import sys
def solve():
problem = Problem()
total = 5.00
variables = ("0.01", "0.05", "0.10", "0.50", "1.00")
values = [float(x) for x in variables]
for variable, value in zip(variables, values):
problem.addVariable(variable, range(int(total / value)))
problem.addConstraint(ExactSumConstraint(total, values), variables)
problem.addConstraint(ExactSumConstraint(100))
solutions = problem.getSolutionIter()
return solutions, variables
def main():
solutions, variables = solve()
for i, solution in enumerate(solutions):
sys.stdout.write("%03d -> " % (i + 1))
for variable in variables:
sys.stdout.write("%s:%d " % (variable, solution[variable]))
sys.stdout.write("\n")
if __name__ == "__main__":
main()
|
aa69dd86aaee9798ff154dec4b832ababf08ad92
|
JoaoPedroPiotroski/School-Stuff
|
/atvd19.py
| 339
| 3.921875
| 4
|
condition = True
soma = 0
numero = []
while condition:
num=int(input('Digite o numero: '))
if (num) != 0 and 0 < num <= 1000 :
soma += (num)
numero.append(num)
else:
break
print('Soma: ' +str(soma))
print('menor valor: %d' %(min(numero)))
print('maior valor: %d' %(max(numero)))
input()
|
8bb6032b64f07df63cfc9a60c029cda10d3493de
|
mfitzp/smrtr
|
/apps/resources/isbn.py
| 5,795
| 3.9375
| 4
|
#!/usr/bin/env python
# isbn.py
# Code for messing with ISBN numbers
# Especially stuff for converting between ISBN-10 and ISBN-13
# Copyright (C) 2007 Darren J Wilkinson
# Free GPL code
# Last updated: 14/8/2007
import sys,re
__doc__="""Code for messing with ISBN numbers. Stuff for validating ISBN-10 and
ISBN-13 numbers, computing check digits and converting from one format
to the other.
This code doesn't know anything about proper hyphenation of ISBNs. Nor does
it know anything about the real "validity" of ISBNs - it just validates on
the basis of the check-digit.
Some examples:
>>> import isbn
>>> isbn.isValid("1-58488-540-8")
True
>>> isbn.isValid("1-58488-540-5")
False
>>> isbn.isValid("978-158488-540-5")
True
>>> isbn.isI10("978-158488-540-5")
False
>>> isbn.isI13("978-158488-540-5")
True
>>> isbn.convert("1-58488-540-8")
'9781584885405'
>>> isbn.convert("978-158488-540-5")
'1584885408'
>>> isbn.isbn_strip("978-158488-540-5")
'9781584885405'
>>> isbn.check("1-58488-540")
'8'
>>> isbn.toI13("1-58488-540-8")
'9781584885405'
>>> isbn.toI13("978-158488-540-5")
'9781584885405'
>>> isbn.url("amazon","978-158488-540-5")
'http://www.amazon.com/exec/obidos/ASIN/1584885408'
The code is very simple pure python code in a single source file. Please
read the source code file (isbn.py) for further information about how
it works.
Please send bug reports, bug fixes, etc. to:
[email protected]
Free GPL code, Copyright (C) 2007 Darren J Wilkinson
http://www.staff.ncl.ac.uk/d.j.wilkinson/
"""
def isbn_strip(isbn):
"""Strip whitespace, hyphens, etc. from an ISBN number and return
the result."""
short=re.sub("\W","",isbn)
return re.sub("\D","X",short)
def convert(isbn):
"""Convert an ISBN-10 to ISBN-13 or vice-versa."""
short=isbn_strip(isbn)
if (isValid(short)==False):
raise "Invalid ISBN"
if len(short)==10:
stem="978"+short[:-1]
return stem+check(stem)
else:
if short[:3]=="978":
stem=short[3:-1]
return stem+check(stem)
else:
raise "ISBN not convertible"
def isValid(isbn):
"""Check the validity of an ISBN. Works for either ISBN-10 or ISBN-13."""
short=isbn_strip(isbn)
if len(short)==10:
return isI10(short)
elif len(short)==13:
return isI13(short)
else:
return False
def check(stem):
"""Compute the check digit for the stem of an ISBN. Works with either
the first 9 digits of an ISBN-10 or the first 12 digits of an ISBN-13."""
short=isbn_strip(stem)
if len(short)==9:
return checkI10(short)
elif len(short)==12:
return checkI13(short)
else:
return False
def checkI10(stem):
"""Computes the ISBN-10 check digit based on the first 9 digits of a
stripped ISBN-10 number."""
chars=list(stem)
sum=0
digit=10
for char in chars:
sum+=digit*int(char)
digit-=1
check=11-(sum%11)
if check==10:
return "X"
elif check==11:
return "0"
else:
return str(check)
def isI10(isbn):
"""Checks the validity of an ISBN-10 number."""
short=isbn_strip(isbn)
if (len(short)!=10):
return False
chars=list(short)
sum=0
digit=10
for char in chars:
if (char=='X' or char=='x'):
char="10"
sum+=digit*int(char)
digit-=1
remainder=sum%11
if remainder==0:
return True
else:
return False
def checkI13(stem):
"""Compute the ISBN-13 check digit based on the first 12 digits of a
stripped ISBN-13 number. """
chars=list(stem)
sum=0
count=0
for char in chars:
if (count%2==0):
sum+=int(char)
else:
sum+=3*int(char)
count+=1
check=10-(sum%10)
if check==10:
return "0"
else:
return str(check)
def isI13(isbn):
"""Checks the validity of an ISBN-13 number."""
short=isbn_strip(isbn)
if (len(short)!=13):
return False
chars=list(short)
sum=0
count=0
for char in chars:
if (count%2==0):
sum+=int(char)
else:
sum+=3*int(char)
count+=1
remainder=sum%10
if remainder==0:
return True
else:
return False
def toI10(isbn):
"""Converts supplied ISBN (either ISBN-10 or ISBN-13) to a stripped
ISBN-10."""
if (isValid(isbn)==False):
raise "Invalid ISBN"
if isI10(isbn):
return isbn_strip(isbn)
else:
return convert(isbn)
def toI13(isbn):
"""Converts supplied ISBN (either ISBN-10 or ISBN-13) to a stripped
ISBN-13."""
if (isValid(isbn)==False):
raise "Invalid ISBN"
if isI13(isbn):
return isbn_strip(isbn)
else:
return convert(isbn)
def url(type,isbn):
"""Returns a URL for a book, corresponding to the "type" and the "isbn"
provided. This function is likely to go out-of-date quickly, and is
provided mainly as an example of a potential use-case for the package.
Currently allowed types are "google-books" (the default if the type is
not recognised), "amazon", "amazon-uk", "blackwells".
"""
short=toI10(isbn)
if type=="amazon":
return "http://www.amazon.com/o/ASIN/"+short
elif type=="amazon-uk":
return "http://www.amazon.co.uk/o/ASIN/"+short
elif type=="blackwells":
return "http://bookshop.blackwell.co.uk/jsp/welcome.jsp?action=search&type=isbn&term="+short
else:
return "http://books.google.com/books?vid="+short
if __name__=='__main__':
isbn="1-58488-540-8"
# isbn="978-158488-540-5"
print isbn
if isValid(isbn):
print "isbn ok"
else:
print "isbn BAD"
print convert(isbn)
print """
For help/information, do "python", "import isbn", "help(isbn)".
"""
# eof
|
c87e50068527cb1602d78f73c4274fada49748c9
|
ElianEstrada/Cursos_Maury_C
|
/Codigos/08 - condicion_if_elif_else.py
| 463
| 3.859375
| 4
|
# Sintaxis del if - elif - else
#Los corchetes ([]) indican opcionalidad
# 'if' '(' condicion ')' ':'
# ' ' bloque_codigo':'
# ' ' bloque_codigo] -> se
# ['elif' '(' condicion2 ')' puede repetir n veces.
# ['else' ':'
# ' ' bloque_codigo]
#Identificar que un número x
#es positivo, 0 o negativo
x = -10;
if (x > 0):
print(f"{x} es positivo");
elif (x == 0):
print(f"{x} es cero");
else:
print(f"{x} es negativo");
|
d01aa234204bd19ab9e6fb73fb884079046da4a8
|
gabriellaec/desoft-analise-exercicios
|
/backup/user_393/ch60_2020_10_05_18_32_07_312707.py
| 267
| 3.8125
| 4
|
def eh_palindromo(lista):
i= 1
lista_invertida= ''
while i <= len(lista):
lista_invertida= lista_invertida + lista[-i]
i = i + 1
print(lista_invertida)
if lista_invertida== lista:
return True
else:
return False
|
6defe8a28b1aa986a36652e7d17267b71371eaa7
|
HarshSharma12/ProjectEulerPython
|
/Ques_7.py
| 578
| 3.5625
| 4
|
# -*- coding: utf-8 -*-
"""
Solved on - 1/8/2011
@author: Harsh Sharma
10001st prime
Problem 7
Published on Friday, 28th December 2001, 06:00 pm; Solved by 195407
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
Answer: 104743
"""
from math import sqrt
n=1
a=0
l=[]
while n<10001:
a+=1
b=2
d=sqrt(a)
while b<d+1:
if a%b==0:
break
elif (b>=d):
l.append(a)
break
b+=1
n=len(l)
n+=1
print len(l)
print a
|
fc08971348295106774e280eccebcf793d221c8f
|
tiantian123/Algorithm
|
/Python/LeetCodePractice/Day1_DeleteListRepeat.py
| 1,711
| 4.15625
| 4
|
#!/usr/bin/env python
# -** coding: utf-8 -*-
# @Time: 2020/3/10 21:05
# @Author: Tian Chen
# @File: Day1_DeleteListRepeat.py
"""
26.删除有序数组中的重复值
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例:
给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。你不需要考虑数组中超出新长度后面的元素。
"""
from typing import List
class Solution:
"""
思路:使用前后双指针p和q, 当前后两个指针所指向的值相等时,前指针后移,当前后指针指向内容不相等时,将前指针的值赋值给后指针后移1位的结点
优化:考虑到没有重复值时,拷贝数据消耗内存太大,加入判断语句 ,只有当 q - p > 1才进行拷贝
"""
def removeDuplicates(self, nums: List[int]) -> int:
# 先判断数组是否为kong
length = len(nums)
if length == 0:
return 0
# 设置双指针
p = 0
q = 1
while q < length:
if nums[p] != nums[q]:
if q - p > 1: # 减少数据转移的次数
nums[p + 1] = nums[q]
p += 1
q += 1
return p + 1
if __name__ == "__main__":
lst = [0,0,1,1,1,2,2,3,3,4]
print("原始数组:", lst)
test = Solution()
length = test.removeDuplicates(lst)
lst = lst[:length]
print(f"移除重复值后的数组:", lst)
|
8cfa18155511b23de159c44a28ee551757067e2d
|
k8godzilla/-Leetcode
|
/1-100/L109.py
| 2,182
| 4.03125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 06:35:39 2019
@author: sunyin
"""
'''
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedListToBST(self, head) :
# head : ListNode
# return : TreeNode
if not head:
return head
head_list = []
while head:
head_list.append(head)
head = head.next
return self.headListToBST(head_list)
def headListToBST(self, headList):
if not headList:
return None
if len(headList) == 1:
return TreeNode(headList[0].val)
elif len(headList) == 2:
t0 = TreeNode(headList[0].val)
t1 = TreeNode(headList[1].val)
t1.left = t0
return t1
else:
i_m = len(headList) // 2
t = TreeNode(headList[i_m].val)
t_left = self.headListToBST(headList[:i_m])
t_right = self.headListToBST(headList[i_m + 1:])
t.left = t_left
t.right = t_right
return t
|
323680559b3f84c5140029508a588907c5822f68
|
ana-romero/mega2021-kenzo-sage
|
/finite_topological_spaces.py
| 75,578
| 3.65625
| 4
|
r"""
Finite topological spaces
This module implements finite topological spaces and related concepts.
A *finite topological space* is a topological space with finitely many points and
a *finite preordered set* is a finite set with a transitive and reflexive relation.
Finite spaces and finite preordered sets are basically the same objects considered
from different perspectives. Given a finite topological space `X`, for every point
`x\in X`, define the *minimal open set* `U_x` as the intersection of all the open
sets which contain `x` (it is an open set since arbitrary intersections of open
sets in finite spaces are open). The minimal open sets constitute a basis for the
topology of `X`. Indeed, any open set `U` of `X` is the union of the sets `U_x`
with `x\in U`. This basis is called the *minimal basis of* `X`. A preorder on `X`
is given by `x\leqslant y` if `x\in U_y`.
If `X` is now a finite preordered set, one can define a topology on `X` given by
the basis `\lbrace y\in X\vert y\leqslant x\rbrace_{x\in X}`. Note that if `y\leqslant x`,
then `y` is contained in every basic set containing `x`, and therefore `y\in U_x`.
Conversely, if `y\in U_x`, then `y\in\lbrace z\in X\vert z\leqslant x\rbrace`.
Therefore `y\leqslant x` if and only if `y\in U_x`. This shows that these two
applications, relating topologies and preorders on a finite set, are mutually
inverse. This simple remark, made in first place by Alexandroff [Ale1937]_, allows
us to study finite spaces by combining Algebraic Topology with the combinatorics
arising from their intrinsic preorder structures. The antisymmetry of a finite
preorder corresponds exactly to the `T_0` separation axiom. Recall that a topological
space `X` is said to be `T_0` if for any pair of points in `X` there exists an
open set containing one and only one of them. Therefore finite `T_0`-spaces are
in correspondence with finite partially ordered sets (posets) [Bar2011]_.
Now, if `X = \lbrace x_1, x_2, \ldots , x_n\rbrace` is a finite space and for
each `i` the unique minimal open set containing `x_i` is denoted by `U_i`, a
*topogenous matrix* of the space is the `n \times n` matrix `A = \left[a_{ij}\right]`
defined by `a_{ij} = 1` if `x_i \in U_j` and `a_{ij} = 0` otherwise (this is the
transposed matrix of the Definition 1 in [Shi1968]_). A finite space `X` is `T_0`
if and only if the topogenous matrix `A` defined above is similar (via a permutation
matrix) to a certain upper triangular matrix [Shi1968]_. This is the reason one
can assume that the topogenous matrix of a finite `T_0`-space is upper triangular.
AUTHOR::
- Julian Cuevas-Rozo (2020): Initial version
REFERENCES:
- [Ale1937]_
- [Bar2011]_
- [Shi1968]_
"""
# ****************************************************************************
# Copyright (C) 2020 Julian Cuevas-Rozo <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from sage.structure.parent import Parent
from sage.matrix.constructor import matrix
from sage.matrix.matrix_integer_sparse import Matrix_integer_sparse
from sage.combinat.posets.posets import Poset
from sage.rings.integer_ring import ZZ
from sage.homology.homology_group import HomologyGroup
from sage.libs.ecl import EclObject, ecl_eval, EclListIterator
from sage.interfaces import kenzo
from sage.features.kenzo import Kenzo
###############################################################
# This section (lines 76 to 246) will be included to src/sage/interfaces/kenzo.py
kenzonames = ['2h-regularization',
'copier-matrice',
'creer-matrice',
'convertarray',
'dvfield-aux',
'edges-to-matrice',
'h-regular-dif',
'h-regular-dif-dvf-aux',
'matrice-to-lmtrx',
'mtrx-prdc',
'newsmith-equal-matrix',
'newsmith-mtrx-prdc',
'random-top-2space',
'randomtop',
'vector-to-list']
if Kenzo().is_present():
ecl_eval("(require :kenzo)")
ecl_eval("(in-package :cat)")
ecl_eval("(setf *HOMOLOGY-VERBOSE* nil)")
for s in kenzonames:
name = '__{}__'.format(s.replace('-', '_'))
exec('{} = EclObject("{}")'.format(name, s))
def quotient_group_matrices(*matrices, left_null=False, right_null=False, check=True):
r"""
Return a presentation of the homology group `\ker M1/ \im M2`.
INPUT:
- ``matrices`` -- A tuple of ECL matrices. The length `L` of this parameter
can take the value 0, 1 or 2.
- ``left_null`` -- (default ``False``) A boolean.
- ``right_null`` -- (default ``False``) A boolean.
- ``check`` -- (default ``True``) A boolean. If it is ``True`` and `L=2`, it
checks that the product of the ``matrices`` is the zero matrix.
OUTPUT:
- If `L=0`, it returns the trivial group.
- If `L=1` (``matrices`` = M), then one of the parameters ``left_null`` or
``right_null`` must be ``True``: in case ``left_null`` == ``True``, it
returns the homology group `\ker 0/ \im M` and in case ``right_null`` == ``True``,
it returns the homology group `\ker M/ \im 0`.
- If `L=2` (``matrices`` = (M1, M2)), it returns the homology group `\ker M1/ \im M2`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import quotient_group_matrices, __convertarray__
sage: from sage.interfaces.kenzo import s2k_matrix
sage: quotient_group_matrices()
0
sage: s_M1 = matrix(2, 3, [1, 2, 3, 4, 5, 6])
sage: M1 = __convertarray__(s2k_matrix(s_M1))
sage: quotient_group_matrices(M1, left_null=True)
C3
sage: quotient_group_matrices(M1, right_null=True)
Z
sage: s_M2 = matrix(2, 2, [1, -1, 1, -1])
sage: M2 = __convertarray__(s2k_matrix(s_M2))
sage: s_M3 = matrix(2, 2, [1, 0, 1, 0])
sage: M3 = __convertarray__(s2k_matrix(s_M3))
sage: quotient_group_matrices(M2, M3)
0
sage: s_M4 = matrix(2, 2, [0, 0, 1, 0])
sage: M4 = __convertarray__(s2k_matrix(s_M4))
sage: quotient_group_matrices(M2, M4)
Traceback (most recent call last):
...
AssertionError: m1*m2 must be zero
"""
assert not (left_null and right_null), "left_null and right_null must not be both True"
if len(matrices)==0:
return HomologyGroup(0, ZZ)
elif len(matrices)==1:
if left_null==True:
m2 = matrices[0]
m1 = __creer_matrice__(0, kenzo.__nlig__(m2))
elif right_null==True:
m1 = matrices[0]
m2 = __creer_matrice__(kenzo.__ncol__(m1), 0)
else:
raise AssertionError("left_null or right_null must be True")
elif len(matrices)==2:
m1, m2 = matrices
if check==True:
rowsm1 = kenzo.__nlig__(m1)
colsm1 = kenzo.__ncol__(m1)
rowsm2 = kenzo.__nlig__(m2)
colsm2 = kenzo.__ncol__(m2)
assert colsm1==rowsm2, "Number of columns of m1 must be equal to the number of rows of m2"
assert __newsmith_equal_matrix__(__newsmith_mtrx_prdc__(m1, m2), \
__creer_matrice__(rowsm1, colsm2)).python(), \
"m1*m2 must be zero"
homology = kenzo.__homologie__(__copier_matrice__(m1), __copier_matrice__(m2))
lhomomology = [i for i in EclListIterator(homology)]
res = []
for component in lhomomology:
pair = [i for i in EclListIterator(component)]
res.append(pair[0].python())
return HomologyGroup(len(res), ZZ, res)
def k2s_binary_matrix_sparse(kmatrix):
r"""
Converts a Kenzo binary sparse matrice (type `matrice`) to a matrix in SageMath.
INPUT:
- ``kmatrix`` -- A Kenzo binary sparse matrice (type `matrice`).
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import k2s_binary_matrix_sparse, \
s2k_binary_matrix_sparse, __randomtop__
sage: KM2 = __randomtop__(6,1)
sage: k2s_binary_matrix_sparse(KM2)
[1 1 1 1 1 1]
[0 1 1 1 1 1]
[0 0 1 1 1 1]
[0 0 0 1 1 1]
[0 0 0 0 1 1]
[0 0 0 0 0 1]
sage: KM = __randomtop__(100, float(0.8))
sage: SM = k2s_binary_matrix_sparse(KM)
sage: SM == k2s_binary_matrix_sparse(s2k_binary_matrix_sparse(SM))
True
"""
data = __vector_to_list__(__matrice_to_lmtrx__(kmatrix)).python()
dim = len(data)
mat_dict = {}
for j in range(dim):
colj = data[j]
for entry in colj:
mat_dict[(entry[0], j)] = 1
return matrix(dim, mat_dict)
def s2k_binary_matrix_sparse(smatrix):
r"""
Converts a binary matrix in SageMath to a Kenzo binary sparse matrice (type `matrice`).
INPUT:
- ``smatrix`` -- A binary matrix.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import k2s_binary_matrix_sparse, \
s2k_binary_matrix_sparse
sage: SM2 = matrix.ones(5)
sage: s2k_binary_matrix_sparse(SM2)
<ECL:
========== MATRIX 5 lines + 5 columns =====
L1=[C1=1][C2=1][C3=1][C4=1][C5=1]
L2=[C1=1][C2=1][C3=1][C4=1][C5=1]
L3=[C1=1][C2=1][C3=1][C4=1][C5=1]
L4=[C1=1][C2=1][C3=1][C4=1][C5=1]
L5=[C1=1][C2=1][C3=1][C4=1][C5=1]
========== END-MATRIX>
"""
dim = smatrix.nrows()
entries = []
for entry in smatrix.dict().keys():
entries.append([entry[0]+1, entry[1]+1])
kentries = EclObject(entries)
return __edges_to_matrice__(kentries, dim)
###############################################################
def FiniteSpace(data, elements=None, is_T0=False):
r"""
Construct a finite topological space from various forms of input data.
INPUT:
- ``data`` -- different input are accepted by this constructor:
1. A dictionary representing the minimal basis of the space.
2. A list or tuple of minimal open sets (in this case the elements of the
space are assumed to be ``range(n)`` where ``n`` is the length of ``data``).
3. A topogenous matrix (assumed sparse). If ``elements=None``, the elements
of the space are assumed to be ``range(n)`` where ``n`` is the dimension
of the matrix.
4. A finite poset (by now if ``poset._is_facade = False``, the methods are
not completely tested).
- ``elements`` -- (default ``None``) it is ignored when data is of type 1, 2
or 4. When ``data`` is a topogenous matrix, this parameter gives the
underlying set of the space.
- ``is_T0`` -- (default ``False``) it is a boolean that indicates, when it is
previously known, if the finite space is `T_0.
EXAMPLES:
A dictionary as ``data``::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace({'a': {'a', 'c'}, 'b': {'b'}, 'c':{'a', 'c'}}) ; T
Finite topological space of 3 points with minimal basis
{'a': {'a', 'c'}, 'b': {'b'}, 'c': {'a', 'c'}}
sage: type(T)
<class 'sage.homology.finite_topological_spaces.FiniteTopologicalSpace'>
sage: FiniteSpace({'a': {'a', 'b'}})
Traceback (most recent call last):
...
ValueError: The data does not correspond to a valid dictionary
sage: FiniteSpace({'a': {'a', 'b'}, 'b': {'a', 'b'}, 'c': {'a', 'c'}})
Traceback (most recent call last):
...
ValueError: The introduced data does not define a topology
When ``data`` is a tuple or a list, the elements are in ``range(n)`` where
``n`` is the length of ``data``::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 3}, {1, 3}, {2, 3}, {3}]) ; T
Finite T0 topological space of 4 points with minimal basis
{0: {3, 0}, 1: {3, 1}, 2: {3, 2}, 3: {3}}
sage: type(T)
<class 'sage.homology.finite_topological_spaces.FiniteTopologicalSpace_T0'>
sage: T.elements()
[3, 0, 1, 2]
sage: FiniteSpace(({0, 2}, {0, 2}))
Traceback (most recent call last):
...
ValueError: This kind of data assume the elements are in range(2)
If ``data`` is a topogenous matrix, the parameter ``elements``, when it is not
``None``, determines the list of elements of the space::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: mat_dict = {(0, 0): 1, (0, 3): 1, (0, 4): 1, (1, 1): 1, (1, 2): 1, (2, 1): 1, \
....: (2, 2): 1, (3, 3): 1, (3, 4): 1, (4, 3): 1, (4, 4): 1}
sage: mat = matrix(mat_dict) ; mat
[1 0 0 1 1]
[0 1 1 0 0]
[0 1 1 0 0]
[0 0 0 1 1]
[0 0 0 1 1]
sage: T = FiniteSpace(mat) ; T
Finite topological space of 5 points with minimal basis
{0: {0}, 1: {1, 2}, 2: {1, 2}, 3: {0, 3, 4}, 4: {0, 3, 4}}
sage: T.elements()
[0, 1, 2, 3, 4]
sage: M = FiniteSpace(mat, elements=(5, 'e', 'h', 0, 'c')) ; M
Finite topological space of 5 points with minimal basis
{5: {5}, 'e': {'e', 'h'}, 'h': {'e', 'h'}, 0: {5, 0, 'c'}, 'c': {5, 0, 'c'}}
sage: M.elements()
[5, 'e', 'h', 0, 'c']
sage: FiniteSpace(mat, elements=[5, 'e', 'h', 0, 0])
Traceback (most recent call last):
...
AssertionError: Not valid list of elements
Finally, when ``data`` is a finite poset, the corresponding finite T0 space
is constructed::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: P = Poset([[1, 2], [4], [3], [4], []])
sage: T = FiniteSpace(P) ; T
Finite T0 topological space of 5 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 2}, 3: {0, 2, 3}, 4: {0, 1, 2, 3, 4}}
sage: type(T)
<class 'sage.homology.finite_topological_spaces.FiniteTopologicalSpace_T0'>
sage: T.poset() == P
True
"""
if hasattr(data, '_hasse_diagram'): # isinstance(data, FinitePosets): # type 4
minimal_basis = {x: set(data.order_ideal([x])) for x in data.list()}
topogenous = data.lequal_matrix()
return FiniteTopologicalSpace_T0(elements=data.list(), minimal_basis=minimal_basis,
topogenous=topogenous, poset=data)
topogenous = None
if isinstance(data, dict): # type 1
n = len(data)
eltos = set()
for B in data.values():
eltos = eltos.union(B)
if not eltos==set(data):
raise ValueError("The data does not correspond to a valid dictionary")
basis = data
if isinstance(data, (list, tuple)): # type 2
n = len(data)
eltos = set()
# In this case, the elements are assumed being range(n)
for B in data:
eltos = eltos.union(B)
if not eltos==set(range(n)):
raise ValueError("This kind of data assume the elements are in range({})".format(n))
basis = dict(zip(range(n), data))
if isinstance(data, Matrix_integer_sparse): # type 3
n = data.dimensions()[0]
assert n==data.dimensions()[1], \
"Topogenous matrices are square"
assert set(data.dict().values())=={1}, \
"Topogenous matrices must have entries in {0,1}"
basis = {}
# Extracting a minimal basis from the topogenous matrix info
if elements:
if not isinstance(elements, (list, tuple)):
raise ValueError("Parameter 'elements' must be a list or a tuple")
assert len(set(elements))==n, \
"Not valid list of elements"
for j in range(n):
Uj = set([elements[i] for i in data.nonzero_positions_in_column(j)])
basis[elements[j]] = Uj
eltos = elements
else:
for j in range(n):
Uj = set(data.nonzero_positions_in_column(j))
basis[j] = Uj
eltos = range(n)
# This fixes a topological sort (it guarantees an upper triangular topogenous matrix)
eltos = list(eltos)
sorted_str_eltos = sorted([str(x) for x in eltos])
eltos.sort(key = lambda x: (len(basis[x]), sorted_str_eltos.index(str(x))))
# Now, check that 'basis' effectively defines a minimal basis for a topology
nonzero = {(eltos.index(x), j):1 for j in range(n) \
for x in basis[eltos[j]]}
topogenous = matrix(n, nonzero)
squared = topogenous*topogenous
if not topogenous.nonzero_positions() == squared.nonzero_positions():
raise ValueError("The introduced data does not define a topology")
if is_T0:
return FiniteTopologicalSpace_T0(elements=eltos, minimal_basis=basis,
topogenous=topogenous)
# Determine if the finite space is T0
partition = []
eltos2 = eltos.copy()
while eltos2:
x = eltos2.pop(0)
Ux = basis[x] - set([x])
equiv_class = set([x])
for y in Ux:
if x in basis[y]:
equiv_class = equiv_class.union(set([y]))
eltos2.remove(y)
partition.append(equiv_class)
if len(partition)==n:
return FiniteTopologicalSpace_T0(elements=eltos, minimal_basis=basis,
topogenous=topogenous)
result = FiniteTopologicalSpace(elements=eltos, minimal_basis=basis,
topogenous=topogenous)
setattr(result, '_T0', partition)
return result
def RandomFiniteT0Space(*args):
r"""
Return a random finite `T_0` space.
INPUT:
- ``args`` -- A tuple of two arguments. The first argument must be an integer
number, while the second argument must be either a number between 0 and 1, or
``True``.
OUTPUT:
- If ``args[1]``=``True``, a random finite `T_0` space of cardinality ``args[0]``
of height 3 without beat points is returned.
- If ``args[1]`` is a number, a random finite `T_0` space of cardinality ``args[0]``
and density ``args[1]`` of ones in its topogenous matrix is returned.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import RandomFiniteT0Space
sage: RandomFiniteT0Space(5, 0)
Finite T0 topological space of 5 points with minimal basis
{0: {0}, 1: {1}, 2: {2}, 3: {3}, 4: {4}}
sage: RandomFiniteT0Space(5, 2)
Finite T0 topological space of 5 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 1, 2, 3}, 4: {0, 1, 2, 3, 4}}
sage: RandomFiniteT0Space(6, True)
Finite T0 topological space of 6 points with minimal basis
{0: {0}, 1: {1}, 2: {0, 1, 2}, 3: {0, 1, 3}, 4: {0, 1, 2, 3, 4}, 5: {0, 1, 2, 3, 5}}
sage: RandomFiniteT0Space(150, 0.2)
Finite T0 topological space of 150 points
sage: RandomFiniteT0Space(5, True)
Traceback (most recent call last):
...
AssertionError: The first argument must be an integer number greater than 5
"""
assert len(args)==2, "Two arguments must be given"
assert args[0].is_integer(), "The first argument must be an integer number"
if args[1]==True:
assert args[0]>5, "The first argument must be an integer number greater than 5"
kenzo_top = __random_top_2space__(args[0])
else:
kenzo_top = __randomtop__(args[0], EclObject(float(args[1])))
topogenous = k2s_binary_matrix_sparse(kenzo_top)
basis = {j:set(topogenous.nonzero_positions_in_column(j)) for j in range(args[0])}
return FiniteTopologicalSpace_T0(elements=list(range(args[0])), minimal_basis=basis,
topogenous=topogenous)
class FiniteTopologicalSpace(Parent):
r"""
Finite topological spaces.
Users should not call this directly, but instead use :func:`FiniteSpace`.
See that function for more documentation.
"""
def __init__(self, elements, minimal_basis, topogenous):
r"""
Define a finite topological space.
INPUT:
- ``elements`` -- list of the elements of the space.
- ``minimal_basis`` -- a dictionary where the values are sets representing
the minimal open sets containing the respective key.
- ``topogenous`` -- a topogenous matrix of the finite space corresponding
to the order given by ``elements``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteTopologicalSpace
sage: elements = [1, 2, 'a', 3]
sage: minimal_basis = {'a': {3, 'a'}, 3: {3, 'a'}, 2: {2, 1}, 1: {1}}
sage: mat_dict = {(0, 0): 1, (0, 1): 1, (1, 1): 1, (2, 2): 1, \
....: (2, 3): 1, (3, 2): 1, (3, 3): 1}
sage: T = FiniteTopologicalSpace(elements, minimal_basis, matrix(mat_dict)) ; T
Finite topological space of 4 points with minimal basis
{'a': {'a', 3}, 3: {'a', 3}, 2: {1, 2}, 1: {1}}
sage: T.topogenous_matrix() == matrix(mat_dict)
True
"""
# Assign attributes
self._cardinality = len(elements)
self._elements = elements
self._minimal_basis = minimal_basis
self._topogenous = topogenous
def space_sorting(self, element):
r"""
Return a pair formed by the index of `element` in `self._elements` and
the index of `str(element)` in the sorted list consisting of the strings of
elements in `self._elements`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace({0: {3, 0}, 3: {3, 0}, 2: {2, 1}, 1: {1}})
sage: T._elements
[1, 0, 2, 3]
sage: T.space_sorting(1)
(0, 1)
sage: T.space_sorting(2)
(2, 2)
"""
eltos = self._elements
sorted_str_eltos = sorted([str(x) for x in eltos])
return (eltos.index(element), sorted_str_eltos.index(str(element)))
def _repr_(self):
r"""
Print representation.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: FiniteSpace({0: {0, 1}, 1: {0, 1}})
Finite topological space of 2 points with minimal basis
{0: {0, 1}, 1: {0, 1}}
sage: Q = Poset((divisors(120), attrcall("divides")), linear_extension=True)
sage: FiniteSpace(Q)
Finite T0 topological space of 16 points
"""
n = self._cardinality
if n < 10:
sorted_minimal_basis = {x: sorted(self._minimal_basis[x], key=self.space_sorting)
for x in self._minimal_basis}
return "Finite topological space of {} points with minimal basis \n {}" \
.format(n, sorted_minimal_basis).replace('[', '{').replace(']', '}')
else:
return "Finite topological space of {} points".format(n)
def __contains__(self, x):
r"""
Return ``True`` if ``x`` is an element of the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: P = Poset((divisors(6), attrcall("divides")), linear_extension=True)
sage: T = FiniteSpace(P)
sage: 3 in T
True
sage: 4 in T
False
"""
return x in self._elements
def elements(self):
r"""
Return the list of elements in the underlying set of the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {1}, {2, 3}, {3}))
sage: T.elements()
[0, 1, 3, 2]
"""
return self._elements
def underlying_set(self):
r"""
Return the underlying set of the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {1}, {2, 3}, {3}))
sage: T.underlying_set()
{0, 1, 2, 3}
"""
return set(self._elements)
def subspace(self, points=None, is_T0=False):
r"""
Return the subspace whose elements are in ``points``.
INPUT:
- ``points`` -- (default ``None``) A tuple, list or set contained in ``self.elements()``.
- ``is_T0`` -- (default ``False``) If it is known that the resulting subspace is `T_0`, fix ``True``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {1, 3, 4}, {0, 2, 5}, {1, 3, 4}, {1, 3, 4}, {0, 2, 5}))
sage: T.subspace((0, 3, 5))
Finite T0 topological space of 3 points with minimal basis
{0: {0}, 3: {3}, 5: {0, 5}}
sage: T.subspace([4])
Finite T0 topological space of 1 points with minimal basis
{4: {4}}
sage: T.subspace() == T
True
"""
if points is None:
return self
assert isinstance(points, (tuple, list, set)), \
"Parameter must be of type tuple, list or set"
points = set(points)
assert points <= set(self._elements), \
"There are points that are not in the space"
if points==set(self._elements):
return self
minimal_basis = {x: self._minimal_basis[x] & points for x in points}
return FiniteSpace(minimal_basis, is_T0=is_T0)
def cardinality(self):
r"""
Return the number of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: P = Poset((divisors(360), attrcall("divides")), linear_extension=True)
sage: T = FiniteSpace(P)
sage: T.cardinality() == P.cardinality()
True
"""
return self._cardinality
def minimal_basis(self):
r"""
Return the minimal basis that generates the topology of the finite space.
OUTPUT:
- A dictionary whose keys are the elements of the space and the values
are the minimal open sets containing the respective element.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {0, 1, 2}, {0, 1, 2}, {3, 4}, {3, 4}))
sage: T.minimal_basis()
{0: {0}, 1: {0, 1, 2}, 2: {0, 1, 2}, 3: {3, 4}, 4: {3, 4}}
sage: M = T.equivalent_T0()
sage: M.minimal_basis()
{0: {0}, 1: {0, 1}, 3: {3}}
"""
return self._minimal_basis
def minimal_open_set(self, x):
r"""
Return the minimal open set containing ``x``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {0, 1, 2}, {0, 1, 2}, {3, 4}, {3, 4}))
sage: T.minimal_open_set(1)
{0, 1, 2}
"""
if not x in self:
raise ValueError("The point {} is not an element of the space".format(x))
else:
return self._minimal_basis[x]
def topogenous_matrix(self):
r"""
Return the topogenous matrix of the finite space.
OUTPUT:
- A binary matrix whose `(i,j)` entry is equal to 1 if and only if ``self._elements[i]``
is in ``self._minimal_basis[self._elements[j]]``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {1, 3, 4}, {0, 2, 5}, {1, 3, 4}, {1, 3, 4}, {0, 2, 5}))
sage: T.topogenous_matrix()
[1 0 1 0 0 1]
[0 1 0 1 1 0]
[0 0 1 0 0 1]
[0 1 0 1 1 0]
[0 1 0 1 1 0]
[0 0 1 0 0 1]
sage: T0 = T.equivalent_T0()
sage: T0.topogenous_matrix()
[1 0 1]
[0 1 0]
[0 0 1]
"""
return self._topogenous
def is_T0(self):
r"""
Return ``True`` if the finite space satisfies the T0 separation axiom.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0}, {1}, {2, 3}, {2, 3}])
sage: T.is_T0()
False
sage: T.equivalent_T0().is_T0()
True
"""
return isinstance(self, FiniteTopologicalSpace_T0)
def equivalent_T0(self, points=None, check=True):
r"""
Return a finite T0 space homotopy equivalent to ``self``.
INPUT:
- ``points`` -- (default ``None``) a tuple, list or set of representatives
elements of the equivalent classes induced by the partition ``self._T0``.
- ``check`` -- if ``True`` (default), it is checked that ``points`` effectively
defines a set of representatives of the partition ``self._T0``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(({0}, {1, 3, 4}, {0, 2, 5}, {1, 3, 4}, {1, 3, 4}, {0, 2, 5}))
sage: T.is_T0()
False
sage: T._T0
[{0}, {1, 3, 4}, {2, 5}]
sage: M1 = T.equivalent_T0()
sage: M1.is_T0()
True
sage: M1.elements()
[0, 1, 2]
sage: M2 = T.equivalent_T0(points={0,4,5}, check=False)
sage: M2.elements()
[0, 4, 5]
sage: T.equivalent_T0(points={0,3,4})
Traceback (most recent call last):
...
ValueError: Parameter 'points' is not a valid set of representatives
"""
if self._T0 is True:
return self
else:
if points is None:
points = [list(A)[0] for A in self._T0]
elif check:
assert isinstance(points, (tuple, list, set)), \
"Parameter 'points' must be of type tuple, list or set"
assert len(points)==len(self._T0), \
"Parameter 'points' does not have a valid length"
points2 = set(points.copy())
partition = self._T0.copy()
while points2:
x = points2.pop()
class_x = None
for k in range(len(partition)):
if x in partition[k]:
class_x = k
partition.pop(k)
break
if class_x is None:
raise ValueError("Parameter 'points' is not a valid set of representatives")
return self.subspace(points, is_T0=True)
def Ux(self, x):
r"""
Return the list of the elements in the minimal open set containing ``x``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Ux(2)
[5, 6, 2]
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.2))
sage: x = random.choice(T._elements)
sage: T.is_contractible(T.Ux(x))
True
"""
return sorted(self._minimal_basis[x], key=self.space_sorting)
def Fx(self, x):
r"""
Return the list of the elements in the closure of `\lbrace x\rbrace`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Fx(2)
[2, 4]
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.2))
sage: x = random.choice(T._elements)
sage: T.is_contractible(T.Fx(x))
True
"""
result = [y for y in self._elements if x in self._minimal_basis[y]]
if result==[]:
raise ValueError("The point {} is not an element of the space".format(x))
return result
def Cx(self, x):
r"""
Return the list of the elements in the star of ``x``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Cx(2)
[5, 6, 2, 4]
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.2))
sage: x = random.choice(T._elements)
sage: T.is_contractible(T.Cx(x))
True
"""
return self.Ux(x) + self.Fx(x)[1:]
def Ux_tilded(self, x):
r"""
Return the list of the elements in `\widehat{U}_x = U_x \minus \lbrace x\rbrace`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Ux_tilded(2)
[5, 6]
"""
return self.Ux(x)[:-1]
def Fx_tilded(self, x):
r"""
Return the list of the elements in `\widehat{F}_x = F_x \minus \lbrace x\rbrace`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Fx_tilded(2)
[4]
"""
return self.Fx(x)[1:]
def Cx_tilded(self, x):
r"""
Return the list of the elements in `\widehat{C}_x = C_x \minus \lbrace x\rbrace`.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 6: {5, 6}, 3: {3, 5}, 2: {2, 5, 6}, \
4: {2, 4, 5, 6}, 1: {1, 5}}
sage: T = FiniteSpace(minimal_basis)
sage: T.Cx_tilded(2)
[5, 6, 4]
"""
return self.Ux(x)[:-1] + self.Fx(x)[1:]
def opposite(self):
r"""
Return the opposite space of ``self``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: mat_dict = {(0, 0): 1, (0, 3): 1, (0, 4): 1, (1, 1): 1, (1, 2): 1, (2, 1): 1, \
....: (2, 2): 1, (3, 3): 1, (3, 4): 1, (4, 3): 1, (4, 4): 1}
sage: T = FiniteSpace(matrix(mat_dict))
sage: T
Finite topological space of 5 points with minimal basis
{0: {0}, 1: {1, 2}, 2: {1, 2}, 3: {0, 3, 4}, 4: {0, 3, 4}}
sage: T.opposite()
Finite topological space of 5 points with minimal basis
{0: {3, 4, 0}, 1: {1, 2}, 2: {1, 2}, 3: {3, 4}, 4: {3, 4}}
sage: T.topogenous_matrix()
[1 0 0 1 1]
[0 1 1 0 0]
[0 1 1 0 0]
[0 0 0 1 1]
[0 0 0 1 1]
sage: T.opposite().topogenous_matrix()
[1 1 0 0 0]
[1 1 0 0 0]
[0 0 1 1 1]
[0 0 1 1 1]
[0 0 0 0 1]
"""
minimal_basis_op = {x:set(self.Fx(x)) for x in self._elements}
T0 = isinstance(self, FiniteTopologicalSpace_T0)
return FiniteSpace(minimal_basis_op, is_T0=T0)
def is_interior_point(self, x, E):
r"""
Return ``True`` if ``x`` is an interior point of ``E`` in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_interior_point(1, {1, 2, 3})
True
sage: T.is_interior_point(2, {1, 2, 3})
False
sage: T.is_interior_point(1, set())
False
sage: T.is_interior_point(3, T.underlying_set())
True
"""
assert x in self.underlying_set() , "Parameter 'x' must be an element of the space"
assert E <= self.underlying_set() , "Parameter 'E' must be a subset of the underlying set"
if not x in E:
return False
return self._minimal_basis[x] <= E
def interior(self, E):
r"""
Return the interior of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.interior({1, 2, 3})
{1}
sage: T.interior({1, 2, 3, 4})
{1, 2, 3, 4}
sage: T.interior({2, 3})
set()
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Int = T.interior(E)
sage: T.is_open(Int)
True
sage: T.interior(Int) == Int
True
sage: Int == X - T.closure(X - E)
True
sage: m = randint(0,len(X))
sage: M = set(random.sample(X, m))
sage: T.interior(E & M) == Int & T.interior(M)
True
"""
X = self.underlying_set()
if E == X or E == set():
return E
assert E < X , "The parameter must be a subset of the underlying set"
return set([x for x in E if self.is_interior_point(x, E)])
def is_open(self, E):
r"""
Return ``True`` if ``E`` is an open subset of the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_open({0})
False
sage: T.is_open({0, 1})
True
sage: T.is_open({0, 1, 4})
True
sage: T.is_open(set())
True
"""
return E == self.interior(E)
def is_closed(self, E):
r"""
Return ``True`` if ``E`` is a closed subset of the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace({'a':{'a','b'},'b':{'a','b'},'c':{'c','d'},'d':{'d'}})
sage: T.is_closed({'a','b','c'})
True
sage: T.is_closed({'b'})
False
"""
X = self.underlying_set()
return self.is_open(X - E)
def is_exterior_point(self, x, E):
r"""
Return ``True`` if ``x`` is an exterior point of ``E`` in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_exterior_point(1, {2, 3})
True
sage: T.is_exterior_point(3, {0, 1, 2})
False
"""
return self._minimal_basis[x].isdisjoint(E)
def exterior(self, E):
r"""
Return the exterior of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.exterior({2})
{0, 1, 4}
sage: T.exterior({2, 4})
{0, 1}
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Ext = T.exterior(E)
sage: Ext.isdisjoint(E)
True
sage: Ext == T.interior(X - E)
True
sage: Ext == X - T.closure(E)
True
sage: T.interior(E) <= T.exterior(Ext)
True
"""
X = self.underlying_set()
if E == X:
return set()
if E == set():
return X
assert E < X , "The parameter must be a subset of the underlying set"
return set([x for x in X - E if self.is_exterior_point(x, E)])
def is_boundary_point(self, x, E):
r"""
Return ``True`` if ``x`` is a boundary point of ``E`` in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_boundary_point(0, {1, 2, 3})
True
sage: T.is_boundary_point(1, {2, 3, 4})
False
"""
Ux = self._minimal_basis[x]
return bool(Ux & E) and not bool(Ux <= E)
def boundary(self, E):
r"""
Return the boundary of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.boundary({1})
{0}
sage: T.boundary({2, 3})
{2, 3}
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Fr = T.boundary(E)
sage: T.is_closed(Fr)
True
sage: Fr == T.boundary(X - E)
True
sage: Fr == T.closure(E) - T.interior(E)
True
sage: Fr == T.closure(E) & T.closure(X - E)
True
sage: T.interior(E) == E - Fr
True
sage: T.boundary(Fr) <= Fr
True
sage: T.boundary(T.boundary(Fr)) == T.boundary(Fr)
True
sage: X == Fr.union(T.interior(E), T.exterior(E))
True
"""
X = self.underlying_set()
if E == X or E == set():
return set()
assert E < X , "The parameter must be a subset of the underlying set"
return set([x for x in X if self.is_boundary_point(x, E)])
def is_limit_point(self, x, E):
r"""
Return ``True`` if ``x`` is a limit point of ``E`` in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_limit_point(0, {1})
True
sage: T.is_limit_point(1, {0, 1})
False
"""
Ux_minus_x = self._minimal_basis[x] - {x}
return not Ux_minus_x.isdisjoint(E)
def derived(self, E):
r"""
Return the derived set of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.derived({0, 1, 2})
{0, 3}
sage: T.derived({3, 4})
{2, 3}
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Der = T.derived(E)
sage: T.derived(Der) <= E.union(Der)
True
sage: T.closure(E) == E.union(Der)
True
"""
X = self.underlying_set()
if E == X or E == set():
return E
assert E < X , "The parameter must be a subset of the underlying set"
return set([x for x in X if self.is_limit_point(x, E)])
def is_closure_point(self, x, E):
r"""
Return ``True`` if ``x`` is a point of closure of ``E`` in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_closure_point(3, {1})
False
sage: T.is_closure_point(3, {1,2})
True
"""
return not self._minimal_basis[x].isdisjoint(E)
def closure(self, E):
r"""
Return the closure of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.closure({0, 2})
{0, 2, 3}
sage: T.closure({0})
{0}
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Cl = T.closure(E)
sage: T.is_closed(Cl)
True
sage: T.closure(Cl) == Cl
True
sage: Cl == X - T.interior(X - E)
True
sage: T.interior(T.boundary(Cl)) == set()
True
sage: Cl == E.union(T.boundary(E))
True
sage: m = randint(0,len(X))
sage: M = set(random.sample(X, m))
sage: T.closure(E.union(M)) == Cl.union(T.closure(M))
True
"""
X = self.underlying_set()
if E == X or E == set():
return E
assert E < X , "The parameter must be a subset of the underlying set"
return E.union(set([x for x in X - E if self.is_closure_point(x, E)]))
def is_dense(self, E):
r"""
Return ``True`` if ``E`` is dense in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1, 2}, {0, 1, 2}, {2}])
sage: T.is_dense({2})
True
sage: T.is_dense({0, 1})
False
"""
return self.closure(E) == self.underlying_set()
def is_isolated_point(self, x, E=None):
r"""
Return ``True`` if ``x`` is an isolated point of ``E`` in the finite space.
If ``E`` is ``None``, return ``True`` if ``x`` is an isolated point of
the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.is_isolated_point(0)
False
sage: T.is_isolated_point(0, {0, 2, 3, 4})
True
"""
if E:
return (self._minimal_basis[x] & E) == set([x])
else:
return self._minimal_basis[x] == set([x])
def isolated_set(self, E=None):
r"""
Return the set of isolated points of a subset in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace([{0, 1}, {1}, {2, 3, 4}, {2, 3, 4}, {4}])
sage: T.isolated_set()
{1, 4}
sage: T.isolated_set({0, 2, 3, 4})
{0, 4}
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T.underlying_set()
sage: k = randint(0,len(X))
sage: E = set(random.sample(X, k))
sage: Iso = T.isolated_set(E)
sage: T.closure(E) == Iso.union(T.derived(E))
True
"""
if E is None:
E = self.underlying_set()
return set([x for x in E if self.is_isolated_point(x, E)])
class FiniteTopologicalSpace_T0(FiniteTopologicalSpace):
r"""
Finite topological spaces satisfying the T0 separation axiom (Kolmogorov spaces).
Users should not call this directly, but instead use :func:`FiniteSpace`.
See that function for more documentation.
"""
def __init__(self, elements, minimal_basis, topogenous, poset=None):
r"""
Define a finite T0 topological space.
INPUT:
- ``elements`` -- list of the elements of the space.
- ``minimal_basis`` -- a dictionary where the values are sets representing
the minimal open sets containing the respective key.
- ``topogenous`` -- a topogenous matrix of the finite space corresponding
to the order given by ``elements`` (it is assumed upper triangular).
- ``poset`` -- a poset corresponding to the finite space (Alexandroff
correspondence) (default ``None``).
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteTopologicalSpace_T0
sage: elements = [0, 1, 2, 3]
sage: minimal_basis = {0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 3}}
sage: mat_dict = {(0, 0): 1, (0, 1): 1, (0, 2): 1, (0, 3): 1, \
....: (1, 1): 1, (1, 3): 1, (2, 2): 1, (3, 3): 1}
sage: T = FiniteTopologicalSpace_T0(elements, minimal_basis, matrix(mat_dict)); T
Finite T0 topological space of 4 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 3}}
"""
FiniteTopologicalSpace.__init__(self, elements, minimal_basis, topogenous)
if poset:
# isinstance(poset, FinitePosets)
assert hasattr(poset, '_hasse_diagram'), \
"Parameter 'poset' must be a real poset!"
# Verify the coherence of the parameters
assert set(self._elements)==set(poset.list()), \
"Elements of poset and minimal_basis do not coincide"
self._elements = poset.list()
else:
# Construct the associated poset
elmts = self._elements
f = lambda x, y: self._topogenous[elmts.index(x), elmts.index(y)]==1
poset = Poset((elmts, f), linear_extension=True)
self._poset = poset
self._T0 = True
def _repr_(self):
r"""
Print representation.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: P = Poset((divisors(6), attrcall("divides")), linear_extension=True)
sage: FiniteSpace(P)
Finite T0 topological space of 4 points with minimal basis
{1: {1}, 2: {1, 2}, 3: {1, 3}, 6: {1, 2, 3, 6}}
sage: Q = Poset((divisors(120), attrcall("divides")), linear_extension=True)
sage: FiniteSpace(Q)
Finite T0 topological space of 16 points
"""
n = self._cardinality
if n < 10:
sorted_minimal_basis = {x: sorted(self._minimal_basis[x], key=self.space_sorting)
for x in self._minimal_basis}
return "Finite T0 topological space of {} points with minimal basis \n {}" \
.format(n, sorted_minimal_basis).replace('[', '{').replace(']', '}')
else:
return "Finite T0 topological space of {} points".format(n)
def poset(self):
r"""
Return the corresponding poset of the finite space (Alexandroff correspondence).
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = ({0}, {0, 1}, {0, 1, 2}, {0, 3})
sage: T = FiniteSpace(minimal_basis) ; T
Finite T0 topological space of 4 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 3}}
sage: T.poset()
Finite poset containing 4 elements with distinguished linear extension
sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)
sage: T = FiniteSpace(P)
sage: T.poset() == P
True
"""
return self._poset
def show(self, highlighted_edges=None):
r"""
Displays the Hasse diagram of the poset ``self._poset``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: T = FiniteSpace(posets.RandomPoset(15, 0.2))
sage: T.show()
Graphics object consisting of 31 graphics primitives
"""
if highlighted_edges:
return self._poset.plot(cover_colors = {'blue': highlighted_edges})
return self._poset.plot()
def stong_matrix(self):
r"""
Return the Stong matrix of the finite `T_0` space i.e. the adjacency matrix
of the Hasse diagram of its associated poset, with ones in its diagonal.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: covers = [[9, 13], [7, 13], [4, 13], [8, 12], [7, 12], [5, 12],
....: [9, 11], [6, 11], [5, 11], [8, 10], [6, 10], [4, 10],
....: [3, 9], [2, 9], [3, 8], [2, 8], [3, 7], [1, 7], [3, 6],
....: [1, 6], [2, 5], [1, 5], [2, 4], [1, 4]]
sage: P = Poset((list(range(1,14)), covers), cover_relations=True)
sage: X = FiniteSpace(P)
sage: X.topogenous_matrix()
[1 0 1 1 0 0 0 1 1 1 1 1 1]
[0 1 1 1 0 1 1 0 1 1 0 1 1]
[0 0 1 0 0 0 0 0 1 0 0 1 0]
[0 0 0 1 0 0 0 0 0 1 0 0 1]
[0 0 0 0 1 1 1 1 1 1 1 1 1]
[0 0 0 0 0 1 0 0 1 0 0 0 1]
[0 0 0 0 0 0 1 0 0 1 0 1 0]
[0 0 0 0 0 0 0 1 1 1 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 1 1]
[0 0 0 0 0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1]
sage: X.stong_matrix()
[1 0 1 1 0 0 0 1 0 0 1 0 0]
[0 1 1 1 0 1 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 1 0 0 1 0]
[0 0 0 1 0 0 0 0 0 1 0 0 1]
[0 0 0 0 1 1 1 1 0 0 1 0 0]
[0 0 0 0 0 1 0 0 1 0 0 0 1]
[0 0 0 0 0 0 1 0 0 1 0 1 0]
[0 0 0 0 0 0 0 1 1 1 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 1 1]
[0 0 0 0 0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1]
"""
return self._poset._hasse_diagram.adjacency_matrix(sparse=True) + matrix.identity(self._cardinality)
def order_complex(self):
r"""
Return the order complex of the finite space i.e. the simplicial complex
whose simplices are the nonempty chains of ``self.poset()``.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = ({0}, {0, 1}, {0, 1, 2}, {0, 3})
sage: T = FiniteSpace(minimal_basis) ; T
Finite T0 topological space of 4 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 3}}
sage: T.order_complex()
Simplicial complex with vertex set (0, 1, 2, 3) and facets {(0, 3), (0, 1, 2)}
"""
return self._poset.order_complex()
def barycentric_subdivision(self):
r"""
Return the barycentric subdivision of the finite space i.e. the face poset
of its order complex.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = ({0}, {0, 1}, {0, 1, 2}, {0, 3})
sage: T = FiniteSpace(minimal_basis) ; T
Finite T0 topological space of 4 points with minimal basis
{0: {0}, 1: {0, 1}, 2: {0, 1, 2}, 3: {0, 3}}
sage: T.barycentric_subdivision()
Finite T0 topological space of 9 points with minimal basis
{(3,): {(3,)}, (2,): {(2,)}, (1,): {(1,)}, (1, 2): {(2,), (1,), (1, 2)},
(0,): {(0,)}, (0, 1): {(1,), (0,), (0, 1)}, (0, 2): {(2,), (0,), (0, 2)},
(0, 1, 2): {(2,), (1,), (1, 2), (0,), (0, 1), (0, 2), (0, 1, 2)},
(0, 3): {(3,), (0,), (0, 3)}}
"""
return FiniteSpace(self._poset.order_complex().face_poset(), is_T0=True)
def is_down_beat_point(self, x, subspace=None):
r"""
Return ``True`` if ``x`` is a down beat point of the subspace of ``self``
determined by ``subspace``.
INPUT:
- ``x`` - an element of the finite space. In case ``subspace`` is not
``None``, `x`` must be one of its elements.
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 4}, 3: {1, 3, 4}}
sage: T = FiniteSpace(minimal_basis)
sage: T.is_down_beat_point(6)
False
sage: T.is_down_beat_point(6, [3, 4, 5, 6])
True
"""
xindex = self._elements.index(x)
if subspace is None:
subspaceindex = [i for i in range(xindex - 1,-1,-1) \
if self._topogenous[i, xindex]==1]
else:
sortsubspace = sorted(subspace, key=self._elements.index, reverse=True)
subspaceindex = [self._elements.index(i) for i in sortsubspace \
if self._topogenous[self._elements.index(i), xindex]==1 \
and self._elements.index(i)!=xindex]
if subspaceindex==[]:
return False
maximal = subspaceindex[0]
for i in subspaceindex:
if not self._topogenous[i, maximal]==self._topogenous[i, xindex]:
return False
return True
def is_up_beat_point(self, x, subspace=None):
r"""
Return ``True`` if ``x`` is an up beat point of the subspace of ``self``
determined by ``subspace``.
INPUT:
- ``x`` - an element of the finite space. In case ``subspace`` is not
``None``, `x`` must be one of its elements.
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 4}, 3: {1, 3, 4}}
sage: T = FiniteSpace(minimal_basis)
sage: T.is_up_beat_point(4)
False
sage: T.is_up_beat_point(4, [1, 2, 3, 4, 5])
True
"""
xindex = self._elements.index(x)
if subspace is None:
subspaceindex = [j for j in range(xindex + 1, self._cardinality) \
if self._topogenous[xindex, j]==1]
else:
sortsubspace = sorted(subspace, key=self._elements.index)
subspaceindex = [self._elements.index(i) for i in sortsubspace \
if self._topogenous[xindex, self._elements.index(i)]==1 \
and self._elements.index(i)!=xindex]
if subspaceindex==[]:
return False
minimal = subspaceindex[0]
for j in subspaceindex:
if not self._topogenous[minimal, j]==self._topogenous[xindex, j]:
return False
return True
def is_beat_point(self, x, subspace=None):
r"""
Return ``True`` if ``x`` is a beat point of the subspace of ``self``
determined by ``subspace``.
INPUT:
- ``x`` - an element of the finite space. In case ``subspace`` is not
``None``, `x`` must be one of its elements.
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 4}, 3: {1, 3, 4}}
sage: T = FiniteSpace(minimal_basis)
sage: T.is_beat_point(2)
True
sage: T.is_beat_point(2, [2, 3, 4, 5])
False
"""
if self._elements.index(x) < self._cardinality / 2:
return self.is_down_beat_point(x, subspace) or self.is_up_beat_point(x, subspace)
else:
return self.is_up_beat_point(x, subspace) or self.is_down_beat_point(x, subspace)
def core_list(self, subspace=None):
r"""
Return a list of elements in a core of the subspace of ``self`` determined
by ``subspace``.
INPUT:
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {4, 5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 2, 4}, 3: {1, 2, 4, 3}}
sage: T = FiniteSpace(minimal_basis)
sage: T.core_list()
[2, 4, 6, 3]
sage: T.core_list([3, 2, 1, 4, 5, 6])
[2, 1, 4, 6]
sage: T.core_list([1, 2, 3, 4, 5])
[5]
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.2))
sage: X = T._elements
sage: k = randint(0,len(X))
sage: E1 = random.sample(X, k)
sage: E2 = random.sample(E1, k)
sage: len(T.core_list(E1)) == len(T.core_list(E2)) # cores are homeomorphic
True
"""
if subspace is None:
subspace = self._elements
beatpoint = None
for x in subspace:
if self.is_beat_point(x, subspace):
beatpoint = x
break
if beatpoint is None:
return subspace
else:
return self.core_list([y for y in subspace if y != beatpoint])
def core(self, subspace=None):
r"""
Return a core of the subspace of ``self`` determined by ``subspace``.
INPUT:
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {4, 5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 2, 4}, 3: {1, 2, 4, 3}}
sage: T = FiniteSpace(minimal_basis)
sage: T.core()
Finite T0 topological space of 4 points with minimal basis
{2: {2}, 3: {2, 4, 3}, 4: {4}, 6: {2, 4, 6}}
sage: T.core([3,2,1,4,5,6])
Finite T0 topological space of 4 points with minimal basis
{1: {2, 4, 1}, 2: {2}, 4: {4}, 6: {2, 4, 6}}
sage: T.core([1,2,3,4,5])
Finite T0 topological space of 1 points with minimal basis
{5: {5}}
"""
return self.subspace(self.core_list(subspace), is_T0=True)
def is_contractible(self, subspace=None):
r"""
Return ``True`` if the finite space is contractible (in the setting of finite spaces,
this is equivalent to say that its cores are singletons).
INPUT:
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {5: {4, 5}, 4: {4}, 2: {2}, 6: {2, 4, 6}, \
1: {1, 2, 4}, 3: {1, 2, 4, 3}}
sage: T = FiniteSpace(minimal_basis)
sage: T.is_contractible()
False
sage: T.is_contractible([1,2,3,4,5])
True
TESTS::
sage: import random
sage: P = posets.RandomPoset(20, 0.5)
sage: X = P.list()
sage: k = randint(0,len(X))
sage: E = random.sample(X, k)
sage: S = P.subposet(E)
sage: F = FiniteSpace(S)
sage: S.has_top()==False or F.is_contractible()
True
sage: S.has_bottom()==False or F.is_contractible()
True
"""
return len(self.core_list(subspace))==1
def is_weak_point(self, x, subspace=None):
r"""
Return ``True`` if ``x`` is a weak beat point of the subspace of ``self``
determined by ``subspace``.
INPUT:
- ``x`` - an element of the finite space. In case ``subspace`` is not
``None``, `x`` must be one of its elements.
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {2: {2}, 5: {2, 5}, 1: {1}, 3: {1, 2, 3}, \
4: {1, 2, 4}, 7: {1, 2, 3, 4, 7}, \
6: {1, 2, 3, 4, 5, 6, 7}, \
8: {1, 2, 3, 4, 5, 6, 7, 8}}
sage: T = FiniteSpace(minimal_basis)
sage: T.is_beat_point(1)
False
sage: T.is_weak_point(1)
True
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.2))
sage: X = T._elements
sage: k = randint(0,len(X))
sage: E = random.sample(X, k)
sage: x = random.choice(E)
sage: T.is_beat_point(x, E)==False or T.is_beat_point(x, E)==T.is_weak_point(x, E)
True
"""
subspaceU = self.Ux_tilded(x)
subspaceF = self.Fx_tilded(x)
if subspace is not None:
subspaceU = list(set(subspaceU) & set(subspace))
subspaceF = list(set(subspaceF) & set(subspace))
if self._elements.index(x) < self._cardinality / 2:
return self.is_contractible(subspaceU) or self.is_contractible(subspaceF)
else:
return self.is_contractible(subspaceF) or self.is_contractible(subspaceU)
def weak_core_list(self, subspace=None):
r"""
Return a list of elements in a weak core (finite space with no weak points)
of the subspace of ``self`` determined by ``subspace``.
INPUT:
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {2: {2}, 5: {2, 5}, 1: {1}, 3: {1, 2, 3}, \
4: {1, 2, 4}, 7: {1, 2, 3, 4, 7}, \
6: {1, 2, 3, 4, 5, 6, 7}, \
8: {1, 2, 3, 4, 5, 6, 7, 8}}
sage: T = FiniteSpace(minimal_basis)
sage: T.weak_core_list()
[8]
sage: T.weak_core_list([1,2,3,4,5])
[1, 2, 3, 4]
TESTS::
sage: import random
sage: T = FiniteSpace(posets.RandomPoset(30, 0.5))
sage: X = T._elements
sage: k = randint(0,len(X))
sage: E = random.sample(X, k)
sage: len(T.weak_core_list(E)) <= len(T.core_list(E))
True
"""
realsubspace = subspace or self._elements
weakpoint = None
for x in realsubspace:
if self.is_beat_point(x, subspace) or self.is_weak_point(x, subspace):
weakpoint = x
break
if weakpoint is None:
return realsubspace
else:
return self.weak_core_list([y for y in realsubspace if y != weakpoint])
def weak_core(self, subspace=None):
r"""
Return a weak core (finite space with no weak points) of the subspace of
``self`` determined by ``subspace``.
INPUT:
- ``subspace`` -- (default ``None``) a list of elements in the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: minimal_basis = {2: {2}, 5: {2, 5}, 1: {1}, 3: {1, 2, 3}, \
4: {1, 2, 4}, 7: {1, 2, 3, 4, 7}, \
6: {1, 2, 3, 4, 5, 6, 7}, \
8: {1, 2, 3, 4, 5, 6, 7, 8}}
sage: T = FiniteSpace(minimal_basis)
sage: T.weak_core()
Finite T0 topological space of 1 points with minimal basis
{8: {8}}
sage: T.weak_core([1,2,3,4,5])
Finite T0 topological space of 4 points with minimal basis
{1: {1}, 2: {2}, 3: {1, 2, 3}, 4: {1, 2, 4}}
"""
return self.subspace(self.weak_core_list(subspace), is_T0=True)
def discrete_vector_field(self, h_admissible=None):
r"""
Return a discrete vector field on the finite `T_0` space i.e. a homologically
admissible Morse matching on the Hasse diagram of the associated poset.
INPUT:
- ``h_admissible`` -- (default ``None``) If it is ``True``, all the edges
`(x, y)` of the Hasse diagram are assumed to be homologically admissible
i.e. tha subspace `\widehat{U}_y - \lbrace x\rbrace` is homotopically
trivial (this can be assumed when the finite space is a barycentric
subdivision).
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: Pcovers = [[1, 2], [2, 3], [3, 4], [3, 5], [4, 6], [5, 6], [6, 7],
....: [6, 8], [8, 9], [9, 10], [1, 11], [7, 12], [9, 12],
....: [7, 13], [10, 13], [11, 13], [8, 15], [7, 16], [8, 16],
....: [11, 16], [15, 17], [2, 19], [6, 20], [18, 20]]
sage: P = Poset((list(range(1,21)), Pcovers), cover_relations=True)
sage: X = FiniteSpace(P)
sage: dvf = X.discrete_vector_field(); dvf
[(2, 3), (4, 6), (8, 9), (7, 12), (15, 17), (18, 20), (10, 13), (11, 16)]
sage: X.show(dvf)
Graphics object consisting of 45 graphics primitives
sage: Qcovers = [[1, 2], [2, 3], [3, 4], [3, 5]]
sage: Q = Poset((list(range(1,6)), Qcovers), cover_relations=True)
sage: Y = FiniteSpace(Q)
sage: Z = Y.barycentric_subdivision()
sage: dvf = Z.discrete_vector_field(h_admissible=True)
sage: Z.show(dvf)
Graphics object consisting of 71 graphics primitives
"""
kenzo_top = s2k_binary_matrix_sparse(self._topogenous)
kenzo_dvfield = EclListIterator(__dvfield_aux__(kenzo_top, None, h_admissible))
result = []
for vector in kenzo_dvfield:
vectorpy = vector.python()
result.append((self._elements[vectorpy[0]-1], self._elements[vectorpy[1]-1]))
return result
def hregular_homology(self, deg=None, dvfield=None):
r"""
The homology of an h-regular finite space.
INPUT:
- ``deg`` -- an element of the grading group for the chain
complex (default ``None``); the degree in which
to compute homology -- if this is ``None``, return the
homology in every degree in which the chain complex is
possibly nonzero.
- ``dvfield`` -- (default ``None``) a list of edges representing a discrete
vector field on the finite space.
EXAMPLES::
sage: from sage.homology.finite_topological_spaces import FiniteSpace
sage: covers = [[9, 13], [7, 13], [4, 13], [8, 12], [7, 12], [5, 12], [9, 11],
....: [6, 11], [5, 11], [8, 10], [6, 10], [4, 10], [3, 9], [2, 9],
....: [3, 8], [2, 8], [3, 7], [1, 7], [3, 6], [1, 6], [2, 5], [1, 5],
....: [2, 4], [1, 4]]
sage: P = Poset((list(range(1,14)), covers), cover_relations = True)
sage: X = FiniteSpace(P)
sage: X.hregular_homology()
{0: Z, 1: C2, 2: 0}
sage: dvf = X.discrete_vector_field()
sage: X.show(dvf)
Graphics object consisting of 38 graphics primitives
sage: X.hregular_homology(dvfield = dvf)
{0: Z, 1: C2, 2: 0}
"""
assert deg==None or deg.is_integer(), "The degree must be an integer number or None"
height = self._poset.height()
if deg and (deg < 0 or deg >= height):
return HomologyGroup(0, ZZ)
kenzo_stong = s2k_binary_matrix_sparse(self.stong_matrix())
if dvfield:
kenzo_targets = EclObject([self._elements.index(edge[1])+1 for edge in dvfield])
kenzo_sources = EclObject([self._elements.index(edge[0])+1 for edge in dvfield])
matrices = __h_regular_dif_dvf_aux__(kenzo_stong, kenzo_targets, kenzo_sources)
else:
matrices = __h_regular_dif__(kenzo_stong)
if deg is not None:
if deg == height - 1:
M1 = __copier_matrice__(kenzo.__nth__(height-1, matrices))
return quotient_group_matrices(M1, right_null=True)
else:
M1 = __copier_matrice__(kenzo.__nth__(deg, matrices))
M2 = __copier_matrice__(kenzo.__nth__(deg+1, matrices))
return quotient_group_matrices(M1, M2, check=False)
else:
result = {}
for dim in range(0, height - 1):
M1 = __copier_matrice__(kenzo.__nth__(dim, matrices))
M2 = __copier_matrice__(kenzo.__nth__(dim+1, matrices))
result[dim] = quotient_group_matrices(M1, M2, check=False)
Mh = __copier_matrice__(kenzo.__nth__(height-1, matrices))
result[height-1] = quotient_group_matrices(Mh, right_null=True)
return result
|
8529374df4895a7013a341c97bb797e53290b5cc
|
karankrw/LeetCode-Challenge-June-20
|
/Week 3/Search_in_BST.py
| 1,591
| 4.09375
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 01:12:08 2020
@author: karanwaghela
"""
"""
Given the root node of a binary search tree (BST) and a value.
You need to find the node in the BST that the node's value equals the given value.
Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2
You should return this subtree:
2
/ \
1 3
In the example above, if we want to search the value 5,
since there is no node with value 5, we should return NULL.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
#Recursive
if root == None:
return None
if root.val == val:
return root
if root.val > val:
return self.searchBST(root.left, val)
return self.searchBST(root.right, val)
#Iterative
curr = root
while curr != None:
if curr.val == val:
return curr
if curr.val > val:
curr = curr.left
else:
curr = curr.right
return curr
|
bc87113f0c65a138e7d5e0c205297285f90453c7
|
yamadathamine/300ideiasparaprogramarPython
|
/008 Controle de tela/menu.py
| 662
| 4.25
| 4
|
# encoding: utf-8
# usando python 3
# Menu posicionado - Implemente um programa que mostra um menu a partir de uma linha lida do teclado
import os
os.system('clear')
linha = int(input("Digite a linha: "))
coluna = int(input("Digite a coluna: "))
print("\033["+str(linha)+";"+str(coluna)+"H Menu relatórios")
linha += 1
print("\033["+str(linha)+";"+str(coluna)+"H 1 - Por nome")
linha += 1
print("\033["+str(linha)+";"+str(coluna)+"H 2 - Por código")
linha += 1
print("\033["+str(linha)+";"+str(coluna)+"H 3 - Por data")
linha += 1
print("\033["+str(linha)+";"+str(coluna)+"H 4 - Fim")
linha += 2
teste=input("\033["+str(linha)+";"+str(coluna)+"HOpção: ")
|
3f17f8f241e1955c667cee7d5bf34276ad4f294c
|
mottaquikarim/pydev-psets
|
/pset_challenging_ext/exercises/solutions/p45.py
| 451
| 4.09375
| 4
|
"""
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
"""
"""Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
Hints:
Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.
"""
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print evenNumbers
|
7a296304e3146720199718e0f0b322b6a704c5d8
|
maurovasconcelos/Ola-Mundo
|
/Python/ex112/utilidadescev/moeda/__init__.py
| 1,498
| 3.953125
| 4
|
def aumentar(preco = 0, taxa = 0, formato=False):
'''
-> Calcula o aumento de um determinado preço,
retornando o resultado com ou sem formatação.
:param preco: o preço que se quer reajustar.
:param taxa: qual é a porcentagem do aumento.
:param formato: quer a saida formatada ou nao ?
:return: o valor reajustado, com ou sem formato.
'''
res = preco + (preco * taxa/100)
return res if formato is False else moeda(res) # retorne o res se o format for falso, se nao, chame o metodo moeda
def diminuir(preco = 0, taxa = 0, formato=False):
res = preco - (preco * taxa/100)
return res if formato is False else moeda(res)
def dobro(preco = 0, formato=False):
res = preco * 2
return res if formato is False else moeda(res)
def metade(preco = 0, formato=False):
res = preco / 2
return res if formato is False else moeda(res)
def moeda(preco = 0, moeda = 'R$'):
return f'{moeda}{preco:.2f}'.replace('.',',') # linha pra formatação bonitinha
def resumo(preco=0, taxaau=10, taxar=5):
print('-' * 30)
print('RESUMO DO VALOR'.center(30))
print('-' * 30)
print(f'Preço analisado: \t{moeda(preco)}')
print(f'Dobro do preço: \t{dobro(preco, True)}')
print(f'Metade do preço: \t{metade(preco, True)}')
print(f'Com {taxaau}% de aumento: \t{aumentar(preco, taxaau, True)}') # \t tabulaçao = ficar bonitinho
print(f'Com {taxar}% de redução: \t{diminuir(preco, taxar, True)}')
print('-' * 30)
|
d6a89112d0378a05a995a00072e35dcc957cf94d
|
JonathanAngelesV/EstructuradeDatos---Unidad2
|
/Examen Unidad 2 - Ejercicio 2.py
| 313
| 3.96875
| 4
|
#Forma recursiva de elevar 2 a la n potencia
#Angeles Valadez Jonathan - 15211883
#Fecha: 10/5/2018
def potencia(numero):
potenciaN = input("A que potencia deseas elevar 2?: ")
Num = int(potenciaN)
operacion = pow(2,Num)
print(str(operacion))
print(" ")
potencia(numero)
potencia(0)
|
faf546c308d6aff54b2ff341883c94005e54263b
|
lucasharzer/Teste_Python
|
/ex3.py
| 162
| 3.9375
| 4
|
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1+n2)/2
print('A média das duas notas é igual a {}'.format(m))
|
1f61f5abb842126258a989d0f22d471a5bb687b6
|
ziyadalvi/PythonBook
|
/5Numeric Types/7Comparisions(Normal and Chained).py
| 927
| 3.921875
| 4
|
#Comparisions:Normal and Chained
print(1<2)
print(2.0 >= 1) #mixed types are allowed in numeric expressions (only)
print(2.0 == 2.0)
print(2.0 != 2.0)
#Python also allows us to chain multiple comparisons together to perform
#range tests. Chained comparisons are a sort of shorthand for larger Boolean expressions.
X = 2
Y = 4
Z = 6
print(X < Y < Z)
print(X < Y and Y < Z)
print(X < Y > Z)
print(X < Y and Y > Z)
print(1 < 2 < 3.0 < 4)
print(1 > 2 > 3.0 > 4)
print(1 == 2 < 3) #Same as: 1 == 2 and 2 < 3
# Not same as: False < 3 (which means 0 < 3, which is true!)
#numeric comparisons are based
#on magnitudes, which are generally simple—though floating-point numbers may not
#always work as you’d expect
print(1.1 + 2.2 == 3.3)
#Prints out false due to the fact that floating-point numbers cannot represent some values
#exactly due to their limited number of bits—
print(1.1 + 2.2)
#3.3000000000000003 not 3.3
|
c8f9cdd9cf855801112ef8da11567e1ae95ad916
|
shahidshabir055/python_programs
|
/leapyears.py
| 430
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 11:35:39 2019
@author: eshah
"""
def find_leap_years(given_year):
# Write your logic here
leap=[]
while(len(leap)<=15):
if((given_year%4==0 and given_year%100!=0) or given_year%400==0):
leap.append(given_year)
given_year=given_year+4
return leap
list_of_leap_years=find_leap_years(2000)
print(list_of_leap_years)
|
2710406174139c89f526ed98855d883089c7d41d
|
RamonFidencio/exercicios_python
|
/EX044.py
| 450
| 3.515625
| 4
|
preco= float (input ("Preço: "))
pag = int(input('Pagemnto: \n1 - A vista (10%' 'de desconto)\n2- Cartão 1x (5%' 'de desconto)\n3- Cartão 2x (Preço normal)\n4- Cartão 3x (20%' 'de Acrescimo)\n'))
if pag == 1:
print('Você pagará: {}'.format(preco*0.9))
elif pag == 2:
print('Você pagará: {}'.format(preco*0.95))
elif pag ==3:
print('Você pagará: {}'.format(preco))
elif pag ==4:
print('Você pagará: {}'.format(preco*1.2))
|
c76cebf6bcc8d369ba71ca3a8b9c7b0c065eaa65
|
nishantk2106/python_more-learning
|
/pairwithgivensum.py
| 364
| 3.8125
| 4
|
# Find pair with given sum in the array
from array import *
def sum(ar,arr_size,s):
for i in range(arr_size):
for j in range(i+1,arr_size):
if (ar[i]+ar[j]==s):
print(ar[i],ar[j])
else:
print("there is no match with the sum")
#
ar=[1,2,2,3,4,4,5,6,7,7]
s=10
arr_size=len(ar)
sum(ar,arr_size,s)
|
d1982a2610c4dbcf7130c841b44f646dc8b7804d
|
RishitAghera/internship
|
/python/scrabble-score/scrabble_score.py
| 541
| 3.5625
| 4
|
def score(word):
s1=["A", "E", "I", "O","U", "L", "N", "R","S", "T"]
s2=["D","G"]
s3=["B","C","M","P"]
s4=["F","H","V","W","Y"]
s5=["J","X"]
s6=["Q","Z"]
cnt=0
for i in word.upper():
if(i in s1):
cnt+=1
elif(i in s2):
cnt+=2
elif(i in s3):
cnt+=3
elif(i in s4):
cnt+=4
elif(i in s5):
cnt+=8
elif(i in s6):
cnt+=10
else:
cnt+=5
return cnt
# print(score("abc"))
|
4a4bedebb70de3935d1b40862b43b6bba2013ca7
|
TanjillaTina/Python-for-Data-Science
|
/Week1/PythonObjectsAndMaps.py
| 2,226
| 4.0625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 12:01:47 2017
In The name of Allah,The Beneficent and The Merciful
@author: TINA
advanced Python Objects and Maps
"""
##Objects in Python don't have any private or protected members,if u instantiate a class u can have access to the entire class
class Person:
department="Computer Science and Engineering"
name=None
location=None
def set_name(self,new_name):
self.name=new_name
def set_Location(self,new_location):
self.location=new_location
########Map function is one of the basis for the "Funtional Programming" in Python
'''
The map function is one of the basis for functional programming in Python. Functional programming is a programming paradigm in which you explicitly declare all parameters which could change through execution of a given function.
Thus functional programming is referred to as being side-effect free, because there is a software contract that describes what can actually change by calling a function.
Now, Python isn't a functional programming language in the pure sense. Since you can have many side effects of functions, and certainly you don't have to pass in the parameters of everything that you're interested in changing.
'''
'''
So, functional programming methods are often used in Python,
and it's not uncommon to see a parameter for a function, be a function itself.
The map built-in function is one example of a functional programming feature of Python,
that I think ties together a number of aspects of the language. The map function signature looks like this
'''
store1={27,56,23,55,99}
store2={43,65,12,33,65}
cheapSet=map(min,store1,store2)
print(cheapSet) ##Map function always returns a map Object
for i in cheapSet:
print(i)
#######
'''
here is a list of Faculty teaching,
write a function and apply it writing a map() to get the faculty titles and last names
'''
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
title = person.split()[0]
lastname = person.split()[-1]
return '{} {}'.format(title, lastname)
li=list(map(split_title_and_name, people))
for i in li:
print(i)
|
f68d8f476a92e6b42b2b4277f75bb6c41d8dbad2
|
fleetster22/silentAuction
|
/main.py
| 2,940
| 3.859375
| 4
|
# Day 9 of 100 Days of Code - The Complete Python Pro Bootcamp for 2021
from time import sleep
from art import logo
# programming_dictionary = {
# "Bug": "A spider in your computer",
# "Function": "A piece of code that you can easily call repeatedly",
# "Loop": "The action of doing something repeatedly",
# }
# programming_dictionary["Nested"] = "A unit of code that is fully contained under another unit of code"
# print(programming_dictionary["Function"])
# edit an entry
# programming_dictionary["Bug"] = "An error in a program that prevents the program from running as expected"
# print(programming_dictionary)
# for key in programming_dictionary:
# print(key)
# print(programming_dictionary[key])
# student_scores = {
# "Harry": 81,
# "Ron": 78,
# "Hermione": 99,
# "Draco": 74,
# "Neville": 62,
# }
#
# student_grades = {}
#
# for student in student_scores:
# if 90 < student_scores[student] <= 100:
# student_grades[student] = "Outstanding"
# elif 80 < student_scores[student] <= 90:
# student_grades[student] = "Exceeds Expectations"
# elif 70 < student_scores[student] <= 80:
# student_grades[student] = "Acceptable"
# else:
# student_grades[student] = "Fail"
#
# print(student_grades)
# Nesting Lists and Dictionaries
# travel_log = [
# {
# "country": "France",
# "cities_visited": ["Paris", "Lille", "Trier", "Dijon"],
# "total_visits": 12
# },
# {
# "country": "Germany",
# "cities_visited": ["Landstuhl", "Stuttgart", "Hamburg"],
# "total_visits": 30
# },
# {
# "country": "New Zealand",
# "cities_visited": ["Auckland", "Rotorua", "Taupo"],
# "total_visits": 1
# },
# ]
#
#
# def add_new_country(name, city, visits):
# new_country = {}
# new_country["country"] = name
# new_country["cities_visited"] = city
# new_country["total_visits"] = visits
# travel_log.append(new_country)
#
#
# add_new_country("Russia", ["Moscow", "Saint Petersburg"], 2)
# print(travel_log)
print(logo)
sleep(0.75)
print("Welcome to the Silent Auction Program.")
sleep(0.5)
bids = {}
end_of_bids = False
def highest_bidder(bidding_war):
highest_bid = 0
winner = ""
for bidder in bidding_war:
bid_amt = bidding_war[bidder]
if bid_amt > highest_bid:
highest_bid = bid_amt
winner = bidder
print(f"The winner of this item is {winner} with a bid of ${highest_bid}")
while not end_of_bids:
name = input("What is your name?\n")
sleep(0.15)
print(f"Welcome, {name}")
sleep(0.5)
bid = int(input("What is your bid on this item? \n$"))
bids[name] = bid
other_bidders = input("Are there any other bidders? Type 'yes' or 'no'\n")
if other_bidders.lower() == 'no':
end_of_bids = True
highest_bidder(bids)
else:
end_of_bids == "yes"
|
883a66d3cfd1562a6500ce1045be029445cba060
|
saleed/LeetCode
|
/365_best.py
| 947
| 3.546875
| 4
|
class Solution(object):
def canMeasureWater(self, jug1Capacity, jug2Capacity, targetCapacity):
"""
:type jug1Capacity: int
:type jug2Capacity: int
:type targetCapacity: int
:rtype: bool
"""
vis=set()
return self.dfs(jug1Capacity,jug2Capacity,0,0,targetCapacity,vis)
def dfs(self,x,y,xremain,yremain,target,vis):
if xremain>x or yremain>y or xremain<0 or yremain<0:
return False
if xremain==target or yremain==target or yremain+xremain==target:
return True
if (xremain,yremain) in vis:
return False
vis.add((xremain,yremain))
return self.dfs(x,y,x,yremain,target,vis) or self.dfs(x,y,xremain,y,target,vis) or self.dfs(x,y,0,yremain,target,vis) \
or self.dfs(x,y,xremain,0,target,vis) or self.dfs(x,y,xremain-yremain,0,target,vis) or self.dfs(x,y,0,yremain-xremain,target,vis)
|
0f145eed10730f52dd0311db4c7987842a3f8327
|
Maerig/advent_of_code_2017
|
/day8/condition.py
| 776
| 3.734375
| 4
|
class Condition(object):
def __init__(self, register, operator, operand):
self.register = register
self.operator = operator
self.operand = int(operand)
def is_valid(self, registers):
register_value = registers[self.register]
if self.operator == '<':
return register_value < self.operand
elif self.operator == '<=':
return register_value <= self.operand
elif self.operator == '>=':
return register_value >= self.operand
elif self.operator == '>':
return register_value > self.operand
elif self.operator == '==':
return register_value == self.operand
elif self.operator == '!=':
return register_value != self.operand
|
591dc8ffbf7da8a52b6001d15220fcb72dff51a6
|
evanmiles/sure-awesome
|
/volAreaSphere.py
| 547
| 4.65625
| 5
|
#volAreaSphere.py
# 1.1 This program calculates the volume and surface area of a sphere using radius input by the user.
#import math package to use math.pi for the value of PI
import math
#take radius of the sphere from user
r=float(input("Enter the radius of the sphere"))
#calculate the surface area of sphere
s_area= 4 * math.pi * pow(r,2)
#calculate the volume of sphere
volume= (4/3) * math.pi * pow(r,3)
#print the output
print("The surface area of the sphere wll be %.2f" %s_area)
print("The volume of the sphere will be %.2f" %volume)
|
3fa362226a5a33dfc89978a0c05e62c719d22dcb
|
MichalWlodarek/Tic-Tac-Toe
|
/TTT.py
| 6,232
| 4.0625
| 4
|
import tkinter.messagebox
try:
import tkinter
except ImportError:
import Tkinter as tkinter
# Declaring button's functions. Empty button when pressed will display 'X', click will turn to False and the next
# button press will produce a 'O' and the click will turn back to True. Count is used to determine whether the match
# was a draw or not. After each button press the game will run through the winning condition function.
def buttonAction(button):
global click, count
if button["text"] == "" and click == True:
button["text"] = "X"
click = False
count += 1
winningCondition()
elif button["text"] == "" and click == False:
button["text"] = "O"
click = True
count += 1
winningCondition()
else:
tkinter.messagebox.showinfo("Tic-Tac-Toe", "This button has already been used!")
# The winning condition function simply checks all possible combinations which allow the player to win with.
def winningCondition():
global countWin, countWinb
if (button1["text"] == "X" and button4["text"] == "X" and button7["text"] == "X" or
button2["text"] == "X" and button5["text"] == "X" and button8["text"] == "X" or
button3["text"] == "X" and button6["text"] == "X" and button9["text"] == "X" or
button1["text"] == "X" and button2["text"] == "X" and button3["text"] == "X" or
button4["text"] == "X" and button5["text"] == "X" and button6["text"] == "X" or
button7["text"] == "X" and button8["text"] == "X" and button9["text"] == "X" or
button1["text"] == "X" and button5["text"] == "X" and button9["text"] == "X" or
button3["text"] == "X" and button5["text"] == "X" and button7["text"] == "X"):
tkinter.messagebox.showinfo("Tic-Tac-Toe", "Player 1 Wins")
countWin += 1
playerA.set(countWin)
elif (button1["text"] == "O" and button4["text"] == "O" and button7["text"] == "O" or
button2["text"] == "O" and button5["text"] == "O" and button8["text"] == "O" or
button3["text"] == "O" and button6["text"] == "O" and button9["text"] == "O" or
button1["text"] == "O" and button2["text"] == "O" and button3["text"] == "O" or
button4["text"] == "O" and button5["text"] == "O" and button6["text"] == "O" or
button7["text"] == "O" and button8["text"] == "O" and button9["text"] == "O" or
button1["text"] == "O" and button5["text"] == "O" and button9["text"] == "O" or
button3["text"] == "O" and button5["text"] == "O" and button7["text"] == "O"):
tkinter.messagebox.showinfo("Tic-Tac-Toe", "Player 2 Wins")
countWinb += 1
playerB.set(countWinb)
elif count == 9:
tkinter.messagebox.showinfo("Tic-Tac-Toe", "DRAW!")
# Restart function will reset the game board but not the scores. It will destroy the frame with buttons and then
# reinitialise the frame.
def restart():
global bFrame, count, click
bFrame.destroy()
bFrame = tkinter.Frame(mainWindow)
bFrame.grid(row=0, column=0, columnspan=3, rowspan=3)
count = 0
click = True
create()
# Creates all the buttons and puts them in a frame
def create():
global button1, button2, button3, button4, button5, button6, button7, button8, button9
button1 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button1))
button1.grid(row=0, column=0)
button2 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button2))
button2.grid(row=0, column=1)
button3 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button3))
button3.grid(row=0, column=2)
button4 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button4))
button4.grid(row=1, column=0)
button5 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button5))
button5.grid(row=1, column=1)
button6 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button6))
button6.grid(row=1, column=2)
button7 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button7))
button7.grid(row=2, column=0)
button8 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button8))
button8.grid(row=2, column=1)
button9 = tkinter.Button(bFrame, text="", font='Arial 20 bold', bg='light blue', fg='black', height=5, width=10, command=lambda: buttonAction(button9))
button9.grid(row=2, column=2)
mainWindow = tkinter.Tk()
mainWindow.title("Tic-Tac-Toe")
mainWindow.configure(background="dark blue")
button = tkinter.StringVar()
playerA = tkinter.IntVar()
playerB = tkinter.IntVar()
count = 0
countWin = 0
countWinb = 0
click = True
# Keeps track of the player's score
labelA = tkinter.Label(mainWindow, text="Player 1:", font='Arial 20 bold', background="dark blue", fg='white', height=1, width=6)
labelA.grid(row=4, column=0)
label1 = tkinter.Label(mainWindow, textvariable=playerA, font='Arial 20 bold', fg="black")
label1.grid(row=4, column=1)
labelB = tkinter.Label(mainWindow, text="Player 2:", font='Arial 20 bold', background="dark blue", fg='white', height=1, width=6)
labelB.grid(row=5, column=0)
label2 = tkinter.Label(mainWindow, textvariable=playerB, font='Arial 20 bold', fg="black")
label2.grid(row=5, column=1)
button10 = tkinter.Button(mainWindow, text="Reset", font='Arial 20 bold', bg='black', fg='white', height=2, width=10, command=restart)
button10.grid(row=4, column=2, sticky="en")
bFrame = tkinter.Frame(mainWindow)
bFrame.grid(row=0, column=0, columnspan=3, rowspan=3)
create()
mainWindow.mainloop()
|
8abf0ca4f47c373e88ebf9e56228f6a20ccb5786
|
xuan-linker/linker-python-study
|
/basic/Basic_Dictionary.py
| 750
| 3.796875
| 4
|
# Dictionary like Java's map
dict = {}
dict['one'] = "1 - Linker"
dict[2] = "2 - xlccc"
testDict = {'name': 'linker', 'web': 'xlccc', 'macro': 'micro'}
print(dict['one'])
print(dict[2])
print(testDict)
print(testDict.keys())
print(testDict.values())
testDict = ([('Xlccc', 1), ('Google', 2), ('Taobao', 3)])
print(testDict)
testDict = {x: x ** 2 for x in (2, 4, 6)}
print(testDict)
testDict = ([('Xlccc', 1), ('Google', 2), ('Taobao', 3)])
testDict2 = dict.fromkeys(testDict)
print(testDict2)
testDict2 = testDict.copy()
print(testDict2)
testDict = ([('Xlccc', 1), ('Google', 2), ('Taobao', 3)])
# print(testDict.get('Xlccc'))
print("---")
dict.setdefault("hello", "world")
testDict = dict
print(testDict)
testDict.clear()
print(testDict)
|
d2f1e3783f9f44df4f13e0c2cbe7c2a2807c7fa6
|
toadereandreas/Babes-Bolyai-University
|
/1st semester/Fundamentals-of-programming/Assignment 2/Complex_Number.py
| 18,273
| 4.46875
| 4
|
import math
def create_complex_number(a, b ):
'''
Function that creates a complex number c given its real part a and imaginary part b.
c = a + ib with a, b € R.
Input : a, b
Preconditions : a, b - are float
Output : c
Postconditions : c - complex number
the real part of c = a
the imaginary part of c = b
'''
return {
"re":a,
"im":b
}
def get_Real(c):
'''
The function return the real part of the complex number c.
Input : c
Preconditions : c - complex number
Output : r
Postconditions : r - float, the real part of c
'''
return c["re"]
def get_Imag(c):
'''
The function return the imaginary part of the complex number c.
Input : c
Preconditions : c - complex number
Output : i
Postconditions : i - float, the imaginary part of c
'''
return c["im"]
def set_Real(c, x):
'''
The function sets the value of the real part of the complex number c at x.
Input : c, x
Preconditions : c - a complex number
x - a float
Output : c
Postconditions : c - complex number with the real part equal with x.
'''
c["re"] = x
return c
def set_Imag(c, x):
'''
The function sets the value of the imaginary part of the complex number c at x.
Input : c, x
Preconditions : c - a complex number
x - a float
Output : c
Postconditions : c - complex number with the imaginary part equal with x.
'''
c["im"] = x
return c
def toStr(c):
'''
The function writes a complex number like : a + ib, if b > 0
a - ib, if b < 0
'''
if get_Imag(c) >= 0 :
return ( str(c["re"]) + ' + ' + str( c["im"]) + "i" )
else:
return ( str(c["re"]) + ' - ' + str(-c["im"]) + "i" )
def add_number_to_list(list,c):
'''
The function adds the complex number c to the list.
Input : list, c
Preconditions : list - a list containing complex numbers
c - a complex number
Output : list
Postconditions : list contains c at the end
'''
list.append(c)
return list
def initialize_list(listComplex):
'''
This function initialises the listComplex list with some complex values.
Input : listComplex
Preconditions : listComplex - a empty list
Output : listComplex
Postconditions : listComplex will now have 10 complex numbers in it.
'''
a = create_complex_number(3.21,-4.90)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(3.21,1.67)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(-0.21,-9.90)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(0,0)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(0.01,-24.90)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(3,-4)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(2,1)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(-6,-3)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(3.21,0)
listComplex = add_number_to_list(listComplex, a )
a = create_complex_number(0,-4.9)
listComplex = add_number_to_list(listComplex, a )
return listComplex
def print_number_of_elements(nmb):
'''
The function determines and prints how many elements does list have.
Input : nmb
Preconditions : nbm - number of elements of a list
Output :
Postconditions :
'''
print()
print('The list has ' + str(nmb) + ' complex numbers :')
def print_list(listComplex):
'''
This function prints the entire list of the complex numbers that are present in listComplex.
Input : listComplex
Preconditions : listComplex - is a list
Output :
Postconditions :
'''
print_number_of_elements(len(listComplex))
for x in range (0,len(listComplex)):
print( 'z' + str(x) + ' = ' + toStr(listComplex[x]) )
def help(x):
'''
This function prints all the commands that exist in the program, so that the user can use them.
'''
print()
print('The commands for this program are as it follows:')
print('EXIT, if you want to close the program.')
print('ADD, if you want to add elements to the sequence.')
print('PRINT, if you want to print the elements of the sequence.')
print('SEQUENCE_REAL, if you want to print the list that contains the longest sequence of real numbers from the primary list.')
print('SEQUENCE_MODULUS, if you want to print the list that contains the longest sequence of complex number with the modulus € [0,10].')
def command_introduction():
'''
This function prints the text that is shown to the user before introducing a command.
'''
print()
print('What would you like to do ?')
print('If you do not know the commands type HELP.')
print()
def delete_spaces(array):
'''
This function delets all the spaces from the string sir.
Input : sir - a string
Preconditions :
Output : res - the string sir but without the spaces
Postconditions :
'''
array = array + ' '
previous = -1
res = ''
for x in range(0,len(array)):
if( array[x] == ' ' ):
aux = array[previous+1:x]
previous = x
res = res + aux
return res
def process_com(command):
'''
This function returns the command such that it is correct and interpretable by the program.
Input : command, a string
Preconditions :
Output : command, the string but without spaces and containing only uppercase letters.
'''
command = delete_spaces(command)
command = command.upper()
return command
def exit():
'''
This function writes the text before the ending of the program.
'''
print('The program will close now. Bye !')
print('T. Andreas made it.')
def sign_position( array ):
'''
This function return the position where + or - is situated in the array.
Input : array
Preconditions : array - string
Output : x
Postconditions : x is a natural number, x € [1,len(array)-2]
'''
sign_position = -1
for x in range (1,len(array)):
if array[x] == '+' or array[x] == '-' :
return x
def determine_real_part(array):
'''
This function returns the real part of a complex number stored in the array string.
Input : array
Preconditions : array - a string
Output : result
Postconditions : result is a float memorising the real part of the complex number stored in array.
'''
auxiliary_array = array[0:sign_position(array)]
result = float(auxiliary_array)
return result
def determine_imag_part(array):
'''
This function returns the imaginary part of a complex number stored in the array string.
Input : array
Preconditions : array - a string
Output : result
Postconditions : result is a float memorising the imaginary part of the complex number stored in array.
'''
auxiliary_array = array[sign_position(array):(len(array)-1)]
result = float(auxiliary_array)
return result
def determine_number(array):
'''
This function determines the complex number which is stored in array as a string.
Input : array
Preconditions : array is a string
Output : number
Postconditions : number is a complex number
'''
real_part = determine_real_part(array)
imag_part = determine_imag_part(array)
number = create_complex_number(real_part, imag_part )
return number
def add_element():
'''
This function returns a complex number read from the keyboard as a string.
Input :
Preconditions :
Output : array
Postconditions : a complex number as a string
'''
array = input()
array = delete_spaces(array)
return array
def add_element_ui(listComplex):
'''
This function adds a complex number to the list listComplex.
Input : listComplex
Preconditions : listComplex is a list of complex numbers
Output : listComplex
Postconditions : listComplex contains one more complex number
'''
print("Enter the complex number that you want to add, as a + bi with a, b € R :")
new_number = determine_number(add_element())
listComplex = add_number_to_list(listComplex, new_number)
return listComplex
def add_elements(listComplex, nmb):
'''
This function adds elements to the list listComplex.
Input : listComplex, nmb
Preconditions : listComplex is a list memorising complex numbers
nmb is a number representing how many new numbers will be added to listComplex
Output : listComplex
Postconditions : listComplex but with nmb more complex numbers in it
'''
for x in range (0,nmb) :
listComplex = add_element_ui(listComplex)
return listComplex
def add_elements_ui(listComplex):
'''
This function reads from the keyboard how many numbers would the user like to add to the list and then adds them.
Input : listComplex
Preconditions : listComplex is a list memorising complex numbers
Output :
Postconditions :
'''
try:
number = int(input("Enter how many numbers would you like to add : "))
except ValueError as ve :
print("Please enter a natural number !")
add_elements(listComplex,number)
print("Addition successfully done !")
def check_real(c):
'''
This function checks whether a complex number has the imaginary part equal with 0.
Input : c
Preconditions : c is a complex number
Output : True or False
Postconditions : True if the imaginary part of c is equal with 0
False if the imaginary part of c is not equal with 0
'''
if c["im"] == 0 :
return True
return False
def get_sequence(listComplex, starting_position, final_position):
'''
This function goes through listComplex from strating_position to final_position copying the elements in another list.
Input : listComplex, starting_position, final_position
Preconditions : listComplex is a list of complex numbers
starting_position is a natural number
final_position is a natural number
Output : listReal
Postconditions : listReal a list containing complex numbers from listComplex
'''
list = []
for x in range (starting_position, final_position + 1):
list.append(listComplex[x])
return list
def sequence_real(listComplex):
'''
This function determines the starting and ending indexes of the longest sequence that contains complex numbers with the imaginary part equal with 0.
Input : listComplex
Preconditions : listComplex is a list containing complex numbers
Output :
Postconditions :
'''
first_position = 0
current_lenght = 0
longest_sequence_lenght = -1
first_position_longest = -1
last_position_longest = -1
for x in range (0,len(listComplex)):
if check_real(listComplex[x]) == True:
if current_lenght == 0:
first_position = x
current_lenght = current_lenght + 1
if current_lenght > longest_sequence_lenght:
longest_sequence_lenght = current_lenght
first_position_longest = first_position
last_position_longest = x
else:
current_lenght = 0
first_position = 0
list = get_sequence(listComplex, first_position_longest, last_position_longest )
print_list(list)
def check_modulus(c):
'''
This function checks whether the modulus of c € [0,10].
Input : c
Preconditions : c is a complex number
Output : True or False
Postconditions : True if the modulus of c € [0,10]
False if the modulus of c < 0 or > 10
'''
if math.sqrt(c["re"] * c["re"] + c["im"] * c["im"]) >= 0 and math.sqrt(c["re"] * c["re"] + c["im"] * c["im"]) <= 10 :
return True
return False
def sequence_modulus(listComplex):
'''
This function determines the starting and ending indexes of the longest sequence that contains complex numbers with the modulus € [0,10].
Input : listComplex
Preconditions : listComplex is a list containing complex numbers
Output :
Postconditions :
'''
first_position = 0
current_lenght = 0
longest_sequence_lenght = -1
first_position_longest = -1
last_position_longest = -1
for x in range (0,len(listComplex)):
if check_modulus(listComplex[x]) == True:
if current_lenght == 0:
first_position = x
current_lenght = current_lenght + 1
if current_lenght > longest_sequence_lenght:
longest_sequence_lenght = current_lenght
first_position_longest = first_position
last_position_longest = x
else:
current_lenght = 0
first_position = 0
list = get_sequence(listComplex, first_position_longest, last_position_longest )
print_list(list)
# -------------------- TEST FUNCTIONS STARTING --------------------
def test_getters():
'''
This function tests whether the get functions work properly.
'''
real = 23.45
imag = 11.23
c = create_complex_number(real,imag)
assert get_Real(c) == 23.45
assert get_Imag(c) == 11.23
def test_setters():
'''
This function test whether the set functions worl properly.
'''
real = 23.45
imag = 11.23
c = create_complex_number(real,imag)
c = set_Real(c,3.33)
assert c["re"] == 3.33
c = set_Imag(c,6.9)
assert c["im"] == 6.9
def test_toStr():
'''
This function check whether toStr function return the right string for a complex number.
'''
a = create_complex_number(3.21,-4.91)
assert toStr(a) == '3.21 - 4.91i'
a = create_complex_number(1.75,2.88)
assert toStr(a) == '1.75 + 2.88i'
def test_create_complex_number():
'''
This function check whether create_complex_number returns the right value.
'''
real = 23.45
imag = 11.23
c = create_complex_number(real,imag)
assert get_Real(c) == real
assert get_Imag(c) == imag
def test_add_number_to_list():
'''
This function chekcs whether add_number_to_list returnss the correct list.
'''
a = create_complex_number(2.42,-0.8)
b = create_complex_number(1,2)
testList = [a]
testList = add_number_to_list(testList,b)
assert testList == [a,b]
def test_initialize_list():
'''
This function checks whether initialize_list returns the proper list.
'''
testList = []
testList = initialize_list(testList)
assert testList[2]["re"] == -0.21
assert testList[9]["im"] == -4.90
assert testList[9]["re"] == 0
assert testList[3]["im"] == 0
assert testList[8]["re"] == 3.21
assert testList[6]["im"] == 1
def test_delete_spaces():
'''
This function checks whether the fhe function delete_spaces delets all the spaces or not.
'''
assert delete_spaces('vin si eu la folbal ') == 'vinsieulafolbal'
assert delete_spaces(' ana are mere dar nu are PERE ') == 'anaaremeredarnuarePERE'
def test_sign_position():
'''
This function checks whether the function sign_position return the proper number.
'''
test_array = "-0.23-1i"
assert sign_position(test_array) == 5
test_array = "1+2.31i"
assert sign_position(test_array) == 1
def test_determine_real_part():
'''
This function checks whether determine_real_part returns the right value ( the real part ).
'''
assert determine_real_part("-0.23-1i") == -0.23
assert determine_real_part("1+2.31i") == 1
def test_determine_imag_part():
'''
This function checks whether determine_imag_part returns the right value ( the imag part ).
'''
assert determine_imag_part("-0.23-1i") == -1
assert determine_imag_part("1+2.31i") == 2.31
def test_determine_number():
'''
This function checks whether determine_number returns a complex number memorising the real and the imaginary part corretly.
'''
test_number = determine_number("-0.23-1i")
assert test_number["re"] == -0.23
assert test_number["im"] == -1
def test_check_real():
'''
This function tests whether check_real properly determines whether a complex number has the imaginary part equal with 0.
'''
test_number = { "re" : -2.123, "im" : 0 }
assert check_real(test_number) == True
test_number = { "re" : -2.123, "im" : -2.123 }
assert check_real(test_number) == False
def test_check_modulus():
test_number = { "re" : -2.123, "im" : 0 }
assert check_modulus(test_number) == True
test_number = { "re" : 6.123, "im" : 123 }
assert check_modulus(test_number) == False
def run_tests():
'''
This function runs all the test functions.
'''
test_getters()
test_setters()
test_toStr()
test_create_complex_number()
test_add_number_to_list()
test_initialize_list()
test_delete_spaces()
test_sign_position()
test_determine_real_part()
test_determine_imag_part()
test_determine_number()
test_check_real()
test_check_modulus()
# -------------------- TEST FUNCTIONS ENDING --------------------
def main():
listComplex = []
listComplex = initialize_list(listComplex)
print('WELCOME TO THE CANDY SHOP ! This program works with a sequence of complex numbers.')
print_list(listComplex)
commands = { "PRINT" : print_list, "HELP" : help, "ADD" : add_elements_ui, "SEQUENCE_REAL" : sequence_real, "SEQUENCE_MODULUS" : sequence_modulus }
while True:
command_introduction()
com = input('Enter command >> ')
com = process_com(com)
if com in commands:
commands[com](listComplex)
elif( com == 'EXIT' ):
exit()
return
else :
print('Illegal command. Please try again !')
run_tests()
main()
|
57fdb5646f2496ef65ff55951c255d3a46a36254
|
iamfrank22/cmsc125-operating_systems
|
/time_sharing.py
| 4,568
| 3.75
| 4
|
import random
import time
import os
class Resource:
def __init__(self, name, id):
self.id = id
self.name = "Resource " + name
self.user_list = []
self.current_user = None
self.is_available = True
def printName(self):
print(self.name)
class User:
def __init__(self, name, id):
self.id = id
self.name = "User " + name
self.resource_num = random.randint(1, generateResource())
self.time = random.randint(1, 30)
def printName(self):
print(self.name)
class Generator:
def __init__(self):
self.resource = []
self.user = []
self.waiting_list = []
def addResource(self):
for resource in range(1, generateResource() + 1):
res = Resource(str(resource), resource)
self.resource.append(res)
def addUser(self):
for user in range(1, generateUser() + 1):
u = User(str(user), user)
self.user.append(u)
# appends the user to the user list of a certain resource
def appendUserList(self):
for user in self.user:
for resource in self.resource:
if user.resource_num == resource.id:
resource.user_list.append(user)
# show users and resources
def showUserAndResource(self):
print("Resources")
print("")
for resource in self.resource:
resource.printName()
if resource.user_list:
for user in resource.user_list:
print(user.name, "\tTime: ", user.time)
print("")
else:
print ("Free")
print("")
print("")
def work(self):
is_all_available = False
while not is_all_available:
print("+++++++++++++++++++++++++++++++++++++++++++++++++")
for resource in self.resource:
resource.printName()
if resource.is_available:
if resource.user_list:
user = resource.user_list[0]
resource.user_list.remove(user)
resource.current_user = user
resource.is_available = False
print("Current User: \t", resource.current_user.name)
print("Time left: \t", resource.current_user.time)
if resource.user_list:
print("\tWaiting List:")
time = resource.current_user.time
for user in resource.user_list:
print("\t", user.name, " ", "Time allocated: ", user.time, "waiting time: ", time)
time+=user.time
print("Status: \tIn Use\n")
else:
print("Status: \tFree\n")
else:
resource.current_user.time -= 1
print("Current User: \t", resource.current_user.name)
print("Time left: \t", resource.current_user.time)
if resource.user_list:
print("\tWaiting List:")
time = resource.current_user.time
for user in resource.user_list:
print("\t", user.name, " ", "Time allocated: ", user.time, "waiting time: ", time)
time += user.time
if resource.current_user.time == 0:
resource.is_available = True
print("Status: \tFree\n")
else:
print("Status: \tIn Use")
print("+++++++++++++++++++++++++++++++++++++++++++++++++")
for resources in self.resource:
if resource.user_list or not resource.is_available:
break
elif (resource.id) == len(self.resource):
is_all_available = True
def generateResource():
return random.randint(1, 30)
def generateUser():
return random.randint(1, 30)
def main():
gen = Generator()
gen.addResource()
gen.addUser()
gen.appendUserList()
timer = 100
while timer > 0:
gen.work()
time.sleep(1)
os.system('CLS')
timer -= 1
if __name__ == '__main__':
main()
|
1ef8b00918375ff2e1a8e60b0e44cef0bddf69a4
|
sandeep256-su/python
|
/atmadv.py
| 3,005
| 3.921875
| 4
|
#atm system
class atm:
"""docstring for atm."""
i=1 #transaction fail attempts
j=1 #pin attempts
bal = 20000.00 #innitial balance
def __init__(self, pin):
self.pin = pin
def security(self):
z=int(8888) # ATM pin
if self.pin==z:
print('\n--------------Welcome to Python Bank---------------')
atm.banking()
else:
if atm.j<=3:
print('wrong pin, attempts left:',4-atm.j)
print('\n')
atm.j+=1
start()
else:
print('\n')
print('Your ATM card is locked plz contact Karthik for pin')
def banking():
print('\nEnter your choice')
key = int(input('---> 1 withdrawal\n---> 2 Deposit\n---> 3 Balacne\n---> 4 Exit\nEnter the transaction number: '))
if key == 1:
atm.withdraw()
elif key == 2:
atm.deposit()
elif key==3:
atm.balance()
elif key==4:
atm.exit()
else:
print('\n')
print('enter valid key')
atm.retry()
def withdraw():
print('\n')
amt = float(input('enter amount to withdraw: '))
if atm.bal <= amt:
print('\n')
print('insufficient fund')
elif amt<100:
print('\n')
print('min balance to withdraw is 100')
else:
atm.bal = atm.bal - amt
print('\n')
print('%d withdrawn from account'%amt)
print('balance',atm.bal)
atm.retry()
def deposit():
print('\n')
amt = float(input('enter amount to deposit: '))
if amt<100:
print('\n')
print('min balance to deposit is 100')
else:
atm.bal = atm.bal + amt
print('\n')
print('%d withdrawn from account'%amt)
print('balance',atm.bal)
atm.retry()
def balance():
print('\n')
print('balance',atm.bal)
atm.retry()
def exit():
import sys
print('\n')
print('-----------------thank you for using ATM--------------')
sys.exit()
def retry():
print()
e = input('\n Press c to continue \n Press n to exit\n (c/n): ')
if e=='c':
atm.banking()
elif e=='n':
atm.exit()
else:
i=1
if i<=3:
print('\n')
print('inalid key, attempts left:',4-atm.i)
atm.i+=1
atm.retry()
else:
print('\n')
print('you tried max limit')
atm.exit()
atm.i+=1
def start():
print('Enter your ATM card pin: ')
p = atm(int(input()))
p.security()
start()
|
649406f3861c6f2a67cef1b850ad5b7c16bd4560
|
thinhntr/JetbrainsAcademySmartCalculator
|
/smart_calculator.py
| 6,760
| 3.984375
| 4
|
from collections import deque
def merge_operators(operators):
minus_operator_count = 0
for operator in operators:
if operator != '-' and operator != '+':
return False
if operator == '-':
minus_operator_count += 1
return '+' if minus_operator_count % 2 == 0 else '-'
def simplify_expr(infix):
new_expr = []
redundant_operators = []
for component in infix:
if component in '+-':
redundant_operators.append(component)
else:
operator = ''
if redundant_operators:
operator = merge_operators(redundant_operators)
redundant_operators = []
if operator:
if not new_expr or new_expr[-1] in '*/(':
new_expr.append(operator+component)
else:
new_expr.append(operator)
new_expr.append(component)
else:
new_expr.append(component)
return new_expr
def compare(operator1, operator2):
return precedence_of(operator1) - precedence_of(operator2)
def precedence_of(operator):
if operator in '+-':
return 0
elif operator in '*/':
return 1
elif operator == '^':
return 2
else:
return -1
def infix_to_postfix(expression):
postfix = []
stack = deque()
for component in expression:
if typeof(component) == 'variable' or typeof(component) == 'number' or component == '(':
stack.append(component)
elif component in '+-*/^':
while stack and (typeof(stack[-1]) == 'variable'
or typeof(stack[-1]) == 'number'
or compare(stack[-1], component) >= 0):
postfix.append(stack.pop())
stack.append(component)
else:
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
while stack:
postfix.append(stack.pop())
return postfix
def run(command):
if command == "/help":
print("Enter an expression to calculate it")
print("Only support int values")
print("Type /exit to quit")
print()
return 'continue'
elif command == "/exit":
print("Bye!")
return 'break'
else:
print("Unknown command")
return 'continue'
def get_value(variable):
if typeof(variable) == 'number':
return int(variable)
if typeof(variable) != 'variable':
return "Invalid assignment"
return variables.get(variable, 'Unknown variable')
def typeof(characters):
if characters.isalpha():
return 'variable'
if characters.isnumeric() or characters[1:].isnumeric() and characters[0] in '+-':
return 'number'
if characters in '+-*/^()':
return 'operator'
return ' ' if characters == ' ' else ''
def next_possible_types(current_component=None):
if current_component is None:
return ['variable', 'number', '(', '+', '-']
if typeof(current_component) == 'variable' or typeof(current_component) == 'number':
return [')', '+', '-', '*', '/', '^']
if current_component in '+-':
return ['variable', 'number', '+', '-', '(']
if current_component in '*/':
return ['variable', 'number', '(', '+', '-']
if current_component == '^':
return ['variable', 'number', '(']
if current_component == '(':
return ['variable', 'number', '+', '-', '(', ')']
if current_component == ')':
return ['+', '-', '*', '/', '^', ')']
def parse(expression):
infix = []
start = 0
current_type = typeof(expression[start])
for end in range(1, len(expression)):
if current_type == 'operator' or typeof(expression[end]) != current_type:
if expression[start] != ' ':
infix.append(expression[start:end])
start = end
current_type = typeof(expression[start])
infix.append(expression[start:])
return infix
def check_syntax(infix_expr):
parentheses = deque()
error = False
previous_component = None
for component in infix_expr:
if typeof(component) == 'variable' and not variables.get(component):
error = 'Unknown variable'
break
elif typeof(component) == '' or (typeof(component) not in next_possible_types(previous_component)
and component not in next_possible_types(previous_component)):
error = 'Invalid expression'
break
elif component == '(':
parentheses.append(component)
elif component == ')':
if len(parentheses) != 0:
parentheses.pop()
else:
error = 'Invalid expression'
break
previous_component = component
if parentheses:
error = 'Invalid expression'
if error:
print(error)
return False
return True
def calculate(postfix):
stack = deque()
for component in postfix:
if typeof(component) == 'number':
stack.append(int(component))
elif typeof(component) == 'variable':
stack.append(get_value(component))
else:
b = stack.pop()
a = stack.pop()
if component == '+':
a += b
if component == '-':
a -= b
if component == '*':
a *= b
if component == '/':
a /= b
if component == '^':
a **= b
stack.append(a)
return int(stack[0])
def evaluate(expression):
infix = parse(expression)
if check_syntax(infix):
print(calculate(infix_to_postfix(simplify_expr(infix))))
def assign(dst, src):
dst = dst.strip()
src = src.strip()
if typeof(dst) != 'variable':
print("Invalid identifier")
return
value = get_value(src)
if isinstance(value, int):
variables[dst] = value
else:
print(value)
if __name__ == '__main__':
variables = dict()
print('S I M P L E C A L C U L A T O R\n')
while True:
expr = input('> ').strip()
if len(expr) == 0:
continue
elif expr[0] == '/':
if run(expr) == 'continue':
continue
else:
break
elif '=' in expr:
eq_pos = 0
for i in range(len(expr)):
if '=' == expr[i]:
eq_pos = i
break
assign(expr[:eq_pos], expr[eq_pos + 1:])
else:
evaluate(expr)
print()
|
0459b7bcc5146ea04d52a7ed25487c62382395f6
|
zerebom/AtCoder
|
/AOJ/algorithm_data1/3D_double_linked_list.py
| 1,019
| 3.703125
| 4
|
class Cell:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinekdList:
def __init__(self):
self.head = None
def insert(self, value):
new = Cell(value)
#番兵。ここを起点にデータが追加されていく
tmp = self.head
# Noneなら=初めてinsertが呼ばれたなら
if not tmp:
# 今のセルを連結する
new.next = new
new.prev = new
self.head = new
return None
#tmp(None)がnewと一致するまで
while not tmp == self.head:
tmp = tmp.next
#つながってたやつを切り離してnewを挿入する
#一個前から見た、次が今になる
tmp.prev.next = new
#newの過去は、今の過去
new.prev = tmp.prev
new.next = tmp
tmp.prev = new
def delete(self,value):
tmp=self.head
|
4fba4841450d77e46da3be2c780c7da274157f64
|
sudhirgamit/Python-Learning
|
/Main1.py
| 1,334
| 4.09375
| 4
|
print("Hello World..!")
# This Is A Single Line Comment
'''A Multiple Line
Are The Excute
In This Code'''
name="Sudhir Gamit"
ch="A"
num=134
point=15.7
pointm=15.77848967463
print(type(name)," : ",name)
print(type(ch)," : ",ch)
print(type(num)," : ",num)
print(type(point)," : ",point)
print(type(pointm)," : ",pointm)
# DataType :- Number, String, Tuples, List, Dictionaries(Maping)
# Arethmetic Operation
print("The Code Is 6 + 7 : ",6+7)
print("The Code Is 6 - 7 : ",6-7)
print("The Code Is 6 * 7 : ",6*7)
print("The Code Is 6 / 7 : ",6/7)
print("The Code Is 6 % 7 : ",6%7)
print("The Code Is 6 // 7 : ",6//7)
print("The Code Is 6 ** 7 : ",6**7)
# Logical Operation
a,b,c=10,20,10
if(a==10 and b==25 and c==10):
print("First Is True..!")
elif(a==20 or b==30 or c==5):
print("Second Is True..!")
elif(a!=10 or b!=30 or c!=5):
print("Third Is True..!")
print("My Data Can Be \"Best Structure\"")
print("My Data Can Be 'Best Structure'")
print('It Is Basic Structure "Nice"')
print("\tToday Is \n My Nice \bDay")
print("\n ********** Emoji Icon In Python **********")
print("\U0001F604",end=" ")
print("\U0001F605",end=" ")
print("\U0001F606",end=" ")
print("\U0001F607",end=" ")
print("\U0001F608",end=" ")
print("\U0001F609",end=" ")
print("\U0001F601",end=" ")
|
a2aab9e2a586a237df57d5baa0012f3457ee2f5a
|
AssiaHristova/SoftUni-Software-Engineering
|
/Programming Fundamentals/mid_exam_preparation/the_final_quest.py
| 1,308
| 3.75
| 4
|
words = input().split()
command = input()
while not command == "Stop":
command_list = command.split()
if 'Delete' == command_list[0]:
index = int(command_list[1])
if index in range(0, len(words)):
words.pop(index + 1)
elif 'Swap' == command_list[0]:
word_1 = command_list[1]
word_2 = command_list[2]
index_1 = 0
index_2 = 0
if word_1 in words and word_2 in words:
for i in range(0, len(words)):
if words[i] == word_1:
index_1 = i
for j in range(0, len(words)):
if words[j] == word_2:
index_2 = j
words[index_1], words[index_2] = words[index_2], words[index_1]
elif 'Put' == command_list[0]:
word = command_list[1]
index = int(command_list[2])
if index in range(0, len(words)):
words.insert(index - 1, word)
elif 'Sort' == command_list[0]:
words.sort(reverse=True)
elif 'Replace' == command_list[0]:
word_1 = command_list[1]
word_2 = command_list[2]
if word_2 in words:
for i in range(0, len(words)):
if words[i] == word_2:
words[i] = word_1
command = input()
print(' '.join(words))
|
033dc80360d80492469b512ea357b93c7b1cc729
|
aravinve/PySpace
|
/ipp.py
| 941
| 3.703125
| 4
|
def greet_user():
print("Hi There!")
print("Welcome Aboard")
def greet_user_special(name):
print("Hi " + name)
def greet_user_full(f_name,l_name):
print("Hi " + f_name + " " + l_name)
def sqaure(number):
return number * number
# Default Return Value is None
def cube(number):
print(number * number * number)
print("Start")
greet_user()
print("Finish")
greet_user_special("Aravind")
greet_user_special("Rocker")
greet_user_full("Aravind","Venkat")
greet_user_full("Venkat","Aravind")
greet_user_full(l_name="Venkat",f_name="Aravind")
print(sqaure(5))
print(cube(5)) # This actually prints None
def emoji_converter(message):
words = message.split(' ')
emojis = {
":)" : "😊",
":(" : "😥"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input(">")
result = emoji_converter(message=message)
print(result)
|
c6163489cdd0301d9224ad6014703fe3c863010a
|
TobyBoyne/fourier-animation
|
/fourier.py
| 2,037
| 4.0625
| 4
|
"""
Calculates the Fourier coefficients for a given set of data points
"""
import matplotlib.pyplot as plt
import numpy as np
class Fourier:
def __init__(self, points, N):
# self.c stores all coefficients of the fourier series
# self.n stores the value of n that each coefficient corresponds to
# self.n == [0, 1, -1, 2, -2, 3, -3, ...]
self.c = np.zeros(2 * N + 1)
self.n = np.array([(n // 2) * (-1) ** (n % 2) for n in range(1, 2 * N + 2)])
self.L = points[-1, 0] - points[0, 0]
values = self.get_points_for_trapz(points)
self.integrate_coefficients(values)
def get_points_for_trapz(self, points):
"""Convert an array of [t, x] points to be ready for integration
Output is a 2D array with rows [t, c_0],
where each row corresponds to the value of the integrand at point t
These rows can then be integrated across via the trapezium rule
This will create rows up to the Nth coefficient of the Fourier series"""
ts = points[:, 0]
xs = points[:, 1]
c_n = np.array([xs * np.exp(-1j * n * ts * 2 * np.pi / self.L) for n in self.n])
integrand_values = np.array([ts, *c_n])
return integrand_values
def integrate_coefficients(self, integrand_values):
ts, values = integrand_values[0, :], integrand_values[1:, 0:]
coeffs = np.trapz(values, x=ts, axis=1)
coeffs *= (1 / self.L)
self.c = coeffs
def __call__(self, ts):
"""Takes an array, and evaluate the fourier series f(t) for each t in ts
Returns an array of f(t)
If the input is an float, return an array of length 1"""
if type(ts) != np.ndarray:
ts = np.array([ts])
fs = np.zeros_like(ts, dtype=np.complex_)
for i, t in enumerate(ts):
f = sum(self.c * np.exp(-1j * self.n * t * 2 * np.pi / self.L))
fs[i] = f
return fs
if __name__ == "__main__":
ts = np.linspace(0, 6.28, 500)
points = np.array([ts, np.sin(ts - 2) + 1j * np.cos(ts)]).T
plt.plot(points[:,1].real, points[:,1].imag)
fourier = Fourier(points, 20)
f_points = fourier(ts)
plt.plot(f_points.real, f_points.imag)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.