blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2b5bafb5e471328a715ee74006e62b9c00f5bfc3 | gjxfree/python | /code/code_2.3.py | 192 | 4.21875 | 4 | # 将”to be or not to be”字符串倒序输出
word = 'to be or not to be'
new_word = []
i = len(word)
while i:
i -= 1
new_word.append(word[i])
print(''.join(new_word)) |
d1a8ac3b20b646e4ecde7d010ce5e67efed1e10d | karbekk/Python_Data_Structures | /Interview/Python_Excercises/Error_Handling_Exceptions/raise.py | 4,987 | 3.984375 | 4 | How do I manually throw/raise an exception in Python?
Use the most specific Exception constructor that semantically fits your issue.
Be specific in your message, e.g.:
raise ValueError('A very specific bad thing happened')
Don't do this:
Avoid raising a generic Exception, to catch it, you'll have to catch all other more specific exceptions that subclass it.
Hiding bugs
raise Exception('I know Python!') # don't, if you catch, likely to hide bugs.
For example:
def demo_bad_catch():
try:
raise ValueError('represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('caught this error: ' + repr(error))
>>> demo_bad_catch()
caught this error: ValueError('represents a hidden bug, do not catch this',)
Won't catch
and more specific catches won't catch the general exception:
def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch e')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
Best Practice:
Instead, use the most specific Exception constructor that semantically fits your issue.
raise ValueError('A very specific bad thing happened')
which also handily allows an arbitrary number of arguments to be passed to the constructor. This works in Python 2 and 3.
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
These arguments are accessed by the args attribute on the Exception object. For example:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
prints
('message', 'foo', 'bar', 'baz')
In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.
When in except clause
When inside an except clause, you might want to, e.g. log that a specific type of error happened, and then reraise. The best way to do this while preserving the stack trace is to use a bare raise statement, e.g.:
try:
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone, prefer to use a bare raise to reraise. This is the syntax in Python 2:
raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
In Python 3:
raise error.with_traceback(sys.exc_info()[2])
Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)
Python 3, Exception chaining
In Python 3, you can chain Exceptions, which preserve tracebacks:
raise RuntimeError('specific message') from error
But beware, this does change the error type raised.
Deprecated Methods:
These can easily hide and even get into production code. You want to raise an exception/error, and doing them will raise an error, but not the one intended!
Valid in Python 2, but not in Python 3 is the following:
raise ValueError, 'message' # Don't do this, it's deprecated!
Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:
raise 'message' # really really wrong. don't do this.
In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.
Example Usage:
I raise Exceptions to warn consumers of my API if they're using it incorrectly:
def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
Create your own error types when apropos:
"I want to make an error on purpose, so that it would go into the except"
You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
and usage:
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.') |
49aa08d196e1fce7c58fcce097ba842bfff34bef | ngonzo95/BarrenLandAnalysis | /BarrenLandAnalysis/model/field.py | 883 | 3.640625 | 4 | from shapely.geometry import box, Polygon
class Field:
"""
Represents a field using a shapely polygon.
"""
def __init__(self, len, width):
self._fieldPolygon = box(0, 0, len, width)
def area(self):
"""
Returns a list representing the area of the feild. If the feild has
been seperated into two sperate areas the list will have a size of 2
"""
if isinstance(self._fieldPolygon, Polygon):
return [self._fieldPolygon.area]
fieldAreas = []
for field in self._fieldPolygon:
fieldAreas.append(field.area)
fieldAreas.sort()
return fieldAreas
def removeBarrenArea(self, barrenField):
"""
Removes a part of the feild that is not to be included in the field
"""
self._fieldPolygon = self._fieldPolygon.difference(barrenField)
|
867c5455bd9e543f7fa299ddcd47e2953bafbe59 | TungstenRain/Python-turtle_attempt | /polygon_turtle.py | 2,016 | 4.25 | 4 | """
This module contains code from
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Chapter 4: Case Study in Think Python 2
Note: Although this is saved in a .py file, code was run on an interpreter to get results
Note: Using Python 3.8.5
"""
import math
import turtle
def square(t, length):
"""
Draws a square with sides of the given length.
Returns the Turtle to the starting position and location.
"""
for i in range(4):
fd(t, length)
lt(t)
def polyline(t, n, length, angle):
"""
Draws n line segments.
t: Turtle object
n: number of line segments
length: length of each segment
angle: degrees between segments
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def polygon(t, n, length):
"""
Draws a polygon with n sides.
t: Turtle
n: number of sides
length: length of each side.
"""
angle = 360.0/n
polyline(t, n, length, angle)
def arc(t, r, angle):
"""
Draws an arc with the given radius and angle.
t: Turtle
r: radius
angle: angle subtended by the arc, in degrees
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
# making a slight left turn before starting reduces the error caused by the linear approximation of the arc
t.lt(step_angle/2)
polyline(t, n, step_length, step_angle)
t.rt(step_angle/2)
def circle(t, r):
"""
Draws a circle with the given radius.
t: Turtle
r: radius
"""
arc(t, r, 360)
# Instantiate the Turtle
bob = turtle.Turtle()
"""
square(bob, 40)
polygon(bob, 200, 5)
polygon(bob, 100, 6)
polygon(bob, 50, 8)
polygon(bob, 25, 10)
circle(bob, 50)
circle(bob, 25)
"""
arc(bob, 40, 90)
turtle.mainloop() |
95f62cf82684a60b5a6b8b580a59001aea328130 | ChangxingJiang/LeetCode | /0101-0200/0109/0109_Python_2.py | 972 | 3.6875 | 4 | from toolkit import ListNode
from toolkit import TreeNode
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
# 异常情况处理
if not head:
return None
# 二分处理
values = []
while head:
values.append(head.val)
head = head.next
print(values)
# 定义递归函数
def helper(vals):
# 边界处理
if len(vals) == 0:
return None
if len(vals) == 1:
return TreeNode(vals[0])
# 二分处理
mid = len(vals) // 2
tree = TreeNode(vals[mid])
tree.left = helper(vals[:mid])
tree.right = helper(vals[mid + 1:])
return tree
# 递归得到结果
return helper(values)
if __name__ == "__main__":
# [0,-3,9,-10,None,5]
print(Solution().sortedListToBST(ListNode([-10, -3, 0, 5, 9])))
|
e6e241487186b62a9aaa63ee0218dc994ee8fcaa | chidamodu/SQL | /SQL _ assessment _ VR-AR_revision.ipynb | 4,019 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
SQL exercises
Table: email_events
Columns: user_id, event, campaign, date
Example: dan, open, quest, 2019-07-01
Question #1: Write a query that accomplishes the following: return a list of email campaigns run during June 2019 and the number of opens per campaign
Quest 1,000
Go 800
Rift 600
Questions I could asked:
get_ipython().set_next_input('Are there null values in the table');get_ipython().run_line_magic('pinfo', 'table')
Are there duplicate values in the table? (meaning: emails sent to the same customer, so there will be duplicate values)
Pseudo:
1. First filter records by June 2019
2. Then filter only the opened ones out of the first step
3. Count per campaign
4. is it possible that emails were sent to a same customer more than one time?
select campaign, count(event) AS event_count
from email_events
where event LIKE '%open%'
groupby campaign;
Select count(event) AS event_num
from
(
Select *
from email_events
where MONTH(date)=6
#YEAR(date)='2019'#quest is only released in 2019 so this is not necessary
)
where event like '%open%'
groupby campaign;
If there are duplicate values then can groupby userid as well, but this entirely depends on the context. Maybe it is compeltely ok to target the same customers many times a month.
get_ipython().set_next_input('Why not');get_ipython().run_line_magic('pinfo', 'not')
select campaign, count(*) AS num_open
from email_events
where event="open" and MONTH(date)=6
group by campaign;
# In[ ]:
# In[ ]:
Question #2: write a query that returns the campaigns that had the most clicks among women age 20-29
Table #2: user_info
Columns: user_id, age, gender
Example: dan, 30, male
I did not even realize that I had join the tables: email_events and user_info for the Question #2
1.
select * from email_events e
inner join
select * from user_info u
on e.user_id=u.user_id
At the end of step 1: I will have the columns as: user_id, event, campaign, date, age, gender
2.
select fog.campaign AS campaign_det, count(fog.event) AS num_event, fog.age AS age_det
from
(
select * from email_events e
inner join
select * from user_info u
on e.user_id=u.user_id
) fog
where fog.event like '%clicks%' AND fog.gender like '%female%'
groupby campaign_det;
3. Final query output
select rain.campaign_det AS campaign, rain.num_event AS event_count
from
(
select fog.campaign AS campaign_det, count(fog.event) AS num_event, fog.age AS age_det
from
(
select * from email_events e
inner join
select * from user_info u
on e.user_id=u.user_id
) fog
where fog.event like '%clicks%' AND fog.gender like '%female%'
groupby campaign_det
) rain
where rain.age_det BETWEEN 20 AND 29
order by num_event DESC;
Output:
campaign | event_count
---------------------------------------------------------------------------------------------------------------------
this is all I did at the collaborative assessment:
select * from user_info
where age (BETWEEN 20 AND 29) AND gender LIKE '%women%'
# In[ ]:
1.
select * from email_events e
join
user_info u
on e.userid=u.userid
2.
select fog.campaign as campaign_name, COUNT(*) AS num_clicks
(
select * from email_events e
join
user_info u
on e.userid=u.userid
) fog
where fog.gender='female' and fog.age BETWEEN 20 and 29
group by fog.campaign
order by num_clicks DESC
LIMIT 1;
# In[ ]:
optimization step
1. filter email_events
select e.user_id, e.event, e.campaign, e.date
from email_events e
where event="click";
2. filter user_info
select u.user_id, u.age, u.gender
from user_info u
where gender="female" and age BETWEEN 20 and 29;
3. join these two tables
select goat.campaign, COUNT(*) as number_clicks
(
select user_id, event, campaign, date
from email_events
where event="click"
) goat
JOIN
(
select user_id, age, gender
from user_info
where gender="female" and age BETWEEN 20 and 29;
) mountain
on goat.user_id=mountain.user_id
group by goat.campaign
order by number_clicks DESC
LIMIT 1;
|
47f48222eae9d146a75a4f67e31c19436045be66 | NickTrossa/Python | /programas/BatallaNaval/version2.7/batallanaval.py | 1,992 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 9 19:18:16 2014
@author: alumno
"""
import random
# Armo el tablero y lo muestro
tablero = []
for x in range(5):
tablero.append(["O"] * 5)
def print_tablero(tablero):
for fila in tablero:
print " ".join(fila)
print "Juguemos a la batalla naval!"
print_tablero(tablero)
def fila_aleatoria(tablero):
return random.randint(0,len(tablero)-1)
def columna_aleatoria(tablero):
return random.randint(0,len(tablero[0])-1)
barco_fila = fila_aleatoria(tablero)
barco_columna = columna_aleatoria(tablero)
#print 'El barco esta en fila %s y columna %s.' %(barco_fila,barco_columna)
#¡De acá en adelante todo debería ir en tu ciclo for!
#¡Asegurate de indentar!
turnos = 4
for turn in range(turnos):
if turn == 0:
print 'Tienes ' + str(turnos) + ' balas para hundir el barco.'
adivina_fila = input("Adivina fila: ")
adivina_columna = input("Adivina columna: ")
if adivina_fila == barco_fila + 1 and adivina_columna == barco_columna + 1:
print "Felicitaciones! Hundiste mi barco!"
break
else:
if (adivina_fila < 1 or adivina_fila > 5) or (adivina_columna < 1 or adivina_columna > 5):
print "Huy, eso ni siquiera esta en el oceano."
elif(tablero[adivina_fila - 1][adivina_columna - 1] == "X"):
print "Ya apuntaste a esa coordenada."
elif adivina_fila == '' or adivina_columna == '':
print "Debes escribir algo!"
else:
print "No tocaste mi barco, ¡soquete!"
tablero[adivina_fila - 1][adivina_columna - 1] = "X"
if turn == turnos-1:
print "GAME OVER LULA"
# ¡Mostrá (turno + 1) acá!
if turn < turnos-1:
print 'Te quedan ' + str(turnos-turn-1) + ' chances de acertar.'
print_tablero(tablero)
else:
print "Ya no te quedan disparos. Mira donde estaba el barco:"
tablero[barco_fila][barco_columna] = "@"
print_tablero(tablero)
|
90689ae35a3976095ac2b7a01452ebfa16dd7ef8 | granthoechst/124_pa3 | /plus_min_gen.py | 332 | 3.703125 | 4 | import numpy as np
import sys
# usage: python plus_min_gen.py n
def gen_plus_min():
plus_min_list = []
for i in range(0,100):
x = np.random.random_integers(0,1)
if x == 0:
plus_min_list.append(-1)
else:
plus_min_list.append(1)
return plus_min_list
print gen_plus_min()
|
883d3df76b00cc8ada27b9dfad5dfa5f68940fbd | matteosan1/python_code | /threading/threading.py | 6,180 | 3.703125 | 4 | import threading
class MyThread ( threading.Thread ):
def run ( self ):
print 'Insert some thread stuff here.'
print 'It'll be executed...yeah....'
print 'There's not much to it.'
import threading
class MyThread ( threading.thread ):
def run ( self ):
print 'You called my start method, yeah.'
print 'Were you expecting something amazing?'
MyThread().start()
import threading
theVar = 1
class MyThread ( threading.Thread ):
def run ( self ):
global theVar
print 'This is thread ' + str ( theVar ) + ' speaking.'
print 'Hello and good bye.'
theVar = theVar + 1
for x in xrange ( 20 ):
MyThread().start()
import pickle
import socket
import threading
# We'll pickle a list of numbers:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# Our thread class:
class ClientThread ( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__ ( self, channel, details ):
self.channel = channel
self.details = details
threading.Thread.__init__ ( self )
def run ( self ):
print 'Received connection:', self.details [ 0 ]
self.channel.send ( pickledList )
for x in xrange ( 10 ):
print self.channel.recv ( 1024 )
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
channel, details = server.accept()
ClientThread ( channel, details ).start()
import pickle
import socket
# Connect to the server:
client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
client.connect ( ( 'localhost', 2727 ) )
# Retrieve and unpickle the list object:
print pickle.loads ( client.recv ( 1024 ) )
# Send some messages:
for x in xrange ( 10 ):
client.send ( 'Hey. ' + str ( x ) + '\n' )
# Close the connection
client.close()
import pickle
import socket
import threading
# Here's our thread:
class ConnectionThread ( threading.Thread ):
def run ( self ):
# Connect to the server:
client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
client.connect ( ( 'localhost', 2727 ) )
# Retrieve and unpickle the list object:
print pickle.loads ( client.recv ( 1024 ) )
# Send some messages:
for x in xrange ( 10 ):
client.send ( 'Hey. ' + str ( x ) + '\n' )
# Close the connection
client.close()
# Let's spawn a few threads:
for x in xrange ( 5 ):
ConnectionThread().start()
import pickle
import Queue
import socket
import threading
# We'll pickle a list of numbers, yet again:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# A revised version of our thread class:
class ClientThread ( threading.Thread ):
# Note that we do not override Thread's __init__ method.
# The Queue module makes this not necessary.
def run ( self ):
# Have our thread serve "forever":
while True:
# Get a client out of the queue
client = clientPool.get()
# Check if we actually have an actual client in the client variable:
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
client [ 0 ].send ( pickledList )
for x in xrange ( 10 ):
print client [ 0 ].recv ( 1024 )
client [ 0 ].close()
print 'Closed connection:', client [ 1 ] [ 0 ]
# Create our Queue:
clientPool = Queue.Queue ( 0 )
# Start two threads:
for x in xrange ( 2 ):
ClientThread().start()
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
clientPool.put ( server.accept() )
import threading
class TestThread ( threading.Thread ):
def run ( self ):
print 'Hello, my name is', self.getName()
cazaril = TestThread()
cazaril.setName ( 'Cazaril' )
cazaril.start()
ista = TestThread()
ista.setName ( 'Ista' )
ista.start()
TestThread().start()
import threading
import time
class TestThread ( threading.Thread ):
def run ( self ):
print 'Patient: Doctor, am I going to die?'
class AnotherThread ( TestThread ):
def run ( self ):
TestThread.run( self )
time.sleep ( 10 )
dying = TestThread()
dying.start()
if dying.isAlive():
print 'Doctor: No.'
else:
print 'Doctor: Next!'
living = AnotherThread()
living.start()
if living.isAlive():
print 'Doctor: No.'
else:
print 'Doctor: Next!'
import threading
import time
class ThreadOne ( threading.Thread ):
def run ( self ):
print 'Thread', self.getName(), 'started.'
time.sleep ( 5 )
print 'Thread', self.getName(), 'ended.'
class ThreadTwo ( threading.Thread ):
def run ( self ):
print 'Thread', self.getName(), 'started.'
thingOne.join()
print 'Thread', self.getName(), 'ended.'
thingOne = ThreadOne()
thingOne.start()
thingTwo = ThreadTwo()
thingTwo.start()
import threading
import time
class DaemonThread ( threading.Thread ):
def run ( self ):
self.setDaemon ( True )
time.sleep ( 10 )
DaemonThread().start()
print 'Leaving.'
import thread
def thread( stuff ):
print "I'm a real boy!"
print stuff
thread.start_new_thread ( thread, ( 'Argument' ) )
|
4b9bbcd3960c4e0706ef9a0e0333352bdf28aa8a | CircularWorld/Python_exercise | /month_01/teacher/day16/exercise02.py | 706 | 3.96875 | 4 | """
迭代员工管理器
"""
class EmployeeIterator:
def __init__(self, data):
self.data = data
self.index = -1
def __next__(self):
self.index += 1
if self.index < len(self.data):
return self.data[self.index]
else:
raise StopIteration()
class EmployeeManager:
def __init__(self):
self.all_employee = []
def add_employee(self, emp):
self.all_employee.append(emp)
def __iter__(self):
return EmployeeIterator(self.all_employee)
manager = EmployeeManager()
manager.add_employee("老王")
manager.add_employee("老李")
manager.add_employee("老孙")
for item in manager:
print(item)
|
5e9c95d435af45e37963dcc92881805625e86b02 | krnets/codewars-practice | /6kyu/Transform To Prime/index.py | 1,907 | 4.34375 | 4 | # 6kyu - Transform To Prime
""" Given a List [] of n integers, find minimum mumber to be inserted in a list,
so that sum of all elements of list should equal the closest prime number.
List size is at least 2 .
List's numbers will only positives (n > 0).
Repeatition of numbers in the list could occur.
The newer list's sum should equal the closest prime number.
Input >> Output Examples
1- minimumNumber ({3,1,2}) ==> return (1)
Since, the sum of the list's elements equal to (6), the minimum number to be inserted to transform the sum to prime number is (1),
which will make *the sum of the List** equal the closest prime number (7)* .
2- minimumNumber ({2,12,8,4,6}) ==> return (5)
Since, the sum of the list's elements equal to (32), the minimum number to be inserted to transform the sum to prime number is (5),
which will make *the sum of the List** equal the closest prime number (37)* .
3- minimumNumber ({50,39,49,6,17,28}) ==> return (2)
Since, the sum of the list's elements equal to (189), the minimum number to be inserted to transform the sum to prime number is (2),
which will make *the sum of the List** equal the closest prime number (191)* . """
# def is_prime(n):
# return n > 1 and all(n % i for i in range(2, int(n ** .5) + 1))
def is_prime(n):
return n == 2 or n % 2 and all(n % i for i in range(3, int(n ** .5) + 1, 2))
def next_prime(n):
while not is_prime(n):
n += 1
return n
def minimum_number(numbers):
s = sum(numbers)
return 0 if is_prime(s) else next_prime(s) - s
# from sympy import *
# import sympy
# def minimum_number(numbers):
# s = sum(numbers)
# return sympy.isprime(5)
q = minimum_number([3, 1, 2]) # 1
q
q = minimum_number([5, 2]) # 0
q
q = minimum_number([1, 1, 1]) # 0
q
q = minimum_number([2, 12, 8, 4, 6]) # 5
q
q = minimum_number([50, 39, 49, 6, 17, 28]) # 2
q
|
3418e2d2e72413ad210f025e92b620ff1388822c | tehmasta/advent-of-code-2020 | /day_1/day1.py | 559 | 3.671875 | 4 | import math
from itertools import combinations
with open("puzzle_input.txt") as puzzle_input:
puzzle_input = [int(line.strip()) for line in puzzle_input]
num_entries = [2, 3]
def find_solution(puzzle_input, num_entries):
for potential_set in combinations(puzzle_input, num_entries):
if sum(potential_set) == 2020:
solution = math.prod(potential_set)
break
return solution
for idx, num in enumerate(num_entries):
solution = find_solution(puzzle_input, num)
print("Solution %i: %s" % (idx + 1, solution)) |
06a0adaca5b56f9f54dd3b8384f641366c1e6afc | cuqjc/curso_python | /second_hangman_.py | 3,203 | 3.765625 | 4 | import random
import os
def normalize(s):
replacements = (
("á", "a"),
("é", "e"),
("í", "i"),
("ó", "o"),
("ú", "u"),
)
for a, b in replacements:
s = s.replace(a, b).replace(a.upper(), b.upper())
return s
def run():
with open('./hangman/data.txt', 'r', encoding='utf-8') as data:
palabra = [line for line in data]
secreta = [letra for letra in random.choice(palabra)]
secreta.pop()
oculto = ['_' for _ in secreta]
secreta = normalize(''.join(secreta))
play(secreta, oculto)
def play(secreta, oculto):
winner = False
vidas = ['🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '💗', '💖']
ingreso = ''
bienvenida = 'Bienveido al juego del ahorcado!!!, tiene que adivinar la palabra antes de agotar las 20 vidas' \
' buena suerte 😎 😎 😎 !!!'
print(bienvenida)
# TRASNFORMO LA LISTA x EN UNA VARIABLE PARA QUE SEA MAS LEGIBLE
while winner is False and len(vidas) > 0:
contador = 0
print(''.join(oculto))
# MIENTRAS EL USUARIO NO SEA GANADOR Y TENGA VIDAS EJECUTAR
print('Letras ya ingresadas = ', ingreso)
# MOSTRAR LETRAS YA INGRESADAS
letra = input('Ingrese un letra = ')
# INGRESAR UNA LETRA
ingreso = str(ingreso) + str(letra) + ' - '
# GUARDAR LETRA EN UNA VARIABLE PARA QUE EL USUARIO NO LA VUELVA A INGRESAR
os.system('clear')
# LIMPIAR PANTALLA
if letra in secreta:
print('si esta\nVidas restantes = ', ''.join(vidas))
# SI LA LETRA SE ENCUENTRA EN LA PALABRA SECRETA MOSTRAR LAS VIDAS ACTUALES
for i in secreta:
# ANALIZAR LETRA POR LETRA DE LA PALABRA SECRETA
# TRANSFORMAR VARIABLE x EN UNA LISTA PARA PODER BORRAR Y AGREGAR NUEVOS CARACTERES
if letra == i:
oculto.pop(contador)
oculto.insert(contador, i)
# SI LA LETRA INGRESADA COINCIDE CON LA LETRA QUE SE ESTA ANALIZANDO EN EL FOR
# BORRAR '_' EN EL INDICE EN EL QUE SE ENCUETRA CON X.POP(INDICE)
# INSERTAR LETRA INGRESADA EN EL INDICE QUE CORRESPONDE
# TRANSFORMAR EL RESULTADO (UNA LISTA) A UNA VARIABLE
#
contador += 1
# AUMENTAR EL CONTADOR QUE REPRESENTA AL INDICE
else:
# TRASFORMO LA VARIABLE VIDA A UNA LISTA
vidas.pop()
# AHORA QUE ES UNA LISTA PUEDO BORRAR EL ULTIMO ELEMENTO
# Y VUELVO A TRANSFORMAR LA LISTA EN UNA VARIABLE PARA PODER VERLA MEJOR EN UN PRINT
print('No esta\nVidas restantes = ', ''.join(vidas))
if ''.join(oculto) == secreta:
winner = True
if winner:
print(f'Felicidades usted gano 👏👏👏👏\nLa palabra era {secreta}')
else:
print('Fin del juego 🤦️🤦️🤦️😨😭🤮🤡💀 la palabra secreta era = ', secreta)
print('PERDEDOR VUELVA A INTENTARLO DESPUES ...')
if __name__ == '__main__':
run()
|
7e8b60d060abfd81b030d1e2855f4ed016dc7ab7 | KaterynaShydlovska/python | /fundamentals/fundamentals/Students_and_Grades.py | 1,096 | 4.21875 | 4 |
length = int(input("How many students do you have?"))
listOfStudents = []
while length:
students = {}
name = input("Students name: ")
if not name:
print("Invalid name, try again..")
name = input("Students name: ")
students["Name"] = name
grade = input("Students garde: ")
while not grade.isnumeric():
print("Please enter the number")
grade = input("Students garde: ")
grade = int(grade)
students["Grade"] = grade
course = input("Select a course: 1 - Math, 2 - Science, 3 - History: ")
while not course.isnumeric():
print("Please enter the number")
course = input("Students garde: ")
course = int(course)
if course == 1:
students["Course"] = 'Math'
elif course == 2:
students["Course"] = 'Science'
elif course == 3:
students["Course"] = 'History'
else:
input("Try again")
listOfStudents.append(students)
length -=1
for el in listOfStudents:
a = str(el).replace("'", "").replace("{", "").replace("',", "").replace("}", "")
print(a) |
d816688d1dd993893769ffd8cb435565c842475c | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_02b-Revisao_Condicional/fabio_02b_02_fem_masc.py | 307 | 3.875 | 4 | def main():
sexo = input('Digite o sexo(F-Feminino || M-Masculino):')
if sexo == 'F' or sexo == 'f':
print('Sexo Feminino.')
elif sexo == 'M' or sexo == 'm':
print('Sexo Masculino.')
else:
print('Sexo Invalido.')
if __name__ == '__main__':
main()
|
6d044556688ac43c30646d6acebb2ddab75a64ee | CapaBE/Python | /ex3_HouseMaxSize.py | 1,923 | 4.09375 | 4 | class House:
"The house that can contain many rooms"
def __init__(self, available_space=100):
self.rooms = []
self.available_space = available_space
self.totalsize=0
def add_rooms(self, *room):
for item in room:
if self.size() + item.size > self.available_space:
raise NotEnoughSpaceError(f'There is not enough space in the house for the {item.name}, Available space: {self.available_space - self.totalsize} -- Space needed: {item.size} ')
else:
self.rooms.append(item)
self.totalsize += item.size
def size(self):
return sum(room.size for room in self.rooms)
def housesize(self):
return len(self.rooms)
#string representation of the house
def __str__(self):
return "House:\n" + "\n".join([str(room) for room in self.rooms])
class Room:
"The room class with it's attributes name and size."
def __init__(self, name, size):
self.name = name
self.size = size
#string representation of the class
def __str__(self):
#includes 2 placeholders
return "{}, {}m".format(self.name, self.size)
class NotEnoughSpaceError(Exception):
pass
# h = House(20)
# bedroom = Room('bedroom', 10)
# kitchen = Room('kitchen', 9)
# bathroom = Room('bathroom', 3)
# h.add_rooms(bedroom, kitchen, bathroom)
# print(h.size())
# print(str(h))
# h = House(100)
# bedroom = Room('bedroom', 80)
# kitchen = Room('kitchen', 15)
# bathroom = Room('bathroom', 30)
# cellar = Room('cellar', 10)
# h.add_rooms(bedroom)
# h.add_rooms(kitchen)
# h.add_rooms(bathroom, cellar)
# # h.add_rooms(bathroom, cellar)
# print(f'Size of the house : {h.size()} m')
# print(f'No. of rooms in the house : {h.housesize()}')
# print(f'max space : {h.available_space}')
# print(str(h))
|
41594f29b28316ed90bd8648ad947381a5fc96f3 | doubleLLL3/Leetcode-Exercise-Codes | /Array/onlyOne.py | 413 | 3.5 | 4 | # nums = [4,1,2,1,2]
# for i in range(len(nums)):
# check = nums.pop(0)
# if check in nums:
# nums.pop(nums.index(check))
# print(check)
# continue
# print(check)
from collections import defaultdict
nums = [4,1,2,1,2]
hash_table = defaultdict(int)
for i in nums:
hash_table[i] += 1
for i in hash_table:
if hash_table[i] == 1:
print(i)
|
147e99f32b430080412234ac9429c8a3cfa0a37d | lenapy/learn_urllib | /examples/basic.py | 1,083 | 3.703125 | 4 | import urllib.request
import urllib.parse
""" get request """
x = urllib.request.urlopen('https://www.google.com/')
# print(x.read())
""" post request, if we need to put some date to request, for example some search request """
url = 'http://www.pythonprogramming.net'
values = {'s': 'basic', 'submit': 'search'}
data = urllib.parse.urlencode(values)
data_enc = data.encode('utf-8')
req = urllib.request.Request(url, data_enc)
resp = urllib.request.urlopen(req)
resp_data = resp.read()
# print(resp_data)
""" post request with using 'User-Agent'"""
try:
url = 'http://google.com/search?q=python'
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) " \
"Chrome/24.0.1312.27 Safari/537.17"
new_req = urllib.request.Request(url, headers=headers)
new_resp = urllib.request.urlopen(new_req)
new_resp_data = new_resp.read()
save_file = open('data_from_google.txt', 'w')
save_file.write(str(new_resp_data))
save_file.close()
except Exception as e:
print(str(e))
|
77b842a8e509f69c52666f0742f61ab84e149db8 | 1050669722/LeetCode-Answers | /Python/problem0016.py | 2,304 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 17 10:34:43 2019
@author: Administrator
"""
class Solution():
def threeSumClosest(self, nums: list, target: int) -> int:
nums = self.merge_sort(nums)
closest= nums[0] + nums[1] + nums[2]
for k in range(len(nums)): #for在内部迭代出最近目标或直接找到目标返回,没有在内部返回,说明没有目标值,只能跳出,然后在外部返回最近目标
p = k + 1
q = len(nums) - 1
while p < q:
# if nums[k]+nums[p]+nums[q] < target: #
# if abs((nums[k]+nums[p]+nums[q])-target) < abs(closest-target):
# closest = nums[k]+nums[p]+nums[q]
# p += 1
# elif nums[k]+nums[p]+nums[q] > target:
# if abs((nums[k]+nums[p]+nums[q])-target) < abs(closest-target):
# closest = nums[k]+nums[p]+nums[q]
# q -= 1
# else:
# return closest
if abs((nums[k]+nums[p]+nums[q])-target) < abs(closest-target):
closest = nums[k]+nums[p]+nums[q]
if nums[k]+nums[p]+nums[q] < target:
p += 1
elif nums[k]+nums[p]+nums[q] > target:
q -= 1
else:
return nums[k]+nums[p]+nums[q]
return closest
def merge(self, left, right):
result = []
i, j = 0, 0
while i<len(left) and j<len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def merge_sort(self, List):
if len(List) <= 1:
return List
else:
num = len(List) // 2
left = self.merge_sort(List[:num])
right = self.merge_sort(List[num:])
return self.merge(left, right)
solu = Solution()
#nums, target = [-1, 2, 1, -4], 1
#nums, target = [0,2,1,-3], 1
nums, target = [1,1,-1,-1,3], 1
print(solu.threeSumClosest(nums, target))
print(solu.merge_sort(nums))
|
f956cb490adc7d1bdec931890ccdc0a5add56039 | bheki-maenetja/small-projects-py | /courses/8_things_you_must_know_in_python/Exercise Files/challenge/min_max_challenge.py | 1,164 | 4.03125 | 4 | import string
DICTIONARY = 'dictionary.txt'
letter_scores = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4,
'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3,
'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8,
'y': 4, 'z': 10
}
def get_scrabble_dictionary():
"""Helper function to return the words in DICTIONARY as a list"""
with open(DICTIONARY, 'rt', encoding='utf-8') as file:
content = file.read().splitlines()
return content
def score_word(word):
"""Return the score for a word using letter_scores.
If the word isn't in DICTIONARY, it gets a score of 0."""
pass # Replace this line with your solution
def remove_punctuation(word):
"""Helper function to remove punctuation from word"""
table = str.maketrans({char:None for char in word if char in string.punctuation})
return word.translate(table)
def get_word_largest_score(sentence):
"""Given a sentence, return the word in the sentence with the largest score."""
pass # Replace this line with your solution |
c98a308c1940331fd6670d1bebe62880da2e9fcc | pfpimenta/biocomp2019 | /lista3parte2/e3-2.py | 6,389 | 3.9375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# exercicio a da lista 3 parte 2 de Biologia Computacional
# Pedro Foletto Pimenta, outubro de 2019
###
import sys
# tree class
class Tree:
# initialization
def __init__(self):
self.left = None
self.right = None
self.left_dist = None
self.right_dist = None
# distance from this point to the leaves
def get_leaves_dist(self):
# if it is ultrametric, it does not matter if we check left or right
if(isinstance(self.left, Tree)):
return self.left_dist + self.left.get_leaves_dist()
else:
return self.left_dist
# printing function ( CALL THIS )
def print_tree(self):
self.print_subtree(self.right, 1, self.right_dist)
self.print_subtree(self.left, 1, self.left_dist)
# auxiliary printing function
def print_subtree(self, subtree, level, dist):
if(isinstance(subtree, Tree)):
print(level*' ' + '-')
self.print_subtree(subtree.left, level+1, subtree.left_dist)
print(level*' ' + level*'-' + str(dist) + level*'-')
self.print_subtree(subtree.right, level+1, subtree.right_dist)
print(level*' ' + '-')
elif(isinstance(subtree, str)):
print(2*level*' ' + level*' - '+str(dist)+ level*' - ' +'\t'+ subtree)
# returns the q_matrix generated from dist_matrix
# according to the neighbour joining algorithm
def get_q_matrix(dist_matrix, otu_list):
# dist_matrix : dicionario com as distancias entre as OTUs
# otu_list : lista das "OTUs" no passo atual ("clusters")
# q_matrix is a dict
q_matrix = {}
# create a q_matrix element for each dist_matrix element
for otu_pair in dist_matrix.keys():
# get otu pair
otu_a, otu_b = otu_pair
# sum of the distances for otu_a and otu_b
sum_a, sum_b = 0, 0
for otu in otu_list:
if(otu != otu_a):
sum_a = sum_a + dist_matrix[(otu_a, otu)]
if(otu != otu_b):
sum_b = sum_b + dist_matrix[(otu_b, otu)]
# q_matrix formula
q_matrix[otu_pair] = (len(otu_list) - 2) * dist_matrix[otu_pair] - sum_a - sum_b
return q_matrix
# returns dist_matrix with otu_a and otu_b fused into a new otu
def update_dist_matrix(dist_matrix, otu_list, otu_a, otu_b):
# dist_matrix : dicionario com as distancias entre as OTUs
# otu_list : lista das "OTUs" no passo atual ("clusters")
# otu_a, otu_b : OTUs a serem fusionadas em uma nova OTU
# add new otu
new_otu = otu_a + '-' + otu_b
for otu in otu_list:
if otu != otu_a and otu != otu_b:
new_dist = (dist_matrix[(otu, otu_a)] + dist_matrix[(otu, otu_b)] - dist_matrix[(otu_a, otu_b)])/2
new_key = (new_otu, otu)
dist_matrix[new_key] = new_dist
new_key = (otu, new_otu)
dist_matrix[new_key] = new_dist
# remove otu_a and otu_b
for otu in otu_list:
# remove otu_a distances
key = (otu, otu_a)
dist_matrix.pop(key, None)
key = (otu_a, otu)
dist_matrix.pop(key, None)
# remove otu_b distances
key = (otu, otu_b)
dist_matrix.pop(key, None)
key = (otu_b, otu)
dist_matrix.pop(key, None)
return dist_matrix
# Agglomerative methods for ultrametric trees (Neighbour Joining)
def neighbour_joining(dist_matrix):
# dist_matrix : dicionario com as distancias entre as OTUs
# inicializacao da lista de OTUs
otu_list = []
for key in dist_matrix:
if(key[0] not in otu_list):
otu_list.append(key[0])
if(key[1] not in otu_list):
otu_list.append(key[1])
# initialize tree clusters
tree_clusters = {}
for otu in otu_list:
tree_clusters[otu] = otu
# enquanto a arvore nao tiver completa
while(len(otu_list)>1):
# calcular matriz Q
q_matrix = get_q_matrix(dist_matrix, otu_list)
# find smallest distance for clustering
otu_a, otu_b = min(q_matrix, key=q_matrix.get)
# branch lenght estimation
sum_a, sum_b = 0, 0
for otu in otu_list:
if(otu != otu_a):
sum_a = sum_a + dist_matrix[(otu_a, otu)]
if(otu != otu_b):
sum_b = sum_b + dist_matrix[(otu_b, otu)]
branch_lenght_a = (dist_matrix[(otu_a, otu_b)])/2 + (1.0/(2*len(otu_list) - 2))*(sum_b - sum_a)
branch_lenght_b = (dist_matrix[(otu_a, otu_b)]) - branch_lenght_a
# versao com distancias arredondadas (mais paredida com a do wikipedia mas nao funciona para o nosso caso)
#branch_lenght_a = int(round( (dist_matrix[(otu_a, otu_b)])/2 + (1.0/(2*len(otu_list) - 2))*(sum_b - sum_a) ))
#branch_lenght_b = (dist_matrix[(otu_a, otu_b)]) - branch_lenght_a
# update distance matrix
dist_matrix = update_dist_matrix(dist_matrix, otu_list, otu_a, otu_b)
# update OTU list
new_otu = otu_a + '-' + otu_b
otu_list.append(new_otu)
otu_list.remove(otu_a)
otu_list.remove(otu_b)
# update tree : new tree node
new_tree_node = Tree()
new_tree_node.right = tree_clusters[otu_a]
new_tree_node.right_dist = branch_lenght_a
new_tree_node.left = tree_clusters[otu_b]
new_tree_node.left_dist = branch_lenght_b
# update tree clusters
tree_clusters.pop(otu_a)
tree_clusters.pop(otu_b)
tree_clusters[new_otu] = new_tree_node
# DEBUG
#print("DEBUG otu list: " + str(otu_list))
return tree_clusters[otu_list[0]]
# objetivos:
# - construcao de arvores filogeneticas
# - implementacao do metodo Agglomerative methods for ultrametric trees (UPGMA)
# matriz de distancias dos 5 primatas (Gorila, Orangotango, Humano, Chipanzé, Gibão):
# é um dict na real
dist_matrix = {}
#dist_matrix[('gor', 'gor')] = 0.0
dist_matrix[('gor', 'ora')] = 0.189
dist_matrix[('gor', 'hum')] = 0.11
dist_matrix[('gor', 'chi')] = 0.113
dist_matrix[('gor', 'gib')] = 0.215
dist_matrix[('ora', 'gor')] = 0.189
#dist_matrix[('ora', 'ora')] = 0.0
dist_matrix[('ora', 'hum')] = 0.179
dist_matrix[('ora', 'chi')] = 0.192
dist_matrix[('ora', 'gib')] = 0.211
dist_matrix[('hum', 'gor')] = 0.11
dist_matrix[('hum', 'ora')] = 0.179
#dist_matrix[('hum', 'hum')] = 0.0
dist_matrix[('hum', 'chi')] = 0.09405
dist_matrix[('hum', 'gib')] = 0.205
dist_matrix[('chi', 'gor')] = 0.113
dist_matrix[('chi', 'ora')] = 0.192
dist_matrix[('chi', 'hum')] = 0.09405
#dist_matrix[('chi', 'chi')] = 0.0
dist_matrix[('chi', 'gib')] = 0.214
dist_matrix[('gib', 'gor')] = 0.215
dist_matrix[('gib', 'ora')] = 0.211
dist_matrix[('gib', 'hum')] = 0.205
dist_matrix[('gib', 'chi')] = 0.214
#dist_matrix[('gib', 'gib')] = 0.0
# construcao de uma arvore ultrametrica filogenetica a partir da matriz de distancias usando UPGMA
tree = neighbour_joining(dist_matrix)
# printar resultados
print("printing resulting tree:")
tree.print_tree()
|
bcd88abcac9daaa4c7c0e11f08e2345d39bdd5bc | sebsanscartier/nhlstats | /Documents/test.py | 735 | 3.546875 | 4 | import requests
import json
headers = { 'Content-Type': 'application/json'}
def get_team_stats():
#fetches all the the team from the best team
api_url = 'https://statsapi.web.nhl.com/api/v1/teams?expand=team.stats'
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))
else:
return None
team_info = get_team_stats()
if team_info is not None:
print("Successfully created the .JSON file")
for team in team_info.items():
with open('all_team_info.json', 'w') as f:
print(json.dumps(team, indent=2), file=f)
else:
print('[!] Request Failed') |
ac2a502ce7300cd8ac00c77702b6e06341ba2d4e | sunnyyeti/Leetcode-solutions | /23 Merge k Sorted Lists.py | 1,559 | 4 | 4 | # You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
# Merge all the linked-lists into one sorted linked-list and return it.
# Example 1:
# Input: lists = [[1,4,5],[1,3,4],[2,6]]
# Output: [1,1,2,3,4,4,5,6]
# Explanation: The linked-lists are:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# merging them into one sorted list:
# 1->1->2->3->4->4->5->6
# Example 2:
# Input: lists = []
# Output: []
# Example 3:
# Input: lists = [[]]
# Output: []
# Constraints:
# k == lists.length
# 0 <= k <= 10^4
# 0 <= lists[i].length <= 500
# -10^4 <= lists[i][j] <= 10^4
# lists[i] is sorted in ascending order.
# The sum of lists[i].length won't exceed 10^4.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import heapq
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
ListNode.__lt__ = lambda self, other: self.val<other.val
k = len(lists)
if k==0:
return None
if k==1:
return lists[0]
head = ListNode(-1,None)
store = head
heap = [(ln.val,ln) for ln in lists if ln]
heapq.heapify(heap)
while heap:
cur_node_val, cur_node = heapq.heappop(heap)
head.next = cur_node
next_node = cur_node.next
if next_node:
heapq.heappush(heap,(next_node.val,next_node))
head = head.next
return store.next
|
35566557894c66eb2a39bf1cc18c6b244fea15af | tristenallgaier2023/bikers | /src/models.py | 945 | 3.953125 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Bike_Classifier(nn.Module):
"""
This class creates a neural network for classifying bikers as casual(0) or
member(1).
Network architecture:
- Input layer
- First hidden layer: fully connected layer of size 2 nodes
- Second hidden layer: fully connected layer of size 3 nodes
- Output layer: a linear layer with one node per class (so 2 nodes)
ReLU activation function for both hidden layers
"""
def __init__(self):
super(Bike_Classifier, self).__init__()
self.fc1 = nn.Linear(3, 2)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(2, 3)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(3, 2)
def forward(self, input):
x = self.fc1(input)
x = self.relu1(x)
x = self.fc2(x)
x = self.relu2(x)
x = self.fc3(x)
return x
|
b8470e288cba262e885c0c8dede2b83119b8e15f | ethanl2014/CSE-331-Projects | /CSE-331-Projects/Project3/proj3/Stack.py | 4,378 | 4.0625 | 4 | ###################################
# PROJECT 3 - STACK
# Author: Ethan Lee
# PID: A48941153
###################################
class Stack:
# DO NOT MODIFY THIS CLASS #
def __init__(self, capacity=2):
"""
Creates an empty Stack with a fixed capacity
:param capacity: Initial size of the stack.
"""
self._capacity = capacity
self._data = [0] * self._capacity
self._size = 0
def __str__(self):
"""
Prints the elements in the stack from bottom of the stack to top,
followed by the capacity.
:return: string
"""
if self._size == 0:
return "Empty Stack"
output = []
for i in range(self._size):
output.append(str(self._data[i]))
return "{} Capacity: {}".format(output, str(self._capacity))
###### COMPLETE THE FUNCTIONS BELOW ######
# --------------------Accessor Functions---------------------------------
def get_size(self):
'''
Gets the number of elements in the stack
:param none
:return: int of the size (number of elements) in the stack
'''
return self._size
def is_empty(self):
'''
Determines if the stack has elements in it
:param none
:return: bool, True if stack is empty, False if not
'''
if self._size == 0:
return True
return False
def top(self):
'''
Returns the most recently added element (the top) in the stack
:param none
:return: the last element pushed on the stack
'''
if self._size == 0:
return None
return self._data[self._size-1]
# ---------------------------Mutator Functions------------------------------
def push(self, addition):
'''
Calls the grow function to increase the stack size if necessary, then puts a new element
into the first empty space of the stack
:param addition: the element to push on to the stack
:return: none
'''
self.grow()
self._data[self._size] = addition
self._size = self._size + 1
def pop(self):
'''
Deletes and returns the top of the stack
:param none
:return: the top of the stack, or none if the stack is empty
'''
if self._size == 0:
return None
top_value = self._data[self._size-1]
self._size = self._size - 1
self.shrink()
return top_value
def grow(self):
'''
If the stack capacity is equal to its size, creates a list with double the capacity and copies the stack over
:param none
:return: none
'''
if self._size == self._capacity:
self._capacity = 2*self._capacity
B = [0] * self._capacity
for i in range(0,self._size):
B[i] = self._data[i]
self._data = B
def shrink(self):
'''
If the stack size is less than or equal to half its capacity, creates a list with half the capacity and copies
the stack over
:param none
:return: none
'''
if self._capacity//2 < 2:
pass
elif self._size <= self._capacity//2:
self._capacity = self._capacity//2
B = [0] * self._capacity
for i in range(0,self._size):
B[i] = self._data[i]
self._data = B
def Palindrome(phrase):
'''
Determines if a given phrase is a palindrome (same forwards as backwards) using the stack class
:param phrase: string whose palindrome status is in question
:return: bool, True if palindrome, False if not
'''
import string
phrase = "".join(char.lower() for char in phrase if (char in string.ascii_letters or char in string.digits))
#removes all punctuation and spaces from the phrase string and changes uppercase letters to lowercase
#imports and uses the string method function for ascii letters and digits
phrasestack = Stack()
for i in phrase:
phrasestack.push(i)
for i in phrase:
if i != phrasestack.pop():
return False
return True |
8e521e958ba014089a9cdcfaf8d715da9cd3a129 | EduardoSlonzo/python_project | /Exercicio_em_python/Numeros_pares.py | 330 | 3.8125 | 4 | n = int(input("Quantos numeros você vai digitar? "))
vet = [0 for x in range(n)]
for i in range(n):
vet[i] = int(input("Digite um numero: "))
pares = 0
print("\nNumeros pares")
for i in range(n):
if vet[i] % 2 == 0:
print(vet[i], end=" ")
pares = pares + 1
print(f"\n\nQuantidade de pares = {pares}") |
ac9a7487c26747b77dabb17f670540d940340979 | SapnaDeshmuk/list_questions_python | /split.py | 121 | 3.578125 | 4 | str2="sapna"
str2lst=list(str2)
print(str2lst)
stob1="hi hello welcome python is awesome"
stob2=stob1.split()
print stob2 |
00085e26d7077509a518417a29db42c4f6e2581a | SilasA/Random-Scripts | /defintegral.py | 681 | 3.984375 | 4 | # A simple script to find an estimate for the area under the curve
# f(x) on interval [x, y] with n number of rectangles with
# p end point
import math
def f(x):
return 15 / x # function here
def estimate(x, y, n, p):
rectWidth = (y - x) / n
itr = rectWidth * p + x
areaAccum = 0.0
for i in range(n):
areaAccum += rectWidth * f(itr)
itr += rectWidth
return areaAccum
x = float(input("Lower Bound: "))
y = float(input("Upper Bound: "))
n = int(input("Number of Rectangles: "))
print("Left endpoint")
print(estimate(x, y, n, 0))
print("Middle endpoint")
print(estimate(x, y, n, 0.5))
print("Right endpoint")
print(estimate(x, y, n, 1))
|
98337bd816547c7f24890aea931d168f79923156 | mertturkmenoglu/python-examples | /examples/old_examples/examples/exception_handling.py | 270 | 3.8125 | 4 | # Exception handling program
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
try:
for i in range(len(numbers)):
print(numbers[i])
# Throws error
print("11th element = %d" % (numbers[10]))
except IndexError:
print("Index Error. Check your index!!!")
|
c0d39b2bf9752f2e25e2de0cf3a930d6d065c35a | rafaelperazzo/programacao-web | /moodledata/vpl_data/25/usersdata/132/11936/submittedfiles/av1_3.py | 214 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a=input('digite o valor de a:')
b=input('digite o valor de b:')
i=a
while True:
if a%i==0 and b%i==0:
print(a)
break
i=i-1 |
69468fce187cecd3983adaa139aaf0784e4cbb2d | georgejordan3/learnpython3thehardway | /learnpython3thehardway/ex19.py | 1,444 | 4.4375 | 4 | # Uses the function def to define cheese_and_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# Formats cheese_count to the printed string
print(f"You have {cheese_count} cheeses!")
# Formats boxes_of_crackers to the printed string
print(f"You have {boxes_of_crackers} boxes of crackers!")
# Prints a string
print("Man that's enough for a party!")
# Prints a string and starts a new line
print("Get a blanket.\n")
# Demonstrates another method in a string
print("We can just give the function numbers directly:")
# Uses the function with the defined values for the variables and then prints
cheese_and_crackers(20, 30)
# Demonstrates another method in a string
print("OR, we can use variables from our script:")
# Provides a value for the variable
amount_of_cheese = 10
# Provides a value for the variable
amount_of_crackers = 50
# Prints the function with the defined values above
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# Demonstrates another method in a string
print("We can even do math inside too:")
# Prints the function with arithmetic in the values for the variables
cheese_and_crackers(10 + 20, 5 + 6)
# Demonstrates another method in a string
print("And we can combine the two, variables and math:")
# Prints the function with arithmetic and defined values above
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
|
3167f92859c3f0379ddfca007757f81311021532 | tonikarppi/yks | /yks.py | 2,011 | 4.34375 | 4 | def plus(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def minus(a, b):
"""
Returns the difference between a and b.
"""
return a - b
def times(a, b):
"""
Returns the product of a and b.
"""
return a * b
def divided_by(a, b):
"""
Returns the ratio of a to b.
"""
return a / b
def max_of(a, b):
"""
Returns the larger of the values a and b.
"""
if a >= b:
return a
return b
def max_in(values):
"""
Returns the largest value in `values`,
or `None` if the input list is empty.
"""
max_value = None
for v in values:
if max_value is None or v > max_value:
max_value = v
return max_value
def main(*args):
"""
Computes the result of applying two operands to an operator. The input to the
function is expected to be of form <operator> <num1> <num2>.
The possible values for the operators are 'add', 'subtract', 'multiply',
and 'divide'. This function returns a tuple (success, message), where success
is a boolean value indicating whether the function exited correctly.
"""
operators = {
"add": plus,
"subtract": minus,
"multiply": times,
"divide": divided_by,
}
error = False
try:
operator = args[0]
lhs = int(args[1])
rhs = int(args[2])
except (IndexError, ValueError):
error = True
if error or operator not in operators:
return False, "Expected: yks <add|subtract|multiply|divide> <num1> <num2>."
try:
result = operators[operator](lhs, rhs)
except ZeroDivisionError:
return False, "Division by zero encountered."
return True, str(result)
def console_run():
"""
Calls the main function with system args.
This function is meant to be called as an entrypoint script.
"""
import sys
success, message = main(*sys.argv[1:])
print(message)
sys.exit(0 if success else 1)
|
3a2b9bcf4f64d0cec913e75ee6d92d4ecdcb81a3 | komalkri-dev/character-o-graph | /A_to_J.py | 4,013 | 3.765625 | 4 | import turtle
def draw_A(offset):
a = turtle.Turtle()
a.speed(4)
a.color("yellow")
a.up()
a.forward(offset)
a.down()
a.left(73.5)
a.forward(72.1)
a.right(147)
a.forward(72.1)
a.backward(28)
a.right(106.5)
a.forward(25.9)
a.hideturtle()
def draw_B(offset):
# draw b shape
b = turtle.Turtle()
b.speed(4)
b.color("pink")
b.up()
b.forward(offset)
b.down()
b.left(90)
b.forward(70)
b.right(90)
b.forward(15)
for ba in range(18):
b.forward(3.15)
b.right(10)
b.forward(17)
b.right(180)
b.forward(17)
for ba in range(18):
b.forward(3.10)
b.right(10)
b.forward(22)
b.hideturtle()
def draw_C(offset):
# drawing alphabet c
c = turtle.Turtle()
c.speed(4)
c.color("cyan")
c.up()
c.forward(offset)
c.down()
c.left(90)
c.up()
c.forward(70)
c.right(90)
c.forward(42)
c.right(180)
# drawing starts here
c.down()
c.forward(11.5)
for ca in range(9):
c.forward(4.9)
c.left(10)
c.forward(14)
for ca in range(9):
c.forward(4.9)
c.left(10)
c.forward(15.4)
c.hideturtle()
def draw_D(offset):
# drawing alphabet d
d = turtle.Turtle()
d.speed(4)
d.color("white")
d.up()
d.forward(offset)
d.down()
d.left(90)
d.forward(70)
d.right(90)
d.forward(11.5)
for da in range(9):
d.forward(4.9)
d.right(10)
d.forward(13.9)
for da in range(9):
d.forward(5.04)
d.right(10)
d.forward(15.4)
d.hideturtle()
def draw_E(offset):
# drawing alphabet e
e = turtle.Turtle()
e.speed(4)
e.color("orange")
e.up()
e.forward(offset)
e.down()
e.left(90)
e.forward(70 )
e.right(90)
e.forward(38.5)
e.backward(38.5)
e.right(90)
e.forward(35)
e.left(90)
e.forward(31.5)
e.backward(31.5)
e.right(90)
e.forward(35)
e.left(90)
e.forward(42)
e.hideturtle()
def draw_F(offset):
# drawing alphabet f
f = turtle.Turtle()
f.speed(4)
f.color("lime")
f.up()
f.forward(offset)
f.down()
f.left(90)
f.forward(70)
f.right(90)
f.forward(42)
f.backward(42)
f.right(90)
f.forward(35)
f.left(90)
f.forward(35)
f.hideturtle()
def draw_G(offset):
g = turtle.Turtle()
g.speed(9)
g.color('pink')
g.up()
g.forward(offset)
g.down()
g.up()
g.left(90)
g.forward(70)
g.right(90)
g.forward(39.2)
g.right(90)
g.forward(3.5)
g.right(180)
g.down()
# start
g.left(40)
for ga in range(5):
g.forward(1.4)
g.left(10)
g.forward(14)
for ga in range(9):
g.forward(3.01)
g.left(10)
g.forward(35)
for ga in range(9):
g.forward(2.94)
g.left(10)
g.forward(7.7)
for ga in range(9):
g.forward(2.94)
g.left(10)
g.forward(17.5)
g.left(90)
g.forward(17.5)
g.hideturtle()
def draw_H(offset):
# drawing alphabet h
h = turtle.Turtle()
h.speed(4)
h.color("cyan")
h.up()
h.forward(offset)
h.down()
h.left(90)
h.forward(70)
h.backward(35)
h.right(90)
h.forward(42)
h.left(90)
h.forward(35)
h.backward(70)
h.hideturtle()
def draw_I(offset):
# drawing alphabet i
i = turtle.Turtle()
i.speed(4)
i.color("yellow")
i.up()
i.forward(offset)
i.forward(3.5)
i.down()
i.left(90)
i.forward(70)
i.hideturtle()
def draw_J(offset):
# drawing alphabet j
j = turtle.Turtle()
j.speed(4)
j.color("white")
j.up()
j.forward(offset)
j.left(90)
j.forward(70)
j.right(90)
j.forward(42)
j.down()
j.right(90)
j.forward(47.6)
for ja in range(18):
j.forward(3.64)
j.right(10)
j.forward(7)
j.hideturtle()
|
c262ed6a76ff62230cb46c13303a2a4dfc60c31f | cossta/Validador-Palindromo | /palindromo 0.2.py | 5,837 | 3.703125 | 4 | """ Importando Tkinter """
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
"""Colores utilizados:
1. 2a1a5e
2. f45905
3. fb9224
4. fbe555
5. dfddc7
El orden de los colores va desde el más oscuro hasta el más claro"""
root = Tk()
miFrame = Frame(root)
root.title("Calculadora")
root.geometry("700x500+100+100")
root.title("Palindromo Con Pila PRO")
root.config(background='#fb9224')
miFrame.pack()
"""--------------- Inicio del Menú -------------------------------"""
def infoAdicional():
messagebox.showinfo("Informacion de Aplicacion",
"Si necesitas ayuda, debes ir a un Psicologo o a un Psiquiatra todo depende de ti y tus necesidades")
def avisoLicencia():
messagebox.showwarning("Tacaño", "No compraste la licencia, la pirateaste")
def salirDeLaAplicacion():
valorSalir=messagebox.askquestion("¿Desea salir de la Aplicación?")
if valorSalir=="yes":
root.destroy()
barraMenu = Menu(root)
root.config(menu=barraMenu, width=350, height=300)
archivoMenu=Menu(barraMenu, tearoff=0)
archivoMenu.add_command(label="Nuevo")
archivoMenu.add_command(label="Abrir archivo")
archivoMenu.add_command(label="Guardar")
archivoMenu.add_command(label="Guardar como...")
archivoMenu.add_separator()
archivoMenu.add_command(label="Cerrar")
archivoMenu.add_command(label="Salir", command=lambda:salirDeLaAplicacion())
archivoEdicion=Menu(barraMenu, tearoff=0)
archivoEdicion.add_command(label="Copiar")
archivoEdicion.add_command(label="Cortar")
archivoEdicion.add_command(label="Pegar")
archivoHerramientas=Menu(barraMenu)
archivoAyuda=Menu(barraMenu, tearoff=0)
archivoAyuda.add_command(label="Ayuda extra...", command=lambda:infoAdicional())
archivoAyuda.add_command(label="Licencia", command=lambda:avisoLicencia())
archivoAyuda.add_command(label="Acerca de...")
barraMenu.add_cascade(label="Archivo", menu=archivoMenu)
barraMenu.add_cascade(label="Edicion", menu=archivoEdicion)
barraMenu.add_cascade(label="Herramientas", menu=archivoHerramientas)
barraMenu.add_cascade(label="Ayuda", menu=archivoAyuda)
"""--------------- Fin del Menú -------------------------------"""
"""--------------- Inicio de Clase de la Pila -------------------------------"""
class Pila(object):
def __init__(self):
self.items=["#"]
def apilar(self,dato):
self.items.append(dato)
def desapilar(self):
return self.items.pop()
"""--------------- Fin de Clase de la Pila -------------------------------"""
"""--------------- Inicio de la Clase del Automata -------------------------------"""
def VerificarPalindromo():
pilaPalindromo = Palindro.get()
Palindromo=Pila()
estado = 1
for i in range(0,len(pilaPalindromo)):
transicion=pilaPalindromo[i]
print(transicion)
topePila=Palindromo.desapilar()
if estado == 1:
if transicion=="a" and topePila=="#":
Palindromo.apilar("#")
Palindromo.apilar("a")
elif transicion=="b" and topePila=="#":
Palindromo.apilar("#")
Palindromo.apilar("b")
elif transicion=="a" and topePila=="a":
Palindromo.apilar("a")
Palindromo.apilar("a")
elif transicion=="b" and topePila=="a":
Palindromo.apilar("a")
Palindromo.apilar("b")
elif transicion=="a" and topePila=="b":
Palindromo.apilar("b")
Palindromo.apilar("a")
elif transicion=="b" and topePila=="b":
Palindromo.apilar("b")
Palindromo.apilar("b")
elif transicion=="c" and topePila=="#":
Palindromo.apilar("#")
estado = 2
elif transicion=="c" and topePila=="b":
Palindromo.apilar("b")
estado = 2
elif transicion=="c" and topePila=="a":
Palindromo.apilar("a")
estado = 2
else:
print("No cumple 2")
Palindromo.apilar(topePila)
return False
elif estado == 2:
if transicion=="a" and topePila=="a":
# pass
print("Soy a")
elif transicion=="b" and topePila=="b":
# pass
print("Soy b")
else:
print("No cumple 3")
Palindromo.apilar(topePila)
return False
topePila=Palindromo.desapilar()
if topePila=="#":
print("Soy #")
Palindromo.apilar("#")
estado = 3
if estado == 3:
print("Si cumple")
return True
else:
print("No cumple 4")
return False
"""--------------- Fin de la Clase del Automata -------------------------------"""
LabelPalindromo = Label(miFrame, text="Palindromo Con Pila PRO", font=("Full Pack 2025",12))
LabelPalindromo.config(bg="#fb9224", justify="center")
LabelPalindromo.grid(row=1, column=0, columnspan=2,pady=30)
Palindro = StringVar()
TextoPalindromo = Entry(miFrame, width=50, textvariable=Palindro)
TextoPalindromo.grid(row=3, column=0, columnspan=2, pady=30)
TextoPalindromo.config(bg="#dfddc7")
miFrame.config(bg="#fb9224")
ButtonPalindromoLento = Button(miFrame, text="Verificar Lento", command=VerificarPalindromo)
ButtonPalindromoLento.grid(row=4, column=0)
ButtonPalindromoLento.config(bg="#fbe555")
ButtonPalindromoRapido = Button(miFrame, text="Verificar Rapido")
ButtonPalindromoRapido.grid(row=4, column=1)
ButtonPalindromoRapido.config(bg="#fbe555")
root.mainloop() |
d0b79b946d99e31a3f4d8cbc26392de7be46ce30 | maumneto/IntroductionComputerScience | /CodeClasses/LoopCodes/cod5.py | 236 | 3.640625 | 4 | for i in [1,2,3,4,5]:
print(i)
print('--------------------')
for j in [5,4,3,2,1]:
print(j)
print('--------------------')
for k in [5,1,2,3,7]:
print(k)
print('--------------------')
for i in range(15,0,-2):
print(i)
|
b3250c0ca5faff622c7c298e85505a9000e4a577 | haha001/Test | /test.py | 503 | 4 | 4 |
sup = "MUHAHAHA"
#Python er sjovt nok I guess
print("Hello World!")
#Det er dog lidt mærkeligt uden delimiter
print("Mit navn er Simon",sup)
print("To plus to er lig med", 2 + 2)
print("To ganget med 0 er lig med", 2 *0, '\n')
#True false? med print :O
print("Er 3 + 2 større end 7 -1?")
print(3 + 2 > 7 - 1)
#Dette er en multikommentar
"""
print("I like typing this.")
print ("This is fun")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
"""
|
0ab22da9dd4c4bc2c29f7f4a1492d14d628ef17c | thesharpshooter/codeforce | /day9/word.py | 194 | 3.859375 | 4 | string = raw_input()
lower_count = sum(map(str.islower,string))
upper_count = sum(map(str.isupper,string))
if lower_count < upper_count:
print string.upper()
else:
print string.lower()
|
a538d732e9efe761dbb663b582748b8d9a38e54a | haruto0519/haruto_hirai | /game_project.py | 682 | 3.625 | 4 |
#-----import statements-----
import random as rand
import turtle as trtl
spot = trtl.Turtle()
import turtle as score_writter
spot.showturtle()
spot.shape("circle")
spot.shapesize(2)
spot.color("red")
spot.speed(8)
score = 0
#def update_score():
def clicked(x, y):
score =+ 1
new_xpo = rand.randint(-380,380)
new_ypo = rand.randint(-280,280)
spot.penup()
spot.goto(new_xpo, new_ypo)
#update_score
spot.pendown()
spot.onclick(clicked)
#-----game configuration----
#-----initialize turtle-----
#-----game functions--------
#-----events----------------
wn = trtl.Screen()
wn.mainloop() |
55c4c0d4bab880af134ed5dc11a8707749ec0b08 | Lominelo/infa_2021_Litovchenko | /lab_2/упр 10.py | 327 | 3.984375 | 4 | import turtle
turtle.shape('turtle')
def circlel(t):
for i in range (0,100):
turtle.forward(t)
turtle.left(360/100)
def circler(t):
for i in range (0,100):
turtle.forward(t)
turtle.right(360/100)
for j in range (0,12):
circlel(1)
circler(1)
turtle.left(360/12)
|
fb2b39f3d591ceb4a752a4af36ae9046b6145c8c | devw/hackerrank | /src/basic.py | 2,645 | 4.375 | 4 | def reverse_words_order_and_swap_cases(sentence):
# Implement a function that takes a string consisting of words separated by single spaces and returns a string containing all those words but in the reverse order and such that all cases of letters in the original string are swapped, i.e. lowercase letters become uppercase and uppercase letters become lowercase.
# Example: "aWESOME is cODING" -> "Coding IS Awesome"
return " ".join(sentence.split(" ")[::-1]).swapcase()
class Car:
# The constructor for Car must take two arguments. The first of them is its maximum speed, and the second one is a string that denotes the units in which the speed is given: either "km/h" or "mph". The class must be implemented to return a string based on the arguments. For example, if car is an object of class Car with a maximum speed of 120, and the unit is "km/h", then printing car prints the following string: "Car with the maximum speed of 120 km/h", without quotes. If the maximum speed is 94 and the unit is "mph", then printing car prints in the following string: "Car with the maximum speed of 94 mph", without quotes.
def __init__(self, speed, unitSpeed):
self.speed = speed
self.unitSpeed = unitSpeed
def __new__(cls, speed, unitSpeed):
return f"Car with the maximum speed of {speed} {unitSpeed}"
class Boat:
# The constructor for Boat must take a single argument denoting its maximum speed in knots. The class must be implemented to return a string based on the argument. For example, if boat is an object of class Boat with a maximum speed of 82, then printing boat prints the following string: "Boat with the maximum speed of 82 knots", without quotes.
def __init__(self, speed):
self.speed = speed
def __new__(cls, speed):
return f"Boat with the maximum speed of {speed} knots"
class Multiset():
# A multiset is the same as a set except that an element might occur more than once in a multiset. Implement a multiset data structure in Python.
def __init__(self):
self.multiset = []
def add(self, val):
# adds one occurrence of val from the multiset, if any
self.multiset.append(val)
def remove(self, val):
# removes one occurrence of val from the multiset, if any
self.multiset.remove(val)
def __contains__(self, val):
# returns True when val is in the multiset, else returns False
return val in self.multiset
def __len__(self):
# returns the number of elements in the multiset
return len(self.multiset)
def __repr__(self):
return f"{self.multiset}"
|
f18ee93eb0accf94bf8fcab95c9a4c9101cf234c | alishahussain/Level0-Module5 | /_03_nested_loops/amazing_rings/amazing_rings.pyde | 1,123 | 3.96875 | 4 | """
Go to the recipe to run the demonstration before starting this program
"""
def setup():
# Set the size of your sketch to be a rectangle like in the recipe demonstration
# Call the noFill() command so all the ellipses will be transparent
def draw():
# Use a for loop to make the first set of rings that will start in the left half
# of the window.
# Make this set of rings move across the sketch to the right
# Hint: Make two variables, one for x and another for the speed.
# Then increase x by the amount in speed.
# When the rings reach the right side of the sketch, reverse the direction so
# they move.
# Hint: speed = -speed *
# When the rings reach the left side of the sketch, reverse the direction again
# CHALLENGE - to finish the Amazing Rings
# Add another for loop to draw the second set of rings that will start in the
# right half of the window
# Make this set of rings move in the opposite direction to the other rings
# These rings must also "bounce" off the sides of the window.
|
a5ca5154e4dd500ad7404fef8f978a7489d60b2c | w3cp/coding | /python/python-3.5.1/7-input-output/6-format-3.py | 426 | 3.65625 | 4 | #
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print('{0:10} ==> {1:10d}'.format(name, phone))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
|
6b4ae9e4025626e8c044086725a5957658686412 | selik/destructure | /examples/fips.py | 2,136 | 3.5 | 4 | #!/usr/bin/env python3
'''
Suppose you're trying to estimate someone's median household income
based on their current location. Perhaps they posted a photograph on
Twitter that has latitude and longitude in its EXIF data. You might go
to the FCC census block conversions API (https://www.fcc.gov/general
/census-block-conversions-api) to figure out in which census block the
photo was taken.
'''
from destructure import match, MatchError, Binding, Switch
import json
from urllib.request import urlopen
from urllib.parse import urlencode
url = 'http://data.fcc.gov/api/block/find?'
params = {'format': 'json', 'showall': 'true',
'latitude': 28.35975, 'longitude': -81.421988}
# 'latitude': 28.359, 'longitude': -81.421}
# 'latitude': 0, 'longitude': 100}
results = Binding()
schema_one = \
{
"County": {
"name": results.county,
"FIPS": str,
},
"State": {
"name": results.state,
"code": str,
"FIPS": str,
},
"Block": {
"FIPS": results.fips,
},
"executionTime": str,
"status": "OK",
}
schema_intersection = \
{
"executionTime": str,
"County": {
"FIPS": str,
"name": results.county
},
"messages": [
"FCC0001: The coordinate lies on the boundary of mulitple blocks, first FIPS is displayed. For a complete list use showall=true to display 'intersection' element in the Block"
],
"Block": {
"FIPS": str,
"intersection": results.intersection
},
"status": "OK",
"State": {
"code": str,
"FIPS": str,
"name": results.state
}
}
with urlopen(url + urlencode(params)) as response:
text = response.read().decode('utf-8')
data = json.loads(text)
s = Switch(data)
if s.case(schema_one):
codes = [results.fips]
elif s.case(schema_intersection):
codes = [block['FIPS'] for block in results.intersection]
else:
fmt = 'Could not match any schemas to {data!r}'
raise MatchError(fmt.format(data=data))
for fips in codes:
print(fips)
# From there, it's on to http://api.census.gov to finish the task.
|
2cf8dccc58b6139ccceff9253e2711a8d1a4b8b0 | q42355050/260201026 | /lab05/example1.py | 109 | 4.09375 | 4 | number = int(input("Enter the number: "))
for i in range(10):
print(number, "x", i+1, "=", number*(i+1)) |
1765819a9a5b7c5630561baba67d8f9d3a05e700 | Sandhya99999/AllPrograms | /PythonPrograms/Series.py | 436 | 4.0625 | 4 | TermNumber = int(input('Enter a number upto which you want to print the terms like this series(1, 4, 27, 256, .....):'))
print('The terms in the above series upto', TermNumber, 'are', end = '')
TermCounter = 2
Product = 1
while Product <= TermNumber:
print('', Product, end = '')
Counter = 1
Product = 1
while Counter <= TermCounter:
Product = Product * TermCounter
Counter += 1
TermCounter += 1
print('.') |
f2fa03f3b76f1d02d91d226778c45aff63c43e7e | ulaireatea/Python | /Exercicios/ex038(Comparando números).py | 267 | 4.03125 | 4 | n1 = float(input('Digite um valor: '))
n2 = float(input('Digite outro valor: '))
if n1 > n2:
print('O primeiro número digitado é maior.')
elif n1 < n2:
print('O segundo número digitado é maior.')
else:
print('Os dois números digitados são iguais.')
|
4b13761b39d27f39e013376e6a37612f3c4c1e00 | lschanne/DailyCodingProblems | /year_2019/month_05/2019_05_10__min_edit_for_valid_parentheses.py | 1,018 | 4.28125 | 4 | '''
May 10, 2019
Given a string of parentheses, write a function to compute the minimum number
of parentheses to be removed to make the string valid (i.e. each open
parenthesis is eventually closed).
For example, given the string "()())()", you should return 1.
Given the string ")(", you should return 2, since we must remove all of them.
'''
def min_edit_for_valid_parentheses(string):
balance = 0
count = 0
for char in string:
if char == '(':
balance += 1
elif char == ')':
balance -= 1
if balance < 0:
balance = 0
count += 1
balance += count
return balance
if __name__ == '__main__':
import sys
for string in sys.argv[1:]:
print('input string: {}'.format(string))
print(
'minimum number of parentheses to be removed: {}'.format(
min_edit_for_valid_parentheses(string)
)
)
print('------------------------------------------')
|
221b998428b7fb4be63380bc07ec957360006fbe | bobhancock/pythonsysadmin | /text/starts_ends_with.py | 290 | 3.71875 | 4 | filename = "foo.txt"
print(filename.endswith("txt")) # True
print(filename.startswith("foo")) # True
print(filename.startswith("bar")) # False
print(filename.startswith( ("bar", "bob", "foo") )) # True
print(filename.startswith("o", 1)) # True
print(filename.startswith("oo", 1, 3)) # True
|
0f59d7ef7c8fb3833cbc99dc39bb3aeb3222f247 | bhusalashish/DSA-1 | /Data/Hashing/Subarray with zero-sum/Hashing.py | 853 | 3.96875 | 4 | '''
#### Name: Subarray with zero-sum
Link: [link]()
#### Sub_question_name: Hashing
Link: [link]()
Iterate and find the current sum and add to set()
If sum is 0 or sum is present in set() ; zero substring exists
**Prefix Sum**
arr[] = {1, 4, -2, -2, 5, -4, 3}
If we consider all prefix sums, we can
notice that there is a subarray with 0
sum when :
1) Either a prefix sum repeats or
2) Or prefix sum becomes 0.
Prefix sums for above array are:
1, 5, 3, 1, 6, 2, 5
Since prefix sum 1 repeats, we have a subarray
with 0 sum.
'''
def check_zero(arr):
n = len(arr)
exist = set()
running_sum = 0
for num in arr:
running_sum += num
if running_sum == 0 or running_sum in exist:
return True
exist.add(running_sum)
return False
arr = [-3, 2, 3, 1,-1, 6]
print(check_zero(arr)) |
f3d6284b4e4fb8aef7495b2fa6f732179cf96a33 | znnznn/coursera | /week2/while/digital st n.py | 106 | 3.625 | 4 | n = int(input())
i = 1
while (i ** 2) <= n:
m = i ** 2
print(m, end=' ')
i = i + 1
print(' ')
|
5b9eac13c6ce7a7d2a82c787be68af5d1b9a5e40 | shlokKh/interview-practice | /chapter4/p9.py | 663 | 3.53125 | 4 | '''
My logic is for every level it 2^h h = the height
'''
def weave_list(l1, l2, results, prefix):
if len(l1) == 0 or len(l2) == 0:
result = prefix
results.append(result + l1 + l2)
return
headFirst = l1.pop(0)
print(headFirst)
prefix.append(headFirst)
weave_list(l1, l2, results, prefix)
prefix.pop()
l1.insert(0, headFirst)
headSecond = l2.pop(0)
prefix.append(headSecond)
weave_list(l1, l2, results, prefix)
prefix.pop()
l2.insert(0, headSecond)
l1 = [1,2]
l2 = [3,4]
results = []
prefix = []
weave_list(l1, l2, results, prefix)
print(results)
|
5584c075d2da0a6f180ea6dbc4fe74cf369d0bf6 | kyleetaan/git-pythonmasterclass | /src/basics/stringSlice.py | 254 | 3.65625 | 4 | # 0123456789012345678901234
letters = "abcdefghijklmnopqrstuvwyz"
print(letters[16:13:-1])
print(letters[4::-1])
print(letters[:-9:-1])
for i in range(1, 13):
print("No. {0:<2} squared is {1:<3} and cubed is {2:<4}".format(i, i**2, i**3)) |
326bf08efdb2a680919bb95949c84b03944e8f82 | henzelis/Python_Learning2020 | /regex_password_cheker.py | 452 | 3.65625 | 4 | import re
pattern = re.compile(r"[A-Za-z0-9@#$%]{8,}")
while True:
password = input('Please input password that contain letters, numbers, symbols $%#@, and at least 8 char long: ')
check = pattern.fullmatch(password)
try:
if password == check.group():
print('Your password accepted!')
break
except AttributeError:
print('Please input password in right format')
continue
|
5cca6d8d30ea83613cb40c62b6f6acbc26ee49a5 | GoncalvesCarol/algoritimos1_2021 | /cursoPythonIniciante/somaDoisNumeros.py | 99 | 3.75 | 4 | x = input("Informe um número ")
y = input("Informe um número ")
z = int(x) + int(y)
print (z)
|
b8432951e84bc639a863e2e2ec618e08c56d472b | ZhiyuSun/leetcode-practice | /1-100/054_螺旋矩阵.py | 2,356 | 4.03125 | 4 | """
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# 2021.03.02 直奔题解,模拟法
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows, columns = len(matrix), len(matrix[0])
visited = [[False] * columns for _ in range(rows)]
total = rows * columns
order = [0] * total
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
row, column = 0, 0
directionIndex = 0
for i in range(total):
order[i] = matrix[row][column]
visited[row][column] = True
nextRow, nextColumn = row + directions[directionIndex][0], column + directions[directionIndex][1]
if not (0 <= nextRow < rows and 0 <= nextColumn < columns and not visited[nextRow][nextColumn]):
directionIndex = (directionIndex + 1) % 4
row += directions[directionIndex][0]
column += directions[directionIndex][1]
return order
# 2021.03.02 按层来遍历
class Solution2:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows, columns = len(matrix), len(matrix[0])
order = list()
left, right, top, bottom = 0, columns - 1, 0, rows - 1
while left <= right and top <= bottom:
for column in range(left, right + 1):
order.append(matrix[top][column])
for row in range(top + 1, bottom + 1):
order.append(matrix[row][right])
if left < right and top < bottom:
for column in range(right - 1, left, -1):
order.append(matrix[bottom][column])
for row in range(bottom, top, -1):
order.append(matrix[row][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return order
|
228b82484be51baefa52875bef00de199ccd4120 | sureshmelvinsigera/linkedlist | /checkPalindrome.py | 2,223 | 3.890625 | 4 | '''
Given a singly linked list of characters, write a function that returns true
if the given list is palindrome, else false.
The list below is palindrome:
{Empty List}
1
1 -> 2 -> 2 -> 1
'''
from linkedlist import Node
from linkedlist import LinkedList
'''
Approach 1 (Using stack):
1) Traverse the given list from head to tail and push every visited node to stack.
2) Traverse the list again. For every visited node, pop a node from stack and
compare data of popped node with currently visited node.
3) If all nodes matched, then return true, else false.
Time complexity of above method is O(n), but it requires O(n) extra space.
'''
def checkPalindromeStackBased(node):
s = []
current = node
while current:
s.append(current.data)
current = current.next
current = node
while current:
if current.data != s.pop():
return False
current = current.next
return True
'''
Approach 1 (Finding middle of list and reversing and checking and reversing again):
1) If list is empty or has only one node return True.
2) If number of nodes are even, reverse the list from midNode else reverse
the list from midNode.next.
3) Traverse the two segments and compare.
4) Reverse the second segment again.
Time complexity of above method is O(n), but it requires O(n) extra space.
'''
def checkPalindrome(node):
if node is None or node.next is None:
return True
fast, middle, preMiddle = node, node, None
l = 0
while fast and fast.next:
l += 2
fast, preMiddle, middle = fast.next.next, middle, middle.next
if fast:
l += 1
r = reverse(middle)
revNode = r
while node and revNode:
if node.data != revNode.data:
preMiddle.next = reverse(r)
return False
node, revNode = node.next, revNode.next
preMiddle.next = reverse(r)
return True
def reverse(node):
prev = None
while node:
node.next, prev, node = prev, node, node.next
return prev
l = LinkedList()
print checkPalindrome(l.head)
l.append(1)
print checkPalindrome(l.head)
l.append(2)
l.append(3)
print checkPalindrome(l.head)
l.append(2)
l.append(1)
print checkPalindromeStackBased(l.head)
|
57b0133b81edab740c7c641c2112bb7a8e693deb | Barathkumar-09/Games | /stone_paper_scissors.py | 1,280 | 4.15625 | 4 | '''
Stone Paper scissor game:
Points :
1. if paper and rock then paper wins
2. if paper and scissor then scissor wins
3. if rock and scissor then scissor wins
'''
import random
score=computr=flag=0
computer = ["p", "s", "r"]
max=int(input("Enter the maximum score! :"))
#print(random.choice(comp))
print("""p=paper
r=rock
s=siccor
""")
while(flag<max):
player=input("Enter your choice:")
comp=random.choice(computer)
print("|",player, ":",comp,"|" )
if(((player=="s")and(comp=="p"))or((player=="r")and(comp=="s"))or((player=="p")and(comp=="s"))or((player=="p")and(comp=="r"))):
score+=1
print("you scored :)")
elif(((player=="s")and(comp=="p"))or((player=="s")and(comp=="r"))or((player=="s")and(comp=="r"))or((player=="r")and(comp=="p"))):
computr+=1
print("comp scored :(")
elif(((player=="p")and(comp=="p"))or((player=="s")and(comp=="s"))or((player=="r")and(comp=="r"))):
print("Tie :|")
else:
print("wrong input!")
print("|computer :",computr,"|","you:",score,"|")
if(computr<score):
flag=score
elif(score<computr):
flag=computr
if(score==max):
print("\t\tyou win!!")
break
if(computr==max):
print("\t\tyou lose :(")
break
|
06e05c8cb3439eb41f2bd286c51d4111a1eae94b | sergiodealencar/courses | /material/curso_em_video/ex072.py | 1,025 | 4.03125 | 4 | # numeros = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
# 11, 12, 13, 14, 15, 16, 17, 17,
# 19, 20)
# extenso = ('zero', 'um', 'dois', 'três', 'quatro',
# 'cinco', 'seis', 'sete', 'oito', 'nove',
# 'dez', 'onze', 'doze', 'treze', 'quatorze',
# 'quinze', 'dezesseis', 'dezesete', 'dezoito',
# 'dezenove', 'vinte')
# usuario = int(input('Digite um número entre 0 e 20: '))
# while usuario not in numeros:
# usuario = int(input('Tente novamente. Digite um número entre 0 e 20: '))
# print(f'Você digitou o número {extenso[usuario]}.')
cont = ('zero', 'um', 'dois', 'três', 'quatro',
'cinco', 'seis', 'sete', 'oito', 'nove',
'dez', 'onze', 'doze', 'treze', 'quatorze',
'quinze', 'dezesseis', 'dezesete', 'dezoito',
'dezenove', 'vinte')
while True:
num = int(input('Digite um número entre 0 e 20: '))
if 0 <= num <= 20:
break
print('Tente novamente. ', end='')
print(f'Você digitou o número {cont[num]}.')
|
517b96f69ba4faa2e17fdb9b2644f3fe0ff0c55b | Hansung-Lee/TIL | /Algorithm/baekjoon/11655_ROT13.py | 338 | 3.609375 | 4 | msg = input()
result = ""
for m in msg:
code = ord(m)
if 64 < code < 91:
code += 13
if code > 90:
code -= 26
result += chr(code)
elif 96 < code < 123:
code += 13
if code > 122:
code -= 26
result += chr(code)
else:
result += m
print(result) |
7128d17bfab3b3fcf99ed36af792837c18558b5e | JuyeonYu/Algorithm_DataType | /ReverseWord.py | 230 | 3.796875 | 4 | def reverse_word(str):
word_list = str.split(" ")
reversed_list = [""] * len(word_list)
for index, value in enumerate(word_list):
reversed_list[len(reversed_list) - index - 1] = value
return reversed_list
|
5ae4c195730d26475155ca0a8bee894ae41a413b | PlanckConstant/Python-course | /Lesson14.py | 1,270 | 3.875 | 4 | l = [1, 2, 3, 'hello', ['test', 10], 'word', True]
l2 = list('hello')
l3 = list((1, 2, 5)) #Кортеж внутри списка
l4 = [i for i in 'hello'] #каждый символ в строке
l5 = [i for i in 'hello word' if i != ' '] #Кроме ' '
l51 = [i+'(str)'+i for i in 'hello word!' if i not in [' ', 'e', 'o', '!']] #С условиями, есл и i не содержит ...
print(l, l2, l3, l4, l5, l51, sep='\n')
###### Генераторы ######
print(range(10)) #Возврящает первую и последнюю цифру последовательности
print(list(range(10))) #Возвращает всю последовательность от 0 (по умолчанию)
print(list(range(2, 10))) #Возвращает всю последовательность (старт, стоп)
print(list(range(1, 10, 2)))#Возвращает всю последовательность с шагом (старт, стоп, шаг)
l6 = list(range(0, 11))
print(l6)
######## Вложенные цыклы ########
for i in range(1, 3):
print(f'Внешний цикл # {i}')
for j in range(1 ,3):
print(f'\tВнутренний цикл # {j}')
|
02d23a19396a5304adb3276c3ac6870fabaad524 | bhoj001/python_tutorial | /ex_1.5_datatype_frozenset.py | 2,449 | 4.15625 | 4 | '''
author: bhoj bahadur karki
date: 2020-jan-19th
purpose : about frozenset in python
set vs frozenset:
There are currently two built-in set types, set and frozenset. The set type is mutable — the
contents can be changed using methods like add() and remove(). Since it is mutable,
it has no hash value and cannot be used as either a dictionary key or as an element
of another set. The frozenset type is immutable and hashable — its contents cannot
be altered after it is created; it can therefore be used as a dictionary key or as
an element of another set.
Both set and frozenset support set to set comparisons. Two sets are equal if and only if every
element of each set is contained in the other (each is a subset of the other). A set is less
than another set if and only if the first set is a proper subset of the second set (is a subset,
but is not equal). A set is greater than another set if and only if the first set is a proper
superset of the second set (is a superset, but is not equal).
Instances of set are compared to instances of frozenset based on their members.
For example, set('abc') == frozenset('abc') returns True and so
does set('abc') in set([frozenset('abc')]).
'''
x = frozenset([2,3,4])
print(x)
# x[0]=3 # TypeError: 'frozenset' object does not support item assignment
# x.clear() # AttributeError: 'frozenset' object has no attribute 'clear'
# iteriating
for item in x:
print(item)
del x # removing frozenset
# -----Methods supported by set but not frozenset-------
'''
The following table lists operations available for set that do not apply to immutable instances
of frozenset:
update(*others)
set |= other | ...
Update the set, adding elements from all others.
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all others.
difference_update(*others)
set -= other | ...
Update the set, removing elements found in others.
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
add(elem)
Add element elem to the set.
remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
discard(elem)
Remove element elem from the set if it is present.
pop()
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
clear()
Remove all elements from the set.
'''
|
9b58a579b3d5e2a210d16101bd965147253be111 | tansonlee/sorting-algorithms | /main.py | 975 | 4 | 4 | from bubble_sort import bubble_sort
from insertion_sort import insertion_sort
from selection_sort import selection_sort
from merge_sort import merge_sort
from quick_sort import quick_sort
from tree_sort import tree_sort
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Laura", 18)
person2 = Person("James", 22)
person3 = Person("Sam", 12)
person4 = Person("Anthony", 18)
people = [person1, person2, person3, person4]
# order people by their age.
# if their age is equal, order by name alphabetically
def strict_total_order(person1, person2):
if person1.age != person2.age:
return person1.age < person2.age
elif person1.name.lower() != person2.name:
return sorted([person1.name.lower(), person2.name.lower()])[0] == person1.name.lower()
else: # names and age are equal
return False # they are equal
sorted_people = tree_sort(people, strict_total_order)
for person in sorted_people:
print(person.name, end=" ") |
d3c746dd701543862e0a3cfeb92f95bcc2f2520b | Pincaptain/idea-bag-solutions | /prime-factorization/service/factorization_service.py | 503 | 3.96875 | 4 | import math
class FactorizationService(object):
def prime_factorization(self, number: int) -> list:
if number < 2:
return []
factors = []
while number % 2 == 0:
factors.append(2)
number /= 2
for i in range(3, int(math.sqrt(number)) + 1, 2):
while number % i == 0:
factors.append(i)
number /= i
if number > 2:
factors.append(int(number))
return factors
|
24cf1c3cf3fd7dd1112fbfc1a40a37c8691ce91a | minhthe/practice-algorithms-and-data-structures | /Binary Search/isSquare.py | 487 | 3.546875 | 4 | '''
https://leetcode.com/problems/valid-perfect-square/
'''
class Solution:
def isPerfectSquare(self, num: int) -> bool:
def f(num, l , r):
while l<=r:
mid = int( (r-l)/2 + l )
if mid * mid == num: return True
if mid * mid > num:
r = mid -1
else:
l = mid + 1
return False
l, r = 1, num
ans = f(num,l, r)
return ans |
b2a0b8d00c912a1e189271fb623923ce563c7f26 | yangh9596/Algo-Leetcode | /Leetcode/257_Binary paths.py | 731 | 3.921875 | 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def path(node, ret, string):
if not node.left and not node.right:
ret.append(string + str(node.val))
if node.left:
path(node.left, ret, string + str(node.val) + "->")
if node.right:
path(node.right, ret, string + str(node.val) + "->")
if not root:
return []
ret = []
path(root, ret, "")
return ret
|
3abeca784381d1cb1031663faf4de96e8cc82eac | ceucomputing/automarker | /test1/submission_D.py | 145 | 3.6875 | 4 | # Addition Problem
# Student D
try:
x = int(input("Enter x: "))
y = int(input("Enter y: "))
print(x + y)
except:
print('Error')
|
3004a31a95acbe4ee9062d80d85daf0dfae79409 | emilcw/tdde23-labbar | /tdde23-labbar/lab8/lab8C.py | 1,746 | 3.515625 | 4 |
"""Implementation av remove-funktion i lab8C, körexempel ligger i lab8C_test och
förklaringar till hur funktionen fungerar ligger i Forklara8C.txt. Var
Samtliga funktioner hör hemma finns angiver ovanför funktionen"""
#Denna funktion hör hemma i calendar.py
def remove(cal_name, d, m, t1):
"String x Integer x String x String"
day = new_day(d)
mon = new_month(m)
start = convert_time(t1)
cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name)))
new_date(day,mon)
if is_booked_from(cal_day, start):
insert_calendar(cal_name, remove_appointment(fetch_calendar(cal_name),
day, mon, start))
print("The appointment has been removed")
else:
print("This person is not booked here")
#Denna funktion hör hemma i booking.py
def remove_appointment(cal_year, day, mon , start):
"calendar_year x day x month x time -> calendar_year"
cal_day = calendar_day(day, calendar_month(mon, cal_year))
return insert_calendar_month(
mon,
insert_calendar_day(
day,
delete_appointment(cal_day, start),
calendar_month(mon, cal_year)),
cal_year)
#Denna funktion hör hemma i calendar_abstraction.py
def delete_appointment(cal_day, start):
"calendar_day x time -> calendar_day"
def del_app(al,start):
if is_same_time(start, start_time(get_span(al[0]))):
return al[1:]
else:
return [al[0]] + del_app(al[1:],start)
ensure(start,is_time)
ensure(cal_day, is_calendar_day)
return attach_tag('calendar_day', del_app(strip_tag(cal_day), start))
|
1a1ac2a5ec05c06fcfe38d53d8f6dcb2f293c4f1 | okeonwuka/PycharmProjects | /ThinkPython/swampy-2.1.5/mysquare1a.py | 294 | 3.53125 | 4 | # Exercise 4.3
# 4.3.1
from TurtleWorld import *
# For some reason we need to initialise TurtleWorld() otherwise
# error
world = TurtleWorld()
# Function that draws a square
def square():
t = Turtle()
for i in range(4):
fd(t, 100)
lt(t)
# Draw a square
square()
|
351d4169be4efc2b2ab4f7a05430c1cbe0f7d6bc | vukakarthik/PyTrain | /08_classes-basics/02_inheritance.py | 1,032 | 4.0625 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduceyourself(self):
print("My name is " + self.name)
print("My age is " + str(self.age))
class Teacher(Person): # this class inherits the class above!
def __init__(self, name, age):
self.courses = [] # initialise a new variable
super().__init__(name, age) # call the init of Person
def stateprofession(self):
print("I am a teacher!")
def introduceyourself(self):
super().introduceyourself() # call the introduceyourself() of the Person
self.stateprofession()
print("I teach " + str(self.nrofcourses()) + " course(s)")
for course in self.courses:
print("I teach " + course)
def addcourse(self, course):
self.courses.append(course)
def nrofcourses(self):
return len(self.courses)
author = Teacher("Chandra Babu Naidu", 60)
author.addcourse("Python")
author.addcourse("Golang")
author.introduceyourself() |
256ab64bd14ae59d67214ac8e69fc85be9bc22f5 | joyrexus/CS212 | /homework/unit_4/bridge/refactor/search.py | 2,904 | 3.859375 | 4 | class Path(list):
'''
Representation of a path (sequence of states).
'''
def __init__(self, *args): super(Path, self).__init__(args)
# make paths comparable by cost
def __lt__(self, other): return self.cost < other.cost
def __le__(self, other): return self.cost <= other.cost
def __gt__(self, other): return self.cost > other.cost
def __ge__(self, other): return self.cost >= other.cost
def __add__(self, other): return Path(*list.__add__(self, other))
@property
def first(self):
'''First element in path.'''
return self[0]
@property
def last(self):
'''Last element in path.'''
return self[-1]
@property
def cost(self):
'''
Cost of this path.
The cumulative path cost should be specified in the
cost property of the last state in the path.
'''
return self.last.cost
class PathList(Path):
'''
List of paths, where each path is a sequence of states.
'''
def add(self, path):
'''
Add path, replacing costlier path (to same state)
if it exists.
After adding, re-sort paths (by cost).
'''
for i, p in enumerate(self):
if p.last == path.last: # final states equivalent?
if p.cost < path.cost:
return # existing path is better
else:
del self[i] # existing path is worse
break
super(PathList, self).append(path) # add path
self.sort() # re-sort paths by cost
def least_cost(start, next, goal):
'''
Return least cost path from start start state to goal state.
We begin with a start state, consider all successor states
of the last state on the best path (evaluated by cost) produced
by next(state), and conclude when goal(path) is true.
A path is a sequence of states and the cost of a path is the sum
of each state's action cost (state.action.cost).
'''
seen = set() # states already seen
paths = PathList(Path(start)) # ordered list of paths taken
while paths:
path = paths.pop(0) # remove first/best path
if goal(path):
return path
else:
seen.add(path.last) # add last to states seen
for s in next(path.last): # successors to last state
if s not in seen:
s.cost = s.action.cost + path.cost # cost to get here
paths.add(path+[s]) # add extended path
if __name__ == '__main__':
x = Path('a', 'b', 'c')
y = Path('d', 'e', 'f')
assert x.first is 'a'
assert y.first is 'd'
P = PathList(x, y)
assert P.first is x
assert P.last is y
|
cef1af5538f7814e55fdedf636ab1fdce73a0387 | denisela1/work_log | /csv_funcs.py | 8,397 | 4.15625 | 4 | import csv
from datetime import datetime
import re
import os
def clear():
"""Function to clear screen as the program runs."""
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
def read_file():
"""
Function to read the csv file and return data as a dictionary, dates being
the keys and tasks, time, notes are the values.
{'2017-10-14': [ {'name': 'Task', 'time': '10', 'notes': ''} ]}
"""
with open("logs.csv", 'r') as csvfile:
reader = csv.reader(csvfile)
result = list(reader)
dictionary = {}
for i in result[1:]:
date, task, mins, notes = i[0], i[1], i[2], i[3]
details = {'Name': task, 'Time': mins, 'Notes': notes}
if date in dictionary.keys():
dictionary[date].append(details)
else:
dictionary.update({date: [details]})
return dictionary
def show_options(data):
"""
Function to display date options after the user input. it's formatted to
be used after the search logic in each search function.
"""
indexed = {}
for i, v in enumerate(data):
indexed.update({i + 1: v})
return indexed
def show_options_direct(data):
"""
Function to display date options after the user input. it's formatted to
be used after the search logic in each search function.
"""
indexed = {}
for i, v in enumerate(data):
print(i + 1, v)
indexed.update({i + 1: v})
return indexed
def show_results(dictionary, selection):
"""
Function to display results based on the selected date.
If a date (the key of the dictionary) has more than one entry,
this function will make sure to provide these options.
Otherwise, only one result will be shown.
"""
for key, value in dictionary.items():
if selection == key:
for i in value:
print(key)
for keys, values in i.items():
print(keys, values)
print('\t')
def show_details(filtered_dictionary):
"""
After the search results are shown and final selection is made,
this function organizes the data to be included in the final
results/details. It's formatted to be used by each search function.
"""
while True:
try:
display_dictionary = show_options(filtered_dictionary.keys())
index = list(range(1, len(display_dictionary)+1))
for i in index:
selection = display_dictionary[i]
show_results(filtered_dictionary, selection)
except ValueError:
print('Sorry, your entry is not valid.\n')
else:
break
def read_dates():
"""
Function to read dates in the csv file and return entries based on the
date selected by the user. Data is stored as a dictionary, dates being
the keys.
"""
dictionary = read_file()
while True:
display_dictionary = show_options_direct(dictionary.keys())
index = int(input("Please select a date to list the details by "
"entering its number on the left side:\n"))
if 0 < index <= len(display_dictionary):
selection = display_dictionary[index]
show_results(dictionary, selection)
else:
raise ValueError
show_details(dictionary)
prompt = (input('\nPress any letter to go back to the main menu or '
'R to return to selection screen.\n')).upper()
if prompt == 'R':
continue
else:
break
def read_time():
"""
Function to run the search logic to find entries by time. The search
logic filters the data and stores it in a variable called
'filtered_dictionary', to be passed to the function 'show_details' to list
the details.
"""
while True:
dictionary = read_file()
match = []
try:
user_input = int(input("Enter the total amount of minutes spent "
"to list associated tasks:\n"))
search = str(user_input)
if user_input > 0:
for key, value in dictionary.items():
for v in value:
if v['Time'] == search:
match.append(key)
if len(match) == 0:
print("Sorry, we couldn't find any entry.\n")
else:
filtered_dictionary = dict(
(k, dictionary[k]) for k in match if k in dictionary)
for v in filtered_dictionary.values():
for i in v:
if i['Time'] != search:
v.remove(i)
show_details(filtered_dictionary)
else:
raise ValueError
except ValueError:
print('Sorry, your entry is not valid.\n')
else:
break
def read_string():
"""
Function to run the search logic to find entries by exact match.
The search logic filters the data and stores it in a variable called
'filtered_dictionary', then passed to the function 'show_details' to list
the details.
"""
dictionary = read_file()
results = {}
search = str(input("Enter a keyword to search for a specific task or "
"note:\n")).lower()
for key, value in dictionary.items():
for v in value:
if search in (v['Name']).lower():
if key in results:
results[key].append(v)
else:
results.update({key: [v]})
if search in (v["Notes"]).lower():
if key in results:
results[key].append(v)
else:
results.update({key: [v]})
if len(results) == 0:
print("Sorry, no entry found.\n")
show_details(results)
def read_pattern():
"""
Function to run the search logic to find entries by pattern.
The search logic filters the data and stores it in a variable called
'filtered_dictionary', then passed to the function 'show_details' to list
the details.
"""
while True:
dictionary = read_file()
filtered = []
try:
search = str(input("Please enter a pattern (e.g. \w).\n"))
for key, value in dictionary.items():
for v in value:
match_name = re.findall(search, v['Name'])
match_notes = re.findall(search, v['Notes'])
if match_name or match_notes:
filtered.append(key)
if len(filtered) == 0:
print("Sorry, no entry found.\n")
break
filtered_dictionary = dict(
(k, dictionary[k]) for k in filtered if k in dictionary)
for v in filtered_dictionary.values():
for i in v:
match_name = re.findall(search, i['Name'])
match_notes = re.findall(search, i['Notes'])
if not match_name or not match_notes:
v.remove(i)
show_details(filtered_dictionary)
except ValueError:
print('Sorry, your entry is not valid.\n')
else:
break
def write_file():
"""Function to enter a new log to the csv file and make sure the user
input is in the required format."""
with open("logs.csv", 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
while True:
try:
date_input = (datetime.strptime(input(
'Enter a date (MM/DD/YYYY).\n'), '%m/%d/%Y')).date()
task_input = str(input('Enter the name of the task.\n'))
time_input = int(input('Enter minutes spent:\n'))
if time_input > 0 and len(task_input) > 0:
notes_input = str(input('Enter any additional notes:\n'))
writer.writerow(
[date_input, task_input, time_input, notes_input])
print('Entry recorded.\n')
except ValueError:
print("Sorry, not a valid entry.\n")
else:
break
|
829bdd85d2b9e1d814463b7c969416b67d4db018 | JuleeKeenanRivers/Keenanrivers_julee | /PyLesson_07/Lesson07.py | 178 | 3.96875 | 4 | number = int(input("Enter a number:"))
digits = 0
num = number
while number > 0:
digits += 1
number = int(number/10)
print("There are", digits, "digits in", num)
|
b3f371c4d5eda88722c3b4d1d9fd57317d2e9de5 | gvattiku/rpiFacedetection | /face_detection.py | 856 | 3.5625 | 4 | """
Takes pictures from the Raspberry Pi Camera at regular intervals. Detects faces
and sends cropped pictures of faces to the server
"""
import cv2
import requests
SERVER_URL = 'http://127.0.0.1:5000/image'
cascPath = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
with picamera.PiCamera() as camera:
camera.resolution = (320, 240)
camera.capture('photo.jpg', format='jpeg')
img = cv2.imread('photo.jpg', 0)
faces = faceCascade.detectMultiScale(
img,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Send each face to the server
for (x, y, w, h) in faces:
cv2.imwrite('cropped.jpg', img[y:y + h, x:x + w])
# Send the image using the requests library
files = {'file': open('cropped.jpg', 'rb')}
requests.post(SERVER_URL, files=files)
|
cc6cecf83bf32c1d445c32d1362ced90f5570869 | Ratna04priya/-Python-worked-problems- | /prob_-_soln/complex_no_add.py | 568 | 4.25 | 4 | # Adding complex numbers
import math
class comp:
def __init__(self,x,y):
self.x=x
self.y=y
def __add__(self,other):
return comp(self.x + other.x, self.y + other.y)
def __str__(self):
string = str(self.x)
string = string +" " + str(self.y)+ "i"
return string
k= input("Enter the real part of complex 1: ")
l= input("Enter the imaginary part of complex 1: ")
m= input("Enter the real part of complex 2: ")
n= input("Enter the imaginary part of complex 2: ")
complex1 = comp(k,l)
complex2 = comp(m,n)
complex3 = complex1 + complex2
print(complex3)
|
864a6cec0205a883059d1ae8e5da436895e707e0 | SeanyDcode/codechallenges | /completed/dailychallenge4.py | 955 | 3.859375 | 4 | # From dailycodingproblem.com
#
# Daily Challenge #4
#
# Given an array of integers, find the first missing positive integer in linear time and constant space.
# In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
#
# For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
#
# You can modify the input array in-place.
array = [3, 4, -1, 1]
def lowest_pos(array):
# declare lowest_int
lowest_int = 1
# iterate through array
for i in range(len(array)):
# pass if negative, 0, or lowest_int already less than current array item
if array[i] <= 0 or array[i] > lowest_int:
pass
# if item equals current lowest_int, increase by 1
else:
lowest_int += 1
return lowest_int
print(lowest_pos(array))
|
776df1c84aba5e4589c55bba35f2e050d8c6ce9e | yadvi12/Lariox-Automation | /aws.py | 881 | 3.90625 | 4 | # Importing OS Module
import os
# This function will set the color of text to blue.
os.system("tput setaf 4")
def aws():
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> AWS AUTOMATION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
print(" ")
while True:
os.system("clear")
print("""
Press 1 for configuring AWS
Press 2 to create key-pair
Press 3 to create security-group
Press 4 to launch an instance
Press 5 to describe an instance
Press 6 to create a volume in EBS
Press 7 to attach an EBS volume to EC2 instance
Press 8 to create a S3 Bucket
Press 9 to exit
""")
print()
op = input("Please enter your choice: ")
if int(op) == 1:
os.system("aws configure")
|
2a4e1c3b69d7152ba1bb4e36e7176c23c8d86ede | Yanjiao-Ao/LeetCode | /01delete_duplicate.py | 521 | 3.515625 | 4 | def delete_duplicate(nums):#解题思路:双指针;优化,如果存在一个没有重复数的列,会多话时间,所以直接
head = 0
tail = 1
if len(nums) ==0:
return 0
if len(nums) == 1:
return 1
while(tail<len(nums)):
if nums[head] != nums[tail]:
nums[head +1] = nums[tail]
head +=1
tail +=1
else:#nums[q] == nums[p]
tail +=1
return head + 1
li = [0,0,1,1,1,2,2,3,3,4]
print(delete_duplicate(li))
|
5367ebc9586710caa234d11302c196bea86a47d7 | Prakashchater/Daily-Practice-questions | /practice.py | 208 | 3.59375 | 4 | def cummilative(arr):
l = []
j = 0
for i in range(len(arr)):
j += arr[i]
l.append(j)
return l
if __name__ == '__main__':
arr = [10,20,30,40,50]
print(cummilative(arr)) |
845bcabcb6f01a88bfbd4588d66682c63ce5cd09 | ktsstudio/kts-school-backend | /1-asyncio/cpu_multi.py | 294 | 3.515625 | 4 | import time
from threading import Thread
COUNT = 50000000
def countdown(n):
while n > 0:
n -= 1
t1 = Thread(target=countdown, args=(COUNT,))
t2 = Thread(target=countdown, args=(COUNT,))
begin = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
print(time.time() - begin)
|
f151df27a4ddbb1ee9a6b93a80e513acec6c6473 | Huzo/Othello-and-The-Journey-games-duck-typing | /Elf.py | 1,652 | 3.53125 | 4 | # CSCI3180 Principles of Programming Languages
#
# --- Declaration ---
#
# I declare that the assignment here submitted is original except for source
# material explicitly acknowledged. I also acknowledge that I am aware of
# University policy and regulations on honesty in academic work, and of the
# disciplinary guidelines and procedures applicable to breaches of such policy
# and regulations, as contained in the website
# http://www.cuhk.edu.hk/policy/academichonesty/
#
# Assignment 2
# Name : Huzeyfe Kiran
# Student ID : 1155104019
# Email Addr : 1155104019@link.cuhk.edu.hk
import random
from NPC import NPC
class Elf(NPC):
MAGIC_CAP = 20
def __init__(self, posx, posy, index, mapp):
super().__init__(posx, posy, index, mapp)
self._name = "E%s" % str(index)
self._power = random.randint(5, self.MAGIC_CAP - 1)
def action_on_warrior(self, warrior):
self.talk(("My name is %s. Welcome tomy home. My magic power is %s." % (self._name, str(self._power))))
self.talk(("Your magic crystal is %s." % warrior.magic_crystal))
self.talk("Do you need my help?")
self.talk("You now have following options: ")
print("1. Yes")
print("2. No")
a = int(input())
if(a == 1):
value = random.randint(1, self._power - 1)
if(warrior.magic_crystal > value):
warrior.decrease_crystal(value)
warrior.increase_health(value)
warrior.talk(("Thanks for your help! %s" % self.name))
else:
warrior.talk("Very embarrassing, I don't have enough crystals.")
return False
|
09b4b2043efdbb4aaab0977ef118ee7e6f671cae | abdirahman-mahat/password-locker | /user.py | 1,414 | 3.96875 | 4 | import unittest
class User:
"""
Class that generates new instances of contacts.
"""
user_list = [] # empty user list
def __init__(self,name,username,password):
self.name = name
self.username = username
self.password = password
"""
__init__ method that helps us define properties for our objects.
"""
def save_user(self):
'''
save_user method saves user objects into user_list
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user_method deletes a saved user from the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_username(cls,username):
'''
method that takes in a username and returns a user that matches that username
'''
for user in cls.user_list:
if user.username == username:
return user
@classmethod
def user_exists(cls,username):
'''
method that checks if a user exists froom the user list
'''
for user in cls.user_list:
if user.username == username:
return True
return False
@classmethod
def display_users(cls):
'''
method that returns a list of all users saved
'''
return cls.user_list
if __name__ == '__main__':
unittest.main() |
aa14d0fc151617d7cd549badf364d8b7224f92cc | brugnara/exercism | /python/raindrops/raindrops.py | 215 | 3.953125 | 4 | def convert(number):
ret = ''
ret += 'Pling' if not number % 3 else ''
ret += 'Plang' if not number % 5 else ''
ret += 'Plong' if not number % 7 else ''
return ret if ret != '' else str(number)
|
b37c1779ef3da92161849e977d7c84a526d3bcbc | sashaobucina/interview_prep | /python/easy/increasing_order_search_tree.py | 1,318 | 4.0625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __eq__(self, other):
return (type(self) == type(other)) and (self.val == other.val) and (self.left == other.left) and (self.right == other.right)
def increasing_BST(root: TreeNode) -> TreeNode:
"""
# 897: Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the
tree is now the root of the tree, and every node has no left child and only 1 right child.
"""
dummy = TreeNode(0)
curr = dummy
def inorder(node):
nonlocal curr
if not node:
return
inorder(node.left)
node.left = None
curr.right = node
curr = node
inorder(node.right)
inorder(root)
return dummy.right
if __name__ == "__main__":
# construct BST
n5 = TreeNode(4)
n4 = TreeNode(1)
n3 = TreeNode(3, left=n4, right=n5)
n2 = TreeNode(6)
n1 = TreeNode(5, left=n3, right=n2)
# construct expected BST
_n5 = TreeNode(6)
_n4 = TreeNode(5, right=_n5)
_n3 = TreeNode(4, right=_n4)
_n2 = TreeNode(3, right=_n3)
_n1 = TreeNode(1, right=_n2)
assert increasing_BST(n1) == _n1
print("Passed all tests!")
|
6ad7aeae0bb87aa6b43d4020a91b5b4d90986aa0 | DayDayGu/LeetCode | /344. Reverse String/xia.py | 372 | 3.625 | 4 | class Solution:
def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
len_str = len(s)
i = 0
while ( i < len_str // 2 ):
swap_index = len_str - i - 1
s[i], s[swap_index] = s[swap_index], s[i]
i += 1
|
282a32db61016f7f8daf6cfd3ac203cf740dba6e | albahnsen/pycircular | /pycircular/utils.py | 5,319 | 4.21875 | 4 | import numpy as np
import pandas as pd
def date2rad(dates, time_segment='hour'):
"""Convert hours to radians
Parameters
----------
dates : array-like of shape = [n_samples] of hours.
Where the decimal point represent minutes / 60 + seconds / 60 / 100 ...
0 <= times[:] <= 24
time_segment: string of values ['hour', 'dayweek', 'daymonth']
Returns
-------
radians : array-like of shape = [n_samples]
Calculated radians
Examples
--------
>>> import numpy as np
>>> from pycircular.utils import date2rad
>>> times = np.array([4, 6, 7])
>>> for time_segment in ['hour', 'dayweek', 'daymonth']:
>>> print(time_segment, date2rad(times, time_segment))
"""
if time_segment == 'hour':
radians = dates * 2 * np.pi / 24
# Fix to rotate the clock and move PI / 2
# https://en.wikipedia.org/wiki/Clock_angle_problem
radians = - radians + np.pi/2
elif time_segment == 'dayweek':
# Day of week goes counter-clockwise
radians = dates * 2 * np.pi / 7 + np.pi/2
elif time_segment == 'daymonth':
# Day of month goes counter-clockwise
radians = dates * 2 * np.pi / 31 + np.pi/2
# TODO: check what to do with last day of month
# Change to be in [0, 2*pi]
radians1 = []
for i in radians:
if(i<0):
radians1.append(i+2*np.pi)
elif(i>(2*np.pi)):
radians1.append(i-2*np.pi)
else:
radians1.append(i)
return radians1
def _date2rad(dates, time_segment='hour'):
"""Convert time_segment to radians
From pycircular.utils.date2rad and pycircular.utils.freq_time
Parameters
----------
dates : pandas DatetimeIndex array-like of shape = [n_samples] of dates.
time_segment: string of values ['hour', 'dayweek', 'daymonth']
Returns
-------
radians : array-like of shape = [n_samples]
Calculated radians
"""
# calculate times
times = dates.dt.hour + dates.dt.minute / 60 + dates.dt.second / 60 / 60
# Change from 100 to 60, consistency for radians
if time_segment == 'hour':
radians = times * 2 * np.pi / 24
# Fix to rotate the clock and move PI / 2
# https://en.wikipedia.org/wiki/Clock_angle_problem
radians = - radians + np.pi/2
elif time_segment == 'dayweek':
time_temp = dates.dt.dayofweek # Monday=0, Sunday=6
times = time_temp + times / 24
# Day of week goes counter-clockwise
radians = times * 2 * np.pi / 7 + np.pi/2
elif time_segment == 'daymonth':
time_temp = dates.dt.day
times = time_temp + times / 24
# Day of month goes counter-clockwise
radians = times * 2 * np.pi / 31 + np.pi/2
# TODO: check what to do with last day of month
# Change to be in range [0, 2*pi]
if hasattr(radians, 'shape'):
# Check if an array
radians.loc[radians < 0] += 2 * np.pi
radians.loc[radians > 2 * np.pi] -= 2 * np.pi
else:
# If it is a scalar
if radians < 0:
radians += 2 * np.pi
elif radians > 2 * np.pi:
radians -= 2 * np.pi
return radians
def freq_time(dates, time_segment='hour', freq=True, continious=True):
"""Calculate frequency per time period and calculate continius time period
Parameters
----------
dates : array-like of shape = [n_samples] of dates in format 'datetime64[ns]'.
time_segment: string of values ['hour', 'dayweek', 'daymonth']
freq : Whether to return the frequencies
Returns
-------
freq_arr : array-like of shape = [unique_time_segment, 2]
where: freq_arr[:, 0] = unique_time_segment
freq_arr[:, 1] = frequency in percentage
times : array-like of shape = [n_samples]
Where the decimal point represent minutes / hours depending on time_segment
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> from pycircular.utils import freq_time
>>> dates = pd.to_datetime(["2013-10-02 19:10:00", "2013-10-21 19:00:00", "2013-10-24 3:00:00"])
>>> for time_segment in ['hour', 'dayweek', 'daymonth']:
>>> print(time_segment)
>>> freq_arr, times = freq_time(dates, time_segment=time_segment)
>>> print(freq_arr)
>>> print(times)
"""
# Get frequency per time_segment
dates_index = pd.DatetimeIndex(dates)
# calculate times
times = dates_index.hour + dates_index.minute / 60 + dates_index.second / 60 / 100
if time_segment == 'hour':
time_temp = dates_index.hour
elif time_segment == 'dayweek':
time_temp = dates_index.dayofweek # Monday=0, Sunday=6
times = time_temp + times / 24
elif time_segment == 'daymonth':
time_temp = dates_index.day
times = time_temp + times / 24
freq_arr = None
if freq:
freq_ = pd.Series(time_temp).value_counts()
freq_ = freq_ / freq_.sum()
freq_arr = np.zeros((freq_.shape[0], 2)) # Hour, freq
freq_arr[:, 0] = freq_.index
freq_arr[:, 1] = freq_.values
if continious:
return freq_arr, times
else:
return freq_arr, time_temp
|
572166b6a02c7f355aaa78677a8a69296d7367b4 | luisfbarajas/practicepython | /console/Numero-mayor-de-tres.py | 451 | 3.96875 | 4 | # Definir una función max_de_tres(), que tome tres números como argumentos y devuelva el mayor de ellos.
def takeANumber():
print('Enter a number: ')
return input()
def maxNumber(n1,n2,n3):
if n1>n2 and n1>n3:
return n1
elif n2>n2 and n2> n2:
return n2
else:
return n3
n1 = int(takeANumber())
n2 = int(takeANumber())
n3 = int(takeANumber())
print ('El número mayor es: '+ str(maxNumber(n1,n2,n3)))
|
9c23555626b99f28ea17c12e657738c12938f031 | ianmiell/lucid | /cron_reader | 2,250 | 3.8125 | 4 | #!/usr/bin/env python3
import sys
import time
import datetime
def usage():
print('An argument of the form HH:MM must be supplied within appropriate bounds (ie 00:00 - 23:59).')
sys.exit(1)
def main():
# Pick up argument 1 and split into HH and MM.
try:
arg = sys.argv[1].split(':')
if len(arg[0]) != 2 or len(arg[1]) != 2:
raise ValueError('')
current_hour = int(arg[0].lstrip('0').zfill(1))
current_minute = int(arg[1].lstrip('0').zfill(1))
except:
usage()
arg = None
# Check that the hours and minutes are within the appropriate values.
if current_hour > 23 or current_hour < 0 or current_minute > 59 or current_minute < 0:
usage()
# Get current time (clock seconds)
current = time.localtime()
# Get the 'current time' with the passed-in time.
current_tm = time.struct_time((current.tm_year, current.tm_mon, current.tm_mday, current_hour, current_minute, 0, current.tm_wday, current.tm_yday, current.tm_isdst))
tomorrow = datetime.date.today() + datetime.timedelta(days = 1)
tomorrow_tm = tomorrow.timetuple()
# For each line in stdin...
for line in sys.stdin:
line_elements = line.split(' ')
if len(line_elements) < 3:
continue
# Extract the times
minute = line_elements[0]
hour = line_elements[1]
command = ' '.join(line_elements[2:]).strip()
if minute == '*':
minute = list(range(0,60))
else:
minute = [int(minute),]
if hour == '*':
hour = list(range(0,24))
else:
hour = [int(hour),]
get_next_run(minute, hour, command, current_tm, tomorrow_tm)
def get_next_run(minute, hour, command, tm, tomorrow_tm):
for d in ('today', 'tomorrow'):
if d == 'today':
year = tm.tm_year
mon = tm.tm_mon
mday = tm.tm_mday
wday = tm.tm_wday
yday = tm.tm_yday
else:
year = tomorrow_tm.tm_year
mon = tomorrow_tm.tm_mon
mday = tomorrow_tm.tm_mday
wday = tomorrow_tm.tm_wday
yday = tomorrow_tm.tm_yday
for h in hour:
for m in minute:
# Calculate time
runtime = time.struct_time((year, mon, mday, h, m, 0, wday, yday, tm.tm_isdst))
# Is this in the future?
if runtime >= tm:
print(str(runtime.tm_hour) + ':' + str(runtime.tm_min).zfill(2) + ' ' + d + ' - ' + command)
# No need to continue - return.
return
main()
|
6b790a90077fd47b94fc97598691bd4253824c72 | aniruddhamurali/python-algorithms | /src/math/number-theory/primes/prime_sieve.py | 495 | 4.1875 | 4 | # Uses the Sieve of Eratosthenes to generate a list of primes below a number
def sieve(n):
"""Return a list of the primes below n."""
prime = [True] * n
result = [2]
append = result.append
sqrt_n = (int(n**.5) + 1) | 1 # ensure it's odd
for p in range(3, sqrt_n, 2):
if prime[p]:
append(p)
prime[p*p::2*p] = [False] * ((n-p*p-1) // (2*p) + 1)
for p in range(sqrt_n, n, 2):
if prime[p]:
append(p)
return result
|
d7e42005ea388211fc8e095696e10fece22c9c2b | H602602/AI-Python- | /session 6/P1.py | 407 | 4.1875 | 4 | a=10
if a>5 :
print(a,"Is greater than 5")
elif a<5 :
print(a,"Is less than 5")
elif a==10 :
print(a,"Is equal to 10")
else :
print(a,"Is not equal to 10")
# a=10
# if a>5 :
# print(a,"Is greater than 5")
# if a<5 :
# print(a,"Is less than 5")
# if a==10 :
# print(a,"Is equal to 10")
# if a<10:
# print(a,"Is less than 10")
|
5c9edc51e13252b9ca0a700fd91e5e52747b67b8 | MadhaviSattiraju/Python-coding | /primeno.py | 168 | 4.0625 | 4 | n=int(input("Enter a number"))
count=0
for i in range(1,n+1):
if n%i==0:
count+=1
if count==2:
print(n,'is prime')
else:
print(n,'is not a prime')
|
66e6fba3d331346d1e751304f7e1cbaae61dc0dc | UMBC-CMSC-671-F20/code | /ms3.py | 661 | 3.796875 | 4 | """ 3x3 magic square problem """
import constraint as c
p = c.Problem()
p.addVariables(range(0, 9), range(1, 9+1))
p.addConstraint(AllDifferentConstraint(), range(0, 9))
p.addConstraint(ExactSumConstraint(15), [0,4,8])
p.addConstraint(ExactSumConstraint(15), [2,4,6])
for row in range(3):
p.addConstraint(ExactSumConstraint(15),
[row*3+i for i in range(3)])
for col in range(3):
p.addConstraint(ExactSumConstraint(15),
[col+3*i for i in range(3)])
for s in p.getSolutions():
print()
for row in range(3):
for col in range(3):
print(s[row*3+col], end='')
print()
|
f0b1b37312a79a38af32bdb4237738d9b560a3fb | Aparna-Shankar/Python-Tutorial | /File Objects.py | 3,211 | 4.03125 | 4 | """
File Objects
******************************************************************************************************
Reading from files
******************************************************************************************************
"""
f = open('File_test.txt','r') # Here f is the file object
print(f.name) # prints the name of the file
print(f.mode) # prints the mode in which the file was opened
# f_contents = f.readline() # Reads the file line by line
# print(f_contents, end='') # end='' gets rid of the newline after reading each line
# f_contents = f.readline()
# print(f_contents, end='')
f_contents = f.read() # Reads the entire file
# print(f_contents)
"""
There is a limit to the number of files that can be opened simultaneously. So it is necessary
to close the file after we read it
"""
f.close()
print(f.closed) # to check if the file is closed
# print(f.read()) # cannot read the file when closed
"""
Using files with context managers. This will automatically close files
with open('File_test.txt','r') as f:
"""
# To read the entire file contents using for loop
# for line in f:
# print(line, end='')
# To read certain number of characters from the file
# size_to_read = 10
# f_contents = f.read(size_to_read)
# while len(f_contents) > 0:
# print(f_contents, end='')
# f_contents = f.read(size_to_read)
# print(f.tell()) # Tells the current postion after file read
# f.seek(0) # sets the cursor back to postion 0 of the file
"""
******************************************************************************************************
Writing to files
Opening the file in w mode overwrites it's contents
******************************************************************************************************
"""
# with open('File_test_w','w') as f:
# f.write('Test')
# f.seek(0)
# f.write('Rest')
# # Reading & Writing to files
# with open('File_test.txt','r') as rf:
# with open('File_test_w','w') as wf:
# for line in rf:
# wf.write(line)
# Writing to another file only if content matches the user's input
# Ask User for a list of 3 friends
# Tell user if friend present in file
# Write friend to file copy
rf = open('File_test.txt', 'r')
f_line = rf.readlines() #This returns the content of the file in the form of a list with a '\n'
rf.close()
new_line = [line.strip() for line in f_line]
friends = input('Enter 3 friend names separated by (,): ').split(',')
#The split function above also returns the string contents as a list
file_line_set = set(new_line)
friends_set = set(friends)
pos_present = file_line_set.intersection(friends_set)
wf = open('File_test_w.txt', 'w')
for pos in pos_present:
wf.write(f'{pos}\n')
print(f'{pos} is present in file!')
wf.close()
# # Writing image files in binary mode
# with open('watercolour.jpg','rb') as rf:
# with open('watercolour_copy.jpg','wb') as wf:
# for line in rf:
# wf.write(line)
# # Writing image files in binary mode in chunks
# with open('watercolour.jpg','rb') as rf:
# with open('watercolour_copy.jpg','wb') as wf:
# chunk_size = 4096
# rf_chunk = rf.read(chunk_size)
# while len(rf_chunk) > 0:
# wf.write(rf_chunk)
# rf_chunk = rf.read(chunk_size)
|
aa7ea8fc5291d423e6e13a27a717661ae8d8965e | the-strawman/cspath-datastructures-capstone-project | /Soho-Restaurants-master/script.py | 4,457 | 4.25 | 4 | from trie import Trie
from data import *
from welcome import *
from hashmap import HashMap
from linkedlist import LinkedList
# Printing the Welcome Message
print_welcome()
# Entering cuisine data
food_types = Trie()
eateries = HashMap(len(types))
for food in types:
food_types.add(food)
eateries.assign(food, LinkedList())
# restaurant data-point key names:
eatery_cuisine = "cuisine"
eatery_name = "name"
eatery_price = "price"
eatery_rating = "rating"
eatery_address = "address"
# Entering restaurant data
for restaurant in restaurant_data:
current_eateries_for_cuisine = eateries.retrieve(restaurant[0])
current_eatery_data = HashMap(len(restaurant))
current_eatery_data.assign(eatery_cuisine, restaurant[0])
current_eatery_data.assign(eatery_name, restaurant[1])
current_eatery_data.assign(eatery_price, restaurant[2])
current_eatery_data.assign(eatery_rating, restaurant[3])
current_eatery_data.assign(eatery_address, restaurant[4])
if current_eateries_for_cuisine.get_head_node().get_value() is None:
current_eateries_for_cuisine.get_head_node().value = current_eatery_data
else:
current_eateries_for_cuisine.insert_beginning(current_eatery_data)
# Begin user interaction logic
quit_code = "quit!"
def quit_sequence():
print("\nThanks for using SoHo Restaurants!")
exit()
intro_text = """
What type of food would you like to eat?
Type that food type (or the beginning of that food type) and press enter to see if it's here.
(Type \"{0}\" at any point to exit.)
""".format(quit_code)
partial_match_text = """
Type a number to select a corresponding cuisine.
Or type the beginning of your preferred cuisine to narrow down the options.
"""
while True:
# What cuisine are we looking for?
user_input = str(input(intro_text)).lower()
if user_input == quit_code:
quit_sequence()
# First try a full-text match
my_cuisine = food_types.get(user_input)
if not my_cuisine:
print("Couldn't find \"{0}\".".format(user_input.title()))
# if no match on full-text search, try prefix search
while not my_cuisine:
available_cuisines = food_types.find(user_input)
if not available_cuisines:
# a prefix search found nothing, so return the whole list of available cuisines
available_cuisines = food_types.find("")
print("Here is the list of available cuisines:\n")
else:
print("Here are some matches from the available cuisines:\n")
idx = 0
for cuisine in available_cuisines:
idx += 1
print("{0} - {1}".format(idx, cuisine.title()))
available_cuisines_response = input(partial_match_text)
if available_cuisines_response == quit_code:
quit_sequence()
# the user input could be an int or a str.
# try to process an int value, a ValueError exception indicates non-int input
try:
idx = int(available_cuisines_response) - 1
print("Search for {0} restaurants?".format(available_cuisines[idx].title()))
user_response = str(input("(Hit [enter]/[return] for 'yes'; type 'no' to perform a new search.) ")).lower()
if user_response == quit_code:
quit_sequence()
elif user_response in ["", "y", "yes", "[enter]", "[return]", "enter", "return"]:
my_cuisine = available_cuisines[idx]
else:
user_input = None
except ValueError:
available_cuisines_response = str(available_cuisines_response).lower()
my_cuisine = food_types.get(available_cuisines_response)
if not my_cuisine:
user_input = available_cuisines_response
# Now we have a cuisine, let's retrieve the restaurants & present the data
my_eateries = eateries.retrieve(my_cuisine)
current_node = my_eateries.get_head_node()
print("\n{} restauants in SoHo".format(my_cuisine.title()))
print("-"*20)
while current_node:
eatery = current_node.get_value()
print('{:<14}{}'.format("Restaurant:", eatery.retrieve(eatery_name)))
print("{:<14}{}".format("Price:", "$" * int(eatery.retrieve(eatery_price))))
print("{:<14}{}".format("Rating:", "*" * int(eatery.retrieve(eatery_rating))))
print("{:<14}{}".format("Address:", eatery.retrieve(eatery_address)))
print("-"*20)
current_node = current_node.get_next_node()
user_response = str(input("\nWould you like to look for restaurants matching a different cuisine? ")).lower()
if user_response in ["n", "no", "q", "quit", "x", "exit", quit_code]:
quit_sequence()
|
807892fdfb7de4451753eac1104445d1185730ca | asimali5/asimali | /PycharmProjects/Loops/check.py | 736 | 3.90625 | 4 |
def print_word():
ar=[]
ar3={}
with open('bc.txt')as file_object:
contents=file_object.read()
for word in contents.split():
if word in ar:
continue
else:
counter=0
fl=len(contents.split())
for word2 in contents.split():
if word.lower()==word2.lower():
counter=counter+1
if word not in ar:
ar.append(word)
ar3.update({word.lower():counter})#code append on 11-16-2017 wednesday#
a3=sorted(ar3.items()) # Printing keys in sorted orders
for k,v in a3:# Printing keys wise in asc sorted orders ///comment on 11-17
print(k,v)# Printing keys,values in sorted orders ///comment on 11-17
print_word() |
17c7cc996f2edd6ce3d18f23e238c3ffc386254c | vxiaohan/LeetCodeProblems | /3_LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.py | 972 | 3.859375 | 4 | import unittest
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
stringList = list(s)
stringLength = len(stringList)
if stringLength == 0:
return 0
maxLength = 0
headIndex = 0
while headIndex + maxLength + 1 <= stringLength:
subList = stringList[headIndex:headIndex+maxLength+1]
subDic = set(subList)
if len(subDic) == len(subList):
maxLength += 1
else:
headIndex += 1
return maxLength
class LongestSubstringTestCase(unittest.TestCase):
def test_longest(self):
test = Solution()
self.assertEqual(test.lengthOfLongestSubstring('b'),1)
self.assertEqual(test.lengthOfLongestSubstring('ab'), 2)
self.assertEqual(test.lengthOfLongestSubstring('aaaabbbbb'), 2)
if __name__ == '__main__':
unittest.main()
|
6e763d69c805fdcd1159590918179b4c01aafc04 | cunhasb/Data-Structures-Python- | /linked-list/test-linked-list.py | 2,109 | 3.875 | 4 | import linked_list
import unittest
class TestGetPosition(unittest.TestCase):
"""
Test the get_position function from the linkedlist library
"""
def test_get_position(self):
"""
print (ll.get_position(3).value)
Test that the invoking get_position(3) will return the correct value
"""
# Set up some Elements
e1 = linked_list.Element(1)
e2 = linked_list.Element(2)
e3 = linked_list.Element(3)
e4 = linked_list.Element(4)
# Start setting up a LinkedList
ll = linked_list.LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Test
result = ll.get_position(3).value
self.assertEqual(result, 3)
# Test insert
def test_insert(self):
"""
Should insert element into position, should print 4
"""
# Set up some Elements
e1 = linked_list.Element(1)
e2 = linked_list.Element(2)
e3 = linked_list.Element(3)
e4 = linked_list.Element(4)
# Start setting up a LinkedList
ll = linked_list.LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Test
ll.insert(e4, 3)
result = ll.get_position(3).value
self.assertEqual(result, 4)
# Test delete
def test_delete(self):
"""
Should delete an element from the LinkedList, should print 2
"""
# Set up some Elements
e1 = linked_list.Element(1)
e2 = linked_list.Element(2)
e3 = linked_list.Element(3)
e4 = linked_list.Element(4)
# Start setting up a LinkedList
ll = linked_list.LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Insert Element
ll.insert(e4, 3)
# Delete Element
ll.delete(1)
# Test
result = ll.get_position(1).value
self.assertEqual(result, 2)
result = ll.get_position(2).value
self.assertEqual(result, 4)
result = ll.get_position(3).value
self.assertEqual(result, 3)
if __name__ == '__main__':
unittest.main()
|
c3854622cc23fadd15c6213339730c2fbbe531fa | scottenriquez/wiki-depth | /depth_search.py | 3,016 | 3.703125 | 4 | import threading
import wikipedia
MAX_THREADS = 125
def depth_search(user_start_page, depth_row, target_page, pages_hit, depth):
"""
#user_start_page: the Wikipedia page instantiated from the user's command line arguments
#depth_row: a list of links to all Wikipedia pages in a given depth
#target_page: the Wikipedia page instantiated from the user's command line arguments
#pages_hit: a hash map used to keep track of pages already seen
#depth: an integer value representing the current depth
Method that searches through all paths of one depth for descending
"""
# check if the target page is the current depth
global MAX_THREADS
if found_in_current_depth(depth_row, target_page):
print("Found the target page \"" + target_page.title + "\" at a depth of " + str(
depth) + " from \"" + user_start_page.title + "\"")
return depth
print("Target page not found at depth " + str(depth))
print("Building new search...")
thread_list = []
next_depth_row = []
# iterate the page links for the current depth
for link in depth_row:
# check if already seen
if link not in pages_hit:
if len(thread_list) <= MAX_THREADS:
new_thread = threading.Thread(target=build_next_depth, args=(link, next_depth_row, pages_hit, depth))
thread_list.append(new_thread)
else:
for thread in thread_list: thread.start()
for thread in thread_list: thread.join()
thread_list = []
# start and join threads, start depth search on next depthSearch
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
depth_search(user_start_page, next_depth_row, target_page, pages_hit, depth + 1)
def found_in_current_depth(current_depth_row, target_page):
"""
#current_depth_row: a list of titles that reference Wikipedia articles
#target_page: the Wikipedia page instantiated from the user's command line arguments
Determines whether or not the target page is in the current depth
"""
return target_page.title in current_depth_row
def build_next_depth(link, next_depth_row, pages_hit, depth):
"""
#link: the current page link
#next_depth_row: the list of pages to search in the next depth
#pages_hit: the hash table containing the pages already visited
Obtains the pages links from the Wikipedia API
"""
print("Searching the \"" + link + "\" page at depth " + str(depth))
pages_hit[link] = 1
# build the next depth's link list
get_links_for_search_terms(wikipedia.search(link), next_depth_row)
return
def get_links_for_search_terms(results, depth_row):
"""
#results: the output of a wikipedia.search() call
#depth_row: links for the current row
Encodes the search results and generates a list
"""
for page in results:
depth_row.append(page.encode("utf-8"))
return
|
65264806184c94c816974e103795c6c260b8bbd6 | kkaya10/Python_Examples | /port_scanner.py | 774 | 3.734375 | 4 | import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target = input("[+] Enter Target IP: ")
port_list = list()
def scanner(port):
try:
sock.connect((target, port))
return True
except:
return False
while True:
target_ports = int(input("[+] Type port numbers which you want to scan , type 0 to exit !"))
if target_ports != 0:
port_list.append(target_ports)
elif target_ports == 0:
break
for portNumber in range(1,len(port_list)):
print("Scanning port", port_list[portNumber])
if scanner(port_list[portNumber]):
print('[*] Port', port_list[portNumber], '/tcp','is open')
else:
print('[*] Port', port_list[portNumber], '/tcp','is closed')
|
d013a491e2138eeffbeb61188af604d142a96f93 | joshmurr/text_encoder | /text_encryptor.py | 1,564 | 3.953125 | 4 | #!/uer/bin/python
# -*- coding: utf-8 -*-
# Text Encryptor -- by Josh Murr
from random import randint
everything = []
def makeEverything():
for i in range(32,127):
everything.append(chr(i))
def generateKey(a, n):
key = []
for i in range(n):
key.append(ord(a[randint(0,len(a)-1)])-32)
return key
def convertKey(key):
converted = []
for i in range(len(key)):
converted.append(chr(key[i]+32))
converted = "".join(converted)
return converted
def encrypt(word, key):
encryption = []
final = []
for i in range(len(word)):
encryption.append(ord(word[i])-32)
for i in range(len(encryption)):
encryption[i] += key[i]
encryption[i] %= len(everything)
encryption[i] = chr(encryption[i]+32)
return "".join(encryption)
def decrypt(eText, key):
encryptedText = []
final = []
thisKey = key
for i in range(len(eText)):
encryptedText.append(ord(eText[i])-32)
for i in range(len(encryptedText)):
new = encryptedText[i]-thisKey[i]
new %= len(everything)
final.append(chr(new+32))
return "".join(final)
def main():
makeEverything()
word = raw_input('Enter some text to encrypt: ')
key = generateKey(everything, len(word))
encryption = encrypt(word, key)
ck = convertKey(key)
decryptedText = decrypt(encryption, key)
print "Text = " + word
print "Key = " + ck
print "Encryption = " + encryption
print "Decrypted text = " + decryptedText
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.