blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e58e7d318e7030a8502e892cbd81afeb45058112 | starmap0312/refactoring | /making_method_calls_simpler/replace_parameter_with_method.py | 1,891 | 3.984375 | 4 | # - if a parameter can be obtained by invoking a method, and the receiver function can also
# invoke the method, then remove the parameter, and let the receiver function invoke the
# method itself(reduce the parameter list size)
# - methods with short parameter list are easier to understand
# before
class Product(object):
def __init__(self, quantity, itemPrice):
self._quantity = quantity
self._itemPrice = itemPrice
def getPrice(self):
basePrice = self._quantity * self._itemPrice # a temp variable used as a parameter
if self._quantity > 100:
discountLevel = 2 # a temp variable used as a parameter
else:
discountLevel = 1
# the method depends on two parameters
finalPrice = self.discountedPrice(basePrice, discountLevel) # a temp variable
return finalPrice
def discountedPrice(self, basePrice, discountLevel):
# the method can get both parameters by itself, so try to remove the parameters
if discountLevel == 2:
return basePrice * 0.1
else:
return basePrice * 0.05
print Product(80, 100.0).getPrice()
# after
class NewProduct(object):
def __init__(self, quantity, itemPrice):
self._quantity = quantity
self._itemPrice = itemPrice
def getBasePrice(self):
# replace parameter with method
return self._quantity * self._itemPrice
def getDiscountedLevel(self):
# replace parameter with method
return 2 if self._quantity > 100 else 1
def getPrice(self):
# both parameters are removed and replaced with methods
# the method get the parameters by methods instead
if self.getDiscountedLevel() == 2:
return self.getBasePrice() * 0.1
else:
return self.getBasePrice() * 0.05
print NewProduct(80, 100.0).getPrice()
|
1bd4590a0e9042a54501b9004c188571bcb832e7 | msc-jinal/rosalind_python | /printformat.py | 259 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 10:30:43 2018
@author: User
"""
from collections import defaultdict
def funt1():
return 'Hari'
myd = defaultdict(int)
myd['a']=1
myd['b']=5
print ("%s - %s %d.%d" % ('Hari','Jinal',50,90)) |
4503bb7b06c1704d19be9af9043910666a2f25e8 | dmvincent/HackerRank | /Python3/Loops/loops.py | 109 | 3.53125 | 4 | #!/usr/bin/python3
if __name__ == '__main__':
n = int(input())
i = 0
while i < n:
print(i**2)
i+=1
|
f28330315c8371cb2714482bb6739bb4855d23ff | rafaelperazzo/programacao-web | /moodledata/vpl_data/398/usersdata/299/81325/submittedfiles/av1_programa2.py | 345 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import math
#COMECE SEU CÓDIGO ABAIXO DESTA LINHA
a=int(input('1:')
b=int(input('2:')
c=int(input('3:')
d=int(input('4:')
e=int(input('5:')
f=int(input('6:')
if a<b and b<c and c<d and d<e and e<f:
print('C')
elif a>b and b>c and c>d and d>e and e>f:
print('D')
else:
print('N') |
30b734ec58ecb08a5dd213a71e931af389ca44fd | ccuwxy/learn_python_code | /python入门/_02_分支/03_逻辑运算演练.py | 93 | 3.84375 | 4 | age = int(input("age:"))
if age >= 0 and age <=120:
print("ok")
else:
print("error!") |
c3f6b71a424eb84b006c6581d815eb638f3092b3 | Sasha1505-ctrl/Testing_task | /String30.py | 674 | 3.921875 | 4 | print("Дан символ C и строки S, S0. После каждого вхождения символа C в строку S вставить строку S0.")
c = input("Введите символ C\n")
def string30(C, S=input("Введите строку S\n"), S0=input("Введите строку S0\n")):
assert len(C) == 1, "Введите не строку, символ"
assert len(S) > 1, "Введите не пустую строку и не символ"
assert len(S0) > 1, "Введите не пустую строку и не символ"
for i in range(len(S)):
if C in S[i]:
print(S0)
print(string30(c))
|
de88cec972b3a047f45f5caeb82ac6b7849d4a62 | felixdittrich92/Python3 | /6_ObjectOriented/exceptions.py | 3,160 | 3.71875 | 4 | import numbers
import builtins
from math import sqrt
from functools import total_ordering
@total_ordering
class Vector2D:
def __init__(self, x=0, y=0):
if isinstance(x, numbers.Real) and isinstance(y, numbers.Real): # Numbers.Real = reele Zahl
self.x = x
self.y = y
else:
raise TypeError('You must pass in int/float values for x and y!') # welche Exception geworfen werden soll
def __call__(self):
print("Calling the __call__ function!")
return self.__repr__()
def __repr__(self):
return 'vector.Vector2D({}, {})'.format(self.x, self.y)
def __str__(self):
return '({}, {})'.format(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __abs__(self):
return sqrt(pow(self.x, 2) + pow(self.y, 2))
def check_vector_types(self, vector2):
if not isinstance(self, Vector2D) or not isinstance(vector2, Vector2D):
raise TypeError('You have to pass in two instances of the vector class!')
def __eq__(self, other_vector):
self.check_vector_types(other_vector) # überprüfen ob Vector
if self.x == other_vector.x and self.y == other_vector.y:
return True
else:
return False
def __lt__(self, other_vector):
self.check_vector_types(other_vector) # überprüfen ob Vector
if abs(self) < abs(other_vector):
return True
else:
return False
def __add__(self, other_vector):
self.check_vector_types(other_vector) # überprüfen ob Vector
x = self.x + other_vector.x
y = self.y + other_vector.y
return Vector2D(x, y)
# try (== 1):
# except (>= 1):
# finally (optional):
def __sub__(self, other_vector):
try:
x = self.x - other_vector.x
y = self.y - other_vector.y
return Vector2D(x, y)
except AttributeError as e:
print("AttributeError: {} was raised!".format(e))
return self
except Exception as e:
print("Exception {}: {} was raised!".format(type(e), e))
finally: # wird immer am Schluss ausgeführt
print("finally")
def __mul__(self, other):
if isinstance(other, Vector2D):
return self.x * other.x + self.y * other.y
elif isinstance(other, numbers.Real):
return Vector2D(self.x * other, self.y * other)
else:
raise TypeError('You must pass in a vector instance or an int/float number!')
def __truediv__(self, other):
if isinstance(other, numbers.Real):
if other != 0.0:
return Vector2D(self.x / other, self.y / other)
else:
raise ValueError('You cannot divide by zero!') # Werterror wenn 0
else:
raise TypeError('You must pass in an int/float value!')
# alle Exceptions
builtin_list = [builtin for builtin in dir(builtins) if 'Error' in builtin]
print(builtin_list)
print('\n')
v1 = Vector2D(3, 2)
v2 = Vector2D(1, 2)
print(v1 - 2)
# v3 = Vector2D('S', 'e') |
cfa9e1f63e894225d5b322b665056418650076cc | liush79/snippets | /thread/thread_callback.py | 1,203 | 3.546875 | 4 | import threading
class CallbackThread(threading.Thread):
def __init__(self, target, target_args=None,
callback=None, callback_args=None, *args, **kwargs):
super(CallbackThread, self).__init__(target=self.target_wrapper, *args, **kwargs)
self.target_method = target
self.callback = callback
self.callback_args = callback_args
self.target_args = target_args
def target_wrapper(self):
self.target_method(*self.target_args)
if self.callback:
self.callback(*self.callback_args)
# example
if __name__ == '__main__':
import time
def my_work(param1, param2):
print("Do my work - start ({}, {})".format(param1, param2))
for i in range(1, 6):
print('Working.. %d/5' % i)
time.sleep(1)
print("Do my work - end")
def my_callback(param1, param2):
print("My callback is called ({}, {})".format(param1, param2))
thread = CallbackThread(target=my_work,
target_args=('target', 12345),
callback=my_callback,
callback_args=('callback', 67890))
thread.start()
|
7f09dd0960a504eab60f682eb455c9d60e4753dd | melvinanthonyrancap/Exercises-for-Programmers-57-Challenges-Python | /Answers/exercise18.py | 1,399 | 4.46875 | 4 | import os
os.system('cls')
print("Press C to convert from Fahrenheit to Celsius." \
"\nPress F to convert from Celsius to Fahrenheit.")
user_input = input("Your choice: ")
if user_input.lower() == "c":
temperature = int(input("Please enter the temperature in Fahrenheit: "))
celsius = (temperature - 32) * (5/9)
print(f"The temperature is Celsius is {celsius}.")
elif user_input.lower() == "f":
temperature = int(input("Please enter the temperature in Celsius: "))
fahrenheit = ((temperature * (9/5)) + 32)
print(f"The temperature in Fahrenheit is {fahrenheit}")
else:
print("Not a Valid Choice.")
"""
Temperature Converter
You’ll often need to determine which part of a program is
run based on user input or other events.
Create a program that converts temperatures from Fahrenheit
to Celsius or from Celsius to Fahrenheit. Prompt for the
starting temperature. The program should prompt for the
type of conversion and then perform the conversion.
The formulas are
C = (F − 32) × 5 / 9
and
F = (C × 9 / 5) + 32
Example Output
Press C to convert from Fahrenheit to Celsius.
Press F to convert from Celsius to Fahrenheit.
Your choice: C
Please enter the temperature in Fahrenheit: 32
The temperature in Celsius is 0.
Constraints
• Ensure that you allow upper or lowercase values for C
and F.
• Use as few output statements as possible and avoid
repeating output strings.
""" |
a21425171e24ea71602053ef2b7d7e8a47e19d87 | kcarr/party-2020 | /main.py | 3,879 | 3.546875 | 4 | # Import the pygame module
import pygame
from pygame.sprite import RenderUpdates
from pygame.locals import (
K_ESCAPE,
KEYDOWN,
K_DOWN,
QUIT,
)
from modules.game_play import GamePlay
from modules.game_play import GameMode
from modules.ui_elements import UIElement
from constants import (
SCREEN_WIDTH,
SCREEN_HEIGHT,
TITLE_SCREEN_COLOR,
TITLE_TEXT_COLOR,
)
def main():
# Initialize pygame
pygame.init()
# Create the screen object
# The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Set the background color
screen.fill(TITLE_SCREEN_COLOR)
pygame.display.flip()
# Start the game mode at the title screen
game_mode = GameMode.TITLE_SCREEN
# Initialize the game playing
game_play = GamePlay(screen)
# Set high score
high_score = 0
while game_mode != GameMode.QUIT:
if game_mode == GameMode.TITLE_SCREEN:
game_mode = title_screen(screen)
if game_mode == GameMode.GAME_SCREEN:
game_mode = game_play.playing(screen)
def title_screen(screen, player=False):
# Make a Title that is a "button"
game_title = UIElement(
center_position=(400, 200),
font_size=100,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="Party 2020!",
reactive=False,
)
# Make the start "button"
start_button = UIElement(
center_position=(400, 400),
font_size=50,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="START",
action=GameMode.GAME_SCREEN,
)
# Make the quit "button"
quit_button = UIElement(
center_position=(400, 450),
font_size=30,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="QUIT",
action=GameMode.QUIT,
)
# Make a description that is a "button"
desc1 = UIElement(
center_position=(400, 525),
font_size=15,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="Avoid the virus",
reactive=False,
)
# Make a description that is a "button"
desc2 = UIElement(
center_position=(400, 540),
font_size=15,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="Masks will save you if you're exposed to the virus",
reactive=False,
)
# Make a description that is a "button"
desc3 = UIElement(
center_position=(400, 555),
font_size=15,
bg_rgb=TITLE_SCREEN_COLOR,
text_rgb=TITLE_TEXT_COLOR,
text="Catch toilet paper",
reactive=False,
)
buttons = RenderUpdates(game_title, start_button, quit_button, desc1, desc2, desc3)
return title_loop(screen, buttons, fill=TITLE_SCREEN_COLOR)
def title_loop(screen, buttons, fill=(255,255,255)):
looping = True
while looping:
mouse_up = False
for event in pygame.event.get():
# Did the user click the window close button? If so, stop the loop
if event.type == QUIT:
return GameMode.QUIT
# Did the user hit a key?
if event.type == KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
return GameMode.QUIT
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouse_up = True
screen.fill(fill)
for button in buttons:
ui_action = button.update(pygame.mouse.get_pos(), mouse_up)
if ui_action is not None:
return ui_action
buttons.draw(screen)
pygame.display.flip()
if __name__ == "__main__":
main() |
f432758dc07ef6a972d5ec4ad238398007978a0c | AbhijnaDasam/pycbit-hackathon | /3_list.py | 356 | 3.59375 | 4 | list1=["Ron","Hermione","Harry","Professor","Dobby","List Items 2","The House Elf","Potter","Granger","Lockhart","Weasley"]
list2=["Potter","Fred","Greg","George","Voldemort","Sirius","Dumbledore"]
temp=""
l=len(list1)
for i in range(0,l-1):
for j in range(0,l-i-1):
if list1[j]>list1[j+1]:
list1[j],list1[j+1]=list1[j+1],list1[j]
print(list1+list2)
|
5a7646c804b50563fc086d905f0422a5d16fdad1 | highheaven15/Python-Algorithm-DataStructure | /1과/03. 조건문(if분기문, 다중if문).py | 724 | 4.0625 | 4 | 3. 조건문(if분기문, 다중if문)
조건문 if(분기, 중첩)
#같다 ==, 같지 않다 !=
x=7
if x==7:
print("Lucky")
print("ㅋㅋ")
x=15
if x>=10:
if x%2==1:
print("10이상의 홀수")
x=9
if x>0:
if x<10:
print("10보다 작은 자연수")
x=7
if x>0 and x<10:
print("10보다 작은 자연수")
#파이썬은 이렇게도 가능하다
x=7
if 0<x<10:
print("10보다 작은 자연수")
#if, else, elif
x=10
if x>0:
print("양수")
else:
print("음수")
x=93
if x>=90:
print('A')
elif x>=80:
print('B')
elif x>=70:
print('C')
elif x>=60:
print('D')
else:
print('F')
|
8688fb58085cbeaf46fbb0ef7cf9e30905a797e3 | Lordjiggyx/PythonPractice | /Basics/Print.py | 1,512 | 4.46875 | 4 | #use the print() method to display somthing in the terminal
print("Hello World")
#Like java you can concatenate strings in this method
print("Hello" + " Tomi" + " welcome to python")
#If you want to concatenate numbers in a print() expression wrap the number in str()
#str is used to convert an object into a string
print("2+3 = " + str(2+3))
#Print can take in a anything regardless of the data type
#Print() is a method meaning it can take in it's own arguments each seprated with a comma what it does is that it calls str() on every argument treating it as a string and also adds a space between each atrgument
print("Tomi did you know that", "2 + 3 =", 5)
#You can pass in sep as an argument which stands for seperator this allows you determine how you want to join items in a print method or assign spaces
#sep comes between elements not around them so be able to account for this
print("hello" , "world" , sep="\n")
print("home","user","documents", sep="/")
print('node', 'child', 'child', sep=' -> ')
#We can use the end arguement in order to prevent linebreaks this argument dictates what we end the line with in this example you can see that after the first print happens ok comes on the same line showing that we ended the line with an empty space
print("Checking file progres....", end="")
print("ok")
#Sep and End can be used together
print('Mercury', 'Venus', 'Earth', sep=', ', end=', ')
print('Mars', 'Jupiter', 'Saturn', sep=', ', end=', ')
print('Uranus', 'Neptune', 'Pluto', sep=', ') |
5f90f77f35c6a3d96ecd061e29dd76423c75cdfc | Qleoz12/UVA-Problems | /ink2.py | 4,050 | 3.59375 | 4 | '''
Pontificia Universidad Javeriana Cali
Final project of 'Analisis y Diseño de Algoritmos' - 2017-1
Student: Daniel Cano Salgado
Code: 1872525
Commitment sentence:
"Como miembro de la comunidad académica de la Pontificia Universidad Javeriana Cali me comprometo
a seguir los más altos estándares de integridad académica."
UVA Problem - 11665 Chinese Ink
'''
from sys import stdin
INF = 10**5
class dforest(object):
def __init__(self,size=100):
"""Creates a empty disjoint forest"""
self.__parent = [ i for i in range(size) ]
self.__size = [ 1 for i in range(size) ]
self.__rank = [ 0 for i in range(size) ]
def __len__(self):
"""Return the number of elements of the forest"""
return len(self.__parent)
def __contains__(self,x):
"""Tells if an element x is in the forest"""
return 0 <= x < len(self)
def find(self,x):
"""Returns the class index of the tree where x belongs"""
assert x in self
if self.__parent[x]!=x:
self.__parent[x] = self.find(self.__parent[x])
return self.__parent[x]
def union(self,x,y):
"""Makes the union between 2 trees"""
assert x in self and y in self
rx,ry = self.find(x),self.find(y)
if rx!=ry:
nx,ny = self.__rank[rx],self.__rank[ry]
if nx<=ny:
self.__parent[rx] = ry
self.__size[ry] += self.__size[rx]
if nx==ny: self.__rank[ry]+=1
else:
self.__parent[ry] = rx
self.__size[rx] += self.__size[ry]
def size(self,x):
"""Returns the size of a tree"""
assert x in self
return self.__size[self.find(x)]
class vertex(object):
def __init__(self,x,y):
"""Creates a dot in 2D with coordinates (x,y)"""
self.x = x
self.y = y
def pointInSegment(p,q,r):
"""Tells if a point r is in |p,q|"""
if (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y)):
return True
return False
def orientation(p,q,r):
"""Given 3 points, tells if they are oriented clockwise, counter-clockwise or if they are collinear"""
val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
if val == 0: return 0
return 1 if val > 0 else 2
def segmentIntersect(a1,a2,b1,b2):
"""Tells if segment |a1,a2| intersects with |b1,b2|"""
o1 = orientation(a1, a2, b1)
o2 = orientation(a1, a2, b2)
o3 = orientation(b1, b2, a1)
o4 = orientation(b1, b2, a2)
if o1 != o2 and o3 != o4:return True
if o1 == 0 and pointInSegment(a1, b1, a2):return True
if o2 == 0 and pointInSegment(a1, b2, a2):return True
if o3 == 0 and pointInSegment(b1, a1, b2):return True
if o4 == 0 and pointInSegment(b1, a2, b2):return True
return False
def polygonContention(polygon,x):
"""Tells if a point x is inside a polygon"""
count,verInf = 0,vertex(x.x,INF)
for i in range(0,len(polygon)-1):
if segmentIntersect(polygon[i],polygon[i+1],x,verInf) and count<2: count+=1
return True if count == 1 else False
def solve(N,polygons):
ans,p1,df = 0,0,dforest(N)
while p1 != N-1:
p2 = p1+1
while p2 != N:
root1,root2 = df.find(p1),df.find(p2)
if root1 != root2:
intersection,contain,i = False,False,0
while i <= len(polygons[p1])-2 and intersection == False:
j = 0
while j <= len(polygons[p2])-2 and intersection == False:
intersection = segmentIntersect(polygons[p1][i],polygons[p1][i+1],polygons[p2][j],polygons[p2][j+1])
j+=1
i+=1
if intersection == False:
contain = polygonContention(polygons[p1],polygons[p2][0]) or polygonContention(polygons[p2],polygons[p1][0])
if intersection or contain:
df.union(p1,p2)
ans+=1
p2+=1
p1+=1
return N-ans
def main():
inp = stdin
N,ans = int(inp.readline().strip()),[]
while N != 0:
polygons,n = [],N
while n > 0:
line = inp.readline().strip().split()
p = [vertex(int(line[x]),int(line[x+1])) for x in range(0,len(line)-1,2)]
p.append(p[0])
polygons.append(p)
n-=1
ans.append(str(solve(N,polygons)))
N = int(inp.readline().strip())
print('\n'.join(ans))
main() |
3832d7c976dc18e1bfd61457ca8904eb637c7945 | ggodol/Python_RPA | /1_excel/4_open_file.py | 577 | 3.640625 | 4 | """
6. 파일 열기
https://youtu.be/exgO1LFl9x8?t=2077
"""
from openpyxl import load_workbook # 파일 불러 오기
wb = load_workbook("sample.xlsx") # sample.xlsx 파일에서 wb 을 불러옴
ws = wb.active # 활성화된 sheet
# cell 데이터 불러오기
# for x in range(1,11):
# for y in range(1,11):
# print(ws.cell(row=x, column=y).value, end=" ") # 1 2 3 4
# print()
# cell 갯수를 모를 때
for x in range(1,ws.max_row + 1):
for y in range(1,ws.max_column + 1):
print(ws.cell(row=x, column=y).value, end=" ") # 1 2 3 4
print() |
6d3b674fddfd6bb611656711ca21945ac2000727 | dersonf/aulaemvideo | /exercicios/ex102.py | 140 | 4 | 4 | #!/usr/bin/python36
def factorial(n, show=0, return=0):
if n = 0
return '1'
print(factorial(int(input('Digite um valor: '))))
|
42e719feeaab83c9967b516c9bbf823c2b4318d7 | glorilia/coffee-project | /model.py | 4,965 | 3.765625 | 4 | """ Models for Coffee Project App """
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
# Create a SQLAlchemy object named db
db = SQLAlchemy()
#********* Data model classes for the db (SQLAlchemy object) ***************#
class User(db.Model):
"""A user."""
__tablename__ = 'users'
user_id = db.Column(db.Integer,
autoincrement=True,
primary_key=True)
email = db.Column(db.String,
unique=True,
nullable=False)
password = db.Column(db.String,
nullable=False)
lat = db.Column(db.Float)
lng = db.Column(db.Float)
# Relationships
user_features = db.relationship('UserFeature')
def __repr__(self):
return f'<User email={self.email} user_id={self.user_id}>'
class Shop(db.Model):
"""A coffee shop."""
__tablename__ = 'shops'
# The place_id (shop_id in here), name, and address columns will come from
# information obtained from the Google Maps API
shop_id = db.Column(db.String,
primary_key=True)
name = db.Column(db.String) # Not unique, shops can have many locations
address_num = db.Column(db.Integer)
address_street = db.Column(db.String)
zipcode = db.Column(db.String)
lat = db.Column(db.Float)
lng = db.Column(db.Float)
# Relationships
user_features = db.relationship('UserFeature')
def __repr__(self):
return f'<Shop name={self.name} address={self.address_num} {self.address_street}>'
# repr doesn't include shop_id (place_id) bc it can be veeerryy long
class Type(db.Model):
"""A type of feature, usually drink or aspect"""
__tablename__ = "types"
type_id = db.Column(db.Integer,
primary_key=True,
autoincrement=True)
name = db.Column(db.String,
nullable=False)
# Relationships
features = db.relationship('Feature')
def __repr__(self):
return f'<Type name={self.name} type_id={self.type_id}>'
class Feature(db.Model):
"""A feature, like a latte, or privacy."""
__tablename__ = "features"
feature_id = db.Column(db.Integer,
primary_key=True,
autoincrement=True)
name = db.Column(db.String,
unique=True,
nullable=False)
type_id = db.Column(db.Integer,
db.ForeignKey('types.type_id'),
nullable=False)
description = db.Column(db.String,
nullable=False)
# Relationships
type = db.relationship('Type')
user_features = db.relationship('UserFeature')
def __repr__(self):
return f'<Feature name={self.name} feature_id={self.feature_id}>'
class UserFeature(db.Model):
"""A drink a user has added."""
__tablename__ = "user_features"
user_feature_id = db.Column(db.Integer,
autoincrement=True,
primary_key=True)
user_id = db.Column(db.Integer,
db.ForeignKey('users.user_id'),
nullable=False)
feature_id = db.Column(db.Integer,
db.ForeignKey('features.feature_id'),
nullable=False)
shop_id = db.Column(db.String,
db.ForeignKey('shops.shop_id'),
nullable=False)
details = db.Column(db.String,
nullable=False)
nickname = db.Column(db.String)
ranking = db.Column(db.Integer,
default=0)
last_updated = db.Column(db.DateTime)
# Relationships
user = db.relationship('User')
shop = db.relationship('Shop')
feature = db.relationship('Feature')
def __repr__(self):
return f'<UserFeature user_feature_id={self.user_feature_id} ranking={self.ranking}>'
#********* END OF Data model classes for the db (SQLAlchemy object) ***************#
# Connects the app entered as an argument to the db (SQLAlchemy object)
# and the hard-coded postgresql database of choice (here: coffee-project)
def connect_to_db(flask_app, db_uri='postgresql:///coffee_project', echo=True):
""" Connects the flask_app to the default postresql database. """
flask_app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
flask_app.config['SQLALCHEMY_ECHO'] = echo
flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.app = flask_app
db.init_app(flask_app)
print('Connected to the db!')
if __name__ == '__main__':
from server import app
# Call connect_to_db(app, echo=False) if your program output gets
# too annoying; this will tell SQLAlchemy not to print out every
# query it executes.
connect_to_db(app)
# Only need to run when creating (or re-creating) the db tables
# db.create_all()
|
6135495c7f1006d198d89ac8b42a9fb9892ac3d0 | flfoxjr/IPND-Module3-CYOQ | /code_your_own_quiz.py | 6,642 | 4.15625 | 4 | # A program that presents a quiz to the user, prompts for & evaluates inputs,
# and outputs the result
quiz_blanks = ["__1__","__2__","__3__","__4__","__5__"]
quiz_answers = ["blanks,three,easy,medium,hard","NCAA,March,64,Elite,Four","1991,yellow,"
"multi-paradigm,def,:"]
intro = "Please select a quiz difficulty by typing in one of the below options: "
quiz = ["This is quiz 1. It is easy. It has __1__ to fill in. There are __2__ quizzes available "
"to choose from. This one is __3__ in difficulty, while the other options are __4__ and "
"__5__ .",
"This is quiz 2. It is medium. March Madness is a tournament put on by the __1__ . "
"It happens every __2__ and April. The tournament is made up of 68 teams, but only "
"__3__ actually officially make it into the tournament. There are 6 rounds of the "
"tournament: the round of 64, round of 32, sweet 16, __4__ 8, Final __5__ , and the "
"national championship.",
"This is quiz 3. It is hard. Python is a programming langauge that first showed up in "
"__1__ . Its logo is made up of two pythons, one blue in color, the other is __2__ . "
"The lanaguage is very easy to learn compared to many other languages. It is a __3__ "
"programming language, supporting, among other things, object-oriented programming and "
"structured programming. Methods, or functions, are started with the __4__ identifier, "
"which is then followed with a __5__ ."]
num_of_tries = 5
def start_quiz():
"""Initiates the program and processes the version of the quiz to execute."""
version = 4
while version > 3:
print intro
#difficulty = raw_input("Possible choices: 1 = easy, 2 = medium, 3 = hard: ")
difficulty = raw_input("Possible choices: easy, medium, hard: ")
version = quiz_version(difficulty)
#i = version
num_of_tries = int(raw_input("Enter max number of tries per blank you'd like to have: "))
run_quiz(quiz, quiz_blanks, quiz_answers, version, num_of_tries)
def quiz_version(difficulty):
"""
Checks user input to determine quiz version.
Args:
difficulty -- the input provided by the user
Returns:
version -- int value that tells program what version of quiz to run
"""
version = 0
if difficulty == 'easy':
version = 1
return int(version)
elif difficulty == 'medium':
version = 2
return int(version)
elif difficulty == 'hard':
version = 3
return int(version)
else:
print "Invalid Selection. Please try again."
version = 4
return int(version)
def run_quiz(quiz, quiz_blanks, quiz_answers, version, num_of_tries):
"""
Runs the quiz process.
Args:
quiz -- quiz strings passed into the function
quiz_blanks -- quiz blanks passed into the function
quiz_answers -- quiz answers passed into the function
version -- quiz version passed into the function
num_of_tries -- number of tries, as previously input by the user
Returns:
none
Prints:
replaced -- final string with replaced answers
"""
replaced = []
print quiz[version-1]
quiz = quiz[version-1].split()
quiz_answers = quiz_answers[version-1].split(",")
for word in quiz:
replacement_needed = replacement_check(word, quiz_blanks, replaced)
if replacement_needed != None:
answer = answer_input(replacement_needed, quiz_blanks, quiz_answers, num_of_tries)
if answer != "You've reached the max attempts. Please try the quiz again.":
word = word.replace(replacement_needed, answer)
replaced.append(word)
else:
print "fail: " + answer
break
else:
replaced.append(word)
replaced = " ".join(replaced)
print "Final: " + str(replaced)
def replacement_check(word, quiz_blanks, replaced):
"""
Checks each word in the quiz string to determine if it needs to be replaced by user input.
Args:
word -- individual word from the active quiz list, to be checked
quiz_blanks -- individual cross checker to determine when a word in the quiz needs replacement
replaced -- updated quiz output list passed in, to then be passed into 'join_split' function
Returns:
word -- the cross check output, if relevant, such as '__1__', to prompt user which blank they are on
"""
for prompts in quiz_blanks:
if prompts in word:
join_split(replaced, prompts)
return word
return None
def join_split(replaced, prompts):
"""
Joins the list that makes up the quizzes current position, outputs it, then breaks back it down to a list
for evaluation.
Args:
replaced -- current quiz replacement list
prompts -- the 'quiz_blank' label that tells the user which prompt they are at, such as '__1__'
Returns:
replaced -- updated quiz replacement list
"""
replaced = " ".join(replaced)
print replaced + " " + prompts
replaced = replaced.split()
return replaced
def answer_input(replacement_needed, quiz_blanks, quiz_answers, num_of_tries):
"""
Prompts the user for replacement input for the current blank in the quiz.
Args:
replacement_needed -- the 'quiz_blank' label that is currently being replaced
quiz_blanks -- the 'quiz_blank' list used to determine location index to be replaced
quiz_answers -- answer list used to check against user input for correct response
num_of_tries -- the number of attempts a user gets to be correct
Returns:
user_input -- the input that the user provided, if corect
max_attempts -- the 'fail' string if the user fails the quiz
"""
tries = 0
location = quiz_blanks.index(replacement_needed)
while tries < num_of_tries:
user_input = raw_input("Enter answer for " + replacement_needed + ": ")
if user_input == quiz_answers[location]:
return str(user_input)
tries += num_of_tries
else:
print "Incorrect, try again."
tries += 1
print str(num_of_tries - tries) + " attempts left!"
max_attempts = "You've reached the max attempts. Please try the quiz again."
return max_attempts
start_quiz()
|
b23354339fb127426632ed3e2fcffd8de1f3a2bf | soumendrak/Problems | /Euler-3_V1.2.py | 430 | 4.15625 | 4 | print "Enter the number"
num = int(raw_input())
def process(num):
div2,div1,counter = 0,0,2
while counter < num:
if num % counter == 0:
div1 = counter
if div2 < div1:
div2= div1
counter += 1
# if div2 == 0:
print "the largest prime factor is %d" %(num)
# return
# else:
# process(div2)
# return
# sumnum = sum(map(int, str(num)))
# print "sum of the digits of the number is %d" %(sumnum)
process(num) |
4ca2f274e9edc2a3991620f98df66cd1022976cb | IvanRojas616/pythonmini | /translateUI.py | 2,099 | 3.53125 | 4 | from tkinter import *
from PIL import Image, ImageTk
import google_trans_new
import os
from google_trans_new import google_translator, LANGUAGES
root = Tk()
frameImage = Frame(root)
frameImage.pack()
def translate(obj, objTo, tolang):
try:
translator= google_translator()
text = str(objTo.get("1.0",END))
print(text)
translation = translator.translate(text,lang_tgt=tolang)
obj.delete(1.0,"end")
obj.insert(1.0, translation)
except Exception as e:
print("Error!!!",e.args)
fileDir = os.path.dirname(os.path.abspath(__file__))
img = Image.open(os.path.join(fileDir,"traductor.png"))
out = img.resize((200, 200), Image.ANTIALIAS)#redimensionamos la imagen
imgFinal = ImageTk.PhotoImage(out)#luego usamos ImageTk, para usarla en Tkinter
#recordar que no estamos usando el PhotoImage común sino el de Pillow
Label(frameImage,image=imgFinal).grid(row=0,column=0,columnspan=2)
frameTraductor = Frame(root)
entradaIdiomaObjetivo = Entry(frameTraductor,justify="center")
entradaIdiomaObjetivo.grid(row=0,column=0,pady=20,padx=20,columnspan=5)
textTo = Text(frameTraductor,width=50,height=20,wrap=WORD)
textTo.grid(row=1,column=1,pady=10)
textTradu = Text(frameTraductor,width=50,height=20,wrap=WORD)
textTradu.grid(row=1,column=3,pady=10)
scrollOne = Scrollbar(frameTraductor,command=textTo.yview,orient=VERTICAL,
cursor="exchange")
scrollOne.grid(row=1, column=0, sticky="nsew")
scrollTwo = Scrollbar(frameTraductor,command=textTradu.yview,orient=VERTICAL,
cursor="exchange")
scrollTwo.grid(row=1, column=4, sticky="nsew")
textTo.config(yscrollcommand=scrollOne.set)
textTradu.config(yscrollcommand=scrollTwo.set)
traductor = Button(frameTraductor, text="Go",padx=20)
traductor.config(command = lambda:translate(textTradu, textTo,entradaIdiomaObjetivo.get()))
traductor.grid(row=1,column=2)
if not os.path.isfile("countries.txt"):
with open("countries.txt","w") as data:
for k,v in LANGUAGES.items():
data.write(k + '->' + v + '\n')
else:
print("File exists")
frameTraductor.pack()
root.mainloop()
|
65ab7509b0a06f8c6797d6cdc64899dac8547799 | AlexKjes/ai_prog_assignment_2 | /csp_graph.py | 3,038 | 3.71875 | 4 | from copy import copy
class Graph:
"""
Constraint satisfaction graph contains variables connected by constraints
"""
def __init__(self):
self.nodes = []
self.edges = []
def add_node(self, domain):
n = Node(domain)
self.nodes.append(n)
return n
def add_edge(self, from_node, to_node, constraint):
e = Edge(from_node, to_node, constraint)
self.edges.append(e)
return e
def save_state(self):
"""
saves the current state of the graph
:return:
"""
for n in self.nodes:
n.save()
def save_state_by_key(self, key):
"""
saves the current state of the graph by key, so it can be retrieved by the same key
:param key:
:return:
"""
for n in self.nodes:
n.key_save(key)
def revert(self):
for n in self.nodes:
n.revert()
def load_state_by_key(self, key):
for n in self.nodes:
n.key_revert(key)
class Node:
"""
Node represents a variable in a csp
"""
def __init__(self, domain):
self.domain = domain
self.history = []
self.name_store = {}
self.to_edges = []
def update(self, new_domain):
"""
updates to this variables domain notifies reevaluates variables dependant on this
:param new_domain:
:return:
"""
self.domain = new_domain
for e in self.to_edges:
e.revise()
def save(self):
self.history.append(copy(self.domain))
def key_save(self, key):
self.name_store[key] = copy(self.domain)
def revert(self):
self.domain = self.history.pop()
def key_revert(self, key):
self.domain = self.name_store[key]
class Edge:
"""
Represents a constraint
"""
def __init__(self, from_node, to_nodes, constraint):
self.to_nodes = to_nodes
[to_node.to_edges.append(self) for to_node in to_nodes]
self.from_node = from_node
self.constraint = constraint
self.revise()
def revise(self):
updated_domain = []
change = False
for element in self.from_node.domain:
if all([len(to_node.domain) != 0 for to_node in self.to_nodes]) and self.constraint(element, [to_node.domain for to_node in self.to_nodes]):
updated_domain.append(element)
else:
change = True
if change:
self.from_node.update(updated_domain)
def remove(self):
[n.to_edges.remove(self) for n in self.to_nodes]
if __name__ == '__main__':
n1 = Node([i for i in range(10)])
n2 = Node([i for i in range(10)])
n3 = Node([i for i in range(10)])
Edge(n1, n2, lambda x, y: any([x < z for z in y]))
Edge(n2, n3, lambda x, y: x < max(y))
Edge(n3, n2, lambda x, y: x > min(y))
Edge(n2, n1, lambda x, y: x > min(y))
Edge(n1, n1, lambda x, y: x > 3)
print(n1.domain)
|
81f755685891e2f696254e680fe11615cd175064 | kkulykk/json_navigation | /main.py | 1,925 | 4.09375 | 4 | """
Module to navigate through json file
"""
from pathlib import Path
import sys
import json
def get_location_to_json():
"""
Ask user the location where json file is stored
"""
while True:
path = input("\nEnter a path to file: ")
if Path(path).exists():
return path
print('Invalid path')
def read_file(path: str) -> dict:
"""
Return dictionary with the iformation from file
"""
with open(path, mode='r', encoding='utf-8') as file:
data = json.load(file)
return data
def parse(data: dict):
"""
Go through json file structure and shows content
"""
while True:
if type(data) == list:
if len(data) == 0:
print("O files here. Nothing to display")
else:
print('\nThis object is list.', len(data), 'elements in this directory\nChoose\
where to go by entering number in range from 1 to', len(data), 'or type EXIT to quit: ')
element = int(input())
if element == "EXIT":
sys.exit()
elif element not in range(1, len(data) + 1):
print("\nInvalid location")
sys.exit()
data = data[element-1]
elif type(data) == dict:
keys = list(data.keys())
print('\n', len(keys), 'elements in this directory: \n')
for i in keys:
print(i)
location = input('\nChoose where to go or type EXIT to quit: ')
if location == "EXIT":
sys.exit()
elif location not in keys:
print("\nInvalid location")
sys.exit()
data = data[location]
else:
print('\nNothing to display, except:')
print(data)
break
if __name__ == '__main__':
parse(read_file(get_location_to_json()))
|
ef5cad16482eef369ca1c5c7b675896696ff3db0 | Oscar-Oliveira/Python-3 | /4_Control_Flow/1_Decision/A_if.py | 138 | 3.921875 | 4 | """
if
"""
NUMBER = 17
value = int(input("input a value: "))
if value == NUMBER:
print("Winner!!!")
print("Game over...")
|
395dbec4520eef6c61294d7146dc0ff0be6368c1 | DanielMagallon/Python-dev | /PrimerosPasos/FluentBook/Chapter1-P1/Collections.py | 1,362 | 3.75 | 4 | import collections
from random import choice
Card = collections.namedtuple('Card',["rank","suit"])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = "spades diamonds clubs hearts".split()
def __init__(self):
self._cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, pos):
return self._cards[pos]
deck = FrenchDeck()
print("Size: "+str(len(deck)))
for c in deck:
print(c)
print("Random...")
print(choice(deck))
print("Deck 12::13=",deck[12::13])
for c in reversed(deck):
print(c)
print("Card('2','spades')? "+str(Card('2','spades') in deck))
print("Card('22','spades')? "+str(Card('22','spades') in deck))
#list2 = ["Edgar","Daniel"]+["Magallon","Villanueva"]
#print(list2)
class Storage():
sets={}
def __setitem__(self, key, value):
self.sets.__setitem__(key,value)
def __getitem__(self, key):
return self.sets.__getitem__(key)
alamacen=Storage()
alamacen["1"]="Edgar"
print("Key 1 contains: "+alamacen["1"])
bob = ('Bob', 30, 'male')
print('Representation:', bob)
jane = ('Jane', 29, 'female')
print('\nField by index:', jane[0])
print('\nFields by index:')
for p in [bob, jane]:
print('{} is a {} year old {}'.format(*p)) |
86ab970e35d635fd3e46d170127d6ab0aaf084f0 | melissafear/CodingNomads_Labs_Onsite | /week_03/02_exception_handling/03_else.py | 200 | 3.9375 | 4 | '''
Write a script that demonstrates a try/except/else.
'''
try:
userinput = int(input("number pls: "))
except ValueError as ve:
print(f"Please use a number")
else:
print(userinput**2) |
441b2147d34c5643486888655ff70bf1c9552a91 | TenzinWangpo7298/sierpinski | /sierpinski.py | 1,270 | 3.71875 | 4 | from turtle import *
def drawTriangle(points, color, myTurtle):
myTurtle.fillcolor(color)
myTurtle.up()
myTurtle.goto(points[0])
myTurtle.down()
myTurtle.begin_fill()
myTurtle.goto(points[1])
myTurtle.goto(points[2])
myTurtle.goto(points[0])
myTurtle.end_fill()
def getMid(p1,p2):
return ((p1[0]+ p2[0])/2, (p1[1]+ p2[1])/ 2)
def sierpinski(points, degree, myTurtle):
myTurtle.speed(5)
colormap = ["blue", "red", "green","white","yellow", "violet", "orange","grey","gold","indigo"]
drawTriangle(points,colormap[degree],myTurtle)
if degree > 0:
sierpinski([points[0],
getMid(points[0], points[1]),
getMid(points[0], points[2])],
degree - 1, myTurtle)
sierpinski([points[1],
getMid(points[0], points[1]),
getMid(points[1], points[2])],
degree - 1, myTurtle)
sierpinski([points[2],
getMid(points[2], points[1]),
getMid(points[0], points[2])],
degree - 1, myTurtle)
myTurtle = Turtle()
myWin = myTurtle.getscreen()
myPoints = [(-500,-150), (0,250), (500,-150)]
sierpinski(myPoints,8,myTurtle)
myWin.exitonclick()
|
83e8f6fc3b672823d10c19a18178c1e6ab0c6ed6 | rjnp2/deep_learning_from_scratch | /utils/data_manage.py | 3,064 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 14:55:42 2020
@author: rjn
"""
# importing required library
import numpy as np
def shuffle_data(X : np.array ,
y: np.array,
seed: int = None)-> np.array:
'''
Random shuffle of the samples in X and
Parameters
----------
X : np.array
Dataset.
y : np.array
label data.
seed : int, optional
seed values. The default is None.
Raises
------
TypeError
DESCRIPTION.
Returns
-------
np.array
DESCRIPTION.
'''
if seed and type(seed) != int:
raise TypeError('invalid data types')
if seed:
np.random.seed(seed)
# get spaced values within a given interval of X.shape[0].
idx = np.arange(X.shape[0])
# Modify a sequence of idx by shuffling its contents.
np.random.shuffle(idx)
# return shuffle data of given X and y.
return X[idx],y[idx]
def batch_iterator(X : np.array ,
y: np.array = None,
batch_size: int =64)-> np.array:
'''
Simple generating batch as per batch size
Parameters
----------
X : Array of int or float
Dataset.
y : Array of int or float
label data. The default is None.
batch_size : int, optional
no of batch to be generates . The default is 64.
Returns
-------
yeild of dataset of batch size.
'''
# total size of data in x
n_samples = X.shape[0]
# checking if there is same no of data or not.
# raise error if not.
if y is not None and X.shape[0] != y.shape[0]:
raise Exception(f'X and y should have same no of data. x has {X.shape[0]} and y has {y.shape[0]}')
for i in np.arange(0, n_samples, batch_size):
begin, end = i, min(i+batch_size, n_samples)
if y is not None:
yield X[begin:end], y[begin:end]
else:
yield X[begin:end]
def train_test_split(X : np.array ,
y : np.array ,
test_size: int =0.5,
shuffle: str =True,
seed: int =None):
'''
Split the data into train and test sets
Parameters
----------
X : Array of int or float
Dataset.
y : Array of int or float
label data.
test_size : float, optional
percentage of test size. The default is 0.5.
shuffle : Boolean, optional
DESCRIPTION. The default is True.
seed : int, optional
seeding values. The default is None.
Returns
-------
Spliting data into train and test sets of x and y.
'''
if shuffle:
X, y = shuffle_data(X, y, seed)
# Split the training data from test data in the ratio specified in
# test_size
split_i = len(y) - int(len(y) // (1 / test_size))
X_train, X_test = X[:split_i], X[split_i:]
y_train, y_test = y[:split_i], y[split_i:]
return X_train, X_test, y_train, y_test
|
31f22a386e24aaada589c4d46060731b8ed2d211 | Hitendraverma/Python-Codes | /threadl.py | 1,045 | 4 | 4 | #!/usr/bin/python
import threading
import time
#Code 1
'''
thread = []
def worker():
print "Thead fn working"
return
#for i in range(5):
#t=threading.Thread(target=worker)
#thread.append(t)
#t.start()
''''THreading is initialed using function start()''''
#Adding Argument in fn call
def threadl(num):
print "Arg thread fn wrkng"+num
return
for i in range(5):
t=threading.Thread(target=threadl , args=(i))
thread.append(t)
t.start()
'''
#Code 2 - Naming thread
def worker():
print threading.currentThread().getName(), 'Starting'
time.sleep(3)
print threading.currentThread().getName(), 'Exiting'
def service():
print threading.currentThread().getName(), 'Starting'
time.sleep(4)
print threading.currentThread().getName(), 'Exiting'
for i in range(5):
ser = threading.Thread(name='process' , target=service)
wor = threading.Thread(name='worker', target=worker)
wor2 = threading.Thread(target=worker)
#Using wor2 gives 'Thread-1' in the name thread column in the output
ser.start()
wor2.start()
wor.start()
|
0f847c0b663f991b98bad758681a926511a19b17 | rafaelperazzo/programacao-web | /moodledata/vpl_data/127/usersdata/216/31976/submittedfiles/ex11.py | 545 | 3.953125 | 4 | # -*- coding: utf-8 -*-
dia1= int(input('Digite um dia:'))
dia2= int(input('Digite um dia:'))
mes1= int(input('Digite um mês:'))
mes2= int(input('Digite um mês:'))
ano1= int(input('Digite um ano:'))
ano2= int(input('Digite um ano:'))
if ano1>ano2:
print(Data 1)
elif ano1<ano2:
print(Data 2)
else:
if mes1>mes2:
print(Data 1)
elif mes1<mes2:
print(Data 2)
else:
if dia1>dia2:
print(Data 1)
elif dia1<dia2:
print(Data 2)
else:
print(Datas iguais) |
e16933e3c157187dd74546b2a6d7fc2ca18e93af | cavigna/CodeWars_Python | /kyu6/multiple_three_five.py | 194 | 3.84375 | 4 | suma = 0
def multiple(n):
global suma
if n < 3:
return suma
n -= 1
suma += n if n % 3 == 0 or n % 5 == 0 else 0
return multiple(n)
print(multiple(10))
|
e4d7abc4a49d709a82cf236feb39eab5a1b733e5 | ritiztambi/Dynamic-Topic-Modelling-in-Kafka | /database_script.py | 3,930 | 3.640625 | 4 | import sqlite3
from sqlite3 import Error
import datetime
import time
import os
import csv
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_table_topics(conn):
create_table_sql = """ CREATE TABLE IF NOT EXISTS Topics (
ID integer PRIMARY KEY AUTOINCREMENT,
Name text NOT NULL,
Parent_ID integer,
Timestamp text
); """
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def create_table_actions(conn):
create_table_sql = """ CREATE TABLE IF NOT EXISTS Actions (
Name text NOT NULL,
Action text,
Timestamp text
); """
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def delete_table_topics(conn):
delete_table_sql = """ DROP TABLE IF EXISTS Topics"""
try:
c = conn.cursor()
c.execute(delete_table_sql)
except Error as e:
print(e)
def delete_table_actions(conn):
delete_table_sql = """ DROP TABLE IF EXISTS Actions"""
try:
c = conn.cursor()
c.execute(delete_table_sql)
except Error as e:
print(e)
def create_topic(conn, topic):
sql = ''' INSERT INTO Topics(ID,Name,Parent_ID,Timestamp)
VALUES(?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, topic)
return cur.lastrowid
def create_action(conn, action):
sql = ''' INSERT INTO Actions(Name,Action,Timestamp)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, action)
return cur.lastrowid
def delete_topic(conn, id):
cur = conn.cursor()
sql = ''' DELETE FROM Topics Where ID = ?'''
cur.execute(sql, (id,))
sql = ''' DELETE FROM Topics Where Parent_ID = ?'''
cur.execute(sql, (id,))
return cur.lastrowid
def merge_topics(conn, name):
sql = ''' select ID from Topics where name = ?'''
cur = conn.cursor()
cur.execute(sql, (name,))
parent_id = cur.fetchone()[0]
sql = ''' DELETE FROM Topics Where Parent_ID = ?'''
cur = conn.cursor()
cur.execute(sql, (parent_id,))
os.system('/usr/local/Cellar/kafka/2.0.0/libexec/bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic {}.*'.format(name))
return cur.lastrowid
def split_topics(conn, name):
sql = ''' Select count(*) from Topics where Parent_ID = (select ID from topics where name = ?)'''
cur = conn.cursor()
cur.execute(sql, (name,))
count = cur.fetchone()[0]
# print(count)
child_name = name + str(count)
# print(child_name)
sql = ''' select ID from Topics where name = ?'''
cur = conn.cursor()
cur.execute(sql, (name,))
parent_id = cur.fetchone()[0]
# print(parent_id)
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
create_topic(conn,[None,child_name,parent_id,st])
os.system('/usr/local/Cellar/kafka/2.0.0/libexec/bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic {}'.format(child_name))
def export_log(conn):
sql = ''' SELECT * from Actions '''
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
print (data)
with open('logdata.csv', 'w', newline='') as f_handle:
writer = csv.writer(f_handle)
header = ['Name','Action','Timestamp']
writer.writerow(header)
for row in data:
writer.writerow(row)
|
12f69e19432f94750ca58beb0ee2a2991073c4ee | DRSUCCESS/Python | /comprehension.py | 1,634 | 3.875 | 4 | # # ...COMPREHENSION using list
# # double prize money weekend bonanza
# prizes = [5, 10, 50, 100, 1000]
# dbl_prizes = [ ]
# for prize in prizes:
# dbl_prizes.append(prize*2)
# # print(dbl_prizes)
# # comprehension metthod
# dbl_prizes = [ prize*2 for prize in prizes ]
# # print(dbl_prizes)
# # squaring numbers
# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10]
# square_even_nums = [ ]
# for num in nums:
# if(num **2) % 2 == 0:
# square_even_nums.append(num ** 2)
# # print(square_even_nums)
# # comprehension metthod
# square_even_nums = [num ** 2 for num in nums if (num ** 2 )% 2 ==0 ]
# # print(square_even_nums)
# # ...MAP FUNCTION
# from random import shuffle
# def jumble(word):
# anagram = list(word)
# shuffle(anagram)
# return ''.join(anagram)
# words = ['bestroot', 'carrot', 'potatoes']
# anagrams = [ ]
# # print(list(map(jumble, words))) # using map function
# # print([jumble(word) for word in words]) # comprehension
# # for word in words: # for loop
# # anagrams.append(jumble(word))
# # print(anagrams)
# # ...FILTER
# grades = ['A', 'B', 'C', 'F', 'A', 'C']
# def remove_fails(grade):
# return grade != 'F'
# # print(list(filter(filtered_grades, grades))) #map
# # filtered_grades = [] # function
# # for grade in grades:
# # if grade != 'F':
# # filtered_grades.append(grade)
# # print(filtered_grades)
# # print([grade for grade in grades if grade != 'F' ]) # comprehension
# ...LAMBDA FUNCTION
nums = [1,2,3,4,5,6]
def square(n):
return n*n
# print(list(map(square, nums))) # map
print(list(map(lambda n:n*n, nums))) # lamda
|
e4071bd33c07c4d90aaa37536b03520ece656b7a | dexterka/coursera_files | /1_Python_for_everybody/week5_conditions/conditionals_testing.py | 435 | 4.15625 | 4 | x = 100
# if x > 1 :
# print('It is greater than 1')
# else:
# print('It is lower than or equal to 1')
#
# if x <= 100 :
# print('It is lower than or equal to 100')
# else:
# print('It is greater than 100')
#
# print('All done!')
if x > 100 :
print('Greater than 100')
elif x < 50 :
print('Greater than 50')
else :
print('Ranging from 51 to 100')
print('All done!') |
1f242bb098c1a8315d10ce57c2b13171cfd6c8be | Aviator16/madness-1.0 | /insertion_sort.py | 386 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 20:07:21 2019
@author: ANUBHAB JOARDAR
"""
#Insertion sort
a=[1,4,67,32,41,89,30,6,16]
def insersort(x):
for i in range(1,len(x)):
tmp=i
for j in range(i-1,0,-1):
if x[tmp]<x[j]:
x[j],x[tmp]=x[tmp],x[j]
tmp=tmp-1
print(x)
insersort(a)
|
3b4ce9022b6c11b6305711b46dd2cc1b551e35ed | tdhawale/Python_Practise | /List.py | 2,510 | 4.4375 | 4 | #List is mutable and we can change the values
from builtins import min
fruits = ["Apple","Mango","Banana","Carrot"]
print("**************************************************")
print("Printing the entire List")
print(fruits)
#print('\n')
print("**************************************************")
print("Printing the Specific list item")
print(fruits[2])
fruits.append("Guava")
fruits.append("Lichi")
print("**************************************************")
print("Printing the List from specified Index")
print(fruits)
print(fruits[2:5]) # Prints elements of the list from index 1 to 4
print(fruits[2:6]) # Prints elements of the list from index 2 to index 5()
print(fruits[1:]) # Prints all the list element from 1 till the end of the list
#print(fruits[-5]) # Prints array in backward direction
###############################################################
#We can even make lists of uncommon elements like string and intgers
container = [3,"Mita",4,"Babita"]
print(container)
###############################################################
chinchwad = ["Ramesh","Suresh","Hitesh","Ritesh"]
pimpri = ["Anita","Vanita","Babita","Savita"]
staff = [chinchwad , pimpri]
print("**************************************************")
print("Printing the staff details")
print(staff)
print("**************************************************")
print("Sorting the staff members at chinchwad")
chinchwad.sort()
print(chinchwad)
#insert is used to insert at a specific location
chinchwad.insert(2,"Tejas")
print(chinchwad)
#append adds the new value at the end
chinchwad.append("Nikhil")
print(chinchwad)
#Remove is used to remove a known element
chinchwad.remove("Tejas")
print(chinchwad)
#pop is used to remove the element of the list at a specific position
chinchwad.pop(0)
print(chinchwad)
chinchwad.pop() # No value specified indicates the value on top of the stack will be deleted
print(chinchwad)
#to add multiple entries in the list
chinchwad.extend(["Ganesh","Rahul","Sandeep","Akshay"])
print(chinchwad)
# pop is used to delete single element where as del is used to delete multiple values
del chinchwad[1:3]
print(chinchwad)
print("**************************************************")
print("Printing minimum of the list")
print(min(chinchwad))
print("**************************************************")
print("Printing the sum")
print(max(chinchwad))
chinchwad[1] = "AAAA"
print(chinchwad)
#id is used to give the address of the variable
print(id(chinchwad))
|
049fc582f9296b7d448f9e376c039a3e7723d7e0 | bootcamp-f16/openweather-app | /lib/app.py | 683 | 3.546875 | 4 | import os
from lib.api import API
from lib.weather import Weather
class App():
def __init__(self, api_key):
self.api_key = api_key
self.api = API(api_key)
def run(self):
while True:
try:
print("Enter the name of a city.")
location = input(">>> ")
weather = Weather(self.api.get_current_weather(location=location))
weather.display_weather()
except ValueError as e:
print("Error getting the weather: {}".format(e))
except KeyError as e:
print("There was an error reading the weather data at the location you entered.") |
d91b1f93b3ad622007a02277965f0d82ac3c4d4b | ChocolatePadmanaban/Learning_python | /Day9/part8.py | 296 | 3.8125 | 4 | # Dictionaries and Key
keys = ['a','aa','aaa']
d1 = dict((k,len(k)) for k in keys)
d2 = dict((k,len(k)) for k in reversed(keys))
print('d1: ',d1)
print('d2: ',d2)
print('d1 == d2: ',d1==d2)
s1 = set(keys)
s2 = set(reversed(keys))
print()
print('s1: ',s1)
print('s2: ',s2)
print('s1 == s2: ',s1==s2) |
a09f6989953c09436c5d193e627b5d417ee18ffc | adrianoforcellini/ciencia-da-computaco | /33-Programao Orientada a Objetos E Padroes de Projeto/33.2- Herança, Composiçao e Interfaces/5 - Exercício Estatística.py | 1,031 | 3.65625 | 4 | from collections import Counter
class Estatistica:
def __init__(self, numbers2):
self.numbers2 = numbers2
@classmethod
def media(cls, numbers):
return sum(numbers) / len(numbers)
@classmethod
def mediana(cls, numbers):
numbers.sort()
index = len(numbers) // 2
if len(numbers) % 2 == 0:
return (numbers[index - 1] + numbers[index]) / 2
return numbers[index]
@classmethod
def moda(cls, numbers):
number, _ = Counter(numbers).most_common()[0]
return number
def moda2(self):
self.numbers2, _ = Counter(self.numbers2).most_common()[0]
return self.numbers2
print(Estatistica.media([1,2,3]))
print(Estatistica.mediana([1,2,3]))
print(Estatistica.moda([1,2,3,3]))
minha_estatistica = Estatistica([1, 2 , 2])
print(minha_estatistica.media([1,2]))
print(minha_estatistica.moda2())
### Note como a annotation @classmethod facilita a passagem dos
### valores sem que haja necessidade do uso do self ou init. |
2bbba57e50fced14cacb63c457e793beb43fe583 | yuyuOWO/source-code | /Python/web浏览.py | 744 | 3.890625 | 4 | #http://www.smartoj.com/p/1006
website = ["http://www.acm.org"]
index = 0
while True:
cmd = list(map(str, input().strip().split()))
if len(cmd) == 2:#覆盖当前下标的下一个位置
print(cmd[1])
index += 1
if index >= len(website):
website.append(cmd[1])
else:
website[index] = cmd[1]
elif cmd[0] == "BACK":#不添加的列表
if index <= 0:
print("Ignored")
else:
index -= 1
print(website[index])
elif cmd[0] == "FORWARD":#移动下标
if index > len(website) - 2:
print("Ignored")
else:
index += 1
print(website[index])
elif cmd[0] == "QUIT"
break
|
a79a0e873c842587805a7617f0b30f16938bbef1 | whoch00/ppdRPG | /lib/_types.py | 6,505 | 3.6875 | 4 | """Types of basic objects.
This are merely classes that provide actions to specific types of objects.
"""
from ppdRPG import configs
from ppdRPG import _Object
import logging
class Mobile(_Object):
"""_Objects that can be moved, such as Thing, Npc, Player, but NOT Place."""
def __init__(self):
pass
def move(self,place,position=None,autoSave=configs.autoSave):
"""Move from a position to another taking into account what is on the
destination and on Place.bans
"""
logging.debug("Moving %s to %s on %s." % (self.instanceName,
position, place.instanceName))
if position == None:
position = [0,0]
try:
if self in place.bans:
raise Exception("%s is not allowed in %s" % (self.instanceName,
place.instanceName))
elif not position in place.availablePositions():
raise Exception("Position occupied by %s" % (
place.matrix[position[0]][position[1]]))
# If the object is already on the place, just move it
elif place.contains(self):
place.moveObj(self.position,position)
self.position = position
self.place = place
# Else, add it to the place at position and remove it from it's
# current place, if it is in one.
else:
try:
self.place.matrix[self.position[0]][self.position[1]]=False
except AttributeError:
pass
place.matrix[position[0]][position[1]] = self
self.position = position
self.place = place
except IndexError:
raise Exception("Position outside of place.")
if autoSave:
self.save()
place.save()
def walk(self,x,y):
"""Walk left, right, up, down, diagonals."""
xs = [-1,0,1]
ys = xs
if not x in xs or not y in ys:
raise Exception('Cannot jump spaces.')
position = [self.position[0] + y, self.position[1] + x]
self.move(self.place,position)
def reach(self, destination, currentPosition=None,
visitedPositions=None, unvisitedPositions=None):
"""Go from source to destination on the place matrix considering
what is on the way.
It finds a sub-optimal path from source to destination and either
move the object to the destination or return an error if there
is no possible path.
"""
try:
if self.place.matrix[destination[0]][destination[1]] != False:
raise Exception('Position unavailable.')
except IndexError:
raise Exception("Position outside of %s." % (
self.place.instanceName))
if currentPosition == None:
currentPosition = self.position[:]
if visitedPositions == None:
visitedPositions = currentPosition[:]
if unvisitedPositions == None:
unvisitedPositions = []
currentNeighbors = [[currentPosition[0], currentPosition[1]+1], # Migi
[currentPosition[0], currentPosition[1]-1], # Hidari
[currentPosition[0]+1, currentPosition[1]], # Ue
[currentPosition[0]-1, currentPosition[1]], # Shita
[currentPosition[0]+1, currentPosition[1]+1], # /\>
[currentPosition[0]-1, currentPosition[1]-1], # \/<
[currentPosition[0]+1, currentPosition[1]-1], # /\>
[currentPosition[0]-1, currentPosition[1]+1]] # \/>
# Points outside the matrix do not exist, hence are not neighbors.
# Walls and objects neither. Nor are positions already visited.
toBeDeleted = []
for i in currentNeighbors:
if i[0] < 0 or i[1] < 0: # List[-1] exists, but is not a neighbor.
toBeDeleted.append(i)
else:
try:
if (i in visitedPositions or
not self.place.matrix[i[0]][i[1]] == False):
toBeDeleted.append(i)
except IndexError:
toBeDeleted.append(i)
for i in toBeDeleted:
currentNeighbors.remove(i)
# It is possible to go back and visit unvisited positions.
currentNeighbors += unvisitedPositions
# If there are no neighbors, we are stuck.
if not currentNeighbors:
raise Exception('There is no way to reach the destination.')
# Else, explore said possibilities.
else:
# If the destination is within reach, move to it.
if destination in currentNeighbors:
self.move(self.place,destination)
return None
# Else, move to the possibility closest to the destination.
else:
# Create a dictionaty of {node : distance to the destination}.
nodes = {}
for i in currentNeighbors:
# The number of movements to reach the destination
# (distance from it), being able to walk on a line
# or on a diagonal, is equal to the biggest of either
# the number of columns, or the number of lines
# between the source and the destination.
if abs(destination[0]-i[0]) >= abs(destination[1]-i[1]):
distance = abs(destination[0]-i[0])
else:
distance = abs(destination[1]-i[1])
try:
nodes[distance].append(i)
except KeyError:
nodes[distance] = []
nodes[distance].append(i)
# Set current position as the (first) possibility with
# the smalles distance to the destination.
currentPosition = nodes[min(nodes)][0]
visitedPositions.append(currentPosition)
# Add unvisited possibilities to the unvisitedPositions
# list (if not already in it or if it was visited)
k = currentNeighbors.index(currentPosition)
for i in currentNeighbors[:k] + currentNeighbors[k+1:]:
if (not i in visitedPositions and
not i in unvisitedPositions):
unvisitedPositions.append(i)
try:
unvisitedPositions.remove(currentPosition)
except ValueError:
pass
# Now in the new position, repeat everything until either
# we reach the destination or get stuck.
self.reach(destination,currentPosition,
visitedPositions,unvisitedPositions)
return None
class Usable(_Object):
"""Objects that can be used by a player, a npc...
Places do not inherit this class. It is intended for the Thing class and
it's childs only.
"""
def __init__(self, used=None, bans=None):
if used == None: # Who used it.
self.used = []
else:
self.used = used
if bans == None: # Who is not allowed to use it.
self.bans = []
else:
self.bans = bans
def use(self, obj):
"""Append obj to usedlist if it's allowed to use self.
Use objInstance.use(thingInstance) if you want an object to use a thing.
"""
if not obj in self.bans:
self.used.append(obj)
return None
else:
raise Exception("%s is not allowed to use %s." % (
obj.instanceName, self.name))
def usedBy(self, obj):
"""Was this used by obj?"""
if obj in self.used:
return True
else:
return False
|
a00a64dc18076388c3feaa6d1f97a42f1a92b6d7 | Nisar-1234/Data-structures-and-algorithms-1 | /Trees/Tree Traversal (Pre,In,Post-order).py | 1,533 | 4 | 4 | class BinaryTree():
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insertLeft(self,newData):
if self.left == None:
self.left = BinaryTree(newData)
else:
t = BinaryTree(newData)
t.left = self.left
self.left = t
def insertRight(self, newData):
if self.right == None:
self.right = BinaryTree(newData)
else:
t = BinaryTree(newData)
t.right = self.right
self.right = t
# Pre-order/In-order/Post-order are implemeneted as external functions, not as a part of the class
def printPreorder(node): #PLR
if node:
print(node.data)
printPreorder(node.left)
printPreorder(node.right)
def printInorder(node): #LPR
if node:
printInorder(node.left)
print(node.data)
printInorder(node.right)
def printPostorder(node): #LRP
if node:
printPostorder(node.left)
printPostorder(node.right)
print(node.data)
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = BinaryTree(3)
root.left.left = BinaryTree(4)
root.left.right = BinaryTree(5)
print("====PRE-ORDER TRAVERSAL====")
printPreorder(root)
#printing a blank line
print()
print("====IN-ORDER TRAVERSAL====")
printInorder(root)
#printing a blank line
print()
print("====POST-ORDER TRAVERSAL====")
printPostorder(root)
|
dc40ec1e8653dd737c90a8d2dfc4caf593b90b49 | cocka/py4e | /2_python_data_structures/5week/9.4.py | 1,099 | 4.375 | 4 | #!/usr/bin/python3
# 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.py4e.com/code3/romeo.txt
filename = input("Enter file name: ")
list_all = list()
counts = dict()
bigcount = None
bigword = None
if len(filename) < 1 :
filename = "mbox-short.txt"
try:
fh = open(filename)
except:
print("File cannot be opened:", filename)
quit()
for line in fh:
if line.startswith('From:'):
line = line.rstrip()
words = line.split()
list_all.append(words[1])
for email in list_all:
counts[email] = counts.get(email, 0) + 1
#print(counts)
for email,count in counts.items():
if bigcount is None or count > bigcount:
bigword = email
bigcount = count
print(bigword, bigcount)
|
13d608787bebef1f66a9dd9c9b313fbf072be824 | gabriellaec/desoft-analise-exercicios | /backup/user_084/ch59_2020_03_17_22_52_16_143390.py | 105 | 3.703125 | 4 | def asteriscos(n):
n=int(input('escolha um numero positivo: ')
y='*'
print (y*n)
return n |
00d1745a483622aac40c7f291ca74609fa2f2d36 | puhoy/adventofcode2020 | /1/first.py | 615 | 3.546875 | 4 | from typing import List
def get_input():
with open('input') as f:
lines = f.readlines()
return lines
def get_numbers_2020(inp: List[int]):
for idx_1, num_1 in enumerate(inp):
for idx_2, num_2 in enumerate(inp):
if idx_1 != idx_2:
if num_1 + num_2 == 2020:
return True, num_1, num_2
return False, 0, 0
if __name__ == '__main__':
inp = get_input()
inp_numbers = [int(n) for n in inp]
success, num_1, num_2 = get_numbers_2020(inp_numbers)
if success:
print(num_1 * num_2)
else:
print('nope')
|
f2078f87cec047823dec9cd2d7ceb3d890e4ce88 | Libardo1/Word2Vec-1 | /context_window.py | 842 | 3.984375 | 4 |
def context_window_search(context_size = 3):
""" Illustrates how the context window changes across a sentence
for a given target word """
word_tuple = tuple(['<s>', 'a', 'b', 'c', 'd', 'e', '</s>'])
print "sentence example: ", word_tuple
context_size = context_size
count = 1
context = []
for i, word in enumerate(word_tuple):
if word != '<s>':
target = word
if count > context_size:
context = context[1:]
context.append(word_tuple[i-1])
print "context: {}, target: {}".format(context, target)
if word == '</s>':
for n in range(len(context)-1, 0, -1):
context = context[-n:]
print "context: {}, target: {}".format(context, target)
count += 1 |
97f570fa33de2aeec3f9c59bd35c57b2dd9ea166 | zhangfhub/git_github | /python/ex1/list_1.py | 254 | 3.90625 | 4 | #-*-coding:utf-8 -*-
#!/usr/bin/python3
# @Author:liulan
list1=[1,2,3.14]
#追加元素
# list1.append([4,5,6])
#拓展元素
list1.extend([4,5,6])
#修改元素
#list1[2]=8.7
#删除元素
#del list1[4]
#插入数据
list1.insert(3,134)
print(list1)
|
8761fb92d6d76620dcedc3010872fa199839c9a9 | nielsgroenning/pythonbeginners | /Final_Exam_EDX_1.py | 763 | 4.1875 | 4 | def str_analysis(user_input):
if user_input.isdigit() and int(user_input) > 99:
print(user_input,' is a pretty big number')
elif user_input.isdigit() and int(user_input) < 99:
print(user_input, ' is a smaller number than expected')
elif user_input.isalpha():
print('\"'+ user_input +'\"'' is all alphabetical Characters')
else:
print("The input is a both alphanumeric and integeres")
while True:
user_input = input('Please write a Word or an Integer: ')
if user_input.isalpha():
str_analysis(user_input)
break
elif user_input.isdigit():
str_analysis(user_input)
break
else:
print("You did not write a word or an integer.\nTry again")
|
b9f698b6d62c86ca53ae3e13ad7de9573f68c3e6 | CrzRabbit/Python | /leetcode/0137_M_只出现一次的数字 II.py | 995 | 3.78125 | 4 | '''
给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
示例 1:
输入:nums = [2,2,3,2]
输出:3
示例 2:
输入:nums = [0,1,0,1,0,1,99]
输出:99
提示:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
'''
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ret = {}
for num in nums:
if num not in ret:
ret[num] = 1
else:
ret[num] += 1
for k in ret.keys():
if ret[k] == 1:
return k
return None
nums = [0,1,0,1,0,1,99]
so = Solution()
print(so.singleNumber(nums)) |
3948bed7bb8f579ef3341142b68b8fd89dad201b | kkdelux/practice-python | /Data_Structures/Hash_Tables/hashing_by_chaining.py | 5,057 | 4.03125 | 4 | # To solve hashing by chaining in Python I will need:
# -Linked List class (with a Node class) with methods:
# * push_back(value)
# * find(value)
# * delete(value)
# -Hash function to map items to array as list nodes
# -Hash_Table data structure with the methods:
# * add(key, value)
# * exists(key)
# * get(key)
# * remove(key)
class Linked_List:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def empty(self):
if self.head:
return False
else:
return True
def push_back(self, key, value=None):
node = Node(key, value)
if self.tail:
prev_tail = self.tail
prev_tail.next_node = node
else:
self.head = node
self.tail = node
self.size += 1
def find(self, key):
if self.head:
cur_node = self.head
while cur_node:
if cur_node.key and cur_node.key == key:
return cur_node
else:
cur_node = cur_node.next_node
return None
else:
return None
def delete(self, key):
if self.head:
if self.head.key == key:
node = self.head
self.head = self.head.next_node
del node
elif self.head.key != key and self.head.next_node:
prev_node = self.head
node = self.head.next_node
while node.key != key and node.next_node:
prev_node = node
node = node.next_node
if node.key == key:
prev_node.next_node = node.next_node
if prev_node.next_node == None:
self.tail = prev_node
else:
print "Cannot find key in list"
return
else:
print "Cannot find key in list"
return
else:
print "Cannot delete element from empty list"
return
self.size -= 1
def print_list(self):
node = self.head
while node:
print (str(node.key) + " : " + str(node.value) + ", ") if node.value else (str(node.key) + ", "),
node = node.next_node
print
class Node:
def __init__(self, key, value=None):
self.key = key
self.value = value
self.next_node = None
# Creating hash function outside hash table obj
def Hash(k, m):
total = 0
if type(k) is str:
for i in k:
total += ord(i)
elif type(k) is int:
total = k
elif type(k) is float:
total = int(k)
return total % m
class Hash_Table:
def __init__(self, size=8):
self.table_size = size
self.elem_size = 0
self.arr = [Linked_List() for i in range(self.table_size)]
def resize(self):
if self.elem_size >= (self.table_size * 0.75):
new_table = Hash_Table(self.table_size * 2)
for i in self.arr:
if not i.empty():
node = i.head
while node:
new_table.add(node.key[0], node.key[1])
node = node.next_node
self = new_table
def add(self, key, value=None):
self.resize()
pos = Hash(key, self.table_size)
if self.arr[pos].find(key):
node = self.arr[pos].find(key)
node.value = value
else:
self.arr[Hash(key, self.table_size)].push_back(key, value)
self.elem_size += 1
return
def exists(self, key):
pos = Hash(key, self.table_size)
if self.arr[pos].find(key):
return True
else:
return False
def get(self, key):
pos = Hash(key, self.table_size)
node = self.arr[pos].find(key)
if node:
return node.value if node.value else node.key
else:
print "Key not found in table"
return
def remove(self, key):
pos = Hash(key, self.table_size)
node = self.arr[pos].find(key)
if node:
self.arr[pos].delete(node.key)
return
else:
print "Cannot remove an unfound element from the table"
return
def print_table(self):
for i in range(len(self.arr)):
LL = self.arr[i]
if not LL.empty():
node = LL.head
while node:
print (str(node.key) + " : " + str(node.value) + ", ") if node.value else (str(node.key) + ", "),
node = node.next_node
print
HT = Hash_Table()
HT.add('kyle', 'strem')
HT.print_table()
HT.add(12)
HT.print_table()
print HT.exists(12)
print HT.get(12)
HT.remove('kyle')
HT.print_table() |
d9f01832efa82060c7a9e54a05d2dc45d7cf7652 | leeeju/PyCharm | /PyCharm4.py | 180 | 3.625 | 4 | h = int(input('근무시간'))
p = int(input('시간당 임금'))
if h > 40:
over = h - 40
total = p * 40 + over * p * 1.5
else:
total = h * p
print(f'total{total}')
|
639406c9ee69b1902d25d28ca72424a94f216c8b | xiaomojie/NowCoder | /offer/18.删除链表的节点.py | 1,749 | 3.984375 | 4 | """
在O(1)时间内删除链表节点
给定单项链表的头指针和一个节点指针,定义一个函数在O(1)时间内删除该节点
"""
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def delete_node(self, head, node):
# 最容易想到的方法就是从头往后遍历,是因为要得到被删除节点的前一个节点,但是时间是O(n)
# 其实也可以把被删除节点的后一个节点的内容复制到要删除的节点上,然后删除下一个节点,不过
# 这样就改变了链表的原始结构了(并不算),但是复杂度为O(1)
# 此时还要考虑一些特殊情况:
# 1. 删除的是尾节点,此时下一个节点为空,此时就只能从头遍历了
# 2. 只有一个节点,且要删除这个节点,即删除头结点/尾节点,删除这个节点且将头结点设为空
if not head or not node:
return
if node.next:
node.val = node.next.val
node.next = node.next.next
elif not head.next and head == node:
head = None
else:
p = head
while p.next != node:
p = p.next
p.next = None
return head
p = head = ListNode(1)
# print(head.val, head.next)
p.next = ListNode(2)
# print(head.val,head.next.val, head.next)
p = p.next
p.next = ListNode(3)
# print(head.val, head.next.val, head.next.next.val, head.next.next)
p = p.next
p.next = ListNode(4)
p = p.next
# print(head.val, head.next.val, head.next.next.val, head.next.next.next.val, head.next.next.next)
head = Solution().delete_node(head, p)
while head:
print(head.val)
head = head.next
|
178e62966e7ef4164d4a41341ce1a1a0a2fb05d4 | sharonLuo/LeetCode_py | /length-of-last-word.py | 1,481 | 3.734375 | 4 |
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World",
return 5.
"""
### beat 67%
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
rst = 0
if len(s) > 0:
i = len(s)-1
while i >= 0:
if not s[i].isspace():
rst += 1
else:
if rst != 0:
break
i -= 1
return rst
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
size = len(s)
inx = size-1
while inx >= 0 and s[inx] == " ":
inx -= 1
if inx == -1:
return 0
end_word_inx = inx
while inx >= 0 and s[inx] != " ":
inx -= 1
return end_word_inx - inx
### beat 30%
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
word_list = s.split()
if len(word_list) == 0:
return 0
else:
return len(word_list[len(word_list)-1])
|
0dc9fe0f48db1b10cfaff89b7017451fc088ae46 | korosh1990/python-parsclick | /04 Syntax/syntax.py | 361 | 3.78125 | 4 | #!/usr/local/bin/python3.4
class Nedah:
def __init__(self, kind = "girl"):
self.kind = kind
def whatKind(self):
return self.kind
#------------------------------------------------
def main():
girl = Nedah()
niceGirl = Nedah("nice")
print(girl.whatKind())
print(niceGirl.whatKind())
if __name__ == "__main__": main() |
44603f69fdb185cdbe63b63f249f62cb7f47dff7 | ArmineG/python | /class.py | 693 | 3.515625 | 4 | class BankAccount:
def __init__(self, name, balance=0.0):
self.log("Account is created!")
self.name=name
self.balance = balance
def getBalance(self):
self.log("Balance checked at" + str(self.balance))
return self.balance
def deposit (self, amount):
self.balance += amount
self.log("+" + str(amount) + ":" + str(self.balance))
def withdraw(self, amount):
self.balance -= amount
self.log("-" + str(amount) + ":" + str(self.balance))
def log(self, message):
print(message)
my_bank_account = BankAccount("Jirayr Melikyan")
my_bank_account.deposit(20.0)
my_bank_account.getBalance()
my_bank_account.withdraw(10.0)
my_bank_account.getBalance()
|
c76dbeb7e3b91e0b067817f73d93d31ce4cb9de9 | Navid2zp/ClassAttendanceManager | /ClassAttendanceManager/ClassAttendanceManager.py | 7,940 | 3.828125 | 4 | import json
import time
class AttendanceList(object):
def __init__(self):
self.total_weeks = 16
self.data = {}
self.load_list()
# Load students list
def load_list(self):
with open('list.json') as outfile:
data = json.load(outfile)
self.data = data
# Change total number of weeks shown in the list
# Decreasing the list won't cause any data to be removed
def change_total_weeks(self):
valid = False
new_total_weeks = ""
while not valid:
new_total_weeks = input("How many weeks?\n")
try:
new_total_weeks = int(new_total_weeks)
valid = True
except:
print("Please enter a number!")
self.total_weeks = new_total_weeks
print(f'Total weeks changed to {new_total_weeks}')
@staticmethod
def print_menu_options():
print("""
help - Show help menu
start - Start attendance procedure
list - Show students list
add - Add a student
del - Delete a student
search - Search for students
weeks - Increase or Decrease total weeks (Default is 16)
exit - Exit the program
reset - Reset all data
""")
# Get the table header depending on total weeks
def get_attendance_string(self):
string = ""
space_len = 4
for i in range(self.total_weeks):
string += "Week " + str(i + 1) + " " * (space_len - len(str(i+1)))
return string
# Clears the list.json file + some fun stuff :D
def reset(self):
print("Warning: This action is not recoverable!")
confirm = input("Please send CONFIRM to reset everything!\n")
if confirm == "CONFIRM":
# Just to look cooler :D
print("Reseting ...")
for i in range(21):
p = "=" * i
s = " " * (20 - i)
l = round((100 / 21) * (i + 1))
print(f'[{p}{s}] - {l}%', end="\r")
time.sleep(0.3)
self.data = {}
self.save_changes()
print("\nCompleted!")
# First part of table header
def get_list_string(self):
return "ID Name "
# Save all the changes to list.json file
def save_changes(self):
with open('list.json', 'w') as json_file:
json.dump(self.data, json_file)
def add_student(self):
student_name = input("Please enter a name:\n")
valid_id = False
student_number = ""
while not valid_id:
student_number = input("Please enter student number (Example: 930234875):\n")
if len(student_number) == 9:
try:
int(student_number)
valid_id = True
except:
pass
if not valid_id:
print("Student number should be a number with a length equal to 9")
student_id = str(len(self.data.keys()) + 1)
self.data[student_id] = {
"ID": student_number,
"Name": student_name,
"attendances": []
}
self.save_changes()
print("Student added :)")
def delete_student(self):
student_id = input("Enter student ID from list (Not student number!):\n")
try:
del self.data[student_id]
self.save_changes()
print("Student deleted :)")
except:
print("No such student!")
def add_attendance(self, student_id, status, week):
if len(self.data[student_id]["attendances"]) < week:
for i in range(week - len(self.data[student_id]["attendances"])):
self.data[student_id]["attendances"].append("-")
self.data[student_id]["attendances"][week - 1] = status
@staticmethod
def get_attendance_status():
valid_status = False
status = ""
while not valid_status:
status = input("(A) absent or (P) present:\n")
if status.lower() in ["a", "p"]:
status = status.upper()
valid_status = True
else:
print("Enter A for absent or B for present!")
return status
def do_attendance(self):
valid_week = False
week_number = 1
while not valid_week:
week_number = input("Week number:\n")
try:
week_number = int(week_number)
if 0 < week_number <= self.total_weeks:
valid_week = True
else:
print(f'Week number should be between 0 and {self.total_weeks + 1}')
except:
print("Week NUMBER!")
mode = input("Enter 0 to loop over all students or enter student ID from list:\n")
if mode == "0":
for student in self.data:
print(self.data[student]["Name"])
status = self.get_attendance_status()
self.add_attendance(student, status, week_number)
print("All Done :)")
else:
if mode not in self.data.keys():
print("No student found with that ID!")
else:
status = self.get_attendance_status()
self.add_attendance(mode, status, week_number)
print("Done :)")
self.save_changes()
def printstudents_list(self, students_list):
id_len = 3
name_len = 24
string = ""
for student in students_list:
string += student + str(" " * (id_len - len(student)))
string += students_list[student]["Name"] + " " * (name_len - len(students_list[student]["Name"]))
for i in range(self.total_weeks):
try:
string += " " * 4 + students_list[student]["attendances"][i] + " " * 4
except:
string += " " * 4 + "-" + " " * 4
string += '\n'
print(string)
def search(self):
name = input("Please enter a name:\n")
search_result = {}
counter = 1
for student_id in self.data:
student = self.data[student_id]
if student["Name"].lower() == name.lower() or name.lower() in student["Name"].lower():
search_result[str(student_id)] = student
counter += 1
if len(search_result.keys()) > 0:
print(self.get_list_string() + self.get_attendance_string())
print(self.printstudents_list(search_result))
def start(self):
running = True
self.print_menu_options()
while running:
command = input("Enter your command (help for menu):\n\n")
if command.lower() == "help":
self.print_menu_options()
elif command.lower() == "start":
self.do_attendance()
elif command.lower() == "search":
self.search()
elif command.lower() == "list":
print(self.get_list_string() + self.get_attendance_string())
print(self.printstudents_list(self.data))
elif command.lower() == "add":
self.add_student()
elif command.lower() == "del":
self.delete_student()
elif command.lower() == "exit":
print("Bye Bye :)")
running = False
elif command.lower() == "weeks":
self.change_total_weeks()
elif command.lower() == "reset":
self.reset()
def main():
attendance_obj = AttendanceList()
attendance_obj.start()
if __name__ == "__main__":
main()
|
d295459bc66ed7f5c321537aec3dce8ca9ad692d | carlton435/cp1404practicals | /prac_02/files.py | 445 | 3.75 | 4 |
out_file = open("name.txt", 'w')
name = input("enter your name:")
print(name, file=out_file)
out_file.close()
in_file = open("name.txt", "r")
name = in_file.read()
print("Your name is", name)
in_file.close()
in_file = open("numbers.txt", "r")
number1 = int(in_file.readline())
number2 = int(in_file.readline())
print(number1 + number2)
in_file.close()
in_file = open("numbers.txt", "r")
line = in_file.readlines()
print(line)
in_file.close() |
c0713c25a6db532ce8bf95af85e9e891f41867bc | Monterroso/Tic-Tac-Toe-React-Node.js-Python | /public/Python/board.py | 15,805 | 3.96875 | 4 | import copy
import json
import unittest
class Board:
"""Class representing a board
Members:
grid {list of (list of (int))} -- The 2d array of the grid
x_dist {integer} -- The size of the grid in the X dimension
y_dist {integer} -- The size of the grid in the Y dimension
Methods:
__init__(integer, integer, list of (list of (int))) -- Creates the empty grid, or copies a grid if an array is given
__eq__(object) -- Overloads the equality operator, two boards are equal if their grids are equal
get_at(tuple of (integer, integer)) -- Gets the value at the specified x,y location in the grid
place_at(integer, tuple of (integer, integer)) -- Places the id at the tuple location
get_states(integer) -- Gets all possible states for a given player
check_win(integer) -- Checks if the player is in a win state (only horizontal and vertical)
check_tie() -- Checks if current state is in a tie state (only if the board is completely filled)
copy() -- Copies the grid object and returns the new object
to_JSON() -- Returns this board in JSON format
"""
def __init__(self, x=None, y=None, grid=None):
"""Creates an empty Board with given dimensions if grid is None, copies grid otherwise
Arguments:
x_dist {integer} -- The size of the grid in the X dimension
y_dist {integer} -- The size of the grid in the Y dimension
Raises:
AttributeError -- Exception if the given grid is not uniform in it's height
AttributeError -- Exception if the grid contains a non-integer value
"""
if grid is None:
self.x_dist = x
self.y_dist = y
self.grid = [[0 for _ in range(y)] for _ in range(x)]
else:
#Check to be sure the dimensions are valid
temp_x = len(grid)
temp_y = len(grid[0])
for x in range(len(grid)):
if len(grid[x]) != temp_y:
raise AttributeError("The given grid does not have columns of the same length")
for y in range(len(grid[x])):
if not isinstance(grid[x][y], int):
raise AttributeError("The given grid contains a non integer value at {0}".format((x, y)))
self.x_dist = temp_x
self.y_dist = temp_y
self.grid = copy.deepcopy(grid)
def __eq__(self, obj):
"""Overrides the == operator, two board objects are equal if their grids are the same
Arguments:
obj {object} -- The object we are comparing to self
"""
return isinstance(obj, Board) and obj.grid == self.grid
def get_at(self, location):
"""Returns the value at the specified location
Arguments:
location {tuple of (integer, integer)} -- The tuple to represent the x,y location of the slot
Returns:
{integer} -- The value of the specified slot, 0 if empty, or a player_id if not empty
Raises:
IndexError -- Raised when a location outside of the grid space is attempted to be accessed.
"""
x_look = location[0]
y_look = location[1]
if x_look >= self.x_dist or y_look >= self.y_dist:
raise IndexError("{0} is out of the range of this grid, of width {1} and height {2}".format((x_look,y_look),\
self.x_dist, self.y_dist))
return self.grid[location[0]][location[1]]
def place_at(self, player_id, location):
"""Places the player_id at the location given by the location
Arguments:
player_id {integer} -- The player id to be placed on the grid at the location
location {tuple of (integer, integer)} -- The tuple to represent the x,y location of the slot
Raises:
AttributeError -- Error if the location to place is already occupied.
IndexError -- Error if the location is out of bounds
"""
x_pos = location[0]
y_pos = location[1]
#check if the location is currently occupied
if x_pos >= self.x_dist or y_pos >= self.y_dist:
raise IndexError("The location {0} is out of bounds")
if self.grid[x_pos][y_pos] is not 0:
raise AttributeError("The location {0} is occupied with {1}, you cannot place an id there".format(\
(x_pos, y_pos), self.grid[x_pos][y_pos]))
#sets the id
self.grid[x_pos][y_pos] = player_id
def get_states(self, player_id):
"""Returns all possible game states the player can make
Arguments:
player_id {integer} -- The id of the player
Returns:
{list of (Board)} -- The list of Boards that the player can branch to
"""
boards = []
#Double for loop through x and y coordinates
for x in range(self.x_dist):
for y in range(self.y_dist):
#check if space is free
#if free, dupblicate board, add id to location
#add board to boards
if self.get_at((x, y)) == 0:
new_board = self.copy()
new_board.place_at(player_id, (x, y))
boards.append(new_board)
#return boards
return boards
def check_win(self, win_amount, player_id):
"""Checks if the player has won
Arguments:
win_amount {integer} -- The number of consecutive tiles to win
player_id {integer} -- The id of the player we are checking
Returns:
{boolean} -- Returns true if the player has won, false if they have not
"""
#Row Check
for x in range(self.x_dist):
counter = 0
for y in range(self.y_dist):
if self.get_at((x,y)) == player_id:
counter += 1
else:
counter = 0
if counter == win_amount:
return True
#Column Check
for y in range(self.y_dist):
counter = 0
for x in range(self.x_dist):
if self.get_at((x,y)) == player_id:
counter += 1
else:
counter = 0
if counter == win_amount:
return True
#If hasn't returned true, then it's false
return False
def check_tie(self):
"""Checks if there is no way a player can win, currently returns true if and only if the board is filled
Returns:
{boolean} -- Returns true if the player is not able to win, false if they still can.
"""
for x in range(self.x_dist):
for y in range(self.y_dist):
if self.get_at((x,y)) == 0:
return False
return True
def copy(self):
"""Returns a copy of this grid
Returns:
{Board} -- A deep copy of this grid
"""
return Board(grid=self.grid)
def to_json(self):
"""Returns this board as a JSON object
Returns:
{JSON} -- This object encoded as a JSON, info on the grid, the x and y coordinates
"""
object_json = dict()
object_json["Type"] = self.__class__.__name__
board_obj = dict()
board_obj["x"] = self.x_dist
board_obj["y"] = self.y_dist
board_obj["grid"] = self.grid
object_json["Object"] = board_obj
return json.dumps(object_json)
class BoardTests(unittest.TestCase):
"""Full suit of testing for the board and it's functionality
"""
def test_init(self):
"""Suite testing the init functionality
"""
a_x_dist = 3
a_y_dist = 5
a_board = Board(a_x_dist, a_y_dist)
a_grid_copy = [[0 for _ in range(a_y_dist)] for _ in range(a_x_dist)]
#Check to be sure a_Board has proper attributes
self.assertEqual(a_board.x_dist, a_x_dist, "The x distance was not properly set")
self.assertEqual(a_board.y_dist, a_y_dist, "The y distance was not properly set")
self.assertEqual(len(a_board.grid), a_x_dist, "The width of the grid was not properly set")
self.assertEqual(len(a_board.grid[2]), a_y_dist, "The height of the grid was not properly set")
self.assertEqual(a_board.grid, a_grid_copy, "One of the values in the grid was not set")
b_x_dist = 20
b_y_dist = 2
b_board = Board(b_x_dist, b_y_dist)
b_grid_copy = [[0 for _ in range(b_y_dist)] for _ in range(b_x_dist)]
#Check to be sure a_Board has proper attributes
self.assertEqual(b_board.x_dist, b_x_dist, "The x distance was not properly set")
self.assertEqual(b_board.y_dist, b_y_dist, "The y distance was not properly set")
self.assertEqual(len(b_board.grid), b_x_dist, "The width of the grid was not properly set")
self.assertEqual(len(b_board.grid[2]), b_y_dist, "The height of the grid was not properly set")
self.assertEqual(b_board.grid, b_grid_copy, "One of the values in the grid was not set")
#Check to make sure that the board is properly cloned
c_x_dist = 5
c_y_dist = 3
c_grid = [[0,0,0],[1,2,1],[0,1,1],[2,2,2],[1,0,0]]
c_grid_copy = [[0,0,0],[1,2,1],[0,1,1],[2,2,2],[1,0,0]]
c_board = Board(grid=c_grid)
self.assertEqual(c_board.x_dist, c_x_dist, "The x distance was not properly set")
self.assertEqual(c_board.y_dist, c_y_dist, "The y distance was not properly set")
self.assertEqual(len(c_board.grid), c_x_dist, "The width of the grid was not properly set")
self.assertEqual(len(c_board.grid[2]), c_y_dist, "The height of the grid was not properly set")
self.assertEqual(False, c_board.grid is c_grid, "The grid was not deep copied")
self.assertEqual(c_board.grid, c_grid_copy, "One of the values in the grid was not properly copied over")
def test_init_exceptions(self):
"""Suite testing the behavior of the exceptions in the init method
"""
#Check proper exceptions are raised
uneven_board = [[1,2,3],[0,0],[1,2,5]]
self.assertRaises(AttributeError, Board, grid=uneven_board)
non_int_board = [[1,2],[1,3],['a',7]]
self.assertRaises(AttributeError, Board, grid=non_int_board)
def test_get_at(self):
"""Suite testing the get_at(self, location) method
"""
a_grid = [[1,2,3,4,5],[11,12,13,14,15],[21,22,23,24,25],[31,32,33,34,35]]
a_board = Board(grid=a_grid)
self.assertEqual(a_board.get_at((0,4)), 5)
self.assertEqual(a_board.get_at((3,3)), 34)
self.assertEqual(a_board.get_at((2,1)), 22)
self.assertEqual(a_board.get_at((0,4)), 5)
def test_get_at_exceptions(self):
"""Suite testing the behavior of the exceptions of the get_at method
"""
a_grid = [[0,1,2,3],[10,11,12,13],[20,21,22,23],[30,31,32,33],[40,41,42,43]]
a_board = Board(grid=a_grid)
self.assertRaises(IndexError, a_board.get_at, (5,5))
def test_place_at(self):
"""Suite testing the place_at method
"""
a_grid = [[0,0],[1,2],[1,0],[2,0],[5,5],[0,0]]
a_complete_grid = [[3,1],[1,2],[1,2],[2,0],[5,5],[0,5]]
a_board = Board(grid=a_grid)
a_board.place_at(1, (0,1))
a_board.place_at(2, (2,1))
a_board.place_at(5, (5,1))
a_board.place_at(3, (0,0))
for x in range(a_board.x_dist):
for y in range(a_board.y_dist):
self.assertEqual(a_board.grid[x][y], a_complete_grid[x][y],\
"The value at {0} was not properly placed".format((x,y)))
def test_place_at_exceptions(self):
"""Suite testing the exceptions raised in the place_at method
"""
a_grid = [[0,2,3,4,5,6,0]]
a_board = Board(grid=a_grid)
self.assertRaises(AttributeError, a_board.place_at, 1,(0,4))
self.assertRaises(IndexError, a_board.place_at, 2,(2,2))
def test_get_states(self):
"""Suite testing that all possible states are computed by the game given a player
"""
a_x_dist = 5
a_y_dist = 4
a_board = Board(a_x_dist, a_y_dist)
a_player = 1
a_board_states = a_board.get_states(a_player)
for x in range(a_x_dist):
for y in range(a_y_dist):
temp_board = a_board.copy()
temp_board.place_at(a_player, (x, y))
# self.assertTrue(temp_board.grid in [state.grid for state in a_board_states])
self.assertTrue(temp_board in state for state in a_board_states)
self.assertEqual(len(a_board_states), a_x_dist * a_y_dist)
b_x_dist = 4
b_y_dist = 3
b_grid = [[1,0,0],[2,0,2],[5,0,3],[1,1,1]]
b_player = 2
b_state_results = [Board(grid=[[1,b_player,0],[2,0,2],[5,0,3],[1,1,1]]),
Board(grid=[[1,0,b_player],[2,0,2],[5,0,3],[1,1,1]]),
Board(grid=[[1,0,0],[2,b_player,2],[5,0,3],[1,1,1]]),
Board(grid=[[1,0,0],[2,0,2],[5,b_player,3],[1,1,1]])]
b_board = Board(grid=b_grid)
b_board_states = b_board.get_states(b_player)
# self.assertTrue(all(b_brd in [state.grid for state in b_board_states] for b_brd in b_state_results))
for b_brd in b_state_results:
self.assertTrue(b_brd in b_board_states, "{0} is not in {1}".format(b_brd,b_board_states))
# self.assertTrue(all(b_brd in b_board_states for b_brd in b_state_results))
self.assertEqual(len(b_state_results), len(b_board_states))
def test_check_win(self):
"""Suite testing that wins are properly caught
"""
#Checks a few cases of not having a win, along with a few of having a win.
#Not wins for player 1
not_player = 1
not_a_grid = [[1,0,0],[1,1,0],[0,0,1],[0,1,1]]
not_b_grid = [[1,2,2,1,1],[0,2,1,1,1],[2,2,2,1,1]]
not_c_grid = [[0,0],[0,0],[0,0],[0,0]]
not_a_board = Board(grid=not_a_grid)
not_b_board = Board(grid=not_b_grid)
not_c_board = Board(grid=not_c_grid)
not_a_win = 3
not_b_win = 4
not_c_win = 1
self.assertFalse(not_a_board.check_win(not_a_win, not_player))
self.assertFalse(not_b_board.check_win(not_b_win, not_player))
self.assertFalse(not_c_board.check_win(not_c_win, not_player))
#Wins for player 2
yes_player = 2
yes_a_grid = [[2,2,2],[1,0,0],[0,0,0],[2,0,0],[1,1,1]]
yes_b_grid = [[0,0,0],[1,1,1],[1,1,1]]
yes_c_grid = [[0,1,2,2,0],[2,0,1,2,1],[0,0,0,2,0],[1,1,1,2,1],[0,0,0,2,1],[0,1,2,2,1]]
yes_a_board = Board(grid=yes_a_grid)
yes_b_board = Board(grid=yes_b_grid)
yes_c_board = Board(grid=yes_c_grid)
yes_a_win = 3
yes_b_win = 0
yes_c_win = 6
self.assertTrue(yes_a_board.check_win(yes_a_win, yes_player))
self.assertTrue(yes_b_board.check_win( yes_b_win, yes_player))
self.assertTrue(yes_c_board.check_win(yes_c_win, yes_player))
def test_check_tie(self):
"""Suite testing that ties are properly caught
"""
#Just check if not all are open, vs all being open
not_tie_a_grid = [[0,0,0],[1,0,0],[0,0,0],[0,0,0],[0,0,0]]
not_tie_a_board = Board(grid=not_tie_a_grid)
self.assertFalse(not_tie_a_board.check_tie())
tie_a_grid = [[1 for _ in range(5)] for _ in range(10)]
tie_a_board = Board(grid=tie_a_grid)
self.assertTrue(tie_a_board.check_tie())
def test_copy(self):
"""Suite testing the functionality of the copy method
"""
a_grid = [[0,2,3,4,5,6,0]]
a_board = Board(grid=a_grid)
b_board = a_board.copy()
self.assertEqual(False, a_board is b_board, "The boards are the same and a deepy copy wasn't created")
def test_to_JSON(self):
"""Suite testing that a JSON object is properly created from this board
"""
a_x_dist = 5
a_y_dist = 4
a_grid = [[1,2,0,0],[0,0,0,0],[1,1,1,1],[0,0,0,0],[2,2,2,2]]
a_grid_string = "[[1, 2, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [2, 2, 2, 2]]"
a_board = Board(grid=a_grid)
a_board_string = '{{"Type": "Board", "Object": {{"x": {0}, "y": {1}, "grid": {2}}}}}'\
.format(a_x_dist, a_y_dist, a_grid_string)
a_board_json = a_board.to_json()
print(a_board_json)
self.assertEqual(a_board_json, a_board_string)
if __name__ == '__main__':
unittest.main() |
f661306b819c82ecd69239f73e70eedd013bad27 | duongdinh24/learn-python | /bai62.py | 300 | 3.6875 | 4 | import numpy as np
x=np.random.randint(0,10) #random ra phần tử bất kỳ
x=[]
y=[]
for i in range(10):
x.append(np.random.randint(1,10))
y.append(np.random.randint(1,10))
print(x,y)
x=np.array(x)
y=np.array(y)
np.add(x,y)
np.maxium(x,y)
np.minium(x,y)
np.sqrt(x)
np.square(x,y) |
2adf9dbfa57aa0300bc3ac5777a7cecd182cee78 | Fhernd/Python-CursoV2 | /parte05/ex5.13_union_interseccion_conjuntos.py | 608 | 4.15625 | 4 | # Ejercicio 5.13: Realizar operaciones de unión e intersección de conjuntos.
numeros = set(list(range(1, 11)))
primos = set([2, 3, 5, 7, 11, 13, 17, 19])
print('Contenido del conjunto `numeros`:', numeros)
print('Contenido del conjunto `primos`:', primos)
print()
union = numeros.union(primos)
print('Contenido del conjunto `union`:', union)
print('Cantidad de elementos del conjunto `union`:', len(union))
print()
interseccion = primos.intersection(numeros)
print('Contenido del conjunto `interseccion`:', interseccion)
print('Cantidad de elementos del conjunto `interseccion`:', len(interseccion))
|
2667c8bbb09381266e065249cc82417f62a6f398 | phongluudn1997/leet_code | /reverse_string.py | 361 | 3.6875 | 4 | class Solution:
def reverseString(self, s):
"""
Do not return anything, modify s in-place instead.
"""
l = len(s)
if l < 2:
return s
return self.reverseString(s[l//2:]) + self.reverseString(s[:l//2])
solution = Solution()
result = solution.reverseString(["h", "e", "l", "l", "o"])
print(result)
|
5b7eec2ae592542a68008e25ad5deb46b3c8ed62 | sinbak/py_practice | /python_assign1/제곱과 덧세만.py | 795 | 3.859375 | 4 | def square(n):
if n == 0:
return 0
else:
return 2*(abs(n)-1)+1 + square(abs(n)-1)
def square1(n): #꼬리재귀
def loop(n, ans):
if n == 0:
return 0
else:
return 2*(abs(n)-1)+1 + loop(abs(n)-1, ans + 2*(abs(n)-1)+1)
return loop(n, 0)
def square2(n):
ans = 0
while abs(n) > 0:
n, ans = abs(n)-1, 2*abs(n)-1 + ans
return ans
print(square(0))
print(square(1))
print(square(-2))
print(square(3))
print(square(5))
print(square(-4))
print("///////////")
print(square1(0))
print(square1(1))
print(square1(-2))
print(square1(3))
print(square1(5))
print(square1(-4))
print("mmmmmmmm")
print(square2(0))
print(square2(1))
print(square2(-2))
print(square2(3))
print(square2(5))
print(square2(-4)) |
959850fa9dac7a9010699ea0d6e3e350002396d8 | aaldridge81/rock-paper-scissors-exercise | /game.py | 2,328 | 4.09375 | 4 | # game.py
# importing random function
import random
import os
import dotenv
from dotenv import load_dotenv
load_dotenv() # invoke the function
# introduction to game
print("-------------------")
USER_NAME = os.getenv("USER_NAME", default="Player One")
print(f"PLAYER:'{USER_NAME}'")
print("-------------------")
# asking for user input
user_choice = input("Please choose either 'rock', 'paper', or 'scissors':")
user_choice = user_choice.lower()
# print(x)
print("You chose:", user_choice)
# NOTES from class: different ways to print a string
# can print many things in a string as long as they are seperated by commas
# print("you chose:",x,"another string",x)
# string concat:
# print("you chose:" + "other string here")
# string inerpolation / format string usage
# print(f"you chose: {x}")
# simulating a computer input
options = ['rock', 'paper', 'scissors']
# validate the user selection
#
# stop the program (not try to determine the winner)
# ... if the user choice is invalid
if user_choice in options:
pass
else:
print("OOPS, please choose a valid option and try again")
exit()
computer_choice = random.choice(options)
#NOTES from class
# alternative: computer_choice = choice(options)
print(f"The computer chose: {computer_choice}")
# determining who won
#single equal sign assigns value to variable. the way it is evaluated as saying what is on the right, and store it in the left
# equality operations. is what is on the left equal to what is on the right? true or false
if user_choice == computer_choice:
print("It's tie!")
elif user_choice == "paper" and computer_choice == "rock":
print("You win! Congrats")
elif user_choice == "paper" and computer_choice == "scissors":
print("Oh! The computer won, that's ok!")
elif user_choice == "rock" and computer_choice == "paper":
print("Oh! The computer won, that's ok!")
elif user_choice == "rock" and computer_choice == "scissors":
print("You win! Congrats")
elif user_choice == "scissors" and computer_choice == "paper":
print("You win! Congrats")
elif user_choice == "scissors" and computer_choice == "rock":
print("Oh! The computer won, that's ok!")
# adapted from solution shared by Will in Slack
|
0e4b1acad468158c1d65ff40caa67fc7cfc7f77b | krishnamech47/pythonprogramming | /fib.py | 108 | 3.5625 | 4 | n=int(input())
n1=1
n2=0
c=0
while(c<n):
print(n1,end=" ")
nth=n1+n2
n2=n1
n1=nth
c=c+1
|
cec89f7e2338f79f7ae736a594b383a18a1eeced | will300/Algorithms | /Moderate/intersection.py | 1,070 | 3.796875 | 4 | def intersection(start1, end1, start2, end2):
x11, y11 = start1
x12, y12 = end1
m1 = (y12 - y11) / (x12 - x11)
c1 = y11 - m1*x11
x21, y21 = start2
x22, y22 = end2
m2 = (y22 - y21) / (x22 - x21)
c2 = y21 - m2*x21
# m2*x + c2 = m1*x + c1
x = (c1 - c2) / (m2 - m1)
y = m1*x + c1
if min(start1[1], end1[1]) <= y <= max(start1[1], end1[1]):
return x, y
else:
return "intersection not found"
def test_case(start1, end1, start2, end2, solution, test_func):
tol = 0.1
output = test_func(start1, end1, start2, end2)
if type(solution) == str:
if type(output) == str:
print("Passed")
else:
print(f"Failed, expected {solution}, got {output}")
elif solution[0] - tol <= output[0] <= solution[0] + tol and \
solution[1] - tol <= output[1] <= solution[1] + tol:
print("Passed")
else:
print(f"Failed, expected {solution}, got {output}")
test_case((-14, 0), (0, -7), (-4, -10), (0, 2), (-2.58, -5.71), intersection)
|
e00486a4cfd4580a1e4466c55f4af92243c6e732 | 15194779206/practice_tests | /education/A:pythonBase_danei/1:python基础/8:第八天/3.1:集合的运算.py | 292 | 3.5 | 4 | s1={1,2,3}
s2={2,3,4}
#交集 &
print(s1&s2)
#并集 |
print(s1|s2)
#补集 -
print(s1-s2)#生成属于s1但是不属于s2的值
print(s2-s1)
#对称补集
print(s1^s2)
#子集 <
l={1,2,3}<{1,4}
print(l) #false
#超集 >
l={1,2,3}> {1,3}
print(l) #true
|
97278eed180c757bd1fbe90cded19bed0ea6103c | shri-hari27/DSC-assignment | /python1.py (1).py | 498 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
thriller=["prison break"," avengers end game"," infinity war","Inception"," men in black"," mission impossible","Money Heist","wanda vision"]
comedy=["bean","johhny english","johhny english reborn","johnny english strikes again","rambo 2"]
i=0
movie=input("Enter the movie:")
if movie==thriller[i]:
print("It is a thriller")
elif movie==comedy[i]:
print("It is a comedy")
else:
print("It is not a thriller nor a comedy")
# In[ ]:
|
9dd76b0b1272f421fcc06b095d1af8fd7113eee5 | SimantaKarki/Python | /mergesort.py | 899 | 4.15625 | 4 | # merge sort using recursion
def mergeSort(A, l, r):
if (l >= r):
return
mid = (l+r)//2
mergeSort(A, l, mid)
mergeSort(A, mid+1, r)
merge(A, l, mid, r)
def merge(A, l, m, r):
first_half = A[l:m+1]
second_half = A[m+1:r+1]
i = 0
j = 0
k = l
while i < len(first_half) and j < len(second_half):
if first_half[i] <= second_half[j]:
A[k] = first_half[i]
i += 1
else:
A[k] = second_half[j]
j += 1
k = k+1
while i < len(first_half):
A[k] = first_half[i]
i = i + 1
k = k + 1
while j < len(second_half):
A[k] = second_half[j]
j = j + 1
k = k + 1
if __name__ == "__main__":
A = [33, 42, 9, 37, 8, 47, 5, 29, 49, 31, 4, 48, 16, 0, 26]
mergeSort(A, 0, len(A)-1)
print(A)
|
6d00f18a71a66c342e9118d6595dc08842e1d3c4 | ridhim-art/practice_list2.py | /tuple_set_dictionary/tuples.py | 424 | 3.90625 | 4 | x = (1,2,3,4) #tuples
y = 12,85,96,23 #called tuples
print(x)
print(y)
print(type(x))
print(type(y))
# list to couple conversion
a = [1,2,3,4]
at = tuple(a)
print(a,at)
name = 'ridhi'
namet = tuple(name)
print('string =>',name,'tuple =>',namet)
a = 1
b =2
c = 3
d = a,b,c
print(d)
#function
#count
#index
a = (1,2,8,38,5,9,5,89,9,6,1,2,95,99)
print("counting all 3s = ",a.count(3))
print("insex of 23 =",a.index(23))
|
614cfbf38f37e139c3e851c234e48735f9e4d4d8 | brizjose/JBCodingDojo | /python_stack/python_fundamentals/algorithms/algorithms_make_change.py | 1,415 | 3.765625 | 4 | def change(cents):
coins = {
'dollar': 1,
'quarter': 0.25,
'dime': 0.1,
'nickel': 0.05,
'penny': 0.01
}
#dollars = 0
#quarters = 0
#dimes = 0
#nickels = 0
#pennies = 0
if cents > coins['dollar']:
dollars = (int(cents/coins['dollar']))
remainder = cents - dollars
print "{} dollars".format(dollars)
print "and {} cents remaining".format(remainder)
if remainder > 0:
quarters = (int(remainder/coins['quarter']))
remainder = round(remainder - quarters*coins['quarter'],2)
print "{} quarters".format(quarters)
print "and {} cents remaining".format(remainder)
if remainder > 0:
dimes = (int(remainder/coins['dime']))
remainder = round(remainder - dimes*coins['dime'],2)
print "{} dimes".format(dimes)
print "and {} cents remaining".format(remainder)
if remainder > 0:
nickels = (int(remainder/coins['nickel']))
remainder = round(remainder - nickels*coins['nickel'],2)
print "{} nickels".format(nickels)
print "and {} cents remaining".format(remainder)
if remainder > 0:
pennies = (int(remainder/coins['penny']))
remainder = round(remainder - pennies*coins['penny'],2)
print "{} pennies".format(pennies)
print "and {} cents remaining".format(remainder)
change(3.8)
|
39e53947562fb4871b88bfc3f1de8bf5405d3c3a | Matt-McElheron/python_study | /gene30040/Rosalind_REVC.py | 2,070 | 4.34375 | 4 | #!/usr/bin/python3
# Task: Rosalind problem "REVC".
# Input: A DNA string s of nucleotides.
# Output: The reverse complement of s.
# Date: 06/06/2020
# The sys module allows intake of input variables.
import sys
# This function generates the reverse compliment of DNA.
def dna_revc(s):
# This string variable will be used to generate out output.
revc = ""
# We iterate over the reverse, uppercase form of the input
for base in s[::-1].upper():
# For each base we see, we add the compliment nucleotide to our new "revc" variable.
if base == "A":
revc = revc + "T"
elif base == "T":
revc = revc + "A"
elif base == "G":
revc = revc + "C"
elif base == "C":
revc = revc + "G"
# We then send back our new reverse compliment string.
return revc
# This main function calls our reverse transcribing function, then prints out the answer.
def main(str_input):
# The count is made here using a dictionary in this function.
revc = dna_revc(str_input)
# The requested output is then printed to screen.
print(revc)
return
# Here we execute our code, first checking what the input is correct.
if __name__ == "__main__":
# This line checks if the string has been given as a command line argument, and then uses it.
if len(sys.argv) == 2:
input_string = sys.argv[1]
main(input_string)
# This elif block checks if no command line arguments have been given.
# If none are given, this block will ask the user to input the string manually.
elif len(sys.argv) == 1:
input_string = input("Please provide a DNA string of nucleotides:\n")
main(input_string)
# If too many command line arguments have been given, the code will produce an error message plus an instruction.
else:
print("The correct input format has not been followed.\n"
"Please provide a DNA string s of nucleotides.")
|
7d945a758dbc8f3981ba939db0aa34c5657c2622 | robotammie/Skills-Assessment-1 | /functions.py | 2,535 | 4.34375 | 4 | def hello_world():
"""Prints 'Hello World' to the screen"""
print "Hello World"
def hi_name(name):
"""Prints 'Hi [string]' to screen"""
print "Hi", name
def product(num1, num2):
"""Prints the product of two integers"""
print num1 * num2
def repeat(text, times):
"""Prints the given text [times] number of times, with no spaces or line breaks"""
print text * times
def find_zero(num):
"""Tells the user if the given number is higher, lower, or equal to 0"""
if num > 0:
print "Higher than 0"
elif num < 0:
print "Lower than 0"
else:
print "Zero"
def mult_of_3(num):
"""Determines if the given integer is evenly divisible by 3"""
if num % 3 == 0:
return True
else:
return False
def num_spaces(sentence):
"""Determines the number of spaces in a given sentence"""
spaces = 0
for char in sentence:
if char == " ":
spaces += 1
return spaces
def add_tip(meal, tip=.15):
"""Determines the total cost (meal and tip) of a restaurant meal"""
return meal + meal * tip
def sign_parity(num):
"""Determines whether a given integer is positve or negative, and whether integer
is even or odd. Function returns this data as a tuple.
"""
# Determine sign
if num >= 0:
sign = 'Positive'
else:
sign = 'Negative'
# Determine parity
if num % 2 == 0:
parity = 'Even'
else:
parity = 'Odd'
return (sign, parity)
# test located in line 117, since code generally comes after all functions are defined.
def add_tax(price, state, tax=.05):
"""Determines the total price, tax included, of an item given its list price.
If the item is from California, the tax is updated to the higher, CA amount
"""
if state == "CA":
tax = .07
return price + price * tax
def title_name(name, title="Engineer"):
"""Prints the name and job title of a given person"""
return title + ' ' + name
def print_letter(addressee, a_title, sender):
"""Prints a flattering letter to the adressee"""
reciever = title_name(addressee, a_title)
print "Dear {r}, I think you are amazing!\nSincerely, {s}".format(r=reciever, s=sender)
def append_nums(numbers, num):
"""Appends the given number to the given string"""
numbers.append(num)
print numbers
# Unpack the results of sign_parity(int), print both.
num_sign, num_parity = sign_parity(-6)
print num_sign
print num_parity
|
3983da3d1c69dd08e63108074a97ace3634308b1 | MikeSoughton/Miscellaneous_code | /timer.py | 1,258 | 4.125 | 4 | #!/usr/bin/python
import time
def stopwatch(seconds):
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
print("loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed))
time.sleep(1)
#stopwatch(20)
def print_on_interval(savepoint, max_time):
start = time.time()
#time.clock()
time.perf_counter()
elapsed = 0
while True:
try:
while elapsed < max_time:
elapsed = time.time() - start
if round(elapsed,0) % savepoint == 0 and round(elapsed,1) > 0:
print("Maybe I can do something at this point in time...: %f, seconds count: %02d" % (time.perf_counter(), elapsed))
print("loop cycle time: %f, seconds count: %02d" % (time.perf_counter(), elapsed))
time.sleep(1)
except KeyboardInterrupt:
print("Are you sure you want to end the loop?")
end = input()
if end.lower() == "yes" or end.lower() == "y":
print("Ending loop now.")
break
else:
print("Continuing loop")
continue
break
print_on_interval(5, 10) |
2144a3881d4fd0a31789ea8605bb0a94a6685d63 | alvinaashraf/PythonAssignment | /assignemnt3.py | 1,543 | 4.09375 | 4 | val1 = input('enter first vale ')
val2 = input('enter second value ')
operator = input('enter operator ')
val1 = int(val1)
val2 = int(val2)
if operator == '+':
val = val1 + val2
print(val, 'answer')
elif operator == '-':
val = val1 - val2
print(val, 'answer')
elif operator == '*':
val = val1 * val2
print(val, 'answer')
elif operator == '/':
val = val1 / val2
print(val, 'answer')
else:
print('enter correct operator')
name = ['noman', 'shahzad', 'faisal', 'feroz', 'hussain' ,'7 ']
val = input('enter value ')
for numeric_value in name:
if val == '7':
print('there is the numeric value')
break
else:
print('there is no numeric value ')
break
customer = {
"f_name": "Shahid",
"l_name": "Hashmani",
"add": "DHA"
}
customer["language"] = "English"
print(customer)
numeric_items = {'a':500,'b':1000,'c':800}
print(sum(numeric_items.values()))
list_of_values = [20,30,40,50,60,30,70,80,40,90,70,100]
list_of_values.sort()
for duplicate_values in range (len (list_of_values) -1):
if list_of_values[duplicate_values] == list_of_values[duplicate_values+1]:
print (list_of_values[duplicate_values])
grocery_list = {1: "milk", 2: "oil", 3: "tea", 4: "cosmetics", 5: "tissue_paper", 6: "rice"}
def is_key_exist(x):
if x in grocery_list:
print('Key is already exist in a dictionary')
else:
print('Key is not exist in a dictionary')
is_key_exist(3)
|
8366bdb04efea0c40de1a8d2574a421cd09e510d | jackisace/primarySchool | /modules/classesModule.py | 3,221 | 3.5625 | 4 | from clear import clear
from helpModule import Help
allClasses = ["Art", "Science", "Maths", "English", "History", "Drama", "Music", "PE", "Cooking", "IT"]
def undoChanges(undoClasses):
""" Used for undoing the changes this session"""
classesFile = open("classes.txt", "w")
for eachClass in undoClasses:
classesFile.write(eachClass)
classesFile.write("\n")
classesFile.close()
return undoClasses
def acceptChanges(currentClasses):
"""used to accept the changes this session"""
classesFile = open("classes.txt", "w")
for eachClass in currentClasses:
classesFile.write(eachClass)
classesFile.write("\n")
classesFile.close()
def classes():
"""Classes module, for students to see and update the day's classes"""
classesFile = open("classes.txt", "r")
currentClasses = classesFile.read().split("\n")
undoClasses = []
for eachClass in currentClasses:
undoClasses.append(eachClass)
classesFile.close()
classesFile = None
while True:
clear("")
print("Classes")
print("=======")
print("\n\nYour classes for today are: \n")
for i in range(1,5):
print("{}) {}".format(i, currentClasses[i-1]))
print("\nupdate) update your classes")
print("accept) accept changes")
print("delete) delete changes")
print("quit) main menu")
try:
user = input("\n")[0]
except IndexError:
continue
if "h" in user:
if Help("Classes") == 1:
return
if "a" in user:
acceptChanges(currentClasses)
continue
if "d" in user:
currentClasses = undoChanges(undoClasses)
continue
if "q" in user:
return
if "u" in user:
print("Classes")
print("=======")
print("\n\nYour classes for today are: ")
i = 0
clear("")
for i in range(1,5):
print("{}) {}".format(i, currentClasses[i-1]))
userA = input("\nplease select which one you need to update: \n\n")
if userA == "q":
return
if userA == "quit":
return
if userA == "h":
if Help("Classes") == 1:
return
if userA == "help":
if Help("Classes") == 1:
return
userA = int(userA) - 1
j = 0
clear("")
for eachAllclass in allClasses:
if j < len(allClasses) - 1:
j += 1
print("{}) {}".format(j, eachAllclass))
userB = input("please select which one you need to update to: ")
if userB == "q":
return
if userB == "quit":
return
if userB == "h":
if Help("Classes") == 1:
return
if userB == "help":
if Help("Classes") == 1:
return
userB = int(userB) - 1
currentClasses[userA] = allClasses[userB]
|
0a2bfa3f3921f8d3c33395c072440ff35b25257d | ThalesLeal/python | /URI/atividade 1.py | 89 | 3.578125 | 4 | A = int(input("Valor de A"))
B = int(input("Valor de B"))
print("Soma = %i" % (A + B))
|
11e576c02ddd1f45ab4830116f935137c7e65805 | fgiacca56/Lab8-Python3 | /Pig.py | 13,003 | 3.984375 | 4 | import random
def rollDice():
return random.randint(1,6)
#question 1
def oneTurn():
turn_total = 0
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
value = True
else:
turn_total += roll
return turn_total
#oneTurn()
#question 2
def oneTurn2():
turn_total = 0
value = False
while not value:
roll = rollDice()
if roll == 1:
turn_total = 0
value = True
elif turn_total >= 20:
value = True
else:
turn_total += roll
return turn_total
def holdAtTwenty():
scores = {"0": 0, "20": 0,"21": 0,"22": 0, "23": 0, "24": 0, "25": 0}
integer = int(input("Hold-at-20 turn simulations?: "))
for i in range(integer):
total = str(oneTurn2())
if total in scores:
scores[total] += 1
print("Score" , "Estimated Probability", sep="\t")
for value in scores:
probability = scores[value] / integer
print(value , probability, sep="\t")
#holdAtTwenty()
#question 3
def oneTurn3():
turn_total = 0
value = False
while not value:
roll = rollDice()
if roll == 1:
turn_total = 0
value = True
elif turn_total >= hold_value:
value = True
else:
turn_total += roll
return turn_total
def holdAtX():
scores = {}
amount_times = int(input("Please enter the number of times you wish to loop: "))
for i in range(amount_times):
total = oneTurn3()
if total not in scores:
scores[total] = 1
else:
scores[total] += 1
for value in scores:
probability = scores[value] / amount_times
print(value , probability, sep="\t")
#hold_value = int(input("Please enter the hold value: "))
#holdAtX()
#question 4
def oneTurn4():
score = int(input("Score?: "))
turn_total = 0
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
value = True
else:
turn_total += roll
new_score = turn_total + score
print("New score: " + str(new_score))
#oneTurn4()
#question 5
def oneTurn5():
new_score = 0
while new_score < 100:
turn_total = 0
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
new_score += turn_total
print("New score: " + str(new_score))
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
new_score += turn_total
print("New score: " + str(new_score))
value = True
else:
turn_total += roll
#oneTurn5()
#question 6
def averagePigTurns():
games = int(input("Games?: "))
new_score = 0
turn = 0
for i in range(games):
while new_score < 100:
turn_total = 0
value = False
while not value:
roll = rollDice()
if roll == 1:
turn_total = 0
new_score += turn_total
turn += 1
value = True
elif turn_total >= 20:
new_score += turn_total
turn += 1
value = True
else:
turn_total += roll
average_turns = turn / games
print("Average turns: " + str(average_turns))
#averagePigTurns()
#question 7
def twoPlayerPig():
player_1 = 0
player_2 = 0
check_turns = 2
while player_1 < 100 and player_2 < 100:
turn_total = 0
if check_turns % 2 == 0:
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_1 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
player_1 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
else:
turn_total += roll
else:
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
else:
turn_total += roll
#twoPlayerPig()
#question 8
def pigGame():
player_1 = 0
player_2 = 0
check_turns = 2
player_choice = random.randint(1,2)
if player_choice == 1:
print("You are player 1")
else:
print("Your are player 2")
print("Enter nothing to roll or enter anything to hold: ")
while player_1 < 100 and player_2 < 100:
turn_total = 0
if player_choice == 1:
if check_turns % 2 == 0:
print("It is player 1's turn")
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_1 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
else:
turn_total += roll
roll_hold = input("Turn total: " + str(turn_total) + "\t" + "Roll/Hold?: ")
if roll_hold == "roll":
if turn_total >= 20:
print("Turn total: " + str(turn_total))
player_1 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
else:
continue
else:
print("Turn total: ", turn_total)
player_1 += turn_total
print("Player 1 score: ", player_1)
print("Player 2 score: ", player_2)
check_turns += 1
value = True
else:
print("It is player 2's turn")
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
else:
turn_total += roll
if player_choice == 2:
while player_1 < 100 and player_2 < 100:
if check_turns % 2 == 0:
print("It is player 1's turn")
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
elif turn_total >= 20:
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 2 score: " + str(player_2))
print("Player 1 score: " + str(player_1))
check_turns += 1
value = True
else:
print("It is player 2's turn")
value = False
while not value:
roll = rollDice()
print("Roll: " + str(roll))
if roll == 1:
turn_total = 0
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
else:
turn_total += roll
roll_hold = input("Turn total: " + str(turn_total) + "\t" + "Roll/Hold?: ")
if roll_hold == "roll":
if turn_total >= 20:
print("Turn total: " + str(turn_total))
player_2 += turn_total
print("Player 1 score: " + str(player_1))
print("Player 2 score: " + str(player_2))
check_turns += 1
value = True
else:
continue
else:
print("Turn total: ", turn_total)
print("Player 1 score: ", player_1)
player_2 += turn_total
print("Player 2 score: ", player_2)
check_turns += 1
value = True
#pigGame()
|
469b22bd3c9556a0210fdb62db652ea4b5055039 | jtyliu/Competitive-Programming | /cf/1355/DecToHex.py | 228 | 3.515625 | 4 | # Hi you found this.
def toHex(a):
return "{0:#0{1}x}".format(a,4)[2:]
def ree(a):
return '#'+''.join(list(map(toHex,map(int,a.split())))).upper()
out=""
for i in range(16):
out+=ree(input())+'\n'
print(out)
|
874f4f87c3d71172d0c4e5c42a98eeddc6077190 | invisilmk/- | /14_归并.py | 661 | 3.796875 | 4 |
def merge_sort(alist):
n = len(alist)
mid = n//2
if n <= 1:
return alist
left_li = merge_sort(alist[:mid])
right_li = merge_sort(alist[mid:])
# merge(right,left)
left_pointer,right_pointer = 0,0
result = []
while left_pointer<len(left_li)and right_pointer<len(right_li):
if left_li[left_pointer]<right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer+=1
else:
result.append(right_li[right_pointer])
right_pointer+=1
result += left_li[left_pointer:]
result += right_li[right_pointer:]
return result
|
eb568855fc1459024d08a0f7d741fff3f8220517 | Ting-Hsuan-Lin/ai_work | /hw2.py | 600 | 3.75 | 4 | import random
print("想不到下一餐要吃甚麼嗎?讓pyhon幫你決定!")
print("最多可輸入99種餐點,輸入完畢請輸入Done")
food_choice=[]
count=99
for i in range(count):
food=input("請輸入想吃的食物:")
if (food)!="Done":
if i !=3:
food_choice.append(food)
else:
print("您已達數量上限")
break
else:
print("以下是你想吃的食物:")
print (food_choice)
break
print ("以下是系統幫你選的食物:")
print (random.choice(food_choice))
|
de973fae096bb5790c527ee594b0c5be30dd80fc | acedit/Python_kurs | /week1'2/legal.py | 134 | 3.734375 | 4 | godini=input("Your age?")
godini=int(godini)
if godini<=21:
print("You are illegal here.")
else:
print("You are legal here.")
|
6fa421d6c2999e80a17314eb971817c3812985ac | coolsnake/JupyterNotebook | /new_algs/Sequence+algorithms/Selection+algorithm/castle_on_the_grid_modified_bfs.py | 3,875 | 3.90625 | 4 | """
@author: David Lei
@since: 7/11/2017
https://www.hackerrank.com/challenges/castle-on-the-grid/forum
Looks like a BFS except the notion of a shortest path is the shortest step and a step can
move > 1 cell. A step is any location vertical or horizontal which is not a X.
So do a bfs but instead of just checking +- 1 cell to the left, right, above and below we need
a function that returns all possible neighbours.
When we want to visit a neighbour, mark is as visited and append it to the queue.
Also note that (x, y) pairs represent (row, col) instead of (col, row) like we are used to.
Passed :)
"""
from collections import deque
def get_neighbours_can_visit_in_one_step(grid, current_x, current_y):
neighbours = []
# We only can visit a neighbour if it isn't "X, hasn't been visited before and we are current not at it.
# Check if not visited using "." as we make it point to parent once visited.
# From (current_x, current_y) want to check what you can reach from:
# - current_x to 0
# - current_x to end of column
# - current_y to 0
# - current_y ot end of row.
# like so:
# (x-1, y)
# (x, y-1) (x, y) (x, y+1)
# (x+1, y)
# if any "X" encountered then we stop as it is a barrier we can't go through.
# Check in current column, fix y value, change x value.
# Check from current_x to end of column.
for i in range(current_x + 1, len(grid[0])): # Don't need to check bound as current_y + 1 if >= len(gird) will not execute.
if grid[i][current_y] == "X":
break
elif grid[i][current_y] == ".":
neighbours.append((i, current_y))
# Check from current_x to start of column.
for i in range(current_x - 1, -1, -1):
if grid[i][current_y] == "X":
break
elif grid[i][current_y] == ".":
neighbours.append((i, current_y))
# Check in current row, fix x value, change y value.
# Check from current_y to end of row..
for i in range(current_y + 1, len(grid)):
if grid[current_x][i] == "X":
break
elif grid[current_x][i] == ".":
neighbours.append((current_x, i))
# Check from current_y to start of row.
for i in range(current_y - 1, -1, -1):
if grid[current_x][i] == "X":
break
elif grid[current_x][i] == ".":
neighbours.append((current_x, i))
return neighbours
def minimumMoves(grid, startX, startY, goalX, goalY):
if startX == goalX and startY == goalY:
return 0
# Complete this function
grid[startX][startY] = (-1, -1)
queue = deque([(startX, startY)])
found_goal = False
while queue and not found_goal:
node = queue.popleft()
neighbours = get_neighbours_can_visit_in_one_step(grid, node[0], node[1])
for neighbour in neighbours:
if neighbour == (goalX, goalY):
grid[neighbour[0]][neighbour[1]] = node # Make it point to parent.
found_goal = True
break # Found shortest path to goal.
grid[neighbour[0]][neighbour[1]] = (node[0], node[1]) # Make it point to parent.
queue.append(neighbour)
steps = 0
current_x = goalX
current_y = goalY
while True:
parent = grid[current_x][current_y]
current_x = parent[0]
current_y = parent[1]
steps += 1
if current_x == startX and current_y == startY:
return steps
if __name__ == "__main__":
n = int(input().strip())
grid = []
for _ in range(n):
grid.append([x for x in input().strip()])
startX, startY, goalX, goalY = input().strip().split(' ')
startX, startY, goalX, goalY = [int(startX), int(startY), int(goalX), int(goalY)]
result = minimumMoves(grid, startX, startY, goalX, goalY)
print(result) |
a476722ba68e1b529a19648a7549e9a518fd24c6 | RobertKoehlmoos/intro-to-functions | /problems.py | 3,657 | 4.5625 | 5 | """
Write a function called list_manipulation. This function should take in four parameters ( a list,
command, location and value).
1. IF the command is 'remove' and the location is 'end', the function should remove the last value
in the list and return the value removed.
2. IF the command is 'remove' and the location is 'beginning', the function should remove the first value
in the list and return the value removed.
3. IF the command is 'add' and the location is 'beginning', the function should add the
value (the 4th parameter) to the beginning of the list and return the list.
4. IF the command is 'add' and the location is 'end', the function should add the
value (the 4th parameter) to the end of the list and return the list.
5. IF no value is provided to add, it should use 0 as it's value
Example output
list_manipulation([1,2,3], "remove", "end") # 3
list_manipulation([1,2,3], "remove", "beginning") # 1
list_manipulation([1,2,3], "add", "beginning", 20) # [20,1,2,3]
list_manipulation([1,2,3], "add", "end", 30) # [1,2,3,30]
list_manipulation([1,2,3], "add", "end") # [1,2,3,0]
"""
def list_manipulation(...): # three dots is me letting you know to add parameters
pass
"""
The fibonacci sequence is a sequence of integers. The 0th value is 0, the first is 1.
From there forward, all fibonacci numbers are defined as the sum the the two fibonacci numbers
right before it. So the second number is the sum of the first and zeroth; The 0th and first fibonacci
numbers added together is 0 + 1 = 1, so the second fibonacci number is 1. The third is the second and
first added together, so 1 + 1 = 2 as the third. This patter holds, so the 100th number is the 99th
added to the 98th.
Using recursion, write the below function that, based on a provided integer n, returns the n-th fibonacci number.
Assume the input will be a non-negative integer
"""
def fibonacci(n: int) -> int:
pass
"""
Tell me what the 100th fibonacci number is. Don't worry, I'll wait.
Okay, I lied, I won't actually wait that long.
You probably noticed your function was taking a while to return. If you wrote your fibonacci function using normal
recursion it probably takes an exponential amount as the number it's calculating grows larger, so calculating
the 99th fibonacci number takes almost twice as long as the 98th, and four times as long as the 97th, etc.
Rewrite your original function in the below fast_fibonacci to be able to calculate them quickly. Here are some tips:
Your original function repeats work. If I ask for the 100th fibonacci number it will calculate the 99th and 98th numbers,
but in calculating the 99th number it will again calculate the 98th number. This repetition gets worse the further
down you go.
So take advantage of scoping. First, make some type of data structure that keeps track of fibonacci values you've
already found. Then, using another function you write inside of fast_fibonacci, check if the values you need are already
in that data structure. If not, once you're done calculating then store the number you found for future use.
If you pull it off right you should find that your function runs blazing fast through 1000, which is the highest
number it will be tested against.
If you find it's taking more than a few seconds to test, then hit ctrl-C and figure out what's stopping your code.
This process is called amortization, and the general use of it is a more advanced topic.
"""
def fast_fibonacci(n: int) -> int:
pass
"""
Double Bonus Challenge:
Rewrite fast_fibonacci to run fast without using recursion.
Hint: You won't need to nest anything deeper than a single for loop
""" |
a098008608f0fd332edd6eb5f9595b633b2f5e61 | fanliu1991/LeetCodeProblems | /17_Letter_Combinations_Phone_Number.py | 1,582 | 4.1875 | 4 | '''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
1:
2: a, b, c
3: d, e, f
4: g, h, i
5: j, k, l
6: m, n, o
7: p, q, r, s
8: t, u, v
9: w, x, y, z
Example:
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
'''
import sys, optparse, os
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "":
return []
digit_letter_map = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
letters = []
for num in digits:
letters.append(digit_letter_map[num])
combination = reduce(lambda x, y: [c1 + c2 for c1 in x for c2 in y], letters, [""])
return combination
# reduce(function, iterable[, initializer])
# Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
# For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
# The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable.
digits = "456"
solution = Solution()
result = solution.letterCombinations(digits)
print result
"""
Complexity Analysis
"""
|
261bec06bb651d04138ecdf59e0cd00adf343b10 | ardavast/hackerrank | /python/15_closures_and_decorators/p02.py | 602 | 3.84375 | 4 | #!/usr/bin/env python3
# coding: utf-8
"""
Decorators 2 - Name Directory
https://www.hackerrank.com/challenges/decorators-2-name-directory
"""
def person_lister(f):
def inner(people):
return [f(x) for x in sorted(people, key=lambda x: int(x[2]))]
return inner
@person_lister
def name_format(person):
return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]
if __name__ == '__main__':
n = int(input())
persons = []
for _ in range(n):
person = input().split()
persons.append(person)
print(*name_format(persons), sep='\n')
|
4044970dd746b173302b81f4bb44d4167c32a8b9 | Malvin007marlo/pseudocode | /pseudocode.py | 340 | 3.875 | 4 | print("enter marks")
a=int(input())
b= int(input())
k=int(input())
s=int(input())
d=int(input())
total= a+b+k+s+d
avg=(a+b+k+s+d)/5
print (total)
print (avg)
if avg>=70and avg<=100:
print("grade A")
elif avg>60 and avg<=69:
print("b")
elif avg>=50 and avg <=59:
print("b")
elif avg>=40 and avg <49:
print("e") |
70777eea776a3602a6c1116fac18124b86dab249 | jschnab/leetcode | /arrays/max_number_marked_indices.py | 807 | 3.765625 | 4 | """
leetcode 2576: find the maximum number of marked indices
We are given an integer array A. Initially, all the indices are unmarked. We
are allowed to make this operation any number of times:
* Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j],
then mark i and j.
Return the maximum possible number of marked indices in nums using the above
operation any number of times.
"""
def marked_indices(A):
A.sort()
i = 0
for j in range(len(A) - len(A) // 2, len(A)):
if 2 * A[i] <= A[j]:
i += 1
return 2 * i
def test1():
assert marked_indices([3, 5, 2, 4]) == 2
print("test 1 successful")
def test2():
assert marked_indices([9, 2, 5, 4]) == 4
print("test 2 successful")
if __name__ == "__main__":
test1()
test2()
|
609a8b00dec388448f0f2e2bbf299070e7f52d5b | conqueror-1/lib | /pandas/test.py | 187 | 3.578125 | 4 | import pandas as pd
Age = pd.Series([10,20,30,40],index=["age1","age2","age3","age4"])
print(Age[0])
filtered_age = Age[Age>20]
print (filtered_age)
print(Age.values)
print(Age.index)
|
c09d239a3a34bb87c1ec5c45592c6d4cfdc938b4 | SuperSultan/Assembler-Symbol-Table | /p1.py | 3,495 | 3.96875 | 4 | import fileinput
import sys
class HashTable():
def __init__(self):
self.size = 100
self.key = [None] * self.size
self.value = [None] * self.size
self.count = 0
def getData(self):
'''
Grabs data from file, adds it to a cleanlist without whitespace nor empty
:return: content
'''
raw_content = []
for line in fileinput.input():
line = line.strip().split()
raw_content.append(line)
content = [x for x in raw_content if x]
return content
def insert(self, key, data):
'''
Inserts the key-data pair, checks for collisions, inserts if symbol tab
:param key: character string
:param data: optional integer to be put in table
:return: return once it is stored
'''
start = self.hashFun(key)
print("Storing " + key + " " + data)
for i in list(range(start, self.size)) + list(range(start)):
if self.count >= 100:
print("Error: Unable to insert " + key + " " + data + " because the hashtable is full!")
break
if self.key[i] == key:
print("Error: " + key + " already exists at " + str(i))
break
if self.key[i] is not None:
print("Collision at index " + str(i))
continue
self.key[i] = key
self.value[i] = data
print(" Stored at " + str(i))
self.count = self.count + 1
return
def search(self, key):
'''
:param key: string to be searched for
:return: return empty list if key does not exist or is not found
'''
start = self.hashFun(key)
for i in list(range(start, self.size)) + list(range(start)):
if self.key[i] is None:
return []
elif self.key[i] == key:
print("Found " + self.key[i] + " " + self.value[i] + " at location " + str(i))
return [i]
return []
def hashFun(self, key):
'''
:param key: takes a string as key, hashes it as an ASCII value
:return: Remainder of sum of ASCII values
'''
sum = 0
for pos in range(len(key)):
sum = sum + ord(key[pos])
return sum % self.size
def parse(self, content):
for split in content:
if len(split) > 2:
print("Error: input must be a key-value pair separated by whitespace")
continue
elif len(split) == 2: # insert entry in symbol table if length of list is 2
if split[1].isdigit():
table.insert(split[0], split[1])
else:
print("Error: " + split[0] + " " + split[1] + " is an invalid key-value pair")
continue
elif len(split) == 1: # search for entry in symbol table if length of list is 1
entry = table.search(split[0])
if len(entry) == 0: # if entry is returned as empty list, it is not found
print("Error: " + split[0] + " not found")
if __name__ == "__main__":
table = HashTable() # create HashTable object, grab data
try:
content = table.getData()
except IOError:
print("File " + fileinput + "does not exist")
sys.exit(1) # exit if file not found
table.parse(content)
|
44f581293a79c68dad1fafedc47ac50cd7241b99 | briantaylorjohnson/python_data_visualization | /scatter_squares.py | 728 | 4.09375 | 4 | # Plotting and Styling Individual Points with scatter()
import matplotlib.pyplot as plt
# Data set
x_values = [1, 2, 3, 4, 5]
y_values = [2, 4, 9, 16, 25]
# Apply style to chart
plt.style.use('seaborn')
# Instantiate fig and ax variables for plotting data
fig, ax = plt.subplots()
# Use scatter() method to plot a single point with x and y coordinates
# s argument sets the size of the dots used to draw the graph
ax.scatter(x_values, y_values, s=100)
# Set chart title and label axes
ax.set_title('Square Numbers', fontsize=24)
ax.set_xlabel('Value', fontsize=14)
ax.set_ylabel('Square of Value', fontsize=14)
# Set size of tick labels
ax.tick_params(axis='both', which='major', labelsize=14)
# Render chart
plt.show()
|
98d75eefc790445628e1f12ac4c3758a07775a34 | lynia1/python-streichholz | /streichholz.py | 1,371 | 3.984375 | 4 | #!/usr/bin/env python3
# coding: utf-8
# anzahl an Streichhoelzern
from random import randint
streichhölzer = randint(5,25)
print()
print('Die Anzahl der Streichhölzer beträgt',streichhölzer)
#Wiederholung bis die anzahl der Streichhölzer 0 beträgt
while(streichhölzer>0):
# Nutzer zieht 1-2 Streichhölzer
print()
anzahl_nutzer=input('Wie viele Streichhölzer ziehst du? ')
if(anzahl_nutzer.isdigit()):
number_nutzer = int(anzahl_nutzer)
else:
print('Eingabe nicht gültig, gebe die Zahl 1 oder 2 ein.')
continue
if(number_nutzer<0 or number_nutzer>2):
print('Eingabe nicht gültig, gebe die Zahl 1 oder 2 ein.')
continue
print('Deine Eingabe war:', anzahl_nutzer)
# abziehen
streichhölzer= streichhölzer-number_nutzer
if(streichhölzer<=0):
print('Du hast gewonnen!')
break
else:
print('Die Anzahl der Streichhölzer beträgt',streichhölzer)
# Computer zieht 1-2 Streichhölzer
from random import randint
anzahl_computer= randint(1,2)
print()
print('Die Eingabe des Computers war:',anzahl_computer)
streichhölzer= streichhölzer-anzahl_computer
if(streichhölzer<=0):
print('Der Computer hat gewonnen!')
else:
print('Die Anzahl der Streichhölzer beträgt',streichhölzer)
|
e61a74a867510837c624d124dd6d2513b205f722 | alex-belonozhko/Projects-Python | /Gosha Dudar/if_Elif.py | 370 | 4.21875 | 4 | def YourAge():
age = int (input ("Enter your age: "))
if age > 0:
if age == 18:
print("now you are not a child")
elif age < 18:
print("You are a child")
elif age > 18:
print("You are an adult")
elif age < 0:
print("Ohh You are not born yet")
else:
print("Happy Birthday!!!")
|
f1d31c52af7f8f3ded6c3cadafa7a1eeea41809b | jiyoung-99/coding_test | /Greedy/plus_and_multi.py | 553 | 3.640625 | 4 | """
각 자리가 숫자로만 이루어진 문자열 S가 주어졌을 때 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인하며 숫자 사이에 'X'또는 '+' 연산자를 넣어
결과적으로 만들어질 수 있는 가장 큰 수를 구하는 프로그램을 작성하시오
모든 연산은 왼쪽부터 오른쪽으로 시작됩니다.
"""
data = input()
result = int(data[0])
for i in range(1, len(data)):
num = int(data[i])
if num <= 1 or result <= 1:
result += num
else:
result *= num
print(result) |
50980ce90d315f624870db512b2b586deba96fcc | Djuniou/Challenges-from-freecodecamp.org | /Scientific computing with Python Projects/Probability Calculator/prob_calculator.py | 1,427 | 3.765625 | 4 | import copy
import random
# Consider using the modules imported above.
class Hat():
def __init__(self,**hat):
self.total_balls = 0
self.contents = []
self.__dict__.update(hat)
for entry in hat:
for value in range(hat[entry]):
self.contents.append(entry)
self.total_balls += 1
def draw(self,number):
self.out_balls = []
if (number<self.total_balls):
for i in range(number): # number=number of balls to be taken out
x=random.randint(0,len(self.contents)-1)
self.out_balls.append(self.contents[x])
self.contents.pop(x)
return self.out_balls
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
total_success = 0
expected_list = []
for entry in expected_balls:
for value in range(expected_balls[entry]):
expected_list.append(entry)
for i in range(0,num_experiments):
exp_hat = copy.deepcopy(hat)
out_balls = exp_hat.draw(num_balls_drawn)
for k,item in enumerate(expected_list):
if (item in out_balls):
out_balls.remove(item)
if (k==(len(expected_list)-1)):
total_success += 1
else:
break
return (total_success/num_experiments)
|
ce6528ce56d670ea625a8d32b475fcca6c41af3d | kunal-singh786/basic-python | /conversation in bin, oct, hex.py | 203 | 3.9375 | 4 | base=int(input("enter base"))
a=int(input("enter no:"),base)
print(a)
c=int(input("Enter the require conversion"))
if c==1:
print(bin(a))
elif c==2:
print(oct(a))
elif c==3:
print(hex(a)) |
391e735fd99ba7818728bf9141d08f3658ad0942 | angelar0107/LeetCodeRecord | /71SimplifyPath.py | 460 | 3.75 | 4 | class Solution:
def simplifyPath(self, path: str) -> str:
pathlist = path.split('/')
result = []
for i in range(len(pathlist)):
curr = pathlist[i]
if curr == '.' or not curr:
continue
elif curr == '..':
if result:
result.pop()
continue
result.append(curr)
return '/' + '/'.join(result)
|
2d712d93938419d3a8c0298c6c512ce6b871f537 | GoldExplosion/dsaPython | /dsapy/BinaryTree.py | 3,514 | 4.3125 | 4 | class BinaryTree():
"""
Binary Tree class.
ATTRIBUTES
==========
data: int
the key value
left: BinaryTree
the left child BT
right: BinaryTree
the right child BT
METHODS
=======
insert(Data):
PARAMETERS
==========
data: any type
data to be added.
RETURNS
=======
None
initialization of binary tree.
display(s):
PARAMETERS
==========
to specify the order of printing.
options: in , pre , post
RETURNS
=======
None
prints the tree in specified order
find(n, count):
PARAMETERS
==========
n: int
key value
count: int
positions value
RETURNS
=======
count: int
it returns the position value or else None.
the position value goes like this...
0
/ \
1 2
/ \ / \
3 4 5 6
/ \ / \/ \ / \
search(key):
PARAMETERS
==========
key: int
the to data to be searched
RETURNS
=======
Node
the Object address for the node.
if a node with the data value
equal to key doesn't exist, then
it returns None.
"""
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, Data):
if self.data is not None:
if self.data >= Data:
if self.left is None:
self.left= BinaryTree(Data)
else:
self.left.insert(Data)
else:
if self.right is None:
self.right = BinaryTree(Data)
else:
self.right.insert(Data)
else:
self.data = Data
def display(self, s="in"):
if s == "in":
if self.left:
self.left.display()
print(self.data, end=" ")
if self.right:
self.right.display()
elif s == "pre":
print(self.data, end=" ")
if self.left:
self.left.display(s="pre")
if self.right:
self.right.display(s="pre")
elif s=="post":
if self.left:
self.left.display(s="pre")
if self.right:
self.right.display(s="pre")
print(self.data, end=" ")
else:
print("ERROR: Invalid Order Type")
def find(self, n, count=0):
if self.data == n:
return count
if self.data < n:
if self.right is None:
return self.right
return self.right.find(n, count=2*count+2)
if self.left is None:
return self.left
return self.left.find(n, count=2*count+1)
def search(self, key):
if self.data == key:
return self
if self.data < key:
if self.right is None:
return self.right
return self.right.search(key)
if self.left is None:
return self.left
return self.left.search(key)
|
b3e7733faef1d66236bb33eae96abed2164d0950 | aydentownsley/AirBnB_clone | /tests/test_models/test_city.py | 1,208 | 3.765625 | 4 | #!/usr/bin/python3
""" Testing Base Model Module """
import unittest
from models.base_model import BaseModel
from models.city import City
from datetime import datetime
class TestCity(unittest.TestCase):
""" testing output from User class """
def test_attrs(self):
""" test attrs of City when created """
city = City()
self.assertEqual(city.name, "")
self.assertEqual(City.name, "")
self.assertEqual(city.state_id, "")
self.assertEqual(City.state_id, "")
self.assertIn("id", city.__dict__)
self.assertIn("created_at", city.to_dict())
self.assertIn("updated_at", city.to_dict())
def test_set_attrs(self):
""" test the attrs of City when set """
city2 = City()
city2.name = "Hawaii"
self.assertEqual(city2.name, "Hawaii")
city2.state_id = "<3"
self.assertEqual(city2.state_id, "<3")
self.assertEqual(City.name, "")
self.assertEqual(City.state_id, "")
def test_inheritance(self):
""" test the inheritance of City from BaseModel """
city3 = City()
self.assertIsInstance(city3, BaseModel)
self.assertIsInstance(city3, City)
|
ed03de4e548b6617b4042c7b12a061d699086630 | girishramnani/compititive_coding | /SPOJ/SPOJ-candy.py | 439 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 11 17:01:39 2014
@author: girish
"""
iteration = int(input())
ans_list=[]
for i in range(iteration):
input()
no_of = int(input())
sum1=0
for j in range(no_of):
sum1+=int(input())
if(sum1 % no_of == 0):
ans_list.append("YES")
else:
ans_list.append("NO")
for k in range(iteration):
print(ans_list[k])
|
cbe23d1d091a789679147a5f0df01f3cfc905500 | rpendley6/TrafficSimulation | /CA/simulator.py | 1,074 | 3.65625 | 4 | import car as car
import world as world
import numpy as np
import random
import time
from matplotlib import pyplot as plt
from matplotlib import colors
def simulate(world, num):
#runs the simulation for num iterations
for n in range(num):
print("n: " + str(n))
world.propogateForward()
world.generateCars()
print("\n")
print(world.world)
time.sleep(1)
#PEACHSTREET HAS TWO LANES
lanes = 2
#AVERAGAE LENGTH OF CAR IS 14.4FT
#DISTANCE IS 1800FT so approx 128 sqaures
roadlength = 128
#NUMBER OF NEW CARS PER TIME INTERVAL
new_cars = 2
new_world = world.World(lanes, roadlength, new_cars, 75)
new_world.generateCars()
print(new_world.world)
#TIME INTERVALS IS 15
time_interval = 584
simulate(new_world, time_interval)
# PEACHTREE STREET FROM 10th to 14th
# 10th to 11th: Approx 535FT which is around 37 Squares
# 11th to 12th: Approx 485FT which is around 35 Sqaures (37 + 35 = 72)
# 12th to 14th (No Traffic Light at 13th): Approx 800FT which is around 56 Squares () |
84439f12bcacdeab212cd059e695ada7caf78784 | Avraj19/oop_animals | /animal_class.py | 493 | 3.59375 | 4 | class Animals():
def __init__(self, name, age=0, num_legs=4, tail=1):
# setting attribute name to instances of Dog class
self.name = name
self.age = age
self.paws = num_legs
self.tail = tail
def stretch(self):
return 'yyyyyaaaauuu \n'
def jumps(self):
return 'I always land on my paws \n'
def eat(self, food=''):
return 'I\'m hungry' + food + '\n'
def sleep(self):
return 'zzZZzzZZz ZZzzzZZzz\n'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.