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
|
---|---|---|---|---|---|---|
1fa61cfc52c3571bbc749803949ceef0ce1b3c9a | davidcg97/JuegoMedieval | /Medieval Game.py | 3,290 | 3.5 | 4 | import random
class Ciudadanos:
def __init__(self): # Constructor
Granjeros.__init__(self)
Artesanos.__init__(self)
Militares.__init__(self)
Taberneros.__init__(self)
Curas.__init__(self)
self.profesion = random.choice(profesion)
self.cantidad = cantidad
self.comida = 50
cantidad = cantgranj + cantartes + cantmili + canttaber + cantcuras
def __str__(self):
return f"{self.profesion}, {self.cantidad}"
class Granjeros(Ciudadanos):
def __init__(self): # Constructor
Ciudadanos.__init__(self)
self.profesion = "Granjero"
self.cantgranj = cantgranj
def Producir_comida(self):
Ciudadanos.__init__(self)
if comida > 0 and cantgranj > 10:
comida += 1
def Reproducir(self):
Ciudadanos.__init__(self)
Artesanos.__init__(self)
if comida >= 10 and cantgranj + cantartes >= 20:
random.choice(profesion)
def __str__(self):
return f"{self.cantgranj}"
class Artesanos(Ciudadanos):
def __init__(self): # Constructor
Ciudadanos.__init__(self)
self.profesion = "Artesano"
self.cantartes = cantartes
def Producir_elementos(self):
armas = ["Armadura", "Espada", "Escudo", "Lanza"]
arma = random.choice(armas)
return f"{arma}"
def Reproducir(self):
Ciudadanos.__init__(self)
Granjeros.__init__(self)
if comida >= 10 and cantgranj + cantartes >= 20:
random.choice(profesion)
def __str__(self):
return f"{self.cantartes}"
class Militares:
def __init__(self): # Constructor
Ciudadanos.__init__(self)
Artesanos.__init__(self)
self.cantmili = cantmili
self.arma = Artesanos.Producir_elementos()
self.tipo = tipo
if self.arma == "Armadura":
tipo == "Armado"
if self.arma == "Espada":
tipo == "Guerrero"
if self.arma == "Escudo":
tipo == "Defensor"
if self.arma == "Lanza":
tipo == "Lancero"
def Luchar(self):
if self.tipo == "Armado":
print("Vistoria.")
elif self.tipo == "Guerrero":
print("Vistoria.")
elif self.tipo == "Defensor":
print("Derrota.")
elif self.tipo == "Lancero":
print("Derrota.")
#def Organizar(self):
def __str__(self):
return f"{self.cantmili}, {self.arma}, {self.tipo}"
class Taberneros:
def __init__(self): # Constructor
Ciudadanos.__init__(self)
self.profesion = "Tabernero"
self.canttaber = canttaber
self.hidromiel = hidromiel
def Producir_hidromiel(self):
Ciudadanos.__init__(self)
if comida > 20 and canttaber > 10:
hidromiel += 1
#def Dirigir(self):
def __str__(self):
return f"{self.canttaber}"
class Curas:
def __init__(self): # Constructor
Ciudadanos.__init__(self)
self.profesion = "Cura"
self.cantcuras = cantcuras
#def Gastar(self):
#def Defender(self):
def __str__(self):
return f"{self.cantcuras}"
profesion = ["Granjero", "Artesano", "Militar", "Tabernero", "Cura"] |
62008b0cbfc79cdde766ba6d018826faf18f7765 | AkshayVaswani/PyCharmProjects | /1-28-19/exit slip.py | 408 | 3.75 | 4 | import turtle
import math
alex = turtle.Turtle()
wn = turtle.Screen()
wn.bgcolor("white")
alex.color("green")
alex.pensize(3)
size=20
def square(size):
for i in range(4):
alex.forward(size)
alex.left(90)
for i in range(5):
square(size)
alex.penup()
alex.right(135)
alex.forward(math.sqrt(200))
alex.left(135)
alex.pendown()
size = size + 20
wn.exitonclick() |
52484a18d615e3a863a7ac4fe13f0f74a6340e4e | DaltonLarrington/Dalton-Larrington-Data-Structures | /Dalton Larrington DS Level 04 - Recursion/DS Level 04 Part B 2.py | 488 | 4.21875 | 4 | #Fibonacci Sequence Non-recursive
#Programmer: Dalton Larrington
#Date: 2-13-18
import time
startTime = time.time()
def fib(n):
x = 0
y = 1
#Will find the nth number in the range 0 to n adding z and y each time
for i in range(0, n):
z = x
x = y
y = z + y
return x
#Prints the sequence from 0 to 100 using the range above. 100 denotes n, which is terms.
for i in range(0, 10):
print(fib(i))
print("Runtime:", time.time() - startTime)
|
fd174d26829328977e106090f0ca4a3ccf2eab6b | samirsaravia/Python_101 | /Bootcamp_2020/AdvancedPython/Regular_expressions/basics.py | 1,286 | 3.625 | 4 | import re
#
# [aeiou] Match any vowel
# [^aeiou] ^ inverts selection, this matches any consonant
# [a-z] Match any lowercase letter from a-z
# \d Matches any decimal digit; this is equivalent to the class [0-9]
# \D Matches any non-digit character; this is equivalent to the class
# [^0-9]
# \s Matches any whitespace character; this is equivalent to the
# class [ \t\n\r\f\v]
# \S Matches any non-whitespace character; this is equivalent to the
# class [^ \t\n\r\f\v]
# \w Matches any alphanumeric character; this is equivalent to the
# class [a-zA-Z0-9_]
# \W Matches any non-alphanumeric character; this is equivalent to
# the class [^a-zA-Z0-9_]
# set a pattern using re module
pattern = re.compile(r'samir')
print(pattern.match('samir'))
# Match expressions to the pattern
me = pattern.match('samir')
print(me.group())
me_2 = pattern.match('hello samir')
me_3 = pattern.search('hello samir')
print(me_3)
print(me_3.group())
pattern_2 = re.compile(r's\D+')
print(pattern_2.match('samir12345'))
# searching for specific data
string = '''image01.jpg,image01.png,image02.jpg,my_doc.doc,my_doc2.docx,
london_bridge.gif, another_doc.doc,my_pdf.pdf'''
pattern_3 = re.compile(r'(\w+)\.(jpg|png|gif)')
print(pattern_3)
for m in re.finditer(pattern_3, string):
print(m.group())
|
489b667d5b4be2277b5cfe1c3750e12aef8d5e1e | MashodRana/Computer-Vision | /contour_pixels/contour_pixels.py | 2,557 | 4.09375 | 4 | # Load necessary packages
import cv2
import numpy as np
import matplotlib.pyplot as plt
def preprocess_image(img):
"""
This method for preprocessing the image.
First convert the image into gray scale image then apply binary thresholding to get
better result on contour detection.
parameters::
img: a image.
returns::
Return a tuple contain a gray image and a binary image respectively.
"""
# Converting image color BGR to GRAY
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray) # display the gray image
plt.show()
# Using binary threshold
_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
plt.imshow(binary, cmap='gray') # display the threshold image
plt.show()
return gray, binary
def find_contours(binary_img):
"""
Find a list of contours present in the image. Binary image/ gray scale image
is recommended by openCV.
parameters::
binary_img: a image where pixels are settled with thresholding.
returns::
A list of contours.
"""
# Finding the contours
cnts, _ = cv2.findContours(binary_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours: %d" % (len(cnts)))
return cnts
def extract_pixels(img, cnts):
"""
Extract pixel values of the image.
parameters::
img: a image. if this is a RGB or BGR image pixel will be a numpy array with 3 elements.
cnts: a list of contours extracted with cv2.findContours function.
returns::
A list contain pixel value for each of the contour.
"""
cnts_px = []
for i, contour in enumerate(cnts):
# Create numpy array with image height and width
mask = np.zeros(img.shape[:2], dtype=np.uint8)
# Draw the contour on the mask
cv2.drawContours(mask, cnts, i, color=255, thickness=cv2.FILLED)
# Find the coordinates of pixels and pixel values
px = np.where(mask == 255) # get the (x,y) position of each pixel which has value 255
# Extract coordinates value from the image
cnts_px.append(img[px[0], px[1]]) # store pixels into the list
return cnts_px
if __name__=='__main__':
# Reading an image
file_name = 'images/test2.jpg'
image = cv2.imread(file_name)
# Preprocess the image
gray_img, bin_img = preprocess_image(image)
# Find contours
contours = find_contours(bin_img)
# Find pixel values of each contour
cont_pxvalues = extract_pixels(gray_img, contours)
|
20a815648421e020386fb49b4c027a29e9ce2807 | kimgeonsu/python_19s | /bingo_20193125.py | 2,076 | 3.703125 | 4 | # 5x5 빙고 게임
import random
board=[[' ' for x in range(1,6)] for y in range(5)]
n=1
for r in range(5) :
for c in range(5) :
board[r][c]=n
n += 1
numlist=[]
comlist=[]
bingo=0
#빙고판 만들기
while True :
for r in range(5) :
for c in range(5) :
print("{:>3}" .format(board[r][c]),end=" ")
print()
#사용자로부터 숫자 입력 받기
num=int(input("번호를 선택하세요:"))
numlist.append(num)
#잘못된 위치 확인하기
if num < 1 or num > 25 :
print("잘못된 위치입니다.")
elif num in comlist :
print("이미 선택된 숫자입니다.")
continue
#위치 맞을 시 숫자 X로 변환
else :
for r in range(5) :
for c in range(5):
if board[r][c] == num :
board[r][c]='X'
#컴퓨터가 숫자 고르기
com=random.randint(1,25)
comlist.append(com)
if com not in numlist :
for r in range(5) :
for c in range(5) :
if board[r][c] == com :
board[r][c] ='O'
#빙고 체크
for i in range(5) :
if board[i][0] == board[i][1] == board[i][2] == board[i][3] == board[i][4] :
print("빙고!")
bingo += 1
for i in range(5) :
if board[0][i] == board[1][i] == board[2][i] == board[3][i] == board[4][i] :
print("빙고!")
bingo += 1
if board[0][0] == board[1][1] == board[2][2] == board[3][3] == board[4][4] :
print("빙고!")
bingo += 1
elif board[0][4] == board[1][3] == board[2][2] == board[3][1] == board[4][0] :
print("빙고!")
bingo += 1
#빙고하면 게임 종료!
if bingo == 1 :
break
print("게임을 종료합니다.")
|
b3dd985d5b21a6d0ec87831b370a8dc8c87d1b3f | devpla/algorithm | /BOJ/02579-계단_오르기-yeonhee.py | 348 | 3.5 | 4 | n = int(input())
stairs = [0] + [int(input()) for _ in range(n)]
dp = [0] * (n+1)
if n == 1:
print(stairs[1])
elif n == 2:
print(stairs[1] + stairs[2])
else:
dp[1] = stairs[1]
dp[2] = stairs[2] + stairs[1]
for i in range(3, n+1):
dp[i] = max(dp[i-2] + stairs[i], dp[i-3] + stairs[i] + stairs[i-1])
print(dp[n])
|
5fac13a7530eeae5ee5703e8ba992c294bc12d72 | sunset375/CodingDojo-1 | /Python/Python_Knowledge/algos/w4d3/main.py | 333 | 4.03125 | 4 | # 0, 1, 1, 2, 3, 5, 8
def fibonacci(num):
if num < 2:
return 0
if num == 2:
return 1
return fibonacci(num-2) + fibonacci(num-1)
fibonacci(5) # -> 3
def fibonacci(5):
if num < 2:
return 0
if num == 2:
return 1
return fibonacci(num-2) + fibonacci(num-1)
fibonacci(3)
|
856bc5a4ba75f38de0b1a94c0b0ac1918268b917 | CYanLong/learn-python3 | /chapter9-example/feild.py | 278 | 3.671875 | 4 | class Counter:
count = 0 #类属性定义在外面.
def __init__(self): #实例属性定义在__init__方法中
self.__class__.count += 1
if __name__ == '__main__':
print(Counter.count) #0
c1 = Counter()
print(Counter.count) #1
c2 = Counter()
print(Counter.count) #2 |
a6a2d369ddccdb3fc6c0c247db86fa0a93db32e5 | vsivakumar9/Python-general | /PyParagraph/main_pypara1.py | 3,558 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 19 13:18:49 2018
@author: Shiva
"""
#Program reads thru a text file to obtain statistics like approx word count,
#sentence count, average letter count per word, average sentence length etc.
import os
import re
#filepath = os.path.join("raw_data","paragraph_1.txt")
#outfile = ("pypara_result.txt")
#filepath = os.path.join("raw_data","paragraph_2.txt")
filepath = os.path.join("raw_data","paragraph_1.txt")
outfile = ("pypara_result1.txt")
# Use paragraph_1.txt as the file name
#fname = input("Enter file name: ")
fname=filepath
if len(fname) < 1 :
fname = filepath
print(fname)
try :
fh = open(fname)
except:
print ('invalid file name or path: ',fname)
quit()
linelist=list()
periods=list()
periodlist=list()
#dict to count word frequency
#countsdict=dict()
sentcnt = 0
#wordcnt = 0
linecnt=0
totwordcnt = 0
totletlength = 0
# average letter length.
avgletcnt = 0.0
#average sentence length.
avgsentlength = 0.0
#loop thru the lines in the paragraph being read.
for line in fh:
#print(line)
linecnt += 1
#print("linecnt : " + str(linecnt))
# split line into words and store in array linewrods.
line=line.strip('\n')
linelist.append(line)
#print(linelist)
#Find words with periods using regex to determine number of sentences.
#periods = re.findall('(\S*["."])',line)
#periods = re.findall('[A-Z][^.]*(\S+?[.])',line)
periods = re.findall('[A-Z].*\s(\S+[.])',line)
#print(periods)
#split sentence to words for other stats like letter cnt and word cnt.
linewords = line.split(" ")
#print(linewords)
if len(linewords) >= 2 :
#append word with the period to a list to determine # of sentences.
periodlist.append(periods)
#add number of sentences to total.
sentcnt = sentcnt + len(periods)
totwordcnt = totwordcnt + len(linewords)
#count letters in each word.
# loop thru word array to determine required counts.
for word in linewords :
letlength = len(word)
totletlength = totletlength + letlength
#print(periodlist)
#print("totwordcnt : " + str(totwordcnt) )
#print("sentcnt : " + str(sentcnt) )
#print("totletlength : " + str(totletlength))
#calc avg sentence length(total # of words / total # of sentences.
avgsentlength = totwordcnt / sentcnt
#average letter count in word(Total # of letters / Total # of words in para )
avgletcnt = totletlength / totwordcnt
#sentences = line.split(".")
#print(sentences)
#close file handle
fh.close()
#Print final tallies
print(" ")
print("Approximate Word Count : " + str(totwordcnt) )
print("Approximate Sentence Count: " + str(sentcnt) )
#print("Average Letter Count : " + str(avgletcnt) )
print("Average Letter Count : " + "%.2f" % avgletcnt)
print("Average Sentence Length : " + "%.2f" % avgsentlength)
with open(outfile,'w') as fhout:
print("Paragraph Analysis", file=fhout,end='\n')
print("----------------------------------------", file=fhout,end='\n')
print("Approximate Word Count : " + str(totwordcnt),
file=fhout,end='\n')
print("Approximate Sentence Count: " + str(sentcnt),
file=fhout,end='\n')
print("Average Letter Count : " + "%.2f" % avgletcnt,
file=fhout,end='\n')
print("Average Sentence Length : " + "%.2f" % avgsentlength,
file=fhout,end='\n')
|
bd15c8f22ccf30cef979007d3e2af8a12ba2ecae | gerrycfchang/leetcode-python | /easy/judge_route_circle.py | 1,516 | 4.15625 | 4 | # 657. Judge Route Circle
#
# Initially, there is a Robot at position (0, 0).
# Given a sequence of its moves, judge if this robot makes a circle,
# which means it moves back to the original place.
#
# The move sequence is represented by a string. And each move is represent by a character.
# The valid robot moves are R (Right), L (Left), U (Up) and D (down).
# The output should be true or false representing whether the robot makes a circle.
#
# Example 1:
# Input: "UD"
# Output: true
# Example 2:
# Input: "LL"
# Output: false
import collections
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
lrqueue, udqueue = [], []
for c in moves:
if c == 'U':
udqueue.append(1)
elif c == 'D':
udqueue.append(-1)
elif c == 'R':
lrqueue.append(1)
else:
lrqueue.append(-1)
return True if sum(lrqueue) + sum(udqueue) == 0 else False
def judgeCircleSol(self, moves):
"""
:type moves: str
:rtype: bool
"""
c = collections.Counter(moves)
return True if c['U'] == c['D'] and c['L'] == c['R'] else False
if __name__ == "__main__":
sol = Solution()
assert sol.judgeCircle('UD') == True
assert sol.judgeCircle('LL') == False
assert sol.judgeCircleSol('UD') == True
assert sol.judgeCircleSol('LL') == False |
6bfc6cf501fb828f1cdbf0f3d21e91b8ad53078a | OZ-T/PythonDesignPatterns | /decorator/decorator_tree_class.py | 2,687 | 4 | 4 | """
A working, clean Binary Search Tree class in Python.
The Binary Search Tree data structure maintains the following invariants:
1. For any node to the left of a given point in the tree, such node has a value smaller than the given point.
2. For any node to the right of a given point in the tree, such node has a value larger than the given point.
3. Any node has between 0 and 2 subtree children (inclusive).
For the purpose of this implementation, we will use a Python class `Tree` with the following attributes:
A. Tree.left is a Tree class or None
B. Tree.right is a Tree class or None
C. Tree.value is an integer (not a float, String, or any other Python datatype)
The following invariants of this tree class must be tested:
1. Left and right subchildren of a node follow the ordering invariant of the general BST data structure (points 1 and 2 above).
2. Left and right subchildren of a node are either Tree class instances or None (points A and B above).
3. The value of a non-None node must be an integer.
"""
import copy
def assert_invariants(func):
def wrapper(*args):
experiment_tree = args[0]
update = args[1]
old_tree = copy.deepcopy(experiment_tree)
assert(experiment_tree.is_tree())
func(experiment_tree, update)
try:
assert(experiment_tree.is_tree())
except:
print('reverting')
experiment_tree.value = old_tree.value
experiment_tree.left = old_tree.left
experiment_tree.right = old_tree.right
return wrapper
class Tree(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
assert(self.is_tree())
# Helper functions for updating tree left and right children
@assert_invariants
def set_left(self, new_left):
self.left = new_left
@assert_invariants
def set_right(self, new_right):
self.right = new_right
# Helper function for updating the Tree node's value
@assert_invariants
def set_value(self, new_value):
self.value = new_value
# Generalized function to check tree invariants
def is_tree(self):
if (not isinstance(self, Tree)):
return False
if (not(type(self.value) == int)):
return False
if (self.left and self.right):
return ((self.left.value < self.value) and
(self.right.value > self.value) and
(self.left.is_tree()) and
(self.right.is_tree()))
elif (self.left):
return ((self.left.value < self.value) and
(self.left.is_tree()))
elif (self.right):
return ((self.right.value > self.value) and
(self.right.is_tree()))
else:
return True
|
84417f4b8612b779717fcec448a81d396be3cfc1 | 26barnwal11/Algorithms-1 | /Sorting/Quick Sort/QuickSort.py | 753 | 3.921875 | 4 |
import array
"""" Quick Sort implementation as done in CLRS """
def quicksort(arr,first,last):
if first<last:
middle = partition(arr,first,last)
quicksort(arr,first,middle-1)
quicksort(arr,middle+1,last)
def partition(arr,first,last):
""" Taking last element as Pivot """
pivot = arr[last]
""" zone for elements smaller than pivot """
zone_index = first-1
for j in range(first,last):
if arr[j] <= pivot :
zone_index += 1
arr[j], arr[zone_index] = arr[zone_index], arr[j]
arr[last] = arr[zone_index+1]
arr[zone_index+1] = pivot
return zone_index+1
arr = array.array('i',[9,8,7,6,5,4,3,2,1])
quicksort(arr,0,len(arr)-1)
print(arr)
|
45985142e570b097fab134d1245a0f05e27f6058 | scarvalhojr/programming | /leetcode/3sum-closest/solution_b.py | 1,136 | 3.5625 | 4 | #!/usr/bin/env python
from bisect import bisect_left
from sys import maxint
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
closest_sum = None
closest_dist = maxint
length = len(nums)
nums.sort()
for i1, n1 in enumerate(nums):
for i2 in range(i1 + 1, length - 1):
needed = target - n1 - nums[i2]
i3 = bisect_left(nums, needed, lo=i2+1)
if i3 < length:
if nums[i3] == needed:
return target
dist = abs(needed - nums[i3])
if dist < closest_dist:
closest_sum = n1 + nums[i2] + nums[i3]
closest_dist = dist
if i3 - 1 > i2:
dist = abs(needed - nums[i3 - 1])
if dist < closest_dist:
closest_sum = n1 + nums[i2] + nums[i3 - 1]
closest_dist = dist
return closest_sum
|
0a34d061fc47755236f5790a4fa7c62e781b4a3d | paumih/handwriting-characters-extraction | /handwriting_char_extraction.py | 4,695 | 3.71875 | 4 | import os
from cv2 import cv2
import numpy as np
import math
def rotate_image(image, angle):
"""
Rotates the given image by the input angle in the counter-clockwise direction
Parameters
----------
image : ndim np.array
image to be rotated
angle : float
angle of rotation as degrees.
Returns
-------
rotated image as np.array
"""
# create an tuple that contains height/2, width/2
image_center = tuple(np.array(image.shape[1::-1]) / 2)
# rot_mat 2x3 rotation mattrix
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
# apply the affine transformation to the image
# size of the output image image.shape[1::-1]
result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
return result
def read_image(img_path):
image = cv2.imread(img_path)
scale_percent = 18 # percent of original size
width = int(image.shape[1] * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
dim = (width, height)
rescaled_img = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
return image, rescaled_img
def save_img(dir_path,filename,img):
"""
dir_path - directory path where the image will be saved
filename - requires a valid image format
img - image to be saved
"""
file_path = os.path.join(dir_path,filename)
cv2.imwrite(file_path,img)
def find_text_angle(dilated_img,org_img):
"""
org_img - original image
img - dilated img
"""
lines = cv2.HoughLinesP(dilated_img,rho=1,theta=np.pi/180,threshold=30,minLineLength=5,maxLineGap=20)
nb_lines = len(lines)
angle = 0
for line in lines:
x1,y1,x2,y2 = line[0]
angle += math.atan2((y2-y1),(x2-x1))
angle/=nb_lines
rotated = rotate_image(org_img, angle-1)
rot_dilated = rotate_image(dilated_img,angle-1)
return rotated, rot_dilated
def extract_text_lines(img,output_dir):
"""
img - image from which the text lines are extracted
output_dir - directory where the extracted lines should be saved
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray, 5)
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 5, 5)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (16, 2))
dilate = cv2.dilate(thresh, kernel, iterations=2)
rotated,rot_dilated = find_text_angle(dilate,img)
cnts = cv2.findContours(rot_dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(cnts) == 2:
cnts = cnts[0]
else:
cnts = cnts[1]
lines_path = os.path.join(output_dir,'lines')
if not os.path.exists(lines_path):
os.makedirs(lines_path)
for line_idx, line in enumerate(cnts, start=-len(cnts)):
x, y, w, h = cv2.boundingRect(line)
roi = rotated[y:y + h, x:x + w]
filename = 'line'+str(line_idx)+ '.jpg'
save_img(lines_path,filename=filename,img=roi)
def extract_text_chars(img,output_dir):
"""
img - image from which the individual chars are extracted
output_dir - directory where the extracted lines should be saved
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray, 7)
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 7, 11)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 7))
dilate = cv2.dilate(thresh, kernel, iterations=1)
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(cnts) == 2:
cnts = cnts[0]
else:
cnts = cnts[1]
chars_path = os.path.join(output_dir,'chars')
if not os.path.exists(chars_path):
os.makedirs(chars_path)
for char_idx, character in enumerate(cnts, start=-len(cnts)):
x, y, w, h = cv2.boundingRect(character)
roi = img[y:y + h, x:x + w]
filename = 'char'+str(char_idx)+ '.jpg'
save_img(chars_path,filename=filename,img=roi)
if __name__ == '__main__':
# provide the indut/outpur directory paths
input_dir = os.path.join(os.getcwd(),'images')
output_dir = os.path.join(os.getcwd(),'output')
for img_file in os.listdir(input_dir):
img_file_path = os.path.join(input_dir,img_file)
image, rescaled_image = read_image(img_path=img_file_path)
img_out_dir = os.path.join(output_dir,img_file.split('.')[0])
extract_text_lines(rescaled_image,img_out_dir)
extract_text_chars(image,img_out_dir) |
02e1c54278a092333d77aa76221a6223e37a6e6e | abhishekdwibedy-2002/Spectrum_Internship_Task | /prgm1.py | 803 | 4.65625 | 5 | # Python3 program to Convert characters of a string to opposite case
# Function
def case_converter(string):
length = len(string)
for i in range(length):
# Checks for lower case character
if string[i] >= 'a' and string[i] <= 'z':
# Convert it into Upper case
string[i] = chr(ord(string[i]) - 32)
# Checks for Upper case character
elif string[i] >='A' and string[i] <= 'Z':
# Convert it into lower case
string[i] = chr(ord(string[i]) + 32)
# Main Code
string = input("Enter The Case That To Be Converted :-")
string = list(string)
# Calling the Function
case_converter(string)
string = ''.join(string)
print("String After Conversion :-" + string) |
f35ad76356e42fab906bb790aa36252d74555e35 | Man0j-kumar/python | /remove 3rd.py | 247 | 3.671875 | 4 | def removethird(int_list):
pos=2
idx=0
len_list=(len(int_list))
while len_list>0:
idx=(pos+idx)%len_list
print(int_list.pop(idx))
len_list-=1
nums=[int(x) for x in input().split()]
removethird(nums) |
bf164acce47738ecce1a629b7fea65721fa65c69 | Devrother/algorithm-exercises | /Dovlet/3stair-rendezvous/seunguklee/solution.py | 120 | 3.53125 | 4 | a, b = map(int, input().split())
def gcd(x, y):
return x if y == 0 else gcd(y, x % y)
print((a + b) // gcd(a, b))
|
07cca0cb8b55a1f4e970a1851ce04134e9dc9c8b | nosbod18/Alien-Crash | /choose_path_2.py | 10,077 | 3.6875 | 4 | # 2/10/20
# Evan Dobson
# Project: Alien crash
# Module: choose_path_2
import time
import random
import variables as var
def choose_path2(): # defines a function to allow the player to choose a path
is_helecopter = random.randint(1,2) # sets a random number (1 or 2) to is_helecopter
if is_helecopter == 1: # checks if is_helecopter equals 1
print("\n\nAfter you walk some more, you start to hear the unmistakable sound of a helecopter.")
time.sleep(3.5)
print("\nThis didn't sound like an ordinary helecopter, this one was big. Proabably military.")
time.sleep(3.5)
print("\nYou briefly laugh at the chances of you meeting a helecopter out here, but right now your only focus is to evade the helecopter,")
print("which you can now see, heading straight towards you")
time.sleep(4.5)
print("\nThere's a grove of trees far ahead that would provide you with a good hiding spot, but theres a good chance the helecopter will see you before you get there.")
time.sleep(3.5)
print("\nOr you could go back to that run down house you passed a while ago, but you would lose a lot of time, which only increases the chance of your ship being found.")
time.sleep(3.5)
path2 = " "
while path2 != "1" and path2 != "2": # defines a while loop that will display the code below until the player enters 1 or 2
print("\nWill you run towards the helecopter, or will you play it safe and run back? (1 or 2)")
path2 = input()
return(path2)
else:
print("\nAs you walk, you start to see buildings on the horizon. Looks like a town is ahead, but it's still a long way off.")
time.sleep(3.5)
print("\nYou start worrying about all the things that could go wrong, like your ship being found, or someone spotting you out here in the open.")
time.sleep(3.5)
print("\nYou quicken your stride.")
time.sleep(3)
print("\nFinally you reach the edge of the town. On the other side of it is a big scrapyard where there is sure to be enough materials for you.")
time.sleep(3.5)
var.continue_var1 = True
def check_path2(path2): # defines a function to check which path the player took
if path2 == str(1): # checks if the path the player entered equals 1
print("\nYou start sprinting towards that small patch of trees way up ahead.")
time.sleep(3.5)
print("\nAs you run, you notice the trees don't seem to be getting any closer. They're a lot farther away than you thought.")
time.sleep(3.5)
print("\nThe helecopter's even closer now.")
time.sleep(3)
print("\nJust as you're about to enter the trees, the helecopter is right above you. A spotlight bursts on,")
time.sleep(3.5)
is_discovered = random.randint(1,10) # sets a random number (1 or 2) to is_discovered
if is_discovered > 3: # checks to see if is_discovered equals the path the player chose
print("\nilluminating everything around you! A feeling of dread creeps in you as you know you have been spotted.")
time.sleep(3.5)
print("\nYou dive behind a fallen tree and try your best to hide, but to no avail.")
time.sleep(3.5)
print("\nYou hear feet hitting the ground as people are lowered from the helecopter, which has been hovering over the patch of trees.")
time.sleep(3.5)
print("\nPeople rush into the woods and in no time you are found...")
time.sleep(3.5)
print("\n\nYou were discovered! You got taken away by the government, never to be seen again...")
var.end = True
else:
print("\nbut you are already in the woods. You dive behind a fallen tree and wait, terrified that you were spotted.")
time.sleep(3.5)
print("\nThe helecopter hovers over the woods, its spotlight sweeping from side to side.")
time.sleep(3.5)
print("\nLuckily, the leaves are dense enough that only a little of the light penetrates into the woods.")
time.sleep(3.5)
print("\nAfter what seems like forever, the helecopter flys off and you breathe a huge sigh of relief.")
time.sleep(3.5)
print("\nThat was close. Again. You need to be more careful.")
time.sleep(3)
print("\nYou start walking, and soon see a town on the horizon. There's a scrapyard on the outskirts.")
time.sleep(3.5)
print("\nHopefully it's big enough materials for you to find everything you need.")
time.sleep(3.5)
print("\nOnce your reach the scrapyard, all doubts are flung from your mind.")
time.sleep(3.5)
print("\nPiles and piles of materials are scattered all around. You will definately be able to find all the materials you need.")
time.sleep(3.5)
print("\nAs you are searching for the last few pieces, you hear a strange whirring noise followed by a tremendous crash")
print("which scares you so bad you drop all of your materials.")
time.sleep(4.5)
print("\nGrumbling as you pick them up, you go and investigate the noise.")
time.sleep(3.5)
is_person = random.randint(1,10)
if is_person == 1:
print("\nAs you round a pile of scrap metal where the noise came from, you see a person operating a huge crane. He spots you immediatly and you know it...")
time.sleep(3.5)
print("\n\nYou were discovered! You got taken away by the government, never to be seen again...")
var.end = True
else:
print("\nAs you round the pile of scrap metal where the noise came from, you see nothing obvious that could have made such a noise.")
time.sleep(3.5)
print("\nAfter a little more investigating, the wind blows past you making the same whirring noise you heard earlier.")
time.sleep(3.5)
print("\nThe wind knocks off a piece of metal from the top of the stack, which then falls and makes the same huge crash.")
time.sleep(3.5)
print("\nBreathing a sigh of relief that it wasn't a human made sound, you leave the scrapyard with your materials in tow.")
time.sleep(3.5)
people_at_crash = random.randint(1,10)
if people_at_crash > 3:
print("\nAs you approach where your ship crashed, you notice a set of lights bobbing around. Looks like your ship has been found.")
time.sleep(3.5)
print("\nYou reach the top of the hill and lay down to avoid being seen while trying to figure out the best way to do this.")
time.sleep(3.5)
print("\nAfter a little bit of thinking, you decide to run to your ship while the people are out of view.")
time.sleep(3.5)
print("\nThe lights dissappear behind the ship. Ok. Time to run.")
time.sleep(3.5)
print("\nGetting up, you sprint down the hill with your materials in tow. They are making a lot of noise.")
time.sleep(3.5)
print("\nJust as you are about to reach the door and be safe, the people come running and catch you right as you were about to board...")
time.sleep(3.5)
print("\n\nYou were discovered! You got taken away by the government, never to be seen again...")
var.end = True
else:
print("\nIts eerily quiet as you reach where your ship crashed. You expected lots of people, but it doesn't seem like anyone's around.")
time.sleep(3.5)
print("\nYou reach the top of the hill and lay down to make sure there's no one here.")
time.sleep(3.5)
print("\nAfter inspecting the area around the ship, you are satisfied that no one is here.")
time.sleep(3.5)
print("\nAll the same, as you get up, you run down the hill, constantly looking left and right.")
time.sleep(3.5)
print("\nYou make it to the door without incident.")
time.sleep(3)
print("\nAfter another hard couple of hours hammering away, your ship is repaired.")
time.sleep(3.5)
print("\nYou engage the warp drive and jump into hyperspace, on your way home.")
time.sleep(3.5)
print("\n\nCongradulations! You repaired your ship and left Earth without being discovered by the humans!")
var.end = True
elif path2 == str(2):
print("\nYou look at the trees ahead, but decide to play it safe. Turning around, you sprint back to the house.")
time.sleep(3.5)
print("\nYou make it into the house with plenty of time before the helecopter flys over. Turning around, you take in the inside of the house.")
time.sleep(3.5)
print("\nAs you look around, the sight of a body on the ground startles you hard enough to knock over some jars on the table. Is it dead?")
time.sleep(3.5)
print("\nThe body jumps to his feet, just as startled as you are. Oh. Not dead, just asleep. Wait...")
time.sleep(3.5)
print("\nHe's another alien... just like you.")
time.sleep(3.5)
print("\nAfter getting to know him a little, you learn that he desperatly needs your help. If you help him, he is sure to reward you.")
time.sleep(3.5)
print("\nHowever, helping him will cost a lot of time.")
time.sleep(3.5)
|
0f6d7266af4a384ce3eacf12090e7aa274693404 | dwitka/tsp_solver | /tspturtle.py | 1,696 | 4.03125 | 4 | import turtle
f = 16
def draw(L):
"""(list of tuples-->None)
Draws a line from one set of coordinates to the next
until all coordinates have been connected and then
returns to starting points."""
turtle.speed(10)
length = L.__len__() - 1
for item in L:
turtle.penup()
turtle.goto(item[0] *f, item[1]*f)
turtle.pendown()
x = L.index(item)
if x != length:
turtle.goto(L[x + 1][0]*f, L[x + 1][1]*f)
else:
turtle.goto(L[0][0]*f, L[0][1]*f)
def draw_points(L):
"""(list of tuples-->None)
Draws a point for every set of coordinates in the list
and then calls draw() to connect the points."""
turtle.setworldcoordinates(-100,-100,1000,1000)
for item in L:
turtle.penup()
turtle.goto(item[0]*f, item[1]*f)
turtle.pendown()
turtle.goto(item[0]*f + 1, item[1]*f)
turtle.goto(item[0]*f + 1, item[1]*f +1)
turtle.goto(item[0]*f -1 , item[1]*f +1)
turtle.goto(item[0]*f -1 , item[1]*f -1)
turtle.goto(item[0]*f + 2 , item[1]*f - 1)
turtle.hideturtle()
#draw(L)
def tsp_draw(PL, P, PR):
"""((tuple, tuple, tuple)-->None)
graphically connects node P to points on map PL and PR,
while erasing the line from PL to PR"""
turtle.penup()
turtle.goto(PL[0]*f, PL[1]*f)
turtle.pendown()
turtle.pencolor("white")
turtle.goto(PR[0]*f, PR[1]*f)
turtle.pencolor("black")
turtle.goto(P[0]*f, P[1]*f)
turtle.goto(PL[0]*f, PL[1]*f)
def exit_turtle():
"""(None-->None)
closes the turtle on click"""
turtle.exitonclick()
|
10a804ead02715ddc9b9bf2a530ede3237d0db93 | dev-danilosilva/integer-arithmetic-expression-evaluator | /interpreter.py | 7,586 | 3.5 | 4 | '''
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : (PLUS | MINUS) factor | INTEGER | LPAREN expr RPAREN
'''
from enum import Enum
from typing import Any
# ==== Lexical Analyzer ====
class TokenType(Enum):
START = 0
INTEGER = 1
PLUS = 2
MINUS = 3
MULT = 4
DIV = 5
SPACE = 6
LPAREN = 7
RPAREN = 8
EOF = 9
class Token:
def __init__(self, type_: TokenType, value: Any):
self.type = type_
self.value = value
def __repr__(self) -> str:
return f'Token<{self.type}, {self.value}>'
class Lexer:
def __init__(self, source: str) -> None:
self.source = source
self.pos = -1
self.curr_char = None
self.curr_token = Token(TokenType.START, None)
self.operations = {
'+': TokenType.PLUS,
'-': TokenType.MINUS,
'*': TokenType.MULT,
'/': TokenType.DIV
}
def __iter__(self):
return self
def __next__(self):
if self.curr_token.type == TokenType.EOF:
raise StopIteration
return self.get_next_token()
def advance(self, reverse=False) -> None:
if reverse:
self.pos -= 1
if self.pos > 0:
self.curr_char = self.source[self.pos]
else:
self.curr_char = None
self.curr_char = Token(TokenType.START, None)
else:
self.pos += 1
if self.pos < len(self.source):
self.curr_char = self.source[self.pos]
else:
self.curr_char = None
self.curr_token = Token(TokenType.EOF, None)
def curr_char_is_digit(self) -> bool:
return self.curr_char and self.curr_char.isdigit()
def curr_char_is_operation(self) -> bool:
return self.curr_char and self.curr_char in self.operations.keys()
def curr_char_is_space(self) -> bool:
return self.curr_char and self.curr_char.isspace()
def curr_char_is_lparen(self) -> bool:
return self.curr_char and self.curr_char == '('
def curr_char_is_rparen(self) -> bool:
return self.curr_char and self.curr_char == ')'
def take_full_integer(self):
full_number = ''
while self.curr_char_is_digit():
curr_char = self.curr_char
full_number += curr_char
self.advance()
self.advance(reverse=True)
return int(full_number)
def get_next_token(self) -> Token:
self.advance()
if self.curr_token == TokenType.EOF or self.pos >= len(self.source):
self.curr_token = self.curr_token = Token(TokenType.EOF, None)
elif self.curr_char_is_digit():
self.curr_token = Token(TokenType.INTEGER, self.take_full_integer())
elif self.curr_char_is_operation():
self.curr_token = Token(self.operations[self.curr_char], self.curr_char)
elif self.curr_char_is_lparen():
self.curr_token = Token(TokenType.LPAREN, '(')
elif self.curr_char_is_rparen():
self.curr_token = Token(TokenType.RPAREN, ')')
elif self.curr_char_is_space():
return self.get_next_token()
else:
self.curr_token = Token(TokenType.EOF, None)
return self.curr_token
# === Parser / Syntax Analyzer ===
class Ast:
def __init__(self, token: Token) -> None:
self.token = token
class UnaryOp(Ast):
def __init__(self, token: Token, expr: Ast) -> None:
super().__init__(token)
self.expr = expr
class BinOp(Ast):
def __init__(self, token: Token, left: Ast, right: Ast) -> None:
super().__init__(token)
self.left = left
self.right = right
def __str__(self) -> str:
return f'BinOp<{self.left.token.type.name} {self.token.type.name} {self.right.token.type.name}>'
class Num(Ast):
def __init__(self, token: Token) -> None:
super().__init__(token)
def __str__(self) -> str:
return f'Num<{str(self.token.value)}>'
class Parser:
def __init__(self, lexical_analyzer: Lexer) -> None:
self.lexer = lexical_analyzer
self.curr_token = lexical_analyzer.get_next_token()
def raise_exception(self, error_message):
raise Exception(error_message)
def eat(self, *or_):
for type_ in or_:
if self.curr_token.type == type_:
self.curr_token = self.lexer.get_next_token()
return
expected = ' or '.join(map(lambda t: t.name, or_))
got = self.curr_token.type.name
self.raise_exception(f'I was expecting for {expected} but got {got}.')
def factor(self):
token = self.curr_token
if token.type == TokenType.INTEGER:
self.eat(TokenType.INTEGER)
return Num(token)
elif token.type == TokenType.LPAREN:
self.eat(TokenType.LPAREN)
ast_node = self.expr()
self.eat(TokenType.RPAREN)
return ast_node
elif token.type in (TokenType.PLUS, TokenType.MINUS):
self.eat(TokenType.PLUS, TokenType.MINUS)
return UnaryOp(token, self.factor())
self.raise_exception('Invalid Factor')
def term(self):
factor = self.factor()
while self.curr_token.type in (TokenType.MULT, TokenType.DIV):
token = self.curr_token
self.eat(TokenType.MULT, TokenType.DIV)
factor = BinOp(token, factor, self.factor())
return factor
def expr(self):
term = self.term()
while self.curr_token.type in (TokenType.PLUS, TokenType.MINUS):
op = self.curr_token
self.eat(TokenType.PLUS, TokenType.MINUS)
term = BinOp(op, term, self.term())
return term
def parse(self):
return self.expr()
# === Interpreter ===
class NodeVisitor:
def visit(self, node: Ast):
method_name = 'visit_' + type(node).__name__
visitor = getattr(self, method_name, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
raise Exception(f'visit_{type(node).__name__} or a generic_visit is not implemented')
class Interpreter(NodeVisitor):
def __init__(self, ast: Ast) -> None:
self.ast = ast
self.operations = {
TokenType.PLUS : lambda x, y: x + y,
TokenType.MINUS : lambda x, y: x - y,
TokenType.MULT : lambda x, y: x * y,
TokenType.DIV : lambda x, y: x // y
}
def visit_BinOp(self, node: Ast):
op = self.operations[node.token.type]
return op(self.visit(node.left), self.visit(node.right))
def visit_Num(self, node: Ast):
return node.token.value
def visit_UnaryOp(self, node: Ast):
if node.token.type == TokenType.MINUS:
return -self.visit(node.expr)
else:
return +self.visit(node.expr)
def execute(self):
return self.visit(self.ast)
def main():
while True:
source_code = input('pyparser > ')
if source_code == ':q':
print('Tchau!')
break
lexer = Lexer(source_code)
parser = Parser(lexer)
try:
ast = parser.parse()
except:
print('Invalid Input')
continue
interpreter = Interpreter()
print(interpreter.execute())
if __name__ == '__main__':
main()
|
1276b131313f780195fd5c61746f58ab19f2b3a4 | rashmitallam/PythonBasics | /count_upper_lower_case_dict.py | 1,527 | 4.03125 | 4 | #WAP to accept a sentence which contains upper and lower case characters, return a dict containing count of total no. of upper and lower case chars
def CountUpperLowerDict(s1):
res=dict()
u_count=l_count=0
for ch in s1:
if ch != ' ':
if ch.isupper():
if res.get(ch) != None:
res[ch] += 1
else:
res[ch] = 1
u_count += 1
else:
if res.get(ch) != None:
res[ch] += 1
else:
res[ch] = 1
l_count += 1
return(res,l_count,u_count)
def main():
s=input('Enter a sentence having upper and lower case characters:')
(res,l,u)=CountUpperLowerDict(s)
print 'Count of Lower case chars: {}\nCount of Upper case chars: {}'.format(l,u)
for x in res:
print(x,res[x])
#print 'Count of Upper case chars: '+str(u)
if __name__ == '__main__':
main()
'''
>>>
RESTART: C:\Users\Admin\Desktop\Python_2019\Dictionary\hw_2_3\count_upper_lower_case.py
Enter a sentence having upper and lower case characters:'Hi. My name is Rashmi Tallam. I like Programming!'
Count of Lower case chars: 35
Count of Upper case chars: 6
('a', 5)
('!', 1)
('r', 2)
('e', 2)
('g', 2)
('P', 1)
('i', 5)
('H', 1)
('k', 1)
('M', 1)
('m', 5)
('o', 1)
('n', 2)
('I', 1)
('s', 2)
('R', 1)
('T', 1)
('h', 1)
('y', 1)
('.', 2)
('l', 3)
>>>
'''
|
fd01d7fd0b173fa5ea4509bb192f7db03c0069b0 | xhuang68/XHSimpleProjects | /sort_algorithm_python/merge_sort.py | 622 | 3.984375 | 4 | __author__ = 'xiaohuang'
def merge_sort(array):
if len(array) <= 1:
return array
mid = len(array) / 2
left = merge_sort(array[:mid])
right = merge_sort(array[mid:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
if len(left) > 0:
result += left
if len(right) > 0:
result += right
return result
array = [5, 7, 3, 4, 6, 9, 8, 1, 0, 2]
result = merge_sort(array)
print result |
9b63be2473b73ea213cb074558ec54e6c1c7b4d7 | sumanthmadupu/MyPython | /guessing_game.py | 495 | 3.96875 | 4 | #guessing game
import random
comp_num = random.randint(1,9)
usr_inp = input("Guess a number between [1,9] : ")
attempt = 1
while(1):
try:
if comp_num > int(usr_inp):
print("Go higher")
elif comp_num < int(usr_inp):
print("Go lower")
else:
print("Awesome.You got it in "+str(attempt)+" times")
break
attempt += 1
usr_inp = input("Guess again...: ")
except ValueError:
if usr_inp.upper() == "EXIT":
break
else:
print("type 'exit' to quit .")
usr_inp = input() |
ac3e2eadd27227b2748fe342b474060054217f7c | PFSDevTeam/kaffeeklatsch | /kaffeeklatsch/forms/RegistrationForm.py | 1,238 | 3.515625 | 4 |
#File: RegistrationForm.py
#@author: Ryan Dombek, Geoff Floding, David Hovey
#Description: this file contains the form to register the user
# based on given credentials
# Imports
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, Length, Regexp, EqualTo
# Define the elements of the RegistrationForm
class RegistrationForm(FlaskForm):
username = StringField('username',
validators =[DataRequired(),
Length(min=1, max=25)])
# Regex pattern taken from https://www.section.io/engineering-education/password-strength-checker-javascript/
password = PasswordField('password',
validators = [DataRequired(),
Length(min=8, max=64, message='Password length must be between 8 and 64 characters.'),
Regexp('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,64})', message="Password must contain 1 lower and upper case letter, number and a special character")])
repeatPassword = PasswordField('Repeat Password', validators = [EqualTo('password', message='Passwords must match')])
submit = SubmitField('submit')
|
4a73f8d597120103b06ed2489eb6fc1c0f115022 | badbit/int-python | /pira.py | 465 | 4.28125 | 4 | #progama para hacer una piramide
def piramide (escalon):
numero= 1
estrellitas= 1
espacio= escalon
while numero<=escalon:
print("%s%s" %(espacio*" ", estrellitas *"*"))
espacio=espacio-1
estrellitas=estrellitas+2
numero=numero+1
print("\esta es su priamide.")
print(".:programa para hacer piramides:.")
escalon=int(input("introduce el numero de escalones: "))
print(piramide(escalon)) |
b8a1fafb5ba4161f22cb0505fa7fd558b87478f1 | jjpikoov/university | /python/1/1.py | 2,861 | 4.0625 | 4 | #!/usr/bin/env python
from sys import argv
from random import randint
def roll_dice():
"""Function returns random number from 1 to 6"""
return randint(1, 6)
def game(number_of_matches):
"""Game"""
player1_won_games = 0
player2_won_games = 0
for match in range(number_of_matches):
print "======"
print "ROUND {0}".format(match + 1)
print "======"
print "Player1 rolls a dice..."
player1_first_roll = roll_dice()
print "First roll: {0}, so far: {1}".format(player1_first_roll, player1_first_roll)
player1_second_roll = roll_dice()
player1_scores_in_match = player1_first_roll + player1_second_roll
print "Second roll: {0}, so far: {1}\n".format(player1_second_roll, player1_scores_in_match)
print "Player2 rolls a dice..."
player2_first_roll = roll_dice()
print "First roll: {0}, so far: {1}".format(player2_first_roll, player2_first_roll)
player2_second_roll = roll_dice()
player2_scores_in_match = player2_first_roll + player2_second_roll
print "Second roll: {0}, so far: {1}\n\n".format(player2_second_roll, player2_scores_in_match)
if player1_scores_in_match > player2_scores_in_match:
player1_won_games += 1
elif player1_scores_in_match < player2_scores_in_match:
player2_won_games += 1
print "First player: {0} won matches".format(player1_won_games)
print "Second player: {0} won matches\n\n".format(player2_won_games)
if (player1_won_games == player2_won_games) and (match == number_of_matches - 1) :
print "+++++++++++++++++"
print "+++ EXTRA GAME +++"
print "+++++++++++++++++"
extra_time()
def extra_time():
while True:
print "Player1 rolls a dice..."
player1_first_roll = roll_dice()
print "First roll: {0}, so far: {1}".format(player1_first_roll, player1_first_roll)
player1_second_roll = roll_dice()
player1_scores_in_match = player1_first_roll + player1_second_roll
print "Second roll: {0}, so far: {1}\n".format(player1_second_roll, player1_scores_in_match)
print "Player2 rolls a dice..."
player2_first_roll = roll_dice()
print "First roll: {0}, so far: {1}".format(player2_first_roll, player2_first_roll)
player2_second_roll = roll_dice()
player2_scores_in_match = player2_first_roll + player2_second_roll
print "Second roll: {0}, so far: {1}\n\n".format(player2_second_roll, player2_scores_in_match)
if player1_scores_in_match > player2_scores_in_match:
print "FIRST PLAYER WON A GAME!!!"
break
elif player1_scores_in_match < player2_scores_in_match:
print "SECOND PLAYER WON A GAME!!!"
break
game(int(argv[1]))
|
a702c65c643f8623c8c474e7455888df0a5d4de3 | MajidSalimi/Python-Learning | /WorkingWithFiles/Files.py | 260 | 3.921875 | 4 | #Opens a read-only File
f=open('MyFile.txt','r')
#Reads file's content
file_content=f.read();
#closes the file
f.close()
#opens or creates a writable files
f2=open('a_file.txt','w')
#writes in the file
f2.write("This is my first program with files")
f2.close() |
eb8939664c8d052a0bafe2a89a030571b86cd71f | meloLeeAnthony/PythonLearn | /05-object面向对象/01类和对象.py | 1,072 | 4.15625 | 4 | """
Created on 2018年10月10日
@author: Administrator
"""
# <class '__main__.Dog'>
class Dog(object):
"""
面向对象的对象
"""
@staticmethod
def run():
"""
面向对象的方法
"""
print("running")
# init不是构造器,只是完成对象的初始化操作,默认调用,可以在创建对象的时候写成参数
def __init__(self, name, age):
print("init被调用")
self.name = name
self.age = age
def __new__(cls, name, age):
print("new被调用")
return object.__new__(cls)
def __str__(self):
return "name:%s---age:%s" % (self.name, self.age)
def __del__(self):
print("%s被回收" % self.name)
dog = Dog("haha", 12)
dog.run()
dog2 = Dog("heihei", 3)
dog2.run()
print(isinstance(dog2, Dog))
print(dog.name)
print(dog.age)
print(dog2.age)
print(dog2.name)
print(dog)
print(dog2)
dog = Dog("haha", 12)
dog2 = dog
dog3 = dog
print("dog2被删除")
del dog
print("dog3被删除")
del dog3
print("dog被删除")
del dog2
|
827b61898c325f8c827bd68ed0cb86b1c65ec635 | repsac/invert_binary_tree | /_unittest.py | 580 | 3.703125 | 4 | import invert_binary_tree
TREE_A = tuple(range(1, 8))
TREE_A_INVERT = (1, 3, 2, 7, 6, 5, 4)
TREE_B = tuple(range(1, 32))
TREE_B_INVERT = tuple([1, 3, 2] + list(reversed(range(4, 8)))
+ list(reversed(range(8, 16)))
+ list(reversed(range(16, 32))))
def run_tests():
assert invert_binary_tree.invert(TREE_A) == TREE_A_INVERT, \
"Failed to invert first tree"
assert invert_binary_tree.invert(TREE_B) == TREE_B_INVERT, \
"Failed to invert second tree"
def _main():
run_tests()
if __name__ == '__main__':
_main() |
fa0a903dff422680f6a2244283c2f6358be3c874 | enterpriseih/Python100days | /day01_15/day11/file3.py | 541 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 写文本文件
# 将100以内的素数写入到文件中
# @Date : 2019-07-14 16:13:22
# @Author : yaolh ([email protected])
# @Link : https://github.com/yaolihui129
# @Version : 0.1
from math import sqrt
def is_prime(n):
for factor in range(2,int(sqrt(n)) + 1):
if n % factor == 0:
return False
return True
# with open('prime.txt','a') as f:
with open('prime.txt','w') as f:
for num in range(2,100):
if is_prime(num):
f.write(str(num)+ '\n')
f.close()
print('写入完成!')
|
9b13d87c9f8236d26e9c238155a260d63272588b | deepcpatel/data_structures_and_algorithms | /Graph/number_of_islands_II.py | 3,740 | 4 | 4 | # Link: https://www.lintcode.com/problem/number-of-islands-ii/
# Approach: Every new land block can create three possibilities. If it is isolated (no neighbouring land), then it creates new island. If it has one surrounding island, then it can extend that island
# or else if there are detached surrounding island, then it joins them. Thus, we use union find algorithm to join the island. For that, we keep parent and number of children count of each island
# block. If two or more than two islands are to be merged, we merge smaller islands to the larger island. And at each iteration, we return the number of islands so far in our matrix.
"""
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
"""
@param n: An integer
@param m: An integer
@param operators: an array of point
@return: an integer array
"""
def find(self, n): # Find parent of current island
if self.parents[n] != n:
self.parents[n] = self.find(self.parents[n])
return self.parents[n]
def union(self, li): # Join neighbouring islands
max_c, sup_par, merged_island = float('-inf'), -1, 0
for n in li: # Finding the island with highest children (super island)
parent = self.find(n)
if self.nchildren[parent] > max_c:
max_c = self.nchildren[parent]
sup_par = parent
for n in li: # Merging other island with super island
parent = self.find(n)
if parent != sup_par:
self.parents[parent] = sup_par
self.nchildren[sup_par] += self.nchildren[parent]
merged_island += 1
return merged_island # Returns number of merged islands. We will use it to decrement the total island count
def find_neighbours(self, o, n, m): # Finds surrounding lands if any
li = []
if o.x-1 >= 0 and self.land[o.x-1][o.y] != 0:
li.append(self.land[o.x-1][o.y])
if o.x+1 < n and self.land[o.x+1][o.y] != 0:
li.append(self.land[o.x+1][o.y])
if o.y-1 >= 0 and self.land[o.x][o.y-1] != 0:
li.append(self.land[o.x][o.y-1])
if o.y+1 < m and self.land[o.x][o.y+1] != 0:
li.append(self.land[o.x][o.y+1])
return li
def numIslands2(self, n, m, operators):
self.parents, self.nchildren, self.land, self.counter, num_island = {}, {}, [[0]*m for i in range(n)], 1, 0
ans = []
for o in operators:
if self.land[o.x][o.y] == 0: # Check if this cell already has land or not
neighbours = self.find_neighbours(o, n, m)
if len(neighbours) == 0: # No surrounding land. Then create new one
npar, self.counter = self.counter, self.counter + 1
self.parents[npar], self.nchildren[npar] = npar, 0
num_island += 1
else: # If current land block is joining surrounding island, then join those islands
merged_island = self.union(neighbours)
npar = self.find(neighbours[0])
num_island -= merged_island # Decrementing total island count
self.land[o.x][o.y] = npar
self.nchildren[npar] += 1 # Update children of parent island
ans.append(num_island) # Append total number of islands
return ans |
8e598c4f1898bce19e8776d5f0c580fa3ae108d6 | RensOliemans/dmx-hackathon | /color.py | 1,267 | 4.03125 | 4 | """
Module containing the Color class
"""
class Color:
"""Color object, having r, g, b, and a to_hex method."""
r = 0
g = 0
b = 0
def __init__(self, r, g, b):
self.r = r or 0
self.g = g or 0
self.b = b or 0
def to_hex(self):
"""Converts this object to a hex representation"""
return "#{:02X}{:02X}{:02X}".format(self.r, self.g, self.b)
@staticmethod
def to_rgb(hex_code):
"""Converts a given hex code to a Color object with proper rgb values.
:param: hex_code, color code in hex (with or without '#' to convert)
"""
color = hex_code.lstrip('#')
return Color(*tuple(int(color[i:i + 2], 16) for i in (0, 2, 4)))
def __add__(self, other):
return Color(int(self.r + other.r), int(self.g + other.g), int(self.b + other.b))
def __sub__(self, other):
return Color(int(self.r - other.r), int(self.g - other.g), int(self.b - other.b))
def __mul__(self, other):
return Color(int(self.r * other), int(self.g * other), int(self.b * other))
def __eq__(self, other):
return self.r == other.r and self.g == other.g and self.b == other.b
def __str__(self):
return self.to_hex()
__rmul__ = __mul__
|
6fa8dd08d37c74094bc74373aa88078fba4e9160 | AxelRaze/Subsecuencia | /Subsecuencia.py | 1,010 | 3.578125 | 4 | class Subsecuencia:
maximo = 0
datosSecuenMax = []
def _lis(self,arr, n):
# caso base _punto_quiebre
if n == 1:
return 1
maxFinalizaado = 1
for i in range(1, n):
res = self._lis(arr, i)
if arr[i - 1] < arr[n - 1] and res + 1 > maxFinalizaado:
self.datosSecuenMax.append(arr[i])
maxFinalizaado = res + 1
self.maximo = max(self.maximo, maxFinalizaado)
# print(self.maximum, end= '')
return maxFinalizaado
def lis(self,arr):
#global maximo
#valores = []
# lenght of arr
n = len(arr)
self.maximo = 1
self._lis(arr, n)
return self.maximo
def main():
arr = [3,10,2,1,20]
secuencia = Subsecuencia()
secuencia.lis(arr)
print("La subsecuencia creciente más larga es de tamaño", secuencia.lis(arr))
#n = len(arr)
if __name__ == "__main__":
main()
|
6e6bccda0b771bb7f3c16e14a937687b7ed0aeea | Jimut123/code-backup | /python/python_new/Python 3/elif.py | 213 | 4.40625 | 4 | #Program checks if the number is positive or negative# And displays an appropriate message
num=3.4
#num=0
#num=-4.5
if num>=0:
print("Positive number")
elif num==0:
print("Zero")
else:
print("Negative number")
|
e0cb9722eb6a70891511a09b4afe531d0b2bde28 | arozrai/removeFiles-project99 | /RemoveFiles.py | 1,926 | 3.8125 | 4 | import time
import os
import shutil
def main():
path = input("Which folder will you want to apply this program on? ")
days = int(input("Delete files over what days old: "))
seconds = time.time() - (days * 24 * 60 * 60)
print(seconds)
pathExists = os.path.exists(path)
deletedFoldersCount = 0
deletedFilesCount = 0
if(os.path.exists(path)):
for root_folder,folders,files in os.walk(path):
if (seconds >= getFile_folderAge(root_folder)):
remove_folder(root_folder)
deletedFoldersCount += 1
break
else:
for folder in folders:
folder_path = os.path.join(root_folder,folder)
if (seconds >= getFile_folderAge(folder_path)):
remove_folder(folder_path)
deletedFoldersCount += 1
for file in files:
file_path = os.path.join(root_folder,file)
if (seconds >= getFile_folderAge(file_path)):
remove_file(file_path)
deletedFilesCount += 1
else:
print("Folder was not found")
print("Amount of folders deleted: ",deletedFoldersCount,", Amount of files deleted: ",deletedFilesCount)
def getFile_folderAge(path):
ctime = os.stat(path).st_ctime
return ctime
def remove_folder(path):
if not shutil.rmtree(path):
print(path+" is removed successfully")
else:
print("Unable to delete the path")
def remove_file(path):
if not os.remove(path):
print(path+" is removed successfully")
else:
print("Unable to delete the path")
main()
# folder = os.path.join()
# daysUnchanged = st_ctime(os.stat(path))
# if (daysUnchanged > seconds):
# root=os.path.splitext(path)
# if ():
# os.remove(path)
# elif ():
# shutil.rmtree()
|
d9c7fe58b3b09ffd0e45e640ed83fd532afbd176 | WustAnt/Python-Algorithm | /Chapter5/5.2/5.2.2/5-4.py | 553 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/8/21 17:14
# @Author : WuatAnt
# @File : 5-4.py
# @Project : Python数据结构与算法分析
def binarySearch(list,item):
'有序列表的二分搜索递归版本'
if len(list) == 0:
return False
else:
midpoint = len(list) // 2
if list[midpoint] == item:
return True
else:
if item < list[midpoint]:
return binarySearch(list[:midpoint], item)
else:
return binarySearch(list[midpoint+1:], item) |
1a708735606c875b34212081359558e198b5aa5b | dinobobo/Leetcode | /702_search_sorted_array_unknown_size.py | 730 | 3.8125 | 4 | # Find boundary and binary search
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
# Binary search
def binary_search(l, r):
while l <= r:
mid = l + (r - l)//2
if reader.get(mid) == target:
return mid
elif reader.get(mid) > target:
r = mid - 1
else:
l = mid + 1
return -1
# Find boundary
l, r = 0, 1
while reader.get(r) < target and reader.get(r) != 2147483647:
l = r
r *= 2
return binary_search(l, r)
|
3dfd5cdcda7b93d4e7c065a437789942b8eb9567 | tipdaddy78/keep_quiet_defusal | /modules/wire_sequence.py | 1,358 | 4 | 4 | red = [" ", "c", "b", "a", "ac", "b", "ac", "abc", "ab", "b"]
blue = [" ", "b", "ac", "b", "a", "b", "bc", "c", "ac", "a"]
black = [" ", "abc", "ac", "b", "ac", "b", "bc", "ab", "c", "c"]
def solve_wire_sequence():
print("WIRE SEQUENCE MODULE - START")
red_count = 0
blue_count = 0
black_count = 0
while True:
wire_color = input("\nEnter the next wire color; b for black, u for blue; or 'done'\n")
if wire_color == "done":
break
if wire_color == "red" or wire_color == "r":
red_count += 1
connection = input("What letter is it connected to?\n")
if connection in red[red_count]:
print("cut")
else:
print("leave")
if wire_color == "blue" or wire_color == "u":
blue_count += 1
connection = input("What letter is it connected to?\n")
if connection in blue[blue_count]:
print("cut")
else:
print("leave")
if wire_color == "black" or wire_color == "b":
black_count += 1
connection = input("What letter is it connected to?\n")
if connection in black[black_count]:
print("cut")
else:
print("leave")
print("WIRE SEQUENCE MODULE - END")
return |
a88d22d984b206d0ce70750336faa5766315882a | brunnaarruda/lab2018.2 | /navio.py | 2,008 | 3.578125 | 4 | class Campo:
def __init__(self):
self.navio = [] # é uma lista de lists == matriz
def lerCampo(self, l, i, j, b = False):
achou = b
if l[i][j] != '#':
return
else:
if achou == False: #comeca com falso e muda pra vdd pq achou o navio
achou = True
self.navio.append([])
l[i][j] = 'x' # ta mudando o navio hastag pra x
self.navio[len(self.navio) - 1].append((i, j)) #usou o -1 pq a ultima posicao da lista de navios é um a menos
self.lerCampo(l, i, j + 1, achou) # direita
self.lerCampo(l, i - 1, j,achou) # baixo
self.lerCampo(l, i, j - 1,achou) # esquerda
self.lerCampo(l, i + 1, j,achou) # cima
lc_matriz= input().split() #lc_matriz[0]=linha lc_matriz[1]=coluna
linha, coluna=int(lc_matriz[0]),int(lc_matriz[1])
l,borda_paralela,troca = [],[],"@"
for a in range(coluna+1):
borda_paralela.append(troca)
l.append(borda_paralela)
for b in range(linha):
caractere=list(troca+input()+troca)
l.append(caractere)
l.append(borda_paralela)
campo = Campo()
for i in range(linha + 1):
for j in range(coluna + 1):
campo.lerCampo(l, i, j)
lista_tiro=[]
num_tiros=int(input())
for y in range(num_tiros):
tiro = input().split()
x = int(tiro[0]), int(tiro[1])
lista_tiro.append(x)
for i in campo.navio: # i == a 1 navio da lista de navio
for j in range(len(i)): #j == a posicao dos pedacos do navio
for k in lista_tiro:
if k == i[j]: # se a pos tiro == pos do pedaco do navio ele troca pra um X
i[j]="X"
navios_destruidos=0
for i in campo.navio:
achou_navio= True
for j in i:
if j != "X":
achou_navio=False # se dentro da lista de pedacos do navio n tiver todos elementos com X ele n achou o navio destruido
break
if achou_navio:
navios_destruidos+=1 #Tudo foi X == navio destruidissimo
print(navios_destruidos)
|
80a1862d15c253316ecd1d91bdfadca6c452b332 | cognitiaclaeves/sphinx-autodoc-example | /src/silly_module.py | 774 | 3.71875 | 4 | # coding: utf-8
import pandas as pd
class PandasInput():
"""Class responsible for dealing with input pandas objects
(docstring written using Google style)
Attributes:
csv_file (str): filename of the csv file
"""
def __init__(self, csv_file):
self.csv_file = csv_file
def load_df(self, sep=','):
"""Load dataframe
Args:
`sep` (str, optional): separator (default: comma)
Returns:
dataframe
"""
return pd.read_csv(self.csv_file)
def fun_to_test(number):
"""Triple power `number`
(docstring written using Numpy style)
Parameters
----------
number : int
número
Returns
-------
int
"""
return number*number*number
|
a97d81a99ae5b4d90ae5eb9e133e8e603dba8ceb | Jirada01/Python | /test2 5_2.py | 462 | 3.53125 | 4 | list_name = [มาม่า,ลาบ,ส้มตำ,ข้าวแกง]
list_price = [12,60,40,25]
class shoplist :
def show_shoplist (self):
print ("แสดงรายการสินค้า [a]\n","เพิ่มรายการสินค้า [s] \n","ออกจากระบบ [x]\n")
def show() :
for x in range(0,len(list_name)) :
def input_list() :
x = shoplist()
x.show_shoplist() |
f8826f8d5268b9150bbf9cf3828898015c024c2a | misterwhybe/dataprocessing | /Homework/Week_1/visualizer.py | 1,185 | 3.953125 | 4 | #!/usr/bin/env python
# Name: wiebe jelsma
# Student number: 12468223
"""
This script visualizes data obtained from a .csv file
"""
import csv
import matplotlib.pyplot as plt
from statistics import mean
def visualize():
INPUT_CSV = "movies.csv"
START = 2008
END = 2018
# dictionary for the data
data_dict = {str(key): [] for key in range(START, END)}
with open(INPUT_CSV, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader)
for row in reader:
data_dict[row[2]].append(float(row[1]))
# calculate average rating per year
def average(data_dict):
average_rating=[]
for ratings in list(data_dict.values()):
average_rating.append(round(sum(ratings)/len(ratings),1))
linechart(average_rating)
# make line chart with averages per year
def linechart(average_rating):
plt.plot(list(data_dict),average_rating)
plt.title('Average rating per year')
plt.ylabel('IMDb rating')
plt.xlabel('Year')
plt.show()
average(data_dict)
if __name__ == "__main__":
visualize() |
1710ac1d81c4665706a2a79691acd5cfdb627224 | AolDunedein/BioLab | /run.py | 998 | 3.578125 | 4 | import fetch_sequence
import blasting
import dict_csv_gene
# FERRAMENTA CRIADA EM CONJUNÇÃO PELOS GRUPOS 13 e 9
# fetch_sequence
while True:
inp = input("Insira o seu grupo: ")
g=9
try:
g = int(inp)
if g<0 or g>13:
raise ValueError("Not Valid")
except Exception:
print("Nao valido, tente outra vez.")
continue
break
sequence_name = fetch_sequence.fetch_sequence(g)
#blasting with nr db
#nr_blast_result = blasting2.blast("nr",sequence_name)
swiss_blast_result = blasting.blast("swissprot",sequence_name)
print("Indexing values and creating table...")
# create dictionary for each gene
gene_dict = dict_csv_gene.create_gene_dict(sequence_name,None,swiss_blast_result)
# create csv from dict
csv_filename = dict_csv_gene.csv_export(gene_dict)
print ("Generated CSV file '"+csv_filename+"' successfully!")
report_filename = dict_csv_gene.create_report(gene_dict)
print ("Generated report file '"+report_filename+"' successfully!")
|
bf6a6485023d46693ee45973be858af11fd5e780 | nidhi2509/Mini-Python-Projects | /gradient-2.py | 1,389 | 3.78125 | 4 |
import image
def copy_image(img):
'''
Creates a copy of an image by iterating over the height and width and copying
each pixel to a new image.
Preconditions:
img is an image object
Postconditions:
return a copy of that image object
'''
assert isinstance(img, image.Image), 'img must be an Image object.'
imgcp = image.Image(img.width(), img.height(), title='Copied Image')
for r in range(img.height()):
for c in range(img.width()):
pixclr = img.get(c, r)
imgcp.set(c, r, pixclr)
return imgcp
def gray_copy(img):
'''
For now, this is just the same code that is in copy_image.
Change it so that it returns a grayscale copy of the given image.
'''
imgcp = image.Image(img.width(), img.height(), title='Copied Image')
for r in range(img.height()):
for c in range(img.width()):
pixclr = img.get(c, r)
rc = pixclr[0]
bc = pixclr[1]
gc = pixclr[2]
ave = (rc + bc + gc)/3
newclr = (ave,ave,ave)
imgcp.set(c, r, newclr)
return imgcp
def main():
img1 = image.Image(file='piechart.gif')
img1.show()
img2 = copy_image(img1)
img2.show()
img3 = gray_copy(img2)
img3.show()
image.mainloop()
if __name__ == '__main__':
main() |
8e40514dbad21219feb29d65a558c0ace8e4be35 | dongyueqian/pythonspider | /05_thread_process.py | 334 | 3.78125 | 4 | import math
def fn(n):
if n<2:
return False
if n==2:
return True
if n % 2 == 0:
return False
sq = int(math.floor(math.sqrt(n)))
for i in range(3,sq+1,1):
print(i,'------')
a = n % i
print(a)
# return sq
print(fn(27))
# for i in range(3,4,2):
# print(i)
|
4ac13cbe272d8ed915e0bc275a03603d1ee11265 | tlee0058/python_basic | /compare_lists.py | 1,690 | 4.59375 | 5 | # # Assignment: Type List
# # Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
# # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the list contains. If it contains only one type, print that type, otherwise, print 'mixed'.
# # Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get?
# Assignment: Compare Lists
# Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
# Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." Try the following test cases for lists one and two:
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
# list_one = [1,2,5,6,5]
# list_two = [1,2,5,6,5,3]
# list_one = [1,2,5,6,5,16]
# list_two = [1,2,5,6,5]
# list_one = ['celery','carrots','bread','milk']
# list_two = ['celery','carrots','bread','cream']
def compare_list(list_one, list_two):
if not len(list_one) == len(list_two):
print "The lists are not the same"
else:
for i in range(0, len(list_one)):
if not list_one[i] == list_two[i]:
print "The lists are not the same"
return
print "The lists are the same"
compare_list(list_two, list_one)
|
af7178afda5d5a2b40081c43ffcf0df33e69b979 | BigNianNGS/AI | /python_base/exercise.py | 2,683 | 3.75 | 4 | '''
第一题:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
'''
# ~ while(1):
# ~ score = input('请输入成绩(q for quit):')
# ~ if score == 'q' or score == 'quit':
# ~ break
# ~ score_int = float(score)
# ~ if(score_int >= 90):
# ~ print('A')
# ~ elif(score_int >= 60):
# ~ print('B')
# ~ else:
# ~ print('C')
# score = int(input('请输入你的成绩分数:'))
# if score >= 90:
# print('成绩为A')
# elif score >= 60 and score < 90:
# print('成绩为B')
# else:
# print('成绩为C')
'''
第二题:for
创建一个名为favorite_places的字典。
在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1〜3个地方.
朋友指出一个名字(input)。遍历这个字典,并将输入名字及其喜欢的地方打印出来
还可以继续输入名字 如果输入q则退出
#创建字典
favorite_places = {'张三':['上海','北京','广州'],'李四':['九寨沟','张家界','鼓浪屿'],'东方耀':['长沙', '上海', '深圳']}
'''
# ~ favorite_paces = {
# ~ '张三':['上海','北京','广州'],
# ~ '李四':['九寨沟','张家界','鼓浪屿'],
# ~ '张dk':['长沙', '上海', '深圳'],
# ~ }
# ~ flag = True
# ~ while(flag):
# ~ username = input('请输入名字(q for quit):')
# ~ if username == 'q' or username == 'quit':
# ~ flag = False
# ~ continue
# ~ #break is ok here
# ~ places = favorite_paces[username]
# ~ print(username + ' 喜欢去的地方分别是 '+ '、'.join(places))
'''
第三题:
99乘法表
用for循环打印99乘法表
用while
1x1 =1
1x2 = 2 2x2 = 4
'''
# ~ start_num = 1
# ~ while(start_num <= 9):
# ~ second_num = 1
# ~ while(second_num <= start_num):
# ~ print(str(second_num)+ '*'+str(start_num) +'='+ str(second_num * start_num), end=' ')
# ~ second_num+=1
# ~ start_num+=1
# ~ print('')
for i in range(1, 10):
for j in range(1, i+1):
print('%dX%d=%d'%(j,i,(i*j)), end=' ')
print()
'''
第四题:
1-100的和
1+2+3+4+...+100 = ?
range(1,101)
'''
# ~ total_sum = 0
# ~ for item in range(1,101):
# ~ total_sum += item
# ~ print('1-100的和为'+ str(total_sum))
'''
第五题:
从键盘输入一个字符串,将小写字母全部转换成大写字母,
将字符串以列表的形式输出(如果字符串包含整数,转为整型)?
'''
#todo
# ~ string = input('请输入字符串(q or quit for end):')
# ~ string2 = string.encode('gbk')
# ~ print (string.upper())
# ~ num_string = filter(string.isdigit,string2)
# ~ print (num_string)
|
426b5525fe953b527e13b92f54dec102f545f90d | mneary1/csmatters | /Unit1/inputCheckingStudent.py | 3,570 | 4.40625 | 4 | #This file's purpose is to practice checking inputs and using operators such
#as loops and if statements.
def main():
#Print out welcome
print("Hello there! \n This program will take a number and run it through")
print(" a series of tests.")
#Use getValidInput to get a number
number = getValidInput("Please enter your number.")
#This boolean will be false until the user decides to end the program
done = False
#This loop will keep going until the user indicates the program should end
while not done:
#Print out menu
print("\nPlease pick a choice:\n1. Is Even?\n2. Is positive?")
print("3. Is a factor of 3?\n4.Is a perfect square?\n5. Quit")
#Get input from the user
choice = getValidInput("")
print("")
#These if statements will check the input from the user and run the
#correct tests
if(choice == 5):
#If the user typed 5, they want to quit, so we make our loop end
#by making done true
done = True;
elif(choice == 4):
perfectSquare(number)
elif(choice == 3):
factorOfThree(number)
elif(choice == 2):
isPositive(number)
elif(choice == 1):
isEven(number)
else:
#If the number given was not between one and 5, it will hit this
#else and print the error.
print("Invalid number. Please try again.")
#This function checks if a given input is a number. It will keep asking
#until the user types in a number.
def getValidInput(message):
good = False
#This is very similiar to the while loop above. It will keep going until
#the boolean good is proven true. This happens when a valid input is
#entered
while ######CODE:
#Get input from user. Check if it is a number.
number = input(message)
if(number.isdigit() == True):
#If it is, end the loop
good = True;
else:
#if it is not a number, tell the user
print("That is not a number. Please try again.")
#return the number
return int(number)
#This function checks if the number is even
def isEven (number):
#What makes a number even? Fill in the contents of this if statement
if(##################CODE):
print("It is even")
else:
print("It is odd")
return
#This function checks if the number is positive
def isPositive(number):
#What nmakes a number positive? Fill in the if statement
if(#########CODE):
print("It is positive")
else:
print("It is negative")
return
#This function checks if the number is a multiple of three
def factorOfThree(number):
#This if statement should look a lot like the one in isEven
if(#######CODE):
print("It is divisible by three")
else:
print("It is not divisible by three")
#This function checks if the number is a perfect square
def perfectSquare(number):
#This variable keeps track of the root we are checking
root = 1
#How would we check if a number is a perfect square? Use root to fill
#in the condition for the while loop and if statement
while(######CODE):
if(############CODE):
print("It is a perfect square")
return
#This makes the value of root increase by one
root+=1
print("It is not a perfect square")
return
main()
|
34a36764e1ff6f2dcc120b020b71706033d0e198 | Jaredcscott/Project-Euler | /src/python/prob14.py | 1,028 | 4.03125 | 4 | def even(num):
return num/2
def odd(num):
return (3 * num) + 1
num = 1
longestChain = 0
while num < 1000000:
chain = []
curNum = num
while curNum != 1:
if curNum % 2 == 0:
chain.append(curNum)
curNum = even(curNum)
chain.append(curNum)
else:
chain.append(curNum)
curNum = odd(curNum)
chain.append(curNum)
if len(chain) > longestChain:
print(chain)
print("New highest!: " + str(num)
longestChain = num
print(longestChain)
largestSeq = 0
ansNum = 0
num = 1
while num < 1000000:
curNum = num
chain = []
chain.append(curNum)
while curNum != 1:
if curNum % 2 == 0:
curNum /= 2
chain.append(curNum)
else:
curNum = (curNum * 3) + 1
chain.append(curNum)
#print(curNum)
if len(chain) > largestSeq:
largestSeq = len(chain)
ansNum = num
num += 1
print(ansNum, largestSeq)
|
50c802ca6a97315598e63c67f71f37d482c22274 | oshsage/Python_Pandas | /py4e/CodeUp/1063_Ternary.py | 514 | 3.75 | 4 | # 입력된 두 정수 a, b 중 큰 값을 출력하는 프로그램을 작성해보자.
# 단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.
a, b = input().split(' ')
c = int(a)
d = int(b)
print(c) if c>=d else print(d)
# 새로 알게 된 것: 파이썬은 삼항연산자를 지원하지 않는다.
# [true_value] if [condition] else [false_value] // 파이썬 지원
# if문과 비슷할 수 있겠으나 뒤에 계속 이어붙이는 것이 특징이다.
# ex) bb = 1 if aa == 0 else aa |
9e4a9ba5a5858a854db5795d7ad9fed19c5860e1 | 2morrow-py/Learning-Python | /Seção 6 - Estruturas de Repetição em Python/loop_while.py | 738 | 3.984375 | 4 | """
Loop while
Forma geral
while expressão_booleana:
//execuão do loop
O bloco do while será repetido enquanto a expressão booleana for verdadeira.
Expressão Booleana é toda expressão onde o resultado é verdadeiro ou falso.
Exemplo:
num = 5
num < 5
# Exemplo 1
numero = 1
while numero < 10:
print(numero)
#numero = numero + 1
# OBS: Em um loop while, é importante que cuidemos do critério de parada para não causar um loop infinito.
# C ou Java
while(expressão){
//execução
}
# do while (C ou Java)
do {
//execução
}while(expressão)
"""
# Exemplo 2
resposta = ''
while resposta != 'sim':
resposta = input('Já acabou Jéssica? ')
|
4ba3600eed38439df459e71a27012fa9786bbe99 | cagataybalikci/Python-Password-Generator-App | /main.py | 4,124 | 3.546875 | 4 | from tkinter import messagebox
from tkinter import *
import password_generator
import pyperclip
import json
# CONSTANTS
DARK = "#383e56"
ORANGE = "#fb743e"
# PASS WORD GENERATOR
def generate_password():
gen_password = password_generator.random_password()
password_input.insert(0, gen_password)
pyperclip.copy(gen_password)
messagebox.showinfo(title="Password Generated!",
message="Secure password generated and copy to clipboard for your use. ")
# SAVE PASSWORD
def add():
website_name = website_input.get().title()
email = email_input.get()
password = password_input.get()
new_data = {website_name: {
"email": email,
"password": password,
}}
if len(website_name) == 0 or len(email) == 0 or len(password) == 0:
messagebox.showerror(title="Empty Space", message="You need to fill all boxes.")
else:
try:
with open("data.json", "r") as data_file:
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
data.update(new_data)
with open("data.json", "w") as data_file:
json.dump(data, data_file, indent=4)
finally:
website_input.delete(0, "end")
password_input.delete(0, "end")
def search():
try:
with open("data.json") as data_file:
data = json.load(data_file)
website_name = website_input.get().title()
if len(website_name) != 0:
if website_name in data:
email = data[website_name]["email"]
password = data[website_name]["password"]
messagebox.showinfo(title=website_name,
message=f"Website Name: {website_name}\nEmail : {email}\n "
f"Password : {password}")
else:
messagebox.showerror(title="Not Found!!!",
message=f"No password found related to {website_name}!!!")
else:
messagebox.showerror(title="Empty Input Area!!!",
message="You need to type something to search...")
except FileNotFoundError:
messagebox.showerror(title="No data file found!!",
message="You need to create at least one password to create data "
"file to use search function...")
# UI SETUP
window = Tk()
window.title("Password Manager")
# App Icon
img = Image("photo", file="images/logo.png")
window.call('wm', 'iconphoto', window.w, img)
# Screen setup
window.maxsize(width=500, height=500)
window.minsize(width=500, height=500)
window.config(bg=DARK, padx=20, pady=20)
canvas = Canvas(width=200, height=200, bg=DARK, highlightthickness=0)
bg_image = PhotoImage(file="images/logo.png")
canvas.create_image(128, 128, image=bg_image)
canvas.grid(row=0, column=1)
# Labels
website_label = Label(text="Website Name:", bg=DARK, fg=ORANGE, pady=10)
website_label.grid(row=1, column=0)
email_label = Label(text="Email/Username:", bg=DARK, fg=ORANGE, pady=10)
email_label.grid(row=2, column=0)
password_label = Label(text="Password:", bg=DARK, fg=ORANGE, pady=10)
password_label.grid(row=3, column=0)
# Entries
website_input = Entry(width=21)
website_input.grid(row=1, column=1)
website_input.focus()
email_input = Entry(width=35)
email_input.grid(row=2, column=1, columnspan=2)
email_input.insert(0, "[email protected]")
password_input = Entry(width=21)
password_input.grid(row=3, column=1)
# Buttons
password_generate_button = Button(text="Generate Password", pady=4, command=generate_password)
password_generate_button.grid(row=3, column=2)
add_button = Button(text="Add", width=36, pady=5, command=add)
add_button.grid(row=5, column=1, columnspan=2)
search_button = Button(text="Search", pady=4, padx=39, command=search)
search_button.grid(row=1, column=2)
window.mainloop()
|
fa6a894756b9c81d019dc11c774ddbed82ae24a1 | wechuli/python | /decorators/exercises/ex6_test.py | 694 | 3.890625 | 4 | # Write a function called delay which accepts a time and returns an inner function that accepts a function.When used as a decorator, delay will wait to execute the function being decorated by the amount of time passed into it. Defore starting the timer, delay will also print a message informaing the user that there will be a delay before the decorated function gets run
from time import sleep
from functools import wraps
def delay_execution(fn):
wraps(fn)
def wrapper(*args, **kwargs):
print("Wait for it ...")
sleep(3)
return fn(*args, **kwargs)
return wrapper
@delay_execution
def sum_nums(a, b):
return a + b
print(sum_nums(12, 58))
|
ed2327f14695f1bad68b1db7da44dce0fcf1b5e8 | leandrotominay/pythonaprendizado | /aula07/mediaAluno.py | 332 | 4 | 4 | import math
#Desenvolva um programa que leia as duas notas de um aluno, calcula e mostre a sua média
print("**PROGRAMA QUE LE NOTAS E FAZ A MEDIA**")
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a primeira nota: '))
media = (nota1 + nota2) / 2
print("A media do aluno é igual a {}".format(media))
|
3861c887e367c4c50f2d600d96a984801b85e80b | bhumish/project-euler | /85.py | 327 | 3.5 | 4 | #!/usr/bin/env python
import math
def squares(row,col):
return row* (row+1) * col * (col+1) / 4
topl = 2000000
dist = 2000000
for r in range(1,100):
for c in range(1,100):
temp = squares(r,c)
d = int(math.fabs(topl-temp))
if d<dist:
answer = (r,c)
dist = d
print dist, answer
print "area", answer[0]*answer[1]
|
a969fcec83e35191f18eef942a900e1dfa39ced7 | Parth-Shah-Tool-Kit/complete-python-tutorial | /part3/exercise5.py | 299 | 4.21875 | 4 | '''
Input a name from the user
and then input argument to be searched
print the number of times the argument was present
'''
name = input("Enter your name: ")
arg = input("Enter query to be searched: ")
count = name.count(arg)
print(f"The query {arg} was present {str(count)} times")
|
297874250282427cbf99ae3a7e316205b1f7d23d | bopopescu/education | /chapter 1_begins/enterpret.py | 551 | 3.53125 | 4 | from datetime import datetime
import random
import time
odds = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]
#последовательный вывод с каждой строки
#for i in "123":
#повторение количество раз
for i in range(3):
right_this_minute =datetime.today().minute
if right_this_minute in odds:
print("This minute seems is litle odd.")
else:
print("Not an odd minute")
wait_time = random.randint(1,10)
time.sleep(wait_time) |
5ae52df265ac9cf088b9873b426ba305967d4ecb | osamadel/Python-Online-Courses | /Misc_TestCode/problem_set_1-3.py | 1,240 | 4.09375 | 4 | """
Description :
A program to calculate the credit card balance after one year if a person only pays the minimum monthly payment
required by the credit card company each month.
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
Monthly interest rate= (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
"""
balance = 320000
annualInterestRate = 0.2
monthly_interest_rate = annualInterestRate/12
lower_fixed = balance/12
upper_fixed = balance * (1 + monthly_interest_rate)**12 / 12.0
fixed = 0
unpaid_balance = 0
balance_copy = balance
while True:
balance_copy = balance
fixed = (lower_fixed+upper_fixed)/2
for i in range(12):
# min_monthly_payment = monthlyPaymentRate * balance
unpaid_balance = balance_copy - fixed
balance_copy = unpaid_balance + monthly_interest_rate * unpaid_balance
if balance_copy > 0.01: lower_fixed = fixed
elif balance_copy < 0: upper_fixed = fixed
else: break
print round(fixed,2) |
c17f760d7e87f15da9f00fb9528b8369006ce650 | EdwardJPeng94/Personal-Projects | /Connect Four Draft.py | 11,716 | 3.71875 | 4 | from tkinter import *
import tkinter.messagebox
root = Tk()
root.title('Connect Four')
#------------------------------------variables--------------------------------##
count = 0
moves_o = []
moves_x = []
placement_0 = 6
placement_1 = 6
placement_2 = 6
placement_3 = 6
placement_4 = 6
placement_5 = 6
placement_6 = 6
#functions
##----------------------------function to place moves ----------------------##
def enter(num):
global count
global placement_0
global placement_1
global placement_2
global placement_3
global placement_4
global placement_5
global placement_6
if num == 0:
if count % 2 == 0 and placement_0 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg='red')
move.grid(row = placement_0, column = num)
moves_o.append((placement_0, num))
placement_0 -= 1
count+=1
elif count % 2 != 0 and placement_0 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_0, column = num)
moves_x.append((placement_0, num))
placement_0 -= 1
count+=1
if num == 1:
if count % 2 == 0 and placement_1 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg ='red')
move.grid(row = placement_1, column = num)
moves_o.append((placement_1, num))
placement_1 -= 1
count+=1
elif count % 2 != 0 and placement_1 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg ='blue')
move.grid(row = placement_1, column = num)
moves_x.append((placement_1, num))
placement_1 -= 1
count+=1
if num == 2:
if count % 2 == 0 and placement_2 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg='red')
move.grid(row = placement_2, column = num)
moves_o.append((placement_2, num))
placement_2 -= 1
count+=1
elif count % 2 != 0 and placement_2 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_2, column = num)
moves_x.append((placement_2, num))
placement_2 -= 1
count+=1
if num == 3:
if count % 2 == 0 and placement_3 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg = 'red')
move.grid(row = placement_3, column = num)
moves_o.append((placement_3, num))
placement_3 -= 1
count+=1
elif count % 2 != 0 and placement_3 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_3, column = num)
moves_x.append((placement_3, num))
placement_3 -= 1
count+=1
if num == 4:
if count % 2 == 0 and placement_4 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg='red')
move.grid(row = placement_4, column = num)
moves_o.append((placement_4, num))
placement_4 -= 1
count+=1
elif count % 2 != 0 and placement_4 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_4, column = num)
moves_x.append((placement_4, num))
placement_4 -= 1
count+=1
if num == 5:
if count % 2 == 0 and placement_5 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg ='red')
move.grid(row = placement_5, column = num)
moves_o.append((placement_5, num))
placement_5 -= 1
count+=1
elif count % 2 != 0 and placement_5 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_5, column = num)
moves_x.append((placement_5, num))
placement_5 -= 1
count+=1
if num == 6:
if count % 2 == 0 and placement_6 > 0:
move = Button(root, text = 'O', height = 5, width = 10, fg ='red')
move.grid(row = placement_6, column = num)
moves_o.append((placement_6, num))
placement_6 -= 1
count+=1
elif count % 2 != 0 and placement_6 > 0:
move = Button(root, text = 'X', height = 5, width = 10, fg='blue')
move.grid(row = placement_6, column = num)
moves_x.append((placement_6, num))
placement_6 -= 1
count+=1
print('moves_o:', moves_o)
print('moves_x:', moves_x)
if count % 2 == 0:
win_x()
else:
win_o()
##------------------------- o wins--------------------------------------------##
def win_o():
horizontal_win_1 = []
horizontal_win_2 = []
horizontal_win_3 = []
horizontal_win_4 = []
vertical_win = []
#horizontal wins 1
for r in range(moves_o[-1][1] - 3, moves_o[-1][1]+1):
horizontal_win_1.append((moves_o[-1][0], r))
check = all(move in moves_o for move in horizontal_win_1)
if check is True:
print('O wins 1')
tkinter.messagebox.showinfo('Winner:','O Wins Horizontally!!!')
#horizontal wins 2
for r in range(moves_o[-1][1] - 2, moves_o[-1][1] + 2):
horizontal_win_2.append((moves_o[-1][0], r))
check = all(move in moves_o for move in horizontal_win_2)
if check is True:
print('O wins 2')
tkinter.messagebox.showinfo('Winner:','O Wins Horizontally!!!')
#horizontal wins 3
for r in range(moves_o[-1][1] - 1, moves_o[-1][1] + 3):
horizontal_win_3.append((moves_o[-1][0], r))
check = all(move in moves_o for move in horizontal_win_3)
if check is True:
print('O wins 3')
tkinter.messagebox.showinfo('Winner:','O Wins Horizontally!!!')
#horizontal wins 4
for r in range(moves_o[-1][1], moves_o[-1][1] + 4):
horizontal_win_4.append((moves_o[-1][0], r))
check = all(move in moves_o for move in horizontal_win_4)
if check is True:
print('O wins 4')
tkinter.messagebox.showinfo('Winner:','O Wins Horizontally!!!')
#vertical wins
for c in range(moves_o[-1][0], moves_o[-1][0] + 4):
vertical_win.append((c, moves_o[-1][1]))
check = all(move in moves_o for move in vertical_win)
if check is True:
print('O wins vertical')
tkinter.messagebox.showinfo('Winner:','O Wins Vertically!!!')
#positive diagonals
#negative diagonals
########### ---------------------- x wins --------------------------------------
def win_x():
horizontal_win_1 = []
horizontal_win_2 = []
horizontal_win_3 = []
horizontal_win_4 = []
vertical_win = []
positive_win = []
#horizontal wins 1
for r in range(moves_x[-1][1] - 3, moves_x[-1][1]+1):
horizontal_win_1.append((moves_x[-1][0], r))
check = all(move in moves_x for move in horizontal_win_1)
if check is True:
print('X wins 1')
tkinter.messagebox.showinfo('Winner:','X Wins Horizontally!!!')
#horizontal wins 2
for r in range(moves_x[-1][1] - 2, moves_x[-1][1] + 2):
horizontal_win_2.append((moves_x[-1][0], r))
check = all(move in moves_x for move in horizontal_win_2)
if check is True:
print('O wins 2')
tkinter.messagebox.showinfo('Winner:','X Wins Horizontally!!!')
#horizontal wins 3
for r in range(moves_x[-1][1] - 1, moves_x[-1][1] + 3):
horizontal_win_3.append((moves_x[-1][0], r))
print('horizontal moves:', horizontal_win_3)
check = all(move in moves_x for move in horizontal_win_3)
if check is True:
print('O wins 3')
tkinter.messagebox.showinfo('Winner:','X Wins Horizontally!!!')
#horizontal wins 4
for r in range(moves_x[-1][1], moves_x[-1][1] + 4):
horizontal_win_4.append((moves_x[-1][0], r))
check = all(move in moves_x for move in horizontal_win_4)
if check is True:
print('O wins 4')
tkinter.messagebox.showinfo('Winner:','X Wins Horizontally!!!')
#veritcal wins
for c in range(moves_x[-1][0], moves_x[-1][0] + 4):
vertical_win.append((c, moves_x[-1][1]))
check = all(move in moves_x for move in vertical_win)
if check is True:
print('X wins vertical')
tkinter.messagebox.showinfo('Winner:','X Wins Vertically!!!')
#positive diagonals
for r in range(moves_x[-1][0] + 3, moves_x[-1][0] - 1, -1):
for c in range(moves_x[-1][1] - 3, moves_x[-1][1] + 1):
positive_win.append((r,c))
print('positive win:',positive_win)
check = all(move in moves_x for move in positive_win)
if check is True:
print('X wins diagonal')
tkinter.messagebox.showinfo('Winner:','X Wins Diagonally!!!')
#negative diagonals
####--------------------------------buttons ---------------------------------###
#buttons
for c in range(0,7):
if c == 0:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(0))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 1:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(1))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 2:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(2))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 3:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(3))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 4:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(4))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 5:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(5))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
if c == 6:
for r in range(0,7):
if r == 0:
entry = Button(root, text = 'Press', height = 5, width = 10, command = lambda: enter(6))
entry.grid(row = r, column = c)
else:
blank = Button(root, text = r, height = 5, width = 10)
blank.grid(row = r, column = c)
root.mainloop()
|
21cfa43f700c71ada3697a3c8524a4711ce2a3e1 | naddleman/aoc2018 | /day06-chronal.py | 2,656 | 3.65625 | 4 | """
https://adventofcode.com/2018/day/6
given a list of points
find the area of the largest finite set of coordinates closest to some point
Theorem: The area V(p) is infinite if p is on the boundary of the convex hull
"""
import numpy as np
TEST_INPUT = """1, 1
1, 6
8, 3
3, 4
5, 5
8, 9"""
def from_coord(coord: str):
x, y = [int(a) for a in coord.split(", ")]
return (x,y)
def manhattan(pt1, pt2):
return abs(pt1[0] - pt2[0]) + abs(pt1[1] - pt2[1])
def edges(points):
xs = [pt[0] for pt in points]
ys = [pt[1] for pt in points]
return (min(xs), min(ys), max(xs), max(ys))
def makegrid2(points):
(height, width) = (edges(points)[3] + 5,edges(points)[2] + 5)
grid = np.zeros((height, width), dtype=np.uint8)
for i in range(len(points)):
pt = points[i]
grid[pt[1] + 2, pt[0] + 2] += i + 1
return grid, height, width
def assign_areas(points):
grid, height, width= makegrid2(points)
print(grid.shape)
step = 0
for (x,y), value in np.ndenumerate(grid):
if step % 10000 == 0:
print(step)
step += 1
distances = []
for i in range(len(points)):
pt = points[i]
distances.append(manhattan((x,y), (pt[0], pt[1])))
nearest = [i for i, v in enumerate(distances) if v == min(distances)]
if len(nearest) == 1:
grid[x,y] = nearest[0] + 1
unique, counts = np.unique(grid, return_counts=True)
infinites = set()
infinites = infinites.union(set(np.unique(grid[0])))
infinites = infinites.union(set(np.unique(grid[-1])))
infinites = infinites.union(set(np.unique(grid[:, 0])))
infinites = infinites.union(set(np.unique(grid[:, -1])))
areas = []
for i in range(1, len(points) + 1):
if i not in infinites:
areas.append(counts[i])
return max(areas)
TEST_POINTS = [from_coord(coord) for coord in TEST_INPUT.split("\n")]
assert assign_areas(TEST_POINTS) == 17
def total_dist(points, dist_limit):
grid, height, width= makegrid2(points)
close_enough = 0
step = 0
for (x,y), value in np.ndenumerate(grid):
if step % 10000 == 0:
print(step)
step += 1
total_dist = 0
for pt in points:
total_dist += manhattan((x,y), (pt[0], pt[1]))
if total_dist < dist_limit:
close_enough += 1
return close_enough
assert total_dist(TEST_POINTS, 32) == 16
file = 'data/day06_input.txt'
with open(file) as f:
ins = f.read().rstrip('\n')
points = [from_coord(coord) for coord in ins.split('\n')]
#print(assign_areas(points))
print(total_dist(points, 10000))
|
77b561320c697c35aea4afb3461f80a4ac40a82e | lastz/lastz | /tools.python2/maf_sort.py | 4,401 | 3.515625 | 4 | #!/usr/bin/env python
"""
Sort alignment blocks in a maf file, according to the user's choice of key
--------------------------------------------------------------------------
:Author: Bob Harris ([email protected])
"""
import sys,re
validKeys = ["score","pos1","pos2","beg1","beg2","end1","end2","diag","name1","name2"]
def usage(s=None):
message = """
maf_sort --key=[-]<score|beg1|beg2|end1|end2|diag|name1|name2> < maf_file > maf_file
"""
if (s == None): sys.exit (message)
else: sys.exit ("%s\n%s" % (s,message))
def main():
# parse the command line
if (len(sys.argv) < 2):
usage("you must specify a key")
elif (len(sys.argv) > 2):
usage("wrong number of arguments")
arg = sys.argv[1]
if (not arg.startswith("--key=")):
usage("unrecognized argument: \"%s\"" % arg)
keyName = arg[arg.find("=")+1:]
keyReverse = False
if (keyName.startswith("-")):
keyName = keyName[1:]
keyReverse = True
if (keyName.startswith("+")):
keyName = keyName[1:]
keyReverse = False
if (keyName not in validKeys):
usage("unrecognized key: \"%s\"" % keyName)
# process the blocks
blocks = []
for (block,comments) in read_blocks(sys.stdin):
key = get_key_value(keyName,block)
blocks += [(key,block,comments)]
if (len(blocks) > 0):
blocks.sort()
if (keyReverse): blocks.reverse()
for (key,block,comments) in blocks:
if (comments != []):
print ("\n".join([line for line in comments]))
print ("\n".join([line for line in block]))
print ("")
# read_blocks--
# Collect the lines that belong to the next alignment block. A block has the
# form shown below.
#
# a score=19951
# s apple 23871 367 + 70000 CCCCCGC...
# s orange 13 390 - 408 CTCCTGC...
def read_blocks(f):
comments = []
block = []
lineNumber = 0
for line in f:
lineNumber += 1
line = line.rstrip()
if (line.startswith("#")):
comments += [line]
continue
if (line == ""):
if (len(block) == 3):
yield (block,comments)
comments = []
block = []
continue
elif (len(block) == 0):
continue
else:
assert (False), "premature end of block at line %d" % lineNumber
if (len(block) == 3): "long block at line %d" % lineNumber
block += [line]
if (len(block) == 3):
yield (block,comments)
elif (len(block) != 0):
assert (False), "premature end of file"
# get_key_value--
# Extract the specied key value from a maf block
#
# a score=19951
# s apple 23871 367 + 70000 CCCCCGC...
# s orange 13 390 - 408 CTCCTGC...
scoreRe = re.compile("^a score=(?P<score>.+)$")
textRe = re.compile("^s"
+ " +(?P<name>[^ ]+)"
+ " +(?P<pos>[0-9]+)"
+ " +(?P<len>[0-9]+)"
+ " +(?P<strand>[-+])"
+ " +[0-9]+"
+ " +[-ACGTacgtNn]+$")
def get_key_value(keyName,block):
try:
line = block[0]
m = scoreRe.match(line)
if (m == None): raise ValueError
score = float(m.group("score"))
except ValueError:
assert (False), "bad score line: %s" % line
try:
line = block[1]
m = textRe.match(line)
if (m == None): raise ValueError
name1 = m.group("name")
pos1 = int(m.group("pos"))
len1 = int(m.group("len"))
strand1 = m.group("strand")
except ValueError:
assert (False), "bad line: %s" % line
try:
line = block[2]
m = textRe.match(line)
if (m == None): raise ValueError
name2 = m.group("name")
pos2 = int(m.group("pos"))
len2 = int(m.group("len"))
strand2 = m.group("strand")
except ValueError:
assert (False), "bad line: %s" % line
if (keyName == "score"):
return (score,pos1,strand1,pos2,strand2,len1,len2,name1,name2)
if (keyName in ["pos1","beg1"]):
return (pos1,strand1,pos2,strand2,len1,len2,score,name1,name2)
if (keyName in ["pos2","beg2"]):
return (pos2,strand2,pos1,strand1,len2,len1,score,name1,name2)
if (keyName in ["end1"]):
return (pos1+len1,strand1,pos2+len2,strand2,len1,len2,score,name1,name2)
if (keyName in ["end2"]):
return (pos2+len2,strand2,pos1+len1,strand1,len2,len1,score,name1,name2)
if (keyName in ["diag"]):
return (strand1,strand2,pos1-pos2,pos1,len1,len2,score,name1,name2)
if (keyName in ["name1"]):
return (name1,score,len1,strand1,pos1,name2,len2,strand2,pos2)
if (keyName in ["name2"]):
return (name2,score,len2,strand2,pos2,name1,len1,strand1,pos1)
assert False
if __name__ == "__main__": main()
|
59ed88c230cb05f940deef27643a942f4b7952c2 | LiudaShevliuk/python | /lab4_1.py | 256 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
a = float(input('Enter positive number: '))
b = float(input('Enter one more positive number that greater than 0: '))
x = math.sqrt(a * b) / (math.exp(a) * b) + a* math.exp(2 * a / b)
print(x)
|
f0902857df6d09d947b2f22f82f21cfaac4f61cb | SLEDAssessment/shop | /shop.py | 969 | 3.8125 | 4 | from stock import Stock
print (" M A I N - M E N U")
print ("1. Create Customer")
print ("2. View Customers")
print ("3. Action 3")
print ("4. Action 4")
print ("5. Action 5")
while True:
# Get user input:
choice = input('Enter a choice from the menu [1-5] : ')
# Convert input (number) to int type:
choice = int(choice)
if choice == 1:
print("Create Customer...")
elif choice == 2:
print ("Action 2...")
#processing #2 is done here
elif choice == 3:
print ("Action 3...")
#processing #3 is done here
elif choice == 4:
print ("Create Stock")
Stock.create_Stock()
elif choice == 5:
print ("Action 5...")
#processing #5 is done here
else:
print ("Invalid entry. You should choose 1-5 only. Program exiting.....please restart it and try again.")
# Add sys.exit() (will have to add 'import sys' to top
|
8366cc24b51dd932638772dce320e2c2e0ff0dbb | KumarLokesh15/Model-Deployment | /salary.py | 514 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def salary_exp_pred(exp):
df = pd.read_csv('Salary_Data-1.csv')
x = df.iloc[:,0]
y = df.iloc[:,1]
x = x.values
y = y.values
model = LinearRegression()
x_new = x.reshape(-1,1)
y_new = y.reshape(-1,1)
model.fit(x_new,y_new)
x_test = np.array(exp)
x_test = x_test.reshape((1,-1))
return model.predict(x_test)[0][0]
|
b4013fda23af65683ac8e99c2817badf559cb5c4 | Hugomguima/FEUP | /1st_Year/1st_Semestre/Mnum/Exame/Exame 2014/Pergunta7.py | 257 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 16:25:25 2020
@author: Hugo
"""
f = lambda x : x**4-4*x**3+x-3
g = lambda x : (4*x**3-x+3)**(1/4)
def picard(x):
for i in range(3):
print(x)
x = g(x)
picard(3.5) |
7ed232a59607d87aceecc6ad8f8b95278e01a8ca | RyanIsBored/unit-3 | /squares.py | 115 | 3.78125 | 4 | #Ryan Jones
#2/26/18
#squares.py
num = int(input('Enter a number: '))
for i in range(0,(num)):
print((i+1)*(i+1)) |
dc1c456f30dd01d71a3f18e1f05f64ea95b9e1d0 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/59/tables.py | 1,336 | 4.0625 | 4 | #
# c_ MultiplicationTable
#
# ___ - length
# """Create a 2D self._table of (x, y) coordinates and
# their calculations (form of caching)"""
# _length ?
# _table # list
# ___ i __ r.. 1 ? +1
# row # list
# ?.a.. ?
#
# j 1
# current i
# w.... ? < _?
# ? +_ ?
# ?.a.. c..
# ? +_ 1
# _?.a.. ?
#
# ___ -l
# """Returns the area of the table (len x* len y)"""
# _area ? * ?
# r.. ?
#
# ___ -s
# """Returns a string representation of the table"""
# _table_output ""
# ___ row __ _table
# table_row ""
# ___ ele __ r.. |l.. r.. -1
# t.. +_ _*? | "
# t.. +_ _? r.. -1
# _? +_ _* ?\n
# r.. ?
#
# ___ calc_cell x y
# """Takes x and y coords and returns the re-calculated result"""
# _x ?
# _y ?
#
# __ ? > _l.. o. ? > _l..
# r.. I..
# ____
# _result ? * ?
# r.. ?
#
#
# # if __name__ == "__main__":
# # table = MultiplicationTable(4)
# # print(table._table)
# # print(table.__len__())
# # print(table.__str__())
# # print(table.calc_cell(4, 3)) |
892a5ed8857652a2a54ab6a17b6dc8f689147717 | privateOmega/coding101 | /clap/nth-fibanocci.py | 609 | 3.78125 | 4 | def fibanocci_doubling(number):
if number == 0:
return (0, 1)
else:
a, b = fibanocci_doubling(number >> 1)
c = a * ((b << 1) - a)
d = a * a + b * b
if number & 1:
return (d, c + d)
else:
return (c, d)
def main():
noOfTestCases = int(input())
testCases = []
if noOfTestCases < 1:
return
for iterator in range(noOfTestCases):
testCases.append(int(input()))
for iterator in range(noOfTestCases):
print(fibanocci_doubling(testCases[iterator])[1])
if __name__ == '__main__':
main()
|
fddd856d0b857bcc47902377158e82bd145c5d1c | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/dsrkir001/util.py | 1,505 | 3.625 | 4 |
#A module of utility functions to manipulate 2-dimensional arrays
#27 April 2014
#Kiran Desraj
#import function to be used when copying the grid
import copy
#create a 4x4 grid :
def create_grid(grid):
for i in range (4):
grid.append ([0]*4)
return grid
#print out a 4x4 grid in 5-width columns within a box :
def print_grid (grid):
print("+","-"*20,"+",sep="")
for i in grid:
print('|', end='')
for j in i:
j = str(j)
if j == '0':
print(' '.ljust(5), end = '')
else:
print(j.ljust(5),end = '')
print('|')
print("+","-"*20,"+",sep="")
# no zeros and no matching values next to each other
def check_lost (grid):
for i in range(len(grid)-1):
for j in range(len(grid[i])-1):
if grid[i][j] == 0:
return False
elif grid[i][j] == grid[i][j+1]:
return False
elif grid[i][j] == grid[i+1][j]:
return False
return True
#check if there is a value=>32
def check_won (grid):
for i in range(4):
for j in range(4):
if grid[i][j]>= 32:
return True
return False
#f return a copy of the grid :
def copy_grid (grid):
grid2 = copy.deepcopy(grid)
return grid2
#check whether every term in grids are equal:
def grid_equal (grid1, grid2):
if grid1==grid2:
return True
else:
return False |
26c8497323e31c5e4453258b6c7dbd498bb5e9f5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/940.py | 1,605 | 3.71875 | 4 | def checkline(line):
if (line[0]=='X' or line[0]=='T') and (line[1]=='X' or line[1]=='T') \
and (line[2]=='X' or line[2]=='T') and (line[3]=='X' or line[3]=='T'):
return 'X won'
if (line[0]=='O' or line[0]=='T') and (line[1]=='O' or line[1]=='T') \
and (line[2]=='O' or line[2]=='T') and (line[3]=='O' or line[3]=='T'):
return 'O won'
def solve():
first = f.readline()
second = f.readline()
third = f.readline()
fourth = f.readline()
f.readline()
x=checkline(first)
if x:
return x
x=checkline(second)
if x:
return x
x=checkline(third)
if x:
return x
x=checkline(fourth)
if x:
return x
x=checkline([first[0],second[0],third[0],fourth[0]])
if x:
return x
x=checkline([first[1],second[1],third[1],fourth[1]])
if x:
return x
x=checkline([first[2],second[2],third[2],fourth[2]])
if x:
return x
x=checkline([first[3],second[3],third[3],fourth[3]])
if x:
return x
x=checkline([first[0],second[1],third[2],fourth[3]])
if x:
return x
x=checkline([first[3],second[2],third[1],fourth[0]])
if x:
return x
if '.' in first or '.' in second or '.' in third or '.' in fourth:
return 'Game has not completed'
else:
return 'Draw'
with open('A-large.in','r') as f:
o = open('A-large.out','w')
for z in range(int(f.readline())):
output = 'Case #'+str(z+1)+': '+solve()+'\n'
o.write(output)
o.close()
|
eb718a6b30964893f08aa2eaa03f828ecfcf312b | 353solutions/353bytes | /ml/bool-index/snail.py | 520 | 3.625 | 4 | """
Draw a green (color=[0, 0xFF, 0]) square on the snail image
- line width=5
- top left: (217, 42)
- bottom right: (525, 275)
"""
import matplotlib.pyplot as plt
img = plt.imread('snail.jpg').copy()
plt.imshow(img)
tl_x, tl_y = 217, 42 # x = row, y = column
br_x, br_y = 525, 275
width = 5
color = [0, 0xFF, 0] # green
img[tl_x:tl_x+width, tl_y:br_y] = color
img[br_x:br_x+width, tl_y:br_y] = color
img[tl_x:br_x, tl_y:tl_y+width] = color
img[tl_x:br_x, br_y:br_y+width] = color
plt.imshow(img)
plt.show()
|
712a7429a3f821993e2bdf298d0ba206c52df8ab | 0verlo/python_playground | /sumtest.py | 232 | 3.953125 | 4 | #!/usr/bin/env python
# coding=utf-8
def calc_sum(*numbers):
sum = 0
for value in numbers:
sum = sum + value
return sum
sum = 0
for x in list(range(11)):
sum = sum + x
print(sum)
print(calc_sum(1,2,3,4,5))
|
0499a60f0aa47df52aae2c12e8981dfbcaa9a24c | Urobs/daily-coding-problem | /problem12/index.py | 260 | 3.609375 | 4 | def count_unique_climb_ways(distance, steps):
count = 0
for step in steps:
if distance - step == 0:
count += 1
elif distance - step > 0:
count += count_unique_climb_ways(distance - step, steps)
return count |
a7a99791590c5172ddc0db67bccac7ebe495cd12 | phamd1989/Algorithms | /Inversions.py | 1,183 | 3.5625 | 4 | import sys
def inversionList(arr):
size = len(arr)
if (size == 1):
return arr
low_arr = arr[0:size/2]
high_arr = arr[size/2:size]
return mergeAndCount(inversionList(low_arr), inversionList(high_arr))
def mergeAndCount(low_arr, high_arr):
global count
combined_arr = []
l = len(low_arr)
r = len(high_arr)
i, j = 0, 0
while(i<l and j<r):
if (low_arr[i] < high_arr[j]):
combined_arr.append(low_arr[i])
i = i + 1
else:
combined_arr.append(high_arr[j])
j += 1
count += l - i
while(i<l):
combined_arr.append(low_arr[i])
i += 1
while(j<r):
combined_arr.append(high_arr[j])
j += 1
return combined_arr
def readInput():
inputArray = []
inFile = sys.argv[1]
try:
myInput = open(inFile, 'r')
while (True):
num = myInput.readline().strip()
if (len(num) == 0):
break
inputArray.append(int(num))
finally:
myInput.close()
return inputArray
count = 0
inputArr = readInput()
#print inputArr
inversionList(inputArr)
print count
|
ec560397c393da2d8edef59287b535d1327e2879 | herbertguoqi/drivercommend | /logic/recommend.py | 769 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#抽象类加抽象方法就等于面向对象编程中的接口
from abc import ABCMeta,abstractmethod
class recommend(object):
__metaclass__ = ABCMeta #指定这是一个抽象类
@abstractmethod #抽象方法
def Lee(self):
pass
def Marlon(self):
pass
class recommendImplDB(recommend):
def __init__(self):
print ('DB interface')
def Lee(self):
print ('DB Lee')
def Marlon(self):
print ("DB Marlon")
class recommendImplSrc(recommend):
def __init__(self):
print ('Src interface')
def Lee(self):
print ('Src Lee')
def Marlon(self):
print ("Src Marlon")
a=recommendImplSrc()
a.Lee()
a.Marlon() |
fbb45074da49dea11e3d77b207797cbc960e2fdc | CHALASS770/WOG | /live.py | 3,069 | 3.953125 | 4 | from GuessGame import *
from time import sleep
from MemoryGame import *
from CurrencyRouletteGame import *
def welcome(name):
print("Hello %s ! Welcome in World of Game!!! "% name)
print("Here you can find many cool games to play ")
def load_game():
valideplay = True
while valideplay == True:
try :
play=int(input("Please choose a game to play: \n 1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back \n 2. Guess Game - guess a number and see if you chose like the computer \n 3. Weather Roulette - Guess the current temperature currently in Jerusalem \n"))
if 1 <= play <= 3 :
valideplay = False
else:
raise ValueError("your choice is invalide")
except ValueError:
print("****please enter a valid value ****** \n ********************* \n")
validedif = True
while validedif == True:
try :
difficult = int(input("choose a dificult betwin 1 and 5 \n "))
if 1 <= difficult <=5 :
validedif = False
else :
raise ValueError("your choice is invalide")
except ValueError:
print("****please enter a valid value**** \n ********************\n")
if play == 1 :
print("you choose to play to Memory Game")
elif play == 2:
print("you choose to play to Guess Game")
elif play == 3:
print("you choose to play to Weather Roulette")
if difficult == 1 :
print("difficult is easy")
elif difficult == 2:
print("difficult is easy plus")
elif difficult == 3:
print("difficult is hard")
elif difficult == 4:
print("difficult is hard plus")
elif difficult == 5:
print("difficult is very Hard")
return play, difficult
def play_game(playGame, level):
sleep(3)
if playGame == 2:
for i in range(20):
print('')
print('**************************************')
print('***** WELCOME TO THE GUESS GAME ******')
print('**************************************')
for i in range(3):
print('')
game = GuessGame()
game.generat_number(level)
game.compare_result()
elif playGame == 1:
for i in range(20):
print('')
print('**************************************')
print('***** WELCOME TO THE MEMORY GAME ******')
print('**************************************')
for i in range(3):
print('')
game = MemoryGame(level)
game.play()
elif playGame == 3:
for i in range(20):
print('')
print('**************************************')
print('***** WELCOME TO THE ROULETTE GAME ******')
print('**************************************')
for i in range(3):
print('')
game = CurrencyRouletteGame(level)
game.play() |
0b5e933e23d5226d910ea953eda6009c01e4c1fd | m-baez/platzi-retos_semana3 | /reto1.py | 386 | 3.84375 | 4 | # Reto #1 Longitud del string
"""Pide a tu usuario que ingrese el nombre de su curso favorito, obtén la longitud de ese string y muéstralo en pantalla."""
def main():
print('-'*60)
curse = str(input('Ingresa el nombre de tu curso favorito: ').__len__())
print('\nEsta es la longitud de caracteres: %s' % curse)
print('-'*60)
if __name__ == '__main__':
main()
|
cd13a24b5b3a31f7c138bea9ed2b5ac08e4cb9cd | jlc175/For_Offer-Python3 | /数据结构/数组/3.数组中重复的数字/题目一/FindDuplicateEdit.py | 965 | 3.734375 | 4 | def duplicate(nums):
# 判断是否输入了[0,n-1]以外的数字
for num in nums:
if num < 0 or num > len(nums) - 1:
return False
# 从头遍历数组
for i in range(len(nums)):
# 当前位置的数字不在它应该的位置
while nums[i] != i:
# 如果当前位置的数字与它应该在的位置的数字相同,则找到了一对相同的数字
if nums[i] == nums[nums[i]]:
return nums[i]
# 将当前数字放到它应该在的位置
temp = nums[nums[i]]
nums[nums[i]] = nums[i]
nums[i] = temp
# 未找到相同的数字
return False
if __name__ == '__main__':
case1 = [2, 1, 3, 4, 3, 5]
case2 = [2, 2, 3, 4, 3, 5]
case3 = []
print('一个重复元素的情况', duplicate(case1))
print('多个重复元素的情况', duplicate(case2))
print('无元素的情况', duplicate(case3))
|
731387ce57aabc297c84fecec52234b9e1fe2829 | TonyHoanTrinh/MathVisualizations | /fractalsimaging/fractalsimaging.py | 2,762 | 4.0625 | 4 | '''
Import the libarires to get access to mathematical functions and imaging
'''
import numpy
from numba import jit
import matplotlib.pyplot as plt
'''
The Mandelbrot Set:
For us define this as the set of complex numbers c such that when c are equated into the formula fc = z^2 + c, the formula was not
diverge pass a distance of 2 from the origin of the complex plane. z0 = 0. The complex number with the formula a + bi, where
a is the real part which is represented on the x axis of the complex plane. And b is the imaginary part which is represented on the
y axis of the complex plain. If the complex number c when using the formula does not diverge is it colored black otherwise it is colored
based on the speed in which it grows.
'''
'''
We defined our function which takes in the max number of iterations until we stop, the real part and imaginary part of the complex number
'''
@jit
def mandelbrot (maxIterations, realPart, imagPart):
'''We set our c in the formula as the arguments taken from the function when called'''
c = complex(realPart, imagPart)
'''Set z as our 0'''
z = 0.0j
''' We iterate to the max number of iterations we want'''
for i in range(maxIterations):
''' We do the arithmetic for the formula '''
z = z * z + c
'''
We check if the magnitude(modulus) of our current point is greater than a distance of 2 from the original point
If so we break out of the loop and function
'''
if(z.real * z.real + z.imag * z.imag) >= 2:
return 1
return maxIterations
'''
We define our size and we create an array of zeros using numpy.zeros
'''
rowSize = 2000
columnSize = 2000
result = numpy.zeros([rowSize, columnSize])
'''
Row is our real axis and column is our imaginary axis of the complex place, here we enumerate the spacing of the graph,
Then we call in the mandelbrot function
'''
for row_index, realPart in enumerate(numpy.linspace(-2, 1, num = rowSize)):
for column_index, imagPart in enumerate(numpy.linspace(-2,1, num = columnSize)):
result[row_index, column_index] = mandelbrot(300, realPart, imagPart)
'''
Set parameters and labels of the graphical representation
'''
plt.figure(dpi = 100)
plt.imshow(result.T, cmap = 'hot', interpolation = 'nearest', extent = [-2,1,-1,1])
plt.xlabel("Real Axis")
plt.ylabel("Imaginary Axis")
plt.show()
'''
Additional features that could be implemented are the Julia set, Newton Fractal, Sierpinski, Koch and various other fractals than the
standard Mandelbrot set. Another point of interest may be to try and expand by using different methods and libraries (Specifically
Turtle) to generate a Mandelbrot set. Potential for expanding on this mini side project in the future.
''' |
a503d5c05d9af595b921725f90caf0644870acbc | DavidWellsTheDeveloper/DailyCodingChallenge | /Problem #28 [Medium].py | 2,123 | 4.125 | 4 | # Good morning! Here's your coding interview problem for today.
# This problem was asked by Palantir.
# Write an algorithm to justify text. Given a sequence of words and an integer line
# length k, return a list of strings which represents each line, fully justified.
# More specifically, you should have as many words as possible in each line. There
# should be at least one space between each word. Pad extra spaces when necessary so
# that each line has exactly length k. Spaces should be distributed as equally as
# possible, with the extra spaces, if any, distributed starting from the left.
# If you can only fit one word on a line, then you should pad the right-hand side with spaces.
# Each word is guaranteed not to be longer than k.
# For example, given the list of words
# ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
# and k = 16, you should return the following:
# ["the quick brown", # 1 extra space on the left
# "fox jumps over", # 2 extra spaces distributed evenly
# "the lazy dog"] # 4 extra spaces distributed evenly
if __name__ == '__main__':
k = 16
items = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
# space_characters = number_of_words - 1
evenResponse = []
number_of_words = 0
current_word_length = 0
current_index = 0
while current_index < len(items):
working_string = []
while len(items) > current_index and (number_of_words-1) + current_word_length + len(items[current_index]) <= k:
working_string.append(items[current_index])
current_word_length += len(items[current_index])
number_of_words += 1
current_index += 1
spaces_to_add = k - current_word_length
extras = 0
for i in range(0, spaces_to_add):
working_string[i % (number_of_words-1)] += " "
if i >= (number_of_words-1):
extras += 1
print(''.join(working_string) + " # " + str(extras) + " extra spaces")
evenResponse.append(working_string)
number_of_words = 0
current_word_length = 0
|
0c059e1437dbb659eb0fc8bdeeac9e5f299eaed8 | rrabit42/Python-Programming | /Python프로그래밍및실습/ch5-function/lab5-13.py | 223 | 4.0625 | 4 | def findMax(list) :
max = list[0]
for i in range (1, len(list)) :
if max < list[i] :
max = list[i]
return max
numbers = [5, 2, 9, 8, 1, 4, 7, 3, 6]
max = findMax(numbers)
print(max) |
5c65395313abe7d17b5328c12a52cff83d68aeec | daparthi001/python | /Module2/Commands9.py | 605 | 3.828125 | 4 |
# # cmp() - This method returns -1 if x < y, returns 0 if x == y and 1 if x > y
#
# print "cmp(80, 100) : ", cmp(80, 100)
# print "cmp(180, 100) : ", cmp(180, 100)
# print "cmp(100, 100) : ", cmp(100, 100)
# print "cmp(80, -100) : ", cmp(80, -100)
#
# #max()
# arr = [2,3,5,7,9,11]
# print "Max value :: %d"%max(arr)
# print "Min value :: %d"%min(arr)
#
# # List to Tuple
# # A tuple is a sequence of immutable Python objects.
arr = [2,3,5,7,9,11]
t = tuple(arr)
print t
# Tuple to List
print list(t)
#Enumerate
enumerate_t = tuple(enumerate(t))
print enumerate_t
# # Xrange is deprecated
|
c6c8d001b1bbaa2c044c178f08a8d9c6e408a1b9 | heliormarques/labprog2019.2 | /dijkstra.py | 1,435 | 3.578125 | 4 | inf = float("inf");
vetor = {};
vetor['a'] = {};
vetor['a']['b'] = 6;
vetor['a']['d'] = 1;
vetor['b'] = {}
vetor['b']['d'] = 2;
vetor['b']['e'] = 2;
vetor['b']['c'] = 5;
vetor['c'] = {};
vetor['c']['e'] = 5;
vetor['d'] = {};
vetor['d']['e'] = 1;
vetor['e'] = {};
def dijkstra(vetor, start, finish):
menorCaminho = {}
anterior = {}
naoVisto = vetor
infinity = inf
path = []
for node in naoVisto:
menorCaminho[node] = infinity
menorCaminho[start] = 0
while naoVisto:
minNode = None
for node in naoVisto:
if minNode is None:
minNode = node
elif menorCaminho[node] < menorCaminho[minNode]:
minNode = node
for cam, distance in vetor[minNode].items():
if distance + menorCaminho[minNode] < menorCaminho[cam]:
menorCaminho[cam] = distance + menorCaminho[minNode]
anterior[cam] = minNode
naoVisto.pop(minNode)
currentNode = finish
while currentNode != start:
try:
path.insert(0,currentNode)
currentNode = anterior[currentNode]
except KeyError:
print('Path not reachable')
break
path.insert(0,start)
if menorCaminho[finish] != infinity:
print(str(menorCaminho[finish]) + " pelo caminho " + str(path))
dijkstra(vetor, 'a', 'c')
|
368cd1abb302797f76e0f48536014543bae9aff6 | djanshuman/Algorithms-Data-Structures | /Python/Searching/Binary_Search_Recursive.py | 458 | 3.765625 | 4 | '''
Created on 02-Jun-2020
@author: dibyajyoti
'''
def Search(alist,element):
if(len(alist) ==0):
return False
else:
mid=len(alist)//2
if(alist[mid]==element):
return True
else:
if(element > alist[mid]):
return Search(alist[mid+1:], element)
else:
return Search(alist[:mid], element)
alist=[10,56,78,99,121,145]
print(Search(alist,78))
|
68ca4adaae6f8a0830f83acded0c29b7970850ca | jmctsm/Udemy_2020_Complete_Python_BootCamp | /15_PDFs_and_Spreadsheets/00-Working-with-CSV-Files.py | 1,159 | 3.8125 | 4 | import csv
def line_break():
for x in range(0,25):
print("*", end="")
print("\n")
# Reading CSV Files
line_break()
data = open("example.csv", encoding="utf-8")
print(data)
# Encoding
line_break()
csv_data = csv.reader(data)
data_lines = list(csv_data)
print(data_lines)
print(data_lines[:3])
for line in data_lines[:5]:
print(line)
print(len(data_lines))
all_emails = []
for line in data_lines[1:]:
all_emails.append(line[3])
print(all_emails)
full_names = []
for line in data_lines[1:]:
full_names.append(line[1] + ' ' + line[2])
print(full_names)
# Writing to CSV Files
line_break()
# New File
line_break()
# newline controls how universal newlines works (it only applies to text
# mode). It can be None, '', '\n', '\r', and '\r\n'
file_to_output = open('to_save_file.csv', 'w', newline='')
csv_writer = csv.writer(file_to_output, delimiter=',')
csv_writer.writerow(['a', 'b', 'c'])
csv_writer.writerows([['1', '2', '3'], ['4', '5', '6']])
file_to_output.close()
# Existing File
line_break()
f = open('to_save_file.csv', 'a', newline='')
csv_writer = csv.writer(f)
csv_writer.writerow(['new', 'new', 'new'])
f.close()
|
c5260e1253d76b7f4253e499a2e0f274338018c9 | dawidgdanski/python-training | /learningpython/decorators/timerdeco1.py | 1,313 | 3.765625 | 4 | # File timerdeco1.py
# Caveat: range still differs - a list in 2.X, an iterable in 3.X
# Caveat: timer won't work on methods as coded (see quiz solution)
import sys
import time
force = list if sys.version_info[0] == 3 else (lambda X: X)
class timer:
def __init__(self, func):
self.func = func
self.alltime = 0
def __call__(self, *args, **kargs):
start = time.perf_counter()
result = self.func(*args, **kargs)
elapsed = time.perf_counter() - start
self.alltime += elapsed
print('%s: %.5f, %.5f' % (self.func.__name__, elapsed, self.alltime))
return result
@timer
def listcomp(N):
return [x * 2 for x in range(N)]
@timer
def mapcall(N):
return force(map((lambda x: x * 2), range(N)))
if __name__ == "__main__":
result = listcomp(5) # Time for this call, all calls, return value
listcomp(50000)
listcomp(500000)
listcomp(1000000)
print(result)
print('allTime = %ss' % listcomp.alltime) # Total time for all listcomp calls
print('')
result = mapcall(5)
mapcall(50000)
mapcall(500000)
mapcall(1000000)
print(result)
print('allTime = %s' % mapcall.alltime) # Total time for all mapcall calls
print('\n**map/comp = %ss' % round(mapcall.alltime / listcomp.alltime, 3))
|
a6c86d695cf8bb25f3ebe3db7cb4f2917966816e | kdheepak/hawk-dove | /species.py | 3,832 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
Evolutionary game theory
The strategy of the Hawk (a fighter strategy) is to first display aggression, then escalate into a fight until he either wins or is injured.
The strategy of the Dove (fight avoider) is to first display aggression but if faced with major escalation by an opponent to run for safety.
"""
from __future__ import absolute_import, division, print_function
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object)
import random
class Bird(object):
def __init__(self, *args, **kwargs):
if self.strategy is None:
self.strategy = kwargs.pop('strategy', None)
self.fitness = kwargs.pop('fitness', 50)
self.fights = kwargs.pop('fights', 0)
self.species = kwargs.pop('species', self.__class__.__name__)
self.active = True
def __str__(self):
return("""{}\t{}\t{}""".format(self.species, self.fitness, self.fights))
class Hawk(Bird):
def __init__(self, *args, **kwargs):
self.strategy = kwargs.pop('strategy', 'Aggressive')
super().__init__(*args, **kwargs)
class Dove(Bird):
def __init__(self, *args, **kwargs):
self.strategy = kwargs.pop('strategy', 'Passive')
super().__init__(*args, **kwargs)
class Population(object):
def __init__(self, *args, **kwargs):
"""
Attribute
---------
number_of_hawks (int)
number_of_doves (int)
"""
self.individuals = [Hawk() for _ in range(0, kwargs.pop('number_of_hawks', 10))] + [Dove() for _ in range(0, kwargs.pop('number_of_doves', 10))]
self.THRESHOLD = kwargs.pop('THRESHOLD', 100)
self.total = len(self.individuals)
self.history = []
self.clean()
def describe(self):
print("Number of hawks = {}".format(self.number_of_hawks))
print("Number of doves = {}".format(self.number_of_doves))
print("Percent of hawks = {}".format(self.number_of_hawks/self.total*100))
print("Percent of doves = {}".format(self.number_of_doves/self.total*100))
@property
def random_individual(self, active=True):
try:
i = random.choice([individual for individual in self.individuals if individual.active==active])
i.active = False
return i
except IndexError:
return None
def clean(self):
self.individuals = [bird for bird in self.individuals if bird.fitness >= 0]
for bird in self.individuals:
bird.active = True
self.total = len(self.individuals)
self.number_of_hawks = [bird.species for bird in self.individuals].count('Hawk')
self.number_of_doves = [bird.species for bird in self.individuals].count('Dove')
if self.total == 0:
self.total = 1
self.history.append([self.number_of_hawks, self.number_of_doves, self.number_of_hawks/self.total, self.number_of_doves/self.total])
self.breed()
def breed(self):
for individual in self.individuals:
if individual.fitness >= 100:
individual.fitness = 100
breed_pool = []
# print("{} number of breeders exist".format(len([individual for individual in self.individuals if individual.fitness > self.THRESHOLD])))
for individual in self.individuals:
if individual.fitness >= self.THRESHOLD:
individual.fitness = individual.fitness / 2
breed_pool.append((individual.species, individual.fitness))
for baby, fitness in breed_pool:
if baby == 'Hawk':
self.individuals.append(Hawk(fitness=fitness))
if baby == 'Dove':
self.individuals.append(Dove(fitness=fitness))
|
0fb5c770b39584f088df120e9970f5e5e100bd15 | yogeshasok/Python_Assgn01 | /Yog_python/Ass_20.py | 202 | 3.578125 | 4 | limit = int(input("Enter the limit to generate Fibo series "))
li =[0,1]
a = 0
b = 1
c = 0
res=0
while(c<limit):
li.append(a+b)
res=a+b
print res
a = b
b = res
c = c+1
print li
|
2f3a453d8e8ccfc169e805029019d115b74ce716 | vyashole/learn | /05-inputs.py | 1,094 | 4.46875 | 4 | # User input can be taken from the console using the input()
user_name = input("Enter your name:")
print("Hello, " + user_name)
# note that input always comes in as string
# so id a use puts in 5 python gets "5"
# To convert your data types you can use casting
# int() - casts to an integer number from an integer literal,
# a float literal (by rounding down to the previous whole number),
# or a string literal (providing the string represents a whole number)
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
print(x, y, z)
# float() - casts to a float number from an integer literal,
# a float literal or a string literal
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
# str() - casts to a string from a wide variety of data types,
# including strings, integer literals and float literals
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
# casting is often used in combination with input
g = int(input("Get me a number:"))
|
a77db03253de0c74ab66bc4c9827a1aff2ddf8fd | Andrea-Vigano/rnenv | /rnenv111/rn/rn.py | 48,194 | 3.796875 | 4 | """
RN 1.11 class module
Following the 'functional RN representation' protocol, based on the
dynamic representation of real numbers as a sequence of integers and operations that bind them.
Operations between numbers aren't new, they are normally performed by the language itself, but in the case of
mathematically represented real numbers, sometimes it is not possible to perform the operation required without a
loss in precision. Normally, this is not a big deal, but with this project our task is to permit a way to
represent real numbers and operate with them with no loss in precision.
This is made possible by checking if the operation required can be performed without a precision loss; if that is not
the case, the return value of the operation will be a real number storing the information of the operation that should
have been performed and the terms involved in that operations. This form of real number is valid and fully operative,
meaning you can use it as a normal and 'simple' real number object, permitting the representation of nested
structures we see in algebra.
For example, performing: √3 + √2 = 1.73 + 1.41 = 3.14 involve a certain level of approximation, because √3 and √2
are irrational. So, usually in algebra the sum is not performed in the first place, and the number is represented by
and expression, in this case, by two terms connected with '+', indicating a sum. So an object which aims to
algebraically represent numbers has to permit this kind of representation.
The example provided is a simple case, but the expression could also be more complex: if we were to divide the number
from the previous example by 2, we obviously would not be able to perform the operation; the number should then have
a form like:
√3 + √2
------- --> 'TrueDiv( Add( Sqr( 3 ), Sqr( 2 ) ), 2 )'
2
Which presents another level of complexity that has to be handled. Virtually, there is no limit to the amount of
complexity you can get to. To project this reality into a computable model, the RN object should be represented in two
main forms, strictly related to each other: the 'simple' RN, representable with a single integer, and the more complex
ones, which refer to an operation and its terms.
NOTE: in the example above, the numbers √3 and √2 fall into the second category, because their object should reference
the square root operation.
"""
# TODO redefine operations engine with the new functionalities added the RN class
# TODO implement root reduction algorithms
# TODO update string build for RN class (maybe with operation priority implementation)
from abc import ABCMeta, abstractmethod, ABC
from numpy import lcm
import math
from rnenv111.rn.mathfuncs.funcs import reduce_fraction, reduce_root
math = math
# op validator (used to assert that other is always an RN, even if integers are also accepted)
def _validate(func):
def inner(self, other):
# self is already RN
if not (isinstance(other, RN) or isinstance(other, int)):
raise ValueError('Unable to perform {} between {} (RN) and {} ({})'
.format(func, self, other, type(other)))
if isinstance(other, int):
other = RN(other)
return func(self, other)
return inner
class RN:
"""
RN 'functional representation' class
Following the functional RN representation protocol, as explained in the rn.py module DOC string.
"""
# ACCEPTED / IMPLEMENTED OPERATIONS CLASSES
PERMITTED_OPERATIONS = ()
def __init__(self, *terms, op=None):
"""
The type of RN instantiated depends from the parameters passed by the user:
if the kw op is not specified (left as None), it will assume that self is a 'simple' RN (integer),
and will expect ONLY one term of type int.
if the op is specified, than it won't perform any validation, as it should have been done by the operator class,
which validate the parameters relatively to the type of operation specified (for example, there are
unary and binary operators...).
Normally you should not specify operations, as this is done in the background by the operation methods of
the class itself; for instance, the RN.__add__ method can tell if the terms of the operation can be
simplified or should be left as they are. If that is the case, it will return an RN with the additional level
of complexity needed.
:param op: reference to the operator, set to None by default, does not need to be specified if you are
trying to represent an integer real number
:param terms: terms of the instance, if no operator is specified, only one term needs to be passed, else
the number depends on the operator type.
"""
if not op:
# if no op -> simple RN
if len(terms) != 1:
raise ValueError('Bad user argument, RN where op is not specified should get 1 term, got {}'
.format(terms))
if not isinstance(terms[0], int):
raise ValueError('Bad user argument, RN where op is not specified should get only int objects,'
' got {}'.format(type(terms[0])))
self.op = op
self.terms = terms
# string representation
def __str__(self):
"""
If op is None, will return the string of the only term.
Else, will use the string method defined in the op class
:return: string representation of instance
"""
if not self.op:
return str(self[0])
return self.op.string(self.terms)
def __repr__(self):
"""
repr(self)
:return: string representation
"""
return str(self)
# data casing
def __int__(self):
"""
Integer cast to RN value, if no op, returns its only term
else, truncate float(self), which actually calculate RN value recursively
executing the operations related to self and each term of self
:return: Integer
"""
return self[0] if not self.op else int(float(self))
def __float__(self):
"""
Float cast to RN value, if no op, returns its only terms cast to float
else, recursively calculate the value of the RN by going up the different
level of complexity in the representation of RN
:return: Float
"""
if not self.op:
return float(self[0])
else:
flt_terms = tuple(map(lambda x: float(x), self.terms))
func = self.op.__name__.lower() if not issubclass(self.op, ArithmeticOperation) \
else '__' + self.op.__name__.lower() + '__'
if func == '__matmul__':
return flt_terms[0] ** (1 / flt_terms[1])
else:
code_fragment = 'flt_terms[0].' + func + ('(*flt_terms[1:])' if flt_terms[1:] else '()')
return float(eval(code_fragment))
def __bool__(self):
"""
Boolean cast to RN value, return False only is RN
is equal to 0
:return: Bool value
"""
return self != 0
# faster terms getter
def __getitem__(self, item):
"""
self[index]
Won't validate because the index call at terms
will handle errors by itself
:param item: integer
:return: object in terms (RN or int)
"""
return self.terms[item]
# equality
@_validate
def __eq__(self, other):
"""
self == other
Comparison is made by comparing float values of self and other
:param other: RN or int
:return: Boolean
"""
if float(self) == float(other):
return True
return False
@_validate
def __ne__(self, other):
"""
self != other
:param other: RN or int
:return: Boolean
"""
return not self == other
# comparisons
@_validate
def __gt__(self, other):
"""
self > other
Compare float values
:param other: RN or int
:return: Boolean
"""
return float(self) > float(other)
@_validate
def __ge__(self, other):
"""
self >= other
Compare float values
:param other: RN or int
:return: Boolean
"""
return float(self) >= float(other)
@_validate
def __lt__(self, other):
"""
self < other
Compare float values
:param other: RN or int
:return: Boolean
"""
return float(self) < float(other)
@_validate
def __le__(self, other):
"""
self <= other
Compare float values
:param other: RN or int
:return: Boolean
"""
return float(self) <= float(other)
# types getters
# TODO define actual logic for is_rational / is_irrational
def is_integer(self):
return not self.op
def is_rational(self):
return True
def is_irrational(self):
return False
# operations
# Arithmetic operations: add, sub, mul, truediv, floordiv, pow, root (using matmul for that) (binary operators)
# + neg, pos and abs (unary operators)
# when the arguments make it to the actual function, they will always be RNs, as the decorator
# __validate will convert them if any integer is found
def __neg__(self):
return self * -1
def __pos__(self):
return self
def __abs__(self):
return self if self >= 0 else -self
@_validate
def __add__(self, other):
"""
self + other
:param other: RN (if int is turned to RN by __validate)
:return: RN object sum
"""
return Add(self, other).rv()
@_validate
def __radd__(self, other):
return Add(other, self).rv()
@_validate
def __sub__(self, other):
"""
self - other
:param other: RN (if int is turned to RN by __validate)
:return: RN object difference
"""
return Sub(self, other).rv()
@_validate
def __rsub__(self, other):
return Sub(other, self).rv()
@_validate
def __mul__(self, other):
"""
self * other
:param other: RN (if int is turned to RN by __validate)
:return: RN object product
"""
return Mul(self, other).rv()
@_validate
def __rmul__(self, other):
return Mul(other, self).rv()
@_validate
def __truediv__(self, other):
"""
self / other
Validate: raise error if other == 0
:param other: RN (if int is turned to RN by __validate)
:return: RN object quotient
"""
return TrueDiv(self, other).rv()
@_validate
def __rtruediv__(self, other):
return TrueDiv(other, self).rv()
@_validate
def __floordiv__(self, other):
"""
self // other
Validate: raise error if other == 0
:param other: RN (if int is turned to RN by __validate)
:return: RN object exact quotient
"""
return FloorDiv(self, other).rv()
@_validate
def __rfloordiv__(self, other):
return FloorDiv(other, self).rv()
@_validate
def __mod__(self, other):
"""
self % other
Get by calculating self / other - self // other
:param other:
:return:
"""
return Mod(self, other).rv()
@_validate
def __rmod__(self, other):
return Mod(other, self).rv()
@_validate
def __pow__(self, power, modulo=None):
"""
self ** power
Validate: raise error if self and power are both zeros
if self < 0 and power is not rational
:param power: RN power
:param modulo: None
:return: RN object power
"""
return Pow(self, power).rv()
@_validate
def __rpow__(self, other, modulo=None):
return Pow(other, self).rv()
@_validate
def __matmul__(self, other):
"""
self@ other
Which is interpreted as [self]√ other
Validate: raise error if self is even and other < 0
if self is zero
if self < 0 and other is zero
:param other: Radicand
:return: RN object root
"""
return MatMul(self, other).rv()
@_validate
def __rmatmul__(self, other):
return MatMul(other, self).rv()
# Operation abstract class
class Operation(metaclass=ABCMeta):
"""
Operation super - abstract class, interface that every operation class should follow:
- OPERANDS_NUMBER attribute specifying how many terms are needed to perform the operation required
- validation method of signature 'validate_terms(terms) -> None'
- string representation method of signature 'string(terms) -> str'
- return value getter of signature 'rv(self) -> RN'
Every sub class of this is an 'operation class', meaning that every time the operation they refer to
is performed, an instance of them is created to get the nature of the return value (if it is a 'simple' RN
or another level of complexity is needed)
The standard return value (rv) should be defined for when each term of the operation is 'simple' (no op),
in the other cases, the rv should call a specific method from the Operation subclass, with a standardized name
defined from the op types of the terms separated by an '_'. In this way, we are able to move the case specific
code out of the rv method, making it easier to understand and modify. If the method is not defined, that it will
assume that the operation it is trying to perform cannot be reduced, so it will return the standard RN object
with another level of complexity to it.
NOTE: the name of each operation should be (non caps sensitive) equal to the name of the function related to
itself in RN class, for instance '__add__' -> class name should be 'Add'
"""
PERMITTED_OPERANDS = (int, RN)
# number of operands needed to perform operation
# here set to NotImplemented but defined in subclasses
OPERANDS_NUMBER = NotImplemented
OPERATOR = NotImplemented
# operand properties
PROPERTIES = NotImplemented
def __init__(self, *terms):
"""
Standard initialization of the operation:
validate terms -> self.validate_terms
set terms attribute, parsing every item so that there are only RN in the list
:param terms: operation terms, their number vary depending on the operation performed
"""
self._validate_terms(terms)
self.terms = tuple(map(lambda x: x if isinstance(x, RN) else RN(x), terms))
def _validate_terms(self, terms):
"""
Validate that the terms passed could be the operands of they operation type represented.
If no, raise error.
:param terms: RN operands
:return: None
"""
if len(terms) != self.OPERANDS_NUMBER:
raise ValueError('Bad user argument, cannot perform operation {} with {} terms ({}), {} are needed'
.format(self.__class__.__name__, len(terms), terms, self.OPERANDS_NUMBER))
for term in terms:
if not any(isinstance(term, tp) for tp in self.PERMITTED_OPERANDS):
raise ValueError('Bad user argument, operation {} can be performed only with types {},\n terms {}'
' contains one or more invalid type/s '
.format(self.__class__.__name__, self.PERMITTED_OPERANDS, terms))
@staticmethod
@abstractmethod
def string(terms):
"""
Return the string representation of the operation, using the terms passed.
:param terms: operation terms
:return: string representation
"""
def rv(self):
"""
Return the actual RN object resulting from the operation,
following the functional RN representation protocol.
More detailed parsing is defined in the methods defined in the
Operation subclasses.
:return: RN object
"""
# standard return value
return RN(op=self.__class__, *self.terms)
# Arithmetic operations
# -> Add, Sub, Mul, TrueDiv, FloorDiv, Pow, Root
class ArithmeticOperation(Operation, ABC):
"""
ABC super class for arithmetic operations, like Add, Sub, Mul...
- define OPERANDS_NUMBER equal to 2
- define a string method builder common for most of the operations
- define a super rv method
"""
OPERANDS_NUMBER = 2
PROPERTIES = []
def _validate_terms(self, terms):
super()._validate_terms(terms)
@classmethod
def string_builder(cls):
"""
Returns a method that should return the string representation of the
operation passed (using the cls.OPERATOR attribute)
:return: string representation getter
"""
def inner(terms):
joint = ' ' + cls.OPERATOR + ' '
return joint.join([str(term) for term in terms])
return inner
def rv(self):
"""
Return RN return value of the operation
for the arithmetic operations, in general, can perform operation in this cases:
- if each term op is none
if operation cannot be performed, return Operation rv method call
:return: RN object
"""
# call operator method
op_1 = self.terms[0].op
op_2 = self.terms[1].op
op_1 = op_1.__name__.lower() if op_1 else 'none'
op_2 = op_2.__name__.lower() if op_2 else 'none'
try:
# try to call the operation method for the terms defined operations
return eval('self.' + op_1 + '_' + op_2 + '(*self.terms)')
except AttributeError:
# no operation method found
# -> if commutative properties
if 'commutative' in self.PROPERTIES:
try:
func = eval('self.' + op_2 + '_' + op_1)
return eval('self.' + op_2 + '_' + op_1 + '(*reversed(self.terms))')
except AttributeError:
pass
return super().rv()
# possible data parsing in operation:
# - Complexity level add (no operation)
# - Nested add / sub parsing
# - Fractional operations
# - Addends merge into mul
def _complexity_level(_cls):
"""
Std operation parsing procedure,
used for Add operations that cannot
be reduced, so the complexity level is increased
:param a: First RN
:param b: Second RN
:return: RN sum object
"""
def inner(a, b):
# No validation needed, as this method is only called locally
data = (a, b)
return RN(op=_cls, *data)
return inner
def _sum_sub_parsing(_cls):
"""
Operation parsing involving sums or subs,
will parse the terms involved in the actual operation
and try merge them.
Will have to specify where both the operands are sum / sub or only one.
:return: RN object
"""
# will assume classes passed are the right ones with the right methods defined
def inner(_a: bool, _b: bool):
def double_inner(a, b):
"""
-> sum data parsing
list every term in the sum (considering that sum may involve more than one term)
- loop sum terms, if term is a sum -> parse, else add to list
if any of the terms in list is compatible to the int, add it
Re build new sum object if merging has been done
Compatibility check:
if a + term is not a sum, merge
Example:
3 + (√3 + 4) --> list = [Root 3, 4] where for is compatible with 3 (both integer)
-> √3 + 7
"""
terms = []
terms += _cls._parse_sum(a) if _a else [a]
terms += _cls._parse_sum(b) if _b else [b]
return _cls._sum_terms(_cls._merge_sum(terms))
return double_inner
return inner
def _fractional_sum(_a: bool, _b: bool):
"""
Operation involving fractions (TrueDiv objects)
Will bring everything on a single fraction and sum the terms
there.
Need to specify which operands are fractions
:param _a: First RN
:param _b: Second RN
:return: RN object
"""
def inner(a, b):
# hardcoded logic
if not _b:
return TrueDiv(a[0] + b * a[1], a[1]).rv()
if not _a:
return TrueDiv(b[0] + a * b[1], b[1]).rv()
else:
return TrueDiv(a[0] * b[1] + a[1] * b[0], a[1] * b[1]).rv()
return inner
def _addends_merge(a, b):
"""
Operation involving two equal addends
that are turned into a Mul object
:param a: First RN
:param b: Second RN
:return: RN mul object
"""
if a == b:
data = (2, a)
return RN(op=Mul, *data)
data = (a, b)
return RN(op=Add, *data)
def _cl_add(a, b):
"""
Complexity Level adder for Add class
"""
return _complexity_level(Add)(a, b)
def _ssp_add(_a, _b):
"""
Sum Sub Parsing for Add class
"""
return _sum_sub_parsing(Add)
class Add(ArithmeticOperation):
OPERATOR = '+'
PROPERTIES = ['commutative']
@staticmethod
def string(terms):
return Add.string_builder()(terms)
@staticmethod
def _parse_sum(_sum):
"""
Returns the list of terms involved in the sum / sub
:param _sum: RN sum / sub
:return: terms list
"""
_list = []
# get sum / sub terms
for p, term in enumerate(_sum.terms):
if term.op in (Add, Sub):
_list.extend(Add._parse_sum(term))
else:
if _sum.op == Sub and p == 1:
_list.append(-term)
else:
_list.append(term)
return _list
@staticmethod
def _merge_sum(terms):
"""
Returns the parsed terms of the sum / sub,
merging the terms that can be merged
:param terms: sum / sub terms (use Add._parse_sum to get them)
:return: terms list (parsed)
"""
# sort by op class name (if terms can be merged, they have the same op)
terms = sorted(terms, key=lambda x: x.op.__name__.lower() if x.op else 'none')
for p, term in enumerate(terms):
try:
_sum = term + terms[p + 1]
if _sum.op != Add:
terms[p] = None
terms[p + 1] = _sum
except IndexError:
continue
return [term for term in terms if term]
@staticmethod
def _sum_terms(terms):
"""
Sum up parsed sum terms
:param terms: Addends
:return: RN object sum
"""
if len(terms) == 0:
return RN(0)
elif len(terms) == 1:
return terms[0]
rv = 0
for p, term in enumerate(terms):
if p == 0:
rv = term + terms[1]
elif p != 1:
rv += term
return rv
# operations explicit declarations
@staticmethod
def none_none(a, b):
"""
Int + Int
Simple integers sum
:return: RN object
"""
return RN(a[0] + b[0])
none_add = staticmethod(_ssp_add(False, True))
none_sub = staticmethod(_ssp_add(False, True))
none_mul = staticmethod(_cl_add)
none_truediv = staticmethod(_fractional_sum(True, False))
none_floordiv = staticmethod(_cl_add)
none_mod = staticmethod(_cl_add)
none_pow = staticmethod(_cl_add)
none_matmul = staticmethod(_cl_add)
add_add = staticmethod(_ssp_add(False, True))
add_sub = staticmethod(_ssp_add(False, True))
add_mul = staticmethod(_cl_add)
@staticmethod
def add_truediv(a, b):
"""
Sum + fraction
bring every think to single fraction,
then sum numerator terms
num = each term of sum * den + num
:return: RN object
"""
terms = Add._parse_sum(a * b[1]) + [b[0]]
# sum num terms and return fraction
return TrueDiv(Add._sum_terms(terms), a[1]).rv()
add_floordiv = staticmethod(_cl_add)
add_mod = staticmethod(_cl_add)
add_pow = staticmethod(_cl_add)
add_matmul = staticmethod(_ssp_add(False, True))
sub_sub = staticmethod(_ssp_add(False, True))
sub_mul = staticmethod(_cl_add)
sub_truediv = staticmethod(_fractional_sum(True, False))
sub_floordiv = staticmethod(_cl_add)
sub_mod = staticmethod(_cl_add)
sub_pow = staticmethod(_cl_add)
sub_matmul = staticmethod(_ssp_add(False, True))
mul_mul = staticmethod(_cl_add)
mul_truediv = staticmethod(_fractional_sum(True, False))
mul_floordiv = staticmethod(_cl_add)
mul_pow = staticmethod(_cl_add)
@staticmethod
def mul_matmul(a, b):
"""
Mul + Root
if one of the terms in Mul is equal to Root,
merge
:return: RN object
"""
data = (a, b)
if a[0] == b and not a[1].op:
data = (a[1] + 1, b)
elif a[1] == b and not a[0].op:
data = (a[0] + 1, b)
if data[0].op == Add:
data = (a, b)
return RN(op=Add, *data)
truediv_truediv = staticmethod(_fractional_sum(True, False))
truediv_floordiv = staticmethod(_fractional_sum(True, False))
truediv_mod = staticmethod(_fractional_sum(True, False))
truediv_pow = staticmethod(_fractional_sum(True, False))
truediv_matmul = staticmethod(_fractional_sum(True, False))
floordiv_floordiv = staticmethod(_addends_merge)
floordiv_mod = staticmethod(_cl_add)
floordiv_pow = staticmethod(_cl_add)
floordiv_matmul = staticmethod(_cl_add)
mod_mod = staticmethod(_addends_merge)
mod_pow = staticmethod(_cl_add)
mod_matmul = staticmethod(_cl_add)
pow_pow = staticmethod(_addends_merge)
pow_matmul = staticmethod(_cl_add)
matmul_matmul = staticmethod(_addends_merge)
def _cl_sub(a, b):
"""
Complexity Level adder for Sub class
"""
return _complexity_level(Sub)(a, b)
def _ssp_sub(_a, _b):
"""
Sum Sub Parsing for Add class
"""
return _sum_sub_parsing(Sub)
class Sub(ArithmeticOperation):
OPERATOR = '-'
@staticmethod
def string(terms):
return Sub.string_builder()(terms)
# operations explicit declarations
# @staticmethod
# def none_none(a, b):
# return RN(a[0] - b[0])
#
# @staticmethod
# def truediv_none(a, b):
# """
# fraction - integer:
# - num - integer * den / den
#
# :return: RN object
# """
#
# data = (a[0] - b[0] * a[1], a[1])
# return TrueDiv(*data).rv()
#
# @staticmethod
# def none_truediv(a, b):
# """
# integer - fraction:
# - integer * den - num / den
#
# :return: RN object
# """
#
# data = (a[0] * b[1] - b[0], b[1])
# return TrueDiv(*data).rv()
#
# @staticmethod
# def truediv_truediv(a, b):
# """
# fraction + fraction
# - num1 * den2 - num2 * den1, den1 * den2
#
# :return: RN object
# """
#
# data = (a[0] * b[1] - b[0] * a[1], a[1] * b[1])
# return TrueDiv(*data).rv()
#
# @staticmethod
# def matmul_matmul(a, b):
# """
# Root - Root
#
# Reduce if a == b
#
# :return: RN object
# """
#
# if a == b:
# return RN(0)
# data = (a, b)
# return RN(op=Add, *data)
@staticmethod
def none_none(a, b):
"""
Integer - Integer
Simple subtraction
:return: RN object
"""
return RN(a[0] - b[0])
@staticmethod
def none_add(a, b):
"""
Integer - Sum
Sum parsing
:return: RN object
"""
return _ssp_sub(False, True)(a, b)
@staticmethod
def none_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def none_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def add_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def sub_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mul_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def truediv_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def floordiv_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def mod_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def pow_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_none(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_add(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_sub(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_mul(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_truediv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_floordiv(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_mod(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_pow(a, b):
"""
DOC to be defined
:return: RN object
"""
@staticmethod
def matmul_matmul(a, b):
"""
DOC to be defined
:return: RN object
"""
class Mul(ArithmeticOperation):
OPERATOR = '*'
PROPERTIES = ['commutative']
@staticmethod
def string(terms):
return Mul.string_builder()(terms)
@staticmethod
def none_none(a, b):
return RN(a[0] * b[0])
@staticmethod
def truediv_none(a, b):
"""
fraction * integer:
- num * integer, den
- reduce integer and den if possible
:return: RN object
"""
data = (a[0] * b[0], a[1])
return TrueDiv(*data).rv()
@staticmethod
def none_truediv(a, b):
return Mul.truediv_none(b, a)
@staticmethod
def truediv_truediv(a, b):
"""
fraction * fraction:
- num1 * num2, den1 * den2
:return: RN object
"""
data = (a[0] * b[0], a[1] * b[1])
return TrueDiv(*data).rv()
@staticmethod
def matmul_matmul(a, b):
"""
Root * Root
get indexes lcm, result is a new root,
with index equal to the lcm, and the radicand
equal to the product of each radicand ** (lcm // old index)
:return: RN object
"""
_lcm = int(lcm(a[0], b[0]))
return MatMul(_lcm, (a[1] ** (_lcm // a[0])) * (b[1] ** (_lcm // b[0]))).rv()
class TrueDiv(ArithmeticOperation):
OPERATOR = '/'
def _validate_terms(self, terms):
"""
Override validation method
- check that den is not 0
:param terms:
:return:
"""
super()._validate_terms(terms)
if terms[1] == 0:
raise ZeroDivisionError('Bad user argument, cannot divide by zero')
@staticmethod
def string(terms):
return TrueDiv.string_builder()(terms)
@staticmethod
def none_none(a, b):
"""
No op case: check if division can be performed completely, partially or not
:return: RN object
"""
num, den = reduce_fraction(a[0], b[0])
if den == 1:
return RN(num)
data = (RN(num), RN(den))
return RN(op=TrueDiv, *data)
@staticmethod
def truediv_none(a, b):
"""
fraction / integer
:return: RN object
"""
data = (a[0], a[1] * b[0])
return TrueDiv(*data).rv()
@staticmethod
def none_truediv(a, b):
"""
integer / fraction
:return: RN object
"""
data = (a[0] * b[1], b[0])
return TrueDiv(*data).rv()
@staticmethod
def truediv_truediv(a, b):
"""
fraction / fraction
:return: RN object
"""
data = (a[0] * b[1], a[1] * b[0])
return TrueDiv(*data).rv()
class FloorDiv(ArithmeticOperation):
OPERATOR = '//'
def _validate_terms(self, terms):
"""
Override validation method
- check that den is not 0
:param terms:
:return:
"""
super()._validate_terms(terms)
if terms[1] == 0:
raise ZeroDivisionError('Bad user argument, cannot divide by zero')
@staticmethod
def string(terms):
return FloorDiv.string_builder()(terms)
@staticmethod
def none_none(a, b):
return RN(a[0] // b[0])
@staticmethod
def truediv_none(a, b):
"""
fraction // integer
:return: RN object
"""
data = (float(a) // b[0], )
return RN(*data)
@staticmethod
def none_truediv(a, b):
"""
integer // fraction
:return: RN object
"""
data = (a[0] // float(b), )
return RN(*data)
@staticmethod
def truediv_truediv(a, b):
"""
fraction // fraction
:return: RN object
"""
data = (float(a) // float(b), )
return RN(*data)
class Mod(ArithmeticOperation):
OPERATOR = '%'
def _validate_terms(self, terms):
"""
Validate mod terms:
- other != 0
:param terms: operation terms
:return: None
"""
super()._validate_terms(terms)
if terms[1] == 0:
raise ValueError('Unable to operate {} with {} and zero'
.format(self.__class__.__name__, terms[0]))
@staticmethod
def string(terms):
return Mod.string_builder()(terms)
@staticmethod
def none_none(a, b):
"""
Integer % Integer
:return: RN object mod
"""
return a[0] % b[0]
class Pow(ArithmeticOperation):
OPERATOR = '**'
def __init__(self, *terms):
"""
Initialize Pow object, if exponent is negative,
change its value to positive and change base to 1 / base
:param terms: Pow terms
"""
super().__init__(*terms)
if self.terms[1] < 0:
self.terms = (1 / self.terms[0], -self.terms[1])
def _validate_terms(self, terms):
"""
Validate pow terms:
- exponent = 0 and base = 0
- real exponent and base < 0
are all cases where it is no possible to perform the operation
:param terms: base and exponent
:return: None
"""
super()._validate_terms(terms)
if terms[0] == 0 and terms[1] == 0:
raise ValueError('Unable to perform 0^0')
elif terms[0] < 0 and not terms[1].is_rational:
raise ValueError('Unable to calculate operation {} with negative base {} and real exponent {}'
.format(self.__class__.__name__, terms[0], terms[1]))
@staticmethod
def string(terms):
return Pow.string_builder()(terms)
@staticmethod
def none_none(a, b):
"""
Integer ** Integer
:return: RN object
"""
return RN(a[0] ** b[0])
@staticmethod
def truediv_none(a, b):
"""
fraction ** Integer
:return: RN object
"""
data = (a[0] ** b[0], a[1] ** b[0])
return TrueDiv(*data).rv()
@staticmethod
def none_truediv(a, b):
"""
Integer ** (num / den)
-> [den] Root (Integer ** num)
:return: RN object
"""
data = (b[1], a[0] ** b[0])
return MatMul(*data).rv()
@staticmethod
def truediv_truediv(a, b):
"""
fraction ** fraction
-> Root(den_2, fraction_1 ** num_2)
:return: RN object
"""
return Pow.none_truediv(a, b)
@staticmethod
def matmul_none(a, b):
"""
Root ** Integer
-> [Index]√ (Radicand ** Integer)
:return: RN object
"""
return MatMul(a[0], a[1] ** b).rv()
@staticmethod
def matmul_truediv(a, b):
"""
Root ** fraction
-> [Index]√ (Radicand ** Integer)
:return: RN object
"""
return Pow.matmul_none(a, b)
class MatMul(ArithmeticOperation):
OPERATOR = '√'
def _validate_terms(self, terms):
"""
Validate root terms:
- radicand < 0 and even index
- index = 0
- radicand = 0 and index < 0
are all invalid cases where the operation is not possible
:param terms: index and radicand
:return: None
"""
super()._validate_terms(terms)
if terms[0] % 2 == 0 and terms[1] < 0:
raise ValueError('Unable to perform {} of even index {} and negative radicand {}'
.format(self.__class__.__name__, terms[0], terms[1]))
elif terms[0] == 0:
raise ValueError('Unable to perform {} of zero index and radicand {}'
.format(self.__class__.__name__, terms[1]))
elif terms[0] < 0 and terms[1] == 0:
raise ValueError('Unable to perform {} of negative index {} and zero radicand'
.format(self.__class__.__name__, terms[0]))
@staticmethod
def string(terms):
return MatMul.string_builder()(terms)
@staticmethod
def none_none(a, b):
"""
[Integer]√ Integer
Save sign
Check if root is an integer -> return simple RN
else -> return RN with op = Root
:param a: RN index
:param b: RN radicand
:return: RN object root
"""
radicand, index, sign = b[0], a[0], False
if b < 0:
radicand = -radicand
sign = True
root = radicand ** (1 / index)
if int(root) == round(root, 5):
return RN(int(root)) if not sign else RN(-int(root))
else:
# reduce root
mul_factor, index, radicand = reduce_root(index, radicand)
data = (index, radicand)
if mul_factor != 1:
data = (mul_factor, RN(op=MatMul, *data))
return RN(op=Mul, *data)
return RN(op=MatMul, *data)
@staticmethod
def none_truediv(a, b):
"""
[Integer]√ fraction
Integer root of both
then try rationalization
# TODO implement rationalization
:return: RN object
"""
data = (MatMul(a, b[0]).rv(), MatMul(a, b[1]).rv())
return RN(op=TrueDiv, *data)
@staticmethod
def truediv_none(a, b):
"""
[fraction]√ Integer
Use Integer root of base ** denominator
:return: RN object
"""
return MatMul(a[0], Pow(b, a[1]).rv()).rv()
@staticmethod
def truediv_truediv(a, b):
"""
[fraction]√ fraction
Same code of truediv_none
:return: RN object
"""
return MatMul.truediv_none(a, b)
@staticmethod
def none_matmul(a, b):
"""
[Integer]√ Root
New index is product of old indexes
:return: RN object
"""
data = (a * b[0], b[1])
return RN(op=MatMul, *data)
@staticmethod
def truediv_matmul(a, b):
"""
[fraction]√ Root
New index is product of old indexes,
parse as MatMul after
:return: RN object
"""
return MatMul(a * b[0], b[1]).rv()
|
edb038a532a4abb86d24f3aa306391b5a993c976 | BetiaZ/FinalProject17 | /game1.py | 17,097 | 4.34375 | 4 | #introduction
print("""ISLAND ADVENTURE
~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~
YOU WAKE UP ON A DESERTED ISLAND. YOUR GOAL IS TO MAKE IT TO THE OTHER SIDE OF THE ISLAND,
WHERE THERE ARE SHIPS THAT CAN TAKE YOU HOME, IN THE SHORTEST AMOUNT OF TIME POSSIBLE.
GOOD LUCK (YOU'RE GONNA NEED IT).""")
#this class stores all the attributes of the character, inputted by the user
#has inventory, health, keeps track of days, and the attribute to walk
class Character(object):
"""Character class"""
# initializing the character
def __init__(self, name):
self.name = name
#storing the inventory in a dictionary
self.inventory = {
'food': 0,
'clothes': 2,
'money': 30}
#starting statuses, a set value before the game starts
self.day = 1
self.distance_left = 10
self.total_distance = 50
self.health = 100
print(f"""Welcome, {name}. You wake up with only the clothes on your back and $30 in your pocket.""")
# if this function is called, the inventory will be printed
def list_inventory(self):
# will be printed in this format using a for loop
for k, v in self.inventory.items():
print(f"""{k} --- {v}""")
# if this function is called, the status will be printed
def list_status(self):
print(f""" \n
Day --- {self.day}
Distance until next checkpoint --- {self.distance_left}
Health --- {self.health} \n
""")
# the character walks forward, and different scenario occurs at each distance
def list_walk(self, miles = 5):
self.distance_left -= miles
self.total_distance -= miles
self.day += 1
#food decreases with each day
if self.inventory['food'] > 0:
self.inventory['food'] -= 2
#health decreases each time you walk
if self.health > 0:
self.health -= 2
print(f"""
Day: {self.day} --- Next Checkpoint in: {self.distance_left} miles
""")
#defining the character
a = Character(input("""What is your name? \n - """))
#Checkpoints (every 10 miles) are stored in a list
checkpoints = [50, 40, 30, 20, 10, 0]
#the first checkpoint is the simplest and allows the user to choose if they want to see their inventory, status, or move forward
def ckpt1():
#The options are chosen by the user and are stored as a variable
#it also turns the user's input into an int (instead of a string) so that it can be used later
b = int(input(f"""What would you like to do?
1. Inventory
2. Status
3. Go forward (miles left: {a.distance_left})\n - """))
#using if and elif statements to have different options and results
if b == 1:
a.list_inventory()
ckpt1()
elif b == 2:
a.list_status()
ckpt1()
elif b == 3:
a.list_walk()
#If the user types in a value that isn't listed, the block of code will repeat instead of having an error
else:
print("""invalid input.""")
ckpt1()
#The function is called once the total distance reaches 50
if a.total_distance == 50:
ckpt1()
#defining the store function, which allows the user to add items to their inventory and decreases their money if they buy something
def store1():
d = int(input("""
1. food --- $1 per pound
2. clothes --- $3 per piece
3. stay overnight --- $10
4. leave the hut \n - """))
#checks the user's input and runs a block of code based on it
if d == 1:
pounds = int(input("How many pounds? (you eat 2 pounds a day; will be rounded to the nearest whole #) \n - "))
#The user chooses amount of food they want to buy, and its cost is calculated automatically
cost_f = pounds * 1
#Also, the amount of food in the inventory is changed based on how much they buy
a.inventory['food'] += pounds
#The cost is subtracted from the amount of money in the inventory
a.inventory['money'] -= cost_f
print(f"""\n You bought {pounds} pounds of food. You now have {a.inventory['money']} dollars.\n """)
#The function also runs again in case you want to buy something else
store1()
elif d == 2:
#Runs the same way as the block of code above, except with clothes
pieces = int(input("How many? (will be rounded to the nearest whole #) \n - "))
cost_c = pieces * 3
a.inventory['clothes'] += pieces
a.inventory['money'] -= cost_c
print(f"""\n You bought {pieces} pieces of clothing. You now have {a.inventory['money']} dollars. \n""")
store1()
elif d == 3 and a.inventory['money'] >= 10:
#If staying overnight, it will be the next day
a.day += 1
#Health is reset to 100 because you rested
a.health = 100
#Costs $10 to stay, so this amount is subtracted from money
a.inventory['money'] -= 10
print(f"""\n You stayed in the sketchy hut overnight. Even though the bed was made of hay, you feel rested.
It is now Day {a.day}. You have {a.inventory['money']} dollars left.\n """)
#prints the player's status automatically to inform them that it is the next day
a.list_status()
a.distance_left = 10
#returns to the ckpt1 function so that the player can still buy anything else they want
ckpt1()
elif d == 3 and a.inventory['money'] < 10:
print("You do not have enough money to do so.")
store1()
elif d == 4:
a.distance_left = 10
a.list_walk()
else:
print("""invalid input. try again \n - """)
store1()
#similar to ckpt1, except that the user has more options
#if they choose to approach the vendor, the store function is called
def ckpt2():
c = int(input("""You approach the edge of the dense forest.
On the outskirts of the trees seems to be a sketchy hut with an old man sitting in a lawn chair outside it.
What do you do?
1. Inventory
2. Status
3. Approach the sketchy vendor
4. Keep on walking - you don't want to cause any trouble \n - """))
if c == 1:
a.list_inventory()
elif c == 2:
a.list_status()
elif c == 3:
print("You slowly walk towards the vendor, and he greets you with a smile.\n 'Would you like to buy something?' he says. 'Here are my prices:'")
#the store function is called, which was created earlier
store1()
elif c == 4:
a.list_walk()
else:
print("""invalid input. try again \n - """)
ckpt2()
while a.total_distance == 45:
print("You have no food and are starving.\nYour health is now 90.")
#health is reset to 90
a.health = 90
#calls the first checkpoint function
ckpt1()
while a.total_distance == 40:
ckpt2()
#checks if total distance is 35 and if the user has food in their inventory - results in diff outcomes
if a.total_distance == 35 and a.inventory['food'] <= 1:
a.distance_left = 0
print("You went too long without food. You have died of starvation. :( \n ***THE END***")
if a.total_distance == 35 and a.inventory['food'] > 1:
ckpt1()
#similar to ckpt1 function, the user can rest this time
def ckpt3():
a.distance_left = 10
d = int(input(f"""
1. Inventory
2. Status
3. Stop to rest
4. Keep going (miles left: {a.distance_left})\n - """))
if d == 1:
a.list_inventory()
ckpt3()
elif d == 2:
a.list_status()
ckpt3()
elif d == 3:
#The user inputs how long they want to rest
days = int(input("How many days?\n - "))
#based on this response, the status is altered
a.day += days
#health increases by 5 each day
a.health += days * 5
print(f"You rested for {days} days. You feel much better and it has gotten warmer.")
#automatically prints status
a.list_status()
ckpt3()
elif d == 4:
a.distance_left = 10
a.list_walk()
else:
print("""invalid input. try again \n - """)
ckpt3()
#Checks the distance and how much food and clothing the user has
if a.total_distance == 30 and a.inventory['clothes'] <= 2 and a.inventory['food'] > 1:
print("""The temperature has dropped over 30 degrees and it has started to snow.
You realize that you are shivering and forgot to buy another piece of clothing, like a jacket, at the vendors hut.
Throughout the course of the day, you develop hypothermia and die. :(
***THE END***""")
#uses if statements to check each one
if a.total_distance == 30 and a.inventory['clothes'] > 2 and a.inventory['food'] <= 1:
print(f"You went too long without food. You have died of starvation. :( \n ***THE END***")
if a.total_distance == 30 and a.inventory['clothes'] > 2 and a.inventory['food'] > 1:
print("""The temperature has dropped over 30 degrees and it has started to snow.
Luckily, you have a warm jacket that you bought from the sketchy vendor.
Even though you are freezing, you are still able to survive.
What would you like to do?""")
a.health -= 10
ckpt3()
#defining a function to be used later
#uses the random module to add variety to the game
#The user chooses what weapon they want to use, and will get a different result each time
#the food is added to their inventory
def hunt():
#importing the random module to be used later on
import random
h = int(input("""Choose your weapon:
1. Bow and Arrows
2. Rifle
3. Knife
4. Sheer luck\n - """))
if h == 1:
#if 1 is typed, the random module will choose a random number between 0 and 15, not including 0
g = random.randint(0,15)
#Based on what random number is chosen, that amount of food is added to inventory
a.inventory['food'] += g
#informs the user of the amount of food collected
print(f"You have chosen to hunt. You have killed a deer and collected {g} pounds of food. Congrats!")
print(f"You now have {a.inventory['food']} pounds of food.")
elif h == 2:
#if 2 is typed, the random module will choose a random number between 0 and 20, not including 0 (increases the chance of getting a higher number)
i = random.randint(0,20)
a.inventory['food'] += i
print(f"You have chosen to hunt. You have killed a deer and collected {i} pounds of food. Congrats!")
print(f"You now have {a.inventory['food']} pounds of food.")
elif h == 3:
#runs the same way as the blocks of code above
j = random.randint(0,10)
a.inventory['food'] += j
print(f"You have chosen to hunt. You have killed a rabbit and collected {j} pounds of food. Congrats!")
print(f"You now have {a.inventory['food']} pounds of food.")
elif h == 4:
#runs the same way as the blocks of code above
k = random.randint(0,5)
a.inventory['food'] += k
print(f"You have chosen to hunt. You have managed to catch a squirrel and collected {k} pounds of food. Congrats!")
print(f"You now have {a.inventory['food']} pounds of food.")
else:
#otherwise, the hunt function is called again
print("""invalid input. try again \n - """)
hunt()
#similar to ckpt1, except there is an option to call the hunt function
def ckpt4():
#resets the distance left to 10, to avoid getting a negative distance left
a.distance_left = 10
e = int(input(f"""
1. Inventory
2. Status
3. Stop to rest
4. Hunt for food
5. Keep going (miles left: {a.distance_left}) \n - """))
if e == 1:
a.list_inventory()
#After the inventory is printed, the ckpt4 function will run again so that the user can choose more than one option at one time
ckpt4()
elif e == 2:
a.list_status()
ckpt4()
elif e == 3:
#the user inputs an amount of days that is used to recalculate the health and day
f = int(input(""""How many days would you like to rest?
Your health will increase by 5 for every night you rest.\n - """))
a.day += f
a.health += f * 5
#informs the user of what they chose
print(f"""You rested for {f} days. You feel ready to continue your journey.""")
a.list_status()
ckpt4()
elif e == 4:
#hunt function is called if the user chooses to do so
hunt()
ckpt4()
#checks to make sure the user has enough food before walking
elif e == 5 and a.inventory['food'] > 1:
a.list_walk()
#if they do not, the game ends
elif e == 5 and a.inventory['food'] <= 1:
print("You have run out of food and come down with dysentery.\n You have died. :(\n ***THE END***")
else:
print("""invalid input. try again \n - """)
ckpt4()
#makes sure the user has food before continuing
if a.total_distance == 25 and a.inventory['food'] <= 1:
print("You went too long without food. You have died of starvation. :( \n ***THE END***")
if a.total_distance == 25 and a.inventory['food'] > 1:
ckpt1()
if a.total_distance == 20 and a.inventory['food'] > 1:
a.distance_left = 10
print(f"""You have made it past the mountain range. Surprisingly, you feel hopeful.
You reach a small clearing in the forest.
You have {a.inventory['food']} pounds of food left. What would you like to do?""")
#calls the ckpt4 function, defined earlier
ckpt4()
if a.total_distance == 20 and a.inventory['food'] <= 1:
#The game ends if the player has no food
print("You have run out of food and come down with dysentery.\n You have died. :(\n ***THE END***")
#user can choose two different options of what to do at the river, with different results
def ckpt5():
l = int(input("""
1. Try to swim across
2. Hop on the rocks all the way across\n - """))
if l == 1:
print("You try to swim across, except you realize that you don't know how to swim. \n You drown. :( \n ***THE END***")
elif l == 2:
print("""You carefully jump from rock to rock. \n Unfortunately, on the last rock, you slip and fall into the cold water. \n
You manage to barely make it to shore, but because the water was so cold you get hypothermia. Your health decreases by 50.""")
a.health -= 50
a.distance_left = 5
a.list_status()
ckpt1()
else:
print("invalid input. try again \n - ")
ckpt5()
#For all the distances following, a different function will run depending on what is in the user's inventory
#I used 'if' and 'and' statements to check what the user has
if a.total_distance == 15 and a.inventory['food'] > 1 and a.health > 0:
ckpt1()
if a.total_distance == 15 and a.inventory['food'] <= 1:
print("You ran out of food and died of starvation. :( \n ***THE END***")
if a.total_distance == 10 and a.inventory['food'] > 1 and a.health > 0:
print("You reach a wide river that is about 6 ft. deep. What do you do?")
ckpt5()
if a.total_distance == 10 and a.inventory['food'] <= 1 and a.health > 0:
print("You reach a river, but you have run out of food. You die of starvation. :( \n ***THE END***")
if a.total_distance == 5 and a.inventory['food'] <= 1 and a.health == 0:
print("Even though you survived the river, you are too weak to continue. You die of hypothermia. :( \n ***THE END***")
if a.total_distance == 5 and a.inventory['food'] > 0 and a.health == 0:
print("Even though you survived the river, you are too weak to continue. You die of hypothermia. :( \n ***THE END***")
if a.total_distance == 5 and a.inventory['food'] <= 1 and a.health > 0:
print("Even though you survived the river, you have run out of food. You die of starvation. :( \n ***THE END***")
if a.total_distance == 5 and a.inventory['food'] > 1 and a.health > 0:
a.distance_left = 5
ckpt1()
if a.total_distance == 0 and a.inventory['food'] > 1 and a.health > 0:
a.distance_left = 0
print(f"""You finally have reached the edge of the forest. You can see a fishing community ahead.
You run up to the docks, and the fisherman there is willing to give you a ride home.
WHOOPTY DOOOOOOOOOOO!!!!
YOU DID IT, {a.name} !!!!!!
YOU SURVIVED!!!!!!!
YOU AIN'T DEDDDDDDD!!!!!!!!
🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
-----------------------------
END RESULTS:
It took you {a.day} days.
Your end health is {a.health}.""")
print("""
RANKINGS:
Days:
Between 10 and 12: Master
Between 13 and 15: Average
Between 16 and 20: Alright
Over 21: Ehhhh
Health:
Between 80-100: Master
Between 50-79: Average
Between 29-49: Alright
Less than 29: Ehhhhh
-----------------------------
Created by: Betia Zeng
End credits: Anonymous Donor
Thanks for playing!""")
|
b288148e339c4022224b898eb9a718d889593083 | KRyan07901/python-challenge | /PyBank/mainbank.py | 670 | 3.71875 | 4 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
with open('budget_data.csv') as file:
csv_reader_object = csv.reader(file)
# Use return number of lines method
csv_reader_object.line_num
# Count # of months
count_of_months = 0
with open('budget_data.csv') as file:
csv_reader_object = csv.reader(file)
if csv.Sniffer().has_header:
next(csv_reader_object)
for row in csv_reader_object:
count_of_months += 1
count_of_months
print("Financial Analysis")
print("----------------------")
print(f"Total Months:",count_of_months)
|
24c460d06a6fc2035d7983b3b71327d8e4e184cf | Jayas234/Project_fILES | /dbsevencode.py | 265 | 3.59375 | 4 | def even(s,n):
i=2
c=0
while(True):
if i%2==0:
print(i,end=" ")
c=c+1
if c==4:
break
i=i+1
s,n=map(int,input().split())
n1=even(s,n)
'''
s=2
n=4
output= 2 4 6 8 '''
|
efad42ddd8ac6f919a359134c7e7301dbedc6bb7 | DevinS73/notes | /twod_lists.py | 804 | 4.375 | 4 |
a=[[1,2,3],
[4,5,6]]
##One way to traverse a 2d list:
#for i in range(len(a)):
# for j in range(len(a[i])):
# print(a[i][j],end=' ')
# print()
##Another way to traverse a 2d list:
def print_2d_list(lst):
for row in lst:
for element in row:
print(element,end=' ')
print()
##Add all elements in 2d list
#sum=0
#for i in range(len(a)):
# for j in range(len(a[i])):
# sum+=a[i][j]
#print(sum)
#sum=0
#for row in a:
# for element in row:
# sum+=element
#print(sum)
##Changing elements in a 2d list:
#for i in range(len(a)):
# for j in range(len(a[i])):
# a[i][j]+=1
#print_2d_list(a)
##Creating a 2d list
#x=[[0]*5]*8 DOES NOT WORK
#x[0][0]=100
#print(x)
#To make an m x n list
m=5
n=8
x=[[0]*n for i in range(m)]
print(x) |
f6cbfb53a059265923d1f438904d704a9df8b822 | yash0024/AutomatedPuzzleSolving | /puzzle.py | 1,299 | 3.78125 | 4 | """
=== Module Description ===
This module contains the abstract Puzzle class.
DO NOT MODIFY ANYTHING IN THIS MODULE.
"""
from __future__ import annotations
from typing import List
class Puzzle:
""""
A full-information puzzle, which may be solved, unsolved,
or even unsolvable. This is an abstract class.
"""
def fail_fast(self) -> bool:
"""
Return True if this Puzzle can never be solved.
Note: fail_fast may return False in some situations where
it can't EASILY be determined that the puzzle has no solution.
But we can override this in a subclass where it can EASILY be
determined that this Puzzle can't be solved.
"""
return False
def is_solved(self) -> bool:
"""
Return True iff this Puzzle is in a solved state.
This is an abstract method that must be implemented
in a subclass.
"""
raise NotImplementedError
def extensions(self) -> List[Puzzle]:
"""
Return a list of legal extensions of this Puzzle.
If this Puzzle has no legal extensions, then an empty list
should be returned.
This is an abstract method that must be implemented
in a subclass.
"""
raise NotImplementedError
|
84792bce9ddfd5deffd08c523a8d33289152693f | deepak00108/coding | /addition of complex | 928 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
#Write your code here
class comp :
def __init__(self,r,i):
self.r = r
self.i = i
def add(self,other) :
other.real2 = real2
other.img2 = img2
c = complex(self.r+other.real2,self.i+other.i)
print("Sum of the two Complex numbers :{}{}{}i".format(int(c.real), "+" ,int(c.imag)))
def sub(self,other) :
x = complex(self.r-other.r,self.i-other.img2)
print("Subtraction of the two Complex numbers :{}{}{}i".format(int(x.real), "+" if x.imag >=0 else "-",abs(int(x.imag))) )
if __name__ == '__main__':
real1 = int(input().strip())
img1 = int(input().strip())
real2 = int(input().strip())
img2 = int(input().strip())
p1 = comp(real1,img1)
p2 = comp(real2,img2)
p1.add(p2)
p1.sub(p2)
|
cb9d299a055e334c6ccac1c69a199f8c0e1e5394 | GPython21/Gayane | /Lesson 3/Lesson3-Ex.1.py | 317 | 4.03125 | 4 | def check_palindrome_1(avtobuska):
reversed_avtobuska = avtobuska[::-1]
status = 1
if (avtobuska != reversed_avtobuska):
status = 0
return status
avtobuska = "fsdfdsf"
status= check_palindrome_1(avtobuska)
if(status == 1):
print("It is a palindrome ")
else:
print("Sorry! Try again")
|
1dad408bc798923b7b1f84375982d203ca1c8fb4 | yunnyang/Practice_Code | /medium/leetCode648.py | 625 | 3.5625 | 4 | # 648. Replace Words
import collections
class Solution:
def replaceWords(self, dict: List[str], sentence: str) -> str:
words = sentence.split(" ")
visited = collections.defaultdict()
for i in range(len(words)):
word = words[i]
if word in visited:
words[i] = visited[word]
else:
for d in dict:
if d in word:
if word.find(d) == 0:
visited[word] = d
words[i] = d
break
return " ".join(words) |
d9c3495132f3f935de1c46b188af433fd39bdc21 | bssrdf/pyleet | /K/KthMissingPositiveNumber.py | 1,958 | 3.828125 | 4 | '''
-Easy-
Given an array arr of positive integers sorted in a strictly increasing
order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...].
The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd
missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
'''
class Solution(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
n = len(arr)
init, missing = 0, 0
for i in range(1, n+1):
if arr[i-1]-i > 0:
missing = arr[i-1]-i
if missing >= k:
return arr[i-2]+k-init if i >= 2 else k-init
init = missing
return arr[-1]+k-missing
def findKthPositiveLogN(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
l, r = 0, len(arr)
while l < r:
mid = (l + r) // 2
# search the last appreance of 'i'
# such that a[i]-i <= k
if arr[mid] - mid > k:
r = mid
else:
l = mid + 1
print(arr[mid], mid, l, r, k)
return r + k
if __name__ == "__main__":
print(Solution().findKthPositive([2,3,4,7,11], 5))
print(Solution().findKthPositive([1,2,3,4], 2))
print(Solution().findKthPositive([1,13,18],17))
print(Solution().findKthPositiveLogN([2,3,4,7,11], 5))
print(Solution().findKthPositiveLogN([1,2,3,4], 2))
print(Solution().findKthPositiveLogN([1,13,18],17)) |
Subsets and Splits