blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6552880a9fc548d75ddef566681f44fe7696eada | IngridFCosta/exerciciosPythonBrasil | /EstruturaDeRepetição/ex24.py | 252 | 3.625 | 4 | totNotas=float(input('Informe o total de notas que você quer calcular: '))
cont=0
media=soma=0
while cont < totNotas:
nota=float(input(f'Informe a {cont+1}ª nota:'))
cont+=1
soma+=nota
media=soma/totNotas
print(f'A média é {media:.2f}') |
cec5343cba032aefc51606fc70308f9a317df5fb | hastysun/Python | /Lessons/U5L5.py | 734 | 3.625 | 4 | ## Unit 5 Lesson 5 - Timers
## Computer Programming II - Gavin Weiss
## Libraries
import time
import random
import simpleguitk as simplegui
##> Define Global Variables
time = 0
##> Define Helper Functions
##> Define Classes
##> Define Event Handlers
def draw(canvas):
canvas.draw_text(str(time), [50,60], 12, "Gray", "Monospace")
return
def TimeInc():
global time
time = time + 1
##> Create Frame
frame = simplegui.create_frame("SimpleGUI", 150, 100)
timer = simplegui.create_timer(10, TimeInc)
# The first paremeter is time in milliseconds
# The second parameter is the function to run each time
##> Register Event Handlers
frame.set_draw_handler(draw)
##> Start Frame and Timers
timer.start()
frame.start()
|
d61dfb0e8574aa212c54c3fb3f5ab512737caeb5 | Sue9/Leetcode | /Python Solutions/203 Remove Linked List Elements.py | 1,134 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 11:13:58 2019
@author: Sue
203. Remove Linked List Elements
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
#solution 2:
dummyHead = ListNode(-1)
dummyHead.next = head
prev = dummyHead
while(prev.next):
if(prev.next.val == val):
prev.next = prev.next.next
else:
prev = prev.next
return dummyHead.next
"""
#solution 1: recursively
if (head is None):
return head
if(head.val == val):
return self.removeElements(head.next, val)
else:
head.next = self.removeElements(head.next, val)
return head
"""
|
3796530926e2ebe31a2ce2d892a17e2281ce0ed9 | YosriGFX/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 197 | 4.03125 | 4 | #!/usr/bin/python3
def uppercase(str):
for a in range(len(str)):
b = ord(str[a])
if b >= 97 and b <= 123:
b -= 32
print(end="{}".format(chr(b)))
print()
|
3960b92436b430d854257c467be1ca3005204e5e | aggarnav/distance | /dist.py | 1,354 | 3.828125 | 4 |
from math import atan2, cos, sin, sqrt, radians
import re
def calc_distance(origin, destination, planet):
"""great-circle distance between two points on a sphere
from their longitudes and latitudes"""
lat1, lon1 = origin
lat2, lon2 = destination
if planet.lower()=="earth".lower():
radius = 6371 # km. earth
if planet.lower()=="mars".lower():
radius = 3390 #radius of mars
if planet.lower()=="moon".lower():
radius = 1737 #radius of moon
dlat = radians(lat2 - lat1)
dlon = radians(lon2 - lon1)
a = (sin(dlat / 2) * sin(dlat / 2) + cos(radians(lat1)) * cos(radians(lat2)) *
sin(dlon / 2) * sin(dlon / 2))
c = 2 * atan2(sqrt(a), sqrt(1 - a))
d = radius * c
return d
xmlfile = open('placemarks.xml','r')
contents = xmlfile.readlines()
nodes = {}
i=0
for content in contents:
lon = re.findall(r'<longitude>(.+?)</longitude>', content)
lat = re.findall(r'<latitude>(.+?)</latitude>', content)
nodes[i] = (float(lat[0]), float(lon[0]))
i += 1
while True:
n1 = int(input("Enter the number of the first POI: "))
planet = (contents[n1].split("@"))[0]
n2 = int(input("Enter the number of the Second POI: "))
print ("distance of" + str(nodes[n1]) + "from" + str(nodes[n2]) + "is " + str(calc_distance(nodes[n1], nodes[n2],planet)))
|
14d8b769af3f324d3b809ab2b658d42e3ad3f738 | franklingu/leetcode-solutions | /questions/shortest-distance-to-a-character/Solution.py | 1,070 | 3.84375 | 4 | """
Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.
"""
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
l, l1, s = len(S), 0, 1
r = [None] * l
for i, c in enumerate(S):
if c == C:
r[i] = 0
l1 += 1
while l1 < l:
for i, n in enumerate(r):
if n != 0:
continue
if i - s >= 0 and r[i - s] is None:
r[i - s] = s
l1 += 1
if i + s < l and r[i + s] is None:
r[i + s] = s
l1 += 1
s += 1
return r
|
b0e67f9f15117a4fa946778912fa7d2dea10898a | JIC-CSB/jicgeometry | /jicgeometry/__init__.py | 8,131 | 4.15625 | 4 | """Module for geometric operations.
The module contains two classes to perform geometric operations in 2D and 3D
space:
- :class:`jicgeometry.Point2D`
- :class:`jicgeometry.Point3D`
A 2D point can be generated using a pair of x, y coordinates.
>>> p1 = Point2D(3, 0)
Alternatively, a 2D point can be created from a sequence.
>>> l = [0, 4]
>>> p2 = Point2D(l)
The x and y coordinates can be accessed as properties or by their index.
>>> p1.x
3
>>> p1[0]
3
Addition and subtraction result in vector arithmetic.
>>> p1 + p2
<Point2D(x=3, y=4, dtype=int)>
>>> p1 - p2
<Point2D(x=3, y=-4, dtype=int)>
Scalar multiplication is supported.
>>> (p1 + p2) * 2
<Point2D(x=6, y=8, dtype=int)>
Scalar division uses true division and as a result always returns a 2D point of
``dtype`` ``float``.
>>> p1 / 2
<Point2D(x=1.50, y=0.00, dtype=float)>
It is possible to calculate the distance between two points.
>>> p1.distance(p2)
5.0
Points can also be treated as vectors.
>>> p3 = p1 + p2
>>> p3.unit_vector
<Point2D(x=0.60, y=0.80, dtype=float)>
>>> p3.magnitude
5.0
"""
import math
__version__ = "0.6.0"
class Point2D(object):
"""Class representing a point in 2D space."""
def __init__(self, a1, a2=None):
if a2 is None:
# We assume that we have given a sequence with x, y coordinates.
self.x, self.y = a1
else:
self.x = a1
self.y = a2
self._set_types()
def _set_types(self):
"""Make sure that x, y have consistent types and set dtype."""
# If we given something that is not an int or a float we raise
# a RuntimeError as we do not want to have to guess if the given
# input should be interpreted as an int or a float, for example the
# interpretation of the string "1" vs the interpretation of the string
# "1.0".
for c in (self.x, self.y):
if not (isinstance(c, int) or isinstance(c, float)):
raise(RuntimeError('x, y coords should be int or float'))
if isinstance(self.x, int) and isinstance(self.y, int):
self._dtype = "int"
else:
# At least one value is a float so promote both to float.
self.x = float(self.x)
self.y = float(self.y)
self._dtype = "float"
@property
def dtype(self):
"""Return the type of the x, y coordinates as a string."""
return self._dtype
@property
def magnitude(self):
"""Return the magnitude when treating the point as a vector."""
return math.sqrt(self.x**2 + self.y**2)
@property
def unit_vector(self):
"""Return the unit vector."""
return Point2D(self.x / self.magnitude, self.y / self.magnitude)
def distance(self, other):
"""Return distance to the other point."""
tmp = self - other
return tmp.magnitude
def __repr__(self):
s = "<Point2D(x={}, y={}, dtype={})>"
if self.dtype == "float":
s = "<Point2D(x={:.2f}, y={:.2f}, dtype={})>"
return s.format(self.x, self.y, self.dtype)
def __eq__(self, other):
if self.dtype != other.dtype:
return False
return self.x == other.x and self.y == other.y
def __add__(self, other):
return Point2D(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point2D(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Point2D(self.x * other, self.y * other)
def __div__(self, other):
return self * (1/float(other))
def __truediv__(self, other):
return self.__div__(other)
def __len__(self):
return 2
def __getitem__(self, key):
if key == 0:
return self.x
elif key == 1:
return self.y
else:
raise(IndexError())
def __iter__(self):
return iter([self.x, self.y])
def astype(self, dtype):
"""Return a point of the specified dtype."""
if dtype == "int":
return Point2D(int(round(self.x, 0)), int(round(self.y, 0)))
elif dtype == "float":
return Point2D(float(self.x), float(self.y))
else:
raise(RuntimeError("Invalid dtype: {}".format(dtype)))
def astuple(self):
"""Return the x, y coordinates as a tuple."""
return self.x, self.y
class Point3D(object):
"""Class representing a point in 3D space."""
def __init__(self, a1, a2=None, a3=None):
if a2 is not None and a3 is not None:
self.x, self.y, self.z = a1, a2, a3
else:
self.x, self.y, self.z = a1
self._set_types()
def _set_types(self):
"""Make sure that x, y, z have consistent types and set dtype."""
# If we given something that is not an int or a float we raise
# a RuntimeError as we do not want to have to guess if the given
# input should be interpreted as an int or a float, for example the
# interpretation of the string "1" vs the interpretation of the string
# "1.0".
for c in (self.x, self.y, self.z):
if not (isinstance(c, int) or isinstance(c, float)):
raise(RuntimeError('x, y coords should be int or float'))
if (isinstance(self.x, int)
and isinstance(self.y, int) and isinstance(self.z, int)):
self._dtype = "int"
else:
# At least one value is a float so promote both to float.
self.x = float(self.x)
self.y = float(self.y)
self.z = float(self.z)
self._dtype = "float"
@property
def dtype(self):
"""Return the type of the x, y coordinates as a string."""
return self._dtype
def __iter__(self):
return iter([self.x, self.y, self.z])
def __repr__(self):
s = "<Point3D(x={}, y={}, z={}, dtype={})>"
if self.dtype == "float":
s = "<Point2D(x={:.2f}, y={:.2f}, z={:.2f}, dtype={})>"
return s.format(self.x, self.y, self.z, self.dtype)
def __eq__(self, other):
if self.dtype != other.dtype:
return False
return (self.x == other.x
and self.y == other.y
and self.z == other.z)
def __add__(self, other):
return Point3D(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Point3D(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
return Point3D(self.x * other, self.y * other, self.z * other)
def __div__(self, other):
return self * (1/float(other))
def __truediv__(self, other):
return self.__div__(other)
def __len__(self):
return 3
def __getitem__(self, key):
if key == 0:
return self.x
elif key == 1:
return self.y
elif key == 2:
return self.z
else:
raise(IndexError())
@property
def magnitude(self):
"""Return the magnitude when treating the point as a vector."""
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
@property
def unit_vector(self):
"""Return the unit vector."""
return Point3D(self.x / self.magnitude,
self.y / self.magnitude,
self.z / self.magnitude)
def distance(self, other):
"""Return distance to the other point."""
tmp = self - other
return tmp.magnitude
def astype(self, dtype):
"""Return a point of the specified dtype."""
if dtype == "int":
return Point3D(int(round(self.x, 0)),
int(round(self.y, 0)),
int(round(self.z, 0)))
elif dtype == "float":
return Point3D(float(self.x), float(self.y), float(self.z))
else:
raise(RuntimeError("Invalid dtype: {}".format(dtype)))
def astuple(self):
"""Return the x, y coordinates as a tuple."""
return self.x, self.y, self.z
|
2da66c5ad92859d80ca33d0a80ecb2d6e5323b07 | surathjhakal/data_structures-algorithim | /searching & sorting/binary_search.py | 441 | 3.875 | 4 | def binary_search(list1,ele):
found=False
f=0
l=len(list1)-1
pos=0
while pos<len(list1) and not found:
mid=(f+l)//2
if list1[mid]==ele:
found=True
elif list1[mid]>ele:
l=mid-1
else:
f=mid+1
pos+=1
return found
list1=[2,23,45,65,87,91,98]
ele=91
s=binary_search(list1,ele)
if s:
print("number found")
else:
print("number not found")
|
90f28bdf6e3c21e86e8c1e72a919b50eed0f8128 | diamondstone/project-euler | /python/pe24.py | 1,421 | 3.578125 | 4 | from math import factorial
def baseftonum(basef): #computes the number with "base" factorial representation basef
num=0
l=len(basef)
for i in range(l): num+=factorial(l-i)*basef[i]
return num
def numtobasef(num,l): # computes the l-"digit" "base" factorial representation of num
# there's probably a real name for this
basef=[0]*l
for i in range(l):
basef[i]=num/factorial(l-i)
num-=basef[i]*factorial(l-i)
return basef
def baseftoperm(basef): # converts a base-factorial representation to the corresponding permutation
basef.append(0)
l=len(basef)
perm=[0]*l
for i in range(l):
while perm[i] in perm[:i]: perm[i] += 1
for j in range(basef[i]):
perm[i]+=1
while perm[i] in perm[:i]: perm[i] += 1
return perm
def permtobasef(perm): # converts a base-factorial representation to the corresponding permutation
l=len(perm)-1
basef=perm[:l]
for i in range(l):
for j in range(basef[i]):
if j in perm[:i]: basef[i] -= 1
return basef
def permtonum(perm): return baseftonum(permtobasef(perm))
def numtoperm(num,l): return baseftoperm(numtobasef(num,l-1))
def nextperm(perm):
l=len(perm)
num=permtonum(perm)+1
if num==factorial(l): return None
return numtoperm(num,l)
perm=numtoperm(999999,10)
print perm
perm=reduce(lambda x,y:x+y,map(str,perm))
print perm
|
d8ca1fac9a23e9e9cf5bb6ebd57973eb41eaf1d8 | codeisgreat/Computerized-Robot-Arena-Program | /board.py | 7,217 | 3.65625 | 4 | import robot
'''
provides access to robot constructor.
'''
import projectile
'''
provides access to projectile constructor.
'''
from random import shuffle, randrange
'''
Import shuffle function to randomize turn order.
'''
import copy
"""
Import deepcopy function to allow safe board-state passing.
"""
import logging
''' Import logging module. '''
DEFAULT_BOARD_SIZE = 25
'''
The default size of the board.
'''
class Board:
'''
A representation of the game board.
Keeps a collection of the robots in play
and performs the logic for updating the board each tick.
@note: For the sake of consistency and type safety, all references to actors passed into and out of the Board class
should be strings representing the name of the actor, and therefore the key of the actor in the Board.actors dict.
Methods of Board should always return the name, and should always take the name in as parameters when referencing actors.
'''
actors = None
'''
An instance-variable dict containing the active actors on the board.
'''
destroyed = None
'''
An instance-variable dict for stashing destroyed actors.
'''
boardSize = 0
'''
The size of the board, specifically the number of tiles on the side of a square board.
Actors on the board may have coordinates in the range of [0,boardSize),
that is, 0 <= coord < boardSize
If boardSize is 0, the board is unbounded.
'''
def __init__(self, scripts = None, boardSize = DEFAULT_BOARD_SIZE):
'''
Initializes robot.actors to add to Board
@param scripts: A dict containing the robotBehavior objects keyed to the script's name
@param boardSize: The size of the board, i.e., the length in tiles of the sides of the the square board.
'''
#initialization of instance variables (necessary for copying purposes)
self.boardSize = boardSize
self.actors = {}
self.destroyed = {}
# logging.info("initializing board")
# if scripts is None, this is a copy,
# so do not initialize robots from script_name,
# copy code will take care of it
if scripts is not None:
for script_name in scripts:
# logging.debug("initializing {}".format(script_name))
# logging.debug(scripts)
# initialize the robot actor at a random location on the board
self.actors[script_name] = robot.Robot(randrange(self.boardSize), randrange(self.boardSize), 0, scripts[script_name], script_name)
def update(self):
'''
Updates the positions of all actors and performs all other simulation logic.
'''
# make a copy of the list of keys so python doesn't freak out if a robot gets deleted
keys = list(self.actors.keys())
# shuffle list for random turn order
# chosen so that turn order is not predictably in order to simulate all
# action happening concurrently on average
shuffle(keys)
for key in keys:
# double check that actors[key] has not been destroyed
if key in self.destroyed:
continue
# Have robot act
self.actors[key].takeAction(self)
# check to see if any robot has been destroyed
keys2 = list(self.actors.keys())
for key2 in keys2:
# health == 0 is used a general flag for destroying an actor
if self.actors[key2].health <= 0:
# logging.debug("{} destroyed".format(self.actors[key2]))
# stash destroyed robot
self.destroyed[key2] = self.actors[key2]
# remove destroyed robot from robot list
del self.actors[key2]
def occupied(self, x, y):
'''
Returns the names of the actors occupying (x, y), returns None otherwise
@returns a list containing the names of the actors (keys in Board.actors) occupying (x, y). The list is empty if the space is empty.
'''
# =======================================================
# iterate over the list of actors
# if the actor's coordinates match the given coordinates,
# append actor to the list of actors
# =======================================================
actorsInSpace = []
for key in self.actors:
actor = self.actors[key]
if x == actor.xPosition and y == actor.yPosition:
actorsInSpace.append(key)
return actorsInSpace
def spawnProjectile(self, x, y, rotation):
'''
Instantiates a new projectile object and add it to the list of actors.
@param x: the x coordinate of the projectile to be spawned
@param y: the y coordinate of the projectile to be spawned
@param rotation: the direction the projectile should move in.
'''
# if board is infinite, no need to check against board bounds
if self.boardSize > 0:
# if out of bounds, return without spawning projectiles
if x < 0 or x >= self.boardSize:
return
if y < 0 or y >= self.boardSize:
return
# spawn projectile
newProjectile = projectile.Projectile(x, y, rotation)
self.actors[newProjectile.name] = newProjectile;
def collision(self, actor1, actor2, damage1 = 1, damage2 = 1):
'''
Simulates a collision between actor1 and actor2 by applying some amount of damage to them.
Subtracts damage1 from actor1's health, and subtracts damage2 from actor2's health.
@param actor1: The first actor in the collision, should be a key to the object in self.actors.
@param actor2: The second actor in the collision, should be a key to the object in self.actors.
@param damage1: The damage to be applied to actor1. Defaults to 1.
@param damage2: The damage to be applied to actor2. Defaults to 1.
'''
# logging.debug('collision between {} and {}'.format(actor1, actor2))
# apply damage to robots
self.actors[actor1].health -= damage1
self.actors[actor2].health -= damage2
def getRobots(self):
'''
Returns a dict containing only the robots on the board.
'''
result = {}
for key in self.actors:
if (isinstance(self.actors[key], robot.Robot)):
result[key] = self.actors[key]
return result
def getProjectiles(self):
'''
Returns a dict containing only the projectiles on the board.
'''
result = {}
for key in self.actors:
if (isinstance(self.actors[key], projectile.Projectile)):
result[key] = self.actors[key]
return result
def __deepcopy__(self, memo=None):
'''
Returns a deep copy of the board, used for stashing the current state of the board.
Creates a Board object with all of the actors in the current object,
but uses shallow copies of the actors which only have their positions and identifying info.
@note: The copy should have no references to values in the original object,
such that manipulating any values within the copy will not effect the original, and vice versa.
'''
# initialize new board object
boardCopy = Board()
# fill in copies of actors
for key in self.actors:
boardCopy.actors[key] = copy.copy(self.actors[key])
# fill in copies of destroyed actors
for key in self.destroyed:
boardCopy.destroyed[key] = copy.copy(self.destroyed[key])
# return the copy
return boardCopy
def __copy__(self):
'''
Returns a copy of the board, used for stashing the current state of the board.
@note: This is an alias for __deepcopy__, both function exactly the same. This method is only provided for compatability.
'''
return copy.deepcopy(self)
|
caf27e1a2be85a56ae670fe49d7d5307f21d5ccc | XNCV/Basic-Python-programming-examples | /assignment_3/l3_ex5.py | 662 | 3.75 | 4 | def generate_autocomplete(words):
# Create the set of the keys
set_of_keys = []
for word in words:
key = ''
for character in word:
key = key + character
set_of_keys.append(key)
# Create the set of the keys with one time appeared
set_of_keys = set(set_of_keys)
# Create the autocomplete results
dic_out = {}
for key in set_of_keys:
dic_out[key] = []
for word in words:
# If the word begin by key, we will chose this word
if key == word[0:len(key)]:
dic_out[key].append(word)
# Stransfer srom list type to set type
dic_out[key] = set(dic_out[key])
return dic_out
print(generate_autocomplete(['a', 'abc', 'abd', 'abd', 'b']))
|
80923a54091c776d6615ba77cc4ae74ae60c68b3 | DarthVi/hpcscripts | /multinode/subsample.py | 1,410 | 3.515625 | 4 | """
2020-09-12 14:09
@author: Vito Vincenzo Covella
"""
import numpy as np
import pandas as pd
import sys
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Please insert a file to subsample and a label to subsample")
exit(1)
#input csv file
input_file = str(sys.argv[1])
input_name = input_file.split('.')[0]
nodename = input_file.split('_')[0].split('/')[-1]
#input label to subsample
labelToSubsample = int(sys.argv[2])
#sanity check for the input label to subsample
if labelToSubsample < 0 or labelToSubsample > 7:
print("Wrong label given as input")
exit(1)
df = pd.read_csv(input_file, header = 0)
counts = df['label'].value_counts(sort=False)
#take all the counts except the count of the label we want to subsample and take the mean of this new list
countX = list(filter(lambda x: x != counts[labelToSubsample], counts))
targetValue = int(np.mean(countX))
#take a subsample of the label selected
df_label = df[df['label'] == labelToSubsample].sample(targetValue, random_state=42)
#concatenate the subsampled dataframe with the rest of the dataframe
df = pd.concat([df_label, df[df['label'] != labelToSubsample]], axis = 0)
substring = "_subsampled" + str(labelToSubsample) + ".csv"
#save to file the new subsampled dataframe
df.to_csv(input_name + substring, index=False, header=True) |
58bec2c9773f085df393ed5b34e110b483e98b3b | ricardomartinez4/python | /orientadoObjetos/practica089.py | 2,733 | 3.8125 | 4 | """
Clases abstractas en Python
(https://www.analyticslane.com/2020/10/05/clases-abstractas-en-python/)
Un concepto importante en programación orientada a objetos es el de las clases abstractas.
Unas clases en las que se pueden definir tanto métodos como propiedades, pero que no pueden ser instancias directamente.
Solamente se pueden usar para construir subclases.
Permitiendo así tener una única implementación de los métodos compartidos, evitando la duplicación de código.
Otra característica de estas clases es que no es necesario que tengan una implementación de todos los métodos necesarios.
Pudiendo ser estos abstractos.
Los métodos abstractos son aquellos que solamente tienen una declaración, pero no una implementación detallada de las funcionalidades.
Las clases derivadas de las clases abstractas debe implementar necesariamente todos los métodos abstractos para poder crear una clase que se ajuste a la interfaz definida.
En el caso de que no se defina alguno de los métodos no se podrá crear la clase.
Resumiendo, las clases abstractas define una interfaz común para las subclases.
Proporciona atributos y métodos comunes para todas las subclases evitando así la necesidad de duplicar código.
Imponiendo además lo métodos que deber ser implementados para evitar inconsistencias entre las subclases.
"""
"""
A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call mechanisms.
Usage:
class C(metaclass=ABCMeta):
@abstractmethod
def my_abstract_method(self, ...):
...
"""
from abc import ABC, abstractmethod
#
#
# EL ABC es el que permita que esto funciono pues no heredamos de Object sino de ABC que a su vez heredará de object
#
class Animal(ABC):
@abstractmethod
def mover(self):
pass
@abstractmethod
def comer(self):
print('Animal come')
class Felino(Animal):
def mover(self):
print('Mover felino')
def comer(self):
# Podemos hacer que se ejecute primero el método abstracto de la clase de la que se hereda
super().comer()
print('Felino come')
class Gato(Felino):
pass
"""
class Dog(Animal):
pass
"""
g = Felino()
g.mover()
g.comer()
gt = Gato()
gt.mover()
gt.comer()
"""
print('------------->Aquí tenemos error porque no tenemos definidas los métodos abstractos mover y comer de Animal ')
p = Dog()
""" |
c201b91b988b1d5654d123c3400d3be69c04322c | nagasax26/design-pattren-in-python | /adapter/adapter.py | 590 | 3.515625 | 4 | from abc import ABCMeta, abstractmethod
class A:
def method_a(self):
print('method a called')
class B:
def method_b(self):
print('method b called')
class IAdapter(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def method_a():
pass
class BAdapter(IAdapter):
def method_a(self):
return B().method_b()
# Without adapter
classes = [A(), B()]
for c in classes:
if isinstance(c, B):
c.method_b()
else:
c.method_a()
# with adapter
classes = [A(), BAdapter()]
for c in classes:
c.method_a() |
fec85184491ecfb8a1ccd9750b48efecbbaf1371 | fanleung/LearnPyQt | /3_Layout_management/example1.py | 1,207 | 3.53125 | 4 | # 布局管理
# 在一个GUI程序里,布局是一个很重要的方面。布局就是如何管理应用中的元素和窗口。
# 有两种方式可以搞定:绝对定位和PyQt5的layout类
# 1. 绝对定位
# · 元素不会随着我们更改窗口的位置和大小而变化。
# · 不能适用于不同的平台和不同分辨率的显示器
# · 更改应用字体大小会破坏布局
# · 如果我们决定重构这个应用,需要全部计算一下每个元素的位置和大小#
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lable1 = QLabel('fanleung', self)
# 这个元素的左上角就在程序的左上角开始(15,10)的位置
lable1.move(15, 10)
lable2 = QLabel('code', self)
lable2.move(35, 40)
lable3 = QLabel('for programers', self)
lable3.move(55, 70)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('绝对定位')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
|
0adf79120eb0b2d8d68ffa1e5c210aca3da87917 | bloodblood/leetcode | /python/To_Lower_Case.py | 353 | 3.75 | 4 | class Solution(object):
def toLowerCase(self, str):
res = ''
for i,c in enumerate(str):
if ( c >= 'A' and c <= 'Z'):
res += chr(ord(c) - ord('A') + ord('a'))
else:
res += c
return res
if __name__ == '__main__':
str = "AAc"
print(Solution.toLowerCase(0, str))
|
73793028a83eb16b0083f7a5dd182d217dedfc9a | atrox3d/1HDOC-Mail-Merge-Project-Start | /main.py | 980 | 3.890625 | 4 | #TODO: Create a letter using starting_letter.txt
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
#Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp
PLACEHOLDER = "[name]"
with open("input/names/invited_names.txt") as names_file:
names = names_file.readlines()
print(names)
with open("input/letters/starting_letter.txt") as letter_file:
letter_contents = letter_file.read()
for name in names:
stripped_name = name.strip()
new_letter = letter_contents.replace(PLACEHOLDER, name)
with open(f"output/readytosend/letter_for_{stripped_name}.txt", "w") as completed:
completed.write(new_letter)
|
2b9fcca3cc19e961a935ed5a7a07a08ec86d2fac | shubhM13/Data-Manipulation-at-Scale-Systems-and-Algorithms | /Assignment3_MapReduce/friend_count.py | 2,455 | 4.1875 | 4 | # Problem 3
# Consider a simple social network dataset consisting of a set of
# key-value pairs (person, friend) representing a friend relationship
# between two people. Describe a MapReduce algorithm to count the
# number of friends for each person.
# Map Input
# Each input record is a 2 element list [personA, personB] where personA
# is a string representing the name of a person and personB is a string
# representing the name of one of personA's friends. Note that it may or
# may not be the case that the personA is a friend of personB.
# Reduce Output
# The output should be a pair (person, friend_count) where person is a
# string and friend_count is an integer indicating the number of friends
# associated with person.
# You can test your solution to this problem using friends.json:
# $ python friend_count.py friends.json
# You can verify your solution by comparing your result with the file friend_count.json.
import MapReduce
import sys
# Part 1
# We create a MapReduce object that is used to pass data between the map
# function and the reduce function, you won't need to use this object directly.
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
# Part 2
# Each input record is a 2 element list [personA, personB] where personA
# is a string representing the name of a person and personB is a string
# representing the name of one of personA's friends. Note that it may or
# may not be the case that the personA is a friend of personB.
# The Mapper Function
def mapper(record):
# key: person identifier
key = record[0]
mr.emit_intermediate(key, 1)
# Part 3
# The output should be a pair (person, friend_count) where person is a
# string and friend_count is an integer indicating the number of friends
# associated with person.
# The Reducer Function
def reducer(key, list_of_values):
# key: friend
# value: list of friends
total = 0
for value in list_of_values:
total += value
mr.emit((key, total))
# Part 4
# The code loads the json file and executes the MapReduce query which
# prints the result to stdout.
# Do not modify below this line
# =============================
if __name__ == '__main__':
try:
# Pass the first file name
inputdata = open(sys.argv[1])
except:
# If the input is blank
input_file = "data\\friends.json"
inputdata = open(input_file)
mr.execute(inputdata, mapper, reducer)
|
3579f7973c3876bda7c363e503f1de701da833c7 | lee-shun/learn_py | /section2/msg_of_object.py | 280 | 3.640625 | 4 | print(type(123))
#实例属性以及类属性
class Student(object):
def __init__(self, name):
self.name = name
#给实例绑定属性
s = Student('Bob')
s.score = 90
#类属性就是在类中直接定义属性,同名的属性,实例的会覆盖掉类的属性
|
295fe9bdad1bf6d7621e59bc6e251949722e3638 | yvonneonu/Test4 | /test4.py | 671 | 3.78125 | 4 | # Python program to check valid password
import re
passw = input("Enter Password ::>")
fl = 0
while True:
if (len(passw)<8):
fl = -1
break
elif not re.search("[a-z]", passw):
fl = -1
break
elif not re.search("[A-Z]", passw):
fl = -1
break
elif not re.search("[0-9]", passw):
fl = -1
break
elif not re.search("[_@$]", passw):
fl = -1
break
elif not re.search("\s", passw):
fl = -1
break
else:
fl = 0
print("This is Valid Password")
break
if fl ==-1:
print("Not a Valid Password")
# This code was generated by Yvonne Onuorah
|
8c7dcffed07d8861b27a0fdcf0b58f9073749e75 | natsumemaya/hexlet_tasks | /8_oop/tree_builder/tests.py | 1,876 | 3.59375 | 4 | from solution import TreeBuilder
def test_tree_builder():
tree = TreeBuilder()
tree.add('root')
with tree:
tree.add('first child')
tree.add('second child')
with tree:
tree.add('grandchild')
tree.add('bastard')
with tree: # noqa: WPS328, this subtree is empty intentionally
pass # noqa: WPS420, we need to do nothing
tree.add('another bastard')
assert tree.structure == [
'root',
[
'first child',
'second child',
['grandchild'],
'bastard',
'another bastard',
],
]
print('test_tree_builder is Ok!')
test_tree_builder()
# class TreeBuilder(object):
# def __init__(self, initial_structure=None):
# if initial_structure is None:
# initial_structure = []
# self.structure = initial_structure
# self._target_for_add = self
# @property # getter
# def structure(self):
# return self._structure
# @structure.setter
# def structure(self, value):
# self._structure = value
# def add(self, leaf_value):
# """Add to the current node."""
# self._target_for_add.append(leaf_value)
# def append(self, leaf_value):
# """Add to base level."""
# self._structure.append(leaf_value)
# def __enter__(self):
# self._target_for_add = TreeBuilder.Node(self._target_for_add)
# def __exit__(self, exc_type, exc_val, exc_tb):
# if self._target_for_add:
# self._target_for_add.parent.append(self._target_for_add)
# self._target_for_add = self._target_for_add.parent
# class Node(list):
# def __init__(self, parent, *args):
# self.parent = parent
# initial_value = list(args)
# self.extend(initial_value)
|
eb45e2b7e7e3fb97801b33e0319877ba6bba7dcb | mavas/climate | /climate.py | 1,701 | 3.890625 | 4 | """
Return the rank of a given set of documents in ascending order.
"""
import math
corpus = ('the', 'cat', 'dog')
def dot_product(a, b):
"""Computes the dot product between 2 vectors."""
assert len(a) == len(b)
return sum([a*b for (a, b) in zip(a, b)])
def magnitude(a):
"""Computes the magnitude of a vector."""
return math.sqrt(dot_product(a, a))
def _compute_vector_for_document(d):
"""Computes the vector for a document."""
return [1 if t in d else 0 for t in corpus]
def _compute_vector_for_query(q):
"""Computes the vector for a query."""
return [1 if q == t else 0 for t in corpus]
def _top(d, q):
"""Computes the top portion of the scoring algorithm."""
return dot_product(d, q)
def _bottom(d, q):
"""Computes the bottom portion of the scoring algorithm."""
return magnitude(d) * magnitude(q)
def score_document(q, d):
"""
Computes a score of the given document with respect to the given query.
The algorithm used for scoring is:
d dot q
-----------
||d|| x ||q||
That is, the top portion is the dot product between the document vector and
the query vector. The bottom portion is the magnitude of the first vector
multiplied by the magnitude of the second.
"""
q = _compute_vector_for_query(q)
d = _compute_vector_for_document(d)
r = _top(d, q)/_bottom(d, q)
return r
def rank_documents(q, docs):
"""Returns the rank of the given documents in ascending order."""
r = []
for d in docs:
r.append(score_document(q, d))
return sorted(r)
if __name__ == '__main__':
assert score_document('dog', ["the", "dog"]) == 1/math.sqrt(2)
|
95b2cc82f75cafa76265bc839cd8f8270001f2f4 | nihalgaurav/acadview_python | /class2/6_fill_in_the_blanks.py | 140 | 3.78125 | 4 | #tony stark
name="Tony Stark"
salary=1000000
#previous question:- print('%s''%d')%(___,___)
#now corrected answer >>>
print("%s%d"%(name,salary)) |
e916396b6e00532533f47f4ee846a5b14c598d32 | Vutsuak16/LeetCode | /algorithm-solution/insertion.py | 242 | 3.734375 | 4 | def insertion(A):
for i in range(1,len(A)):
curr_value=A[i]
position=i
while position>0 and A[position-1]>curr_value:
A[position]=A[position-1]
position-=1
A[position]=curr_value
A=[1,2,3,-1,0,10000,1]
insertion(A)
print A
|
2392e97ec210f3bc9e21cd0214ccaee564e682ae | Amritpal-001/100-days-of-code | /EulerBase/Euler_solutions/Getting primes .py | 1,820 | 4.03125 | 4 |
def getPrimesBelowN(n=1000000):
"""Get all primes below n with the sieve of Eratosthenes.
@return: a list 0..n with boolean values that indicate if
i in 0..n is a prime.
"""
from math import ceil
primes = [True] * n
primes[0] = False
primes[1] = False
primeList = []
roundUp = lambda n, prime: int(ceil(float(n) / prime))
for currentPrime in range(2, n):
if not primes[currentPrime]:
continue
primeList.append(currentPrime)
for multiplicant in range(2, roundUp(n, currentPrime)):
primes[multiplicant * currentPrime] = False
return primes
def isCircularPrime(primes, number):
"""Check if number is a circular prime.
Keyword arguments:
primes -- a list from 0..n with boolean values that indicate if
i in 0..n is a prime
number -- the integer you want to check
"""
number = str(number)
for i in range(0, len(number)):
rotatedNumber = number[i:len(number)] + number[0:i]
if not primes[int(rotatedNumber)]:
return False
return True
if __name__ == "__main__":
print("Start sieving.")
primes = getPrimesBelowN(1000000)
print("End sieving.")
numberOfPrimes = 2
print(2) # I print them now, because I want to skip all primes
print(5) # that contain one of those digits: 0,2,4,5,6,8
for prime, isPrime in enumerate(primes):
if (not isPrime) or ("2" in str(prime)) or \
("4" in str(prime)) or ("6" in str(prime)) or \
("8" in str(prime)) or ("0" in str(prime)) or \
("5" in str(prime)):
continue
if isCircularPrime(primes, prime):
print(prime)
numberOfPrimes += 1
print("Number of circular primes: %i" % numberOfPrimes)
|
639532ca68d87539661b30ec5dbd4a8009bde34d | KhaledAbuNada-AI/Simulation-of-Role-Playing-game | /animal.py | 2,467 | 3.625 | 4 | from random import randint
class animal():
def __init__(self,name="",type="",bark="",atek=''):
self.name = name
self.type = type
self.bark = bark
self.atek = atek
self.life = 100
self.pos = (0, 0)
def printAnimal(self):
return "am animal".format(self.name)
def health(self):
if self.life > 0:
self.life -= randint(0, self.life)
print(self.life)
def move(self):
self.pos = (randint(-100,100), randint(-100,100))
print(self.pos)
def Few_Life(self):
if self.life >=100:
self.life -= 40
def is_alive(self):
if self.life > 0:
return True
else:
return False
def is_dead(self):
if self.life == 0:
return True
else:
return False
def __str__(self):
return 'naem:{}\t type:{}\t bark:{}\t atek:{}\t'.format(self.naem, self.type, self.bark, self.atek)
class cat(animal):
def __init__(self,name,type,bark,atek,mycolor,myspot):
super().__init__(name,type,bark,atek) #animal.__init__(self,name,type,bark)
self.color = mycolor
self.spot = myspot
def __str__(self):
return 'color:{}\t spot:{}\t'.format(self.color, self.spot,super().__str__())
def my_bark(self):
return "I'm barking".format(self.name)
def printCat(self):
print("am cat")
class dog(animal):
def __init__(self,bv,lsk,name,type,bark):
super().__init__(name,type,bark)
self.bv = bv
self.lsk = lsk
def jogging(self):
return 'I am Jogging'
def printDog(self):
return 'Am Dog'
def __str__(self):
return 'BV:{}\t LSK:{}\t'.format(self.bv, self.lsk, super().__str__())
class lions(animal):
def __init__(self,protection=None,name="",type="",bark="",atek='' ):
super().__init__(name="",type="",bark="",atek='')
self.protection = protection
def my_eat(self):
return 'I eat meat'
def __str__(self):
return 'protection:{}\t'.format(self.protection,super().__str__())
obj1 = cat(name="lulu",type="cat",bark="Mewo",atek='yrs',mycolor="white",myspot=True)
obj1.printAnimal()
obj1.printCat()
print(obj1.name)
obj2 = cat(name='adad',type='cat',bark='yrs',atek='', mycolor='rad',myspot=True)
#print(obj2)
|
a4e10bb01133169fa902ea1aed23f0cc15f046d4 | junxdev/this-is-coding-test-with-python-by-ndb | /appendix-a/06-libraries/02-itertools.py | 478 | 3.921875 | 4 | from itertools import permutations
# permutation
data = ['A', 'B', 'C']
result = list(permutations(data, 3))
print(result)
from itertools import combinations
# combination
result = list(combinations(data, 2))
print(result)
from itertools import product
# product
result = list(product(data, repeat = 2))
print(result)
from itertools import combinations_with_replacement
# combination with replacement
result = list(combinations_with_replacement(data, 2))
print(result)
|
31b28e098c14fb9bde7045cd26b04958c2649b21 | akaushal123/Project-Euler | /7. nth Prime.py | 1,208 | 4.3125 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
"""
potential_prime calculates prime number with value 6*n+1 and 6*n-1 (by property that all prime are formed by this way)
is_prime checks for the prime number formed by the potential_prime
nth_prime makes a list for the prime numbers of the given limit
"""
def potential_prime(n):
return [6 * n - 1, 6 * n + 1]
def is_prime(n):
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if (n % i) == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def nth_prime(limit):
primes = [2, 3]
if len(primes) == limit:
return primes
n = 1
while len(primes) < limit:
potential_prime_number = potential_prime(n)
if is_prime(potential_prime_number[0]):
primes.append(potential_prime_number[0])
if is_prime(potential_prime_number[1]):
primes.append(potential_prime_number[1])
n += 1
return primes[limit - 1]
if __name__ == "__main__":
num = int(input("Enter the term: "))
print(nth_prime(num))
|
afbc4195124c2185d23ea934273371a46f7fc33f | gabferraz/anotacoes-livro-fluent-python | /02-data_structure/2.1-sequences.py | 6,318 | 4.0625 | 4 | # Part 2 - Data Structures
# Cap. 2:
# LIST COMPREHENSIONS
# Listcomps só devem ser utilizadas para gerar uma lista, se for necessario fazer algum processamento de dados
# ou executar um código varias vezes o recomendado é utilizar o loop for. Listcomp não substitui o for.
# Exemplo: Criando uma lista de todos os modelos de camisa possíveis
cores = ['preto', 'branco']
tamanhos = ['G', 'M', 'P']
# Essa linha gera uma lista de tuplas organizadas por cores e depois tamanhos
# É o mesmo resultado de dois for aninhados na mesma ordem da listcomp
camisas = [(cor, tamanho) for cor in cores
for tamanho in tamanhos]
print(camisas)
# GENERATOR EXPRESSIONS
# Genexp serve para preencher outros tipos de sequencers tirando listas.
# É melhor do que usar listcomp para preencher outros sequencers pois utiliza menos memória.
# O mesmo exemplo de cima só que utilizando genexp e sem construir os modelos na memória
for camisa in (f'{cor} {tamanho}' for cor in cores for tamanho in tamanhos):
print(camisa)
# TUPLE
# Tuplas tem duas funções: Servem como listas imutáveis ou como um conjunto de campos sem nomes
# Quando se utiliza tuplas como um conjunto de campos o número de campos e sua ordem é importante
# Por exemplo:
id_viajantes = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA2058268')]
for passaporte in sorted(id_viajantes):
print('%s/%s' % passaporte)
# Um dos motivos da tupla funcionar bem como um conjunto de campos é a capacidade de unpacking
# Podemos "desempacotar" a tupla em variáveis e iteráveis
# Por exemplo:
# \-> Desempacotação paralela: Os valores da tupla são distribuidos para as variáveis
cidade, ano, populacao, area = ('Tokyo', 2003, '32450', '8014')
# \-> Prefixo *: Em uma operação que recebe mais de um parâmetro você pode desempacotar a tupla com *
print(divmod(20, 8))
t = (20, 8)
print(divmod(*t))
# \-> Retorno de multiplas variáveis: No exemplo anterior a função divmod retorna dois valores utilizando
# tuplas que pode ser desempacotada em variáveis diferentes
quociente, resto = divmod(*t)
print(f'{quociente} {resto}')
# \-> Prefixo * para pegar excesso: Na definição de uma função * pode ser utilizado para pegar argumentos
# em excesso. Isso também funciona para desempacotação paralela
a, b, *resto = range(6)
print(f'{a}, {b}, {resto}')
# \-> Desempacotamento de tupla aninhada: Se a tupla que for desempacotada tiver uma tupla aninhada
# o Python vai realizar o desempacotamento correto se a expressão combinar com a estrutura da tupla
dados_metro = [
('Tokyo', 'JP', 36.9, (35.689722, 139.691778)),
('Delhi NCR', 'IN', 21.9, (28.613888, 77.208889)),
('Mexico City', 'MX', 20.1, (19.433333, -99.133333)),
('Sao Paulo', 'BR', 19.7, (-23.547777, -46.635833)),
]
fmt = '{:15} | {:9.4f} | {:9.4f}'
for nome, pais, populacao, (latitude, longitude) in dados_metro:
if longitude <= 0:
print(fmt.format(nome, latitude, longitude))
# NAMED TUPLE
# Umas das desvantagens da tupla como um conjunto de campos é a falta de um label
# Named tuples resolve esse problema
from collections import namedtuple
# namedtuple recebe dois parâmetros: nome da classe e um iterável de strings ou uma string
# com os nomes dos atributos separados por espaço
Cidade = namedtuple('Cidade', 'nome pais populacao coordenadas')
tokyo = Cidade('Tokyo', 'JP', 36.933, (35.689722, 139.691677))
print(tokyo)
print(tokyo.populacao)
print(tokyo[3])
# OBS: Tuplas como lista imutáveis:
# Tuplas possuem todas as funções de lista que não envolvem adicionar ou remover itens
# com exceção do método __reversed__ por motivos de otimização
# SLICING
# É possível fazer slices com pulos (stride) com a chamada s[começo:fim:stride]. Por exemplo:
s = 'bicicleta'
print(s[::3])
print(s[::-2])
# Também é possível armazenar slices como objeto, que pode ser interessante para processar
# arquivos de texto puro por exemplo
comprovante = """
1909 Chave de fenda R$5.50 3 R$16.50
4052 Chave estrela R$4.30 2 R$8.60
5942 Corda sisal 1m R$1.20 5 R$6.00
"""
CODIGO = slice(0, 4)
DESCRICAO = slice(4, 19)
PRECO_UNIDADE = slice(19, 27)
QUANTIDADE = slice(27, 31)
PRECO_TOTAL = slice(31, None)
linha_items = comprovante.split('\n')[1:]
for item in linha_items:
print(item[PRECO_TOTAL], item[DESCRICAO])
# Slices também podem ser utilizados para modificar a região de uma sequência
l = list(range(10))
print(l)
del l[2:6]
print(l)
l[3:5] = [11, 11, 11]
print(l)
# Usando + e * com sequências:
# Os operadores + e * suportam sequências, para isso ambos os operandos tem que ser do mesmo tipo
# Esses operadores nunca modificam a sequência, eles sempre retornam uma nova sequência
# OBS: Cuidado com expressões tipo a * n se a for uma sequência que contém elementos mutáveis.
# O problema é que os resultados dessa expressão pode ser diferentes do esperado. Por exemplo
# se a = [[]] então a * 3 vai resultar numa lista com 3 referências para a mesma lista interior
# OBS: O melhor meio de contruir listas de multiplas dimensões é utilizando listcomp.
# Podemos ver nesse exemplo que o campo é modificado do jeito esperado
tabuleiro = [['_'] * 3 for i in range(3)]
tabuleiro[1][2] = 'X'
print(tabuleiro)
# Utilizar o operador * é errado pois acaba criando referências para as listas aninhadas
# nesse caso todos os elementos da lista representam a mesma lista
errado = [['_'] * 3] * 3
errado[1][2] = 'O'
print(errado)
# Operadores += e *= com sequências
# O comportamento desses operadores vão depender se a sequência é imutável ou não
# se a sequência for imutável um novo objeto será criado e associado ao nome da
# variável original. Logo não é recomendado realizar concatenações repetidas em
# sequência imutáveis utilizando esses valores pois é ineficiente.
# OBS: Algumas dicas importantes:
# -Não é uma boa ideia colocar elementos mutáveis dentro de elementos imutáveis
# -As operações *=, +=, etc não são atômicas
# list.sort vs sorted()
# O método list.sort altera o objeto enquanto a função sorted() retorna um novo objeto
# list.sort retorna None no final que é uma convenção do Python que indica que o método
# altera o objeto
|
bc346830b45b19e69cc9c4493d86953954033c15 | chinaylssly/fluent-python | /future/temp.py | 1,082 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import random,sys
from time import sleep,time
from concurrent import futures
MAX_WORKERS= 20
tl=[i*0.01 for i in range(20)]
def do_one(t=0.2):
sleep(t)
return t
def do_many(tl=tl):
tl=tl[:5]
with futures.ThreadPoolExecutor(max_workers=3) as executor:
to_do=[]
for t in tl:
future=executor.submit(do_one,t)
to_do.append(future)
msg='Schduled for {:.2f}: {}'
print (msg.format(t,future))
results=[]
for future in futures.as_completed(to_do):
res=future.result()
##在本例中,调用future.result()方法绝不会阻塞,因为future由as_completed函数产出
msg='{} result: {!r}'
print (msg.format(future,res))
results.append(res)
return len(results)
return len(list(res))
def main(do_many=do_many):
t0=time()
count=do_many()
t=time()-t0
msg='execute {:2d} task cost {:.2f} s'
print (msg.format(count,t))
if __name__ =='__main__':
main()
|
e1a2225f36675f3f13132049edbea8edfae0022f | NitroLine/python-task-help | /1-10/04_alexandr.py | 664 | 3.78125 | 4 | # Написать функцию, возвращающую True или False, если число является александрийским.
def isAlexanderNumber(number):
for p in range(1, int(number ** (1 / 3)) + 1):
if number / p != number // p:
continue
ppplus1 = p * p + 1
for k in range(1, int(ppplus1**(1 / 2)) + 1):
r = -ppplus1 / k - p
if r != int(r):
continue
q = -k - p
if number == p * r * q and 1 == p*q + p*r + q*r:
return True
return False
if __name__ == '__main__':
print(isAlexanderNumber(1884161251122450))
|
d87d0e1ae4b428d61adccef4a5942b708fbd86dc | 2020-A-Python-GR1/py-vinueza-garcia-rafael-eduardo | /Deberes/Deber 1/main.py | 11,084 | 3.78125 | 4 | #Programa creado por Rafael Vinueza para la materia Python 2020A
import os
import sys
def iniciar_menu():
print("----------------------------------- Menu Principal -----------------------------------\n")
print("Digite un numero dependiendo de la operacion que quiera realizar: \n")
try:
opcion_zoologico = input(" 1 -> Crear Zoologico \n 2 -> Leer los datos de un Zoologico \n 3 -> Modificar Zoologico \n 4 -> Eliminar Zoologico (incluyendo sus animales) \n 5 -> Salir del programa \n\n eleccion: ")
if(opcion_zoologico == "1"):
crear_zoologico()
elif(opcion_zoologico == "2"):
buscar_zoologico()
elif(opcion_zoologico == "3"):
modificar_zoologico()
elif(opcion_zoologico == "4"):
eliminar_zoologico()
elif(opcion_zoologico == "5"):
sys.exit()
else:
print("\nLa opcion seleccionada no es correcta.\n")
iniciar_menu()
except Exception as error:
print("\nLa opcion seleccionada no es correcta.\n")
iniciar_menu()
def crear_zoologico():
nombre_zoologico = input("\nIngrese el nombre del zoologico: ")
if(os.path.isfile(f"./zoologico_{nombre_zoologico}.txt")):
print(f"\nEl zoologico '{nombre_zoologico}' ya existe, volvera al menu principal\n")
iniciar_menu()
else:
print("\nIngrese las caracteristicas del zoologico: ")
try:
pais_zoologico = input("\nPais del zoologico: ")
numero_especies_zoologico = int(input("\nNumero de especies: "))
precio_entrada_zoologico = float(input("\nPrecio de la entrada: "))
area_zoologico = input("\nArea del zoologico: ")
hora_apertura_zoologico = input("\nHora de apretura: ")
except Exception as error:
print("\nError al leer los datos, regresara al menu principal\n")
iniciar_menu()
print("\nIngrese los animales del zoologico: \n")
try:
animal1 = input("\nAnimal #1 : ")
animal2 = input("\nAnimal #2 : ")
animal3= input("\nAnimal #3 : ")
animal4 = input("\nAnimal #4 : ")
animal5 = input("\nAnimal #5 : ")
except Exception as error:
print("\nError al leer los datos, regresara al menu principal\n")
iniciar_menu()
try:
file = open(f"./zoologico_{nombre_zoologico}.txt", "w")
file.write(f"{pais_zoologico};{numero_especies_zoologico};{precio_entrada_zoologico};{area_zoologico};{hora_apertura_zoologico}\n")
file.write(f"{animal1};{animal2};{animal3};{animal4};{animal5}")
file.close()
print(f"\nArchivo 'zoologico_{nombre_zoologico}.txt' creado con exito\n")
continuar = input("\nPresione enter para regresar al menu principal\n")
iniciar_menu()
except Exception as error:
print("\nError al crear el archivo, regresara al menu principal\n")
iniciar_menu()
def buscar_zoologico():
contenido = os.listdir('./')
contenido.sort
contenido.remove('main.py')
if(contenido):
print("\nEscoja el numero del zoologico para mostrar su informacion: ")
i = 1
arreglo_zoologico = []
for zoologico in contenido:
zoologico = zoologico.replace("zoologico_","")
zoologico = zoologico.replace(".txt","")
arreglo_zoologico.append(zoologico)
print(f"\n{i} -> {zoologico}")
i = i + 1
try:
indice_zoologico = int(input("\neleccion: ")) - 1
except Exception as error:
print("\nEl numero ingresado no es correcto, volvera al menu principal.\n")
iniciar_menu()
archivo_zoologico_abierto = open(f"./zoologico_{arreglo_zoologico[indice_zoologico]}.txt")
lista_lineas = archivo_zoologico_abierto.readlines()
archivo_zoologico_abierto.close()
if(len(lista_lineas) == 2):
datos_zoologico = lista_lineas[0].split(sep=';')
datos_animales = lista_lineas[1].split(sep=';')
print(f"\nLas caracteristicas del zoologico son las siguientes: \n - Pais del zoologico: {datos_zoologico[0]} \n - Numero de especies en el zoologico: {datos_zoologico[1]} \n - Precio de la entrada: {datos_zoologico[2]} \n - Area del zoologico: {datos_zoologico[3]} \n - Hora de apertura del zoologico: {datos_zoologico[4]}")
print(f"\nLos animales que contiene este zoologico son los siguientes: \n - Animal 1: {datos_animales[0]} \n - Animal 2: {datos_animales[1]} \n - Animal 3: {datos_animales[2]} \n - Animal 4: {datos_animales[3]} \n - Animal 5: {datos_animales[4]} \n")
continuar = input("\nPresione enter para regresar al menu principal\n")
iniciar_menu()
else:
print("\nEl archivo seleccionado no tiene el formato adecuado. Volvera al menu principal\n")
iniciar_menu()
else:
print("\nNo existen archivos de zoologicos, cree uno y regrese. Volvera al menu principal\n")
iniciar_menu()
def modificar_zoologico():
contenido = os.listdir('./')
contenido.sort
contenido.remove('main.py')
if(contenido):
print("\nEscoja el numero del zoologico para modificar su informacion: ")
i = 1
arreglo_zoologico = []
for zoologico in contenido:
zoologico = zoologico.replace("zoologico_","")
zoologico = zoologico.replace(".txt","")
arreglo_zoologico.append(zoologico)
print(f"\n{i} -> {zoologico}")
i = i + 1
try:
indice_zoologico = int(input("\neleccion: ")) - 1
except Exception as error:
print("\nEl numero ingresado no es correcto, volvera al menu principal.\n")
iniciar_menu()
archivo_zoologico_abierto = open(f"./zoologico_{arreglo_zoologico[indice_zoologico]}.txt")
lista_lineas = archivo_zoologico_abierto.readlines()
archivo_zoologico_abierto.close()
if(len(lista_lineas) == 2):
datos_zoologico = lista_lineas[0].split(sep=';')
datos_animales = lista_lineas[1].split(sep=';')
datos_zoologico[4] = datos_zoologico[4].replace("\n", "")
repetir = 1
nombre_zoologico_inicial = arreglo_zoologico[indice_zoologico]
while(repetir == 1):
print("\nIngrese el numero del dato que desee modificar: \n")
print(f"1 -> Nombre del zoologico: {arreglo_zoologico[indice_zoologico]}\n2 -> Pais del zoologico: {datos_zoologico[0]} \n3 -> Numero de especies en el zoologico: {datos_zoologico[1]} \n4 -> Precio de la entrada: {datos_zoologico[2]}\n5 -> Area del zoologico: {datos_zoologico[3]}\n6 -> Hora de apertura: {datos_zoologico[4]}\n7 -> Animal 1: {datos_animales[0]} \n8 -> Animal 2: {datos_animales[1]} \n9 -> Animal 3: {datos_animales[2]} \n10 -> Animal 4: {datos_animales[3]} \n11 -> Animal 5: {datos_animales[4]}")
print(f"12 -> Terminar el proceso de modificacion y guardar")
eleccion = input("\neleccion: ")
if(eleccion == "1"):
arreglo_zoologico[indice_zoologico] = input("\nIngrese el nuevo nombre del zoologico: ")
elif(eleccion == "2"):
datos_zoologico[0] = input("\nIngrese el nuevo valor del pais del zoologico: ")
elif(eleccion == "3"):
datos_zoologico[1] = input("\nIngrese el nuevo valor del numero de especies en el zoologico: ")
elif(eleccion == "4"):
datos_zoologico[2] = input("\nIngrese el nuevo valor del precio de la entrada: ")
elif(eleccion == "5"):
datos_zoologico[3] = input("\nIngrese el nuevo valor del area del zoologico: ")
elif(eleccion == "6"):
datos_zoologico[4] = input("\nIngrese el nuevo valor de la hora de apertura del zoologico: ")
elif(eleccion == "7"):
datos_animales[0] = input("\nIngrese el nuevo animal 1: ")
elif(eleccion == "8"):
datos_animales[1] = input("\nIngrese el nuevo animal 2: ")
elif(eleccion == "9"):
datos_animales[2] = input("\nIngrese el nuevo animal 3: ")
elif(eleccion == "10"):
datos_animales[3] = input("\nIngrese el nuevo animal 4: ")
elif(eleccion == "11"):
datos_animales[4] = input("\nIngrese el nuevo animal 5: ")
elif(eleccion == "12"):
repetir = 17
else:
print("\nLa opcion seleccionada no es correcta, se termina el proceso de modificacion\n")
repetir = 17
os.remove(f"./zoologico_{nombre_zoologico_inicial}.txt")
file = open(f"./zoologico_{arreglo_zoologico[indice_zoologico]}.txt", "w")
file.write(f"{datos_zoologico[0]};{datos_zoologico[1]};{datos_zoologico[2]};{datos_zoologico[3]};{datos_zoologico[4]}\n{datos_animales[0]};{datos_animales[1]};{datos_animales[2]};{datos_animales[3]};{datos_animales[4]}")
file.close()
continuar = input("\nModificaciones guardadas exitosamente. Presione enter para continuar\n")
iniciar_menu()
else:
print("\nEl archivo seleccionado no tiene el formato adecuado. Volvera al menu principal\n")
iniciar_menu()
else:
print("\nNo existen archivos de zoologicos, cree uno y regrese. Volvera al menu principal\n")
iniciar_menu()
def eliminar_zoologico():
contenido = os.listdir('./')
contenido.sort
contenido.remove('main.py')
if(contenido):
print("\nEscoja el numero del zoologico que desea eliminar: ")
i = 1
arreglo_zoologico = []
for zoologico in contenido:
zoologico = zoologico.replace("zoologico_","")
zoologico = zoologico.replace(".txt","")
arreglo_zoologico.append(zoologico)
print(f"\n{i} -> {zoologico}")
i = i + 1
print(f"\n{i} -> Regresar al menu principal")
try:
indice_zoologico = int(input("\neleccion: ")) - 1
except Exception as error:
print("\nEl numero ingresado no es correcto, volvera al menu principal.\n")
iniciar_menu()
if(indice_zoologico + 1 == i):
iniciar_menu()
else:
os.remove(f"./zoologico_{arreglo_zoologico[indice_zoologico]}.txt")
continuar = input("\nArchivo de zoologico eliminado exitosamente. Presione enter para continuar\n")
iniciar_menu()
else:
print("\nNo existen archivos de zoologicos, cree uno y regrese. Volvera al menu principal\n")
iniciar_menu()
def main():
iniciar_menu()
if __name__=="__main__":
main()
|
eabb3b0e0f12da4fa35480f2495e0f2c503e7acf | salini/advent2018 | /day10.py | 9,949 | 3.578125 | 4 | """
--- Day 10: The Stars Align ---
It's no use; your navigation system simply isn't capable of providing walking directions in the arctic circle, and certainly not in 1018.
The Elves suggest an alternative. In times like these, North Pole rescue operations will arrange points of light in the sky to guide missing Elves back to base. Unfortunately, the message is easy to miss: the points move slowly enough that it takes hours to align them, but have so much momentum that they only stay aligned for a second. If you blink at the wrong time, it might be hours before another message appears.
You can see these points of light floating in the distance, and record their position in the sky and their velocity, the relative change in position per second (your puzzle input). The coordinates are all given from your perspective; given enough time, those positions and velocities will move the points into a cohesive message!
Rather than wait, you decide to fast-forward the process and calculate what the points will eventually spell.
For example, suppose you note the following points:
position=< 9, 1> velocity=< 0, 2>
position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1>
position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> velocity=< 2, 2>
position=<-6, 10> velocity=< 2, -2>
position=< 1, 8> velocity=< 1, -1>
position=< 1, 7> velocity=< 1, 0>
position=<-3, 11> velocity=< 1, -2>
position=< 7, 6> velocity=<-1, -1>
position=<-2, 3> velocity=< 1, 0>
position=<-4, 3> velocity=< 2, 0>
position=<10, -3> velocity=<-1, 1>
position=< 5, 11> velocity=< 1, -2>
position=< 4, 7> velocity=< 0, -1>
position=< 8, -2> velocity=< 0, 1>
position=<15, 0> velocity=<-2, 0>
position=< 1, 6> velocity=< 1, 0>
position=< 8, 9> velocity=< 0, -1>
position=< 3, 3> velocity=<-1, 1>
position=< 0, 5> velocity=< 0, -1>
position=<-2, 2> velocity=< 2, 0>
position=< 5, -2> velocity=< 1, 2>
position=< 1, 4> velocity=< 2, 1>
position=<-2, 7> velocity=< 2, -2>
position=< 3, 6> velocity=<-1, -1>
position=< 5, 0> velocity=< 1, 0>
position=<-6, 0> velocity=< 2, 0>
position=< 5, 9> velocity=< 1, -2>
position=<14, 7> velocity=<-2, 0>
position=<-3, 6> velocity=< 2, -1>
Each line represents one point. Positions are given as <X, Y> pairs: X represents how far left (negative) or right (positive) the point appears, while Y represents how far up (negative) or down (positive) the point appears.
At 0 seconds, each point has the position given. Each second, each point's velocity is added to its position. So, a point with velocity <1, -2> is moving to the right, but is moving upward twice as quickly. If this point's initial position were <3, 9>, after 3 seconds, its position would become <6, 3>.
Over time, the points listed above would move like this:
Initially:
........#.............
................#.....
.........#.#..#.......
......................
#..........#.#.......#
...............#......
....#.................
..#.#....#............
.......#..............
......#...............
...#...#.#...#........
....#..#..#.........#.
.......#..............
...........#..#.......
#...........#.........
...#.......#..........
After 1 second:
......................
......................
..........#....#......
........#.....#.......
..#.........#......#..
......................
......#...............
....##.........#......
......#.#.............
.....##.##..#.........
........#.#...........
........#...#.....#...
..#...........#.......
....#.....#.#.........
......................
......................
After 2 seconds:
......................
......................
......................
..............#.......
....#..#...####..#....
......................
........#....#........
......#.#.............
.......#...#..........
.......#..#..#.#......
....#....#.#..........
.....#...#...##.#.....
........#.............
......................
......................
......................
After 3 seconds:
......................
......................
......................
......................
......#...#..###......
......#...#...#.......
......#...#...#.......
......#####...#.......
......#...#...#.......
......#...#...#.......
......#...#...#.......
......#...#..###......
......................
......................
......................
......................
After 4 seconds:
......................
......................
......................
............#.........
........##...#.#......
......#.....#..#......
.....#..##.##.#.......
.......##.#....#......
...........#....#.....
..............#.......
....#......#...#......
.....#.....##.........
...............#......
...............#......
......................
......................
After 3 seconds, the message appeared briefly: HI.
Of course, your message will be much longer and will take many more seconds to appear.
What message will eventually appear in the sky?
"""
import numpy as np
import pylab as pl
from advent.log import show_log, log
def _manhattan_distance(p0, p1):
return abs(p0[0]-p1[0]) + abs(p0[1]-p1[1])
class Star(object):
def __init__(self, pos, vel):
self.pos = np.array(pos)
self.vel = np.array(vel)
def integrate(self):
self.pos += self.vel
def __repr__(self):
return "p=%s, v=%s" % (self.pos, self.vel)
def are_connected(si_pos, sj_pos):
if _manhattan_distance(si_pos, sj_pos) <= 2:
return True
else:
False
def _get_stars():
stars = []
with open("inputs/day10.txt") as f:
for l in f.readlines():
#example: position=<-10466, -10485> velocity=< 1, 1>
p, sep, v = l.partition("velocity=<")
p = p.replace("position=<", "").replace(">", "")
v = v.replace(">", "")
pos = [int(d) for d in p.split(",")]
vel = [int(d) for d in v.split(",")]
stars.append(Star(pos, vel))
return stars
def _get_adjacency_matrix(stars):
N = len(stars)
adj_mat = np.zeros((N,N))
for idxi in range(N):
for idxj in range(N):
if idxi != idxj and are_connected(stars[idxi], stars[idxj]):
adj_mat[idxi, idxj] = 1
return adj_mat
def _get_subgraphs(stars_pos):
adj_mat = _get_adjacency_matrix(stars_pos)
def get_recursive_graph(cidx, remaining_nodes):
connections = [n for n in remaining_nodes if adj_mat[cidx, n]==1]
for n in connections:
remaining_nodes.remove(n)
subconnect = []
for n in connections:
subconnect.extend(get_recursive_graph(n, remaining_nodes))
subconnect.append(cidx)
return subconnect
sub_graph_idx = []
remaining_nodes = range(len(stars_pos))
while len(remaining_nodes):
cidx = remaining_nodes.pop(0)
sub_graph = get_recursive_graph(cidx, remaining_nodes)
sub_graph_idx.append(sub_graph)
subgraphs = []
for sgi in sub_graph_idx:
subgraphs.append( np.array([stars_pos[idx] for idx in sgi]))
return subgraphs
def _get_stars_systems_dim(stars_poses):
return stars_poses.max(axis=1) - stars_poses.min(axis=1)
def get_message_in_sky(max_time=100000):
stars = _get_stars()
N = len(stars)
stars_pos0 = np.array([s.pos for s in stars]) # init position
stars_vel0 = np.array([s.vel for s in stars]) # init velocity
log( "compute integrated positions...")
stars_poses = np.array([stars_pos0 + stars_vel0*t for t in range(max_time)])
log("compute system dimensions...")
stars_sys_dim = _get_stars_systems_dim(stars_poses)
log("filter possible systems (with small dimensions)...")
possible_systems = [sp for sp,dim in zip(stars_poses, stars_sys_dim) if all(dim < 2*N)]
log("%d possibility" % len(possible_systems))
log("compute connexity...")
connexity = [(len(_get_subgraphs(sp)),sp) for sp in possible_systems]
min_connex_size, min_connex = min(connexity, key=lambda x: x[0])
log("found with min connexity %d" % min_connex_size)
subgraphs = _get_subgraphs(min_connex)
pl.figure()
for i,sg in enumerate(subgraphs):
pl.plot(sg[:,0], -sg[:,1], "o", color = [float(i)/len(subgraphs)]*3)
pl.grid()
pl.axis('equal')
pl.show()
"""
--- Part Two ---
Good thing you didn't have to wait, because that would have taken a long time - much longer than the 3 seconds in the example above.
Impressed by your sub-hour communication capabilities, the Elves are curious: exactly how many seconds would they have needed to wait for that message to appear?
"""
def get_time_to_get_message(max_time=100000):
stars = _get_stars()
N = len(stars)
stars_pos0 = np.array([s.pos for s in stars]) # init position
stars_vel0 = np.array([s.vel for s in stars]) # init velocity
log("compute integrated positions...")
stars_poses = np.array([stars_pos0 + stars_vel0*t for t in range(max_time)])
log("compute system dimensions...")
stars_sys_dim = _get_stars_systems_dim(stars_poses)
log("filter possible systems (with small dimensions)...")
possible_systems = [(t, sp) for t, sp in enumerate(stars_poses) if all(stars_sys_dim[t] < 2*N)]
log("%d possibility" % len(possible_systems))
log("compute connexity...")
connexity = [(t, len(_get_subgraphs(sp)),sp) for t, sp in possible_systems]
T, min_connex_size, min_connex = min(connexity, key=lambda x: x[1])
log("found at time %d with min connexity %d" % (T, min_connex_size))
return T
def check():
print("- Part 1: you need to run program and read by yourself") #Your puzzle answer was GEJKHGHZ.
print("- Part 2: {0}".format(get_time_to_get_message()==10681)) #Your puzzle answer was 10681.
if __name__ == '__main__':
show_log(True)
print("Part 1: get message in sky: %s" % get_message_in_sky()) #reply "GEJKHGHZ"
print("Part 2: get time to get message: %s" % get_time_to_get_message())
|
412ab66d747a484ee95a79dead13b06876430f5d | adnan-alam/Algorithms-implemented-in-Python | /Algorithms/insertion-sort.py | 299 | 4.15625 | 4 |
def insertionSort(array):
size = len(array)
for index in range(1,size):
temp = array[index]
hole = index
while hole > 0 and array[hole-1] > temp:
array[hole] = array[hole-1]
hole -= 1
array[hole] = temp
return array
|
6f556f21983664e7ca49ab82ad0459454f04691f | adu013/problems-python | /sort-InsertionSort/main.py | 839 | 4.1875 | 4 | # Sorting in ascending order \
# using Insertion Sort
def insertion_sort_via_swap(array):
for i in range (1, len(array)):
for j in range(i-1, -1, -1): # Starting from i-1 to 0 shifting by -1
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
else:
break
return array
def insertion_sort_via_shift(array):
for i in range (1, len(array)):
current_value = array[i]
for j in range(i-1, -1, -1):
if array[j] > current_value:
array[j+1] = array[j]
else:
array[j+1] = current_value
return array
# Validation
array = [4, 6, 24, 57, -4, -34, 73, 16, 8, 987, 3456, 34, -6736, 50]
x1 = insertion_sort_via_swap(array)
x2 = insertion_sort_via_shift(array)
print(x1)
print(x2)
|
827ed0297bcef19179f160b63d2f3b06c5992a16 | yonetaniryo/planning_python | /planning_python/data_structures/planning_problem.py | 884 | 4.09375 | 4 | #!/usr/bin/env python
"""Struct to define a planning problem which will be solved by a planner"""
class PlanningProblem:
def __init__(self, params):
self.initialized = False
self.params = params
def initialize(self, env=None, lattice=None, cost=None, heuristic=None, start_n=None, goal_n=None, visualize=False):
self.env = env
self.lattice = lattice
self.cost = cost
self.heuristic = heuristic
self.start_n = start_n
self.goal_n = goal_n
self.visualize = visualize
self.initialized = True
print('Planning Problem Initialized')
def reset_env(self, env):
"""Given the same lattice, cost, heuristic and params, reset the underlying environment"""
self.env = env
def reset_heuristic(self, heuristic):
"""Reset the heuristic function being used"""
self.heuristic = heuristic
|
2f8d3a6e5467586223c2cd61bf2c05e5d2be7651 | WellingtonTorres/PythonExercicios | /ex014.py | 129 | 3.953125 | 4 | c = float(input('Digite a temperatura em ºC: '))
f = 32 + c * 9/5
print('A temperatura {}ºC corresponde a {}ºF'.format(c, f))
|
605c21afedff26b2eed86d3d07a02589563e4002 | adnan15110/DataCompressionWithAdvise | /tests/test_context_tree.py | 508 | 3.71875 | 4 | from context_tree.context_tree import Trie, Queue
# Input keys (use only 'a' through 'z' and lower case)
def test_context_tree():
data='aababca'
# Trie object
t = Trie()
CONTEXT_LEN=3
q=Queue()
for char in data:
if q.size() < CONTEXT_LEN:
q.enqueue(char)
else:
q.dequeue()
q.enqueue(char)
if q.size()==CONTEXT_LEN:
t.insert(q.getQueueData())
assert 2 == t.search('ab')
assert 1 == t.search('bab') |
f631d7f0c20f9e4e151971c918c521baafa2689b | kevin31613/Leetcode | /Leetcode/1480.Running_Sum_of_1d_Array.py | 476 | 3.703125 | 4 | class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
l = len(nums)
nums1 = list()
nums2 = list()
k = 0
h = 0
while k < l:
k += 1
nums1 = [n1 for i, n1 in enumerate(nums) if i < k]
h = sum(nums1)
nums2.append(h)
print(nums2)
nums = [1,2,3,4]
h = Solution()
print(h.runningSum(nums)) |
d64eba77a0571454149a4573e1c317d6f12f726f | Hk4Fun/algorithm_offer | /target_offer/16_反转链表.py | 3,202 | 4.03125 | 4 | __author__ = 'Hk4Fun'
__date__ = '2018/1/30 15:24'
'''题目描述:
输入一个链表的头结点,反转该链表并输出反转后链表的头结点
'''
'''主要思路:
思路1:定义三个指针,分别指向当前遍历到的结点、它的前一个结点以及后一个结点
指向后一个结点的指针是为了防止链表断裂,因为需要把当前结点的下一个指针指向前一个结点
思路2:递归实现
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def ReverseList1(self, pHead): # 4行代码搞定
pre, cur = None, pHead
while cur:
# pre, cur.next, cur = cur, pre, cur.next
# 不能 pre, cur, cur.next = cur, cur.next, pre,否则后面cur.next中的cur是已经更新的cur
# 因此必须先保存cur.next,至于pre在哪个位置都行,因为它没引用cur
# 所以为了代码更加容易理解,可以重新调整一下顺序:从后往前
cur.next, cur, pre = pre, cur.next, cur
# 上面的一行等于下面四行
# next = cur.next # 先保存下一个结点防止断裂
# cur.next = pre
# pre = cur
# cur = next
return pre
def ReverseList2(self, pHead):
def recursive(pre, cur):
if not cur: return pre
next = cur.next
cur.next = pre
return recursive(cur, next)
if not pHead: return
return recursive(None, pHead)
# ================================测试代码================================
from Test import Test
class MyTest(Test):
def my_test_code(self):
self.debug = False # debug为True时每个测试用例只测试一遍,默认情况下关闭debug模式
self.TEST_NUM = 1 # 单个测试用例的测试次数, 只有在debug为False的情况下生效
# 只需在此处填写自己的测试代码
# testArgs中每一项是一次测试,每一项由两部分构成
# 第一部分为被测试函数的参数,第二部分只有最后一个,为正确答案
def linkNodes(values):
head = ListNode(None)
lastNode = head
for val in values:
newNode = ListNode(val)
lastNode.next = newNode
lastNode = newNode
return head.next
self.debug = False
testArgs = []
testArgs.append([linkNodes([1, 2, 3, 4, 5, 6]), [6, 5, 4, 3, 2, 1]]) # 1->2->3->4->5->6
testArgs.append([linkNodes([1]), [1]]) # 只有一个结点的链表: 1
testArgs.append([[], []]) # 空链表
return testArgs
def convert(self, result, *func_arg):
# 在此处填写转换函数,将测试结果转换成其他形式
def listNodes(pHead): # 将链表的值按顺序放进列表中
l = []
while pHead:
l.append(pHead.val)
pHead = pHead.next
return l
return listNodes(result)
if __name__ == '__main__':
solution = Solution()
MyTest(solution=solution).start_test()
|
9fbf77ca27564ef5d2a7961d508331545862b244 | sobrienpdx/pdx.code.guild | /pick6.py | 2,424 | 4 | 4 | # Have the computer play pick6 many times and determine net balance.
#
# Generate a list of 6 random numbers representing the winning tickets
# Start your balance at 0
# Loop 100,000 times, for each loop:
# Generate a list of 6 random numbers representing the ticket
# Subtract 2 from your balance (you bought a ticket)
# Find how many numbers match
# Add to your balance the winnings from your matches
# After the loop, print the final balance
# imports
import random
# constants
# Functions
#makes a list of 6 numbers
def pick6(top_range):
i = 0
numbers = []
while i < 6:
numbers.append(random.choice(range(1, top_range)))
i += 1
return numbers
# compares the ticket to the winning numbers
def compare_numbers(winning, ticket):
matches = 0
i = 0
while i < 6:
if ticket[i] == winning [i]:
matches +=1
i += 1
return matches
# calculates dollar value of ticket after purchase price
def money_won(matches):
if matches == 1:
winnings = 4
elif matches == 2:
winnings = 7
elif matches == 3:
winnings = 100
elif matches == 4:
winnings = 50000
elif matches == 5:
winnings = 1000000
elif matches == 6:
winnings = 25000000
elif matches == 0:
winnings = 0
winnings = winnings - 2
return winnings
def find_net_gain(top_range):
a = 0
net_gain = 0
while a < 5000:
winning = pick6(top_range)
# print("Winning numbers are {}".format(winning))
ticket = pick6(top_range)
# print("Ticket numbers are {}".format(ticket))
matches = compare_numbers(winning, ticket)
winnings = money_won(matches)
net_gain = net_gain + winnings
#print("There are {} matches. Net gain is {}".format(matches, net_gain))
a += 1
print(net_gain)
print(top_range)
return net_gain
top_range = 20
net_gain = 10000
winning = pick6(top_range)
#print("Winning numbers are {}".format(winning))
ticket = pick6(top_range)
print(find_net_gain(top_range))
print("Ticket numbers are {}".format(ticket))
while net_gain < -2000 or net_gain > 2000:
if net_gain < 2000:
top_range = top_range - 1
if net_gain > 2000:
top_range += 1
net_gain = find_net_gain(top_range)
print(net_gain)
print(top_range)
continue
#print("Your lifetime profit is {}".format(net_gain))
|
a833302137dbde18594e052e38a62a14e3362981 | dimamik/AGH_Algorithms_and_data_structures | /PRACTISE/LATO_FOR_EXAM/Sortowania/ALL/Zad_2_Median_Of_Sequence.py | 1,400 | 3.640625 | 4 | """
https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem
!Counting sort need to be used!
"""
import tab
import statistics
def Median(arr):
"""
Takes sorted array and returns its median
"""
if (len(arr) % 2 == 0):
return (arr[len(arr)//2 - 1] +arr[len(arr)//2] )/2
else:
return arr[len(arr)//2]
def Zad(arr,d,first_time_executed = true):
tab_c =[0] * 201
warning =0
first = 0
curr_tab_c = [None] * 201
sorted_tab = []
tab_to_return = [0]*(d)
for i in range(len(arr)):
if (i<d):
tab_c[arr[i]]+=1
else:
tmp_i = i
for j in range(len(tab_c)):
curr_tab_c[j]=tab_c[j]
if (first_time_executed):
first_time_executed = false
for i in range(1, len(tab_c)):
curr_tab_c[i] += curr_tab_c[i-1]
for j in range(d-1, -1, -1):
index_in_ret = curr_tab_c[arr[j]]-1
tab_to_return[index_in_ret] = arr[j]
curr_tab_c[arr[j]] -= 1
i = tmp_i
median = Median(tab_to_return)
k=arr[i]
if k>= 2 * median:
warning+=1
tab_c[arr[i]]+=1
tab_c[arr[first]]-=1
first+=1
return warning
pass
print(Zad(tab.tab,20000))
|
b286b74ab03860aa68e22e84f341afb7d45aeea6 | lumaherr/python_fundamentals | /02_basic_datatypes/02_04.py | 139 | 3.859375 | 4 | F = int(input("Please enter Fahrenheit degree: "))
C = round((F - 32) * (5 / 9), 1)
print(F, "degrees fahrenheit = ", C, "degrees celsius") |
05aca7b92b1c7d1c2d6166759da2a425a754274f | PauloJoaquim/cursopython | /ex099.py | 1,250 | 4.0625 | 4 | #Paulo, precisei assistir para fazer, mas fiz sem problemas, pois estava fazendo utilizando lista
from time import sleep
def maior(*números):
maior = 0
cont = 0
print('-='*20)
print(f'Analisando os valores informados...')
sleep(0.5)
for c in números:
print(f'{c}', end=' ', flush=True)
sleep(0.5)
cont += 1
print(f'-> Foram informados ao todo {cont} números')
print(f'O \033[1mmaior\033[m valor informado foi \033[1;36m{max(números)}\033[m')
print(f'E o \033[1mmenor\033[m valor informado foi \033[1;31m{min(números)}\033[m')
print()
maior(2, 9, 4, 5, 7, 1)
maior(4, 7, 0)
maior(1, 2)
maior(6)
maior(0)
#Guanabara
'''from time import sleep
def maior(* núm):
cont = maior = 0
print('-=' * 30)
print('Analisando os valores passados...')
for valor in núm:
print(f'{valor} ', end='', flush=True)
sleep(0.3)
if cont == 0:
maior = valor
else:
if valor > maior:
maior = valor
cont += 1
print(f'Foram informados {cont} valores ao todo.')
print(f'O maior valor informado foi {maior}.')
# Programa principal
maior(2, 9, 4, 5, 7, 1)
maior(4, 7, 0)
maior(1, 2)
maior(6)
maior()''' |
0c07e1ea7bf1e63ececb58211957b1e63444e83f | jaegyeongkim/Today-I-Learn | /알고리즘 문제풀이/프로그래머스/Level 1/문자열 내 p와 y의 개수.py | 268 | 3.5625 | 4 | def solution(s):
answer = True
p_cnt = 0
y_cnt = 0
for word in s:
if word == 'p' or word == 'P':
p_cnt += 1
elif word == 'y' or word == 'Y':
y_cnt += 1
if p_cnt != y_cnt:
return False
return True
|
cbe0a808e1bcd0ad79f94be8409329186fe4c108 | kim-minahm/CMDA-3654 | /minahm92_inclass4_final.py | 3,147 | 4.40625 | 4 | #Inclass4 Part 3
"""What does the code below do? Run the code in iPython.
For each line of code, add an explanation
through a comment."""
#PART I
#Use the code from Lecture14.py to create and change the
#'stuff' list; Then comment on each line of the code below
#what it does, and what the result is
#Lecture 14
#creates a string
ten_things = "Apples Oranges Crows Telephone Light Sugar"
#print "Wait there are not 10 things in that list. Let's fix that."
#splits the string, delimiting by spaces
stuff = ten_things.split(' ')
#makes an array 8 things
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
#checks length of stuff and if not 10 then go thruogh loop
while len(stuff) != 10:
#remove last item from more_stuff(right to left) and store it into next one
next_one = more_stuff.pop()
print "Adding: ", next_one
#add the popped item to stuff
stuff.append(next_one)
print "There are %d items now." % len(stuff)
#print the list
print "The 'stuff' list: ", stuff
#Working with Dictionaries
#makes a dictionary where a is 'some value' and b is a list of 1 through 4
d1 = {'a': 'some value', 'b': [1, 2, 3, 4]} #can contain lists
#Access an element by key
print d1['a']
#Add an element (a pair key: value) to the dict
d1[7] = 'an integer'
print d1
#Check if the dict contains a certain key
print "b" in d1
#Delete a value
del d1[7]
print d1
#Use functions defined for dictionaries
print "Keys", d1.keys()
print "Values", d1.values()
#/Lecture 14
print stuff[1]
print stuff[-1]
print stuff.pop()
print ' '.join(stuff)
print '#'.join(stuff[3:5])
#PART II
#Create comments where marked with # to explain the code below
# creates a dictionary with the state name and its abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# linkes the state abbreviation to a city
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# adds a definition to ny and or to the capitals
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# prints the state and the capital
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
#prints the abbreviation associated with the state
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# prints all the cities found in the given state
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# iterates through the state and checks the abbreviations for it
print '-' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# prints all the cities and checks for a given abbreviation
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# checks for all the states through abbrev and finds the corrosponding abreviation
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
|
e49418ec7022b41d1e5c218ae479afee8445fc86 | sninala/Python-Programming | /Programs/data_structures/searching_sorting/selectionSort.py | 640 | 3.703125 | 4 | #selection sort improves on the bubble sort by making only one exchange for every pass through the list
def selectionSort(items):
iterations = len(items) -1
while iterations:
maxValuePosition = 0
for current_position in range(1, iterations+1):
if items[current_position] > items[maxValuePosition]:
maxValuePosition = current_position
temp = items[iterations]
items[iterations] = items[maxValuePosition]
items[maxValuePosition] = temp
iterations -= 1
return items
items = [15, 70, 23, 44, 16, 99, 66, 32]
print selectionSort(items)
###O(nsquare) |
0ae3ec55cf289b0852476476be9330ffaab176f5 | leban-a/World-of-wizzard-and-warriors | /Die.py | 8,184 | 3.953125 | 4 | from random import randint
from Loading import *
class Die(): # Handles all actions which utilize a Dice Roll
critical_hit = False
# dice_list will store the differnt types of dice
dice_list = {
'D4':4,
'D6':6,
'D8':8,
'D10':10,
'D12':12,
'D20':20
}
# Each task which is perfomred will have a differnt difficulty. which will be a random rumber within the difficulty range.
difficulty_list={
"Very Easy":(randint(1,5)),
"Easy":(randint(6,10)),
"Medium":(randint(11,15)),
"Hard":(randint(16,20)),
"Very Hard":(randint(21,25)),
"Imposible":(randint(26,30))
}
def roll(self,die): # roll acts as a dice
roll = randint(1,self.dice_list.get(die))
return roll
def skill_roll(self,skill,difficulty,die): # skill check performed
print("The difficulty for this task is set to {}".format(difficulty)),sec(2)
difficulty = self.difficulty_list.get(difficulty)
print("\nYou need to roll a number equal to or above {}".format(difficulty)),sec(2)
gap()
print("Perform Skill Check"),sec(2)
input("#"),sec(4)
roll = self.roll('D20')
print(f"\nYou've rolled a {roll} with a proficiency of {skill}")
roll_total = roll + skill
if roll_total >= difficulty:
condition = True
else:
condition = False
return (condition)
def initiative_roll(self,PC_bonus,NPC_bonus,NPC_Name):
tie = False
while True: # Loop once as long as "tie" remains False
if tie == True:
prompt()
print("It's a Tie"),sec(2)
gap()
# PC initiative Roll
print("Perfrom a Initiative Check"),sec(2)
input("#")
roll = self.roll('D20')
print("\nYou've rolled a {} with Proficiency of {}".format(roll,PC_bonus)),sec(2)
PC_roll_total = roll + PC_bonus
prompt()
#NPC initiative Roll
print("{} will perform an Initiative Check".format(NPC_Name)),sec(4)
roll = self.roll('D20')
print("\n{} rolled a {} with a Proficiency of {}".format(NPC_Name,roll,NPC_bonus)),sec(2)
NPC_roll_total = roll + NPC_bonus
if NPC_roll_total == PC_roll_total:
tie = True
else:
break
prompt()
if NPC_roll_total > PC_roll_total: #sets who will act first.
print("{} rolled highest".format(NPC_Name)),sec(2)
return 'NPC'
else:
print("You've rolled the highest"),sec(2)
return 'PC'
def attack_roll(self,difficulty,player,NPC_Name,atk_bonus): # Used to to determine if an attack succeds or fails.
if player == "PC":
print("{} has a Armour class of {}".format(NPC_Name,difficulty)),sec(2)
gap()
print("Perform an Attack Roll"),sec(2)
input("#"),sec(4)
roll = self.roll('D20')
print(f"\nYou've rolled a {roll} with an Attack Bonus of {atk_bonus}"),sec(2) #" with a proficiency of {skills_main.get(skill)}""")
roll_total = roll + atk_bonus
if roll == 1:
print("\nYou've missed")
condition = False
elif (roll_total >= difficulty):
print("\nThus succeding in breaking through {}'s armour".format(NPC_Name)),sec(2)
condition = True
else:
print("\nThus failing to break through {}'s armour".format(NPC_Name))
condition = False
elif player == "NPC": # NPC actions will be automated
roll=self.roll("D20")
print("{} will perform an Attack Roll".format(NPC_Name)),sec(4)
print("\n{} has rolled a {} with an Attack Bonus of {}".format(NPC_Name,roll,atk_bonus)),sec(2)
roll_total = roll + atk_bonus
if roll == 1:
print("\nYou've missed")
condition = False
elif (roll_total >= difficulty):
print("\nThus succeding in breaking through your armour".format(NPC_Name)),sec(2)
condition = True
else:
print("\nThus failing to break through your armour".format(NPC_Name))
condition = False
if roll >= 20:
self.critical_hit = True
return condition
def hit_roll(self,die,rolls,bonus,player,NPC_Name): # Used to determine the amount of damage PC or NPC recieves.
damage = 0
if self.critical_hit == True:
self.critical_hit = False
rolls += 1
gap()
print("Critical Hit!!")
if player == "PC":
print("\nYou've gained an additional Hit Roll"),sec(2)
elif player == "NPC":
print("\n{} has gained an additional Hit Roll".format(NPC_Name)),sec(2)
if player == "PC":
count = 0
while count < rolls:
count += 1
gap()
print("Perform Hit Roll"),sec(2)
input("#"),sec(4)
roll = self.roll(die)
print("\nYou've rolled a {}".format(roll)),sec(2)
damage += roll
total_damage = damage + bonus
print("\nYou've dealt a total of {} Hit Points".format(total_damage))
return total_damage
elif player == "NPC":
gap()
print("{} will will perform an Hit Roll".format(NPC_Name)),sec(4)
count=0
while count != rolls:
count += 1
roll = self.roll(die)
print("\n{}'s rolled a {}".format(NPC_Name,roll)),sec(4)
damage += roll
total_damage = damage + bonus
print("\n{} has dealt a total of {} Hit Points".format(NPC_Name,total_damage))
return total_damage
def death_saving_throw(PC_health):
prompt()
print("Your Hit Points have fallen to 0")
print("\nYou have to peform a Death Saving Throw")
successes = ["O","O","O"]
failures = ["O","O","O"]
saves = 0
fails = 0
while (saves != 3) and (fails != 3):
sec(3)
gap()
print("Perform Saving Throw")
input("#")
saving_throw = Die().roll('D20')
sec(2)
gap()
print("You've Rolled a {}\n".format(saving_throw)),sec(2)
if saving_throw == 20:
print("You've regained 1 Hit Point")
PC_health += 1
successes[saves] = "X"
saves += 1
elif saving_throw == 1:
print("You've gained two fails")
failures[fails]=("X")
fails = fails + 1
if fails != 3:
failures[fails] = "X"
fails += 1
elif saving_throw >= 10:
print("That's a success")
successes[saves] = ("X")
saves += 1
else:
print("That's a fail")
failures[fails] = ("X")
fails += 1
sec(2)
gap()
print("Successes: {}".format(successes))
sec(0.2)
print("\nFailures: {}".format(failures))
if saves == 3:
PC_health =+ 1
return PC_health
|
e080b94f5fd0375df0d17b4643b28bcc2c626e7d | choyai/Data-Structure-FRA142 | /test.py | 525 | 3.8125 | 4 | from LinkedList import LinkedList
from Node import Node
from StackClass import StackClass
from Queue import Queue
import datetime
stacki = StackClass()
queue = Queue()
print(str(queue.isEmpty))
print(str(stacki.isEmpty))
#for i in range(10):
#stacki.push(Node(i))
#queue.add(Node(i))
#print(Node(i))
#for i in range(10):
#print(stacki.pop())
#print(queue.remove())
linked = LinkedList()
for i in range(10):
linked.add(Node(i), i)
for i in range(10):
print(linked.remove(i))
|
da33120e8219f02a1687b995f959a819b12f84ba | paulaandrezza/URI-Solutions | /2454.py | 112 | 3.578125 | 4 | a = input().split()
if a[0] == '0':
print("C")
elif a[1] == '0':
print("B")
else:
print("A") |
4bb4444bd34ac889604a31f9b55e2b09a6773ee5 | alindsharmasimply/Python_Practice | /seventyEighth.py | 386 | 3.625 | 4 | import string
import random
def password_generator():
for i in range(0, 6):
print random.choice(list(string.printable)),
print ' '
password_generator()
def password_generator2():
characters = 'abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*?'
password = random.sample(characters, 6)
password = "".join(password)
print password
password_generator2()
|
f93e75399d28908f952e947240afb0b9e92019a9 | 2019-b-gr2-fundamentos/Fund-Alquinga-Chuquimarca-Jefferson-Gilberto | /Deberes/arreglos.py | 1,019 | 3.84375 | 4 | listacontacto=[]
contacto = {}
def listar ():
for cont in listacontacto:
print (cont["nombre"],"-",cont["celular"],"-",cont["correo"],"-",cont["direccion"],"-",cont["cumpleaños"])
def agregar():
contacto = {}
contacto ["nombre"] = input ("Ingrese nombre:")
contacto ["celular"] = input ("Ingrese celular:")
contacto ["correo"] = input ("Ingrese correo:")
contacto ["direccion"] = input ("Ingrese direccion:")
contacto ["cumpleaños"] = input ("Ingrese fecha de nacimiento:")
listacontacto.append(contacto)
def buscarnombre(nombrebuscar):
for cont in listacontacto:
if (cont["nombre"]== nombrebuscar):
print (cont["nombre"],"-",cont["celular"],"-",cont["correo"],"-",cont["direccion"],"-",cont["cumpleaños"])
def buscarcorreo(correobuscar):
for cont in listacontacto:
if (cont["correo"]== correobuscar):
print (cont["nombre"],"-",cont["celular"],"-",cont["correo"],"-",cont["direccion"],"-",cont["cumpleaños"])
def editar():. |
2a68cc3606abd4966fa003c23c95da6d19ebc466 | ishmam-hossain/problem-solving | /leetcode/896_montonic_array.py | 589 | 3.53125 | 4 | class Solution:
def isMonotonic(self, A) -> bool:
if not A:
return False
increasing_sum = 0
decreasing_sum = 0
for i, n in enumerate(A[:-1]):
if n < A[i+1]:
increasing_sum += 1
elif n > A[i+1]:
decreasing_sum += 1
else:
increasing_sum += 1
decreasing_sum += 1
return increasing_sum == 0 or decreasing_sum == 0 or increasing_sum == len(A) - 1 or decreasing_sum == len(A) - 1
s = Solution()
print(s.isMonotonic([6, 5, 4, 4]))
|
54a70940bb63de2bb281c6c5619ee2188aee9f33 | aysemutlu/Codecademy_CapstoneProject | /Convoluted Kernel Maze.py | 3,129 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
from random import randint
# In[3]:
def build_maze(m,n,swag):
grid = []
grid = [['wall' for col in range(n)] for row in range(m)]
start_i, start_j = randint(0,m-1), randint(0,n-1)
grid[start_i][start_j] = 'start'
mow(grid,start_i,start_j)
explore_maze(grid, start_i, start_j, swag)
return grid
# In[4]:
def print_maze(grid):
for row in grid:
printable_row = ''
for cell in row:
if cell == 'wall':
char = '|'
elif cell == 'start':
char = 'X'
elif cell == 'empty':
char = ' '
else:
char = cell[0]
printable_row += char
print(printable_row)
# In[5]:
def mow(grid, i, j):
directions = ['U', 'D', 'L', 'R']
while len(directions) > 0:
directions_index = randint(0,len(directions)-1)
direction = directions.pop(directions_index)
if direction == 'U':
if i - 2 < 0:
continue
elif grid[i - 2][j] == 'wall':
grid[i - 1][j] = 'empty'
grid[i - 2][j] = 'empty'
mow(grid, i - 2, j)
elif direction == 'D':
if i + 2 >= len(grid):
continue
elif grid[i + 2][j] == 'wall':
grid[i + 1][j] = 'empty'
grid[i + 2][j] = 'empty'
mow(grid, i + 2, j)
elif direction == 'L':
if j - 2 < 0:
continue
elif grid[i][j-2] == 'wall':
grid[i][j-1] = 'empty'
grid[i][j-2] = 'empty'
mow(grid, i, j - 2)
else:
if j + 2 >= len(grid[0]):
continue
elif grid[i][j+2] == 'wall':
grid[i][j+1] = 'empty'
grid[i][j+2] = 'empty'
mow(grid, i, j+2)
# In[8]:
def explore_maze(grid, start_i, start_j, swag):
grid_copy = [row[:] for row in grid]
bfs_queue = [[start_i, start_j]]
directions = ['U','D', 'L', 'R']
while bfs_queue:
i, j = bfs_queue.pop(0)
if grid[i][j] != 'start' and randint(1,10) == 1:
grid[i][j] = swag[randint(0, len(swag) - 1)]
grid_copy[i][j] = 'visited'
for direction in directions:
explore_i, explore_j = i, j
if direction == 'U':
explore_i = i - 1
elif direction == 'D':
explore_i = i + 1
elif direction == 'L':
explore_j = j - 1
else:
explore_j = j + 1
if explore_i < 0 or explore_j < 0 or explore_i >= len(grid) or explore_j >= len(grid[0]):
continue
elif grid_copy[explore_i][explore_j] != 'visited' and grid_copy[explore_i][explore_j] != 'wall':
bfs_queue.append([explore_i, explore_j])
grid[i][j] = 'end'
# In[12]:
print_maze(build_maze(15,25,['candy corn', 'werewolf', 'pumpkin']))
# In[ ]:
#print_maze(build_maze(5,10,None))
|
b85f620551db413e55e7dee2c707f76b82717031 | poljkee2010/python_basics | /week_3/3.6 percents.py | 171 | 3.90625 | 4 | percent, rub, cop = (int(input()) for _ in range(3))
total_cop = cop + rub * 100
total_cop += total_cop * percent / 100
print(int(total_cop // 100), int(total_cop % 100))
|
78d01ef5f1e39a966c2998885bc25dc7e350064d | Bhaney44/Math | /math_module.py | 2,015 | 3.578125 | 4 | #------------------------------
#Number-theoretic and representation functions
#------------------------------
math.ceil(x)
#return the ceiling of x as a float, the smallest integer value >= x
math.factorial(x)
#Return x factorial. Value error if x is not integral or is negative.
math.floor(x)
#Return the floor of x as a float, the largest integer value =< x
math.fsum(iterable)
#return an accurate floating point sum of values in the iterable.
#avoids loss of precision by tracking multiple intermediate partial sums.
#------------------------------
#Power and logarithmic Functions
#------------------------------
math.exp(x)
#return e**x
math.log(x[,base])
#with one argument, return the natural logarithm of x (to base e)
#with two arguments, return the logarithm of x to the given base
#calculated as log(x)/log(base)
math.pow(x,y)
#Return x raised to the power y.
math.sqrt(x)
#Return the square root of x
#------------------------------
#Trigonometric function
#------------------------------
math.acos(x)
#return the arc cosine of x, in radians
math.asin(x)
#return the sine of x, in radians
math.cos(x)
#return the cosine of x radians
math.hypot(x, y)
#return the Euclidean norm.
#This is the length of the vector from the origin to point (x, y).
math.sin(x)
#return the sine of x in radians
math.tan(x)
#return the tangent of x radians
#------------------------------
#Angular conversion
#------------------------------
math.degrees(x)
#Convert angle x from radians to degrees.
math.radians(x)
#Convert angle x from degrees to radians
#------------------------------
#special functions
#------------------------------
math.erfc(x)
#return the error function at x.
math.gamma(x)
#return the gamma function at x.
math.lgamma(x)
#return the natural logarithm of the absolute value of the gamma function at x.
#------------------------------
#Constants
#------------------------------
math.pi
#Mathmatical constant 3.141592...
math.e
#the mathmatical constant 2.718281...
|
0025df1301b3fecda53d2a03d4e2cd76ca06ec4c | MayukhSobo/BestAlgos | /math/squareRoot.py | 599 | 4.09375 | 4 | # Babylonian method for square root....sqrt(n)
# We first initialize y = 1
# Put x = n
# calculate the average of x and y and store it to x...x = (x + y) / 2
# Do y = n / x
# Repeat the process as long as x - y is not very very small
def squareRoot1(n):
x = float(n)
y = 1.0
while x - y > 0.000001:
x = (x + y) / 2.0
y = n / x
return x
print squareRoot1(4)
# Square root using Binary Search
def squareRoot2(a, b=0):
mid = (a + b) / 2
if mid * mid == a:
return mid
elif mid * mid < a:
return squareRoot2(a, mid + 1)
else:
return squareRoot2(mid - 1, b)
print squareRoot2(6)
|
d11af9e12dba0db41d2895a566cbf3d444640bea | austinmw/code | /EC504_Data_Structures/queue/queue_natural.py | 552 | 4.0625 | 4 | # Queue. CRLS 10.1
#
# This is a simplified implementation of Stack using python list
#
# provides push(S,x) pop(S) and stack_empty(S
#
from collections import deque # deque is a Double Ended QUEue
class Queue(deque):
pass
def enqueue(Q,x):
Q.append(x)
def dequeue(Q):
return Q.popleft()
def queue_empty(Q):
return len(S)==0
Q=Queue()
for x in range(6):
enqueue(Q,x)
print(Q)
for x in range(6):
print(dequeue(Q),end=" ")
enqueue(Q,'s')
print(Q)
for x in range(12):
enqueue(Q,x)
print(dequeue(Q))
print(Q)
|
5c397928c458481f1ef005a1ac3b8daa92ace7be | pythonalicante/kata_TDD_01 | /fizz_buzz.py | 543 | 3.796875 | 4 | # coding: utf8
def fizz_buzz(value):
# Comprobamos el tipo de la variable
tipo_de_la_variable = type(value) # int, float, str, dict, list, etc...
if tipo_de_la_variable not in (int, float):
raise TypeError
# Comprobamos que sea divisible por 5 y por 3
if value % 3 == 0 and value % 5 == 0:
return 'fizz buzz'
# Comprobamos que sea divisible por 3
if value % 3 == 0:
return 'fizz'
# Comprobamos que sea divisible por 5
if value % 5 == 0:
return 'buzz'
return value
|
83287be77c2238d6bdebdb7b1f7bb7672258dfb7 | AmyShackles/algo-practice | /LeetCode/Easy/Python3/tests/test_reversestringii.py | 418 | 3.609375 | 4 | import unittest
from Python3.reversestringii import Solution
class TestreverseStr(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_1(self):
# For sanity checking:
# Input: s = "abcdefg", k = 2
# Output: "bacdfeg"
self.assertEqual(Solution.reverseStr("abcdefg", 2), "bacdfeg")
if __name__ == "__main__":
unittest.main()
|
a9898537088b03d3e628df750c3c0f5e43a35bda | joellerena/I_accompany_you_to_code | /codes/codigo1.py | 160 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# joellerena
"""
Created on Thu Aug 29 19:35:15 2019
"""
F = input("Ingrese un valor ")
C = round((int(F)-32)/1.8)
print("C: ",C) |
73eba3bc7bf3792aedc208ecdad843329adde665 | deepakdm2016/pythonPractice | /EdurekaExercise/a11_caseConvert.py | 51 | 3.53125 | 4 | s=input("Please enter the string")
print(s.upper()) |
5157d8f6700def5ec6b14e289b61255a98083f69 | BondiAnalytics/Python-Course-Labs | /04_conditionals_loops/04_01_divisible.py | 342 | 4.40625 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
n = str(input("Provide a number between 1 and 1,000,000,000: ", ))
n = int(n)
if n % 3 == 0:
print("n is divisible by 3")
else:
print("n is not divisible by 3") |
1df8ca510769053dabe4506931d6ec7f8d515d1c | ferreiradeveloper/Python-Juan | /03-Tipos-Datos.py | 420 | 3.515625 | 4 | # tipos de datos en python
# string las comilla puede ser simple o dobre pero nunca combinadas
nombre = 'Francisco'
apellido = " Ferreira"
# int
likes = 250
# Floats
total_pagar = 100.20
# Boolean se debe comenzar con mayuscula
pagado = True
print(nombre+apellido)
print(total_pagar)
print(pagado)
# Tipado Dinamico (en estos lenguajes la variable puede mutar de tipo de datos, pas igual que en PHP,Ruby o JS )
|
d9f65f45814077b0098f568eef6e96ad4c5551d3 | nyannko/leetcode-python | /alg/averange_of_levels_in_binary_tree.py | 856 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
# bfs
from collections import deque
if not root: return []
q = deque([root])
ret = [root.val]
while q:
res = []
for _ in range(len(q)):
cur = q.popleft()
if cur.left:
q.append(cur.left)
res.append(cur.left.val)
if cur.right:
q.append(cur.right)
res.append(cur.right.val)
if res:
ret.append(sum(res) / len(res))
return ret
|
e42a17576816890ed2c35cec73901ef732b6c968 | RodriPerez5/Lenguaje_C | /LenguajePYTHON/1_Operadores.py | 491 | 4.28125 | 4 |
# python 1_Operadores.py
#ejemplos de operadores
x = 3
y = 4
print("y= ", y)
print(x/y, "!=", x//y)#La división entera siempre toma el entero menor (No redondea!)
x = x < y**2 #ESTO DEVUELVE: UN True Ó UN False
print("x < y^2?", x)
y = not x #COMO x ES UN False, ENTONCES y SE CONVIERTE EN UN TIPO bool Y ADOPTA EL VALOR True
print("y= ", y)
print(x and y, x or y)#Los operadores lógicos son idiomáticos (and, or, not)
#RESULTAODO:
# 4.5 != 4
# x < y^2? False
# False True
|
6e296ee878ec9a353450431ff455971c61fc7dd4 | Mis0791/Mis0791.github.io | /product.py | 989 | 3.765625 | 4 | class Product(object):
def __init__(self, price, item, weight, brand, status):
self.price = price
self.item = item
self.weight = weight
self.brand = brand
self.status = status
def Sell(self):
self.status = "sold"
return self
def Tax(self):
tax = .09 * self.price
total = self.price + tax
return total
def Return(self):
if (self.status == "defective"):
self.price = 0
elif (self.status == "for sale"):
self.price = self.price
elif (self.status == "used"):
self.price *= .20
def displayInfo(self):
print "Price is" + " " + str(self.price) + " " + "dollars"
print "Item: " + str(self.item)
print str(self.weight) + "lbs"
print "Brand: " + self.brand
print self.status + ""
return self
product1 = Product(15, "chicken", 2, "Foster Farms", "for sale")
product1.displayInfo() |
bf3dd29f5c3624a773d1d70815eb4096f69445bf | MaskedDevil/All_programs | /Python/demo.py | 1,319 | 4.40625 | 4 | # # Print a patient's data
# patientName = 'John Smith'
# age = 20
# status = 'new'
# print(patientName, age, status)
# # Take an input and print
# name = input('What is your name? ')
# print('Hello', name)
# # Type Conversion Demo...int(), float(), bool(), str()
# birthYear = input('What is your birth year? ')
# age = 2021 - int(birthYear)
# print(age)
# # Sum of Two Numbers
# num1 = input('First: ')
# num2 = input('Second: ')
# sum = float(num1) + float(num2)
# print(sum)
# # String Props...<Strings are immutable>
# course = 'Python for beginners'
# print(course.upper())
# print(course.find('o'))
# print(course.replace('for', '4'))
# print('Python' in course)
# print(course)
# # Arithmetic Operations...'/' division returns floating point '//' division returns integer
# print(10 + 3, 10 - 3, 10 * 3, 10 / 3, 10 // 3, 10 % 3, 10 ** 3)
# # Comparison Operators[not demonstrated], Logical Operators
# price = 25
# print(price > 20 and price < 30)
# print(price < 20 or price < 30)
# print(not price > 20)
# # If-else if-else block
# temperature = 25
# if temperature > 30:
# print("It's a hot day")
# print("Drink plenty of water")
# elif temperature > 20:
# print("It's a nice day")
# elif temperature > 10:
# print("It's a bit cold")
# else:
# print("It's a cold day")
# print('Done')
|
f801c1da31840f6755d94c5c1e25b7f881268e6c | daniel-reich/ubiquitous-fiesta | /ivWdkjsHtKSMZuNEc_11.py | 165 | 4.03125 | 4 |
import re
def find_shortest_words(txt):
A=re.findall('[a-zA-Z]+\'?\w{0,3}', txt)
m=min(len(x) for x in A)
return sorted([x.lower() for x in A if len(x)==m])
|
2aea36c56bc3472a5feba31a375df334c74e9248 | KarlaISA/Programacion | /Laboratorio3b/ejercicio4/ejercicio4.py | 419 | 3.640625 | 4 | #Karla Ivonne Serrano Arevalo
#Ejerercicio 4
#Diciembre 2016
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0.0,2,0.01)
y1=np.sin(3*np.pi*x)
y2=1.2*np.sin(4*np.pi*x)
plt.subplot(3,1,1)
plt.fill_between(x,0,y1)
plt.ylabel('between y1 and 0')
plt.subplot(3,1,2)
plt.fill_between(x,y1,1)
plt.ylabel('between y1 and 1')
plt.subplot(3,1,3)
plt.fill_between(x,y1,y2)
plt.ylabel('between y1 and y2')
plt.xlabel('x')
plt.show()
|
aa5cfdf2de713c2eb5e9b2ed22082a2cfbffc08e | roberthsu2003/python | /重複執行/continue.py | 708 | 3.515625 | 4 | #!usr/bin/python3
'''
#continue.py
#請設計一個程式,讓使用者輸入數值,只有加總正偶數值,不加總正奇數值,如果輸入負數,結束程式。
顯示:========================================
請輸入第1個數值:456
請輸入第2個數值:455
請輸入第3個數值:123
請輸入第4個數值:-1
所有輸入的正偶數的加總是:xxxxxxx
=============================================
'''
num = 0
sum = 0
while(True):
num += 1
inputNum = int(input("請輸入第"+ str(num) + "個數值:"))
if(inputNum < 0):
break
elif (inputNum % 2 == 1):
continue
else:
sum += inputNum
print("所有輸入的正偶數的加總是:", sum)
|
47db8c8e2eb99b5b5296a362a222144a6e293b54 | ajinkyad13/LeetCode_For_Interviews | /Python_Solutions/26. Remove Duplicates from Sorted Array.py | 175 | 3.546875 | 4 | class Solution:
def removeDuplicates(nums):
from collections import Counter
nums = list(Counter(nums).keys())
a= removeDuplicates([1,1,2])
print(a) |
2a1eeb00dfa517a87969b4e1e3d4452e3e19dfbd | MarshalLeeeeee/myLeetCodes | /88-mergeSortedArray.py | 1,558 | 4.09375 | 4 | '''
88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
'''
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if not m:
for i in range(n):
nums1[i] = nums2[i]
elif not n: pass
else:
mi, ni = 0, 0
move = []
while ni < n and mi < m:
if nums1[mi] < nums2[ni]:
move.append(ni)
mi += 1
else:
ni += 1
if len(move) != m:
for i in range(len(move),m):
move.append(ni)
done = []
for i in range(m+n):
done.append(0)
for i in range(m-1,-1,-1):
nums1[i], nums1[i+move[i]] = nums1[i+move[i]], nums1[i]
done[i+move[i]] = 1
ni = 0
for i in range(m+n):
if not done[i]:
nums1[i] = nums2[ni]
ni += 1 |
7d70e7b1dc35210123187fcb8858e1965285f79c | alexandre-mazel/electronoos | /talk/talk.py | 365 | 3.84375 | 4 |
def talk():
while( 1 ):
s = raw_input( "Humain: " );
s = s.lower();
ans = "je n'ai pas compris!"
if( "bonjour" in s ):
ans = "salut"
if( "au revoir" in s ):
ans = "bye"
print "Ordinateur: " + ans
if( ans == "bye" ):
break;
talk(); |
6b292da7bb8c939c84f2fe839ef3245b7a183806 | JobsDong/leetcode | /problems/98.py | 1,212 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = ['"wuyadong" <wuyadong311521@gmail.com>']
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def max_node(self, r):
p = r
while p.right:
p = p.right
return p
def min_node(self, r):
p = r
while p.left:
p = p.left
return p
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if root.left is not None:
if self.max_node(root.left).val >= root.val:
return False
if not self.isValidBST(root.left):
return False
if root.right is not None:
if self.min_node(root.right).val <= root.val:
return False
if not self.isValidBST(root.right):
return False
return True
def tree():
r = TreeNode(2)
r.left = TreeNode(1)
r.right = TreeNode(3)
return r
if __name__ == "__main__":
print Solution().isValidBST(tree())
|
324d650e9fc20ba8de2e89f246a183f97b13d027 | ulat/udacity_intro_to_machine_learning | /datasets_questions/explore_enron_data.py | 5,214 | 3.828125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import pickle
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
print "Analyzing the Enron Dataset"
################################################################################
# How many data points (people)?
print "How many data points (people)?", len(enron_data)
################################################################################
# For each person, how many features are available?
nbFeatures = []
totalNbFeatures = 0
for person in enron_data:
nbFeatures.append(len(person))
totalNbFeatures += len(person)
print "how many features ", nbFeatures, len(nbFeatures), min(nbFeatures), \
totalNbFeatures
################################################################################
# How many POIs are there in the E+F dataset?
pois = 0
poisInEmaillist = 0
for key in enron_data.keys():
if "poi" in enron_data[key].keys():
if enron_data[key]["poi"] == 1:
pois += 1
print "nb of pois: ", pois
################################################################################
# How Many Pois are in the Email File?
poi_reader = open('../final_project/poi_names.txt', 'r')
poi_reader.readline() # skip url
poi_reader.readline() # skip blank line
poi_count = 0
for poi in poi_reader:
poi_count += 1
print "pois in email list: ", poi_count
################################################################################
# What is the total value of the stock belonging to James Prentice?
print "Prentice James Total stock Value", \
enron_data["PRENTICE JAMES"]["total_stock_value"]
################################################################################
# How many email messages do we have from Wesley Colwell to persons of interest?
print "Total mails von Colwell Wesley to POIs", \
enron_data["COLWELL WESLEY"]["from_this_person_to_poi"]
################################################################################
# Whats the value of stock options exercised by Jeffrey K Skilling?
print "Valeu of Stock Options by Skilling Jeffrey", \
enron_data["SKILLING JEFFREY K"]["exercised_stock_options"]
################################################################################
# Among Lay, Skilling and Fastow, who took home the most money?
most_paid = ''
highest_payment = 0
for key in ('LAY KENNETH L', 'FASTOW ANDREW S', 'SKILLING JEFFREY K'):
if enron_data[key]['total_payments'] > highest_payment:
highest_payment = enron_data[key]['total_payments']
most_paid = key
print "Most paid to:", most_paid, "highest payment:", highest_payment
################################################################################
# NotANumber
print(enron_data['SKILLING JEFFREY K'])
################################################################################
# How many folks have a quantified salary?
print "total of persons with quantified salary:", \
len([key for key in enron_data.keys() if enron_data[key]['salary'] != 'NaN'])
# Total of persons without email
print "total of persons without email: ", \
len([key for key in enron_data.keys() if enron_data[key]['email_address']!='NaN'])
################################################################################
# How many people have NaN for total_payments? What is the percentage of total?
no_total_payments = len([key for key in enron_data.keys() if enron_data[key]["total_payments"] == 'NaN'])
print "total payments with NaN:", float(no_total_payments)/len(enron_data) * 100
################################################################################
# What percentage of POIs in the data have "NaN" for their total payments?
POIs = [key for key in enron_data.keys() if enron_data[key]['poi'] == True]
number_POIs = len(POIs)
no_total_payments = len([key for key in POIs if enron_data[key]['total_payments'] == 'NaN'])
print "percentage of POIs in the data have \"NaN\" for their total payments", \
float(no_total_payments)/number_POIs * 100
################################################################################
# If 10 POIs with NaN total_payments were added, what is the new number of people?
# What is the new number of people with NaN total_payments?
print "New total number of datasets in enron_data:", len(enron_data) + 10
print "New total for number of datasets with total_payments == 'NaN':", \
10 + len([key for key in enron_data.keys() if enron_data[key]['total_payments'] == 'NaN'])
################################################################################
# What is the new number of POIs?
new_nb_pois = 10 + len(POIs)
print "new number of POIs: ", new_nb_pois
# What percentage have NaN for their total_payments?
print "percentage with NaN in total_payments", \
float(no_total_payments+10)/(number_POIs+10) * 100
print len(POIs)/float(31)
|
2071de500710cdebe4c174f8e85547be4a69e081 | kissghosts/data-mining-2013 | /problem 3/popular_sequence.py | 8,069 | 3.609375 | 4 | #!/usr/bin/python
import argparse
import sys
import copy
import time
from sets import Set
def support_counting(sequence, sequences):
"""calc support for sequence
"""
support_count = 0
for each_sequence in sequences:
# 1-size sequence
if isinstance(sequence, int):
for each_term in each_sequence:
if sequence in each_term:
support_count += 1
break
# sequence which contains more than 1 course
else:
super_s = copy.deepcopy(each_sequence)
if is_sub(sequence, super_s):
support_count += 1
return support_count
def is_sub(sequence1, sequence2):
"""check whether sequence2 is the super set of sequence 1,
return True or False
"""
for each in sequence1:
for i in range(len(sequence2)):
# use built-in Set class
a = Set(each)
b = Set(sequence2[i])
if b.issuperset(a):
# delete the terms before i, and then move to check
# next course(term) in sequence1
sequence2 = sequence2[(i + 1):]
break
else:
return False
return True
def gen_candidate(sequences):
"""generate candidates
"""
candidates = []
num = len(sequences)
# the combination method used for k = 1 is different
if len(sequences[0]) == 1 and len(sequences[0][0]) == 1:
for n in range(num - 1):
for m in range(n + 1, num):
candidates.append([sequences[n][0], sequences[m][0]])
candidates.append([sequences[m][0], sequences[n][0]])
if sequences[n][0][0] < sequences[m][0][0]:
candidates.append([[sequences[n][0][0], sequences[m][0][0]]])
else:
candidates.append([[sequences[m][0][0], sequences[n][0][0]]])
else:
for n in range(num - 1):
for m in range(n + 1, num):
if len(sequences[n][0]) > 1:
s1 = [sequences[n][0][1:]] + sequences[n][1:]
else:
s1 = sequences[n][1:]
if len(sequences[m][-1]) > 1:
s2 = sequences[m][:-1] + [sequences[m][-1][:-1]]
else:
s2 = sequences[m][:-1]
if s1 == s2 and sequences[n][0][0] != sequences[m][-1][-1]:
if len(sequences[m][-1]) == 1:
msequence = sequences[n] + [sequences[m][-1]]
else:
last_element = sequences[n][-1] + [sequences[m][-1][-1]]
msequence = sequences[n][:-1] + [sorted(last_element)]
# use contiguous subsequence to prune
subs = sub_sequence(msequence)
for each in subs:
if each not in sequences:
break
else:
candidates.append(msequence)
return candidates
def sub_sequence(sequence):
"""generate subsequence for pruning, return a list
"""
subs = []
num = len(sequence)
for i in range(num):
if i == 0 and len(sequence[i]) > 1:
for each in sequence[i][1:]:
copied = copy.copy(sequence[i])
copied.remove(each)
sub = [copied] + sequence[(i + 1):]
if sub not in subs:
subs.append(sub)
if i > 0 and i < num -1:
for each in sequence[i]:
copied = copy.copy(sequence[i])
copied.remove(each)
sub = sequence[:i] + [copied] + sequence[(i + 1):]
if sub not in subs:
subs.append(sub)
if i == num -1 and len(sequence[i]) > 1:
for each in sequence[i][:-1]:
copied = copy.copy(sequence[i])
copied.remove(each)
sub = sequence[:i] + [copied]
if sub not in subs:
subs.append(sub)
return subs
# main func
if __name__ == '__main__':
# option parser
parser = argparse.ArgumentParser(description='description: '
'Apriori-like algorithm to find most popular sequence(s)')
parser.add_argument('--s', dest='support', type=int, default=50,
help="support value, default value is 20 (20 percent)")
parser.add_argument('infile', type=argparse.FileType('r'),
help='path of input file')
parser.add_argument('outfile', type=argparse.FileType('w'),
help='path of output file')
parser.add_argument('--ctoken', type=str, default=' ',
help="string used for splitting each course, e.g. ',', "
"default value is space")
parser.add_argument('--ttoken', type=str, default=', ',
help="string used for splitting each course, e.g. ',', "
"default value is ', '")
parser.add_argument('--minsize', type=int, default=2, help="minimal size "
"of frequent itemsets")
parser.add_argument('--maxsize', type=int, default=0, help="max size of "
"frequent itemsets, 0 means no limitation")
args = parser.parse_args()
if args.minsize < 1:
print "error: minsize should be larger than 1"
sys.exit(1)
# pre-process the input data
minsup = args.support / 100.0
minsize = args.minsize
if args.maxsize <= 0:
maxsize = 0
elif args.maxsize < minsize:
print "error: minsize should not be larger than maxsize"
sys.exit(1)
else:
maxsize = args.maxsize
sequences = []
k1_items = []
frequent_sequences = {}
for line in args.infile:
sequence = []
term = line.strip().split(args.ttoken)
for each in term:
str_list = each.split(args.ctoken)
sequence.append([int(c) for c in str_list])
sequences.append(sequence)
for each_term in sequence:
for each_course in each_term:
if each_course not in k1_items:
k1_items.append(each_course)
# generate the 1-size frequent sequence
print "%s sequence(s)" % len(sequences)
print "generating sequence(s) ..."
start_time = time.time()
count = len(sequences) + 0.0
frequent_sequences[1] = []
for each in k1_items:
sup = support_counting(each, sequences) / count
if sup > minsup:
frequent_sequences[1].append([[[each]], sup])
if not frequent_sequences[1]:
print "no sequence generated"
sys.exit(0)
# generate all frequent sequences
n = 1
while minsize > 1 and ((maxsize != 0 and n < maxsize) or maxsize == 0):
frequent_sequences[n + 1] = []
k_freq_sequences = []
for each in frequent_sequences[n]:
k_freq_sequences.append(each[0])
candidates = gen_candidate(k_freq_sequences)
for each in candidates:
sup = support_counting(each, sequences) / count
if sup > minsup:
frequent_sequences[n + 1].append([each, sup])
if frequent_sequences[n + 1] == []:
frequent_sequences.pop(n + 1)
break
n += 1
end_time = time.time()
print "generating sequence(s) done [%.4fs]" % (end_time - start_time)
# write the result
output = {}
length = len(frequent_sequences) + 1
end = maxsize if (maxsize != 0 and maxsize < length) else length
for i in range(minsize, length):
if frequent_sequences[i]:
for each in frequent_sequences[i]:
if not output.has_key(each[1]):
output[each[1]] = [each[0]]
else:
output[each[1]].append(each[0])
num = 0
for key in sorted(output.keys(), reverse=True):
for each in output[key]:
args.outfile.write("%s, %s\n" % (each, key))
num += 1
print "%s set(s) generated" % num
|
2e5dbfc7cd1f9df1ad43481e1543d0d47a2be9d1 | hc9701/spider_book | /code/3-3.py | 1,291 | 3.65625 | 4 | import sys
寻找女朋友=lambda x:print('%d岁,寻找女朋友ing...'%x)
结婚=lambda x:print('%d岁,结婚啦,xswl'%x)
单身=lambda :print('emmm其实单身也挺好...')
等死=lambda:print('等死,人最终还是要死的,也不知我死的时候是一个人还是两个人,都有可能')
def 生活(结婚年龄):
for 年龄 in range(5):
print('%d岁,没印象,应该单身吧?'%年龄)
for 年龄 in range(5,10):
print('%d岁~%d岁,有印象,单身!'%(年龄,年龄+1))
for 年龄 in range(10,20,2):
print('%d岁~%d岁,依然单身'%(年龄,年龄+2))
while 40>年龄 >=18:
try:
寻找女朋友(年龄)
还没找到女朋友 = 年龄<结婚年龄-3
if 还没找到女朋友 and 年龄<30:
continue
elif not 还没找到女朋友:
pass
else:
raise Exception('唉,注孤生')
except Exception as e:
print(e)
else:
结婚(年龄+3)
return
finally:
等死()
年龄+=1
单身()
if __name__=='__main__':
assert len(sys.argv)==2,'输入结婚年龄哦'
结婚年龄=int(sys.argv[1])
生活(结婚年龄)
|
6b852b5e2ac1454fa36732fd4d637ee136196d89 | Felix-xilef/Curso-de-Python | /Desafios/Desafio49.py | 198 | 3.953125 | 4 | n = int(input('\n\tDigite um número: '))
print('\n\tTabuádo do {}:'.format(n))
for i in range(0, 11):
print('\t {} x {} = {}'.format(n, i, n*i))
input('\n\nPressione <enter> para continuar')
|
3cca3b05254d5ef9129bc817088e892c382fe4a6 | ashkanyousefi/Algorithms_and_Data_Structures | /HW1/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 282 | 4.09375 | 4 | #%%
# Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
n = int(input())
print(calc_fib(n))
# I do not fully understand where the recursive algorithm is keeping the calculated values when we go forward in the chain
|
5c1362a74518ba284fd9c4e589bf6e93183bc362 | onewns/TIL | /algorithm/etc/BOJ_1181(sort).py | 174 | 3.5625 | 4 | import sys
sys.stdin = open('../input.txt', 'r')
n = int(input())
words = list(set(input() for _ in range(n)))
words.sort(key=lambda x: (len(x), x))
print(*words, sep='\n') |
6d7bc6f34bc9e2d8271fbb2494e69deb53d3de2b | LawerenceLee/coding_dojo_projects | /python_stack/car_class.py | 727 | 3.734375 | 4 |
class Car:
def __init__(self, price, speed, fuel, mileage):
self.price = price
if price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.display_all()
def display_all(self):
print("Price: ${}, Speed: {} mph, Fuel: {}, Milage: {} mpg, Tax: {}".format(
self.price, self.speed, self.fuel, self.mileage, self.tax))
toyota_prius = Car(2000, 35, "full", 15)
range_rover = Car(2000, 5, "not Full", 105)
ford_raptor = Car(2000, 15, "Kind of Full", 95)
gremlin = Car(2000, 25, "Full", 25)
jeep = Car(2000, 45, "Empty", 25)
nissan = Car(2000000, 35, "Empty", 15)
|
62350c3f718ff7044f6f13b91a64a1a567ba92c8 | CharlesDerek/MRGI-PythonMasterClass | /08-Builtin-Functions/map.py | 699 | 4.5 | 4 | '''
PYTHON 3: map returns an iterable, not a list as in python 2. Use list() if required
Syntax: map(function,sequence)
map subjects each element in the sequence to the specified function, and returns the results in the form of a list
'''
# NOTE: map(F, S) can almost always be written as [F(x) for x in S] -> lambda is slower than list comprehension
def farenheit(T):
return (9.0/5)*T + 32
temps = [0, 22.5, 40, 100]
print map(farenheit, temps) # notice that the function is not passed with parentheses
print map(lambda T: (9.0/5)*T + 32, temps)
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
print map(lambda x, y, z: x+y+z, a, b, c) # lambda function can use muliple arguments |
b6ed802ec42e7d34cb0844350aeec6e5e2687825 | krsnadatra/Contoh-Program | /2019/computer.py | 6,484 | 3.59375 | 4 | from collections.abc import Iterable
from collections import deque
class Computer:
def __init__(self, int_code, memory=10000):
self.parameter_modes = {'0':lambda x: self.read(x),
'0o': lambda x: x,
'1':lambda x: x,
'2':lambda x: self.read(x + self.relative_base),
'2o':lambda x: x + self.relative_base}
self.instructions = {'01':lambda x, y, out: self.write(x + y, out),
'02':lambda x, y, out: self.write(x * y, out),
'03':lambda out: self.write(self.feed.pop(), out),
'04':lambda x: self.out.appendleft(x),
'05':lambda x, y: self.move(address=y) if x else None,
'06':lambda x, y: self.move(address=y) if not x else None,
'07':lambda x, y, out: self.write(int(x < y), out),
'08':lambda x, y, out: self.write(int(x == y), out),
'09':lambda x: self.move(relative_base_incr=x),
'99':None}
self.int_code = int_code + [0] * memory
self.last_write_to = -1
self.feed = deque()
self.out = deque()
def reset(self):
"""
Set instruction_pointer to 0, reinitialize our memory, and dump self.out.
"""
self.relative_base = 0
self.instruction_pointer = 0
self.memory = self.int_code.copy()
self.out.clear()
def read(self, address=None):
"""
Return the value at instruction_pointer and increment_instruction pointer if address
is None else return the value at address.
"""
if address is None:
address = self.instruction_pointer
self.move()
return self.memory[address]
def write(self, value, address=None):
"""
Write the value at the given address or at instruction_pointer if address is None.
"""
if address is None:
address = self.instruction_pointer
self.memory[address] = value
self.last_write_to = address
def move(self, *, incr=1, address=None, relative_base_incr=None):
"""
If address is given, move instruction_pointer to address
Else if relative_base_incr is given, increment relative_base by relative_base_incr
Else increment instruction_pointer by incr
Passing multiple keywords to this method not suggested.
"""
if address is not None:
self.instruction_pointer = address
elif relative_base_incr is not None:
self.relative_base += relative_base_incr
else:
self.instruction_pointer += incr
def parse_modes(self, read_str, instruction):
"""
Parse modes by filling read_str with leading '0's so that len(modes) == number of
instruction parameters.
If instruction writes out, the mode corresponding to an out parameter has 'o' appended
to it. (We take into account that self.write already interprets out parameters as
positions.)
"""
names = instruction.__code__.co_varnames
modes = reversed(read_str.zfill(len(names)))
return [mode + 'o'[name != 'out':] for mode, name in zip(modes, names)]
def connect(self, new_feed):
"""
If new_feed is a Computer we'll connect that Computer's *out* to our *in*.
If new_feed is a deque, we'll move existing items in feed to new_feed then set
self.feed to new_feed.
Else if new_feed is an iterable we'll move items from that iterable into our feed.
Else we'll place new_feed on top of the stack.
"""
if isinstance(new_feed, Computer):
self << new_feed.out
elif isinstance(new_feed, deque):
new_feed.extend(self.feed)
self.feed = new_feed
elif isinstance(new_feed, Iterable):
for item in new_feed:
self.feed.appendleft(item)
else:
self.feed.append(new_feed) # We may appendleft in the future.
def __lshift__(self, *args, **kwargs): # '<<' functionality for connect
self.connect(*args, **kwargs)
def pop(self):
"""
Shortcut to retrieve oldest output.
"""
return self.out.pop()
def last(self):
"""
Shortcut to retrieve newest output.
"""
return self.out.popleft()
def __len__(self):
"""
Shortcut to check length of self.out.
"""
return len(self.out)
def __bool__(self):
"""
Shortcut for checking if we've produced output.
"""
return bool(self.out)
def compute_iter(self, feed=None):
"""
Returns an iterator, each item being (instruction_pointer, op_code, modes, parameters,
pamaraters with modes applied) of the current state of computation.
"""
self.reset()
if feed is not None:
self << feed
while True:
unparsed = str(self.read())
op_code = unparsed[-2:].zfill(2)
instruction = self.instructions[op_code]
if instruction is None: # Halt
yield self.instruction_pointer - 1, op_code, [], [], []
break
modes = self.parse_modes(unparsed[:-2], instruction)
mapped_modes = map(self.parameter_modes.get, modes)
params = [self.read() for _ in modes]
moded_params = [mode(param) for mode, param in zip(mapped_modes, params)]
yield self.instruction_pointer - len(modes) - 1, op_code, modes, params, moded_params
instruction(*moded_params)
def __iter__(self):
"""
Iterator functionality.
"""
return self.compute_iter()
def compute(self, feed=None):
"""
Returns the last item of compute_iter.
"""
for result in self.compute_iter(feed):
pass
return result
def compute_n(self, niter, feed=None):
"""
Run self.compute niter times.
"""
all_outs = []
if feed is not None:
self << feed
for _ in range(niter):
self.compute()
all_outs.extend(reversed(self.out))
return all_outs
|
7e71c82f1e1368c2d428600e86f283155cde719c | PelinSeloglu/MachineLearningExamples | /BridgeandTorch_A.py | 5,932 | 3.671875 | 4 | import itertools
#node class'ı ve içerisinde uzunluk değerlerini, karşıya geçiş couple'ını, geri dönüşte torch'u taşıyan kişiyi
# ve parent'ını tutar
class Node():
def __init__(self,parent=None, couple = None, turn = None):
self.g = 0 # git gel sürelerinin toplamı
self.h = 0 # bir sonraki geçmesi gereken en uzun süreli kimse
self.f = 0 # g + h
self.parent = parent
self.couple = couple
self.turn = turn
#köprünün sağında kalanların bulunduğu listeyi alarak olası ikili kombinasyonları oluşturur
def generate_couple(arr):
couple_list = []
for subset in itertools.combinations(arr, 2):
couple_list.append(subset)
return couple_list
#node' un g değerini o node için gidiş ve dönüş değerlerinin toplamı olarak hesaplar
def calculate_g(node, left_arr, right_arr):
couple = node.couple
min_couple = min(couple)
max_couple = max(couple)
if len(left_arr) != 0:
min_left_list = min(left_arr)
if min_couple < min_left_list and len(right_arr) > 2:
node.turn = min_couple
return max_couple + min_couple
elif min_couple > min_left_list and len(right_arr) > 2:
node.turn = min_left_list
return max_couple + node.turn
elif len(right_arr) == 2:
node.turn = 0
return max_couple
else:
return max_couple + min_couple
#node'un h değerini kendisinden sonra gelip karşıya geçmesi gereken en büyük değer olarak hesaplar
def calculate_h(node, right_arr):
maxCouple = max(node.couple)
minCouple = min(node.couple)
if len(right_arr) == 0:
return 0
elif maxCouple == max(right_arr):
tempList = right_arr.copy()
tempList.remove(maxCouple)
if minCouple == max(tempList) and len(tempList)>1:
temp2 = tempList.copy()
temp2.remove(minCouple)
return max(temp2)
else:
return max(tempList)
else:
return max(right_arr)
#node'un f uzunluğunu g+h şeklinde hesaplar
def calculate_f(node):
node.f=node.g + node.h
return node.f
#seçilen node'un sağ listeden sol listeye geçmesi için gerekli olan işlemleri yapar
def addLeftRight(node, left_list, right_list):
couple = node.couple
min_couple = min(couple)
max_couple = max(couple)
min_left_list = min(left_list)
if min_couple < min_left_list and len(right_list) > 2:
right_list.remove(max_couple)
left_list.append(max_couple)
node.turn = min_couple
elif min_couple > min_left_list and len(right_list) > 2:
right_list.append(min_left_list)
node.turn = min_left_list
left_list.remove(min_left_list)
left_list.append(min_couple)
left_list.append(max_couple)
right_list.remove(max_couple)
right_list.remove(min_couple)
elif len(right_list) == 2:
left_list.append(min_couple)
left_list.append(max_couple)
right_list.remove(max_couple)
right_list.remove(min_couple)
node.turn = 0
#tüm a* algoritması ile ilgili işlemler burada gerçekleşir
def Solver(start_couple, left_list, right_list, time):
start_node = Node(None, start_couple, min(start_couple))
start_node.h = calculate_h(start_node, right_list)
start_node.g = calculate_g(start_node,left_list,right_list)
start_node.f = calculate_f(start_node)
count = 0
open_list = []
closed_list = []
open_list.append(start_node)
while len(open_list) > 0:
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):#f değerine göre en iyi node seçimi burada gerçekleşir
if item.f < current_node.f:
current_node = item
current_index = index
open_list.pop(current_index)
closed_list.append(current_node)
if current_node.couple == start_node.couple:
left_list.append(max(start_node.couple))
right_list.remove(max(start_node.couple))
start_node.turn = min(start_node.couple)
else:
addLeftRight(current_node, left_list, right_list)
print("Şuandaki Çift: ",current_node.couple)
count += current_node.turn + max(current_node.couple)
if count == time: #sona ulşılınca path döndürme işlemi burada gerçekleşir
path = []
current = current_node
while current is not None:
path.append(current.couple)
current = current.parent
return path[::-1]
children = []
for new_couple in generate_couple(right_list): #sağ listede kalanlara göre olası çiftler oluşturulur
node_couple = new_couple
new_node = Node(current_node, node_couple)
children.append(new_node)
for child in children:
for closed_child in closed_list:
if child == closed_child:
continue
#oluşturulan child için g,h,f değerlerinin hesaplandırılması
child.g = calculate_g(child, left_list, right_list)
child.h = calculate_h(child, right_list)
child.f = calculate_f(child)
for open_node in open_list:
if child == open_node and child.g > open_node.g:
continue
open_list.append(child)
def main():
left_arr = []
right_arr = [1,2,5,8]
start_arr = [1,2,5,8]
time = 15
#ilk node için doğru node seçilip istenilen sonuç elde edilene kadar devam edilir.
for x in generate_couple(start_arr):
path = Solver(x, left_arr,right_arr, time)
if path is not None:
print("Olası yol: ",path)
break
else:
continue
if __name__ == '__main__':
main() |
868b9cdbe7cf261dc560b8476a6bf146d9d7078a | Oleg2394/python-fofanov | /4. Функции и модули/3. Основы функций/3. Основы функций.py | 2,201 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def greeting():
print("Hello!")
# In[2]:
greeting()
# In[3]:
greeting
# In[4]:
help(greeting)
# In[ ]:
# In[5]:
def greeting():
"""
Документация на функцию:
Input: Входные данные
Output: Выходные данные
"""
print("Hello!")
# In[6]:
help(greeting)
# In[ ]:
# In[7]:
def print_name(name): # Функция с аргументом
print(name)
# In[8]:
print_name("Oleg")
# In[9]:
print_name()
# In[ ]:
# In[10]:
def print_name(name="Default"): # Функция с аргументом и значением по умолчанию
print(name)
# In[11]:
print_name()
# In[ ]:
# In[12]:
result = print_name()
print(result)
print(type(result))
# In[ ]:
# In[13]:
def get_greting(name): # Функция с аргументом и возвращаемым значением
return "Hello " + name
gre = get_greting("Oleg")
gre
# In[14]:
def get_sum(a,b):
return a + b
result = get_sum(10,2)
result
# In[15]:
def is_adult(age):
return age >=18
is_adu = is_adult(20)
is_adu
# In[16]:
def is_palindrome(text):
return text == text[::-1]
print(is_palindrome("aabaa"))
print(is_palindrome("aabba"))
# In[ ]:
# In[17]:
def cals_taxes(p1,p2,p3):
return sum((p1,p2,p3) * 0.06
# In[18]:
cals_taxes(10,20,30)
# In[20]:
def cals_taxes(p1,p2,p3,p4):
return sum((p1,p2,p3,p4)) * 0.06
# In[21]:
cals_taxes(10,20,30,40)
# In[ ]:
# In[22]:
def cals_taxes(*args): # *args любое количество аргументов
for x in args:
print(f"Got payment = {x}")
return sum(args) * 0.06
# In[24]:
cals_taxes(10,20,30,40)
# In[ ]:
# In[28]:
def save_players(**kwargs): # *kwargs любое количество аргументов пара ключ значение (словарь)
for k, v in kwargs.items():
print(f"Players {k} has rating {v}")
save_players(Carlsen=2800, Giri=2780)
# In[ ]:
# In[ ]:
# def func_important(a,b,c,d, *args, **kwargs)
|
7f4a54a8207ffd7dbec485df556ee71e4c277212 | omer358/codewars-challenges | /SumOfPairs.py | 238 | 3.90625 | 4 | def sum_pairs(nums, sum_value):
seen = set()
for num in nums:
diff = sum_value - num
if diff in seen:
return [diff, num]
seen.add(num)
print(seen)
print(sum_pairs([5, 9, 13, -3], 10))
|
ff95cc34ffa170db1a2b9612f95006a96bbf8832 | AparnaVB/Python | /Algorithms/PowerFunctionRecursive.py | 363 | 4 | 4 | def power(val, num):
if num == 0:
print("returning 1")
return 1
elif num % 2 == 0:
temp = power(val, num//2)
return temp * temp
elif num < 0:
return 1/power(val, -num)
elif num % 2 != 0:
return val * power(val, num-1)
print(power(10, 4))
print(power(3, 3))
print(power(3, -3))
print(power(2, 0))
|
4a3603bf04adc2c6c73c13718202d65267158174 | PollyIva/personalrep | /3sem/sc/task1_2.py | 946 | 3.796875 | 4 | #!/usr/bin/env python3
import argparse
import os
import random
parser = argparse.ArgumentParser(prog='password generator')
parser.add_argument('-l', '--length', action='store_true', default=False, help='length of the password')
parser.add_argument('len', type=int, nargs = '?', default=8, help='length of the password')
parser.add_argument('-ss', '--skip_symbols', action='store_true', default=False, help='skips signs in a password')
parser.add_argument('-sn', '--skip_numbers', action='store_true', default=False, help='skips digits in a password')
def generate(l, s, n):
st = ''
st1 = ''
for i in range(l):
if n:
st1 += str(random.randint(0,9))
if s:
st1 += random.choice("!_'/:;+=-$#@%")
st1 += chr(random.randint(ord('A'),ord('Z')))
st1 += chr(random.randint(ord('a'),ord('z')))
st = st + random.choice(st1)
print(st);
args = parser.parse_args()
a = args.len
generate(a, not args.skip_symbols, not args.skip_numbers)
|
8c61774bec3ea9612d2f6b54f8ef49a3073e4554 | ruanmarcoss/TrabalhosPython | /17-Aula17/Aula17.py | 575 | 4.03125 | 4 | # Aula 17 02/12/2019
# Dicionário, While
# bole = True
n = 0
# while n >= 30:
# n = n +1
# print(f'Fala tropinha {n}')
# while False:
# n = n +1
# print(f'Fala tropinha {n}')
# while n <= 30:
# n = n +1
# print(f'Fala tropinha {n}')
# break
# print(f'Passou!')
# while n <= 30:
# n = n +1
# print(f'Fala tropinha {n}')
# continue # Linhas abaixo da função não serão executados
# print(f'Passou!')
while n <= 30:
n = n +1
print(f'Fala tropinha {n}')
if n == 10:
continue
print(f'Passou!')
|
f6240dffc780184c3ed753e53fa47ca532e0a0f2 | nyu-cds/cn1036_assignment3 | /binary.py | 943 | 3.734375 | 4 | from itertools import permutations
def zbits(n, k):
"""
The function prints all binary strings of length n that contain k zero bits.
"""
try:
# check arguments #
if type(n)!=int or type(k)!=int:
raise Exception("Error: n,k should be integers.")
elif n<k:
raise Exception("Error: n should be greater than k.")
else:
string = "0"*k + "1"*(n-k)
# generate qualified strings using itertools.permutations #
qualified_str = set()
for i in permutations(string, n):
qualified_str.add(''.join(i))
print(qualified_str)
return qualified_str
except Exception as e:
print(e)
# test #
#assert zbits(4, 3) == {'0100', '0001', '0010', '1000'}
#assert zbits(4, 1) == {'0111', '1011', '1101', '1110'}
#assert zbits(5, 4) == {'00001', '00100', '01000', '10000', '00010'} |
de66adf3d60a8ea0a0ad34a7cf5c74f511124a34 | sayalisathe28/Python | /Day01Demos/StringDemo1.py | 840 | 3.8125 | 4 | #!c:\python27
"""
String objects in python
"""
s1='A"BC'
print "S1 = ",s1 #A"BC
s2="x'yz"
print "S2 = ",s2 #x'yz
#s3='A'BC' #SyntaxError
#s33="A"BC" #SyntaxError
s3='A\'BC'
print "S3 = ",s3 #A'BC
#s4="A\"BC"
#print "S4 = ",s4 #A"BC
s4=""" A'B"C """
print "S4 = ",s4 #A'B"C
s5=""" Welcome
to
Pune"""
print "S5 = ",s5
path1="c:\new\test.txt"
print "Path1 = ",path1
path1="c:\\new\\test.txt"
print "Path1 = ",path1 #c:\new\test.txt
#raw string definition in Python
path2 = r"c:\new\test.txt" #or R'string text'
print "Path2 = ",path2 #c:\new\test.txt
s1="ABC"
print "Type of s1 = ",type(s1) #<type 'str'>
print "------------------------"
num1=100
print "Type of num1 = ",type(num1) #<type 'int'>
pi=3.14
print "Type of pi = ",type(pi) #<type 'float'>
|
d732c55c2db6f2c60b90710f49acb083e0141025 | mcflurryXD96/Week-Two-Assignment | /default.py | 566 | 4.4375 | 4 | # Default shell for a Python 3.x program
# Copy this and rename it to write your own code
#
__author__ = 'Your Name'
# Your class
# Name of program
#
# Brief description of what program does.
# Declare Magic Numbers and Constants
# LOOPCOUNTER = 2
# name = "bob"
# Write program code here
# ask user for a temp in Fahrenheit
# Convert to Celsius
# (F-32) * 5 / 9
# Output answer to user
# Input
F = eval(input("Please enter a temp in Fahrenheit: "))
C = (F-32) * 5 / 9
print("The temp ", F, " in Fahrenheit is equal to ", C, " Celsius")
# Process
# Output |
7451b1cbce812efed5d2232ef9c70e1d99a921f7 | A1LabTeam/lab1 | /src/main.py | 3,339 | 3.609375 | 4 | from enum import Enum
class Location(Enum):
A = "a"
B = "b"
C = "c"
def success(rule):
print("[+] " + rule + " success")
def fail(rule):
print("[-] " + rule + " fail")
class State:
def __init__(self, M, B, Box, On, success):
self.M = M;
self.B = B;
self.Box = Box;
self.On = On;
self.success = success;
def summary(self) -> str:
condition = "(" + self.M.value + "," + self.B.value + "," + self.Box.value + "," + self.On.__str__() + "," + self.success.__str__() + ")"
return condition
# 猴子从state.M 移动到w
def r1(self, w):
currSummary = self.summary()
if self.On != False or self.success != False:
fail("r1")
else:
self.M = w
success("r1")
afterSummary = self.summary()
print("from" + currSummary + "to" + afterSummary)
# 猴子将state.M==state.Box 移动到z
def r2(self, z):
currSummary = self.summary()
if self.M != self.Box or self.On != False or self.success != False:
fail("r2")
else:
self.M = z
self.Box = z
success("r2")
afterSummary = self.summary()
print("from" + currSummary + "to" + afterSummary)
# 猴子站上箱子
def r3(self):
currSummary = self.summary()
if self.M != self.Box or self.On != False or self.success != False:
fail("r3")
else:
self.On = True
success("r3")
afterSummary = self.summary()
print("from" + currSummary + "to" + afterSummary)
# 猴子从箱子上下来
def r4(self):
currSummary = self.summary()
if self.M != self.Box or self.On != True or self.success != False:
fail("r4")
else:
self.On = False
success("r4")
afterSummary = self.summary()
print("from" + currSummary + "to" + afterSummary)
# 猴子拿到香蕉
def r5(self):
currSummary = self.summary()
if self.M != self.Box or self.M != self.B or self.On != True or self.success != False:
fail("r5")
else:
self.success = True
success("r5")
afterSummary = self.summary()
print("from" + currSummary + "to" + afterSummary)
# run
def run(self):
if self.M != self.Box and self.On == True:
print("init failed")
return
elif self.M != self.Box and self.On == False:
self.r1(self.Box)
self.run()
elif self.On == True:
if self.M == self.B:
self.r5()
else:
self.r4()
self.r2(self.B)
self.r3()
self.r5()
else:
if self.M == self.B:
self.r3()
self.r5()
else:
self.r2(self.B)
self.r3()
self.r5()
if __name__ == "__main__":
# (monkey,香蕉,box,onbox??,get香蕉??)
state = State(Location.C, Location.A, Location.C, True, False)
state.run()
# state.r1(Location.B)
# state.r2(Location.C)
# state.r3()
# state.r5()
if state.success:
print("The monkey succeeded in getting the banana!")
|
e02b9c431f3dde041284e9b92a0fcf7dbf2a8377 | dhylands/upy-examples | /colors.py | 338 | 3.875 | 4 | # Example which shows using ANSI color codes to print color to the terminal
# window.
def color(this_color, string):
return "\033[" + this_color + "m" + string + "\033[0m"
for i in range(30, 38):
c = str(i)
print('This is %s' % color(c, 'color ' + c))
c = '1;' + str(i)
print('This is %s' % color(c, 'color ' + c))
|
3fc75a380e1e1944708a5fdee03b15c2f917132d | nearhope/nearhope.github.io | /python/scrapeJackRipper.py | 2,021 | 3.703125 | 4 | from bs4 import BeautifulSoup
from urllib import request
# url = "https://stackoverflow.com/questions/tagged/python"
#
# print(url)
#
# html = request.urlopen(url).read()
# print()
#
# soup = BeautifulSoup(html, 'lxml')
# # parses the link
# htmlLinks=(soup.select('h3 a.question-hyperlink'))[0:10]
# urls=[]
# #makes it a url and stores in a list
# for link in htmlLinks:
# url="https://stackoverflow.com" + link['href']
# urls.append(url)
# # prints list of urls
# for link in urls:
# print(link)
#
# corpusTexts = []
# for url in urls:
# print(url)
# html = request.urlopen(url).read()
# soup = BeautifulSoup(html, "lxml")
# text = soup.text#.replace('\n', '')
# corpusTexts.append(text)
#
# print(corpusTexts)
#.....................
#try scraping NYTimes arts page
#
url = "https://www.nytimes.com/section/arts/design?action=click&contentCollection=arts®ion=navbar&module=collectionsnav&pagetype=sectionfront&pgtype=sectionfront"
print(url)
html = request.urlopen(url).read()
print()
soup = BeautifulSoup(html, 'lxml')
# parses the link
htmlLinks=(soup.select('div a.story-link'))[0:10]
urls=[]
#makes it a url and stores in a list
for link in htmlLinks:
url=link['href']
urls.append(url)
# prints list of urls
#for link in urls:
#print(link)
headlines=[]
for item in soup.find_all('h2')[6:17]:
headlines.append(item.text.replace('\n', ''))
# print('=======')
# print(item.text.replace('\n', ''))
for line in headlines:
print(line)
print("=======")
#
# corpusTexts = []
# for url in urls:
# # print(url)
# html = request.urlopen(url).read()
# soup = BeautifulSoup(html, "lxml")
# textBodies = soup.find_all('div', class_='css-18sbwfn')
# # headlines = soup.find_all(div', class_=" ")
# for textBody in textBodies:
# corpusTexts.append(textBody.text)
# print(htmlLinks)
# print(corpusTexts)
# articles={headlines:corpusTexts}
#
# for header, body in articles.items():
# print(header)
|
1c6c455ad661faa26654af2003325d85aa704e83 | PatrikTrefil/dmenu-vcard-old | /person.py | 523 | 3.546875 | 4 | #!/usr/bin/env python3
"""Module that defines the Person class"""
import unidecode
class Person:
def __init__(self, first_name: str, last_name: str, email: dict, phone: dict, birthday: str):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.phone = phone
self.birthday = birthday
def get_name(self):
return self.first_name + " " + self.last_name
def get_unaccented_name(self):
return unidecode.unidecode(self.get_name())
|
082c151f261527def497d935602d51b74ba46cae | richaraf/Comphys_projects | /Project_5/kristiansen.py | 4,085 | 3.515625 | 4 | import numpy as np
import sys
class System:
def __init__(self, Nparticles, Ndimensions, stepLength, alpha, beta, omega, numberOfMetropolisSteps):
self.Nparticles = Nparticles
self.Ndimensions = Ndimensions
self.stepLength = stepLength
self.alpha = alpha
self.beta = beta
self.particles = self.setInitialState()
self.numberOfMetropolisSteps = numberOfMetropolisSteps
self.omega = omega
self.WaveFunction = TrialWaveFunctionTwoParticles(self.omega)
def setInitialState(self):
particles = []
for i in range(0,self.Nparticles):
particle_i = Particle()
r_init = np.zeros(self.Ndimensions)
for j in range(0,self.Ndimensions):
r_init[j] = 2.0*np.random.uniform(0,1) - 1.0 #Draw random number between -1 and 1
particle_i.setPosition(r_init)
particles.append(particle_i)
return particles
def runMetropolisSteps(self):
nrOfAcceptedSteps = 0
accumulatedEnergy = self.computeLocalEnergy()
for i in range(0,self.numberOfMetropolisSteps):
accepted = self.metropolisStep() #Do a metropolisStep
#Sample stuff
if(accepted):
nrOfAcceptedSteps += 1
accumulatedEnergy += self.computeLocalEnergy()
else:
accumulatedEnergy += self.computeLocalEnergy()
print nrOfAcceptedSteps/float(self.numberOfMetropolisSteps), accumulatedEnergy/(self.numberOfMetropolisSteps+1)
def metropolisStep(self):
#Here you should implement the Metropolis Algorithm
#Compute probability at current position
PR = self.computeProbability()
#Change the position of a random particle at random dimension
random_particle = np.random.randint(0,self.Nparticles)
random_dimension = np.random.randint(0,self.Ndimensions)
change = 2.0*np.random.uniform(0,1) - 1.0
self.particles[random_particle].adjustPosition(change*self.stepLength,random_dimension)
#Compute probability at proposed position
PR_new = self.computeProbability()
w = PR_new/PR
if(w >= np.random.uniform(0,1)):
#Accept
return True
else:
#Reject step and reset position
self.particles[random_particle].adjustPosition(-change*self.stepLength,random_dimension)
return False
def computeProbability(self):
#Compute |psi_T|^2
def computeLocalEnergy(self):
#Here you want to compute the local energy using the analytical expression you derive in
#exercise 5b.
class TrialWaveFunctionTwoParticles:
def __init__(self, omega, alpha):
self.omega = omega
self.alpha = alpha
def evaluate(self, r1, r2, alpha):
#Evaluate the trial wavefunction
def evaluateLaplacian(self,r1,r2,alpha):
#Here you should implement the anlytical expression of the laplacian of the trial wavefunction
#At a later stage you should also include the possibility of evaluating the wavefunction and its laplacian with
#jastrow factor
class Particle:
def __init__(self, dimension=3):
self.position = np.zeros(dimension) #position[0] = x, position[1] = y, ...
def setPosition(self, pos):
for i in range(0,len(pos)):
self.position[i] = pos[i]
def adjustPosition(self, change, whichDim):
self.position[whichDim] += change
def getPosition(self):
return self.position
#Nparticles = 2
#Ndimensions = 3
#stepLength = ...
#alpha = ...
#beta = ...
#numberOfMetropolisSteps = int(1e5)
#omega = 1.0
#system_test = System(Nparticles,Ndimensions,stepLength,alpha,beta,omega, numberOfMetropolisSteps)
#system_test.runMetropolisSteps()
|
eb85b3b6112704e2c582a1ec9ed09ba755908c77 | baeksw/swkits | /snippets/click_001/os_check.py | 535 | 3.625 | 4 | import os
import platform
from enum import Enum
class OS_Type(Enum):
WINDOWS = 100
LINUX = 200
MAC = 300
UNKNOWN = 400
def check_os_type():
osType = OS_Type.UNKNOWN
os_name = platform.system()
if os_name:
name = os_name.lower()
if 'linux' in name:
osType = OS_Type.LINUX
elif 'windows' in name:
osType = OS_Type.WINDOWS
elif 'darwin' in name:
osType = OS_Type.MAC
return osType
OS_TYPE = check_os_type()
|
b6dac43f31b055db430bda020b3e158828e8a267 | thatguysilver/pswaads | /binary_converter.py | 680 | 3.703125 | 4 | import sys
from stack import Stack
def base_converter(dec_num, base):
digits = '012356789ABCDEF'
remainder_stack = Stack()
while dec_num > 0:
remainder = dec_num % base
remainder_stack.push(remainder)
dec_num = dec_num // base
new_string = ''
while not remainder_stack.is_empty():
new_string = new_string + digits[remainder_stack.pop()]
return new_string
try:
if len(sys.argv) > 1:
print(base_converter(int(sys.argv[1]), int(sys.argv[2])))
else:
print('You need to type something.')
except ValueError:
print('Not a base 10 integer, dipshit.')
#WAAAAY simpler than you'd expect.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.