blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b3caf3831004632892e925a98b66858fb7f6a38e | RamonCz/Ciencias | /EstructurasDiscretas/Practica9/funciones.py | 2,984 | 3.953125 | 4 | """
--Estructuras Discretas 2018-1
--Profesor: Laura Freidberg Gojman
--Ayudante: Ricardo Jimenez Mendez
--Practica 9
--Alumno: Cruz Perez Ramon
--No. de Cuenta: 31508148
"""
import types
"""
La funcion distancia de la pracica 1
"""
def distancia((x1,y1),(x2,y2)):
r = (((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)) )**(0.5)
return r
"""
La funcion areaCirculo de la practica 1
"""
def areaCirculo(radio):
r = (radio ** 2) * 3.1416
return (r)
"""
La funcion volCono de la practica 2
"""
def volCono(r,h):
resultado = (3.1416 * (r ** 2)) * h/3
return resultado
"""
La funcion edad de la practica 2
"""
def edad (n):
if (n < 0):
print ("jajaja no mames")
elif (n < 10):
print ("chavito")
elif (n < 18):
print ("Adolescente")
else:
print ("Camara vamos por unas chelas xD")
"""
La funcion eliminaUno de la practica 3
"""
def eliminaUno(n,l):
for i in range(len(l)):
if (n == l[i]):
del l[i]
return l
"""
La funcion eliminaTodos de la practica 3
"""
def eliminaTodos(n,l):
cont = 0
for i in range(len(l)):
if (n == l[cont-i]):
del l[cont -i]
cont += 1
return l
"""
La funcion tira de la practica 3
"""
def tira(n,l):
for i in range(n):
del l[i]
return l
"""
La funcion promedio de la practica 4
"""
def promedio (l):
s = 0
cont = 0
for i in range(len(l)):
s += l[i]
cont += 1
resultado = s/cont
return resultado
"""
La funcion cuentaNum de la practica 4
"""
def cuentaNum (n,l):
cont = 0
for i in range(len(l)):
if (n == l[i]):
cont += 1
return cont
"""
Implementar una funcion que calcule el fibonacci de un numero
"""
def fibonacci (n):
if (n == 0):
return 0
elif (n == 1):
return 1
else:
return (fibonacci (n-1)) + (fibonacci (n-2))
if __name__ == "__main__":
p1 = distancia((0,1),(10,1))
print("Distancia de los puntos ((0,1),(10,1)) = " + str(p1))
p2 = areaCirculo (4)
print("Area del circulo con radio (4) = " + str(p2))
p3 = volCono(4,4)
print("Volumen del cono con radio 4 y altura 4 = "+str(p3))
print("La edad de 15 es : ")
p4 = edad(15)
p5 = eliminaUno(2,[1,2,2,2,3,4,5,6])
print("Elimina Uno de una lista es. 2 , [1,2,2,2,3,4,5,6] ")
for i in range(len(p5)):
print(str(p5[i])+", ")
p6 = eliminaTodos(2,[1,2,2,2,3,4,5,6])
print("Elimina Todos de una lista es. 2 , [1,2,2,2,3,4,5,6]")
for i in range(len(p6)):
print(str(p6[i])+", ")
p7 = tira(2,[1,2,3,4,5,6])
print("Tirar de una lista es. 2 , [1,2,3,4,5,6]")
for i in range(len(p7)):
print(str(p7[i])+", ")
p8 = promedio([10,10,10,1])
print ("El promedio es [10,10,10,1] : "+str(p8))
p9 = cuentaNum(2,[1,2,2,2,2,3,4,5,6,7,8,9,10])
print ("cuenta nuemeros de : 2 , [1,2,2,2,2,3,4,5,6,7,8,9,10]")
print (str(p9))
p10 = fibonacci(6)
print ("El fibonacci de 6 es :"+str(p10))
|
282257b7beba48fd0d324e45872c4dd6c37c08bd | AdamISZ/matasano-solutions | /challenges/matasano6.py | 5,485 | 3.6875 | 4 | import base64
import binascii
import matasano3
def count_nonzero_bits(a):
'''a should be a hex string
returned will be how many non zero
bits are in the binary representation'''
return sum([bin(x).count('1') for x in map(ord,a.decode('hex'))])
def hamming_distance(a,b):
'''Given two strings a, b
we find the hamming distance
between them by calculating how
many of the bits differ. first,
convert each string to binary.'''
if not len(a)==len(b):
raise Exception("Cannot calculate hamming distance on non-equal strings")
return count_nonzero_bits(matasano3.xor(binascii.hexlify(a), binascii.hexlify(b)))
def decrypt_from_keysize(ks, dctxt, verbose=False):
blocks = matasano3.get_blocks(dctxt, ks)
new_blocks=[]
#print new_blocks
for i in range(ks):
new_blocks.append('')
for j in range(len(blocks)):
try:
new_blocks[i] += blocks[j][i]
except TypeError:
if verbose:
print "Failed for i: "+str(i)+ " and j: "+str(j)
pass
result_strings=[]
for i in range(ks):
best,result,score = matasano3.find_key(binascii.hexlify(new_blocks[i]))
if verbose:
print "For position: " + str(i) + " got most likely character: " + best
result_strings.append(result)
if verbose:
print "RESULT STRINGS!!! ++++ \n" , result_strings
return ''.join(i for j in zip(*result_strings) for i in j)
if __name__ == '__main__':
with open('6.txt','r') as f:
data6 = f.readlines()
ciphertext = ''.join([x.strip() for x in data6])
print "starting with this ciphertext: " + ciphertext
dctxt = base64.b64decode(ciphertext)
print "got this decoded: " + binascii.hexlify(dctxt)
trial_1 = 'this is a test'
trial_2 = 'wokka wokka!!!'
print hamming_distance(trial_1,trial_2)
normalised_hamming_distances = {}
for keysize in range(2,41):
normalised_hamming_distances[keysize]=0.0
num_trials = 10
for c in range(num_trials):
block1 = dctxt[c*keysize:(c+1)*keysize]
block2 = dctxt[(c+1)*keysize:(c+2)*keysize]
normalised_hamming_distances[keysize] += hamming_distance(block1,block2)
normalised_hamming_distances[keysize] /= num_trials*8*keysize
print ('for key size: '+ str(keysize) + \
" got NHD: " + str(normalised_hamming_distances[keysize]))
#get key size of 29 as most likely
ks = 29
print decrypt_from_keysize(ks, dctxt)
'''
I'm back and6I'm ringin' the bell
A rockn' on the mike while the fly6girls yell
In ecstasy in ths back of me
Well that's my RJ Deshay cuttin' all them Z'e
Hittin' hard and the girliss goin' crazy
Vanilla's on bhe mike, man I'm not lazy.
I'm lettin' my drug kick in
It controls my mouth and I bsgin
To just let it flow, leb my concepts go
My posse's bo the side yellin', Go Vanilza Go!
Smooth 'cause that's6the way I will be
And if yoc don't give a damn, then
Who you starin' at me
So get opf 'cause I control the stage6
There's no dissin' allowed
I'm in my own phase
The girzies sa y they love me and thwt is ok
And I can dance betber than any kid n' play
Stwge 2 -- Yea the one ya' wannw listen to
It's off my head6so let the beat play through6
So I can funk it up and maks it sound good
1-2-3 Yo -- ]nock on some wood
For good zuck, I like my rhymes atrociyus
Supercalafragilisticexpiwlidocious
I'm an effect and6that you can bet
I can take6a fly girl and make her wet.6
I'm like Samson -- Samson bo Delilah
There's no denyin1, You can try to hang
But yyu'll keep tryin' to get my sbyle
Over and over, practice6makes perfect
But not if yoc're a loafer.
You'll get nywhere, no place, no time, no6girls
Soon -- Oh my God, ho{ebody, you probably eat
Spaqhetti with a spoon! Come on wnd say it!
VIP. Vanilla Ics yep, yep, I'm comin' hard lke a rhino
Intoxicating so oou stagger like a wino
So pcnks stop trying and girl stof cryin'
Vanilla Ice is selln' and you people are buyin'6
'Cause why the freaks are jyckin' like Crazy Glue
Movin1 and groovin' trying to sing6along
All through the ghetty groovin' this here song
Noa you're amazed by the VIP poese.
Steppin' so hard like w German Nazi
Startled by ths bases hittin' ground
There1s no trippin' on mine, I'm jcst gettin' down
Sparkamatic: I'm hangin' tight like a faxatic
You trapped me once anr I thought that
You might hwve it
So step down and lend6me your ear
'89 in my time!6You, '90 is my year.
You'rs weakenin' fast, YO! and I cwn tell it
Your body's gettix' hot, so, so I can smell it6
So don't be mad and don't bs sad
'Cause the lyrics beloxg to ICE, You can call me Dar
You're pitchin' a fit, so etep back and endure
Let the6witch doctor, Ice, do the daxce to cure
So come up close6and don't be square
You wanxa battle me -- Anytime, anyw~ere
You thought that I was6weak, Boy, you're dead wrong6
So come on, everybody and sng this song
Say -- Play t~at funky music Say, go white6boy, go white boy go
play t~at funky music Go white boy,6go white boy, go
Lay down axd boogie and play that funky6music till you die.
Play t~at funky music Come on, Come6on, let me hear
Play that fcnky music white boy you say t, say it
Play that funky mcsic A little louder now
Plao that funky music, white boy6Come on, Come on, Come on
Pzay that funky mu
''' |
09ec9d5dcd7c3b4dd6a922b41f8d5c4437fcd14c | SinaSarparast/CPFSO | /JupyterNotebook/bagOfWords.py | 1,151 | 3.796875 | 4 | from sklearn.feature_extraction.text import CountVectorizer
def get_word_bag_vector(list_of_string, stop_words=None, max_features=None):
"""
returns a vectorizer object
To get vocabulary list: vectorizer.get_feature_names()
To get vocabulary dict: vectorizer.vocabulary_
To convert a list of strings to list of vectors: vectorizer.transform().todense()
Example:
word_bag = bow.get_word_bag_vector([
'All my cats in a row',
'When my cat sits down, she looks like a Furby toy!',
'The cat from outer space'
], stop_words='english')
word_bag_vec.get_feature_names()
> ['cat', 'cats', 'furby', 'like', 'looks', 'outer', 'row', 'sits', 'space', 'toy']
word_bag_vec.transform([
'All my cats in a row'
]).todense()
> [[0 1 0 0 0 0 1 0 0 0]]
For full documentation on word vectorizer,
http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
"""
vectorizer = CountVectorizer(stop_words=stop_words, max_features=max_features)
vectorizer.fit(list_of_string)
return vectorizer
|
cb118d8ffde483159094a69c572e6e0b8654e143 | ashigirl96/fagents | /fagents/snippets/multi_process.py | 857 | 3.734375 | 4 | """Snippets for how to code multi process"""
import multiprocessing
import time
def _worker(i):
print("I'm {0}'th worker".format(i))
time.sleep(1)
return
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
def main1():
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv()) # prints "[42, None, 'hello']"
def main2():
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv()) # prints "[42, None, 'hello']"
if __name__ == '__main__':
main2()
# def main():
# print("Start...")
# for i in range(10):
# process = multiprocessing.Process(target=_worker, args=(i,))
# process.start()
#
#
#
# if __name__ == '__main__':
# main() |
eb2c8203183b49044ab87ff7a8a0181f2ced1aa5 | OskarLundberg/Intentionally-Bad-Name-Generator | /Intentionally Bad Name Generator.py | 1,418 | 3.75 | 4 | import time
import random
import os
def clear():
return os.system('cls' if os.name == 'nt' else 'clear')
# approx 44.4% chance of crashing
def counting():
problem = False
for num in range(1, 101):
clear()
print("picking one of all the possible names")
print("Loading... " + str(num) + " %")
load_time = random.randint(1, 9) / 10
if load_time == 0.9:
if random.randint(1, 100) >= 50:
load_time = random.randint(1, 9)
if random.randint(1, 100) >= 92:
problem = True
break
time.sleep(load_time)
return problem
error_msg = "Stupid answer, try again bitch!\n"
print("*"*50 + "\n")
print(" "*8 + "Welcome to Random Name Generator\n")
print("*"*50 + "\n")
try:
answer = int(input("Choose a number between 1-10: "))
except ValueError:
answer = 666
while not 1 <= answer <= 10:
clear()
print(error_msg)
try:
answer = int(input("Choose a number between 1-10: "))
except ValueError:
pass
problem = True
while problem:
problem = counting()
if problem:
clear()
print("Stupid Problem Occurred")
input("Press 'Enter' to restart Loading: ")
print("Done!\n")
time.sleep(1.5)
print("Random Name: Bob\n")
input("Press 'Enter' to exit") |
1893fdb59156c0bb9f78af01183b1a23e670b779 | chsergey/xmlcls | /xmlcls/xml_elem.py | 4,054 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Base class for wrappers over XML elements
If class name ends with 'List' then:
- class must contains '_list_item_class' attribute with class name
- class constructor returns list of objects with type of '_list_item_class' attribute's value
If 'xpath' attribute is None - the root element will be wrapped else element(s) from xpath value.
"""
class XMLElement:
"""
Base class for custom XML elements objects
TODO: explicit element attributes definition and validation
TODO: use __slots__?
"""
xpath = None
_element = None
_list_item_class = None
def __new__(cls, xml_element):
"""
Find XML element in root xml_element and instantiate class
Args:
cls: class. If class name ends with 'List' - wil be return list: [cls._list_item_class(), ...]
xml_element: root xml element to find by passed class xpath
Returns: list of instances or instance
"""
is_list = cls.__name__.endswith('List')
if is_list and cls._list_item_class is None:
raise Exception('{}._list_item_class is None! Must be child class of XMLElement!'.format(cls))
element = None
if cls.xpath is None:
element = xml_element.get_root()
elif not is_list:
element = xml_element.find(cls.xpath)
elif is_list:
elements = xml_element.findall(cls.xpath)
return [cls.instantiate(cls._list_item_class, elm) for elm in elements] if elements is not None else []
return cls.instantiate(cls, element) if element is not None else cls.instantiate(cls)
@staticmethod
def instantiate(cls, element=None) -> object:
"""
Create instance of class
Args:
cls: class
element: etree.Element
Returns:
instance
"""
obj = super(XMLElement, cls).__new__(cls)
if element is not None:
obj._element = element
obj.__dict__.update(element.attrib)
return obj
@property
def tag(self):
return self.element.tag if self.element is not None else None
@property
def text(self):
return "{}".format(self.element.text).strip() if self.element is not None else None
@staticmethod
def as_text(f) -> callable:
"""
Decorator
"""
def wrap(_self):
xml_elem = f(_self)
if xml_elem is None:
return xml_elem
if isinstance(xml_elem, list):
return [elem.text for elem in xml_elem]
return xml_elem.text
return wrap
@property
def element(self):
return self._element if hasattr(self, '_element') else None
def get_root(self):
""" get root etree.Element """
return self._element.get_root() if self._element is not None else None
def find(self, xpath: str):
""" make xpath query for one etree.Element """
return self._element.find(xpath) if self._element is not None else None
def findall(self, xpath: str) -> list:
""" make xpath query for multiple elements """
return self._element.findall(xpath) if self._element is not None else None
@property
def dict(self) -> dict:
""" get element's attributes as dict """
dict_ = self.__dict__.copy()
if '_element' in dict_:
del dict_['_element']
return dict_
def __repr__(self) -> str:
return '{}: {}'.format(self.tag, self.dict)
def __bool__(self) -> bool:
return bool(self.tag)
def __getitem__(self, key):
return self.__dict__[key] if key in self.__dict__ else None
def __setitem__(self, key, val):
self.__dict__[key] = val
def __delitem__(self, key):
if key in self.__dict__:
del self.__dict__[key]
def __contains__(self, key):
return key in self.__dict__
def __iter__(self):
return iter(self.__dict__.keys())
|
12deaeb9f12fd624459faade33c7d07ac6d9b2e6 | csteinberg23/Lab5- | /test_arraylist.py | 4,271 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 08:35:53 2020
@author: christina
"""
"""
This program tests various functionality of an array list
implemented in the arraylist.py.
Assume the student has completed the array list implementation.
Xiannong Meng
2019-11-14
"""
from arraylist import * # import the array list implementation
from ListException import * # import the ListException class
def test_constructor():
'''Test the list constructor. Create and return an empty list.'''
my_list = List() # create a new list
print('A new list is created, its length should be 0 (zero), it is --> ', len(my_list))
return my_list
def test_insert( my_list ):
'''Test the insert method that insert a new item into the list.
Note that the list insert() method defined takes the form
of insert(self, item, index), i.e., an index must be given.
the method should handle the invalid index itself, not this
test program.'''
items = ['hello', 'how', 'are', 'you', '?'] # some data
for i in range(len(items)):
my_list.insert(items[i], i)
# test insertion at a particular location, other elements should shift
my_list.insert('world', 1)
print('Length of the list should be 6, it is --> ',len(my_list))
# print the list using the __str__() method
print("The list content should be ['hello', 'world', 'how', 'are', 'you', '?']")
print("It is --> ", end = '')
print(my_list)
return my_list # we return the list so other functions can use it.
def test_peek( my_list ):
'''Test the peek() method on the given list.
Assume my_list contains proper information and is generated
by the test_insert() method.'''
print("The items in the list should be ['hello', 'world', 'how', 'are', 'you', '?'], it is --> [", end = '')
for i in range(len(my_list)):
print(my_list.peek(i), ' ', end = '');
print(']')
def test_delete(my_list):
'''Test the delete() method. The delete() method takes an index
as the parameter and removes the item at the index'''
# delete at normal positions
my_list.delete(0)
my_list.delete(1)
n = len(my_list)
my_list.delete(n-1)
# print the content of the list
print("The items in the list should be ['world', 'are', 'you'], it is --> [", end = '')
for i in range(len(my_list)):
print(my_list.peek(i), ' ', end = '');
print(']')
return my_list
def test_exception( my_list ):
'''Test various exceptions of the list'''
# peek exception, testing non-existing index
try:
print('Peek at a non-existing location should raise an exception')
print(my_list.peek(len(my_list) + 2))
except ListException:
print("Caught peek error at a wrong index.")
except:
print("Other errors not caught by ListException when peek.")
# delete exception, testing -1
try:
print('Deleting at index -1, should cause exception')
my_list.delete(-1)
except ListException:
print("Caught delete error at index -1")
except:
print("Other errors not caught by ListException when deleting")
# delete exception, testing n
n = len(my_list) # get an updated list length
try:
print('Deleting at index n, should cause exception')
my_list.delete(n + 2)
except ListException:
print("Caught delete error at index n")
except:
print("Other errors not caught by ListException when deleting")
def test_arraylist():
'''Test various operations of the list ADT in array.'''
print('--- Test the list constructor ---')
my_list = test_constructor()
print('--- Passed constructor test ---\n')
print('--- Test the insert() method ---')
my_list = test_insert( my_list )
print('--- Passed insert() test ---\n')
print('--- Test the peek() method ---')
test_peek( my_list )
print('--- Passed peek() test ---\n')
print('--- Test the delete() method ---')
my_list = test_delete( my_list )
print('--- Passed delete() test ---\n')
print('--- Test the exceptions ---')
test_exception( my_list )
print('--- Passed exceptions test ---\n')
# run the tests
test_arraylist() |
46e3119db13c6cf91480abd401f1e750cda69eea | bhagya97/newProj5409 | /fibonacci.py | 1,246 | 3.703125 | 4 | import time
import logging
import random
fibonacci()
def fibonacci():
logging.basicConfig(filename="logfile.log",level=logging.DEBUG)
starting_time=time.time()
### generate random numbers each time
input1= random.randint(0,100)
### taking input from file
#input_file= open("fib_input.txt", "r")
#input1= int(input_file.readline().strip())
first=0
second=1
### open the output file
output_file= open("fib_output.txt","a")
output_file.write("Input:")
output_file.write(str(input1))
output_file.write("\n")
output_file.write("Output")
output_file.write(str(first))
output_file.write("\n")
output_file.write(str(second))
output_file.write("\n")
for i in range(0,input1-2):
element=first+second
first=second
second=element
output_file.write(str(element))
output_file.write("\n")
### close the files
output_file.close()
#input_file.close()
ending_time=time.time()
###calculate the time taken
time_taken= ending_time-starting_time
logging.debug("fibonacci: %2.18f for Input: %d",time_taken,input1)
print("fibo timetaken",time_taken)
|
8150ef9af406dee91979fef3539286e7e92551ef | mnoskoski/scripts-template-python | /function-print-string.py | 274 | 3.796875 | 4 | print("hello, world!".upper()) # set all text to upper
print("The itsy bitsy spider\nclimbed up the waterspout.")
print("My", "name", "is", "Monty", "Python.", sep="-")
print("Monty", "Python.", sep="*", end="*\n")
print("Programming","Essentials","in",sep="***",end="...") |
5ca276e780a1214a9393eeb006ad6ce8e9760cb4 | mnoskoski/scripts-template-python | /06exercicio.py | 529 | 3.984375 | 4 | """
Estruturas logiscas
and (e)
or (ou)
not (nao)
operadores unarios
- not
operadores binarios
- and, or, is
Para o and ambos valores precisam ser True
Para o or um ou outro valor precisa ser True
Para o not o valor do booleano é invertido, se for True vira false e for false vira True
Para o is o valor é comparado com o segundo valor
"""
ativo = True
logado = False
if ativo and logado:
print('Bem vindo usuario!')
else:
print('Voces precisa ativar sua conta!')
#Ativo é verdadeiro?
print(ativo is True)
|
8c6aff095e83e240fbf00a05b5bec40ff2adec66 | sazemlame/Take-Home-Challenge | /takehome.py | 9,324 | 4.21875 | 4 | """
Automated Parking System:
This application helps you manage a parking lot of n slots. The program has the following functionalities:
1. Park a car in empty slot and store the licence plate number and age of the driver
2. Record which car has left the parking spot
3. Search for the slot number for a particular licence number and age
4. Search for licence plate details for drivers of same age
A list of dictionaries containing details for each car has been implemented. A number of constraints have been taken into care like:
1. The first line of file should create a parking lot
2. Same car cannot be parked twice
3. Driver cannot be under the age of 18
4. The slot which is being vacated cannot be greater than the length of parking lot
"""
import re
import sys
#Functions for implementing commands
def car_park(y):
#print("triggrting parking function")
parking={}
parking['licence_plate_no']=""
parking['age']=""
for s in y.split():
if(re.match('^([A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{4})$',s)):
for cars in plot: #Function implemented for parking the car.
if(cars==None): #Extract the licence plate number and check
continue #If duplicate exsits, return null value
if(cars["licence_plate_no"]==s): #Extract age and check if it is legal driving age
print("Same car number..bad input") #If all constraints check out, perform the function
return(0)
parking['licence_plate_no']=s
if(s.isdigit()):
if(int(s)<18):
print("Illegal Driving age... not allowed to park")
return None
parking['age']=s
if(parking['licence_plate_no']=="" or parking['age']==''):
return None
print("Car with vehicle registration number ",parking["licence_plate_no"]," has been parked at slot number",c+1)
return(parking)
def find_car_with_licence_plate(lplate):
parked_slot=0
for cars in plot: #Extracting the slot number for the car parked with the given licence plate number
if cars==None:
continue
if(cars["licence_plate_no"]==lplate):
parked_slot=(plot.index(cars)+1)
if(parked_slot==0):
print("No matching cars found")
return None
return(parked_slot)
def find_cars_with_age(age):
list_of_slot=[]
for cars in plot: #Finding slot number of cars of people with same age
if cars==None:
continue
if(cars["age"]==age):
list_of_slot.append(plot.index(cars)+1)
if(list_of_slot==[]):
print("No matching cars found")
return None
return(list_of_slot)
def get_lic_no_same_age(a): #Finding licence number of cars with same age
list_of_cars=[]
for cars in plot:
if cars==None:
continue
if(cars["age"]==a):
list_of_cars.append(cars["licence_plate_no"])
if(list_of_cars==[]):
print("No matching cars found")
return None
return(list_of_cars)
def get_lic_no_slot(slot):
car_lic_no=None
for cars in plot:
if cars==None:
continue
if(plot.index(cars)==slot):
car_lic_no=cars["licence_plate_no"]
if(car_lic_no==None):
print("No matching cars found")
return None
return(car_lic_no)
def min_pos_empty(): #Finding the most closest minimun parking slot which is empty
empty_slots=[]
for cars in plot:
if cars==None:
empty_slots.append(plot.index(cars))
return empty_slots[0]
#Driver code starts below
n=0 #size of parking lot
c=0 #count for iterating in the parking lot
plot=[]
filename=input("Enter name of file \n") #Reading the command file
with open(filename,'r') as f:
x=f.readline() #x is the first line of the file
if x.split()[0].lower()!="create_parking_lot": #Creating the database. If the first line is not initializing the database then a message prompt is sent
print("Please create a database")
sys.exit()
else:
n=[int(i) for i in x.split() if i.isdigit()][0]
plot=[None]*n
print("Created parking of ",n," slots")
for y in f: #Reading the other lines of the command file
full=0
if y.split()[0].lower()=="park": #Checking if the command is for Parking the car and running the corresponding function
while(plot[c]!=None): #Park the car if the slot is empty otherwise move to next slot
c+=1
if(c>=n):
print("Parking is full..sorry for the inconvenience")
full=1
break
#print("Checking if car not parked",c)
if(full==0):
car_parked=car_park(y)
if(car_parked==None):
print("Invalid licence plate number")
elif(car_parked==0):
plot[c]=None
else:
plot[c]=car_parked
else:c=0
if y.split()[0].lower()=="leave": #Checking if the command is for a car leaving the parking lot
#print("Removing Car")
for s in y.split():
if(s.isdigit()): #Extracting the slot number
s=int(s)
if(plot[s-1]==None):
print("Slot already vacant at", s) #If the input slot is already vacant
elif(s-1>=n):
print("Please enter a valid slot number") #If the slot number is greater than the length of the parking spot
else:
print("Slot number",s," vacated, the car with vehicle registration number ",plot[s-1]["licence_plate_no"]," left the space, the driver of the car was of age", plot[s-1]["age"])
plot[s-1]=None
c=min_pos_empty() #vacate the car and bring the count to the nearest parking spot
if re.match('^Slot_number',y.split()[0]): #Checking if the command requries to return slot numbers
nslot=None
nslots=None
for s in y.split():
if(re.match('[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{1,4}',s)): #Extracting number plate no to search for the corresponding slot
nslot=find_car_with_licence_plate(s)
if(s.isdigit()): #Extracting age to search for the corresponding slot
nslots=find_cars_with_age(s)
if(nslot!=None):print(nslot)
if(nslots!=None): print(*nslots,sep=',')
if re.match('^Vehicle_registration_number_for_driver_of_age$ ',y.split()[0]): #Command to extract the number plate numbers for drivers of same age or for a given slot number
lic_nos=None
for s in y.split():
if(s.isdigit()):
lic_nos=get_lic_no_same_age(s)
if(lic_nos!=None):print(*lic_nos,sep=',')
if re.match('^Vehicle_registration_number_for_parking_slot$',y.split()[0]): #Command to extract the number plate numbers for drivers of same age or for a given slot number
lic_no=None
for s in y.split():
if(s.isdigit()):
lic_no=get_lic_no_slot(int(s)-1)
if(lic_no!=None):print("The licence plate number of car in slot",s,"is",lic_no)
#print(plot)
|
51309c0f241bd6641845e18b6e7655bc787e1b1c | it-worker-tango/PythonBase | /day03/Day03_2.py | 717 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 21:50:00 2018
@author: Tango
"""
# = 简单的赋值运算符
x = 20
y = x
print("x:",x)
print("y:",y)
print("-" * 30)
# =+ 加赋值 x+=y 等价于 x= x +y
x += y
print("x:",x)
print("y:",y)
print("x+=y:",x)
print("-" * 30)
# -= 减赋值 x-=y 等价于 x=x -y
x = 20
y = 5
x-=y
print("x:",x)
print("y:",y)
print("x-=y:",x)
print("-" * 30)
# *= 乘赋值 x*=y 等价于 x = x * y
x = 20
y = 5
x*=y
print("x:",x)
print("y:",y)
print("x*=y:",x)
print("-" * 30)
# /= 出赋值, x/=y 等价于 x = x/y
x = 20
y = 5
x/=y
print("x:",x)
print("y:",y)
print("x/=y:",x) #注意Python运行除法的结果实浮点型
#其他运算也一样,大家试试 %=, **= //= |
5739eba75117bb3040d6e93e6be2e109749a08e6 | it-worker-tango/PythonBase | /day10/demo3.py | 308 | 3.59375 | 4 | hello = "你好啊朋友" # 定义一个全局变量
def read():
'''看书的功能'''
hello = '你好啊朋友,一起看书吧。'
print(hello)
if __name__ == "__main__":
print("我去书店。。。。")
read()
print("我回家...")
hello = "吃饭。。。"
print(hello) |
c95e2097506e549414b9cd73079c1d793e2fd098 | it-worker-tango/PythonBase | /day11/demo2.py | 203 | 3.859375 | 4 | # 读取文件中的指定个数的字符
with open("demo.txt", 'r') as file:
string = file.read(3) # 读取前3个字符
print("前3个字符为:", string) # 运行结果:前3个字符为: abc |
92e01c676746653ac390ca7482cd9764c3c73bab | it-worker-tango/PythonBase | /day06/demo4.py | 301 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 1 21:30:35 2019
@author: Tango
if 嵌套
"""
number = int(input("请输入去年的销量:"))
if number >= 1000:
print("销量不错")
else:
if number >= 500:
print("销量还过得去")
else:
print("还需要努力啊")
|
1ff7a6d9db89df7d52d699d83f84871d3f82234f | carlos8410/Python_Class | /IntroGUI/GUI_Intr.py | 1,483 | 3.984375 | 4 | """Write a GUI-based program that provides two Entry fields, a button and a label.
When the button is clicked, the value of each Entry should (if possible) be converted into a float.
If both conversions succeed, the label should change to the sum of the two numbers.
Otherwise it should read "***ERROR***."""
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
top_frame = Frame(self)
top_frame.pack(side=TOP)
self.entry_1 = Entry(top_frame)
self.entry_2 = Entry(top_frame)
self.entry_1.pack(side=LEFT)
self.entry_2.pack(side=LEFT)
bottom_frame = Frame(self)
bottom_frame.pack(side=TOP)
Button(bottom_frame, text='Summation', command=self.handle).pack(side=LEFT)
self.label = Label(bottom_frame)
self.label.pack(side=LEFT)
def handle(self):
"""Handle a click of the button by converting the text the
user has placed in the two Entry widgets and summing them
to show in the label"""
print ("hanler")
entry_1 = self.entry_1.get()
entry_2 = self.entry_2.get()
try:
output = float(entry_1) + float(entry_2)
except:
output = "***ERROR***"
self.label.config(text=output)
root = Tk()
app = Application(master=root)
app.mainloop()
#app.destroy()
|
2b35e0b81932a55bef05b180b3048c152fe7d5ba | jvansteeter/CS-360 | /python/htbin/headlines.py | 335 | 3.546875 | 4 | #!/usr/bin/env python
import requests
from bs4 import BeautifulSoup
print "Content-type: text/html"
print
print "<h1>Headlines</h1>"
request = requests.get("http://news.google.com")
soup = BeautifulSoup(request.content, 'html.parser')
results = soup.find_all("span", {"class":"titletext"})
for i in results:
print str(i) + "<br>"
|
2b88a13415abe1fbd15bbf70e50e05ae1cb8395a | IRC-SPHERE/sphere-challenge | /visualise_data.py | 12,500 | 3.546875 | 4 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as pl
import itertools as it
import json
import os
def slice_df(df, start_end):
"""
This slices a dataframe when the index column is the time. This function slices the dataframe 'df' between a window
defined by the 'start_end' parameter. Time is given in seconds.
"""
inds = (df.index >= start_end[0]) & (df.index < start_end[1])
return df[inds]
def slice_df_start_stop(df, start_end):
"""
Some data, eg PIR sensor data and annotation data, are stored in a sparse format in which the 'start' and 'stop'
times are stored. This helper function returns the sequences of a dataframe which fall within a window defined
by the 'start_stop' parameter.
"""
inds = (df.start < start_end[1]) & (df.end >= start_end[0])
return df[inds]
class Slicer(object):
"""
This class provides an interface to querying a dataframe object. Specifically, this is used to query the times for
which
"""
def __init__(self):
pass
def _time_of(self, dataframe, label):
dict_list = dataframe.T.to_dict().values()
filtered = filter(lambda aa: aa['name'] == label, dict_list)
annotations = sorted(filtered, key=lambda ann: ann['start'])
return [(ann['start'], ann['end']) for ann in annotations]
def _times_of(self, dataframes, label):
times = [self._time_of(dataframe, label) for dataframe in dataframes]
return times
def times_of_occupancy(self, location):
return self._times_of(self.locations, location)
def times_of_activity(self, activity):
return self._times_of(self.annotations, activity)
def time_of_occupancy(self, location, index):
start_end = filter(lambda se: len(se) > index, self._times_of(self.locations, location))
return np.asarray([se[index] for se in start_end])
def time_of_activity(self, activity, index):
start_end = filter(lambda se: len(se) > index, self._times_of(self.annotations, activity))
return np.asarray([se[index] for se in start_end])
class Sequence(Slicer):
def __init__(self, meta_root, data_path):
super(Sequence, self).__init__()
self.path = data_path
video_cols = json.load(open(os.path.join(meta_root, 'video_feature_names.json')))
self.centre_2d = video_cols['centre_2d']
self.bb_2d = video_cols['bb_2d']
self.centre_3d = video_cols['centre_3d']
self.bb_3d = video_cols['bb_3d']
self.annotations_loaded = False
self.meta = json.load(open(os.path.join(data_path, 'meta.json')))
self.acceleration_keys = json.load(open(os.path.join(meta_root, 'accelerometer_axes.json')))
self.rssi_keys = json.load(open(os.path.join(meta_root, 'access_point_names.json')))
self.video_names = json.load(open(os.path.join(meta_root, 'video_locations.json')))
self.pir_names = json.load(open(os.path.join(meta_root, 'pir_locations.json')))
self.location_targets = json.load(open(os.path.join(meta_root, 'rooms.json')))
self.activity_targets = json.load(open(os.path.join(meta_root, 'annotations.json')))
self.load()
def load_wearable(self):
accel_rssi = pd.read_csv(os.path.join(self.path, 'acceleration.csv'), index_col='t')
self.acceleration = accel_rssi[self.acceleration_keys]
self.rssi = pd.DataFrame(index=self.acceleration.index)
for kk in self.rssi_keys:
if kk in accel_rssi:
self.rssi[kk] = accel_rssi[kk]
else:
self.rssi[kk] = np.nan
accel_rssi[kk] = np.nan
self.accel_rssi = accel_rssi
self.wearable_loaded = True
def load_environmental(self):
self.pir = pd.read_csv(os.path.join(self.path, 'pir.csv'))
self.pir_loaded = True
def load_video(self):
self.video = dict()
for location in self.video_names:
filename = os.path.join(self.path, 'video_{}.csv'.format(location))
self.video[location] = pd.read_csv(filename, index_col='t')
self.video_loaded = True
def load_annotations(self):
self.num_annotators = 0
self.annotations = []
self.locations = []
self.targets = None
targets_file_name = os.path.join(self.path, 'targets.csv')
if os.path.exists(targets_file_name):
self.targets = pd.read_csv(targets_file_name)
while True:
annotation_filename = "{}/annotations_{}.csv".format(self.path, self.num_annotators)
location_filename = "{}/location_{}.csv".format(self.path, self.num_annotators)
if not os.path.exists(annotation_filename):
break
self.annotations.append(pd.read_csv(annotation_filename))
self.locations.append(pd.read_csv(location_filename))
self.num_annotators += 1
self.annotations_loaded = self.num_annotators != 0
def load(self):
self.load_wearable()
self.load_video()
self.load_environmental()
self.load_annotations()
def iterate(self):
start = range(int(self.meta['end']) + 1)
end = range(1, int(self.meta['end']) + 2)
pir_zeros = [np.zeros(10)] * len(self.pir_names)
pir_t = np.linspace(0, 1, 10, endpoint=False)
pir_df = pd.DataFrame(dict(zip(self.pir_names, pir_zeros)))
pir_df['t'] = pir_t
pir_df.set_index('t', inplace=True)
for lower, upper in zip(start, end):
lu = (lower, upper)
# Acceleration/RSSI
acceleration = slice_df(self.acceleration, lu)
rssi = slice_df(self.rssi, lu)
# PIR
pir_start_stop = slice_df_start_stop(self.pir, lu)
pir_df *= 0.0
if pir_start_stop.shape[0] > 0:
for si, series in pir_start_stop.iterrows():
pir_df[series['name']] = 1.0
pir_t += 1
# Video
video_living_room = slice_df(self.video['living_room'], lu)
video_kitchen = slice_df(self.video['kitchen'], lu)
video_hallway = slice_df(self.video['hallway'], lu)
yield lu, (acceleration, rssi, pir_df.copy(), video_living_room, video_kitchen, video_hallway)
class SequenceVisualisation(Sequence):
def __init__(self, meta_root, data_path):
super(SequenceVisualisation, self).__init__(meta_root, data_path)
def get_offsets(self):
if self.num_annotators == 1:
return [0]
elif self.num_annotators == 2:
return [-0.05, 0.05]
elif self.num_annotators == 3:
return [-0.1, 0.0, 0.1]
def plot_annotators(self, ax=None, lu=None):
if self.annotations_loaded == False:
return
if ax is None:
fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5))
else:
pl.sca(ax)
if lu is None:
lu = (self.meta['start'], self.meta['end'])
palette = it.cycle(sns.husl_palette())
offsets = self.get_offsets()
for ai in xrange(self.num_annotators):
col = next(palette)
offset = offsets[ai]
for index, rr in slice_df_start_stop(self.annotations[ai], lu).iterrows():
pl.plot([rr['start'], rr['end']], [self.activity_targets.index(rr['name']) + offset * 2] * 2, color=col,
linewidth=5)
pl.yticks(np.arange(len(self.activity_targets)), self.activity_targets)
pl.ylim((-1, len(self.activity_targets)))
pl.xlim(lu)
def plot_locations(self, ax=None, lu=None):
if self.annotations_loaded == False:
return
if ax is None:
fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5))
else:
pl.sca(ax)
if lu is None:
lu = (self.meta['start'], self.meta['end'])
palette = it.cycle(sns.husl_palette())
offsets = self.get_offsets()
for ai in xrange(self.num_annotators):
col = next(palette)
offset = offsets[ai]
for index, rr in slice_df_start_stop(self.locations[ai], lu).iterrows():
pl.plot([rr['start'], rr['end']], [self.location_targets.index(rr['name']) + offset * 2] * 2, color=col,
linewidth=5, alpha=0.5)
pl.yticks(np.arange(len(self.location_targets)), self.location_targets)
pl.ylim((-1, len(self.location_targets)))
pl.xlim(lu)
def plot_pir(self, lu=None, sharey=False):
if lu is None:
lu = (self.meta['start'], self.meta['end'])
num = [2, 1][sharey]
first = [0, 0][sharey]
second = [1, 0][sharey]
fig, axes = pl.subplots([2, 1][sharey], 1, sharex=True, sharey=False, figsize=(20, 5 * num))
axes = np.atleast_1d(axes)
pl.sca(axes[second])
for index, rr in slice_df_start_stop(self.pir, lu).iterrows():
pl.plot([rr['start'], rr['end']], [self.location_targets.index(rr['name'])] * 2, 'k')
pl.yticks(np.arange(len(self.pir_names)), self.pir_names)
pl.ylim((-1, len(self.pir_names)))
pl.xlim(lu)
pl.ylabel('PIR sensor')
self.plot_locations(axes[first], lu)
axes[first].set_ylabel('Ground truth')
pl.tight_layout()
def plot_acceleration(self, lu=None, with_annotations=True, with_locations=False):
if lu is None:
lu = (self.meta['start'], self.meta['end'])
fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 7.5))
ax2 = pl.twinx()
df = slice_df(self.acceleration, lu)
df.plot(ax=ax, lw=0.75)
ax.yaxis.grid(False, which='both')
pl.xlim(lu)
ax.set_ylabel('Acceleration (g)')
ax.set_xlabel('Time (s)')
if with_annotations:
self.plot_annotators(ax2, lu)
if with_locations:
self.plot_locations(ax2, lu)
pl.tight_layout()
def plot_rssi(self, lu=None):
if lu is None:
lu = (self.meta['start'], self.meta['end'])
fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5))
ax2 = pl.twinx()
df = slice_df(self.rssi, lu)
df.plot(ax=ax, linewidth=0.25)
ax.yaxis.grid(False, which='both')
pl.xlim(lu)
ax.set_ylabel('RSSI (dBm)')
ax.set_xlabel('Time (s)')
self.plot_locations(ax2, lu)
pl.tight_layout()
def plot_video(self, cols, lu=None):
if lu is None:
lu = (self.meta['start'], self.meta['end'])
fig, axes = pl.subplots(3, 1, sharex=True, figsize=(20, 10))
for vi, (kk, vv) in enumerate(self.video.iteritems()):
x = np.asarray(vv.index.tolist())
y = np.asarray(vv[cols])
palette = it.cycle(sns.color_palette())
pl.sca(axes[vi])
for jj in xrange(y.shape[1]):
col = next(palette)
pl.scatter(x, y[:, jj], marker='o', color=col, s=2, label=cols[jj])
pl.gca().grid(False, which='both')
pl.ylabel(kk)
pl.xlim(lu)
self.plot_locations(pl.twinx(), lu)
pl.tight_layout()
def plot_all(self, plot_range=None):
self.plot_pir(lu=plot_range, sharey=True)
self.plot_rssi(lu=plot_range)
self.plot_acceleration(lu=plot_range)
self.plot_video(self.centre_2d, lu=plot_range)
def main():
"""
This function will plot all of the sensor data that surrounds the first annotated activity.
"""
# Load training data (this will contain labels)
plotter = SequenceVisualisation('public_data/metadata', 'public_data/train/00001')
# Or load testing data (this visualisation will not contain labels and are
# generally shorter sequences of data, between 10-30 seconds long)
plotter = SequenceVisualisation('public_data/metadata', 'public_data/train/00001')
# This function will retreive the time range of the first jumping activity.
plot_range = plotter.times_of_activity('a_jump')
print plot_range
# To provide temporal context to this, we plot a time range of 10 seconds
# surrounding this time period
plotter.plot_all()
pl.show()
if __name__ == '__main__':
main()
|
69a48b8681be3c0a77a2be589519d1a2e35533db | sreetamadas/sample_Python_code | /get_threshold_kneeCurve.py | 4,897 | 4 | 4 | ### calculate threshold X from knee curve ###
## GOOGLE: how to find knee of a curve in noisy data
# method 1: analytical (distance calculation with original data - may be affected by noise in data)
# method 2: distance calculation with Y from curve fitted to original data
# method 3: https://www1.icsi.berkeley.edu/~barath/papers/kneedle-simplex11.pdf
import pandas #as pd
import numpy as np
from numpy import sqrt, exp
from sklearn import linear_model
import math
from scipy.optimize import curve_fit
def thresholdX(temp):
"method 1 : calculate threshold X"
# https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve
# find points at the 2 ends of the X-Y curve
#print temp
max_X = temp['X'].max()
Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y
max_Y = temp['Y'].max()
X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X
# straight line b/w max values : y = ax + b
# (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1
# coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1)
a = (Y_maxX - max_Y)/(max_X - X_maxY)
b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY)
# calculate distance of each pt in the data to the straight line
# distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1)
temp['dist'] = ( a * temp.X + b - temp.Y)/math.sqrt(a*a + 1)
# find point with max distance
maxD = temp['dist'].max()
X_maxD = np.median(temp[temp.dist == maxD].X) # float(temp[temp.dist == maxD].X)
return X_maxD;
# method 2: using curve fitting on the data
# GOOGLE: how to fit a curve to points in python
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html
# https://stackoverflow.com/questions/19165259/python-numpy-scipy-curve-fitting
def func(x, a, b):
"linear fit"
return (a/x) + b;
def func2(x, a, b):
"exponential decay"
return a * exp(-(b*x));
def knee1(temp):
"curve fitting (inverse)"
# find points at the 2 ends of the X-Y curve
#print temp
max_X = temp['X'].max()
Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y
max_Y = temp['Y'].max()
X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X
x = np.array(pandas.to_numeric(temp.X))
y = np.array(temp.Y)
# straight line b/w max values : y = ax + b
# (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1
# coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1)
a = (Y_maxX - max_Y)/(max_X - X_maxY)
b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY)
# curve fitting
params, pcov = curve_fit(func, x, y) # or, with func2 for exp decay
# calculate distance of each pt in the data to the straight line
# distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1)
temp['dist'] = ( a * x + b - func(x, *params))/math.sqrt(a*a + 1)
# find point with max distance
maxD = temp['dist'].max()
Q_maxD = np.median(temp[temp.dist == maxD].X)
return Q_maxD;
def knee2(temp):
"curve fitting (polynomial)"
# find points at the 2 ends of the X-Y curve
max_X = temp['X'].max()
Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y
max_Y = temp['Y'].max()
X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X
x = np.array(pandas.to_numeric(temp.X))
y = np.array(temp.Y)
# straight line b/w max values : y = ax + b
# (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1
# coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1)
a = (Y_maxX - max_Y)/(max_X - X_maxY)
b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY)
# curve fitting
# calculate polynomial
z = np.polyfit(x, y, 2) # polynomial of degree 2
f = np.poly1d(z)
# calculate new y's
y_new = f(x)
# calculate distance of each pt in the data to the straight line
# distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1)
temp['dist'] = ( a * x + b - y_new)/math.sqrt(a*a + 1)
# find point with max distance
maxD = temp['dist'].max()
Q_maxD = np.median(temp[temp.dist == maxD].X) #
#print 'max dist: ',maxD,' ; Q at max dist: ',Q_maxD
return Q_maxD;
######################################################################################################
# sort data by X-column
temp = temp.sort_values(by = 'X', ascending = True)
x = thresholdX(temp)
x1 = knee1(temp)
x2 = knee2(temp)
|
8a60d618f47ce9917bf2c8021b2863585af07672 | sreesindhu-sabbineni/python-hackerrank | /TextWrap.py | 511 | 4.21875 | 4 | #You are given a string s and width w.
#Your task is to wrap the string into a paragraph of width w.
import textwrap
def wrap(string, max_width):
splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)]
returnstring = ""
for st in splittedstring:
returnstring += st
returnstring += '\n'
return returnstring
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result) |
3eefb470c6da99f23213785fba479914399f8728 | Nouw/Programming-class | /les-8/8.1_while-loop_numbers.py | 264 | 3.671875 | 4 | running = True
som = 0
getallen = -1
while running:
getal = int(input("Geef en getal:"))
som += getal
getallen += 1
if getal == 0:
running = False
print("Er zijn " + str(getallen) + " getallen ingevoerd, de som is: " + str(som))
|
d4613de5a15162d087a76da28fd82077cfebc928 | Nouw/Programming-class | /les-11/11.2_json-files_schrijven.py | 961 | 3.609375 | 4 | import json
import os
def store(name, firstl, birthdate, email):
# Basically checks if the data.json file exists if not then create data.json file
files = []
for f_name in os.listdir('.'):
files.append(f_name)
if 'data.json' not in files:
with open('data.json', 'w') as file:
file.write('[]')
# get all the data from the json file and add the login to it
with open('data.json') as data_file:
old_data = json.load(data_file)
old_data.append({"naam": name, "voorletters": firstl, "geb_datum": birthdate, "e-mail": email})
with open('data.json', 'w') as outfile:
json.dump(old_data, outfile, indent=4)
while True:
naam = input("Wat is je achternaam? ")
if naam == "einde":
break
voorl = input("Wat zijn je voorletters? ")
gbdatum = input("Wat is je geboortedatum? ")
email = input("Wat is je e-mail adres? ")
store(naam, voorl, gbdatum, email)
|
90d57fc0012c7370848d13f914790c03a9f10054 | Nouw/Programming-class | /les-8/ns-kaartautomaat.py | 2,035 | 4.1875 | 4 | stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "'s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
def inlezen_beginstation(stations):
running = True
while running:
station_input = input('Wat is uw begin station?')
if station_input in stations:
running = False
return stations.index(station_input)
else:
print('Het opgegeven station bestaat niet!')
def inlezen_eindstation(stations, beginstation):
running = True
while running:
station_input = input('Wat is uw eind station?')
if station_input in stations:
if beginstation < stations.index(station_input):
running = False
return stations.index(station_input)
else:
print("Het station is de verkeerde kant op!")
else:
print('Het opgegeven station bestaat niet!')
def omroepen_reis(stations, beginstation, eindstation):
nameBeginstation = stations[beginstation]
nameEndstation = stations[eindstation]
distance = eindstation - beginstation
price = distance * 5
print("Het beginstation " + nameBeginstation + " is het " + str(beginstation) + "e station in het traject \n" +
"Het eindstation " + nameEndstation + " is het " + str(eindstation) + "e station in het traject \n" +
"De afstand bedraagt " + str(distance) + " station(s) \n" +
"De prijs van het kaartje is " + str(price) + " euro")
print("Jij stapt in de trein in: " + nameBeginstation)
for stationIndex in range((len(stations))):
if eindstation > stationIndex > beginstation:
print("-" + stations[stationIndex])
print("Jij stapt uit in: " + nameEndstation)
beginstation = inlezen_beginstation(stations)
eindstation = inlezen_eindstation(stations, beginstation)
omroepen_reis(stations, beginstation, eindstation) |
4ab0c17cea4ecc2344962dd34235a0afd3eea132 | Nouw/Programming-class | /les-6/6.5_string_functions.py | 491 | 3.796875 | 4 | # Schrijf functie gemiddelde(), die de gebruiker vraagt om een willekeurige zin in te voeren. De functie berekent vervolgens de gemiddelde lengte van de woorden in de zin en print dit uit.
def gemiddelde(zin):
words = zin.split()
print(words)
totalLength = 0
wordCount = 0
for word in words:
length = len(word)
totalLength += length
wordCount += 1
return print(totalLength / wordCount)
zin = input('Tik een willekeurige zin')
gemiddelde(zin) |
a0d1ec47af81124c47b0c16ea678b230255f2ec7 | Iretiayomide/Week-8 | /Assignment 7b.py | 594 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
#import libraries
import matplotlib.pyplot as plt
import pandas as pd
#create dataset
names = ['Bob','Jessica','Mary','John','Mel']
status = ['Senior','Freshman','Sophomore','Senior', 'Junior']
grades = [76,95,77,78,99]
GradeList = zip(status,grades)
#create dataframe
df = pd.DataFrame(data = GradeList, columns=['Status', 'Grades'])
#plot graph
get_ipython().magic(u'matplotlib inline')
df.plot(kind='bar')
# In[10]:
#add code to plot dataset, replacing x-axis with Names column
df2 = df.set_index(df['Status'])
df2.plot(kind="bar")
|
8bf44c4718c44c230b4cac4d0fc5589c0313e31b | lexatnet/school | /python/17-pygame/01-ball/05-collision/engine/collision.py | 2,246 | 3.5 | 4 | def ball_to_box_collision(ball, box):
return {
'x': ball_to_box_collision_x(ball, box),
'y': ball_to_box_collision_y(ball, box)
}
def ball_to_box_collision_x(ball, box):
width = box['size']['width']
height = box['size']['height']
if (ball['rect'].left < 0) or (ball['rect'].right > width):
return True
return False
def ball_to_box_collision_y(ball, box):
width = box['size']['width']
height = box['size']['height']
if ball['rect'].top < 0 or ball['rect'].bottom > height:
return True
return False
def ball_to_ball_collision(ball_a, ball_b):
return {
'x': ball_to_ball_collision_x(ball_a, ball_b),
'y': ball_to_ball_collision_y(ball_a, ball_b)
}
def ball_to_ball_collision_x(ball_a, ball_b):
interval_y = max(ball_a['rect'].bottom, ball_b['rect'].bottom) - min(ball_a['rect'].top, ball_b['rect'].top)
coverage_y = ball_a['rect'].bottom - ball_a['rect'].top + ball_b['rect'].bottom - ball_b['rect'].top
interval_x = max(ball_a['rect'].right, ball_b['rect'].right) - min(ball_a['rect'].left, ball_b['rect'].left)
coverage_x = ball_a['rect'].right - ball_a['rect'].left + ball_b['rect'].right - ball_b['rect'].left
if (
(interval_y < coverage_y)
and
(interval_x < coverage_x)
):
return True
return False
def ball_to_ball_collision_y(ball_a, ball_b):
interval_x = max(ball_a['rect'].right, ball_b['rect'].right) - min(ball_a['rect'].left, ball_b['rect'].left)
coverage_x = ball_a['rect'].right - ball_a['rect'].left + ball_b['rect'].right - ball_b['rect'].left
interval_y = max(ball_a['rect'].bottom, ball_b['rect'].bottom) - min(ball_a['rect'].top, ball_b['rect'].top)
coverage_y = ball_a['rect'].bottom - ball_a['rect'].top + ball_b['rect'].bottom - ball_b['rect'].top
if (
(interval_x < coverage_x)
and
(interval_y < coverage_y)
):
return True
return False
def get_ball_to_balls_collisions(balls, ball):
collisions = []
print('ball = {}'.format(ball['rect']))
for test_ball in balls:
test_ball_collision = ball_to_ball_collision(ball, test_ball)
print('here')
if (test_ball_collision['x'] or test_ball_collision['y']):
print('here 1')
collisions.append(test_ball)
return collisions
|
f6b956a6dc2d4a44bb586c79f16d541ac2c66cff | matanyehoshua/13.10.21 | /Page 38_8.py | 243 | 4 | 4 | # Page 38_8
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
# prints the row x times and how many each row y times:
for i in range(x):
for i in range(y):
print ('*', end = ' ')
print()
|
2c8771dfe733ce5d3e7fb1af3105edd36d18534e | JVLJunior/Exercicios-URI---Python | /URI_1153.py | 91 | 3.515625 | 4 | n = int(input())
cont = n
fat = 1
while cont > 0:
fat *= cont
cont -= 1
print(fat)
|
582a8b75d58698a4d89826aecb927d5dd22458d8 | zhuweida/Tracing-Trends-in-Macronutrient-Intake-and-Energy-Balance-Across-Demographics-with-Statistics-and-Ma | /code/pr2.py | 4,428 | 4 | 4 | """
the function of converting RDD into csv file is based on
http://stackoverflow.com/questions/31898964/how-to-write-the-resulting-rdd-to-a-csv-file-in-spark-python/31899173
And some of the initialization code is provided by our instructor Dr. Taufer.
"""
import re
import argparse
import collections
import sys
from pyspark import SparkContext,SparkConf
import csv,io
conf = SparkConf()
sc = SparkContext(conf=conf)
global t
t=[]
column=[]
for i in range(20):
t.append([])
def list_to_csv_str(x):
"""Given a list of strings, returns a properly-csv-formatted string."""
output = io.StringIO("")
csv.writer(output).writerow(x)
return output.getvalue().strip() # remove extra newline
def float_number(x):
TEMP=[]
a=0 #to record whether there are missing data in the row
for i in range(len(x)):
if x[i] == '': #we use a to record whether there is missing value in this row
a=a+1
if x[i] == '5.40E-79':
x[i]=0
if a == 0: #if a is still 0 it means there are no missing value in this column
#if x[1] == '1': #if the column of recall is 1
for i in range(len(x)):
TEMP.append(float(x[i])) #put all of x which we are satisfied with into list of which name is TEMP
return TEMP
def toCSVLine(data):
return ','.join(str(d) for d in data)
def convert(x):
for i in range(len(x)):
t[i].append(x[i])
return t
def processFile(fileName):
t=[]
line=sc.textFile(fileName)
a=line.zipWithIndex()
b=a.filter(lambda x:x[1]>0).map(lambda x:x[0].split(',')) #make sure to remove the first row which is the name of column(string)
c=b.map(lambda x:[str(y) for y in x]).map(lambda x:(float_number(x)))
data=c.filter(lambda x:len(x)>0) #row_data
d=data.map(lambda x:convert(x))
t=d.collect()
for i in range(8):
column.append(t[-1][i])
colrdd=sc.parallelize(column) #col data
calorie=sc.parallelize(column[4])
protein=sc.parallelize(column[5])
carbon=sc.parallelize(column[6])
fat=sc.parallelize(column[7])
calorie_mean=calorie.mean()
protein_mean=protein.mean()
carbon_mean=carbon.mean()
fat_mean=fat.mean()
calorie_sampleStdev=calorie.sampleStdev()
protein_sampleStdev=protein.sampleStdev()
carbon_sampleStdev=carbon.sampleStdev()
fat_sampleStdev=fat.sampleStdev()
calorie_variance=calorie.sampleVariance()
protein_variance=protein.sampleVariance()
carbon_variance=carbon.sampleVariance()
fat_variance=fat.sampleVariance()
cor_protein_energy = protein.zip(calorie)
cor_carbon_energy=carbon.zip(calorie)
cor_fat_energy=fat.zip(calorie)
cor1=cor_protein_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(protein_sampleStdev*calorie_sampleStdev)))
cor2=cor_carbon_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(carbon_sampleStdev*calorie_sampleStdev)))
cor3=cor_fat_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(fat_sampleStdev*calorie_sampleStdev)))
print cor1.collect()
number = cor1.count()
cor=cor1.zip(cor2).zip(cor3)
print "protein_mean:"+str(protein_mean)
print "carbon_mean:"+str(carbon_mean)
print "fat_mean:"+str(fat_mean)
print "calorie_mean"+str(calorie_mean)
print "protein_variance:"+str(protein_variance)
print "carbon_variance:"+str(carbon_variance)
print "fat_variance:"+str(fat_variance)
print "calorie_variance:"+str(calorie_variance)
print "number of samples:"+str(number)
print "mean correlation of protein and calorie:" +str(cor1.mean())
print "mean correlation of carbon and calorie:" +str(cor2.mean())
print "mean correlation of fat and calorie:"+str(cor3.mean())
print "remind: everytime you run the code you should change the csv name in line 104 of the code to get the csv of correlation "
cors=cor.map(toCSVLine)
cors.saveAsTextFile("2010_correlation_dietarydata.csv")
def quiet_logs(sc):
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )
def main():
quiet_logs(sc)
parser = argparse.ArgumentParser()
parser.add_argument('filename', help="filename of input text", nargs="+")
args = parser.parse_args()
for filename in args.filename:
processFile (sys.argv[1])
if __name__ == "__main__":
main()
|
820dcba436961e21d6b9b5eb93ad76608904b663 | El-akama/week7_task_oop_encapsulation | /task_oop_incapsulation.py | 2,072 | 3.78125 | 4 | # task1
# class Car:
# def __init__(self, make, model, year, odometer=0, fuel=70):
# self.make = make
# self.model = model
# self.year = year
# self.odometer = odometer
# self.fuel = fuel
# def __add_distance(self, km):
# self.odometer += km
# def __subtract_fuel(self, fuel):
# self.fuel -= fuel
# def drive(self, km):
# if self.fuel * 10 >= km:
# self.__add_distance(km)
# kml = km // 10
# self.__subtract_fuel(kml)
# print('Let’s drive!')
# else:
# print('Need more fuel!')
# a = Car('japan', 'toyota', 2020, 70)
# a.drive(100)
# print(a.odometer)
# print(a.fuel)
# task2
# class Mobile:
# __imeil = "samsung"
# __battery = 100
# __info = 'ssd'
# __os = 'charity'
# def listen_music(self):
# self.__battery -= 5
# print(f'играет музыка, заряд батареи {self.__battery} %')
# def watch_video(self):
# self.__battery -=7
# print(f"смотрим видео, заряд батареи {self.__battery} %")
# if self.__battery <= 10:
# print(f"не смотрим видео, заряд батареии {self.__battery} %")
# def battery_charging(self):
# self.__battery = 100
# print('батарея заряжена')
# def info_battery(self):
# if self.__battery == 0:
# raise Exception ("батарея разряжена, нужно подзарядить")
# else:
# print(self.__battery)
# m = Mobile()
# m.listen_music()
# m.listen_music()
# m.listen_music()
# m.listen_music()
# m.listen_music()
# m.listen_music()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# m.watch_video()
# # m.watch_video()
# # m.watch_video() # чтобы вызвать ошибку
# m.info_battery()
# m.battery_charging()
# m.info_battery()
# task3
# делаю |
9264d91dbaf742726eb9c3bf7d70d8931b4556eb | 519984307/BaseHouse | /Python/Base/ProducerConsumer/MultiThread.py | 2,357 | 3.671875 | 4 | import random
import time
from threading import Thread, Lock, Condition
from queue import Queue
class Producer(Thread):
def __init__(self, queue, lock, condition):
super().__init__()
self._queue = queue
self._lock = lock
self._condition = condition
def run(self):
while True:
with self._condition: # 获取或等待线程条件
try:
item = random.randint(1, 100)
'''
block=True ,如果当前队列已经满了,则put()使调用线程暂停,直到空出一个数据单元
block=False,如果当前队列已经满了,则put()将引发Full异常。
block默认为True
'''
if not self._queue.full():
self._lock.acquire()
self._queue.put(item, block=False)
self._lock.release()
self._condition.wait() # 等待
self._condition.notify() # 通知
print('Produce ', item)
else:
self._condition.notify()
print("Queue is full")
except Queue.Full:
print("Queue is full")
time.sleep(1.0e-4)
class Consumer(Thread):
def __init__(self, queue, lock, condition):
super().__init__()
self._queue = queue
self._lock = lock
self._condition = condition
def run(self):
while True:
with self._condition:
if not self._queue.empty():
self._lock.acquire()
item = self._queue.get()
self._lock.release()
self._condition.notify()
self._condition.wait()
print('Consume ', item)
else:
print("Queue is empty, please wait!")
time.sleep(1.0e-4)
if __name__ == '__main__':
q = Queue(maxsize=20)
lock = Lock()
# 线程条件变量,实现线程调度
condition = Condition()
producer = Producer(q, lock, condition)
consumer = Consumer(q, lock, condition)
producer.start()
consumer.start()
|
1560e2c88d1c43d1d8dce3f9aeee17b1b861bd73 | gracenamucuo/PythonStudy | /ClassAndInstance.py | 3,412 | 4.125 | 4 | class Animal(object):
def run(self):
print('Animal is running')
def run_teice(animal):
animal.run()
animal.run()
#对于Python这样的动态语言来说,不一定需要传入Animal类型,只需要保证传入的对象有一个run()方法就可以。
#判断一个变量是不是某个类型
isinstance(a,Animal)
#判断对象类型,使用type()函数:
#type()函数返回的是Class类型
#判断一个对象是否是函数
import types
def fn():
pass
type(fn)==types.FunctionType
True
type(abs)==types.BuiltinFunctionType
True
type(lambda x: x)==types.LambdaType
True
type((x for x in range(10)))==types.GeneratorType
True
#配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态:
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
hasattr(obj, 'x') # 有属性'x'吗?
True
obj.x
9
hasattr(obj, 'y') # 有属性'y'吗?
False
setattr(obj, 'y', 19) # 设置一个属性'y'
hasattr(obj, 'y') # 有属性'y'吗?
True
getattr(obj, 'y') # 获取属性'y'
19
obj.y # 获取属性'y'
19
#类属性归类所有,但是所有该类的实例都可以访问到。
class Stu(object):
pass
s = Stu()
s.name = '添加属性名字'
#绑定方法
#实例绑定方法
def set_age(self,age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age,s)
s.set_age(5)
#类绑定方法
def set_score(self,score):
self.score = score
Stu.set_score = set_score
#对实例的属性进行限制 只允许Stu实例添加name和age属性
class Stu(object):
__slots__ = ('name','age')#用tuple定义绑定的属性名称
#__slots__仅是对当前类实例起作用,对继承的子类不起作用
#@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
#类设计的时候,通常主线是单一继承下来的,但是要‘混入’额外功能的时候,通过多继承就可以实现,为了更好地看出继承关系,一般把非主线的继承名字后缀加上MixIn
#定制类
# __str__ 类似 重写OC类中description方法
class Stu(object):
def __init__(self,name):
self.name = name
def __str__(self):
return 'Stu object (name: %s) ' % self.name
print(Stu('你好'))
#Stu object (name: 你好
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name=%s)' % self.name
__repr__ = __str__
#如果想一个类可以for……in 循环 需要实现一个__iter__()方法,方法返回一个迭代对象,还需要在该类中实现一个__next__()方法 直到遇到StopIteration
# __call__ 我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象
def fn(self,name='world'):
print('Hello , %s.' % name)
Hello = type('Hello',(object,),dict(hello=fn))
#要创建一个class对象,type()函数需要传入3个参数:
#class的名称
#继承的父类的机会,Python支持多继承,如果只有一个父类,也要写成tuple的单元素的写法。
#class的方法名称与函数绑定,上述列子我们把函数fn绑定到方法名hello()上。
|
96ecc6d78dea8ae6abfb7123f10867092a0697cd | KatherineCG/TargetOffer | /3-相关题目.py | 974 | 3.84375 | 4 | class Solution:
def SortInsert(self, a1, a2):
if a1 == [] and a2 == []:
return
a1len = len(a1)
a2len = len(a2)
for i2 in range(a2len):
for i1 in range(len(a1)):
if a1[0] > a1[1]:
if a2[i2] >= a1[i1]:
a1.insert(i1, a2[i2])
break
if a2[i2] <= a1[len(a1)-1]:
a1.insert(len(a1), a2[i2])
break
if a1[0] < a1[1]:
if a2[i2] <= a1[i1]:
a1.insert(i1, a2[i2])
break
if a2[i2] >= a1[len(a1)-1]:
a1.insert(len(a1), a2[i2])
break
return a1
sortinsert = Solution()
a1 = raw_input()
a2 = raw_input()
array1 = a1.split()
array2 = a2.split()
print sortinsert.SortInsert(array1, array2)
|
7443a803eb8dbb482fdb44a726b928adeb29a871 | KatherineCG/TargetOffer | /24-二叉搜索树的后序遍历序列.py | 925 | 3.765625 | 4 | #coding=utf-8
#AC笔记:函数返回布尔值
class Solution():
def VerifySquenceOfBST(self, sequence):
length = len(sequence)
if length <= 0 or sequence == None:
return False
root = sequence[len(sequence)-1]
for i in range(0, length):
if sequence[i] > root:
break
for j in range(i, length):
if sequence[j] < root:
return False
left = True
if i > 0:
left = self.VerifySquenceOfBST(sequence[:i])
right = True
if i < length -1:
right = self.VerifySquenceOfBST(sequence[i:length-1])
if left == right and left == True:
return True
else:
return False
sequence = input()
test = Solution()
result = test.VerifySquenceOfBST(sequence)
if result == True:
print 'true'
else:
print 'false' |
676bc805b36c49dbfb1ecc01daa8b0eb50e63fce | KatherineCG/TargetOffer | /4-替换空格牛客.py | 388 | 3.796875 | 4 | # -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
if not s:
return s
res = ''
for ch in s:
if ch == ' ':
res += '%20'
else:
res += ch
return res
test = Solution()
s = raw_input()
print test.replaceSpace(s) |
ed0e02d164d7d65d7a132809961b80845439aed8 | KatherineCG/TargetOffer | /45-圆圈中最后剩下的数字.py | 489 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if n == 0 or m == 0:
return -1
array = [i for i in range(n)]
i = 0
while len(array) > 1:
remainder = (m-1) % len(array)
array = array[remainder+1:] + array[:remainder]
return array[0]
test = Solution()
n = input()
m = input()
print test.LastRemaining_Solution(n, m)
|
fb19b66574d2de75d864c3e5b10abd3050346c8d | KatherineCG/TargetOffer | /27-二叉搜索树与双向链表.py | 2,694 | 3.6875 | 4 | # -*- coding:utf-8 -*-
import re
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
pLastNodeInList = None
pLastNodeInList = self.ConvertNode(pRootOfTree, pLastNodeInList)
pHeadOfList = pLastNodeInList
while pLastNodeInList != None and pLastNodeInList.left != None:
pHeadOfList = pLastNodeInList.left
pLastNodeInList = pLastNodeInList.left
return pHeadOfList
def ConvertNode(self, pNode, pLastNodeInList):
if pNode == None:
return
pCurrent = pNode
if pCurrent.left != None:
pLastNodeInList = self.ConvertNode(pCurrent.left, pLastNodeInList)
pCurrent.left = pLastNodeInList
if pLastNodeInList != None:
pLastNodeInList.right = pCurrent
pLastNodeInList = pCurrent
if pCurrent.right != None:
pLastNodeInList = self.ConvertNode(pCurrent.right, pLastNodeInList)
return pLastNodeInList
def HandleInput(data):
data = re.sub('[{}]', '', data).split(',')
pRoot = CreateBinaryTree(data, 0)
return pRoot
def CreateBinaryTree(data, n):
if len(data) > 0:
if n < len(data):
if data[n] != '#':
if (n+3) <= len(data) and data[n+1] == '#' and data[n+2] != '#':
if n+3 == len(data) or data[n+3] == '#':
l = n + 2
r = n + 3
else:
l = 2 * n + 1
r = 2 * n + 2
pRoot = TreeNode(data[n])
pRoot.left = CreateBinaryTree(data, l)
pRoot.right = CreateBinaryTree(data, r)
return pRoot
else:
return None
else:
return None
else:
return None
inputarray = raw_input()
test = Solution()
resultltor = ''
resultrtol = ''
if inputarray == '{}':
print None
else:
pRootHead = HandleInput(inputarray)
pLastNodeInList = test.Convert(pRootHead)
while pLastNodeInList.left != None:
resultrtol = resultrtol + pLastNodeInList.val + ','
pLastNodeInList = pLastNodeInList.left
resultrtol = resultrtol + pLastNodeInList.val + ','
while pLastNodeInList != None:
resultltor = resultltor + pLastNodeInList.val + ','
pLastNodeInList = pLastNodeInList.right
print 'From left to right are:' + resultltor[:len(resultltor)-1] + ';From right to left are:' + resultrtol[:len(resultrtol) - 1] + ';' |
586de144105ea4e2cd2f0358e08cd6d4eee20714 | KatherineCG/TargetOffer | /29.1-数组中出现超过一半的数字.py | 1,148 | 3.578125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if self.CheckInvalidArray(numbers):
return 0
number = numbers[0]
times = 1
for i in range(1,len(numbers)):
if numbers[i] == number:
times += 1
else:
times -= 1
if times == 0:
number = numbers[i]
times = 1
if self.ChedkMoreThanHalf(numbers, number):
return number
else:
return 0
def CheckInvalidArray(self, numbers):
g_bInputInvalid = False
if numbers == [] and len(numbers) <= 0 :
g_bInputInvalid = True
return g_bInputInvalid
def ChedkMoreThanHalf(self, numbers, number):
times = 0
for i in range(len(numbers)):
if numbers[i] == number:
times += 1
if times > len(numbers)/2:
return True
else:
return False
test = Solution()
numbers = input()
print test.MoreThanHalfNum_Solution(numbers) |
dc06c6c46c4c9c07f2ea7c75cc3a486f1fd4f9fc | KatherineCG/TargetOffer | /3-二维数组的查找.py | 1,681 | 3.96875 | 4 | # coding=utf-8
'''
在一个二维数组中,每一行都按照从左到右递增的顺序排序
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
'''
查找方式从右上角开始查找
如果当前元素大于target, 左移一位继续查找
如果当前元素小于target, 下移一位继续查找
进行了简单的修改, 可以判定输入类型为字符的情况
'''
class Solution:
def Find(self, array, target):
if array == []:
return False
rawnum = len(array)
colnum = len(array[0])
if type (target) == float and type (array[0][0]) == int:
target = int(target)
elif type (target) == int and type (array[0][0]) == float:
target = float(target)
elif type (target) != type (array[0][0]):
return False
i = colnum - 1
j = 0
while i >=0 and j < rawnum:
if array[j][i] < target:
j += 1
elif array[j][i] > target:
i -= 1
else:
return True
return False
'''
array = [[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]]
'''
target = int(input())
n=int(raw_input("please input the raw number:"))
m = int(raw_input("please input the colnum number:"))
array= [[0 for col in range(m)] for row in range(n)]
for i in range(n):
for j in range(m):
array[i][j] = int(input())
findtarget = Solution()
print(findtarget.Find(array, target))
|
e8e5aadff96ec0b43260a3f7503e459fbdd88161 | KatherineCG/TargetOffer | /33-把数组排成最小的数.py | 1,104 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:
minnum = ''
else:
length = len(numbers)
numbers = map(str, numbers)
self.Compare(numbers, 0, length-1)
minnum = ''.join(numbers)
return minnum
def Compare(self, numbers, start, end):
if start >= end:
return numbers
key = numbers[start]
low = start
high = end
while start < end :
while start < end and int(key + numbers[end]) <= int(numbers[end] + key):
end -= 1
while start < end and int(key + numbers[end]) > int(numbers[end] + key):
numbers[start] = numbers[end]
start += 1
numbers[end] = numbers[start]
numbers[start] = key
self.Compare(numbers, low, start)
self.Compare(numbers, start+1, high)
return numbers
test = Solution()
numbers = input()
print test.PrintMinNumber(numbers) |
f6c4fb4ad8819c4706d19709aa5955c0221bf3a5 | KatherineCG/TargetOffer | /13-在O(1)时间删除链表结点.py | 1,358 | 3.78125 | 4 | # coding=utf-8
class ListNode:
def __init__(self, data, next = None):
self.data = data
self.next = None
def __del__(self):
self.data = None
self.next = None
class Solution:
def __init__(self):
self.head = None
def DeleteNode(self, pListHead, pToBeDeleted):
if not pListHead or not pToBeDeleted:
return None
#中间结点
if pToBeDeleted.next != None:
p = pToBeDeleted.next
pToBeDeleted.data = p.data
pToBeDeleted.next = p.next
p.__del__()
#头结点
elif pToBeDeleted == pListHead:
pListHead = pToBeDeleted.next
pToBeDeleted.__del__()
#尾结点
else:
p = pListHead
while p.next != pToBeDeleted:
p = p.next
p.next = None
pToBeDeleted.__del__()
#输出链表
def PrintLinkList(self, pListHead):
while pListHead != None:
print pListHead.data
pListHead = pListHead.next
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
test = Solution()
test.PrintLinkList(node1)
test.DeleteNode(node1, node3)
test.PrintLinkList(node1)
|
44869bc89939ee9719d4955b5ba8f24542d9df35 | KatherineCG/TargetOffer | /13-调整数组顺序使奇数位于偶数前面.py | 481 | 3.671875 | 4 | # -*- coding:utf-8 -*-
'''
用两个列表,一个存储奇数,一个存储偶数
返回奇数列表+偶数列表
'''
class Solution:
def reOrderArray(self, array):
# write code here
if not array:
return []
evenres = []
oddres = []
for ch in array:
if ch % 2 == 0:
evenres.append(ch)
else:
oddres.append(ch)
return oddres + evenres
|
4f2e3b81459c7de30038d44b7232fea76c621e36 | Z3roTwo/GuessTheNumber | /GuessTheNumber.py | 1,335 | 3.796875 | 4 | import random
import json
loop = True
guess = 0
number = 0
rounds = 0
name = 0
#q = 0
name = input("Display name: ")
number = random.randint(1, 10)
#try:
#with open('Storage.json', 'r') as JSON:
#data = json.load(JSON)
#type(data)
#print(data["name"])
#q = data[rounds]
#except:
#print("2qerrqwreasdf")
# Debug thingy
# print(number)
print(f"Ok {name} the PC have selected a number between 1 - 10")
while loop:
try:
guess = int(input("Your guess: "))
rounds += 1
if guess > number:
print("Aw too bad that's the wrong number, it's too high! :(")
elif guess < number:
print("Aw too bad that's the wrong number, it's to low! :(")
elif guess == number:
print(f"Congrats you did it! The number was {number} and it only took you {rounds} rounds :D")
loop = False
#if rounds < int(q):
#x = {"name": name, "rounds": rounds}
# Sparar x i Storage.json
#f = open('Storage.json', 'w')
#json.dump(x, f)
# Stänger filen
#f.close()
else:
print("Oops something went wrong and the code didn't crash for some reason....")
except:
print("Please enter a number between 1 and 10") |
dff00f606c61a85f97eadf87e8a939121ed22462 | mananaggarwal2001/The-Perfect-Guess-Game | /project2-the_perfect_guess.py | 999 | 4.03125 | 4 | import os
import random
randInt = random.randint(1, 100)
userGuess = None
Gussess = 0
highScore=None
while(userGuess != randInt):
userGuess = int(input("Enter Your Guess: "))
if(userGuess == randInt):
print("You Guessed it Right")
else:
if userGuess > randInt:
print("Your guesss it Wrong! You have made the larger guess")
else:
print("Your guess it wrong! You have made the smaller guess")
Gussess += 1
print(f"The Number of Gusssess for the Right answer the user made is {Gussess}")
with open("highScore.txt", "r") as f:
highScore = f.read()
if(Gussess < int(highScore)):
with open("highScore.txt","w") as f:
f.write(str(Gussess))
print(f"You have broken the high Score and the updated high Score for the Number of gussess is {Gussess}")
else:
print(f"The highest Number of the Guessess the user made for the right answer is :{highScore} ")
|
25001af33ac7a663e5f20810c42d5cba3ac73242 | AhmedElkhodary/Python-3-Programming-specialization | /1- Python Basics/FinalCourseAssignment/pro5.py | 620 | 4.15625 | 4 | #Provided is a list of data about a store’s inventory where each item
#in the list represents the name of an item, how much is in stock,
#and how much it costs. Print out each item in the list with the same
#formatting, using the .format method (not string concatenation).
#For example, the first print statment should read The store has 12 shoes, each for 29.99 USD.
inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
item =[]
for inv in inventory:
item = inv.split(", ")
print("The store has {} {}, each for {} USD.".format(item[1], item[0], item[2]))
|
a53c2faa1c8da8d9f736720d2f653811898ea67a | AhmedElkhodary/Python-3-Programming-specialization | /1- Python Basics/Week4/pro3.py | 256 | 4.3125 | 4 | # For each character in the string already saved in
# the variable str1, add each character to a list called chars.
str1 = "I love python"
# HINT: what's the accumulator? That should go here.
chars = []
for ch in str1:
chars.append(ch)
print(chars)
|
0362c1ae9a526f1ba7b5923d7e28e1d043648556 | ContextLab/quail | /docs/_build/html/_downloads/plot_pnr.py | 515 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
=============================
Plot probability of nth recall
=============================
This example plots the probability of an item being recalled nth given its
list position.
"""
# Code source: Andrew Heusser
# License: MIT
# import
import quail
#load data
egg = quail.load_example_data()
# analysis
analyzed_data = quail.analyze(egg, analysis='pnr', listgroup=['average']*8,
position=5)
# plot
quail.plot(analyzed_data, title='Probability of Recall')
|
a92b0b7e4b40c97f9dcc7aa74f342b4727212f96 | Aakaaaassh/Coding | /Greedy_florist.py | 555 | 3.734375 | 4 | n,x = list(map(int,input().split()))
list1 = []
for i in range(n):
y = int(input("enter price of flower"))
list1.append(y)
print("number of flowers are " + str(n) + " and their prices are ", list1)
Buyer = x
print("Number of buyers are :", Buyer)
res = sorted(list1, reverse=True)
print(res)
def TotalPrice(res):
count = 0
price = 0
k = 1
for i in res:
count += 1
price = price + k*i
if count == Buyer:
k += 1
return price
print(TotalPrice(res))
|
c3a03b2fda7d388c9626f9a9213d49239e659d67 | Aakaaaassh/Coding | /kth_smallest_element.py | 318 | 3.65625 | 4 | n = int(input("Enter no. of test cases: "))
list2 = []
for i in range(n):
a = int(input("Enter size of array: "))
list1 = list(map(int, input().split()))
k = int(input("Enter kth smallest element: "))
res = sorted(list1)
res = res[k-1]
list2.append(res)
for i in list2:
print(i)
|
fba8df5f519498639cd582e945b592200227eaf6 | IbrahimIrfan/ctci | /1/7.py | 580 | 3.78125 | 4 | # O(M*N) in place
def set0(matrix):
rows = set()
cols = set()
m = len(matrix)
n = len(matrix[0])
#O(M*N)
for r in range(0, m):
for c in range(0, n):
# O(1)
if (matrix[r][c] == 0):
rows.update([r])
cols.update([c])
# O(M*N)
for r in range(0, m):
for c in range(0, n):
if (r in rows) or (c in cols):
matrix[r][c] = 0
return matrix
matrix = [
[0,2,3],
[4,5,6],
[7,8,9],
]
print set0(matrix)
|
80a40c327baf5f1e7f3e287815d584918410124a | golbeck/PythonExercises | /NeuralNets/MLP pure numpy/NeuralNetV1.py | 9,514 | 3.984375 | 4 | #implements logistic classification
#example: handwriting digit recognition, one vs. all
import numpy as np
import os
####################################################################################
####################################################################################
def grad_cost(bias,theta,X,Y,eps):
#computes the gradient with respect to the parameters (theta) of the logistic regression model
#bias: 0: no bias; 1: bias term
#theta: np.array of parameters
#X: np.array of inputs (each of the m rows is a separate observation)
#Y: np.array of outpus
#eps: regularization constant (set to zero if unregularized)
#dimension of data
#number of rows (observations)
n=X.shape[0]
#number of columns (features + bias)
m=X.shape[1]
#number of rows in the dependent variable
n_Y=Y.shape[0]
#check if X and Y have the same number of observations
if(n!=n_Y):
print "number of rows in X and Y are not the same"
return -9999.
#compute logistic function
g=1/(1+np.exp(-np.dot(X,theta)))
#only the non-bias features are in the regularization terms in the cost func
theta_reg=np.copy(theta)
if(bias==1):
theta_reg[0]=0.0
#gradient with respect to theta
J_grad=(np.dot(X.T,g-Y)+eps*theta_reg)/n
return J_grad
####################################################################################
####################################################################################
def cost_fn(bias,theta,X,Y,eps):
#cost function for logistic regression
#bias: 0: no bias; 1: bias term
#theta: np.array of parameters
#X: np.array of inputs (each of the m rows is a separate observation)
#Y: np.array of outpus
#eps: regularization constant (set to zero if unregularized)
#dimension of data
#number of rows (observations)
n=X.shape[0]
#number of columns (features + bias)
m=X.shape[1]
#number of rows in the dependent variable
n_Y=Y.shape[0]
#check if X and Y have the same number of observations
if(n!=n_Y):
print "number of rows in X and Y are not the same"
return -9999.
#only the non-bias features are in the regularization terms in the cost func
theta_reg=np.copy(theta)
if(bias==1):
theta_reg[0]=0.0
#compute logistic function
g=1/(1+np.exp(-np.dot(X,theta)))
#log likelihood func
temp0=-np.log(g)*Y-np.log(1-g)*(1-Y)
temp1=theta_reg**2
J=(temp0.sum(axis=0)+0.5*eps*temp1.sum(axis=0))/n
return J
####################################################################################
####################################################################################
def prob_logistic_pred(theta,X):
#theta: np.array of parameters
#X: np.array of inputs (each of the m rows is a separate observation)
#compute logistic function
g=1/(1+np.exp(-np.dot(X,theta)))
y_out=g>0.5
y=np.column_stack((g,y_out))
return y
####################################################################################
####################################################################################
def fit_logistic_class(bias,theta,X,y,eps,tol,k_max):
#theta: np.array of parameters
#bias: 0: no bias; 1: bias term
#X: np.array of inputs (each of the m rows is a separate observation)
#y: np.array of outputs
#eps: regularization constant (set to zero if unregularized)
#tol: stopping tolerance for change in cost function
#k_max: maximum number of iterations for gradient descent
#compute logistic function
J=cost_fn(bias,theta,X,Y,eps)
k=0
abs_diff=1e8
while((abs_diff>tol)&(k<k_max)):
theta-=grad_cost(bias,theta,X,Y,eps)
J_new=cost_fn(bias,theta,X,Y,eps)
abs_diff=abs(J-J_new)
J=J_new
k+=1
# print k,J
return theta
####################################################################################
####################################################################################
def confusion_matrix(y_out,y):
#compute logistic function
m=y.shape[0]
tempTP=0
tempTN=0
tempFP=0
tempFN=0
for i in range(m):
if(y_out[i]==y[i]):
if(y[i]==1.):
tempTP+=1
else:
tempTN+=1
if(y_out[i]!=y[i]):
if(y_out[i]==1.):
tempFP+=1
else:
tempFN+=1
CF=np.array([[tempTP,tempFN],[tempFP,tempTN]])
return CF
####################################################################################
####################################################################################
def confusion_matrix_multi(y_out,y,n_class):
#compute logistic function
m=y.shape[0]
tempTP=0
tempTN=0
tempFP=0
tempFN=0
#rows: actual class label
#cols: predicted class label
CF=np.zeros((n_class,n_class))
for i in range(m):
if(y_out[i]==y[i]):
CF[y[i]-1,y[i]-1]+=1
else:
CF[y[i]-1,y_out[i]-1]+=1
return CF
####################################################################################
####################################################################################
pwd_temp=%pwd
dir1='/home/sgolbeck/workspace/PythonExercises/NeuralNets'
if pwd_temp!=dir1:
os.chdir(dir1)
dir1=dir1+'/data'
dat=np.loadtxt(dir1+'/ex2data1.txt',unpack=True,delimiter=',',dtype={'names': ('X1', 'X2', 'Y'),'formats': ('f4', 'f4', 'i4')})
n=len(dat)
Y=dat[n-1]
m=len(Y)
X=np.array([dat[i] for i in range(n-1)]).T
#de-mean and standardize data
X=(X-X.mean(0))/X.std(0)
#add in bias term
X=np.column_stack((np.ones(m),np.copy(X)))
tol=1e-6
k_max=400
theta=np.random.normal(size=n)
eps=0.1
k_max=400
k=0
bias=1
theta=fit_logistic_class(bias,theta,X,Y,eps,tol,k_max)
y_out=prob_logistic_pred(theta,X)[:,1]
print confusion_matrix(y_out,Y)
####################################################################################
####################################################################################
#compare to statsmodels logistic regression method
import statsmodels.api as sm
from sklearn.metrics import confusion_matrix
# fit the model
logit=sm.Logit(Y,X)
result=logit.fit()
#classify if prediction > 0.5
Y_out=result.predict(X)
Y_out_ind=Y_out>0.5
#confusion matrix
cm = confusion_matrix(Y,Y_out_ind)
print(cm)
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
import scipy.io as sio
dat=sio.loadmat(dir1+'/ex3data1.mat')
Y_all=np.array(dat['y'])
#reshape to 1d np.array
Y_all=Y_all.ravel()
X=np.array(dat['X'])
m=X.shape[0]
n=X.shape[1]
#add in bias term
bias=1
if(bias==1):
n=X.shape[1]+1
X=np.column_stack((np.ones(m),np.copy(X)))
tol=1e-6
eps=0.1
k_max=10000
k=0
Y_class=np.arange(1,11)
prob_out=np.zeros((m,10))
for i in Y_class:
Y=(Y_all==i).astype(int)
theta=np.random.normal(size=n)
theta=fit_logistic_class(bias,theta,X,Y,eps,tol,k_max)
y=prob_logistic_pred(theta,X)
prob_out[:,i-1]=y[:,0]
Y_out=prob_out.argmax(axis=1)+1
CM=confusion_matrix_multi(Y_out,Y_all,10)
print CM
error_rate=CM.diagonal().sum(0)/m
print error_rate
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
Y_class=np.arange(1,11)
prob_out_skl=np.zeros((m,10))
for i in Y_class:
Y=(Y_all==i).astype(int)
logit=sm.Logit(Y,X)
result=logit.fit()
#classify if prediction > 0.5
Y_out=result.predict(X)
prob_out_skl[:,i-1]=Y_out_ind
Y_out_skl=prob_out_skl.argmax(axis=1)+1
CM=confusion_matrix_multi(Y_out_skl,Y_all,10)
####################################################################################
####################################################################################
####################################################################################
####################################################################################
####################################################################################
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
Y_out_SVC=OneVsRestClassifier(LinearSVC(random_state=0)).fit(X, Y_all).predict(X)
cm = confusion_matrix(Y_all,Y_out_SVC)
print(cm)
|
453a816c318a213493b5f6cc9cd9ca2567ae55b9 | golbeck/PythonExercises | /twitter/tweet_parserV1.py | 5,928 | 3.6875 | 4 | import oauth2 as oauth
import urllib2 as urllib
import numpy as np
from pandas import DataFrame, Series
import pandas as pd
import json
# See Assignment 1 instructions or README for how to get these credentials
access_token_key = "89257335-W8LCjQPcTMIpJX9vx41Niqe5ecMtw0tf2m65qsuVn"
access_token_secret = "5tmU9RDxP3tiFShmtDcFE5VVzWy7dGBRvvDp6uwoZWyW2"
consumer_key = "qknqCAZAOOcpejiYkyYZ00VZr"
consumer_secret = "xQM8ynjjXQxy6jWus4qTlCDEPItjZyxqhnAEbbmmUj2Q1JlX5w"
_debug = 0
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "GET"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''
def twitterreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
headers = req.to_header()
if http_method == "POST":
encoded_post_data = req.to_postdata()
else:
encoded_post_data = None
url = req.to_url()
opener = urllib.OpenerDirector()
opener.add_handler(http_handler)
opener.add_handler(https_handler)
response = opener.open(url, encoded_post_data)
return response
def fetchsamples(feed,max_id):
#to build a query, see:
#https://dev.twitter.com/docs/using-search
# feed: string containing the term to be searched for (see above link)
# max_id: string with the ID of the most recent tweet to include in the results
# url = "https://api.twitter.com/1.1/search/tweets.json?q="
url="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name="
url=url+feed
#download the maximum number of tweets
url=url+'&count=200'
url=url+'&exclude_replies=true'
url=url+'&include_rts=false'
if len(max_id)>0:
url=url+'&max_id='+max_id
parameters = []
response = twitterreq(url, "GET", parameters)
return json.load(response)
feed='from%3Acnbc'
feed='cnn'
response=fetchsamples(feed,'')
temp=response.keys()
DF0=DataFrame(response[str(temp[1])])
count=len(DF0.index)
max_id=int(min(DF0.ix[:,'id']))-1
while count <= 3200:
if len(str(max_id))>0:
response=fetchsamples(feed,str(max_id))
count0=len(response[str(temp[1])])
print count0
DF1=DataFrame(response[str(temp[1])],index=range(count,count+count0))
DF0=pd.concat([DF0,DF1])
print DF0.index
max_id=int(min(DF0.ix[:,'id']))-1
print max_id
count+=count0
print count
for i in range(0,len(response['statuses'])):
#twitter screen name
print response['statuses'][i]['user']['screen_name']
#name of the user
# print response['statuses'][i]['user']['name']
#time and date at which tweet was created
print response['statuses'][i]['created_at']
#The UTC datetime that the user account was created on Twitter
# print response['statuses'][i]['user']['created_at']
#unique id code for the user
# print response['statuses'][i]['user']['id']
#unique id code for the user
print response['statuses'][i]['text']
feed='from%3Acnbc'
feed='from%3Acnn'
response=fetchsamples(feed,'')
temp=response.keys()
DF0=DataFrame(response[str(temp[1])])
count=len(DF0.index)
max_id=int(min(DF0.ix[:,'id']))-1
response=fetchsamples(feed,str(max_id))
count0=len(response[str(temp[1])])
print count0
DF1=DataFrame(response[str(temp[1])],index=range(count,count+count0))
DF0=pd.concat([DF0,DF1])
print DF0.index
max_id=int(min(DF0.ix[:,'id']))-1
print max_id
count+=count0
print count
for i in range(0,len(response['statuses'])):
#twitter screen name
print response['statuses'][i]['user']['screen_name']
#name of the user
# print response['statuses'][i]['user']['name']
#time and date at which tweet was created
print response['statuses'][i]['created_at']
#The UTC datetime that the user account was created on Twitter
# print response['statuses'][i]['user']['created_at']
#unique id code for the user
# print response['statuses'][i]['user']['id']
#unique id code for the user
print response['statuses'][i]['text']
for line in response:
print line.strip()
if __name__ == '__main__':
fetchsamples()
#def fetchsamples():
# url = "https://api.twitter.com/1.1/search/tweets.json?q=microsoft"
# parameters = []
# response = twitterreq(url, "GET", parameters)
# return json.load(response)
## for line in response:
## print line.strip()
##if __name__ == '__main__':
## fetchsamples()
myResults = fetchsamples()
#print type(myResults)
#print myResults.keys()
#print myResults["statuses"]
#print type(myResults["statuses"])
results = myResults["statuses"]
#print results[0]
#print type(results[0])
#print results[0].keys()
#print results[0]["text"]
#print results[2]["text"]
#print results[5]["text"]
#for i in range(10):
# print results[i]["text"]
###############################################
#build dictionary
afinnfile = open("AFINN-111.txt")
scores = {}
for line in afinnfile:
term, score = line.split("\t")
scores[term] = float(score)
#print scores.items()
###############################################
#read in tweets and save into a dictionary
atweetfile = open("output.txt")
tweets = []
for line in atweetfile:
try:
tweets.append(json.loads(line))
except:
pass
print len(tweets)
tweet = tweets[0]
print type(tweet)
print tweet.keys()
print type(tweet["text"])
print tweet["text"]
|
57df74cd1011bcce2d372806326c2f61adc6ea14 | naveen-kulkarni0/tensorflow | /flower-classification-tensorflow/data-genr.py | 3,608 | 3.890625 | 4 | """# Data Loading
In order to build our image classifier, we can begin by downloading the flowers dataset. We first need to download the archive version of the dataset and after the download we are storing it to "/tmp/" directory.
After downloading the dataset, we need to extract its contents.
"""
_URL = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
zip_file = tf.keras.utils.get_file(origin=_URL,
fname="flower_photos.tgz",
extract=True)
base_dir = os.path.join(os.path.dirname(zip_file), 'flower_photos')
"""The dataset we downloaded contains images of 5 types of flowers:
1. Rose
2. Daisy
3. Dandelion
4. Sunflowers
5. Tulips
So, let's create the labels for these 5 classes:
"""
classes = ['roses', 'daisy', 'dandelion', 'sunflowers', 'tulips']
"""Also, the dataset we have downloaded has following directory structure.
<pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" >
<b>flower_photos</b>
|__ <b>daisy</b>
|__ <b>dandelion</b>
|__ <b>roses</b>
|__ <b>sunflowers</b>
|__ <b>tulips</b>
</pre>
As you can see there are no folders containing training and validation data. Therefore, we will have to create our own training and validation set. Let's write some code that will do this.
The code below creates a `train` and a `val` folder each containing 5 folders (one for each type of flower). It then moves the images from the original folders to these new folders such that 80% of the images go to the training set and 20% of the images go into the validation set. In the end our directory will have the following structure:
<pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" >
<b>flower_photos</b>
|__ <b>daisy</b>
|__ <b>dandelion</b>
|__ <b>roses</b>
|__ <b>sunflowers</b>
|__ <b>tulips</b>
|__ <b>train</b>
|______ <b>daisy</b>: [1.jpg, 2.jpg, 3.jpg ....]
|______ <b>dandelion</b>: [1.jpg, 2.jpg, 3.jpg ....]
|______ <b>roses</b>: [1.jpg, 2.jpg, 3.jpg ....]
|______ <b>sunflowers</b>: [1.jpg, 2.jpg, 3.jpg ....]
|______ <b>tulips</b>: [1.jpg, 2.jpg, 3.jpg ....]
|__ <b>val</b>
|______ <b>daisy</b>: [507.jpg, 508.jpg, 509.jpg ....]
|______ <b>dandelion</b>: [719.jpg, 720.jpg, 721.jpg ....]
|______ <b>roses</b>: [514.jpg, 515.jpg, 516.jpg ....]
|______ <b>sunflowers</b>: [560.jpg, 561.jpg, 562.jpg .....]
|______ <b>tulips</b>: [640.jpg, 641.jpg, 642.jpg ....]
</pre>
Since we don't delete the original folders, they will still be in our `flower_photos` directory, but they will be empty. The code below also prints the total number of flower images we have for each type of flower.
"""
for cl in classes:
try:
img_path = os.path.join(base_dir, cl)
images = glob.glob(img_path + '/*.jpg')
print("{}: {} Images".format(cl, len(images)))
train, val = images[:round(len(images)*0.8)], images[round(len(images)*0.8):]
for t in train:
if not os.path.exists(os.path.join(base_dir, 'train', cl)):
os.makedirs(os.path.join(base_dir, 'train', cl))
shutil.move(t, os.path.join(base_dir, 'train', cl))
for v in val:
if not os.path.exists(os.path.join(base_dir, 'val', cl)):
os.makedirs(os.path.join(base_dir, 'val', cl))
shutil.move(v, os.path.join(base_dir, 'val', cl))
except:
print("File already exists")
"""For convenience, let us set up the path for the training and validation sets"""
train_dir = os.path.join(base_dir, 'train')
val_dir = os.path.join(base_dir, 'val')
|
5be89cf95fc14294714788db895b2f1ebfc3156b | DiegoCol93/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 192 | 3.78125 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
a_new_dictionary = a_dictionary.copy()
for value in a_dictionary:
a_new_dictionary[value] *= 2
return(a_new_dictionary)
|
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b | DiegoCol93/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,275 | 4.25 | 4 | #!/usr/bin/python3
""" Module for storing the Square class. """
from models.rectangle import Rectangle
from collections import OrderedDict
class Square(Rectangle):
""" Por Esta no poner esta documentacion me cague el cuadrado :C """
# __init__ | Private | method |-------------------------------------------|
def __init__(self, size, x=0, y=0, id=None):
""" __init__:
Args:
size(int): Size of the Square object.
x(int): Value for the offset for display's x position.
y(int): Value for the offset for display's y position.
"""
super().__init__(size, size, x, y, id)
# __str__ | Private | method |--------------------------------------------|
def __str__(self):
""" Returns the string for the Rectangle object """
return "[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y,
self.width)
# update | Public | method |----------------------------------------------|
def update(self, *args, **kwargs):
""" Updates all attributes of the Rectangle object. """
if bool(args) is True and args is not None:
try:
self.id = args[0]
self.size = args[1]
self.x = args[2]
self.y = args[3]
except Exception as e:
pass
else:
for i in kwargs.keys():
if i in dir(self):
setattr(self, i, kwargs[i])
# to_dictionary | Public | method |---------------------------------------|
def to_dictionary(self):
""" Returns the dictionary representation of a Square object. """
ret_dict = OrderedDict()
ret_dict["id"] = self.id
ret_dict["size"] = self.width
ret_dict["x"] = self.x
ret_dict["y"] = self.y
return dict(ret_dict)
# Set & Get __width | Public | method |------------------------------------
@property
def size(self):
""" Getter of the Rectangle's width value. """
return self.width
@size.setter
def size(self, number):
""" Setter of the Rectangle's width value. """
self.width = number
self.height = number
|
dec9ef388badcb3f32458c369c96a74e7f132c90 | DiegoCol93/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 303 | 3.921875 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
if my_list:
list_TF = []
index = 0
for i in my_list:
if i % 2 == 0:
list_TF.append(True)
else:
list_TF.append(False)
index += 1
return list_TF
|
49e4ff54cc9940d752f512059d312e3be381c885 | DiegoCol93/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 238 | 3.9375 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
new_list = my_list.copy()
i = 0
while i < len(my_list):
if my_list[i] == search:
new_list[i] = replace
i += 1
return new_list
|
b6474efae6cd4d892f987547912e85c73bb9fb0e | limelier/advent-of-code-2020 | /19/main.py | 2,233 | 3.640625 | 4 | import re
from typing import List
def get_input():
rules = {}
with open('input.txt') as file:
for line in file:
line = line.strip()
if line:
index, contents = line.split(':')
index = int(index)
contents = contents.strip()
if '"' in contents:
# if literal, extract letter
contents = contents[1]
else:
if '|' not in contents:
contents = [int(num) for num in contents.split(' ')]
else:
cont1, cont2 = contents.split(' | ')
cont1 = [int(num) for num in cont1.split(' ')]
cont2 = [int(num) for num in cont2.split(' ')]
contents = cont1, cont2
rules[index] = contents
else:
break
strings = [line.strip() for line in file]
return rules, strings
def collapse_rules(rules, root=0):
rule = rules[root]
if isinstance(rule, str):
return rule
elif isinstance(rule, List):
return ''.join(collapse_rules(rules, idx) for idx in rule)
else:
left, right = rule
left = ''.join(collapse_rules(rules, idx) for idx in left)
right = ''.join(collapse_rules(rules, idx) for idx in right)
return f'({left}|{right})'
def part_1():
rules, strings = get_input()
pattern = collapse_rules(rules)
regex = re.compile(r'^' + pattern + r'$')
print(sum(1 for string in strings if regex.fullmatch(string)))
def part_2():
rules, strings = get_input()
# rule 0: (8)(11) = (42){n}(42){m}(31){m} = (42){m+n}(31){m}
# a{m+n}b{m} is not possible with pure regex, so we will test for different values of m up to 50
rule_31 = collapse_rules(rules, 31)
rule_42 = collapse_rules(rules, 42)
regexes = [
re.compile('^' + rule_42 + '+' + rule_42 + '{' + str(i) + '}' + rule_31 + '{' + str(i) + '}$')
for i in range(1, 51)
]
print(sum(1 for string in strings if any(regex.fullmatch(string) for regex in regexes)))
if __name__ == '__main__':
part_1()
part_2()
|
b220a0f233abe8c47401f5f91da93abc776434f1 | Jokerzhai/OpenCVPython | /test2/UsingMatplotlib.py | 445 | 3.546875 | 4 | #Matplotlib is a plotting library for Python which gives you wide variety of plotting methods.
# You will see them in coming articles. Here, you will learn how to display image with Matplotlib.
# You can zoom images, save it etc using Matplotlib.
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('board.jpg',0)
plt.imshow(img,cmap = 'gray',internpolation = 'bicubic')
plt.xticks([]),plt.yticks([])
plt.show() |
e4e7696f0a6eb2eeec5a62723bb85bbcc2fd96b6 | manasakandimalla/ICG-Lab | /Lab_5/transition.py | 337 | 3.9375 | 4 | import matplotlib.pyplot as plt
import math
def translation(x,y,h,k):
plt.plot(x,y,marker = 'o')
plt.plot(x+h,y+k,marker='o')
print "enter the co-ordinates of point :"
x0 = input()
y0 = input()
print "enter the co-ordinates of the new origin :"
h = input()
k = input()
translation(x0,y0,h,k)
plt.axis([-10,10,-10,10])
plt.show()
|
1c226cd18e417faf1cc865499b4f801b0481f6a2 | nrvanwyck/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/demo_data.py | 1,207 | 3.859375 | 4 | import sqlite3
conn = sqlite3.connect("demo_data.sqlite3")
curs = conn.cursor()
create_demo_table = """
CREATE TABLE demo (
s TEXT,
x INT,
y INT
);
"""
curs.execute(create_demo_table)
insert_row = """
INSERT INTO demo (s, x, y)
VALUES ('g', 3, 9);"""
curs.execute(insert_row)
insert_row = """
INSERT INTO demo (s, x, y)
VALUES ('v', 5, 7);"""
curs.execute(insert_row)
insert_row = """
INSERT INTO demo (s, x, y)
VALUES ('f', 8, 7);"""
curs.execute(insert_row)
conn.commit()
query = """
SELECT COUNT(*)
FROM demo;"""
row_count = curs.execute(query).fetchall()[0][0]
query = """
SELECT COUNT(*)
FROM demo
WHERE x >= 5 AND y >=5;"""
x_and_y_at_least_5_count = curs.execute(query).fetchall()[0][0]
query = """
SELECT COUNT(DISTINCT y)
FROM demo;"""
unique_y_count = curs.execute(query).fetchall()[0][0]
curs.close()
print("Number of rows:", row_count,
"\nNumber of rows where both x and y are at least 5:",
x_and_y_at_least_5_count,
"\nNumber of unique y values:", unique_y_count)
# Output:
# Number of rows: 3
# Number of rows where both x and y are at least 5: 2
# Number of unique y values: 2
|
3160db69d05f0aed6bbc63f9b2b84020ef4343e0 | CorSar5/Python-World2 | /exercícios 36-71/ex051.py | 209 | 3.765625 | 4 | num = int(input('Primeiro termo: '))
r = int(input('Indique a razão da PA(Progressão Aritmética)'))
décimo = num +(10-1)*r
for c in range(num,décimo,r):
print('{}'.format(c), end='->')
print('ACABOU') |
31a9968211779836bb0e80e1f2c698f69db92b28 | CorSar5/Python-World2 | /exercícios 36-71/ex049.py | 99 | 3.796875 | 4 | t = int(input('Digite um número:'))
for n in range(1,11):
print(f'{n}*{t} é igual a {n * t}') |
7496d32ad90fe4e113b616d72ee8773c9a923897 | CorSar5/Python-World2 | /exercícios 36-71/ex050.py | 274 | 3.796875 | 4 | soma = 0
cont = 0
print('Peço-lhe que me indique 6 números')
for c in range(1, 7):
num = int(input(f'Digite o {c}º valor: '))
if num %2 ==0:
soma += num
cont += 1
print('Deu {} números pares e a soma dos números pares foi {}.'.format(cont,soma)) |
cf09393ec6a76c29cdd9ba6b187edc1121fe612b | CorSar5/Python-World2 | /exercícios 36-71/ex052.py | 220 | 4.15625 | 4 | n = int(input('Escreva um número: '))
if n % 2 == 0 or n % 3 == 0 or n % 5== 0 or n % 7 == 0:
print('Esse número {} não é um número primo'.format(n))
else:
print('O número {} é um número primo'.format(n)) |
a9b43780275bd7e9d95650b80cf984f2619f60ea | SjoerdvanderHeijden/endless-ql | /Jordy_Dennis/QL/expressionnode.py | 8,583 | 4.21875 | 4 | """
An expression can be a single variable, or a combination of a variables with an operator (negation) and multiple other expressions.
All of the types are comparable with boolean operators:
If the variable is 0 or unset, the variable will be converted to a boolean False, True otherwise (just like python does it)
Only numerical values will be accepted for comparison operations such as >, <, <=, etc, Mathematical operations are can also only
be performed on numbers (so no + for strings), the exception to this rule is the != and ==, which can be applied to any child as long
as they have the same type
An error will be thrown if the types are incomparible
"""
from .ast_methods import *
""" Expressions with a left and right side, all of the operators that cause this node to exist are listed in the constructor """
class BinaryNode:
def __init__(self, left, right, op, line):
self.left = left
self.right = right
self.op = op
self.line = line
self.numOps = ["<", "<=", ">", ">="]
self.arithmeticOps = ["+", "-", "/", "*"]
self.allOps = ["!=", "=="]
self.boolOps = ["and", "or"]
"""
Check the actual expression type
"""
def checkTypes(self):
leftType = self.left.checkTypes()
rightType = self.right.checkTypes()
# Compare for the numOp (check that both types are floats/ints), we always return a bool in this case
if self.op in self.numOps:
goodType, expType = self.typeCompareNumOp(leftType, rightType)
if goodType:
return bool
else:
errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str(
self.line)
throwError(errorstring)
# Check if both children are of a numerical type, and return the type (compareOp)
elif self.op in self.arithmeticOps:
goodType, expType = self.typeCompareNumOp(leftType, rightType)
if goodType:
return expType
else:
errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str(
self.line)
throwError(errorstring)
# Boolean operators can always be compared
# (unset or set is converted to True and False) so we do not need a function to check the types serperately
elif self.op in self.boolOps:
return bool
# check it for == and !=, which are boolean operators
elif self.op in self.allOps:
return self.typeCompareAllOp(leftType, rightType)
else:
errorstring = "Unknown operator at line " + str(self.line)
throwError(errorstring)
"""
Check if both types are numerical (int or float), return true, and if they are not of the same type,
return float (a.k.a convert the int)
"""
def typeCompareNumOp(self, leftType, rightType):
if leftType == float and rightType == float:
return True, float
elif leftType == float and rightType == int:
return True, float
elif leftType == int and rightType == float:
return True, float
elif leftType == int and rightType == int:
return True, int
else:
return False, None
"""
Only return the the bool if they are not the same, otherwise throw an error, the only exception are numericals
since we can compare an converted int to a float
"""
def typeCompareAllOp(self, leftType, rightType):
goodType, _ = self.typeCompareNumOp(leftType, rightType)
if goodType:
return bool
elif leftType == rightType:
return bool
else:
errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str(
self.line)
throwError(errorstring)
"""
Call linkVars for children
"""
def linkVars(self, varDict):
self.left.linkVars(varDict)
self.right.linkVars(varDict)
"""
Evaluate expression
"""
def evaluate(self):
left_exp = self.left.evaluate()
right_exp = self.right.evaluate()
return eval(str(left_exp) + " " + self.op + " " + str(right_exp))
# Return string representation of expression for DEBUG
def getName(self):
return str(self.left.getName()) + self.op + str(self.right.getName())
def __repr__(self):
return "Binop: {} {} {}".format(self.left, self.op, self.right)
""" Class for expressions with the unary operator ! """
class UnaryNode:
def __init__(self, left, op, line):
self.left = left
self.op = op
self.line = line
"""
Negation of a variable is always a bool, a set variable will be True and an unset variable is false
"""
def checkTypes(self):
self.left.checkTypes()
# If this is all correct, return a bool
return bool
"""
Call linkVars for children
"""
def linkVars(self, varDict):
self.left.linkVars(varDict)
"""
Return string representation of expression
"""
def getName(self):
return self.op + str(self.left.getName())
"""
Evaluate expression of children and negate the expression
"""
def evaluate(self):
left_exp = self.left.evaluate()
return eval("not " + str(left_exp))
def __repr__(self):
return "Monop: {} {}".format(self.op, self.left)
""" Class for a literal value like 4, or 'apples' """
class LiteralNode:
def __init__(self, value, _type, line):
self.value = value
self.line = line
self.type = _type
"""
return the type for type checking the expression
"""
def checkTypes(self):
return self.type
"""
We do not have to modify the dict here, so we can pass this method
"""
def linkVars(self, varDict):
pass
"""
Return string representation of expression
"""
def getName(self):
return str(self.value)
def evaluate(self):
return self.value
def __repr__(self):
return "literal: {}({}) ".format(self.value, self.type)
""" Class for a variable created during an assignment or question operation, all values have a default value """
class VarNode:
def __init__(self, varname, _type, line, assign=False):
self.varname = varname
self.line = line
self.type = _type
self.value = None
if assign:
self.value = self.getDefaultValue()
"""
Check if the variable actually exists, if so, set our own type, and now this node will be the node used in the dictionary
"""
def linkVars(self, varDict):
if self.varname in varDict:
self.type = varDict[self.varname]['type']
self.value = self.getDefaultValue()
# We finally append the node to the node_list in order to easily change its value in the GUI
varDict[self.varname]['node_list'].append(self)
else:
errorstring = "Undeclared variable '" + self.varname + "' at line " + str(self.line)
throwError(errorstring)
def getDefaultValue(self):
default_values = {
int: 0,
str: "",
bool: False,
float: 0.0
}
try:
return default_values[self.type]
except KeyError:
errorstring = "Invalid default type: " + str(self.type) + "; at line " + str(self.line)
throwError(errorstring)
"""
Return the type for type checking the expression
"""
def checkTypes(self):
return self.type
def evaluate(self):
return self.value
"""
Some useful getters and setters --------------
"""
def getVarname(self):
return self.varname
def getLine(self):
return self.line
def getName(self):
return self.varname
# Set the value of the variable, and only accept its own type or a int to float conversion
def setVar(self, var):
if type(var) == self.type:
self.value = var
elif self.type == float and type(var) == int:
self.value = float(var)
else:
throwError("Bad assignment of variable after expression")
def __repr__(self):
return "VarNode: {} {} {}".format(self.varname, self.type, self.value)
|
388da7afc9018562b7670d03135ae6fa5d649aa1 | SjoerdvanderHeijden/endless-ql | /Jordy_Dennis/GUI/form_scroll_frame.py | 2,087 | 3.875 | 4 | """
A scrollframe is basically a modifyable frame with a scrollbar
Each scrollFrame contains a scrollbar, a canvas, and a contentsFrame.
The contentsFrame can contain widgets.
The canvas is only used to attach the scrollbar to the contents frame
"""
from .gui_imports import *
class ScrollFrameGui:
def __init__(self, parent):
self.frame = create_frame(parent)
self.frame.pack(expand=True, fill='both')
self.canvas, self.contentsFrame = self.createScrollCanvas(self.frame)
self.contentsFrame.pack(expand=True, fill="both")
self.canvas.pack(expand=True, fill="both")
# create a window for the contents frame inside the canvas
self.window = self.canvas.create_window((0, 0), window=self.contentsFrame, anchor='nw')
# binding correct update functions to canvas and contents
self.contentsFrame.bind("<Configure>", self.onConfigureContentFrame)
self.canvas.bind("<Configure>", self.onConfigureCanvas)
"""
Create the canvas, together with the frame that will contain the contents
"""
def createScrollCanvas(self, parent):
canvas = Canvas(parent, background="white")
contentsFrame = create_frame(canvas, "white")
scrollbar = Scrollbar(parent, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill='both')
canvas.configure(yscrollcommand=scrollbar.set)
return canvas, contentsFrame
"""
used to set the window of the canvas to the total width of the canvas
"""
def onConfigureCanvas(self, event):
canvas_width = event.width
self.canvas.itemconfig(self.window, width=canvas_width)
"""
Making sure the scroller stays on the canvas and doesnt allow to scroll to infinity
"""
def onConfigureContentFrame(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
"""
Return contents so widgets can be added
"""
def get_contents(self):
return self.contentsFrame
def get_frame(self):
return self.frame
|
e729e644c6046753e00b30d7d121a6a192054fb6 | merv1618/Python-short-programs | /sample_prime_script.py | 353 | 3.859375 | 4 | from prime_count import primecount
def random_polynomial(x):
return x**2 + 3*x + 1
if __name__ == '__main__':
n = primecount(10)
print("Look at me, I calculated the 10th prime number - it's %i" % n)
print("Now watch me calculate some random polynomial of the 10th prime number")
print("Oh look, it's %i" % random_polynomial(n))
|
4c374bce6543ab75b8ff194de2eaa543457c6159 | ezalos/Rhinoforcement | /state.py | 7,393 | 3.671875 | 4 | #!/usr/bin/env python
import numpy as np
import copy
from color import *
MAX_ROWS = 6
MAX_COLS = 7
class state():
def __init__(self):
self.init_board = np.zeros([MAX_ROWS, MAX_COLS]).astype(str)
self.init_board[self.init_board == "0.0"] = " "
self.player = "X"
self.board = self.init_board
self.last_move = [-1,-1]
self.turn = 0
self.victory = ''
def is_game_over(self):
'''
returns 1, 0
assumes self.victory has been updated (done everytime we drop_piece)
'''
if self.victory == ".":
return (0.0000000001)
elif self.victory == "X":
return (1.0)
elif self.victory == "O":
return (1.0)
else:
return (0.0)
def do_action(self, column):
'''
changes player, turn and victory
'''
if self.victory != '' :
print("Game Over")
elif self.board[0, column] != " ":
print("Invalid move")
print(column)
else:
row = MAX_ROWS - 1
while " " != self.board[row, column]:
row -= 1
self.board[row, column] = self.player
self.last_move = [row, column]
self.turn += 1
self.check_winner()
self.player = "X" if self.player == "O" else "O"
def undrop_piece(self):
if self.last_move[0] != -1:
self.board[self.last_move[0]][self.last_move[1]] = " "
self.turn -= 1
self.player = "X" if self.player == "O" else "O"
else:
print("No memory of last move")
def check_line(self, y, x):
player = self.player
row = self.last_move[0]
col = self.last_move[1]
if 0:
if y == 1 and x == 0:
print("|")
elif y == 0 and x == 1:
print("_")
elif y == 1 and x == 1:
print("/")
elif y == -1 and x == 1:
print("\\")
count = 0
found = 0
for i in range(0, 4):
if 0 <= ((i * x) + row) and ((i * x) + row) < MAX_ROWS:
if 0 <= ((i * y) + col) and ((i * y) + col) < MAX_COLS:
if player == self.board[row + (x * i), col + (y * i)]:
count += 1
found = 1
elif found:
break
for i in range(-1, -4, -1):
if 0 <= (row + (i * x)) and ((i * x) + row) < MAX_ROWS:
if 0 <= ((i * y) + col) and ((i * y) + col) < MAX_COLS:
if player == self.board[row + (x * i), col + (y * i)]:
count += 1
elif found:
break
if 0:
print("Count : ", count)
if count >= 4:
self.victory = player
return True
return False
def check_winner(self):
if self.last_move[0] == -1:
for row in MAX_ROWS:
for col in MAX_COLS:
self.last_move = [row, col]
if self.check_line(1, 0):
return True
elif self.check_line(0, 1):
return True
elif self.check_line(1, 1):
return True
elif self.check_line(-1, 1):
return True
self.last_move = [-1, -1]
else:
if self.check_line(1, 0):
return True
elif self.check_line(0, 1):
return True
elif self.check_line(1, 1):
return True
elif self.check_line(-1, 1):
return True
if self.turn >= 42:
self.victory = "."
return False
def get_reward(self):
'''
returns 1, 0
assumes self.victory has been updated (done everytime we drop_piece)
'''
if self.victory == ".":
return (0)
elif self.victory == "X":
return (1)
elif self.victory == "O":
return (1)
else:
return None
def actions(self):
'''
returns array of possible actions
'''
acts = []
for col in range(MAX_COLS):
if self.board[0, col] == " ":
acts.append(col)
return acts
def valid_moves_mask(self):
valid = np.zeros([MAX_COLS])
for col in range(MAX_COLS):
if self.board[0, col] == " ":
valid[col] = 1
return (valid)
def reset(self):
self.player = "X"
self.last_move = [-1,-1]
self.turn = 0
self.victory = ''
for row in range(MAX_ROWS): ## replace by init board ?
for col in range(MAX_COLS):
self.board[row][col] = " "
def copy(self, other):
'''
copies all attributes of other into self
'''
self.player = other.player
self.last_move[0] = other.last_move[0]
self.last_move[1] = other.last_move[1]
self.turn = other.turn
self.victory = other.victory
for row in range(MAX_ROWS):
for col in range(MAX_COLS):
self.board[row][col] = other.board[row][col]
def encode_board(self):
encoded = np.zeros([3, MAX_ROWS, MAX_COLS]).astype(float)
player_conv = {"O":0, "X":1}
for row in range(MAX_ROWS):
for col in range(MAX_COLS):
pos = self.board[row, col]
encoded[2, row, col] = player_conv[self.player]
if pos != " ":
encoded[player_conv[pos], row, col] = 1.0
return encoded
def decode_board(self, encoded):
self.reset()
player_conv = {0:"O", 1:"X"}
for row in range(MAX_ROWS):
for col in range(MAX_COLS):
for player in range(2):
pos = encoded[row, col, player]
if pos == 1:
self.board[row, col] = player_conv[player]
self.turn += 1
self.player = player_conv[encoded[0,0,2]]
self.check_winner()
def display(self):
board = self.board
move = self.last_move
print("Turn", YELLOW, self.turn - 1, RESET, "for ", end="")
if self.player == "X":
print(BLUE + 'O' + RESET, end="")
else:
print(RED + 'X' + RESET, end="")
print("")
for rows in range(MAX_ROWS):
for cols in range(MAX_COLS):
spot = board[rows, cols]
if cols == move[1] and rows == move[0]:
print(UNDERLINE, end="")
if spot == 'X':
print(RED + 'X' + RESET, end="")
elif spot == 'O':
print(BLUE + 'O' + RESET, end="")
else:
print('.' + RESET, end="")
print(' ', end="")
print('\n', end="")
print("0 1 2 3 4 5 6")
if (self.victory != ''):
print("Victory: ", self.victory)
print('\n', end="")
def stringify(self):
return (str(self.last_move) + np.array_repr(self.board) + self.player) |
e63ebf17f9e55783a8c81d4e88cd29870d62c29c | grvn/aoc2018 | /15/day15-1.py | 3,312 | 3.65625 | 4 | #!/usr/bin/env python3
from sys import argv
from heapq import heappop
from heapq import heappush
#########################################
# Denna innehåller problem med hörnfall #
# påverkar ej resultatet av input #
# dessa är fixade i day15-2.py #
# har ej orkat fixa dem här #
#########################################
atp=3
starthp=200
def main():
elves={}
goblins={}
walls=set()
turns=0
with open(argv[1]) as f:
input=[list(x.strip()) for x in f]
for y,line in enumerate(input):
for x,val in enumerate(line):
if val=='E':
elves[(x,y)]=starthp
elif val=='G':
goblins[(x,y)]=starthp
elif val=='#':
walls.add((x,y))
while elves and goblins:
order=sorted(list(elves)+list(goblins),key=lambda x:(x[1],x[0]))
while order:
# order är sorterad efter ordningen de får röra sig
who=order.pop(0)
if who in elves: # det är en elf
hp=elves.pop(who)
notfoos=elves
foos=goblins
elif who in goblins: # det är en goblin
hp=goblins.pop(who)
notfoos=goblins
foos=elves
else: # död innan den får agera
continue
targets=list(foos)
inuse=set(elves)|set(goblins)|walls
inrange=adjacent(targets)-inuse
nextmove=pickmove(who,inrange,inuse)
if nextmove is None: # kan inte göra något
notfoos[who]=hp
continue
notfoos[nextmove]=hp
if nextmove in inrange: # kan attackera
attack(nextmove,foos)
if elves and goblins:
turns+=1
print(turns*(sum(elves.values())+sum(goblins.values())))
def attack(mypos,targets):
inrange=adjacent({mypos})
postargets=[x for x in inrange if x in targets]
if postargets:
target=min(postargets, key=lambda x: targets[x])
targets[target]-=atp
if targets[target]<=0:
targets.pop(target)
def adjacent(positions):
return set ((x+dx,y+dy) for x,y in positions for dx,dy in [(0,-1),(-1,0),(0,1),(1,0)])
def pickmove(mypos,targetpos,inuse):
if not targetpos: # finns inga rutor bredvid mål som går att nå
return None
if mypos in targetpos:
return mypos
routes=shortestroutes(mypos,targetpos,inuse)
posmove=[x[1] for x in routes]
return min(posmove,key=lambda x:(x[1],x[0])) if posmove else None
def shortestroutes(mypos,targetpos,inuse): # tack google Dijkstra's algoritm
# heapq har ingen sortfunction som man kan skicka lambda till!
# måste invertera x,y för att få sort korrekt
# borde ha haft koordinater som (y,x) från början
# eller söka vidare på google efter prioriterad kö
res=[]
shortest=None
been=set([t[::-1] for t in inuse])
x,y=mypos
todo=[(0,[(y,x)])]
tarpos=[t[::-1] for t in targetpos]
while todo:
dist,path=heappop(todo)
if shortest and len(path)>shortest: # se om vi funnit kortast och gått längre
return res
currpos=path[-1] # ta sista objekt
if currpos in tarpos: # funnit kortast väg
res.append([t[::-1] for t in path])
shortest=len(path)
continue
if currpos in been: # redan besökt
continue
been.add(currpos)
for neigh in adjacent({currpos}):
if neigh in been:
continue
heappush(todo,(dist+1,path+[neigh]))
return res
if __name__ == '__main__':
main()
|
b6d45c2603128eac609cb2199510960df3fbac95 | grvn/aoc2018 | /02/day2-2.py | 437 | 3.53125 | 4 | #!/usr/bin/env python3
from sys import argv
def main():
with open(argv[1]) as f:
input=f.readlines()
id1,id2=next((x,y) for x in input for y in input if sum(1 for a,b in zip(x,y) if a!=b)==1) # Hitta de två rätta ID där endast ett enda tecken diffar
svar="".join(x for x,y in zip(id1,id2) if x==y).strip() # jämför de två rätta och ta bort de tecken som inte stämmer
print(svar)
if __name__ == '__main__':
main()
|
676a6639f3231701b8c3d53f9a5572bc8948e394 | Daniel-HarrisNL/sprintproject | /graphing/main.py | 9,978 | 3.75 | 4 | ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Homework Helper
This program prompts for an input name of an algebraic function then prompts the user for necessary coefficiencts.
It will compute the graph and ask the user if they wish to display the graph or save it to a file.
Authors: Annette Clarke, Nicholas Hodder, Daniel Harris
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
import graphing
import numpy
from matplotlib import pyplot as plt
#Available functions for user to choose from
graph_list = {
"linear" : "f(x) = a*x + b",
"quadratic" : "f(x) = a*x^2 + b*x + c",
"cubic" : "f(x) = a*x^3 + b*x^2 + c*x + d",
"quartic" : "f(x) = a*x^4 + b*x^3 + c*x^2 + d*x + e",
"exponential" : "f(x) = a * b^(c*x + d)",
"logarithmic" : "f(x) = a * log(b*x + c)",
"sine" : "f(x) = a * sin(b*x + c)",
"cos" : "f(x) = a * cos(b*x + c)",
"squareroot" : "f(x) = a * sqrt(b*x + c)",
"cuberoot" : "f(x) = a * sqrt(b*x + c)"
}
def graph_type():
'''
Description: Receives user choice for which function to graph, confirms that the input is an available choice.
Parameters: None
Returns: User selected function type.
'''
while True:
function_type = input("Please select a graph type, or enter 'List' to view available choices: ")
if not function_type.isalpha():
print("Error: Function name must be one word with all alphabetical characters ONLY.")
continue
elif function_type.lower() == "list":
graph_type_list()
elif function_type.lower() not in graph_list:
print("Error: The name provided does not match an available function type.")
continue
else:
print("Graph type selected: {}".format(function_type))
break
return function_type.lower()
def graph_type_list():
'''
Description: Shows a list of all available graph types which user can select from
Paramaters: None
Returns: Nothing
'''
print("Here is a list of available graph types, displaying name and function:\n")
for key,value in graph_list.items():
print("{}: {}\n".format(key.upper(),value))
return
def get_range(graph_type_chosen):
'''
Description: Recieves user inputs for the range start, end and spacing.
Paramaters:
graph_type_chosen - A string containing the user selected graph type
Returns: Starting range, ending range, and range spacing.
'''
while True:
try:
range_start = int(input("Input the start of the range: "))
range_end = int(input("Input the end of the range: "))
range_spacing = int(input("Input the number of points to generate: "))
if range_start > range_end:
print("Error: Starting range value must be less than ending range value.")
continue
if (graph_type_chosen == "logarithmic" or graph_type_chosen == "squareroot") and (range_start < 0 or range_end < 0):
print("Error: Logarithmic and Square root functions must have non-negative range.")
continue
if (range_start < -2147483648) or (range_end > 2147483647):
print("Warning: Extremely large ranges may potentially not work as intended on certain hardware.")
break
except:
print("Error: Must be a number")
continue
return range_start, range_end, range_spacing
def feature_choices():
'''
Description: Prompts user for their choice of graph features, validates the feature name within a loop until correct value entered.
Paramaters: None
Returns: A list of features configured with user input, with 'legend' on its own as True or False.
'''
xlabel = None
ylabel = None
title = None
features = [xlabel, ylabel, title]
fname = ["x-axis", "y-axis", "title"]
counter = 0
while counter < len(features):
while True:
features[counter] = input("Enter a label for the " + fname[counter] + " or leave blank to skip: ")
is_valid = validate(features[counter])
counter = counter + 1
if is_valid == "skip":
features[counter-1] = False
break
elif is_valid == True:
break
#If the entry is invalid the loop will restart, so decrement the counter to retry last value.
counter = counter - 1
legend = input("Enter 'Y' to include a legend or submit any other input (including blank) to skip: ")
if legend.isspace() or legend.lower != 'y' or not legend:
legend = False
return features, legend
def validate(name, deny_special_chars = False):
'''
Description: Validates user inputs with naming conventions,
Paramaters:
name - String to be validated with the convention tests
deny_special_chars - Default false, true if no characters other than alphanumeric are permitted.
Returns: True if name string passes test, false if string fails.
'''
if (name.isspace() or not name) and not deny_special_chars:
return "skip"
elif not name[0].isalnum():
print("Error: Name must begin with an alphanumeric character.")
return False
if deny_special_chars:
if not name.isalnum():
print("Error: Name must contain only alphanumeric characters.")
return False
return True
def draw_graph(x,y,graph_type_chosen,xlabel,ylabel,title,legend):
'''
Description: Renders the graph using all data obtained throughout program
Paramaters:
x - List of all x coordinates
y - List of all y coordinates
graph_type_chosen - A string containing the user selected graph type
xlabel - User input string for x-axis name, default None if skipped.
ylabel - User input string for y-axis name, default None if skipped.
title - User input string for graph title, default None if skipped.
legend - Boolean determined by user selection
Returns: Nothing.
'''
# Set axis of the graph including negative numbers
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
#If the x-range is negative, shift the spines
if any(x < 0):
ax.spines['left'].set_position('center')
#else:
# ax.spines['left'].set_position('zero')
#If the y-range is negative, shift the spines
if any(y < 0):
ax.spines['bottom'].set_position('center')
#else:
# ax.spines['bottom'].set_position('zero')
#Static settings
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#Plot the graph and assign it a legend label according to it's type
plt.plot(x,y, label=graph_type_chosen)
#Draw the optional graph features if selected by the user
if xlabel and any(y < 0):
plt.xlabel(xlabel, veticalalignment='bottom')
elif xlabel:
plt.xlabel(xlabel)
if ylabel and any(x < 0):
plt.ylabel(ylabel, horizontalalignment='left')
elif ylabel:
plt.ylabel(ylabel)
if legend:
plt.legend()
if title:
plt.title(title)
def save_graph():
'''
Description: Saves the graph to a filename defined by user
Paramaters: None
Returns: Nothing.
'''
file_name = input ("Please name the file (it will save as a .png): ")
while not validate(file_name, deny_special_chars = True):
file_name = input("Please try again, enter a valid file name: ")
plt.savefig(file_name + ".png")
return
#Program Start
if __name__ == "__main__":
while True:
#Prompt for graph type
graph_type_chosen = graph_type()
#Assign the range using get_range() NOTE: Start value must be assigned before end value followed by spacing.
range_start, range_end, range_spacing = get_range(graph_type_chosen)
x = numpy.linspace(range_start, range_end, range_spacing)
#Determine graphing function from graphing.py using graph_type_chosen (function name as a string), use get_function() to execute the retrieved function.
get_function = getattr(graphing, graph_type_chosen)
y = get_function(x)
#Input choices for graph features.
features, legend = feature_choices()
xlabel = features[0]
ylabel = features[1]
title = features[2]
#Render the graph in memory
draw_graph(x,y,graph_type_chosen,xlabel,ylabel,title,legend)
#Display or Save
while True:
output_type = input("Would you like to save or display the graph? Please enter 'S' or 'D': ")
if not validate(output_type):
print("Please try again.")
continue
output_type = output_type.lower()
if output_type == "d":
plt.show()
break
elif output_type == "s":
save_graph()
break
else:
print("Error: Wrong character entered, please select one of the options.")
#Continue or end
cont = input("Would you like to make a new graph? Enter 'Y' to continue or any other input to exit.")
if cont.lower() != "y":
break
|
56351369d6585b08ddc07a36b49e940e08003dae | Omkar-Atugade/Python-Function-Files-and-Dictionaries | /week2.py | 8,680 | 4.1875 | 4 | #1. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals.
#Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as each key’s value.
#ANSWER :
medal_count={'United States':70,'Great Britain':38,'China':45,'Russia':30,'Germany':17}
#2. Given the dictionary swimmers, add an additional key-value pair to the dictionary with "Phelps" as the key and the integer 23 as the value.
# Do not rewrite the entire dictionary.
#ANSWER :
swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4}
swimmers['Phelps']=23
#3. Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3.
# Do not rewrite the entire dictionary.
#ANSWER :
sports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2}
sports_periods['hockey']=3
#4. The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics.
#But today, Spain won 2 more gold medals.
#Update golds to reflect this information.
#ANSWER :
golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29}
golds['Spain']=21
#5. Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries.
# Do not hard code this.
#ANSWER :
golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29}
countries=golds
#6. Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point in the 2016 Rio Olympics.
#Using dictionary mechanics, assign the medal count value for "Belarus" to the variable belarus.
#Do not hardcode this.
#ANSWER :
medal_count = {'United States': 70, 'Great Britain':38, 'China':45, 'Russia':30, 'Germany':17, 'Italy':22, 'France': 22, 'Japan':26, 'Australia':22, 'South Korea':14, 'Hungary':12, 'Netherlands':10, 'Spain':5, 'New Zealand':8, 'Canada':13, 'Kazakhstan':8, 'Colombia':4, 'Switzerland':5, 'Belgium':4, 'Thailand':4, 'Croatia':3, 'Iran':3, 'Jamaica':3, 'South Africa':7, 'Sweden':6, 'Denmark':7, 'North Korea':6, 'Kenya':4, 'Brazil':7, 'Belarus':4, 'Cuba':5, 'Poland':4, 'Romania':4, 'Slovenia':3, 'Argentina':2, 'Bahrain':2, 'Slovakia':2, 'Vietnam':2, 'Czech Republic':6, 'Uzbekistan':5}
belarus=medal_count.get('Belarus')
#7. The dictionary total_golds contains the total number of gold medals that countries have won over the course of history.
# Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds.
#Do not hard code this!
#ANSWER :
total_golds = {"Italy": 114, "Germany": 782, "Pakistan": 10, "Sweden": 627, "USA": 2681, "Zimbabwe": 8, "Greece": 111, "Mongolia": 24, "Brazil": 108, "Croatia": 34, "Algeria": 15, "Switzerland": 323, "Yugoslavia": 87, "China": 526, "Egypt": 26, "Norway": 477, "Spain": 133, "Australia": 480, "Slovakia": 29, "Canada": 22, "New Zealand": 100, "Denmark": 180, "Chile": 13, "Argentina": 70, "Thailand": 24, "Cuba": 209, "Uganda": 7, "England": 806, "Denmark": 180, "Ukraine": 122, "Bahamas": 12}
chile_golds=total_golds.get("Chile")
#8. Provided is a dictionary called US_medals which has the first 70 metals that the United States has won in 2016, and in which category they have won it in.
# Using dictionary mechanics, assign the value of the key "Fencing" to a variable fencing_value.
#Remember, do not hard code this.
#ANSWER :
US_medals = {"Swimming": 33, "Gymnastics": 6, "Track & Field": 6, "Tennis": 3, "Judo": 2, "Rowing": 2, "Shooting": 3, "Cycling - Road": 1, "Fencing": 4, "Diving": 2, "Archery": 2, "Cycling - Track": 1, "Equestrian": 2, "Golf": 1, "Weightlifting": 1}
fencing_value=US_medals.get('Fencing')
#9. The dictionary Junior shows a schedule for a junior year semester.
#The key is the course name and the value is the number of credits.
#Find the total number of credits taken this semester and assign it to the variable credits.
#Do not hardcode this – use dictionary accumulation!
#ANSWER :
Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3}
credits=0
for i in Junior.values():
credits=credits+i
#10. Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value.
#ANSWER :
str1 = "peter piper picked a peck of pickled peppers"
freq={}
for c in str1:
if c not in freq:
freq[c]=0
freq[c]=freq[c]+1
#11. Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1 and the number of times it occurs.
#ANSWER :
s1 = "hello"
counts={}
for c in s1:
if c not in counts:
counts[c]=0
counts[c]=counts[c]+1
#12. Create a dictionary, freq_words, that contains each word in string str1 as the key and its frequency as the value.
#ANSWER :
str1 = "I wish I wish with all my heart to fly with dragons in a land apart"
x=str1.split()
freq_words={}
for c in x:
if c not in freq_words:
freq_words[c]=0
freq_words[c]=freq_words[c]+1
#13. Create a dictionary called wrd_d from the string sent, so that the key is a word and the value is how many times you have seen that word.
#ANSWER :
sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good"
x=sent.split()
wrd_d={}
for c in x:
if c not in wrd_d:
wrd_d[c]=0
wrd_d[c]=wrd_d[c]+1
#14. Create the dictionary characters that shows each character from the string sally and its frequency.
#Then, find the most frequent letter based on the dictionary.
#Assign this letter to the variable best_char.
#AMSWER :
sally = "sally sells sea shells by the sea shore"
characters={}
for c in sally:
if c not in characters:
characters [c]=0
characters[c]=characters [c]+1
#15. Find the least frequent letter.
# Create the dictionary characters that shows each character from string sally and its frequency.
#Then, find the least frequent letter in the string and assign the letter to the variable worst_char.
#ANSWER :
sally = "sally sells sea shells by the sea shore and by the road"
characters={}
for i in sally:
characters [i]=characters.get(i,0)+1
sorted (characters.items(), key=lambda x: x[1])
worst_char=sorted(characters.items(), key=lambda x: x[1])[-13][0]
#16. Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1.
# Challenge: Letters should not be counted separately as upper-case and lower-case.
#Intead, all of them should be counted as lower-case.
#ANSWER :
string1 = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures."
string1.lower()
letter_counts={}
for c in string1.lower():
if c not in letter_counts:
letter_counts[c]=0
letter_counts[c]=letter_counts[c]+1
#17: Create a dictionary called low_d that keeps track of all the characters in the string p and notes how many times each character was seen.
#Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as a “t” for example.
#ANSWER :
p = "Summer is a great time to go outside. You have to be careful of the sun though because of the heat."
p.lower()
low_d={}
for c in p.lower():
if c not in low_d:
low_d[c]=0
low_d[c]=low_d[c]+1
|
971187848e721a42aec82fb6aa5d13f881d84ff4 | johnmwalters/dsp | /python/q8_parsing.py | 1,242 | 4.40625 | 4 | # The football.csv file contains the results from the English Premier League.
# The colums labeled 'Goals and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in 'for' and 'against' goals.
import csv
def read_data(data):
with open(data) as csvfile:
reader = csv.DictReader(csvfile)
low_diff = 9999
club = ''
for row in reader:
print row['Team'], row['Games'], row['Wins'], row['Losses'], row['Draws'],row['Goals'], row['Goals Allowed'], row['Points']
goal_difference = int(row['Goals']) - int(row['Goals Allowed'])
abs_goal_difference = abs(int(row['Goals']) - int(row['Goals Allowed']))
print abs_goal_difference
if abs_goal_difference < low_diff:
club = row['Team']
print club
low_diff = abs_goal_difference
else:
low_diff = low_diff
print club
# COMPLETE THIS FUNCTION
#def get_min_score_difference(self, parsed_data):
# COMPLETE THIS FUNCTION
#def get_team(self, index_value, parsed_data):
# COMPLETE THIS FUNCTION
read_data('football.csv')
|
e14986cfefedad1430fb1686076503a05adcc7e1 | pavelkasyanov/euler_problems | /src/problem_5/main.py | 345 | 3.75 | 4 | def ifDividesAll(num):
for i in (3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19):
if num % i != 0:
return False
return True
def main():
num = 20
while True:
if ifDividesAll(num):
break
else:
num = num + 10
print(num)
if __name__ == '__main__':
main()
|
09ebba380e8d5b0fb3681b64d0b9613293f0769b | pavelkasyanov/euler_problems | /src/problem_2/main.py | 474 | 3.8125 | 4 | MAX_FIB_NUMBER = 4 * 1000000
def main():
result_sum = 2
n1 = 1
n2 = 2
while True:
print("=== start iteration ===")
print("n1={}, n2={}".format(n1, n2))
n = n1 + n2
print("n={}".format(n))
if n > MAX_FIB_NUMBER:
print("result sum={}".format(result_sum))
return
if n % 2 == 0:
result_sum += n
n1 = n2
n2 = n
if __name__ == '__main__':
main()
|
714808135eb230b3fca687200a112a888a7809fd | dutraph/python_2021 | /basic/while_calc.py | 675 | 4.21875 | 4 | while True:
print()
n1 = input("Enter 1st number: ")
n2 = input("Enter 2nd number: ")
oper = input("Enter the operator: ")
if not n1.isnumeric() or not n2.isnumeric():
print("Enter a valid number...")
continue
n1 = int(n1)
n2 = int(n2)
if oper == '+':
print(n1 + n2)
elif oper == '-':
print(n1 - n2)
elif oper == '*':
print(n1 * n2)
elif oper == '/':
div = n1 / n2
print(f'{div:.2f}')
else:
print("Must enter a valid operator..")
continue
print(end='\n\n')
exit = input("Exit? [y/n]: ")
if exit == 'y':
break |
fa747700c4617f59a616d2f7cf12d8ad3e85e77f | dutraph/python_2021 | /basic/guess_game.py | 853 | 4.09375 | 4 | secret = 'avocado'
tries = []
chances = 3
while True:
if chances <= 0:
print("You lose")
break
letter = input('Type a letter: ')
if len(letter) > 1:
print('type 1 letter...')
continue
tries.append(letter)
if letter in secret:
print(f'awesome letter {letter} exists...')
else:
print(f'you missed it... {letter} doesnt exists...')
tries.pop()
secret_temp = ''
for secret_letter in secret:
if secret_letter in tries:
secret_temp += secret_letter
else:
secret_temp += '*'
if secret_temp == secret:
print(f'you win... {secret_temp} is the word.')
break
else:
print(secret_temp)
if letter not in secret:
chances -= 1
print(f'you still get {chances} chances...')
print()
|
c750ed33c5ec4069676685a31f4257f58055d9b0 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio023 - Separando digitos de um numero.py | 811 | 4.1875 | 4 | """ Desafio 023
Faça um programa que leia um número de 0 a 9999 e mostre na tela um dos dígitos separados.
Ex: Digite um número: 1834
Unidade: 4
Dezena: 3
Centena: 8
Milhar: 1 """
# Solução 1: com está solução só é possível obter o resulatdo esperado quando se coloca as quatro unidades
num = input('Digite um número entre 0 e 9999: ')
print('Unidade: {} \nDezena: {} \nCentena: {} \nMilhar: {}'.format(num[3], num[2], num[1], num[0]))
# Solução 2: com a lógica matematica é possível obter o resultado desejado independente de quantas unidades sejam usadas
n = int(input('Digite um número entre 0 e 9999: '))
u = n % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print('O número {} tem: \nUnidade(s): {} \nDezena(s): {} \nCentena(s): {} \nMilhar(es): {}'.format(n, u, d, c, m))
|
c2e3b043f0166381203eeda2ef0305c7f67a9290 | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio064 - Tratando varios valores v1.0.py | 556 | 4.0625 | 4 | """ Desafio 064
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor
999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag) """
num = int(input('Informe um número ou 999 para parar: '))
soma = cont = 0
while num != 999:
soma += num
cont += 1
num = int(input('Informe um número ou 999 para parar: '))
print('Foram digitados {} números e a soma entre eles é {}'.format(cont, soma))
|
6282e26c75b7c3673cdbbe6a5418af6232cfa647 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio035 - Analisando triangulos v1.0.py | 574 | 4.21875 | 4 | """ Desafio 035
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo
"""
reta1 = float(input('Informe o valor da primeira reta:'))
reta2 = float(input('Informe o valor da segunda reta:'))
reta3 = float(input('Informe o valor da terceira reta:'))
if (reta2 - reta3) < reta1 < reta2 + reta3 and (reta1 - reta3) < reta2 < reta1 + reta3 and (reta1 - reta2) < reta3 < \
reta1 + reta2:
print('Essas retas podem forma um triângulo')
else:
print('Essas retas não podem formam um triângulo')
|
dd1ae1af46e3a860d227f51cc14f5270e6e4d66d | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio004 - Dissecando uma variavel.py | 718 | 4.25 | 4 | """ Desafio 004
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis
sobre ele """
msg = input(' Digite algo: ')
print('O valor {} e ele é do tipo primitivo desse valor é {}'.format(msg, type(msg)))
print('Esse valor é númerico? {}'.format(msg.isnumeric()))
print('Esse valor é alfabetico? {}'.format(msg.isalpha()))
print('Esse valor é alfanúmerico? {}'.format(msg.isalnum()))
print('Esse valor está todo em maiúsculo? {}'.format(msg.isupper()))
print('Esse valor está todo em minúsculo? {}'.format(msg.islower()))
print('Esse valor tem espaços? {}'.format(msg.isspace()))
print('Esse valor está capitalizado? {}'.format(msg.istitle()))
|
1bc9ada8524c22e186391996992ee6458c992b98 | nataliaqsoares/Curso-em-Video | /Mundo 03/desafio075 - Analise de dados em uma tupla.py | 853 | 4.28125 | 4 | """ Desafio 075
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: a) quantas vezes
apareceu o valor 9; b) em que posição foi digitado o primeiro valor 3; c) quais foram os números pares; """
conjunto = (int(input('Informe um número: ')), int(input('Informe um número: ')), int(input('Informe um número: ')),
int(input('Informe um número: ')),)
cont = 0
print(f'Foram informados os números: {conjunto}\nO 9 apareceu {conjunto.count(9)} vezes')
if conjunto.count(3) == 0:
print(f'O número 3 não foi informado')
else:
print(f'O 3 apareceu na {conjunto.index(3) + 1}º posição')
print(f'Os números pares digitados foram: ', end='')
for num in conjunto:
if num % 2 == 0:
print(num, end=' ')
else:
cont += 1
if cont == 4:
print('nenhum')
|
0048caeb7b3546c1ae8cc917685d0df5242ad2b3 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio033 - Maior e menor valores.py | 600 | 4.15625 | 4 | """ Desafio 033
Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """
n1 = int(input('Informe um número: '))
n2 = int(input('Informe mais um número: '))
n3 = int(input('Informe mais um número: '))
maior = 0
menor = 0
if n1 > n2 and n1 > n3:
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n2:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
print('Dos três números informados o maior número é {} e o menor número é {}'.format(maior, menor))
|
474e5fbf97eca5b09a0527b9cf59290b4f4ff08c | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio053 - Detector de palindromo.py | 579 | 3.921875 | 4 | """ Desafio 053
Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços.
Ex.: Apos a sopa / A sacada da casa / A torre da derrota / O lobo ama o bolo / Anotaram a data da maratona """
frase = str(input('Informe uma frase: ')).lower().split()
frase = ''.join(frase)
cont_frase = len(frase)-1
cont = 0
for c in range(0, len(frase)):
if frase[c] == frase[cont_frase]:
cont += 1
cont_frase -= 1
if len(frase) == cont:
print('Essa frase é um palíndromo')
else:
print('Essa frase não é um palíndromo')
|
fccf2bdb5f6afe42e695468b8cefc57fedb19783 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio028 - Jogo de Adivinhacao v.1.0.py | 526 | 4.25 | 4 | """ Desafio 028
Escreva um programa que faça o computador 'pensar' em um número inteiro entre 0 e 5 e peça para o usuário tentar
descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu
"""
from random import randint
print('Estou pensando em um número entre 0 e 5...')
n1 = randint(0, 5)
n2 = int(input('Em qual número eu pensei? '))
if n1 == n2:
print('Você acertou!')
else:
print('Você errou! Eu estava pensando no número {}'.format(n1))
|
693dd4620876b1525d56d4b03c47a34f032feb20 | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio036 - Aprovando emprestimo.py | 842 | 4.1875 | 4 | """ Desafio 036
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da
casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não
pode exceder 30% do salário ou então o empréstimo será negado """
valor_casa = float(input('Qual valor da casa que deseja financiar? R$'))
salario = float(input('Qual seu salário mensal? R$'))
anos = int(input('Em quantos anos deseja pagar a casa? '))
prestacao = valor_casa / (anos * 12)
if prestacao >= (salario * 0.3):
print('Infelizmente não foi possível financiar está casa no momento')
else:
print('Seu financiamento foi aprovado! As prestações mensais para pagar a casa de {:.2f} em {} anos são de {:.2f}'
.format(valor_casa, anos, prestacao))
|
4fdbc344aff48594e6fedfe984943a25854f6aed | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio012 - Calculando desconto.py | 292 | 3.65625 | 4 | """ Desafio 012
Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto """
preco = float(input('Informe o preço do produto: '))
novopreco = preco - (preco * 0.05)
print('O produto de preço {} com desconto fica por {:.2f}'.format(preco, novopreco))
|
b32e3fa30f283a656532c6154c7795e319ef6c84 | nataliaqsoares/Curso-em-Video | /Mundo 03/desafio100 - Funcoes para sortear e somar.py | 754 | 4.0625 | 4 | """ Desafio 100
Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função
vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores
pares sorteados pela função anterior """
from random import randint
from time import sleep
def sorteia(lst):
print('Sorteando os 5 valores da lista: ', end='')
for c in range(0, 5):
n = randint(0, 10)
lst.append(n)
print(n, end=' ')
sleep(1)
print('Pronto!')
def somaPar(lst):
s = 0
for c in lst:
if c % 2 == 0:
s += c
print(f'Somando os valores pares de {lst}, temos {s}')
num = []
sorteia(num)
somaPar(num)
|
967aa21504999e6fd116ebd555c548bc26f6903c | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio002.1 - Data de nascimento.py | 514 | 4.125 | 4 | """ Desafio002.1
Crie um programa que leia o dia, o mês e o ano de nascimento de uma pessoa e mostre uma mensagem com a data
formatada (mensagem de saida = Você nasceu no dia x de x de x. Correto?) """
# Solução 1
nasci = input('Quando você nasceu? ')
print('Você nasceu em', nasci, 'Correto?')
# Solução 2
dia = input('Em qual dia você nasceu? ')
mes = input('Em qual mês você nasceu? ')
ano = input('Em qual ano você nasceu? ')
print('Você nasceu no dia', dia, 'de', mes, 'de', ano, 'Correto?')
|
acfc2d6ff4b396815192db8f0e87fc8a514fc55d | Guilherme-Avellar/primeiras_aulas | /jogo do ppt aprimorado.py | 1,227 | 4.03125 | 4 | # jogo do pedra, papel ou tesoura, com biblioteca de sorteio
print("Jogo do pedra papel ou tesoura")
player = input("Joque pedra, papel ou tesoura: ")
from random import *
computador = randint(0,2)
if player == "pedra" or player == "Pedra" or player == "PEDRA":
player = 0
else:
if player == "papel" or player == "Papel" or player == "PAPEL":
player = 1
else:
if player == "tesoura" or player == "Tesoura" or player == "TESOURA":
player = 2
else:
computador = "O computador não jogou"
player = 3
if player < 0 or player > 2:
print("O jogo feito está escrito errado ou está inválido")
else:
if player == computador:
print("Empate")
else:
if (player == 0 and computador == 2) or (player == 1 and computador == 0) or (player == 2 and computador == 1):
print("Você venceu")
else:
print("Derrota")
if computador == 0:
computador = "O computador jogou pedra"
else:
if computador == 1:
computador = "O computador jogou papel"
else:
if computador == 2:
computador = "O computador jogou tesoura"
print(computador) |
a916c4834eeb10336fe9c75e2e58e83684fafac8 | thales-mro/python-cookbook | /3-numbers-dates-hours/15-convert-string-to-datetime.py | 487 | 4.0625 | 4 | from datetime import datetime
#way faster solution than showed in main()
def parse_ymd(s):
year_s, month_s, day_s = s.split('-') # only works if you know the string format
return datetime(int(year_s), int(month_s), int(day_s))
def main():
text = '2020-01-25'
y = datetime.strptime(text, '%Y-%m-%d')
z = datetime.now()
diff = z - y
print(diff)
print(datetime.strftime(y, '%A %B %d, %Y'))
print(parse_ymd(text))
if __name__ == "__main__":
main() |
68a32e533997a2817579198a90aafaad911e3fbd | thales-mro/python-cookbook | /2-strings/5-search-and-replace.py | 650 | 3.9375 | 4 | import re
from calendar import month_abbr
def replace_callback(m):
mon_name = month_abbr[int(m.group(2))]
return '{} {} {}'.format(m.group(1), mon_name, m.group(3))
def main():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.replace('yeah', 'yep'))
text = "Today is 02/01/2020. In a week it will be 09/01/2020."
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
print(datepat.sub(r'\3-\2-\1', text))
print(datepat.sub(replace_callback, text))
print("If it is desired to know the number of replacements:")
_, n = datepat.subn(r'\3-\2-\1', text)
print(n)
if __name__ == "__main__":
main() |
499b850f68b05aceb843bcd4f6f94c9cb1077afc | thales-mro/python-cookbook | /2-strings/4-pattern-match-and-search.py | 1,181 | 4.125 | 4 | import re
def date_match(date):
if re.match(r'\d+/\d+/\d+', date):
print('yes')
else:
print('no')
def main():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.find('no'))
date1 = '02/01/2020'
date2 = '02 Jan, 2020'
date_match(date1)
date_match(date2)
print("For multiple uses, it is good to compile the regex")
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(date1):
print("yes")
else:
print("no")
if datepat.match(date2):
print("yes")
else:
print("no")
text = "Today is 02/01/2020. In a week it will be 09/01/2020."
print(datepat.findall(text))
print("Including capture groups (in parenthesis)")
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datepat.match('26/09/1998')
print(m)
print(m.group(0), m.group(1), m.group(2), m.group(3), m.groups())
print(datepat.findall(text))
for month, day, year in datepat.findall(text):
print('{}--{}--{}'.format(year, month, day))
print("With finditer:")
for m in datepat.finditer(text):
print(m.groups())
if __name__ == "__main__":
main() |
881166784fd6a82253a5b189f956582a7a8de5e0 | firebirdrazer/CodingTests | /check_paren.py | 1,952 | 4.40625 | 4 | def check_bracket(Str):
stack = [] #make a empty check stack
while Str != "": #as long as the input is not empty
tChar = Str[0] #extract the first character as the test character
Str = Str[1:] #the rest characters would be the input in the next while loop
if tChar == "(" or tChar == "{": #as the test character is a left-bracket "(" or "{"
stack.append(tChar) #the character would be added into the stack
elif tChar == ")" or tChar == "}": #if the test character is a right-bracket ")" or "}"
if len(stack) == 0: #then we have to check the stack to see if there's a corresponding one
return False #if no or empty, the string would be invalid
else: #if yes, we can pop the corresponding character from the stack
if tChar == ")" and stack[-1] == "(":
stack.pop(-1)
elif tChar == "}" and stack[-1] == "{":
stack.pop(-1)
else:
return False
if stack == []: #which means if the string is valid, the stack would be empty
return True #after the process
else: #if there's anything left after the process
return False #the function would return False
#main program
Test=input() #input string
print(check_bracket(Test)) #return True if the input has valid brackets |
5794112ddeb0e6706ded784d7fec7249659e9450 | mango915/haliteRL | /Modules/encode.py | 22,954 | 3.84375 | 4 | import numpy as np
def one_to_index(V,L):
"""
Parameters
----------
V: LxL matrix with one entry = 1 and the others = 0
L: linear dimension of the square matrix
Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row.
Returns
-------
integer corresponding to the non-zero element of V.
"""
return np.arange(L**2).reshape((L, L))[V.astype(bool)]
def encode(v_dec, L):
"""
Parameters
----------
v_dec: list or numpy array of two integers between 0 and L
L : linear dimension of the square matrix
Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row.
Returns
-------
integer corresponding to the element (v_dec[0],v_dec[1]) of the encoding matrix.
"""
V = np.arange(0,L**2).reshape((L,L))
v_enc = V[v_dec[0],v_dec[1]]
return v_enc
def decode(v_enc, L):
"""
Parameters
----------
v_enc: scalar between 0 and L**2 - 1, is the encoding of a position (x,y)
L : linear dimension of the square matrix
Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row.
Returns
-------
numpy array containg the row and the column corresponding to the matrix element of value v_enc.
"""
V = np.arange(0,L**2).reshape((L,L))
v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0]])
return v_dec
def get_halite_vec_dec_v0(state, q_number = 3, map_size = 7):
"""
Parameters
----------
state: [map_size,map_size,>=3] numpy array, which layers are:
Layer 0: map halite,
Layer 1: ship position,
Layer 2: halite carried by the ships (a.k.a. cargo)
q_number : number of quantization levels
map_size : linear size of the squared map
Returns
-------
quantized halite vector [𝐶,𝑂,𝑆,𝑁,𝐸,𝑊], numpy array of shape (6,)
(where C stands for the halite carried by the ship and O for the cell occupied by the ship)
"""
def halite_quantization(halite_vec, q_number = 3):
"""
Creates q_number thresholds [t0,t1,t2] equispaced in the log space.
Maps each entry of halite_vec to the corresponding level:
if h <= t0 -> level = 0
if t0 < h <= t1 -> level = 1
else level = 2
Parameters
----------
halite_vec : numpy array which elements are numbers between 0 and 1000
q_number : number of quantization levels
Returns
-------
level : quantized halite_vec according to the q_number thresholds
"""
# h can either be a scalar or a matrix
tresholds = np.logspace(1,3,q_number) # [10, 100, 1000] = [10^1, 10^2, 10^3]
h_shape = halite_vec.shape
h_temp = halite_vec.flatten()
mask = (h_temp[:,np.newaxis] <= tresholds).astype(int)
level = np.argmax(mask, axis = 1)
return level.reshape(h_shape)
pos_enc = one_to_index(state[:,:,1], map_size)
pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices
ship_cargo = state[pos_dec[0],pos_dec[1],2]
cargo_quant = halite_quantization(ship_cargo).reshape(1)[0] # quantize halite
map_halite = state[:,:,0]
halite_quant = halite_quantization(map_halite) # quantize halite
halite_vector = []
halite_vector.append(cargo_quant)
halite_vector.append(halite_quant[pos_dec[0], pos_dec[1]])
halite_vector.append(halite_quant[(pos_dec[0]+1)%map_size, pos_dec[1]])
halite_vector.append(halite_quant[(pos_dec[0]-1)%map_size, pos_dec[1]])
halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]+1)%map_size])
halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]-1)%map_size])
return np.array(halite_vector)
def get_halite_vec_dec(state, map_h_thresholds = np.array([100,500,1000]),
cargo_thresholds = np.array([200,400,800,1000]), map_size = 7):
"""
Parameters
----------
state: numpy array, shape (map_size,map_size,>=3), which layers are:
Layer 0: map halite,
Layer 1: ship position,
Layer 2: halite carried by the ships (a.k.a. cargo)
map_h_thresholds: quantization thresholds for halite in map's cells
cargo_thresholds: quantization thresholds for cargo
map_size : int, linear size of the squared map
Returns
-------
quantized halite vector [𝐶,𝑂,𝑆,𝑁,𝐸,𝑊], numpy array of shape (6,)
(where C stands for the halite carried by the ship and O for the cell occupied by the ship)
"""
def halite_quantization(halite_vec, thresholds):
"""
Maps each entry of halite_vec to the corresponding quantized level:
if h <= t0 -> level = 0
if t0 < h <= t1 -> level = 1
and so on
Parameters
----------
halite_vec : numpy array which elements are numbers between 0 and 1000
thresholds : quantization thresholds
Returns
-------
level : quantized halite_vec according to the q_number thresholds
"""
# h can either be a scalar or a matrix
h_shape = halite_vec.shape
h_temp = halite_vec.flatten()
mask = (h_temp[:,np.newaxis] <= thresholds).astype(int)
level = np.argmax(mask, axis = 1)
return level.reshape(h_shape)
pos_enc = one_to_index(state[:,:,1], map_size)
pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices
ship_cargo = state[pos_dec[0],pos_dec[1],2]
cargo_quant = halite_quantization(ship_cargo, cargo_thresholds).reshape(1)[0] # quantize halite
map_halite = state[:,:,0]
halite_quant = halite_quantization(map_halite, map_h_thresholds) # quantize halite
halite_vector = []
halite_vector.append(cargo_quant)
halite_vector.append(halite_quant[pos_dec[0], pos_dec[1]])
halite_vector.append(halite_quant[(pos_dec[0]+1)%map_size, pos_dec[1]])
halite_vector.append(halite_quant[(pos_dec[0]-1)%map_size, pos_dec[1]])
halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]+1)%map_size])
halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]-1)%map_size])
return np.array(halite_vector)
def get_halite_direction(state, map_size = 7):
"""
Returns the direction richest in halite given the ship position.
Works only for a single ship.
Parameters
----------
state: [map_size,map_size,>=3] numpy array
Layer 0: map halite
Layer 1: ship position
Layer 2: halite carried by the ships (a.k.a. cargo)
map_size : linear size of the squared map
Returns
-------
h_dir : int
Dictionary to interpret the output:
{0:'S', 1:'N', 2:'E', 3:'W'}
"""
def roll_and_crop(M, shift, axis, border = 1, center = (3,3)):
"""
Shift matrix and then crops it around the center keeping a border.
Inputs
------
M : squared matrix in numpy array
Matrix to be rolled and cropped
shift : int or tuple of ints
The number of places by which elements are shifted. If a tuple,
then `axis` must be a tuple of the same size, and each of the
given axes is shifted by the corresponding number. If an int
while `axis` is a tuple of ints, then the same value is used for
all given axes.
axis : int or tuple of ints, optional
Axis or axes along which elements are shifted. By default, the
array is flattened before shifting, after which the original
shape is restored.
border : int
Border around central cell (after the shift) to be cropped.
The resulting area is of 2*border+1 x 2*border+1
Parameters
----------
M_cut : numpy matrix of shape (2*border+1,2*border+1)
"""
M_temp = np.roll(M, shift = shift, axis = axis)
M_crop = M_temp[center[0]-border:center[0]+border+1, center[1]-border:center[1]+border+1]
return M_crop
map_halite = state[:,:,0] # matrix with halite of each cell of the map
shipy_pos_matrix = state[:,:,3] # matrix with 1 in presence of the shipyard, zero otherwise
pos_enc = one_to_index(state[:,:,1], map_size) # ship position
pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices
shipy_enc = one_to_index(shipy_pos_matrix, map_size) # shipyard position
shipy_dec = decode(shipy_enc, map_size) #position_decoded
shift = (shipy_dec[0]-pos_dec[0],shipy_dec[1]-pos_dec[1])
centered_h = np.roll(map_halite, shift = shift, axis = (0,1)) #centers map_halite on the ship
mean_cardinal_h = []
# this could be generalized to wider areas, like 5x5, but 3x3 it's enough for a 7x7 map
perm = [(a,sh) for a in [0,1] for sh in [-2,2]] # permutations of shifts and axis to get the 4 cardinal directions
for a,sh in perm:
mean_h = np.mean(roll_and_crop(centered_h, shift = sh, axis = a), axis = (0,1))
mean_cardinal_h.append(mean_h)
mean_cardinal_h = np.array(mean_cardinal_h)
halite_direction = np.argmax(mean_cardinal_h) #+ 1 # take the direction of the 3x3 most rich zone
return halite_direction
def encode_vector(v_dec, L = 6, m = 3):
"""
Encodes a vector of L integers ranging from 0 to m-1.
Parameters
----------
v_dec: list or numpy array of L integers between 0 and m
L : length of the vector
Assign increasing integers starting from 0 up to m**L to an m-dimensional matrix "row by row".
Returns
-------
integer corresponding to the element (v_dec[0],v_dec[1],...,v_dec[L-1]) of the encoding tensor.
"""
T = np.arange(m**L).reshape(tuple([m for i in range(L)]))
return T[tuple(v_dec)]
def encode_vector_v1(v_dec, ranges):
"""
Encodes a vector of len(ranges), whose i-th elements ranges from 0 to ranges[i].
Parameters
----------
v_dec : list or numpy array of integers
ranges : ranges of possible values for each entry of v_dec
Returns
-------
integer corresponding to the element (v_dec[0],v_dec[1],...,v_dec[-1]) of the encoding tensor.
"""
tot_elements = 1
for r in ranges:
tot_elements = tot_elements * r
T = np.arange(tot_elements).reshape(tuple(ranges))
return T[tuple(v_dec)]
def decode_vector(v_enc, L = 6, m = 3):
"""
Decodes an encoding for a vector of L integers ranging from 0 to m-1.
Parameters
----------
v_enc: scalar between 0 and m**L - 1, is the encoding of a position (x1,x2,...,xL)
L : length of the vector
Assign increasing integers starting from 0 up to m**L to an m-dimensional matrix "row by row".
Returns
-------
numpy array containg the indexes corresponding to the tensor element of value v_enc.
"""
T = np.arange(m**L).reshape(tuple([m for i in range(L)]))
return np.array([np.where(v_enc == T)[i][0] for i in range(L)])
def encode2D(v_dec, L1, L2):
"""
Encodes a vector of 2 integers of ranges respectively L1 and L2
e.g. the first entry must be an integer between 0 and L1-1.
Parameters
----------
v_dec: list or numpy array of two integers between 0 and L
L1 : range od the first dimension
L2 : range od the second dimension
Assign increasing integers starting from 0 up to L1*L2-1 to an L1xL2 matrix row by row.
Returns
-------
integer corresponding to the element (v_dec[0],v_dec[1]) of the encoding 2matrix.
"""
V = np.arange(0,L1*L2).reshape((L1,L2))
v_enc = V[tuple(v_dec)]
return v_enc
def decode2D(v_enc, L1, L2):
"""
Decodes an encoding for a vector of 2 integers of ranges respectively L1 and L2.
Parameters
----------
v_enc: scalar between 0 and L1*L2-1, is the encoding of a position (x,y)
L1 : range od the first dimension
L2 : range od the second dimension
Assign increasing integers starting from 0 up to L1*L2-1 to an L1xL2 matrix row by row.
Returns
-------
numpy array containg the row and the column corresponding to the matrix element of value v_enc.
"""
V = np.arange(0,L1*L2).reshape((L1,L2))
v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0]])
return v_dec
def encode3D(v_dec, L1, L2, L3):
"""
Encodes a vector of 3 integers of ranges respectively L1, L2 and L3,
e.g. the first entry must be an integer between 0 and L1-1.
Parameters
----------
v_dec: list or numpy array of three integers between 0 and L
L1 : range od the first dimension
L2 : range od the second dimension
L3 : range od the third dimension
Assign increasing integers starting from 0 up to L1*L2*L3 to an L1xL2xL3 3D-matrix "row by row".
Returns
-------
integer corresponding to the element (v_dec[0],v_dec[1],v_dec[2]) of the encoding 3D-matrix.
"""
V = np.arange(0,L1*L2*L3).reshape((L1,L2,L3))
v_enc = V[tuple(v_dec)]
return v_enc
def decode3D(v_enc, L1, L2, L3):
"""
Decodes an encoding for a vector of 3 integers of ranges respectively L1, L2 and L3.
Parameters
----------
v_enc: scalar between 0 and L1*L2*L3 - 1, is the encoding of a position (x,y)
L1 : range od the first dimension
L2 : range od the second dimension
L3 : range od the third dimension
Assign increasing integers starting from 0 up to L1*L2*L3 to an L1xL2xL3 3D-matrix "row by row".
Returns
-------
numpy array containg the indexes corresponding to the 3D-matrix element of value v_enc.
"""
V = np.arange(0,L1*L2*L3).reshape((L1,L2,L3))
v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0], np.where(v_enc == V)[2][0]])
return v_dec
def encode_state(state, map_size = 7, h_lev = 3, n_actions = 5, debug = False):
"""
Encode a state of the game in a unique scalar.
Parameters
----------
state : [map_size,map_size,>=3] numpy array
Layer 0: map halite
Layer 1: ship position
Layer 2: halite carried by the ships (a.k.a. cargo)
map_size : int, linear size of the squared map
h_lev : int, number of quantization levels of halite
n_actions: int, number of actions that the agent can perform
deubg : bool, verbose mode to debug
Returns
-------
s_enc : int, unique encoding of the partial observation of the game state
"""
debug_print = print if debug else lambda *args, **kwargs : None
pos_enc = one_to_index(state[:,:,1], map_size)[0] # ship position
debug_print("Ship position encoded in [0,%d]: "%(map_size**2-1), pos_enc)
# ADJUST FOR COMPATIBILITY
map_h_thresholds = np.array([10,100,1000]) #same for map and cargo
halvec_dec = get_halite_vec_dec(state, map_h_thresholds, map_h_thresholds, map_size = map_size)
# ADJUST FOR COMPATIBILITY
halvec_enc = encode_vector(halvec_dec) # halite vector
debug_print("Halite vector encoded in [0,%d]: "%(h_lev**6 -1), halvec_enc)
haldir = get_halite_direction(state, map_size = map_size) # halite direction
debug_print("Halite direction in [0,3]: ", haldir)
s_dec = np.array([pos_enc, halvec_enc, haldir])
debug_print("Decoded state: ", s_dec)
s_enc = encode3D(s_dec, L1 = map_size**2, L2 = h_lev**6, L3 = n_actions-1)
debug_print("State encoded in [0, %d]: "%(map_size**2*h_lev**6*(n_actions-1)), s_enc, '\n')
return s_enc
def encode_state_v1(state, map_h_thresholds, cargo_thresholds, map_size = 7, n_actions = 5, debug = False):
"""
Encode a state of the game in a unique scalar.
Parameters
----------
state : [map_size,map_size,>=3] numpy array
Layer 0: map halite
Layer 1: ship position
Layer 2: halite carried by the ships (a.k.a. cargo)
map_size : int, linear size of the squared map
h_lev : int, number of quantization levels of halite for map cells
cargo_lev: int, number of quantization levels of halite for carried halite (a.k.a. cargo)
n_actions: int, number of actions that the agent can perform
deubg : bool, verbose mode to debug
Returns
-------
s_enc : int, unique encoding of the partial observation of the game state
"""
#define some derived quantities
h_lev = len(map_h_thresholds)
cargo_lev = len(cargo_thresholds)
# define debug print function
debug_print = print if debug else lambda *args, **kwargs : None
pos_enc = one_to_index(state[:,:,1], map_size)[0] # get ship position
debug_print("Ship position encoded in [0,%d]: "%(map_size**2-1), pos_enc)
halvec_dec = get_halite_vec_dec(state, map_h_thresholds, cargo_thresholds, map_size = map_size)
ranges = [cargo_lev] + [h_lev for i in range(5)]
halvec_enc = encode_vector_v1(halvec_dec, ranges) # halite vector
debug_print("Halite vector encoded in [0,%d]: "%((h_lev**5)*cargo_lev -1), halvec_enc)
haldir = get_halite_direction(state, map_size = map_size) # halite direction
debug_print("Halite direction in [0,3]: ", haldir)
s_dec = np.array([pos_enc, halvec_enc, haldir])
debug_print("Decoded state: ", s_dec)
s_enc = encode3D(s_dec, L1 = map_size**2, L2 = (h_lev**5)*cargo_lev, L3 = n_actions-1)
debug_print("State encoded in [0, %d]: "%((map_size**2)*(h_lev**5)*cargo_lev*(n_actions-1)), s_enc, '\n')
return s_enc
def scalar_to_matrix_action(action, state, map_size = 7):
# first get the decoded position of the ship
ship_pos_matrix = state[:,:,1]
pos_enc = one_to_index(ship_pos_matrix, map_size)
pos_dec = decode(pos_enc, map_size)
# then fill a matrix of -1
mat_action = np.full((map_size,map_size), -1)
# finally insert the action in the pos_dec entry
mat_action[tuple(pos_dec)] = action
return mat_action
def sym_encode(s, map_size = 7, h_lev = 3, n_actions = 5, debug=False):
# first create all the equivalent states
# rotations
s90 = np.rot90(s, k = 1)
s180 = np.rot90(s, k = 2)
s270 = np.rot90(s, k = 3)
# reflections
s_f = np.flip(s, axis = 1)
s90_f = np.flip(s90, axis = 0)
s180_f = np.flip(s180, axis = 1)
s270_f = np.flip(s270, axis = 0)
s8_dec = [s, s90, s180, s270, s_f, s90_f, s180_f, s270_f]
# then encode all of them
s8_enc = []
for state in s8_dec:
s_enc = encode_state(state, map_size = map_size, h_lev = h_lev, n_actions = n_actions, debug=False)
s8_enc.append(s_enc)
# finally returns all the encoded states
return np.array(s8_enc)
def sym_action(a):
A = np.array([[-1,2,-1],[4,0,3],[-1,1,-1]])
choice = np.full((3,3),a)
M = (A==choice) # mask
M90 = np.rot90(M, k = 1)
M180 = np.rot90(M, k = 2)
M270 = np.rot90(M, k = 3)
# reflections
M_f = np.flip(M, axis = 1)
M90_f = np.flip(M90, axis = 0)
M180_f = np.flip(M180, axis = 1)
M270_f = np.flip(M270, axis = 0)
M8 = [M, M90, M180, M270, M_f, M90_f, M180_f, M270_f]
a8 = []
for m in M8:
a8.append(A[m][0])
return a8
# multi-agent changes
def multi_scalar_to_matrix_action(actions, state, map_size = 7):
# first get the decoded position of the ship
ship_pos_matrix = state[:,:,1]
ships_pos_enc = one_to_index(ship_pos_matrix, map_size)
# then fill a matrix of -1
mat_action = np.full((map_size,map_size), -1)
for i in range(len(ships_pos_enc)):
pos_dec = decode(ships_pos_enc[i], map_size)
#print("pos_dec: ", pos_dec)
# finally insert the action in the pos_dec entry
mat_action[tuple(pos_dec)] = actions[i]
return mat_action
def safest_dir(pos_enc, state, map_size = 7):
# pos_enc is of a single ship
ship_pos_matrix = state[:,:,1]
shipy_enc = one_to_index(state[:,:,3], map_size)
shipy_dec = decode(shipy_enc, map_size)
pos_dec = decode(pos_enc, map_size)
shift = (shipy_dec[0]-pos_dec[0],shipy_dec[1]-pos_dec[1])
centered = np.roll(ship_pos_matrix , shift = shift, axis = (0,1)) #centers map_halite on the ship
s1 = shipy_dec + [0,1]
s2 = shipy_dec + [0,-1]
s3 = shipy_dec + [1,0]
s4 = shipy_dec + [-1,0]
s = [s1,s2,s3,s4]
mask = np.zeros((map_size,map_size)).astype(int)
for x in s:
mask[tuple(x)] = 1
mask = mask.astype(bool)
near_ships = centered[mask] # N,W,E,S -> 2,4,3,1
x = np.array([2,4,3,1])
if near_ships.sum() < 4:
safe_dirs = x[~near_ships.astype(bool)] # safe directions
safest_dir = np.random.choice(safe_dirs)
else:
safest_dir = 0
return safest_dir
def encode_multi_state(state, map_size = 7, h_lev = 3, n_actions = 5, debug = False):
import copy
# returns a list containing the encoded state of each ship
ship_ids = state[:,:,4][state[:,:,1].astype(bool)]
enc_states = []
for i in range(len(ship_ids)):
ID = ship_ids[i] # select one ID in order of position in the map
mask = (state[:,:,4] == ID) # select only the position of the ship with this ID
one_state = copy.deepcopy(state) # work with a deep copy to make changes only on that
one_state[:,:,1][~mask] = 0 # map it to a one-ship state
pos_enc = one_to_index(one_state[:,:,1], map_size)
safe_dir = safest_dir(pos_enc, state, map_size = 7) # new information to encode in the multi-agent case
# recycle the function used to encode the one-ship case by masking the other ships
s1_enc = encode_state(one_state, map_size = map_size, h_lev = h_lev, n_actions = n_actions, debug = debug)
n_states1 = map_size**2*h_lev**6*4 # number of possible states along s1_enc
n_states2 = n_actions
s_enc = encode2D(np.array([s1_enc, safe_dir]), L1 = n_states1, L2 = n_states2)
enc_states.append(s_enc)
return enc_states
# 4D encoding and decoding for arbitrary lengths of the four axis
def encode4D(v_dec, L1, L2, L3, L4):
V = np.arange(0,L1*L2*L3*L4).reshape((L1,L2,L3,L4))
v_enc = V[tuple(v_dec)]
return v_enc
def decode4D(v_enc, L1, L2, L3,L4):
V = np.arange(0,L1*L2*L3*L4).reshape((L1,L2,L3,L4))
v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0], np.where(v_enc == V)[2][0], np.where(v_enc == V)[3][0]])
return v_dec
|
85e4570b02806f103b50429e1d73ec2652e009fe | iamparul08/Hands-on-P6 | /fileio2_ADID.py | 394 | 3.65625 | 4 | #reading first 11 characters from the file
print("First 11 characters of the file:")
f = open("in1_ADID.txt", "r")
print(f.read(11))
f.close()
#reading first line
print("\nReading first line of the file:")
f = open("in1_ADID.txt", "r")
print(f.readline())
f.close()
#using read() method
print("\nRead the content of the file:")
f = open("in1_ADID.txt", "r")
print(f.read()) |
cea334a02a27c95069e54496cc08c6c77eb439e1 | Miranjunaidi/SRMAP_CodingClub_Tests | /Test1/Solutions/Binary/binStrings.py | 568 | 3.625 | 4 |
def all_n_BinStrings(n):
if n == 1:
return ["0", "1"]
else:
given = all_n_BinStrings(n-1)
res = []
for bistr in given:
res.append(bistr + '0')
res.append(bistr + '1')
return res
def numsubString(n, pattern):
return sum([(pattern in s) for s in all_n_BinStrings(n)])
#print(numsubString(6, "11011"))
if __name__ == "__main__":
NumTestCases = int(input())
for i in range(NumTestCases):
n = int(input(""))
pattern = "110011"
print(numsubString(n, pattern))
|
00b2a919a2f0cb213dfc003e78d64d1957cd5c70 | Lyra2108/AdventOfCode | /2015/Day2/Presents.py | 623 | 3.546875 | 4 | def calculate_package_needs(boxes):
paper = 0
ribbon = 0
for box in boxes:
sizes = list(map(lambda size: int(size), box))
x, y, z = sizes
sizes.remove(max(sizes))
x_small, y_small = sizes
paper += 2*x*y + 2*x*z + 2*y*z + x_small*y_small
ribbon += 2*x_small + 2*y_small + x*y*z
return (paper, ribbon)
if __name__ == "__main__":
raw_boxes = open("sizes.txt", "r").readlines()
boxes = map(lambda size: size.split('x'), raw_boxes)
print("They need %d square foot of wrapping paper and %d foot of ribbon." %
calculate_package_needs(boxes))
|
e6484be2f1f99100731c9fe5043e918fad434070 | Lyra2108/AdventOfCode | /2019/Day1/rocketFuel.py | 926 | 3.75 | 4 | from functools import reduce
def read_in_modules():
input_file = open("input.txt", "r")
return list(map(lambda x: int(x), input_file.readlines()))
def simple_calculate_fuel(modules):
return reduce(lambda x, y: x + y, map(lambda module: calculate_fuel(module), modules))
def calculate_fuel(module):
fuel = int(module / 3) - 2
return 0 if fuel < 0 else fuel
def calculate_fuel_with_fuel_fuel(modules):
total_fuel = 0
fuels = modules
while fuels:
fuels = list(filter(lambda module: module > 0, map(lambda module: calculate_fuel(module), fuels)))
if fuels:
total_fuel += reduce(lambda x, y: x + y, fuels)
return total_fuel
if __name__ == '__main__':
modules = read_in_modules()
print("The modules need %d fuel." % simple_calculate_fuel(modules))
print("The modules need %d fuel including their fuel." % calculate_fuel_with_fuel_fuel(modules))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.