blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
bd55d538be2a352b5cdd11c9736711abafadf681 | Runsheng/rosalind | /REVC.py | 776 | 3.65625 | 4 | #!/usr/bin/env python
'''
Rosalind #: 003
Rosalind ID: REVC
Problem Title: Complementing a Strand of DNA
URL: http://rosalind.info/problems/revc/
'''
def reverse_complement(seq):
"""
Given: A DNA string s of length at most 1000 bp.
Return: The reverse complement sc of s.
due to the complement_map,
the symbol such as \n and something else is illegal
the input need to be pure sequence
"""
complement_map = dict(zip("acgtACGTNn-","tgcaTGCANn-"))
complement=[]
for s in seq:
complement.append(complement_map[s])
reverse=''.join(reversed(complement))
return reverse
if __name__ == '__main__':
with open("./data/rosalind_revc.txt") as input_data:
seq=input_data.read().strip()
print reverse_complement(seq) |
8e0e070279b4e917758152ea6f833a26bc56bad7 | chirag16/DeepLearningLibrary | /Activations.py | 1,541 | 4.21875 | 4 | from abc import ABC, abstractmethod
import numpy as np
"""
class: Activation
This is the base class for all activation functions.
It has 2 methods -
compute_output - this is used during forward propagation. Calculates A given Z
copute_grad - this is used during back propagation. Calculates dZ given dA and A
"""
class Activation(ABC):
@abstractmethod
def compute_output(self, Z):
pass
@abstractmethod
def compute_grad(self, A, dA):
pass
"""
class: Sigmoid
This activation is used in the last layer for networks performing binary classification.
"""
class Sigmoid(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return 1. / (1 + np.exp(-Z))
def compute_grad(self, Y, A, dA):
return dA * A * (1 - A)
"""
class: Softmax
This activation is used in the last layer for networks performing multi-class classification.
"""
class Softmax(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return np.exp(Z) / np.sum(np.exp(Z), axis=0)
def compute_grad(self, Y, A, dA):
return A - Y
"""
class ReLU
This activation is used in hidden layers.
"""
class ReLU(Activation):
def __init__(self):
pass
def compute_output(self, Z):
A = Z
A[Z < 0] = 0
return A
def compute_grad(self, Y, A, dA):
dZ = dA
dZ[A == 0] = 0
return dZ
|
01e8da8327f10fc0e14c8af7832e01bf3e98b429 | Warrlor/Lab3-SP | /1.py | 143 | 3.6875 | 4 | import math
n = int (input('введите n'))
i = 1
p = 1
for i in range (1,n+1):
p = p*i
z = math.pow(2,i)
print (p)
print (z)
|
79516107093e5e469e9c6e55b7ec0b630897133a | BradSegel/stuff | /assignments-master/merge_inverge.py | 1,943 | 4 | 4 |
def merge_sort(unsorted_list):
l = len(unsorted_list)
inversion_count = 0
# here's our base case
if l <= 2:
# make sure our pair is ordered
if l==2 and unsorted_list[0] > unsorted_list[1]:
holder = unsorted_list[0]
unsorted_list[0] = unsorted_list[1]
unsorted_list[1] = holder
inversion_count = 1
return (unsorted_list, inversion_count)
# RECURSE!!
split_idx = l/2
a,a_inversion_count = merge_sort(unsorted_list[:split_idx])
b,b_inversion_count = merge_sort(unsorted_list[split_idx:])
inversion_count = a_inversion_count + b_inversion_count
while b: # we're putting b into a, so we don't want to stop while there's b
for idx, a_val in enumerate(a):
if b:
# when we get to a value in 'a' bigger than b[0]
if a_val > b[0]:
inversion_count = inversion_count + len(a[idx:])
a[idx:idx] = [b.pop(0)]
# b now contains larger values than a
if len(a) == idx + 1:
a.extend(b)
b = None # we want out of this while loop
return (a, inversion_count)
def get_inversion_count(unsorted_list):
i = 0
for idx, elem in enumerate(unsorted_list,1):
for x in unsorted_list[idx:]:
if elem > x: i = i + 1
return i
if __name__ == '__main__':
# import random
# sorter = [int(1000 * random.random()) for i in xrange(1000)]
# print 'before: {}'.format((sorter, get_inversion_count(sorter)))
# print 'result: {}'.format(merge_sort(sorter))
nums = []
with open('IntegerArray.txt', 'r') as f:
nums = [int(x) for x in f.read().split("\r\n") if x ]
print "brute: {}".format(get_inversion_count(nums))
print "merge: {}".format(merge_sort(nums)[1])
# print get_inversion_count(nums)
# print merge_sort(nums)[1]
|
f97b32658a54680d8cbfe95abbfd5612e6d22e4e | ssj9685/lecture_test | /assignment/week3.py | 290 | 4.15625 | 4 | num1=int(input("first num: "))
num2=int(input("second num: "))
print("num1 + num2 = ", num1 + num2)
print("num1 + num2 = ", num1 - num2)
print("num1 + num2 = ", num1 * num2)
print("num1 + num2 = ", num1 / num2)
print("num1 + num2 = ", num1 // num2)
print("num1 + num2 = ", num1 % num2) |
bad0deeb8b06195df2613e16e9ebb96b8f1aa802 | shj2013/python | /while.py | 95 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
n=1
while n<=100:
print(n)
n=n+1
print('end')
|
705dbffc6bf57626c64609337ceb701ed849e66d | ptracton/MachineLearning | /my_notes/python/test_cost_function.py | 260 | 3.65625 | 4 | #! /usr/bin/env python3
import numpy as np
import cost_function
Y_GOLDEN = [0.9, 1.6, 2.4, 2.3, 3.1, 3.6, 3.7, 4.5, 5.1, 5.3]
X = np.arange(0, 10, 1)
my_cost = cost_function.cost_function(X, Y_GOLDEN, (1, 0.5))
print("FOUND: Cost = {:02f} ".format(my_cost))
|
5915dcaf57ad92e9a1f3ad46d00ff7fb4cd54caa | 0ashu0/Python-Tutorial | /Lynda Course/1003_raise Exceptions.py | 613 | 3.9375 | 4 | #def main():
#num = 1
#print("main begins")
#for line in readfile('lines.txt'):
#print('printing {} line'.format(num))
#print(line.strip())
#num = num + 1
#
#
#def readfile(filename):
#fh = open(filename)
#return fh.readlines()
#
#main()
def main():
try:
for line in readfile('lines.txt'):
print(line.strip())
except IOError as e:
print('can not read the file: ', e)
except ValueError as e:
print('wrong filename: ', e)
def readfile(filename):
if filename.endswith('.txt'):
fh = open(filename)
return fh.readlines()
else:
raise ValueError('Filename must end with .txt')
main() |
7fd3e2d847f607001cd5a32f09594d17a5ddde35 | hiEntropy/hex | /hex.py | 424 | 3.609375 | 4 | import sys
'''
'''
def convert(value):
if len(value)==1:
return '%'+hex(ord(value[0]))[2:]
else:
return '%'+hex(ord(value[0]))[2:]+convert(value[1:])
def getArgs(value):
if len(value)==1:
return value[0]
else:
return value[0]+getArgs(value[1:])
def main():
if len(sys.argv[1:])>0:
input_string=getArgs(sys.argv[1:])
print(convert(input_string))
main()
|
e045f34684fc8e3efe153ae84d80e3f4d922dd7f | humanoiA/Python-Practice-Sessions | /day2/ass9.py | 336 | 3.71875 | 4 | a=int(input("Enter Hardness: "))
b=int(input("Enter Carbon Content: "))
c=int(input("Enter Tensile Strength: "))
if a>50 and b<0.7:
print("Grade is 9")
elif c>5600 and b<0.7:
print("Grade is 8")
elif a>50 and c>5600:
print("Grade is 7")
elif a>50 or b<0.7 or c>5600:
print("Grade is 6")
else:
print("Grade is 5") |
27a0944fee14ee315bd5489bcdd980448a65f757 | humanoiA/Python-Practice-Sessions | /day3/ass4.py | 142 | 3.65625 | 4 | str= input("Enter String : ")
ch= input("Enter Char: ")
s1=str[:str.index(ch)+1]
s2=str[str.index(ch)+1:].replace(ch,"$")
str=s1+s2
print(str) |
88fb7e1c3ea8b3eda8a2365688cbd09674bbb6da | humanoiA/Python-Practice-Sessions | /day2/test.py | 218 | 3.828125 | 4 | for i,p in zip(range(5),range(4,0,-1)):
for j in range(i):
print(" ",end=" ")
for k in range(i,3):
print("*",end=" ")
for l in range(p):
print("*",end=" ")
print("") |
8cde9dc4f1f709d9ba50cd1818fa88e06259034a | humanoiA/Python-Practice-Sessions | /day3/ass7.py | 111 | 3.640625 | 4 | str=input("Enter String: ")
if len(str)%4==0:
print(str[-1:-len(str)-1:-1])
else:
print("Length issue") |
8fbd95b0aa93df35f082fbdeba058595acc1a497 | humanoiA/Python-Practice-Sessions | /day1/ass4.py | 85 | 3.625 | 4 | b=int(input("Enter Base: "))
h=int(input("Enter height: "))
print("Area is",0.5*b*h)
|
7ac520284b42d4e0d94a76372028c9c3f781c07f | A01375137/Tarea-02 | /porcentajes.py | 483 | 4 | 4 | #encoding: UTF-8
# Autor: Mónica Monserrat Palacios Rodríguez, A01375137
# Descripcion: Calcular el porcentaje de mujeres y hombres inscritos, calcular la cantidad total de inscritos.
# A partir de aquí escribe tu programa
m_i=int(input("Mujeres inscritas: "))
h_i=int(input("Hombres inscritos: "))
total=(m_i+h_i)
print("Total de inscritos:", total)
porc_m=(m_i*100)/total
print("Porcentaje de mujeres:", porc_m, "%")
porc_h=(h_i*100)/total
print("Porcentaje de hombres:", porc_h, "%")
|
a58875f38dab10aabdd477b5578fda70e9b72187 | alexl0/GIISOF01-2-009-Numerical-Computation | /Lab02/Lab02_Exercise1.py | 653 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Horner for a point
"""
#---------------------- Import modules
import numpy as np
#---------------------- Function
def horner(p,x0):
q = np.zeros_like(p)
q[0] = p[0]
for i in range(1,len(p)):
q[i] = q[i-1]*x0 + p[i]
return q
#----------------------- Data
p = np.array([1, -1, 2, -3, 5, -2])
r = np.array([ 5, -3, 1, -1, -4, 0, 0, 3])
x0 = 1.
x1 = -1.
#------------ Call the function (1)
q = horner(p,x0)
print('Q coefficients = ', q[:-1])
print('P(1) = ', q[-1])
print('\n')
#------------ Call the function (2)
q1 = horner(r,x1)
print('Q1 coefficients = ', q1[:-1])
print('R(-1) = ', q1[-1])
|
1670757f322720abc36337fc9fd70043ed0b532c | alexl0/GIISOF01-2-009-Numerical-Computation | /Lab07/Lab07_Exercise3.py | 1,085 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
second derivative
"""
#---------------------- Import modules
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm
#---------------------- Function
def derivative2(f,a,b,h):
x = np.arange(h,b,h)
d2f = np.zeros_like(x)
k = 0
for x0 in x:
d2f[k] = (f(x0+h) - 2* f(x0) + f(x0-h)) / h**2
k += 1
return x, d2f
#---------------------- Plot
def plotDer2(f,d2f_e,a,b,h):
# derivatives
x, d2f_a = derivative2(f,a,b,h)
#plot
plt.plot(x,d2f_e(x),'y',linewidth=6,label='exact')
plt.plot(x,d2f_a,'b--',label='approximate')
plt.legend()
plt.title(r'Second derivative of $\sin(2 \pi x)$')
plt.show()
# Print error
E = norm(d2f_e(x)-d2f_a)/norm(d2f_e(x))
print('%15s %15s\n' % ('h','E(df_f)'))
print('%15.3f %15.6e\n' % (h,E))
#----------------------- Data
f = lambda x: np.sin(2*np.pi*x)
d2f_e = lambda x: -(2*np.pi)**2 * np.sin(2*np.pi*x)
a = 0.
b = 1.
h = 0.01
#------------ Call the function
plotDer2(f,d2f_e,a,b,h)
#%% |
c87fb20dd1a8a233bcc4178dcd5003ef42821bbe | mikejry/simple-rsa | /primes.py | 1,166 | 4 | 4 | import math
class Prime:
def __init__(self, number):
try:
if self.is_prime(number) is False:
self.primeNumber = 2
else:
self.primeNumber = int(number)
except ValueError:
print("Invalid number")
self.primeNumber = 2
def __mul__(self, other):
multiply = self.primeNumber*other.primeNumber
return multiply
def __sub__(self, other):
substitute = self.primeNumber-other
return substitute
def enter_prime(self):
pierwsza = input("Podaj liczbę pierwszą:")
try:
pierwsza = int(pierwsza)
except ValueError:
print("Invalid number")
return pierwsza
def is_prime(self,num):
num = int(num)
if (num < 2):
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def enter_authenticated(self, num):
while self.is_prime(num) == False:
num = self.enter_prime()
return num
|
325b2b1a929506115bfc63e825c551f1eb21bf3a | carnei-ro/request-logger | /server.py | 3,047 | 3.515625 | 4 | #!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import json
import os
class S(BaseHTTPRequestHandler):
def _set_response(self, length):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header('Content-Length', length)
self.end_headers()
def _process_request(self):
data = ''
if self.headers['Content-Length']:
content_length = int(self.headers['Content-Length'])
data = self.rfile.read(content_length)
data = data.decode('utf-8')
r = {}
r['method']=str(self.command)
r['path']=str(self.path)
r['headers']=dict(self.headers)
r['body']=data
logging.info("\n> Method: %s\n> Version: %s\n> Path: %s\n> Headers:\n%s> Body:\n%s\n",
str(self.command), str(self.request_version), str(self.path), str(self.headers), data)
return r
def do_GET(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_HEAD(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_POST(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_PUT(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_DELETE(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_CONNECT(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_OPTIONS(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_TRACE(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_PATCH(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
|
2fedfa213660d5bca39d1598b8de77fd343082f3 | tangym27/mks66-matrix | /main.py | 7,944 | 4.03125 | 4 | from display import *
from draw import *
from matrix import *
from random import randint
import math
screen = new_screen()
matrix = new_matrix(4,10)
m1 = [[1, 2, 3, 1], [4, 5, 6, 1]]
m2 = [[2, 4], [4, 6], [6, 8]]
A = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
B = [[11,12,13,14],[15,16,17,18],[19,20,21,22],[23,24,25,26]]
print("Printing matrix:")
print("=======================================")
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after multiplication (A x B):")
print("=======================================")
matrix_mult(A,B)
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after multiplication (B x A):")
print("=======================================")
matrix_mult(B,A)
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after ident:")
print("=======================================")
IDENT = ident(new_matrix())
matrix_mult(IDENT, A)
print("Ident:")
print_matrix(IDENT)
print("Matrix A:")
print_matrix(A)
#####################################################################################################################
#just doing this because i didnt want to code too many things haha
#black bars in the top and bottom (game is more rectangle than square)
black = [0,0,0]
color = black
heading = new_matrix()
footer = new_matrix()
i = 0
while ( i < 101 ):
add_point(footer, 0, 500-i)
add_point(footer, 500, 500-i)
add_point(heading, 0, 100-i)
add_point(heading, 500, 100-i)
i += 1
draw_lines(heading, screen, color)
draw_lines(footer, screen, color)
#######################################
#makes the ground
block = new_matrix()
i = 0
while (i < 30):
add_point(block, 0, 120-i)
add_point(block, 500, 120-i)
i += 1
draw_lines(block, screen, [ 230, 100, 25 ])
#######################################
#makes the lines in the ground
lines = new_matrix()
j = 0
i = 1
while (j < 500 ):
if (i%2):
add_edge(lines, j, 0, 0, j , 120, 0)
add_edge(lines, j, 107, 0, j+10, 107, 0)
add_edge(lines, j+10, 0, 0, j+10, 120, 0)
j += 10
else:
add_edge(lines, j, 0, 0, j, 120, 0)
add_edge(lines, j+25, 0, 0, j+25, 120, 0)
j += 25
i +=1
draw_lines(lines, screen, black)
#######################################
#such bad code, sets up all of the elements, edges are the outline of each element (right and left side)
i = 0
angle = 2 * math.pi / 360
center= 145
grass = new_matrix()
edge = new_matrix()
edge2 = new_matrix()
grass2 = new_matrix()
edge3 = new_matrix()
edge4 = new_matrix()
grass3 = new_matrix()
edge0 = new_matrix()
edge1 = new_matrix()
cloud = new_matrix()
edge5 = new_matrix()
edge6 = new_matrix()
cloud2 = new_matrix()
edge7 = new_matrix()
edge8 = new_matrix()
circle = new_matrix()
edge9 = new_matrix()
while (i < 20):
#grasses of randomized length
r = randint(20,40 -i) -i
r1 = randint(20,40 -i) -i
add_edge(grass, 300-r, 120+i, 0, 300+r, 120+i, 0)
add_point(edge, 300-r-1,120+i)
add_point(edge2, 300+r+1,120+i)
add_edge(grass2, 60-r1, 120+i, 0, 60+r1, 120+i, 0)
add_point(edge3, 60-r1-1,120+i)
add_point(edge4, 60+r1+1,120+i)
#green hill (top curve and ..lump)
for n in range(180):
angle = (n * 2 * math.pi )/ 360
dx = int(i * math.cos(angle))
dy = int(i * math.sin(angle))
if (i == 19):
add_edge(edge9, center+dx, center + dy, 0, center + dx+1, center +dy+1, 0)
else:
add_edge(circle, center+dx, center + dy, 0, center + dx+1, center +dy+1, 0)
if (i < 15):
add_edge(grass3, 112+i, 119+i+i, 0, 179-i, 119+i+i, 0)
add_edge(grass3, 112+i, 120+i+i, 0, 179-i, 120+i+i, 0)
add_point(edge0, 112+i, 119+i+i)
add_point(edge1, 179-i, 119+i+i)
add_point(edge0, 112+i, 120+i+i)
add_point(edge1, 179-i, 120+i+i)
#clouds which i was told are just the bushes?!
cloud_height = 335+i
add_edge(cloud, 140-r, cloud_height, 0, 140+r, cloud_height, 0)
add_point(edge5, 140-r-1,cloud_height)
add_point(edge6, 140+r+1,cloud_height)
cloud_height2 = 310+i
add_edge(cloud2, 360-r1, cloud_height2, 0, 360+r1, cloud_height2, 0)
add_edge(cloud2, 390-r1, cloud_height2, 0, 390+r1, cloud_height2, 0)
add_edge(cloud2, 420-r1, cloud_height2, 0, 420+r1, cloud_height2, 0)
add_point(edge7, 360-r1-1,cloud_height2)
add_point(edge8, 420+r1+1,cloud_height2)
i+=1
#semi-circle of the green hill
draw_lines( circle, screen, [5,161,4] )
draw_lines( edge9, screen, black )
#bush1
draw_lines(grass, screen, [189,254,24])
draw_lines(edge, screen, black)
draw_lines(edge2, screen, black)
#bush2
draw_lines(grass2, screen, [189,254,24])
draw_lines(edge3, screen, black)
draw_lines(edge4, screen, black)
#green hill
draw_lines(grass3, screen, [5,161,4])
draw_lines(edge0, screen, black)
draw_lines(edge1, screen, black)
#cloud1
draw_lines(cloud, screen, [251,253,252])
draw_lines(edge5, screen, black)
add_edge(edge6, 120 , 335, 0, 160, 335, 0)
draw_lines(edge6, screen, black)
#cloud2
draw_lines(cloud2, screen, [251,253,252])
draw_lines(edge7, screen, black)
add_edge(edge8, 340 , 310, 0, 440, 310, 0)
draw_lines(edge8, screen, black)
#######################################
# makes that really long four block road
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
count = 0
for j in range(6):
i = 0
while (i <20):
height = 190+i
add_edge(b, 180, height, 0, 200 + count, height, 0)
if ((i%5)== 0):
r = randint(4,16)
add_edge(b1, 180, height, 0 , 200+count, height, 0)
add_edge(b2, 180+count+r, height, 0, 180+count+r, height+5, 0)
i += 1
add_edge(b2, 200+count, 190, 0, 200+count, 210, 0)
count += 20
add_edge(b2, 180, height+1, 0 , 300, height+1, 0)
add_edge(b1, 180, 190, 0, 180, height, 0)
draw_lines(b, screen, [179,91,49])
draw_lines(b1, screen, black)
draw_lines(b2, screen, black)
#######################################
#makes the pipe!
pipe = new_matrix()
edge = new_matrix()
edge2 = new_matrix()
add_edge(edge, 455, 154, 0, 415 , 154, 0)
add_edge(edge, 455, 155, 0, 415 , 155, 0)
add_edge(edge, 455, 170, 0, 415 , 170, 0)
add_edge(edge, 455, 171, 0, 415 , 171, 0)
i = 0
while (i < 50):
startx = 450
endx = 420
y = 120+ i
if (i <= 33):
add_edge(pipe, startx, y, 0, endx, y, 0)
add_point(edge, startx, y)
add_point(edge2, endx,y)
add_point(edge, startx+1, y)
add_point(edge2, endx-1,y)
else:
add_edge(pipe, startx+5, y, 0, endx-5, y, 0)
add_point(edge, startx+5, y)
add_point(edge, startx+6, y)
add_point(edge2, endx-6,y)
add_point(edge2, endx-5,y)
i += 1
draw_lines(pipe, screen, [122,206,14])
draw_lines(edge, screen, black)
draw_lines(edge2, screen, black)
#######################################
#makes the first block
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
while (i <20):
height = 190+i
add_edge(b, 100, height, 0, 120 , height, 0)
if ((i%5)== 0):
r = randint(3,17)
i += 1
add_edge(b1, 100, 190, 0, 100, 210, 0)
add_edge(b1, 100, 210, 0, 120, 210, 0)
add_edge(b1, 100, 190, 0, 120, 190, 0)
add_edge(b1, 120, 190, 0 , 120, 210, 0)
draw_lines(b, screen, [204,78,12])
draw_lines(b1, screen, black)
#######################################
#makes the highest block
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
while (i <20):
height = 260+i
add_edge(b, 230, height, 0, 250 , height, 0)
i += 1
add_edge(b1, 230, 260, 0, 230, height, 0)
add_edge(b1, 250, 260, 0, 250, height, 0)
add_edge(b1, 230, 260, 0, 250, 260, 0)
add_edge(b1, 230, height, 0 , 250, height, 0)
draw_lines(b, screen, [204,78,12])
draw_lines(b1, screen, black)
#######################################
display(screen)
save_extension(screen, 'img.png')
|
f377a1f4fcfd4935fde1612668bf91f07987c9e6 | katesorotos/module2 | /ch11_while_loops/ch11_katesorotos.py | 3,691 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 09:11:36 2018
@author: Kate Sorotos
"""
"""while loops"""
##############################################################################################
### Task 1 - repeated division
x = 33
while x >= 1:
print(x, ':', end='') #end'' is a parameter that prints a space rather than a new line
x = x/2
print(x)#exit the while loop (conditon no longer true)
##############################################################################################
### Task 2 - triangular numbers
def triangularNumber(n):
number = 0
while n > 0:
number = number + n
n = n - 1
print(number)
return number
triangularNumber(3)
##############################################################################################
### Task 2 - factorial numbers
def factorialNumber():
n = int(input("Please enter a number: "))
factorial = 1
while n > 0:
factorial = factorial * n
n = n - 1
print(factorial)
return factorial
factorialNumber()
##############################################################################################
### Task 3 - studnet's marks
def gradingStudentMarks():
mark = 1
while mark > 0:
mark = int(input("Please enter your mark: ")) #user input must be inside while loop otherwise condition is forever true
if mark >= 70:
print("Congratualtions! You got a first class mark.")
elif mark >= 40:
print("Well done! You passed.")
else:
print("Fail.")
gradingStudentMarks()
##############################################################################################
### Task 3 - student's marks
didYouPass = 'yes'
while didYouPass == 'yes':
mark = int(input("Please enter your mark: "))
if mark >= 90:
print("Congratualtions! You got an A*.")
elif mark >= 70:
print("Well done! You got a A.")
elif mark >= 60:
print("You got a B.")
elif mark >= 50:
print("You got a C.")
elif mark >= 40:
print("You got a D.")
else:
print("I'm afraid you did not pass.")
didYouPass = input("Did you pass? ")
##############################################################################################
###Task 4 - using break in while loops to exit
i = 55
while i > 10:
print(i)
i = i * 0.8
if i == 35.2:
break #ends the normal flow of the loop
while True:
askName = input("Please enter your name: ")
if askName == 'done':
break
print("Hi, " + askName.title())
###############################################################################################
### Task 5 & 6 - designing a guessing number game program
from random import randint
def guess(attempts, range):
attempt = 0
max_attempts = 3
player_guess = 1
number = randint(1, range)
print()
print('Welcome to the guessing game! \nYou have ' + str(attempts) + ' attempts to guess a number between 1 and ' + str(range))
print("Can you guess my secret number? ")
while attempt < max_attempts:
attempt += 1
player_guess = int(input("Make a guess: "))
print("Attempts made: " + str(attempt))
print()
print("Result: ")
if player_guess < number:
print("No - Too low!")
elif player_guess > number:
print("No - Too high!")
else:
print("well done! You guessed it!")
break
guess(3, 10)
|
c5749efaac303d2f5d56dfdcaeadbb52869208c1 | katesorotos/module2 | /coding_bat/parrot_trouble.py | 419 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 12:27:13 2018
@author: Kate Sorotos
"""
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.
def parrot_trouble(talking, hour):
if (talking and (hour < 7 or hour > 20)):
return True
else:
return False
|
8a5e362bb9373ae525010647cad68256dd5b5fa6 | katesorotos/module2 | /ch13_oop_project/MovingShapes.py | 2,681 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 17 16:31:34 2018
@author: Kate Sorotos
"""
from shape import *
from pylab import random as r
class MovingShape:
def __init__(self, frame, shape, diameter):
self.shape = shape
self.diameter = diameter
self.figure = Shape(shape, diameter)
self.frame = frame
# self.x = 0
# self.y = 0
### creating random movement in x
self.dx = 5 + 10 * r()
### move in positive and negative directions
if r() < 0.5:
self.dx = 5 + 10 * r()
else:
self.dx = -5 + -10 * r()
### creating random movement in y
self.dy = 5 + 10 * r()
### move in positive and negative directions
if r() < 0.5:
self.dy = 5 + 10 * r()
else:
self.dy = -5 + -10 * r()
# self.goto(self.x, self.y)
### adding random variation for the start positions
self.min_max_start(diameter)
### minimum and maximum start position of x and y
def min_max_start(self, diameter):
diameter_2 = diameter / 2
self.minx = diameter / 2
self.maxx = self.frame.width - (diameter_2)
self.miny = diameter / 2
self.maxy = self.frame.height - (diameter_2)
self.x = self.minx + r () * (self.maxx - self.minx)
self.y = self.miny + r () * (self.maxy - self.miny)
def goto(self, x, y):
self.figure.goto(x, y)
def moveTick(self):
### hitting the wall
if self.x <= self.minx or self.x >= self.maxx:
self.dx = (self.dx) * -1
if self.y <= self.miny or self.y >= self.maxy:
self.dy =- self.dy
self.x += self.dx
self.y += self.dy
self.figure.goto(self.x, self.y)
### squares vs diamonds vs circles
class Square(MovingShape):
def __init__(self, frame, diameter):
MovingShape.__init__(self, frame, 'square', diameter)
class Diamond(MovingShape):
def __init__(self, frame, diameter):
MovingShape.__init__(self, frame, 'diamond', diameter)
def min_max_start(self, diameter):
diameter_2 = diameter * 2
self.minx = diameter / 2
self.maxx = frame.width - (diameter_2)
self.miny = diameter / 2
self.maxy = frame.height - (diameter_2)
min_max_start(self, diameter)
class Circle(MovingShape):
def __init__(self, frame, diameter):
MovingShape.__init__(self, frame, 'circle', diameter)
|
414745764aaa0191a4fbc6d86171e3ec14660124 | simonhej1/So4 | /Integral.py | 1,694 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import sympy as sy
import tkinter as tk
from tkinter import ttk
#a = float(input("hvad er a?:"))
#b = float(input("hvad er b?:"))
#c = float(input("hvad er c?:"))
#x = np.linspace(a, b, 100)
#y = np.sin(x)
#plt.figure()
#plt.plot(x, y)
#plt.show()
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
# create widgets
self.Inteknap = tk.Button(text = "Integralregning", command =self.calcInt)
self.Difknap = tk.Button(text = "Differentialregning", command =self.calcDif)
# place widgets
self.Inteknap.pack(side="right")
self.Difknap.pack(side="left")
def calcDif(self):
polynomial = input("To what degree?\n> ")
polynomial = int(polynomial)
if polynomial == 2:
xPower = polynomial
xPowerCoefficient = int(input("What is the coefficient of x^n?"))
xCoefficient = int(input("What is the coefficient of x?"))
newXPower = xPower - 1
newXCoefficient = xCoefficient * xPower
newXPower = str(newXPower)
newXCoefficient = str(newXCoefficient)
equation = newXCoefficient + "x" + newXPower + "+"
elif polynomial == 3:
pass
elif polynomial == 4:
pass
def calcInt(self):
pass
#create app
root = tk.Tk()
root.geometry("225x240")
app = Application(master=root)
app.master.frame()
app.master.title("Dif+Int Regning")
#start app
app.mainloop() |
130f6fcd0668496d386c59b445165adf369c44c0 | fsc2016/LeetCode | /code/36_二叉树最小深度.py | 2,126 | 3.671875 | 4 | '''
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
111. 二叉树的最小深度
'''
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self,root: TreeNode) -> int:
'''
dfs
:return:
'''
def recu(root):
if not root:
return 0
if not root.left and not root.right:
return 1
mindepth=float('inf')
if root.left:
mindepth = min(mindepth,self.minDepth(root.left))
if root.right:
mindepth = min(mindepth, self.minDepth(root.right))
return mindepth+1
return recu(root)
def minDepth2(self, root: TreeNode) -> int:
'''
bfs
'''
if not root:
return 0
dq = deque()
dq.append([root, 1])
while dq:
tmp, depth = dq.popleft()
if not tmp.left and not tmp.right:
return depth
if tmp.left:
dq.append([tmp.left, depth + 1])
if tmp.right:
dq.append([tmp.right, depth + 1])
return 0
'''
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
剑指 Offer 55 - I. 二叉树的深度
'''
def maxDepth2(self, root: TreeNode) -> int:
if not root:
return 0
dq = deque()
dq.append([root,1])
maxdepth = float('-inf')
while dq:
node,depth =dq.popleft()
maxdepth = max(maxdepth,depth)
if node.left:
dq.append([node.left,depth+1])
if node.right:
dq.append([node.right, depth + 1])
return maxdepth
|
316fbc12929968851b0b6e4f8054e0c0ef182428 | fsc2016/LeetCode | /code/3_三数之和.py | 1,340 | 3.59375 | 4 | '''
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
'''
from typing import *
def threeSum(nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []
if not nums or n<3:
return []
# 进行排序
nums.sort()
for i in range(n):
if nums[i] > 0:
return res
# 过滤重复元素
# if i > 0 and nums[i] == nums[i-1]:
# continue
left = i+1
right = n-1
while left < right:
if (nums[i] + nums[left] + nums[right]) == 0:
res.append((nums[i],nums[left],nums[right]))
# 过滤重复元素
# while left < right and nums[left] == nums[left+1]:
# left +=1
# while left < right and nums[right] == nums[right-1]:
# right-=1
left +=1
right -=1
elif (nums[i] + nums[left] + nums[right])>0:
right -=1
else:
left+=1
return res
if __name__ == '__main__':
print(set(threeSum([-1,0,1,2,-1,-4])))
print(threeSum([0,0,0]))
|
1d8035d57a12007ed578bd052f8b140e1db527c3 | fsc2016/LeetCode | /11_bfs_dfs.py | 3,087 | 3.625 | 4 | from collections import deque
class Graph:
def __init__(self,v):
# 图的顶点数
self.num_v = v
# 使用邻接表来存储图
self.adj = [[] for _ in range(v)]
def add_edge(self,s,t):
self.adj[s].append(t)
self.adj[t].append(s)
def _generate_path(self, s, t, prev):
'''
打印路径
:param s:
:param t:
:param prev:
:return:
'''
if prev[t] or s != t:
yield from self._generate_path(s, prev[t], prev)
yield str(t)
def bfs(self,s,t):
'''
广度优先
:param s: 起始节点
:param t: 终止节点
:return:
visited 是用来记录已经被访问的顶点,用来避免顶点被重复访问。如果顶点 q 被访问,那相应的 visited[q]会被设置为 true。
queue 是一个队列,用来存储已经被访问、但相连的顶点还没有被访问的顶点
prev 用来记录搜索路径。当我们从顶点 s 开始,广度优先搜索到顶点 t 后,prev 数组中存储的就是搜索的路径
'''
if s == t : return
visited = [False] * self.num_v
visited[s] = True
prev = [None] * self.num_v
q = deque()
q.append(s)
while q :
w = q.popleft()
# 从邻接表中查询
for neighbour in self.adj[w]:
# 没访问过就访问这个节点,并且加入路径
if not visited[neighbour]:
prev[neighbour] = w
if neighbour == t:
print("->".join(self._generate_path(s, t, prev)))
return
# 当前节点不是,就把节点加入已访问节点列表
visited[neighbour] = True
q.append(neighbour)
def dfs(self,s,t):
'''
深度优先
采用回溯算法的思想,采用递归来实现
:param s: 起始节点
:param t: 终止节点
:return:
'''
found = False
visited = [False] * self.num_v
prev = [None] * self.num_v
def _dfs(from_vertex):
nonlocal found
if found :return
# 当前节点不是终结点,就不停往下一层探寻
visited[from_vertex] = True
if from_vertex == t:
found = True
return
for neighbour in self.adj[from_vertex]:
if not visited[neighbour]:
prev[neighbour] = from_vertex
_dfs(neighbour)
_dfs(s)
print("->".join(self._generate_path(s, t, prev)))
if __name__ == "__main__":
graph = Graph(8)
graph.add_edge(0, 1)
graph.add_edge(0, 3)
graph.add_edge(1, 2)
graph.add_edge(1, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 4)
graph.add_edge(4, 5)
graph.add_edge(4, 6)
graph.add_edge(5, 7)
graph.add_edge(6, 7)
graph.bfs(0, 7)
graph.dfs(0, 7) |
3dd1c0e006ed59e45039c4b49124ec3307aef4f8 | fsc2016/LeetCode | /code/22_数据流中第K大元素.py | 2,337 | 4.03125 | 4 | '''
设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
链接:https://leetcode-cn.com/problems/kth-largest-element-in-a-stream
'''
from typing import *
from heapq import *
import heapq
class KthLargest:
'''
数组法
# '''
# def __init__(self, k: int, nums: List[int]):
# self._nums = nums
# self._k = k
#
# def add(self, val: int) -> int:
# self._nums.append(val)
# self._nums.sort()
# return self._nums[-self._k]
'''
堆
'''
def __init__(self, k: int, nums: List[int]):
self._nums = nums
heapq.heapify(self._nums)
self._k = k
while len(self._nums) > k:
heapq.heappop(self._nums)
def add(self, val: int) -> int:
heapq.heappush(self._nums,val)
if len(self._nums) > self._k:
heapq.heappop(self._nums)
return self._nums[0]
# def __init__(self, k, nums):
# """
# :type k: int
# :type nums: List[int]
# """
# self.k = k
# self.nums = nums
# heapify(self.nums)
# while len(self.nums) > self.k: # cut heap to size:k
# heappop(self.nums)
#
# def add(self, val):
# """
# :type val: int
# :rtype: int
# """
# if len(self.nums) < self.k:
# heappush(self.nums, val)
# heapify(self.nums) # cation
# else:
# top = float('-inf')
# if len(self.nums) > 0:
# top = self.nums[0]
# if top < val:
# heapreplace(self.nums, val)
# return self.nums[0]
if __name__ == '__main__':
arr=[4,5,8,2]
kth = KthLargest(3,arr)
print(kth.add(3))
print(kth.add(5))
print(kth.add(10)) |
7b376a84ba18c6c6da384100816e6c205980f42d | fsc2016/LeetCode | /code/19_最大子序和.py | 867 | 3.78125 | 4 | '''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
'''
from typing import *
def maxSubArray(nums: List[int]) -> int:
'''
动态规划
:param nums:
:return:
'''
# n = len(nums)
# dp = [float('-inf')] * n
# dp[0] = nums[0]
# for i in range(1,n):
# dp[i] = max(dp[i-1]+nums[i],nums[i])
# return max(dp)
# 优化空间复杂度
n = len(nums)
pre_num = nums[0]
best_num = nums[0]
for i in range(1, n):
pre_num = max(pre_num + nums[i], nums[i])
best_num = max(best_num,pre_num)
return best_num
if __name__ == '__main__':
l =[-2,1,-3,4,-1,2,1,-5,4]
print(maxSubArray(l))
|
50df31500f9c57e0e829ea163af7987b93992705 | fsc2016/LeetCode | /code/24_包含min函数的栈.py | 1,935 | 4.09375 | 4 | '''
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
'''
class MinStack:
'''
辅助栈是严格有序的
'''
def __init__(self):
"""
initialize your data structure here.
"""
self.l = []
self.deque=[]
def push(self, x: int) -> None:
self.l.append(x)
if self.deque:
for i in range(len(self.deque)):
if self.deque[i] < x:
self.deque.insert(i,x)
return
self.deque.append(x)
def pop(self) -> None:
popnum=self.l.pop()
self.deque.remove(popnum)
def top(self) -> int:
return self.l[-1]
def min(self) -> int:
return self.deque[-1]
class MinStack1:
'''
非严格有序
'''
def __init__(self):
"""
initialize your data structure here.
"""
self.l = []
self.deque=[]
def push(self, x: int) -> None:
self.l.append(x)
if not self.deque or self.deque[-1] > x:
self.deque.append(x)
def pop(self) -> None:
if self.l.pop() == self.deque[-1]:
self.deque.pop()
def top(self) -> int:
return self.l[-1]
def min(self) -> int:
return self.deque[-1]
if __name__ == '__main__':
minStack = MinStack1()
minStack.push(-2)
minStack.push(0)
minStack.push(-1)
print(minStack.deque)
print(minStack.min())
print(minStack.top())
minStack.pop()
print(minStack.min())
|
13ab84b16c74da6f7f93a033dfb9b2f7c89dab6d | darshanrk18/Algorithms | /CountInversions.py | 903 | 3.828125 | 4 | import random
def merge(A,B):
(C,m,n)=([],len(A),len(B))
(i,j,c)=(0,0,0)
while i+j<m+n:
if i==m:
C.append(B[j])
j+=1
elif j==n:
C.append(A[i])
i+=1
elif A[i]<=B[j]:
C.append(A[i])
i+=1
else:
C.append(B[j])
j+=1
c+=len(A)-i
return (C,c)
def mergesort(A,left,right):
if right-left<=1:
return (A[left:right],0)
mid=(left+right)//2
(L,ca)=mergesort(A,left,mid)
(R,cb)=mergesort(A,mid,right)
(res,c)=merge(L,R)
c+=ca+cb
return (res,c)
'''print("Enter the list of elements to be sorted: ",end=' ')
A=[int(x) for x in input().split()]'''
A=[random.randint(1,50) for x in range(1,10)]
print("List:",A)
(A,c)=mergesort(A,0,len(A))
print("Sorted list:")
for i in A:
print(i,end=' ')
print("\nNo. of inversions:",c)
|
d359233240850fbff418284686c8e92a27397b62 | darshanrk18/Algorithms | /BucketSort.py | 1,779 | 3.90625 | 4 | import math
import string
import random
DEFAULT_BUCKET_SIZE = 5
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
while i>0 and arr[i]<arr[i-1]:
(arr[i-1],arr[i],i)=(arr[i],arr[i-1],i-1)
def sort(array, bucketSize=DEFAULT_BUCKET_SIZE):
f=0
if type(array)==str:
f=1
array=[ord(x) for x in array]
if len(array) == 0:
return array
# Determine minimum and maximum values
minValue = array[0]
maxValue = array[0]
for i in range(1, len(array)):
if array[i] < minValue:
minValue = array[i]
elif array[i] > maxValue:
maxValue = array[i]
# Initialize buckets
bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
buckets = []
for i in range(0, bucketCount):
buckets.append([])
#Distribute input array values into buckets
for i in range(0, len(array)):
buckets[math.floor((array[i] - minValue) / bucketSize)].append(array[i])
#Sort buckets and place back into input array
array = []
for i in range(0, len(buckets)):
insertionSort(buckets[i])
for j in range(0, len(buckets[i])):
array.append(buckets[i][j])
if f:
for i in range(len(array)):
print(chr(array[i]),end=' ')
else:
for i in range(0, len(array)):
print(array[i],end=' ')
c=int(input("1.Str input\n2.Int input\n3.Float input\nEnter your choice: "))
if c==1:
l=[random.choice(string.ascii_uppercase) for x in range(10)]
elif c==2:
l=[random.randint(1,100) for x in range(10)]
else:
l=[float('%.2f'%random.uniform(1,3)) for x in range(10)]
print("Initial list:",l)
print("SORTED LIST".center(51,'*'))
sort(l)
print()
|
e8da0a9a73fd0c0e29eb137c4c842bd002068081 | techphenom/casino-games | /blackjackTable.py | 4,706 | 3.75 | 4 | from random import shuffle
class Card(object):
def __init__(self, rank, suit, value, sort):
self.rank = rank
self.suit = suit
self.value = value
self.sort = sort
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
class Deck(object):
#A deck made of 52 cards.
suits = 'spades diamonds clubs hearts'.split()
ranks = [str(num) for num in range(2,11)] + list('JQKA')
values = dict(zip(ranks, [x for x in range(2,11)] + [10,10,10,11]))
def __init__(self):
self.cards = [Card(rank, suit, self.values[rank], self.values[rank]) for rank in self.ranks
for suit in self.suits]
def __getitem__(self, index):
return self.cards[index]
def __len__(self):
return len(self.cards)
def shuffle(self):
#Pick up (reset) the cards and reshuffle.
self.cards = [Card(rank, suit, self.values[rank], self.values[rank]) for rank in self.ranks
for suit in self.suits]
shuffle(self.cards)
def dealCard(self):
return self.cards.pop(0)
class Hand(object):
def __init__(self):
self.contents = []
def __len__(self):
return len(self.contents)
def __str__(self):
return ', '.join([str(x) for x in self.contents])
def hit(self, card):
self.contents.append(card)
def getHandValue(self):
'''
Sums the values of the cards in the hand.
Does a check to assign either 11 or 1 to Ace.
'''
count = 0
for card in sorted(self.contents, key=lambda card: card.sort):
if card.rank == 'A':
if count <= 10:
card.value = 11
else:
card.value = 1
count += card.value
return count
def checkIfOver(handTotal):
return handTotal > 21
def checkIfBlackjack(handTotal):
return handTotal == 21
def checkWhoWon(dealer, player):
if dealer.getHandValue() > player.getHandValue():
return dealer
if dealer.getHandValue() == player.getHandValue():
return None
else:
return player
def main(player):
print("\nWelcome to the Blackjack Table, {}.".format(player.getName()))
while True:
loser = False
print("Your bankroll = ${}".format(player.getBankroll()))
bet = int(input("Please place a bet: "))
if bet > player.getBankroll():
print("Current bankroll = {}. You don't have enough to cover that bet.".format(player.getBankroll()))
continue
player.decreaseBankroll(bet)
deck = Deck()
deck.shuffle()
playerHand = Hand()
playerHand.hit(deck.dealCard())
playerHand.hit(deck.dealCard())
dealerHand = Hand()
dealerHand.hit(deck.dealCard())
print("Dealer's up card - {}".format(dealerHand))
dealerHand.hit(deck.dealCard())
#Check if either Player or Dealer has a Blackjack
if checkIfBlackjack(playerHand.getHandValue()) and checkIfBlackjack(dealerHand.getHandValue()):
print("Both player and dealer have Blackjack! Tie")
continue
elif checkIfBlackjack(playerHand.getHandValue()):
print("Player has Blackjack! Player wins 3 to 2")
player.increaseBankroll(bet*1.5)
elif checkIfBlackjack(dealerHand.getHandValue()):
print("I'm sorry Dealer has Blackjack. You lose.")
continue
#Player's turn
while True:
print("Your cards- {}".format(playerHand))
print("You have {}".format(playerHand.getHandValue()))
playOrStay = input("Would you like to hit(h) or stay(s)? ")
if playOrStay == 'h':
playerHand.hit(deck.dealCard())
if checkIfOver(playerHand.getHandValue()):
loser = True
break
elif playOrStay == 's':
break
else:
print("Not valid input. Type 'h' to hit or 's' to stay.")
while dealerHand.getHandValue() < 17:
dealerHand.hit(deck.dealCard())
#Determine the winner
if loser:
print("I'm sorry, you went over.")
else:
if checkIfOver(dealerHand.getHandValue()):
print("Dealer broke. You win")
player.increaseBankroll(bet*2)
else:
winner = checkWhoWon(dealerHand, playerHand)
if winner == playerHand:
print("Dealer's cards: {}".format(dealerHand))
print("Your total = {}, dealer's total = {}. You win!".format(playerHand.getHandValue(),dealerHand.getHandValue()))
player.increaseBankroll(bet*2)
elif winner == None:
print("Dealer's cards: {}".format(dealerHand))
print("Your total = {}, dealer's total = {}. Tie!".format(playerHand.getHandValue(),dealerHand.getHandValue()))
player.increaseBankroll(bet)
else:
print("Dealer's cards: {}".format(dealerHand))
print("Your total = {}, dealer's total = {}. You lost :(".format(playerHand.getHandValue(),dealerHand.getHandValue()))
keepPlaying = input("Would you like to keep playing? (y or n) ")
if keepPlaying.lower() == 'n':
break
print("Thank you for playing. See you again soon!")
if __name__ == '__main__':
print("Please run the Casino.py file")
|
291abeb393225f43250c332941419b41c2c6a791 | hjpcs/sort_and_search | /algorithm/bubble_sort.py | 581 | 3.796875 | 4 | from algorithm.generate_random_list import generate_random_list
import timeit
# 冒泡排序
def bubble_sort(l):
length = len(l)
# 序列长度为length,需要执行length-1轮交换
for x in range(1, length):
# 对于每一轮交换,都将序列中的左右元素进行比较
# 每轮交换当中,由于序列最后的元素一定是最大的,因此每轮循环到序列未排序的位置即可
for i in range(0, length-x):
if l[i] > l[i + 1]:
temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
|
c02250cb32fdc76bfc9b156893925fa852cafc8f | Robert66764/Task-Manager | /task_manager.py | 5,323 | 4 | 4 | #Displaying a message and prompting the user for information.
print('Welcome to the Task Manager.\n ')
usernames = input('Please enter Username: ')
passwords = input('Please enter Password: ')
#Opening the text file and splitting the username and password.
userfile = open ('user.txt', 'r+')
uselist = userfile.readlines()
usernameList = [us.split(', ')[0] for us in uselist]
userpasswordList = [us.strip('\n').split(', ')[1] for us in uselist]
#Creating a while loop for the login and password credntials as well as an error message if the username is already in the user.txt file.
while 1:
if usernames in usernameList:
login = False
for usnum, usn in enumerate(usernameList):
if usn == usernames and userpasswordList[usnum] == passwords:
print('You are successfully logged in.')
login = True
break
if login:
break
else:
print('Error: Please try again. ')
usernames = input('Please enter Username: ')
passwords = input('Please enter Password: ')
#Creating a while loop and an if statement to check if the user entered the correct information.
while 1:
#Displaying the various options to the user.
if usernames == 'admin':
user_select = input('''Please select one of the following options:
r - register user
a - add task
va - view all tasks
vm - view my tasks
s - statistics
e - exit
\n
''')
else:
user_select = input('''Please select one of the following options:
r - register user
a - add task
va - view all tasks
vm - view my tasks
e - exit
\n
''')
#If the user selected 'r' then the following menu will display for further information from the user.
if user_select == 's':
task_text = open('tasks.txt','r')
user_text = open('user.txt','r')
num = 0
count = 0
for i in task_text:
total_task = 1
print('This is the total number of tasks: ' + str(total_task))
for i in user_text:
total_user = 1
print('This is the total number of users: ' + str(total_user))
#If the user selected 'r' then the following menu will display for further information from the user.
if user_select == 'r':
user_input_username = input('Please enter a username: ')
while user_input_username in usernameList:
print("user already exist.")
user_input_username = input('Please enter a username: ')
user_input_password = input('Please enter a password: ')
user_input_confirm_password = input('Please confirm password: ')
#Writing to the text file
if user_input_password == user_input_confirm_password:
userfile.write(user_input_username + ", " + user_input_password + "\n")
userfile.close()
elif user_input_password != user_input_confirm_password:
print("Error: Please try again.")
#If the user chooses 'a' the following will be executed.
if user_select == 'a':
task_text = open('tasks.txt','r+')
username_input = input('Please enter a username. ')
user_task = input('Please enter the title of the task. ')
user_description_task = input('Please give a description of the task. ')
user_due_date = input('Please provide the due date of the task. ')
#Importing a module to give the current date and writing to the text file.
from datetime import date
user_date = str(date.today())
task_text.write(username_input + ", " + user_task + ", " + user_description_task + ", " + user_due_date + ", " + user_date)
task_text.close()
#If the user selects va from the menu the following will happen.
if user_select == 'va':
task_file = open('tasks.txt','r')
for i in task_file:
i.split(", ")
split_i = i.split(", ")
print('Task ' + split_i[1])
print('Assigned to: ' + split_i[0])
print('Date assigned: ' + split_i[4])
print('Due date: ' + split_i[3])
print('Task Completed: No')
print('Task Description: ' + split_i[2])
#If the user selects vm the following will happen.
if user_select == 'vm':
task_file = open('tasks.txt','r')
for i in task_file:
i.split(", ")
split_i = i.split(", ")
if usernames == split_i[0]:
i.split(", ")
split_i = i.split(", ")
print('Task ' + split_i[1])
print('Assigned to ' + split_i[0])
print('Date assigned: ' + split_i[4])
print('Due date: ' + split_i[3])
print('Task Completed: No')
print('Task Description: ' + split_i[2])
#If the user selects e the while loop is discontinued.
if user_select == 'e':
break
break
|
c6751727d0f6b20e1505c9007f2543a1f3fe108d | JeffCX/LadBoyCoding_leetcode_solution | /DFS/lc_261_graph_valid_tree.py | 1,132 | 3.578125 | 4 | class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
# Create Graph
graph_dic = {}
for start,end in edges:
if start not in graph_dic:
graph_dic[start] = [end]
else:
graph_dic[start].append(end)
if end not in graph_dic:
graph_dic[end] = [start]
else:
graph_dic[end].append(start)
# DFS to detect cycles
visited = set()
stack = [(0,-1)]
while stack:
node, parent = stack.pop()
visited.add(node)
if node in graph_dic:
for next_node in graph_dic[node]:
if next_node not in visited:
stack.append((next_node, node))
else:
if next_node != parent:
return False
# check if we can traverse all node
if len(visited) != n:
return False
return True |
98de35a03755ceac1e2917c645df12a5997488cf | JeffCX/LadBoyCoding_leetcode_solution | /BinarySearch/lc_33_search_a_rotatedSorted_array.py | 1,143 | 3.609375 | 4 | class Solution:
def search(self, nums: List[int], target: int) -> int:
"""
O(logn)
"""
if not nums:
return -1
# 1. find where it is rotated, find the smallest element
left = 0
right = len(nums) - 1
while left < right:
middle = left + (right - left) // 2
if nums[middle] > nums[right]:
left = middle + 1
else:
right = middle
# find which side we need to binary search
start = left
left = 0
right = len(nums) - 1
if target >= nums[start] and target <= nums[right]:
left = start
else:
right = start
# standard binary search
while left <= right:
middle = left + (right - left) // 2
if nums[middle] == target:
return middle
elif nums[middle] > target:
right = middle - 1
else:
left = middle + 1
return -1 |
418eb29659e375a2c38a3a478791ab71418eec17 | Flood-ctrl/mult_table | /mult_table.py | 2,485 | 3.703125 | 4 | #!/usr/bin/env python3
import sys, getopt, random
elementes = (2, 3, 4, 5, 6, 7, 8, 9)
wrong_answers = 0
re_multiplicable = None
re_multiplier = None
start_multiplicable = int(0)
test_question = int(0)
attempts = len(elementes)
passed_questions = list()
input_attempts = None
input_table = None
# Validate input arguments
try:
opts, args = getopt.getopt(sys.argv[1:],"h:a:t:")
except getopt.GetoptError:
print (f'{sys.argv[0]} -a <attempts> -t <table>')
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
sys.exit(0)
sys.exit(2)
for opt, arg in opts:
if opt == "-h" or opt == "--help":
print (f'{sys.argv[0]} -a <attempts> -t <table>')
sys.exit(0)
elif opt in ("-a", "--attempts"):
try:
input_attempts = int(arg)
except ValueError:
print("Only numbers are allowed")
sys.exit(2)
elif opt in ("-t", "--table"):
try:
input_table = int(arg)
if not 2 <= input_table <= 9:
print("Tables (-t) allowed: [2 3 4 5 6 7 8 9]")
sys.exit(2)
except ValueError:
print("Only numbers are allowed")
sys.exit(2)
if input_table is not None:
start_multiplicable = int(input_table)
if input_attempts is not None:
attempts = int(input_attempts)
while test_question < attempts:
if start_multiplicable != 0:
multiplicable = start_multiplicable
multiplier = random.choice(elementes)
else:
multiplicable = random.choice(elementes)
multiplier = random.choice(elementes)
if re_multiplicable is not None:
multiplicable = re_multiplicable
multiplier = re_multiplier
re_multiplier = None
re_multiplicable = None
else:
string_number = str(multiplicable) + str(multiplier)
if string_number in passed_questions:
#print(f"Duplicate - {string_number}")
continue
result = multiplicable * multiplier
print(f"{multiplicable} x {multiplier} =", end=' ')
try:
input_result = int(input())
except ValueError:
print("Only numbers allowed")
re_multiplicable = multiplicable
re_multiplier = multiplier
continue
if input_result != result:
print(f"Wrong answer, correct - {multiplicable} x {multiplier} = {result}")
wrong_answers += 1
passed_questions.append(string_number)
test_question += 1
print(f"Wrong answers - {wrong_answers}") |
9cd79796786856ba4c4340a48a69f6110dc14a0c | mzmudziak/Programowanie-wysokiego-poziomu | /zajecia_9/zadanie_2.py | 282 | 3.609375 | 4 | import pdb
name = raw_input("Podaj imie: ")
surname = raw_input("Podaj nazwisko: ")
age = raw_input("Podaj wiek: ")
pdb.set_trace()
if age > 18:
ageMessage = 'PELNOLETNI'
else:
ageMessage = 'NIEPELNOLETNI'
print 'Czesc ' + name + ' ' + surname + ', jestes ' + ageMessage |
97a50afd5c942342feb0dbed098807615bf379eb | mzmudziak/Programowanie-wysokiego-poziomu | /zajecia_3/teoria.py | 1,171 | 3.921875 | 4 | # klasy
class Klasa:
def function(self):
print 'metoda'
self.variable = 5
print self.variable
def function2(self, number):
self.function()
print number
obiekt = Klasa()
obiekt.function2(100)
class Klasa2:
atrr1 = None
__attr2 = None
def setAttr2(self, zmienna):
self.__attr2 = zmienna
def setAttr3(self, zmienna):
self.attr3 = zmienna
def add(self):
return self.attr1 + self.__attr2 + self.attr3
obiekt = Klasa2()
obiekt.attr1 = 4
obiekt.setAttr2(5)
obiekt.setAttr3(10)
print obiekt.add()
obiekt.__attr2 = 100
# dziedziczenie
class Car(object):
color = None
def setColor(self, color):
self.color = color
class PersonalCar(Car):
brand = 'Mercedes'
def setBrandAndColor(self, brand, color):
self.brand = brand
super(PersonalCar, self).setColor(color)
car = PersonalCar()
car.setBrandAndColor('Audi', 'niebieski')
print car.color + ' ' + car.brand
class A:
def __init__(self, zmienna):
self.zmienna = zmienna
def __add__(self, other):
return self.zmienna + other.zmienna
print A(5) + A(10)
|
1bfbc576fa5700f11711f258fb1e3f263d487eae | viharika-22/Python-Practice | /Problem-Set-5/13delcons.py | 189 | 3.78125 | 4 | s=list(input())
l=[]
for i in range(len(s)):
if s[i]=="i" or s[i]=="o" or s[i]=="a" or s[i]=="e" or s[i]=="u":
l.append(s[i])
else:
continue
print("".join(l)) |
7970d490d049a731b124994c9bec798830fd5732 | viharika-22/Python-Practice | /PlacementPractice/12.py | 118 | 3.765625 | 4 | str1="Gecko"
str2="Gemma"
for i in range(len(str1)):
if str1[i]==str2[1]:
print(str1.index(str1[i]))
|
8b822102bc23c07c004987c17718d9ba22347b48 | viharika-22/Python-Practice | /Problem-Set-5/new.py | 80 | 3.625 | 4 | s=input()
s1=""
for i in range(len(s)):
s1=s1+s[i]+"-"
print(s1)
|
0019a653229486d697e69a5a40519ccfa6e93503 | viharika-22/Python-Practice | /Problem Set-1/prob5.py | 153 | 3.828125 | 4 | n=str(input())
li=[]
for i in n:
li.append(i)
if li[::]==li[::-1]:
print("yes it is palindrome ")
else:
print("it isn't palindrome")
|
0b0a7902a8f300b3d73f77ae959ec938250e1744 | viharika-22/Python-Practice | /Problem-Set-5/5dectobinary.py | 82 | 3.5 | 4 | def db(n):
if n>1:
db(n//2)
print(n%2,end='')
db(int(input())) |
6782b6a51666db9062c5446b18dd229aa71041b3 | viharika-22/Python-Practice | /PlacementPractice/11.py | 108 | 3.953125 | 4 | n=input()
if n[::]==n[::-1]:
print("it is a palindrome")
else:
print("it is not a palindrome")
|
51632d0bba9edb151cff567dc5c7144361a9a97f | viharika-22/Python-Practice | /Patterns/7.py | 99 | 3.625 | 4 | n=1
for i in range(5):
for j in range(i):
print(n,end='')
n+=1
print() |
9c5afd492bc5f9a4131d440ce48636ca03fa721c | viharika-22/Python-Practice | /Problem-Set-2/prob1.py | 332 | 4.34375 | 4 | '''1.) Write a Python program to add 'ing' at the end of a given
string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3,
leave it unchanged.'''
n=input()
s=n[len(n)-3:len(n)]
if s=='ing':
print(n[:len(n)-3]+'ly')
|
7503e23122425089e90b6d34ee3a2bf7cef0d51a | viharika-22/Python-Practice | /Problem-Set-6/gh10.py | 365 | 3.546875 | 4 | li1=["Arjun", "Sameeth", "Yogesh", "Vikas" , "Rehman","Mohammad", "Naveen", "Samyuktha", "Rahul","Asifa","Apoorva"]
li2= ["Subramanian", "Aslam", "Ahmed", "Kapoor", "Venkatesh","Thiruchirapalli", "Khan", "Asifa" ,"Byomkesh", "Hadid"]
fname=max(li1,key=len)
lname=max(li2,key=len)
longname=fname+" "+lname
print(longname)
ln=longname[::2]
for i in ln:
|
a3f71d9b7b36d057cc1e9aedec93514e7000b682 | viharika-22/Python-Practice | /Problem-Set-6/h1.py | 203 | 3.59375 | 4 | n=int(input())
d={}
l=[]
li=[]
for i in range(n):
key=input()
d[key]=float(input())
for i in d.keys():
l.append([i,d[i]])
for i in range(len(l)):
li.append(l[i][1])
print(li)
|
d31a4b6f5ebbc1c8403d5cd898afb3d0c257b98e | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d62.py | 361 | 3.84375 | 4 | raz = int(input('Digite a razão da sua PA'))
prim = int(input('Digite o primeiro termo da sua PA'))
pa = 0
qnt = 1
recebe = 1
while recebe != 0:
total = recebe +10
while qnt != total:
pa = (prim)+raz*qnt
qnt = qnt + 1
print(pa,end='')
print(' > ',end='')
recebe = int(input('Quantos valores deseja ver a mais?')) |
b61e8d17f1a9efa2909df39f5af3e43ef6314427 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d64.py | 207 | 3.96875 | 4 | soma = opcao = 0
while opcao != 999:
opcao = int(input('Digite um número ou digite 999 para parar'))
if opcao != 999:
soma += opcao
print(f'A soma de todos os números digitados foi {soma}') |
c59e1afb2d8afc09f020531c64fcdd349237aa61 | vitorgabrielmoura/Exercises | /Python 3/Jogos/forca.py | 3,358 | 3.5625 | 4 | import time
from random import randint
import string
def linha():
print(f'{"-"*60}')
def cabecalho(txt):
linha()
print(txt.center(60))
linha()
def criarLista(txt,list):
num = len(txt)
pos = 0
while True:
list.append("_")
pos += 1
if pos == num:
break
def leiaLetra(txt):
while True:
a1 = str(input(txt)).strip()
if a1 in string.ascii_letters:
return a1
else:
print('\033[1;31mERRO. Digite uma letra.\033[m')
def ArquivoExiste(txt):
try:
a = open(txt, 'r')
a.close()
return True
except FileNotFoundError:
return False
def CriarArquivo(txt):
a = open(txt, 'wt+')
a.close()
def lerArquivo(txt):
try:
a = open(txt, 'r')
except:
print('Erro ao ler o arquivo')
else:
print(a.read())
def adicionar(arq, lista):
a = open(arq, 'a')
for pala in lista:
a.write(f'{pala};\n')
a.close()
listaa = ['banana', 'janela',
'paralelepipedo', 'biblia', 'teclado', 'computador']
listaaa = []
count = 0
cabecalho('JOGO DA FORCA')
erro = 0
arquivo = 'palavras.txt'
if not ArquivoExiste(arquivo):
CriarArquivo(arquivo)
a = open(arquivo, 'r')
for linha in a:
a1 = linha.strip().split(';')
listaaa.append(a1)
a.close()
palavra = listaaa[randint(0,5)]
lista = list()
criarLista(palavra[0], lista)
while True:
print('\n\nJogando...')
time.sleep(2)
a1 = leiaLetra(f'Qual letra você escolhe? Minha palavra contém {len(palavra[0])} letras!').lower()
pos = 0
for letra in palavra[0]:
pos += 1
if letra == a1:
print()
print(f'Encontrei a letra {letra} na posição {pos}',end =' ---> ')
lista.insert(pos-1, letra)
lista.pop(pos)
for c in lista:
print(c,end='')
if a1 not in lista:
erro += 1
print(f'Você errou. Restam {len(palavra[0]) - erro} tentativas')
if len(palavra[0]) - erro == 0:
print(f'\nVocê perdeu o jogo. A palavra era {palavra[0].capitalize()}')
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
break
if "_" not in lista:
print('\n\nVocê ganhou :D')
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
break |
edf3f7438d8bb2fd005c6fec9214dac561de41f5 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d88melhorado.py | 496 | 3.5 | 4 | from random import randint
from time import sleep
print('MEGA SENA')
a1 = int(input('\nDigite quantos jogos você quer sortear'))
lista = []
dados = []
total = 1
while total <= a1:
count = 0
while True:
num = randint(1,60)
if num not in dados:
dados.append(num)
count += 1
if count >= 6:
break
lista.append(dados[:])
dados.clear()
total += 1
for c in range(1,a1+1):
print(f'Jogo {c}: {lista[c]}')
sleep(1) |
991c1f76de22d933924b507714b8f2046bf841de | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d25.py | 112 | 3.8125 | 4 | a1=input('Digite seu nome completo')
a2=a1.upper()
print(f"""O seu nome tem Silva?
Resposta: {'SILVA' in a2}""") |
f675b7ad77db93b4b4ae9219117d16c89eda4392 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d89.py | 798 | 3.859375 | 4 | lista = []
temp = []
while True:
temp.append(input('Digite o nome do aluno: ').capitalize())
temp.append(float(input('Nota 1: ')))
temp.append(float(input('Nota 2: ')))
lista.append(temp[:])
temp.clear()
resp = ' '
while resp not in 'SN':
resp = input('Quer continuar? [S/N]: ').upper()
if resp == 'N':
break
print(f'{"-="*20}')
print(f'{"No.":<4}{"Nome":<10}{"Média":>8}\n')
for p, v in enumerate(lista):
print(f'{p+1:<4}{v[0]:<10}{(v[1]+v[2])/2:>8.1f}')
print(f'\n{"-="*20}')
while True:
resp2 = input('Deseja mostrar as notas de qual aluno?: (Digite "Nenhum" para sair) ').upper()
for c in lista:
if resp2 == c[0].upper():
print(f'As notas de {c[0]} são: {c[1]} e {c[2]}')
if resp2 == 'NENHUM':
break |
2319918a3682cb32256845bfcbbb09f26107a502 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d40.py | 423 | 3.984375 | 4 | print('ESTOU DE RECUPERAÇÃO?')
a1=float(input('\nDigite sua primeira nota'))
a2=float(input('Digite sua segunda nota'))
if (a1+a2)/2 <5:
print(f'\033[1;31mVocê está reprovado com nota final {(a1+a2)/2}')
elif (a1+a2)/2 >5 and (a1+a2)/2 <=6.9:
print(f'\033[7;30mVocê está de recuperação com nota final {(a1+a2)/2}\033[m')
else:
print(f'\033[1;32mParabéns! Você foi aprovado com nota final {(a1+a2)/2}') |
680a11e966b96a1f473247ff88750046a5aac8e1 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d82.py | 336 | 3.984375 | 4 | lista = []
while True:
lista.append(int(input('Digite um número')))
resp = str(input('Deseja continuar? [S/N]: ')).upper()
if resp == 'N':
break
print(f"""\nA lista completa é {[x for x in lista]}\nA lista de pares é {[x for x in lista if x % 2 == 0]}
A lista de ímpares é {[x for x in lista if x % 3 == 0]}""") |
6fd6eca9714a2775c68b90acef5e8c2d8fa1bfd6 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d09.py | 253 | 3.875 | 4 | p1=float(input('Pick a number'))
n1=p1*1
n2=p1*2
n3=p1*3
n4=p1*4
n5=p1*5
n6=p1*6
n7=p1*7
n8=p1*8
n9=p1*9
print('The table of {} is'.format(p1))
print('1:{}\n2: {}\n3: {}\n4: {}\n5: {}\n6: {}\n7: {}\n8: {}\n9: {}\n'.format(n1,n2,n3,n4,n5,n6,n7,n8,n9))
|
5c55e9878f158a8a283d096347a299c185f66c04 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d73.py | 1,316 | 3.921875 | 4 | times = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo', 'Internacional', 'Corinthians',
'Fortaleza', 'Goiás', 'Bahia', 'Vasco', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'CSA',
'Chapecoense', 'Avaí')
print(f"""\n{'='*30}
BRASILEIRÃO 2019 TABELA FINAL
{'='*30}
""")
while True:
a1 = int(input("""\nDigite a opção desejada:
[1] Ver os 5 primeiros colocados
[2] Ver os últimos 4 colocados
[3] Times em ordem alfabética
[4] Posição de um time em específico
[5] Sair do programa
Opção: """))
if a1 == 1:
print('\nOs 5 primeiros colocados, em ordem, foram:\n')
for prim in range (0,len(times[:5])):
print(f'{prim+1}. {times[prim]}')
elif a1 == 2:
print('\nOs últimos 4 colocados, em ordem, foram:\n')
for ult in range (16, len(times)):
print(f'{ult+1}. {times[ult]}')
elif a1 == 3:
print('\nOs times em ordem alfabética são:\n')
for tim in sorted(times):
print(tim)
elif a1 == 4:
a2 = input('\nDigite o primeiro nome do time que deseja ver a posição: ').lower().capitalize()
a3 = times.index(a2)
print(f'O {a2} terminou em {a3+1}º lugar')
elif a1 == 5:
break
print('\nObrigado por utilizar a Vitu Enterprises') |
7d7273b8632e1f4d7ac7b9d9a94ae1e0f9b52a96 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d06.py | 154 | 4.15625 | 4 | n1=float(input('Pick a number'))
d=n1*2
t=n1*3
r=n1**(1/2)
print('The double of {} is {} and the triple is {} and the square root is {}'.format(n1,d,t,r)) |
20325275f6f0c1d011dc965f48b9af420ffd2d3f | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d30.py | 158 | 3.875 | 4 | print('### LEITOR DE PAR OU IMPAR ###')
print('\n')
a1=float(input('Digite um número'))
a2=a1%2
if a2 == 0:
print('É PAR!')
else:
print('É ÍMPAR') |
bd512cbe3014297b8a39ab952c143ec153973495 | CarolinaPaulo/CodeWars | /Python/(8 kyu)_Generate_range_of_integers.py | 765 | 4.28125 | 4 | #Collect|
#Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max)
#Task
#Implement a function named
#generateRange(2, 10, 2) // should return iterator of [2,4,6,8,10]
#generateRange(1, 10, 3) // should return iterator of [1,4,7,10]
#Note
#min < max
#step > 0
#the range does not HAVE to include max (depending on the step)
def generate_range(min, max, step):
hey = []
contador = min
while contador < max:
hey.append(contador)
if step > max:
break
contador = contador + step
return hey
|
80de26c35904fbd989d94270c407c16312aba74e | snehaldalvi/Stock_Prediction | /stock_price_prediction.py | 1,163 | 3.515625 | 4 | #stock-price-prediction#
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
df = pd.read_csv('infy.csv')
print(df.columns.values)
df['Open']=df['Open Price']
df['High']=df['High Price']
df['Low']=df['Low Price']
df['Close']=df['Close Price']
print(df)
df = df[['Close', 'Open', 'High', 'Low']]
print(df)
forecast_col = 'Close'
forecast_out = 3
df['label'] =df[forecast_col].shift(-forecast_out)
print(df)
x = np.array(df.drop(['Close','label'],1))
#print(x)
x_lately=x[-forecast_out:]
print(x_lately)
x = x[:-forecast_out]
print(x)
y = np.array(df['label'])
y = y[:-forecast_out]
print(y)
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2)
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)
clf = LinearRegression() #clf object (part of that class)
clf.fit(x_train, y_train)
confidence = clf.score(x_test, y_test) #coefficient of determination
print('confidence:' , confidence)
forecast_set = clf.predict(x_lately)
print(clf)
#print(df)
print(forecast_set)
|
23071a888fd6d9a059d8f11c3ab040f7bcb4415e | remo-help/Restoring_the_Sister | /concatenate.py | 6,217 | 3.609375 | 4 | # -*- encoding: utf-8 -*-
from itertools import chain, zip_longest
def read_in(textfilename): #this gives us a master read-in function, this reads in the file
file = str(textfilename) + '.txt'# and then splits the file on newline, and then puts that into a list
f = open(file, 'r',encoding='utf-8')# the list is returned
string = f.read()
listvar = []
listvar = string.split("\n")
f.close()
return listvar
##############reading in the files
french_training = read_in('data\\french_training_res')
spanish_training = read_in('data\\spanish_training_res')
romanian_training = read_in('data\\romanian_training_res')
portuguese_training = read_in('data\\portuguese_training_res')
italian_training = read_in('data\\italian_training_res')
french_val = read_in('data\\french_val_res')
spanish_val = read_in('data\\spanish_val_res')
romanian_val = read_in('data\\romanian_val_res')
portuguese_val = read_in('data\\portuguese_val_res')
italian_val = read_in('data\\italian_val_res')
french_test = read_in('data\\french_test_res')
spanish_test = read_in('data\\spanish_test_res')
romanian_test = read_in('data\\romanian_test_res')
portuguese_test = read_in('data\\portuguese_test_res')
italian_test = read_in('data\\italian_test_res')
##########we need these functions for the complex concatenation v2
def interspace_strings(string1): #function that allows us to interspace the strings
return ''.join(chain(*zip_longest(string1, ' ', fillvalue=' ')))
def interleave_strings(string1, string2, string3, string4): #ok, so we use itertools chain and zip_longest to interweave, this function allows us to return a string output
return ''.join(chain(*zip_longest(string1, string2, string3, string4, fillvalue='')))
def interleave_strings3(string1, string2, string3): #ok, interleave 3 strings
return ''.join(chain(*zip_longest(string1, string2, string3, fillvalue='')))
def interleave_strings2(string1, string2): #ok, for two strings
return ''.join(chain(*zip_longest(string1, string2, fillvalue='')))
###########################this is the smart complex concatenation, it interweaves the strings, removes all spaces, and then adds spaces between each character
def concatenatecomplexv2(filename, listname1,listname2,listname3,listname4):
newlist =[]
index = -1
for i in listname1: #first we get every single line
index += 1
string2 =listname2[index]
string3=listname3[index]
string4=listname4[index]
newstring=interleave_strings(i, string2, string3, string4)
newstring = newstring.replace(" ", "")
newstring = interspace_strings(newstring)
newlist.append(newstring)
#print(newlist)
textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function
textfile_complex = open(textfilename_complex,'w+',encoding='utf-8')
c=0
for element in newlist: #iterates over the list of training items
c+=1 #creating a counter so we dont have a trailing newline at the end of the file
if c==1: #first entry does not get a newline
textfile_complex.write(element)
else:
textfile_complex.write('\n') #newline for all subsequent entries
textfile_complex.write(element) #writes in the file
textfile_complex.close() #close the file
####################### concatenate with 3 languages
def concatenatecomplex_triple(filename, listname1,listname2,listname3):
newlist =[]
index = -1
for i in listname1: #first we get every single line
index += 1
string2 =listname2[index]
string3=listname3[index]
newstring=interleave_strings3(i, string2, string3)
newstring = newstring.replace(" ", "")
newstring = interspace_strings(newstring)
newlist.append(newstring)
#print(newlist)
textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function
textfile_complex = open(textfilename_complex,'w+',encoding='utf-8')
c=0
for element in newlist: #iterates over the list of training items
c+=1 #creating a counter so we dont have a trailing newline at the end of the file
if c==1: #first entry does not get a newline
textfile_complex.write(element)
else:
textfile_complex.write('\n') #newline for all subsequent entries
textfile_complex.write(element) #writes in the file
textfile_complex.close() #close the file
###########################concatenate 2 languages
def concatenatecomplex_duple(filename, listname1,listname2):
newlist =[]
index = -1
for i in listname1: #first we get every single line
index += 1
string2 =listname2[index]
newstring=interleave_strings2(i, string2)
newstring = newstring.replace(" ", "")
newstring = interspace_strings(newstring)
newlist.append(newstring)
#print(newlist)
textfilename_complex = 'data\\' + filename + '.txt' # creates the filename of the training file, using the 'name' input in the function
textfile_complex = open(textfilename_complex,'w+',encoding='utf-8')
c=0
for element in newlist: #iterates over the list of training items
c+=1 #creating a counter so we dont have a trailing newline at the end of the file
if c==1: #first entry does not get a newline
textfile_complex.write(element)
else:
textfile_complex.write('\n') #newline for all subsequent entries
textfile_complex.write(element) #writes in the file
textfile_complex.close() #close the file
####EXECUTE
concatenatecomplexv2('concatenate_input_complex',french_training,romanian_training,portuguese_training,spanish_training)
concatenatecomplexv2('concatenate_val_complex',french_val,romanian_val,portuguese_val,spanish_val)
concatenatecomplexv2('concatenate_test_complex',french_test,romanian_test,portuguese_test,spanish_test)
concatenatecomplex_triple('concatenate_fre_po_it_input',french_training,portuguese_training,spanish_training)
concatenatecomplex_triple('concatenate_fre_po_it_val',french_val,portuguese_val,spanish_val)
concatenatecomplex_triple('concatenate_fre_po_it_test',french_test,portuguese_test,spanish_test)
concatenatecomplex_duple('concatenate_fre_it_input',french_training, spanish_training)
concatenatecomplex_duple('concatenate_fre_it_val',french_val, spanish_val)
concatenatecomplex_duple('concatenate_fre_it_test',french_test, spanish_test)
|
51626c3279abb8aa5b46e8815976cf73e61f0cba | Wondae-code/coding_test | /backjoon/정렬/quick_sort.py | 1,196 | 3.890625 | 4 | """
퀵 소트
1. 처음을 피벗으로 설정하고 자신 다음 숫자(왼쪽에서부터) 하나씩 증가하면서 자신보다 높은 숫자를 선택한다.
2. 오른쪽부터 진행하여 피벗보다 작은수를 선택한다.
3. 선택된 두 숫자의 위치를 변환한다.
4. 왼쪽과 오른쪽이 교차 하는 위치에 피벗을 가져다 놓고 왼쪽과 오른쪽을 다시 퀵 소트를 진행한다.
"""
array = [5,7,9,0,3,1,6,2,4,8]
def quick_sort(array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
# 4. 교차하기 직전까지 반복문 진행
while left <= right:
# 피벗보다 큰 데이터를 찾을때 까지 반복
while left <= end and array[left] <= array[pivot]:
left+=1
while right > start and array[right] >= array[pivot]:
right -=1
if left > right:
array[right], array[pivot] = array[pivot], array[right]
else:
array[left], array[pivot] = array[pivot], array[left]
quick_sort(array, start, right-1)
quick_sort(array, right+1, end)
quick_sort(array, 0, len(array)-1)
print(array)
|
528d2f290048598d640de14ce92a54c47c09817b | Wondae-code/coding_test | /leetcode/listnode.py | 1,408 | 4.0625 | 4 | class ListNode():
def __init__(self, val = None):
self.val = val
self.next = None
class LinkedList():
def __init__(self):
self.head = ListNode()
def add(self, data):
new_node = ListNode(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
result = 0
while cur.next != None:
cur = cur.next
result += 1
return result
def display(self):
elem = []
cur = self.head
while cur.next != None:
cur = cur.next
elem.append(cur.val)
print(elem)
def erase(self, index):
if index >= self.length():
print("error")
return
cur = self.head
cur_index = 0
while True:
last_node = cur
cur_node = cur.next
if cur_index == index:
last_node.next = cur_node.next
return
cur_index+=1
def get(self, index):
if index >= self.length():
print("error")
return
cur = self.head
def main():
ll = LinkedList()
ll.add(1)
ll.display()
ll.add(2)
ll.display()
ll.add(3)
ll.display()
ll.erase(0)
ll.display()
if __name__ == "__main__":
main() |
f4d10ed1bcbaef9319250d295668e3980da4230b | Wondae-code/coding_test | /backjoon/재귀함수/(2)(2447) 별찍기.py | 213 | 3.640625 | 4 | """
별찍기 -10
https://www.acmicpc.net/problem/2447
*********
"""
def print(x):
star = "*"
non_star = " "
test = x/3
if test != 1:
x/test
x = int(input())
# for i in range(1, x+1):
|
854f12abc5253e2a06e076cdffb22029208cb285 | ontodev/howl | /ontology/template.py | 755 | 3.71875 | 4 | #!/usr/bin/env python3
# Convert a TSV table into a HOWL file
# consisting of lines
# that append the header to the cell value.
import argparse, csv
def main():
# Parse arguments
parser = argparse.ArgumentParser(
description='Convert table to HOWL stanzas')
parser.add_argument('table',
type=argparse.FileType('r'),
help='a TSV file')
args = parser.parse_args()
rows = csv.reader(args.table, delimiter='\t')
headers = next(rows)
for row in rows:
if len(row) < 1:
continue
for i in range(0, min(len(headers), len(row))):
if headers[i] == 'SUBJECT':
print(row[i])
else:
print(headers[i] +' '+ row[i])
print()
# Run the main() function.
if __name__ == "__main__":
main()
|
5a3b4e2ca6d496a53b6b8e55c2f06ac1dbdec3aa | Byung-moon/Daily_CodingChallenge | /0418/bj1236.py | 697 | 3.71875 | 4 | #prob.1236 from https://www.acmicpc.net/problem/1236
N, M = map(int, input().split(" "))
array = []
for x in range(N):
array.append(input())
# Row Search
NeedRow = len(array)
for x in range(len(array)):
for y in range(len(array[0])):
if array[x][y] == 'X':
NeedRow -= 1
break
# Column Search
NeedColumn = len(array[0])
for x in range(len(array[0])):
for y in range(len(array)):
if array[y][x] == 'X':
NeedColumn -= 1
break
# print('NeedRow : %d' %NeedRow)
# print('NeedColumn : %d' %NeedColumn)
# print answer
if (NeedRow >= NeedColumn):
print(NeedRow)
else:
print(NeedColumn)
|
d9d86188c2f37c16dd1b0a3afdcf03cb5223035c | sakshiguj/list | /list print.py | 67 | 3.59375 | 4 |
list=[15,58,20,2,3]
i=0
while i<len(list):
i=i+1
print(list)
|
adcad46d8b5e27a20b1660861e8316f9c7044eab | zingpython/Common_Sorting_Algorithms | /selection.py | 594 | 4.125 | 4 | def selectionSort():
for element in range(len(alist)-1):
print("element", element)
minimum = element
print("minimum", minimum)
for index in range(element+1,len(alist)):
print("index",index)
if alist[index] < alist[minimum]:
print("alist[index]",alist[index])
print("alist[minimum]",alist[minimum])
minimum = index
print("changing minimum", minimum)
alist[element], alist[minimum] = alist[minimum], alist[element]
print("swap a,b = b,a",alist[element], alist[minimum])
# alist = [54,26,93,17,77,31,44,55,20]
alist = [30,20,10]
selectionSort()
print(alist)
|
aedf273538698ee9f6c20eb141afe5e3b81f8742 | xlr10/pyton | /190729/190729_03.py | 1,351 | 3.984375 | 4 | # class
print("class")
print()
class FourCal:
class_num = 1;
def __init__(self, first, second):
self.first = first
self.second = second
# def __init__(self, first, second):
# self.first = first
# self.second = second
# def setNum(self, first, second):
# self.first = first
# self.second = second
def add(self):
return self.first + self.second
def sub(self):
return self.first - self.second
def mul(self):
return self.first * self.second
def div(self):
return self.first / self.second
test = FourCal(1, 4)
print(type(test))
# test.setNum(1,2)
print(test.add())
print(test.sub())
print(test.mul())
print(test.div())
class FourCal_pow(FourCal):
def pow(self):
return self.first ** self.second
test_inheritance = FourCal_pow(2, 3)
print(test_inheritance.add())
print(test_inheritance.sub())
print(test_inheritance.mul())
print(test_inheritance.div())
print(test_inheritance.pow())
class FourCal_safe(FourCal):
def div(self):
if self.second == 0:
print("Can't Divide Zero")
return 0
else:
return super().div()
test_override = FourCal_safe(2, 0)
print(test_override.add())
print(test_override.sub())
print(test_override.mul())
print(test_override.div())
|
0a2c9e6e590cdcb76d761822d6d9fa92afabf659 | xlr10/pyton | /190729/example_01.py | 1,400 | 3.90625 | 4 | ###################### 01
print()
print("example 01")
def is_odd(num):
if num % 2 == 1:
print("%d is Odd" % num)
else:
print("%d is Even" % num)
is_odd(1)
is_odd(2)
###################### 02
print()
print("example 02")
def average_serial(*args):
result = 0
for i in args:
result += i
result /= len(args)
return result
print(average_serial(1, 2, 3, 4, 5, 6))
###################### 03
print()
print("example 03")
# input1 = input("Press 1st Number:")
# input2 = input("Press 2nd Number:")
#total = int(input1) + int(input2)
#print("Sum is %s " % total)
###################### 04
print()
print("example 04")
print("you" "need" "python")
print("you" + "need" + "python")
print("you", "need", "python")
print("".join(["you", "need", "python"]))
###################### 05
print()
print("example 05")
f1 = open("test.txt", 'w')
f1.write("Life is too short")
f1.close()
f2 = open("test.txt", 'r')
print(f2.read())
f2.close()
###################### 06
print()
print("example 06")
f1 = open("test2.txt", 'w')
#f1.write(input())
f1.close()
f2 = open("test2.txt", 'r')
print(f2.read())
f2.close()
###################### 07
print()
print("example 07")
f1 = open("test3.txt", 'r')
tmp=f1.read()
f1.close()
print(tmp)
print(tmp.replace('java','python'))
f1 = open("test3.txt", 'w')
f1.write(tmp.replace('java','python'))
f1.close()
|
1c9b024feb7296496fa5fe37b65844895f6d858e | JiangNanYu639/python-project | /Question 2.py | 1,846 | 4.0625 | 4 | class Time():
def __init__(self, hour, minutes):
self.hour = hour
self.minutes = minutes
@property
def hour(self):
return self.__hour
@hour.setter
def hour(self, h):
if h >= 0 and h <= 23:
self.__hour = h
else:
raise ValueError('hour must be in 0-23')
@property
def minutes(self):
return self.__minutes
@minutes.setter
def minutes(self, m):
if m >= 0 and m <= 59:
self.__minutes = m
else:
raise ValueError('minutes must be in 0-59')
def __str__(self):
t = str(self.__hour) + ':' + str(self.__minutes)
return t
def __lt__(self, other):
if self.__hour < other.__hour:
return True
elif self.__hour == other.__hour:
if self.__minutes < other.__minutes:
return True
else:
return False
else:
return False
def __eq__(self, other):
if self.__hour == other.__hour and self.__minutes == other.__minutes:
return True
else:
return False
def __gt__(self, other):
if self.__hour > other.__hour:
return True
elif self.__hour == other.__hour:
if self.__minutes > other.__minutes:
return True
else:
return False
else:
return False
try:
t1 = Time(11, 50)
t2 = Time(23, 50)
print(t1.hour)
print(t1.minutes)
print(t1)
print(t2)
if t2 < t1:
print('t2 is before t1')
elif t2 == t1:
print('t2 is the same as t1')
else:
print('t2 is after t1')
except ValueError as ret:
print(ret)
|
5b0719eba5b442343ab31e241083ba6cd54c5b9c | JiangNanYu639/python-project | /HM0226.2.py | 439 | 3.59375 | 4 | # 大乐透游戏,给你的6位数,中奖码是958 (9 5 8可以在6位数中任意位置,都存在) ,如何判断自己中奖?
n = input('Pls type your number: ')
a = '9'
b = '5'
c = '8'
length = len(n)
if n.isdigit() and length == 6:
if n.find(a) != -1 and n.find(b) != -1 and n.find(c) != -1:
print('You win!')
else:
print('Sorry.')
else:
print('Not a valid number.')
|
4473702e806d184a6189e699bb8fc65352640661 | fjnajasm/PLN | /PRACTICA 1/Ejercicio2.py | 741 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:02:32 2020
@author: fran
"""
def listas(a, b):
lista_final = []
for i in a:
if(i not in lista_final) and (i in b):
lista_final.append(i)
return lista_final
def comprueba(a):
try:
for i in a:
int(i)
return True
except ValueError:
return False
lista1 = [1,2,3,4, 1,1,1,1,1,1,1,1]
lista2 = [1,3,4,5,6]
compruebaa = comprueba(lista1)
compruebab = comprueba(lista2)
res = []
if (compruebaa is True and compruebab is True):
res = listas(lista1, lista2)
if len(res) == 0:
print("Una de las listas no es de enteros completa")
else:
for i in res:
print(i)
|
614513ba35b93e4c5d2c7a8ee6a22e4ad1f5d424 | Neecolaa/tic-tac-toe | /tictactoe.py | 4,761 | 3.65625 | 4 |
class gameBoard:
def __init__(self, size):
self.size = size
self.board = [[' '] * size for i in range(size)]
self.cellsFilled = 0
def printBoard(self):
rows = list(map(lambda r: " "+" | ".join(r), self.board))#generates list of rows with |
#^idk if this is the best/cleanest way to do this
board = ("\n"+("--- "*self.size)+"\n").join(rows)#adds horizontal lines between rows
print(board)
return board
def printOptions(self):
#determine size of cells
cellSize = len(str(self.size * self.size))
#create options table
options = [[''] * self.size for i in range(self.size)]
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] != ' ':
#add symbol to cell
options[i][j] = str.center(self.board[i][j],cellSize)
else:
#add cell number to cell
options[i][j] = str.center(str(self.size*i+j+1),cellSize)
rows = list(map(lambda r: " "+" | ".join(r), options))#generates list of rows with |
#^idk if this is the best/cleanest way to do this
pboard = ("\n"+(("-"*(cellSize+2))+" ")*self.size+"\n").join(rows)#adds horizontal lines between rows
print(pboard)
return cellSize
def fillCell(self,cellNum, symbol):
#find row and col from cellNum
cellNum = int(cellNum)
row = (cellNum-1)//self.size
col = (cellNum-1)%self.size
#make sure cell is in board
if row >= self.size or col >= self.size:
return False
#check if cell is empty
if self.board[row][col] == ' ':
#if empty add symbol to cell
self.board[row][col] = symbol
self.cellsFilled += 1
return True
else:
#else return false w/o adding anything
return False
def checkForWin(self):
if self.cellsFilled < self.size:
#no way to win already (technically no win until size*2-1, maybe will change to that)
return False
for i in range(self.size):
#horizontal check
row = self.board[i]
#vertical check
col = [row[i] for row in self.board]
if self.checkWinSet(row) == True or self.checkWinSet(col) == True:
return True
#diagonal check
diagL2R = [self.board[i][i] for i in range(self.size)]
diagR2L = [self.board[i][self.size-i-1] for i in range(self.size)]
if self.checkWinSet(diagL2R) == True or self.checkWinSet(diagR2L) == True:
return True
else:
return False
def checkWinSet(self,values):
s = set(values)
if len(s) == 1 and ' ' not in s:
return True
else:
return False
def isFull(self):
return (self.cellsFilled == self.size*self.size)
class game:
def __init__(self):
self.playerCount = int(input('Input player count: '))
self.currentPlayerIdx = 0
self.symbols = self.inputSymbols()
size = int(input('Input board size: '))
self.board = gameBoard(size)
def inputSymbols(self):
symbols = []
for i in range(self.playerCount):
symbols.append(input("Input Player "+str(i+1)+"'s symbol: "))
return symbols
def play(self):
gameWon = False
while gameWon is False and self.board.isFull() is False:
#show current board + available moves
self.board.printOptions()
#get current player's move
moveValid = False
while moveValid is False:
move = input("Player "+str(self.currentPlayerIdx+1)+"'s move: ")
moveValid = self.board.fillCell(move,self.symbols[self.currentPlayerIdx])
if moveValid is False:
print('Selected move not valid! Please reselect.')
#check for win
gameWon = self.board.checkForWin()
if gameWon is False:
#move on to next player
self.currentPlayerIdx = (self.currentPlayerIdx + 1) % self.playerCount
#Game is over
self.board.printBoard()
#Win or tie?
if gameWon is True:
print('Player '+str(self.currentPlayerIdx+1)+' wins!')
elif self.board.isFull() is True:
print("It's a tie!")
print('GAME OVER')
g = game()
g.play() |
632b8b79e60f6a1ef17c8bc4165fab17b262211c | siddhantpushpraj/Python_Basics- | /reimport.py | 4,109 | 4.1875 | 4 | import re
###
'''
if re.search('hi(pe)*','hidedede'):
print("match found")
else:
print("not found")
'''
###
'''
pattern='she'
string='she sells sea shells on the sea shore'
if re.match(pattern,string):
print("match found")
else:
print("not found")
'''
###
'''
pattern='sea'
string='she sells sea shells on the sea shore'
if re.match(pattern,string):
print("match found")
else:
print("not found")
'''
###
'''
pattern=r'[a-z A-Z]+ \d+'
string='Lx 12013,Xyzabc 2016,i am indian'
m=re.findall(pattern,string)
for n in m:
print(n)
'''
###
'''
pattern=r'[a-z A-Z]+ \d+'
string='Lx 12013,Xyzabc 2016,i am indian'
m=re.finditer(pattern,string)
for n in m:
print('match at start index',n.start())
print('match at start index', n.end())
print(n.span())
'''
'''
pattern=r'[a-z A-Z]+ \d+'
string='Lx 12013'
m=re.findall(pattern,string)
for n in m:
print(n)
'''
# Q.A program that uses a regular expression to match string which starts with a
# sequence of digit follwed by blank or space, arbitary character.
'''
import re
a='LXI 2013,XYZ abc 2016,I am an Indian $%5^'
pattern='[a-zA-Z]+[!@#$%&()_] +'
m=re.findall(pattern,a)
for n in m:
print(n)
'''
# Q.WAP to extract charcter from a string using a regular expression.
'''
import re
a=input()
pattern='[a-zA-Z]+ '
m=re.findall(pattern,a)
for i in m:
print(i)
'''
# Q.A program to print first word of string.
'''
import re
a=input()
pattern='[a-zA-Z]+ '
m=re.findall(pattern,a)
for i in m:
print(m[0])
break
'''
# Q.program to print char in pairs
'''
import re
a = input()
pattern = '[a-zA-Z]+'
m = re.findall(pattern, a)
x=m.split("2")
for i in x:
print(i)
'''
# Q.print only first two character of every word.
'''
import re
a=input()
pattern='[a-zA-Z]+'
m=re.findall(pattern,a)
for i in m:
print(i[0:2])
'''
##Q wap to check if string contains only alphabet and digits only
'''
a=input()
pat='[a-zA-Z]'
if re.search(pat,a):
if re.search('[0-9]',a):
print(a)
'''
##QUE to match if string contains 1 a followed by 0 or more b's ie ab* .a,ab,abbbb...
##QUE text="the qiuck brown fox jumps over the lazy dog".search for the following pattern.pattern fox dog horse.
##(b)to find location of fox in a given text
'''
s="the quick brown fox jump over the lazy dog horse"
p1='fox'
p2='dog'
p3='horse'
m=re.findall(p1,s)
n=re.findall(p2,s)
b=re.findall(p3,s)
if(m):
if(b):
if(n):
print("VALID : ",s)
else:
print("INVALID")
else:
print("INVALID")
else:
print("INVALID")
'''
'''
s="the quick brown fox jump over the lazy dog horse"
p1='fox'
m=re.search(p1,s)
s=m.span()
print("index",s)zzzz
'''
#Que pularize the word list=[bush,fox,toy,cat]
'''
li=['bush','fox','toy','cat','half','knife']
for x in li:
if(x[len(x)-1]=='f'):
print(x[0:len(x)-1]+'ves')
elif (x[len(x) - 2] == 'f'):
print(x[0:len(x) - 2] + 'ves')
elif (x[len(x) - 1] == 'x' or x[len(x) - 1] == 'h'):
print(x+'es')
else:
print(x + 's')
def pluralize(noun):
if re.search('[sxz]$', noun):
return re.sub('$', 'es', noun)
elif re.search('[^aeioudgkprt]h$', noun):
return re.sub('$', 'es', noun)
elif re.search('[^aeiou]y$', noun):
return re.sub('y$', 'ies', noun)
else:
return noun + 's'
list1=['bush','fox','toy','cat','half','knife']
for i in list1:
pluralize(i)
print(x)
'''
##Que a website req user to input password and user name,write a programm to validate the password.
##at least one letter from a-z,A-z,@#$,length=6-12
'''
value = []
x=input()
items=x.split(',')
for p in items:
if ((len(p)>6 or len(p)<12)):
if (re.findall("[a-z]",p)):
if (re.findall("[0-9]",p)):
if (re.findall("[A-Z]",p)):
if (re.findall("[$#@]",p)):
value.append(p)
print (",".join(value))
'''
|
1395e5ded5679ceb8a5c607b36a04e647a407147 | siddhantpushpraj/Python_Basics- | /class.py | 2,929 | 4.1875 | 4 | '''
class xyz:
var=10
obj1=xyz()
print(obj1.var)
'''
'''
class xyz:
var=10
def display(self):
print("hi")
obj1=xyz()
print(obj1.var)
obj1.display()
'''
##constructor
'''
class xyz:
var=10
def __init__(self,val):
print("hi")
self.val=val
print(val)
print(self.val)
obj1=xyz(10)
print(obj1.var)
'''
'''
class xyz:
class_var=0
def __init__(self,val):
xyz.class_var+=1
self.val=val
print(val)
print("class_var+=1",xyz.class_var)
obj1=xyz(10)
obj1=xyz(20)
obj1=xyz("sid")
print(obj1.val)
'''
##wap with class employee keeps the track of number of employee in a organisation and also store thier name, desiganation and salary
'''
class comp:
count=0
def __init__(self,name,desigantion,salary):
comp.count+=1
self.name=name
self.desigantion=desigantion
self.salary=salary
print("name ",name,"desigantion ",desigantion,"salary ",salary)
obj1=comp("sid","ceo","150000")
obj12=comp("rahul","manager1","150000")
obj3=comp("danish","manger2","150000")
'''
#wap that has a class circle use a class value define the vlaue of the pi use class value and calculate area nad circumferance
'''
class circle:
pi=3.14
def __init__(self,radius):
self.area=self.pi*radius**2
self.circum=self.pi*radius*2
print("circumferance",self.circum)
print("area", self.area)
radius=int(input())
obj1=circle(radius)
'''
#wap that have a class person storing dob of the person .the program subtract the dob from today date to find whether the person is elgoble for vote or vote
'''
import datetime
class vote:
def __intit__(self,name,dob):
self.name=name
self.dob=dob
def agevote():
today=datetime.date.today()
print(today)
obj1=vote("siddhant",1997)
obj.agevote()
'''
# ACCESS SPECIFIED IN PYTHON
## 1) .__ (private variable) 2)._ (protected variable)
'''
class abc:
def __init__(self,var,var1):
self.var=var
self.__var1=var1
def display(self):
print(self.var)
print(self.__var1)
k=abc(10,20)
k.display()
print(k.var)
# print(k.__var1) #private
print(k.__abc__var1)
'''
##wap uses classes to store the name and class of a student ,use a list to store the marks of three student
class student:
mark=[]
def __init__(self,name):
self.name=name
self.mark=[]
def getmarks(self,sub):
for i in range(sub):
m=int(input())
self.mark.append(m)
def display(self):
print(self.name," ",self.mark)
print("total student")
n=int(int(input()))
print("total subject")
sub=int(input())
s=[]
for i in range(n):
print("student name")
name=input()
s=student(name)
s.getmarks(sub)
s.display()
|
f0229a16a7d08489515081689675a77e2066e348 | siddhantpushpraj/Python_Basics- | /even odd.py | 976 | 4.0625 | 4 | '''
#even odd
a=int(input("enetr a number"))
b=int(input("enetr a number"))
if(a%2==0):
print("even")
for i in range(a,b+1,2):
print(i)
print("odd")
for i in range(a+1,b,2):
print(i)
for i in range(a,b+1):
if(i%2==0):
print(i,"even")
else:
print(i,"odd")
# table
a=int(input("enter a number"))
for i in range(1,11):
print(a,"x",i," = ",a*i)
#pow
a=int(input("enter number"))
b=int(input("enter number"))
c=pow(a,b)
print(c)
'''
#fact
a=int(input("enter a number"))
m=1
for i in range(1,a+1):
m=i*m
print(m)
'''
# sqr sum
a=int(input("enter number"))
b=int(input("enter number"))
c=pow(a,2)
d=pow(b,2)
e=c+d
print(e)
#leap year
for i in range(1900,2102):
if(i%4==0):
if(i%100!=0):
print(i)
#series
a=int(input("enter range"))
c=1
for i in range(1,a+1):
c=(pow(i,i)/i)+c
print(c)
'''
|
27bc28f5e960f4fc56360ad19a4f838b06a95813 | Andyporras/portafolio1 | /cantidadDeNumerosPares.py | 1,059 | 3.90625 | 4 | """
nombre:
contadorDepares
entrada:
num: numero entero positivo
salidad:
cantidad de numero pares que tiene el numero digita
restrinciones:
numero entero positivo mayor a cero
"""
def contadorDepares(num):
if(isinstance(num,int) and num>=0):
if(num==0):
return 0
elif(num%2)==0:
return 1+contadorDepares(num//10)
else:
return contadorDepares(num//10)
else:
return print("dijite un entero positivo")
#---------------------------------------------------------------------------
def cantidadDeNumerosPares(num):
if(isinstance(num,int)and num>0):
return cantidadDeNumerosPares_aux(num,0)
else:
return "digite un numero entero positivo"
def cantidadDeNumerosPares_aux(numVerified,result):
if(numVerified==0):
return result
elif(numVerified%2==0):
return cantidadDeNumerosPares_aux(numVerified//10,result +1)
else:
return cantidadDeNumerosPares_aux(numVerified//10,result)
|
f75dbfe00e001bbbebae43f2ed56c4b8d5098028 | ferrakkem/Complete_codingbat_problem_Python | /app.py | 27,994 | 4.25 | 4 | '''
The parameter weekday is True if it is a weekday,
and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation.
Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True
'''
def sleep_in(weekday, vacation):
if(not weekday or vacation):
return True
else:
False
#print(sleep_in(False, False))
'''
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling.
We are in trouble if they are both smiling or if neither of them is smiling.
Return True if we are in trouble.
monkey_trouble(True, True) → True
monkey_trouble(False, False) → True
monkey_trouble(True, False) → False
'''
def monkey_trouble(a_smile, b_smile):
if a_smile and b_smile:
return True
elif not a_smile and not b_smile:
return True
else:
return True
#print(monkey_trouble(False, True))
'''
Given two int values, return their sum.
Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
'''
def sum_double(num1, num2):
sum = 0
if (num1 == num2):
sum = (num1 + num2)*2
return sum
else:
sum = num1+num2
return sum
#print(sum_double(2, 2))
'''
Given an int n, return the absolute difference between n and 21,
except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
'''
def diff21(n):
if n <= 21:
return 21 - n
else:
return (n - 21) * 2
#print(diff21(66))
'''
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23.
We are in trouble if the parrot is talking and the hour is before 7 or after 20.
Return True if we are in trouble.
parrot_trouble(True, 6) → True
parrot_trouble(True, 7) → False
parrot_trouble(False, 6) → False
'''
def parrot_trouble(hour, is_talking):
if ((is_talking) and (hour<7 or hour>20)):
return True
else:
return False
#print(parrot_trouble(True, 7))
'''
Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.
makes10(9, 10) → True
makes10(9, 9) → False
makes10(1, 9) → True
'''
def makes10(a, b):
if (a == 10) or (b == 10) or (a+b == 10):
return True
else:
return False
#print(makes10(1, 9))
'''
Given an int n, return True if it is within 10 of 100 or 200.
Note: abs(num) computes the absolute value of a number.
near_hundred(93) → True
near_hundred(90) → True
near_hundred(89) → False
'''
def near_hundred(n):
diff1 = abs(100 - n)
diff2 = abs(200 - n)
if (diff1 <= 10 or diff2 <= 10):
return True
else:
return False
#print(near_hundred(90))
'''
Given 2 int values, return True if one is negative and one is positive.
Except if the parameter "negative" is True, then return True only if both are negative.
pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True
'''
def pos_neg(a, b, negative):
if negative:
return (a < 0 and b < 0)
else:
return ((a < 0 and b > 0) or (a > 0 and b < 0))
#print(pos_neg(-1, -1, True))
'''
Given a string, return a new string where "not " has been added to the front.
However, if the string already begins with "not", return the string unchanged.
not_string('candy') → 'not candy'
not_string('x') → 'not x'
not_string('not bad') → 'not bad'
'''
def not_string(sting):
checking_value = 'Not'
if not checking_value.upper() in sting.upper():
return "Not " + sting
else:
return sting
#print(not_string('Not bad'))
'''
Given a non-empty string and an int n, return a new string where the char at index n has been removed.
The value of n will be a valid index of a char in the original string
(i.e. n will be in the range 0..len(str)-1 inclusive).
missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'
'''
def missing_char(string, n):
front = string[:n]
back = string[n + 1:]
return front + back
#print(missing_char('kitten', 1))
'''
Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'
'''
def front_back(str):
if len(str) <= 1:
return str
front_chrac = str[0]
back_chrac = str[-1]
rest_chrac = str[1:-1]
return back_chrac + rest_chrac + front_chrac
#print(front_back('a'))
'''
Given a string, we'll say that the front is the first 3 chars of the string.
If the string length is less than 3, the front is whatever is there.
Return a new string which is 3 copies of the front.
front3('Java') → 'JavJavJav'
front3('Chocolate') → 'ChoChoCho'
front3('abc') → 'abcabcabc
'''
def front3(string):
get_front_three = string[:3]
return get_front_three*3
#print(front3('Chocolate'))
'''
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi
'''
def string_times(string, number):
if (number>0):
return string*number
else:
return "You input negative number"
#print(string_times('Hi', -3))
'''
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars,
or whatever is there if the string is less than length 3. Return n copies of the front;
front_times('Chocolate', 2) → 'ChoCho'
front_times('Chocolate', 3) → 'ChoChoCho'
front_times('Abc', 3) → 'AbcAbcAbc'
'''
def front_times(string, number):
front_slice = string[:3]
if (number <= 3):
return front_slice*number
else:
return front_slice*number
#print(front_times('abc', 3))
'''
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
string_bits('Hello') → 'Hlo'
string_bits('Hi') → 'H'
string_bits('Heeololeo') → 'Hello'
'''
def string_bits(string):
result = ""
for i in range(len(string)):
if i%2 == 0:
result = result + string[i]
return result
#print(string_bits('Heeololeo'))
'''
Given a non-empty string like "Code" return a string like "CCoCodCode".
string_splosion('Code') → 'CCoCodCode'
string_splosion('abc') → 'aababc'
string_splosion('ab') → 'aab
'''
def string_splosion(str):
result = ""
for i in range(len(str)):
result = result + str[:i+1]
return result
#print(string_splosion('ab'))
'''
Given a string, return the count of the number of times that
a substring length 2 appears in the string and also as
the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') → 1
last2('xaxxaxaxx') → 1
last2('axxxaaxx') → 2
'''
def last2(string):
pass
'''
Given an array of ints, return the number of 9's in the array.
array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3
'''
def array_count9(number):
count = 0
for i in number:
if i == 9:
count = count + 1
return count
#print(array_count9([1, 9, 9, 3, 9,9]))
'''
Given an array of ints, return True if one of the first 4 elements in the array is a 9.
The array length may be less than 4.
array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False
'''
def array_front9(number):
count = 0
end = len(number)
if end > 4:
end = 4
for i in range(end):
if number[i] == 9:
return True
return False
#print(array_front9([1, 2, 3, 4, 9]))
'''
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
'''
def array123(numbers):
for i in range(len(numbers) - 2):
if numbers[i] == 1 and numbers[i + 1] == 2 and numbers[i + 2] == 3:
return True
return False
#print(array123([1, 1, 2, 3, 1]))
'''
Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
make_abba('Hi', 'Bye') → 'HiByeByeHi'
make_abba('Yo', 'Alice') → 'YoAliceAliceYo'
make_abba('What', 'Up') → 'WhatUpUpWhat'
'''
def make_abba(a, b):
return a+b+b+a
#print(make_abba('Yo', 'Alice'))
'''
The web is built with HTML strings like "<i>Yay</i>" which draws Yay as italic text.
In this example, the "i" tag makes <i> and </i> which surround the word "Yay".
Given tag and word strings, create the HTML string with tags around the word, e.g. "<i>Yay</i>".
make_tags('i', 'Yay') → '<i>Yay</i>'
make_tags('i', 'Hello') → '<i>Hello</i>'
make_tags('cite', 'Yay') → '<cite>Yay</cite>'
'''
def make_tags(tag, string):
making_tag = "<{tag}>".format(tag)
print(making_tag)
#make_tags('i','yay')
'''
Given an "out" string length 4, such as "<<>>", and a word,
return a new string where the word is in the middle of the out string, e.g. "<<word>>".
make_out_word('<<>>', 'Yay') → '<<Yay>>'
make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>'
make_out_word('[[]]', 'word') → '[[word]]
'''
def make_out_word (str1, str2):
frist = str1[:2]
second = str1[2:]
return frist+str2+second
#print(make_out_word('[[]]', 'Yay'))
'''
Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
extra_end('Hello') → 'lololo'
extra_end('ab') → 'ababab'
extra_end('Hi') → 'HiHiHi'
'''
def extra_end(string):
last_two_chars = string[-2:]
return last_two_chars*3
#print(extra_end('Hello'))
'''
Given a string, return the string made of its first two chars,
so the String "Hello" yields "He". If the string is shorter than length 2,
return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
first_two('Hello') → 'He'
first_two('abcdefg') → 'ab'
first_two('ab') → 'ab'
'''
def first_two(string):
if len(string)>2:
first_two_chars = string[:2]
return first_two_chars
else:
return string
#print(first_two('ab'))
'''
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc
'''
def first_half(string):
get_string_length = int(len(string)/2)
return string[:get_string_length]
#print(first_half('HelloThere'))
'''
Given a string, return a version without the first and last char,
so "Hello" yields "ell". The string length will be at least 2.
without_end('Hello') → 'ell'
without_end('java') → 'av'
without_end('coding') → 'odin'
'''
def without_end(string):
return string[1:len(string)-1]
#print(without_end('coding'))
'''
Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1.
non_start('Hello', 'There') → 'ellohere'
non_start('java', 'code') → 'avaode'
non_start('shotl', 'java') → 'hotlava
'''
def non_start(str1, str2):
return str1[1:]+str2[1:]
#print(non_start('Hello', 'There'))
######################################----List_1------############################
'''
Given an array of ints, return True if 6 appears as either the first or last element in the array.
The array will be length 1 or more.
first_last6([1, 2, 6]) → True
first_last6([6, 1, 2, 3]) → True
first_last6([13, 6, 1, 2, 3]) → False
'''
def first_last6(number):
if number[0] == 9 or number[-1] == 6:
return True
else:
return False
#print(first_last6([13, 6, 1, 2, 3]))
'''
Given an array of ints, return True if the array is length 1 or more,
and the first element and the last element are equal.
same_first_last([1, 2, 3]) → False
same_first_last([1, 2, 3, 1]) → True
same_first_last([1, 2, 1]) → True
'''
def same_first_last(num):
if num[0] == num[-1]:
return True
else:
return False
#print(same_first_last([1, 2, 1]))
'''
Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element.
Both arrays will be length 1 or more.
common_end([1, 2, 3], [7, 3]) → True
common_end([1, 2, 3], [7, 3, 2]) → False
common_end([1, 2, 3], [1, 3]) → True
'''
def common_end(num1, num2):
if (num1[0]== num2[0]) or(num1[-1] == num2[-1]):
return True
else:
return False
#print(common_end([1, 2, 3], [1, 3]))
'''
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
reverse3([1, 2, 3]) → [3, 2, 1]
reverse3([5, 11, 9]) → [9, 11, 5]
reverse3([7, 0, 0]) → [0, 0, 7]
'''
def reverse3(number):
return number[::-1]
#print(reverse3([1, 2, 3]))
####------------------------------------------------logic-1---------------------------------------------------------
'''
When squirrels get together for a party, they like to have cigars.
A squirrel party is successful when the number of cigars is between 40 and 60, inclusive.
Unless it is the weekend, in which case there is no upper bound on the number of cigars.
Return True if the party with the given values is successful, or False otherwise.
cigar_party(30, False) → False
cigar_party(50, False) → True
cigar_party(70, True) → True
'''
def cigar_party(cigars,is_weekend):
if (cigars >= 40) and (cigars <=60) or(cigars >= 40) and is_weekend:
return True
else:
return False
#print(cigar_party(30,False))
'''
You and your date are trying to get a table at a restaurant.
The parameter "you" is the stylishness of your clothes, in the range 0..10,
and "date" is the stylishness of your date's clothes.
The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes.
If either of you is very stylish, 8 or more, then the result is 2 (yes).
With the exception that if either of you has style of 2 or less, then the result is 0 (no).
Otherwise the result is 1 (maybe).
date_fashion(5, 10) → 2
date_fashion(5, 2) → 0
date_fashion(5, 5) → 1
'''
def date_fashion(you, my_date):
if (you >= 8) or my_date >= 8:
return '2'
elif (you <= 2 or my_date<= 2):
return '0'
else:
return '1'
#print(date_fashion(5, 10))
'''
The squirrels in Palo Alto spend most of the day playing.
In particular, they play if the temperature is between 60 and 90 (inclusive).
Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer,
return True if the squirrels play and False otherwise.
squirrel_play(70, False) → True
squirrel_play(95, False) → False
squirrel_play(95, True) → True
'''
def squirrel_play(temperature, is_summer):
if (is_summer):
if (temperature >= 60) and (temperature <= 100):
return True
else:
if (temperature >= 60) and (temperature <= 90):
return True
else:
return False
#print(squirrel_play(95, True))
'''
You are driving a little too fast, and a police officer stops you.
Write code to compute the result, encoded as an
int value: 0=no ticket, 1=small ticket, 2=big ticket.
If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1.
If speed is 81 or more, the result is 2.
Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.
caught_speeding(60, False) → 0
caught_speeding(65, False) → 1
caught_speeding(65, True) → 0
'''
def caught_speeding(speed, is_birthday):
if(is_birthday):
if speed <= 65:
return 0
elif (speed >= 65) and (speed <= 85):
return 1
else:
return 2
else:
if speed <= 60:
return 0
elif (speed >= 60) and (speed <= 80):
return 1
else:
return 2
#print(caught_speeding(60, False))
'''
Given 2 ints, a and b, return their sum.
However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.
sorta_sum(3, 4) → 7
sorta_sum(9, 4) → 20
sorta_sum(10, 11) → 21
'''
def sorta_sum(a, b):
sum = a+b
if sum in range(10, 19):
return '20'
else:
return sum
#print(sorta_sum(19, 4))
'''
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating
if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring.
Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00".
Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
alarm_clock(1, False) → '7:00'
alarm_clock(5, False) → '7:00'
alarm_clock(0, False) → '10:00'
'''
def alarm_clock(day, is_vacation):
if (is_vacation):
if (day >= 1) and (day <= 5):
return "10.00"
else:
return 'Off'
else:
if (day >= 1) and (day <= 5):
return "7.00"
else:
return '10.00'
#print(alarm_clock(5, True))
'''
The number 6 is a truly great number.
Given two int values, a and b, return True if either one is 6.
Or if their sum or difference is 6.
Note: the function abs(num) computes the absolute value of a number.
love6(6, 4) → True
love6(4, 5) → False
love6(1, 5) → True
'''
def love6(a, b):
if (a == 6) or (b == 6):
return True
elif abs(a+b) == 6:
return True
elif abs(a-b) == 6:
return True
else:
return False
#print(love6(13, 7))
'''
Given a non-negative number "num", return True
if num is within 2 of a multiple of 10.
Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2.
near_ten(12) → True
near_ten(17) → False
near_ten(19) → True
'''
def near_ten(num):
mod_num = num % 10
if mod_num <= 2:
return True
else:
return False
#print(near_ten(17))
##--------------------------------logic-2-----------------------------------##
'''
We want to make a row of bricks that is goal inches long.
We have a number of small bricks (1 inch each) and big bricks (5 inches each).
Return True if it is possible to make the goal by choosing from the given bricks.
This is a little harder than it looks and can be done without any loops.
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
'''
def make_bricks():
pass
'''
Given 3 int values, a b c, return their sum.
However, if one of the values is the same as another of the values,
it does not count towards the sum.
lone_sum(1, 2, 3) → 6
lone_sum(3, 2, 3) → 2
lone_sum(3, 3, 3) → 0
'''
def lone_sum(a, b, c):
if a == b and b == c:
return 0
elif a == b:
return c
elif a == c:
return b
elif b == c:
return a
else:
return a+b+c
#print(lone_sum(1, 2, 3))
'''
Given 3 int values, a b c, return their sum.
However, if one of the values is 13 then it does not count towards the sum and values to its right do not count.
So for example, if b is 13, then both b and c do not count.
lucky_sum(1, 2, 3) → 6
lucky_sum(1, 2, 13) → 3
lucky_sum(1, 13, 3) → 1
'''
def lucky_sum(a, b, c):
if a == 13:
return b+c
elif b == 13:
return a
elif c == 13:
return a+b
else:
return a+b+c
#print(lucky_sum(1, 13, 3))
'''
Given 3 int values, a b c, return their sum.
However, if any of the values is a teen -- in the range 13..19 inclusive
-- then that value counts as 0, except 15 and 16 do not count as a teens.
Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule.
In this way, you avoid repeating the teen code 3 times (i.e. "decomposition").
Define the helper below and at the same indent level as the main no_teen_sum().
no_teen_sum(1, 2, 3) → 6
no_teen_sum(2, 13, 1) → 3
no_teen_sum(2, 1, 14) → 3
'''
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) +fix_teen(c)
def fix_teen(n):
#checking in the range 13..19 inclusive then that value counts as 0, except 15 and 16 do not count as a teens
if n >=13 and n <= 19 and n !=15 and n!= 16:
return 0
return n
#print(no_teen_sum(2, 1, 16))
'''
For this problem, we'll round an int value up to the next multiple of 10
if its rightmost digit is 5 or more, so 15 rounds up to 20.
Alternately, round down to the previous multiple of 10
if its rightmost digit is less than 5, so 12 rounds down to 10.
Given 3 ints, a b c, return the sum of their rounded values.
To avoid code repetition, write a separate helper "def round10(num):"
and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10
'''
def round_sum(a, b, c):
return round10(a)+round10(b)+round10(c)
def round10(num):
if num%10 <5:
return num - (num%10)
else:
return num + (10 - num%10)
#print(round_sum(16, 17, 18))
'''
Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1),
while the other is "far", differing from both other values by 2 or more.
Note: abs(num) computes the absolute value of a number.
close_far(1, 2, 10) → True
close_far(1, 2, 3) → False
close_far(4, 1, 3) → True
'''
def close_far():
pass
'''
We want make a package of goal kilos of chocolate.
We have small bars (1 kilo each) and big bars (5 kilos each).
Return the number of small bars to use, assuming we always use big bars before small bars.
Return -1 if it can't be done.
make_chocolate(4, 1, 9) → 4
make_chocolate(4, 1, 10) → -1
make_chocolate(4, 1, 7) → 2
'''
#--------------------------------string-2-----------------------------------------------
'''
Given a string, return a string where for every char in the original, there are two chars.
double_char('The') → 'TThhee'
double_char('AAbb') → 'AAAAbbbb'
double_char('Hi-There') → 'HHii--TThheerree'
'''
def double_char(string):
new_string = ""
for i in string:
new_char = i*2
new_string = new_string + new_char
return new_string
#print(double_char('Hi-There'))
'''
Return the number of times that the string "hi" appears anywhere in the given string.
count_hi('abc hi ho') → 1
count_hi('ABChi hi') → 2
count_hi('hihi') → 2
'''
def count_hi(string):
cout = 0
for i in range(len(string)-1):
if string[i] =='h' and string[i+1] == 'i':
cout = cout+1
return cout
#print(count_hi('hihi'))
'''
Return True if the string "cat" and "dog" appear the same number of times in the given string.
cat_dog('catdog') → True
cat_dog('catcat') → False
cat_dog('1cat1cadodog') → True
'''
def cat_dog(string):
cat_count = 0
dog_count = 0
cat_count = string.count('cat')
dog_count = string.count('dog')
if cat_count == dog_count:
return True
else:
return False
#print(cat_dog('catcat'))
'''
Return the number of times that the string "code" appears anywhere in the given string,
except we'll accept any letter for the 'd', so "cope" and "cooe" count.
count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2
'''
def count_code(string):
count = 0
for i in range(len(string)-1):
if string[i] == 'c' and string[i+1] =='o' and string[i+3] == 'e':
count = count+1
return count
#print(count_code('cozexxcope'))
'''
Given two strings, return True if either of the strings appears at the very end of the other string,
ignoring upper/lower case differences (in other words, the computation should not be "case sensitive").
Note: s.lower() returns the lowercase version of a string.
end_other('Hiabc', 'abc') → True
end_other('AbC', 'HiaBc') → True
end_other('abc', 'abXabc') → True
'''
def end_other(str1, str2):
str1_last_chat = str1[-1]
str2_last_chat = str2[-1]
#print(str1_last_chat)
#print(str2_last_chat)
if str1_last_chat.lower() == str2_last_chat.lower():
return True
else:
return False
#print(end_other('Abd', 'HiaBc'))
'''
Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.).
So "xxyz" counts but "x.xyz" does not.
xyz_there('abcxyz') → True
xyz_there('abc.xyz') → False
xyz_there('xyz.abc') → True
'''
def xyz_there(string):
check_xyz = string.count('xyz')
dot_count = string.count('.xyz')
#print(f'{check_xyz} and {dot_count}')
if check_xyz==dot_count:
return False
else:
return True
#print(xyz_there('.xyzabc'))
#--------------------------list-2---------------------------------------------------------
'''
Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0
'''
def count_evens(numbers):
count = 0
for i in numbers:
if i%2==0:
count = count +1
return count
#print(count_evens([1, 3, 5]))
'''
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
'''
def big_diff(numbers):
lg_num = max(numbers)
sm_num = min(numbers)
difference = lg_num - sm_num
return difference
print(big_diff([7, 2, 10, 9]))
'''
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value. Use int division to produce the final average.
You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) → 3
centered_average([1, 1, 5, 5, 10, 8, 7]) → 5
centered_average([-10, -4, -2, -4, -2, 0]) → -3
'''
def centered_average():
pass
'''
Return the sum of the numbers in the array, returning 0 for an empty array.
Except the number 14 is very unlucky, so it does not count and numbers that come immediately after a 14 also do not count.
sum14([1, 2, 2, 1]) → 6
sum14([1, 1]) → 2
sum14([1, 2, 2, 1, 14]) → 6
'''
def sum14(numbers):
sum = 0
#i = 0
for i in range(len(numbers)-1):
if numbers[i] == 14:
numbers.pop(i)
sum = sum + numbers[i]
return sum
#print(sum14([1, 2,1,1,2,14,1,1]))
'''
Return the sum of the numbers in the array,
except ignore sections of numbers starting with a 6 and extending to the next 7
(every 6 will be followed by at least one 7). Return 0 for no numbers.
sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
'''
def sum67(numbers):
result = 0
flag = True
for num in numbers:
if num == 6:
flag = False
if flag:
result += num
if num == 7:
flag = True
return result
print(sum67([1, 2, 2, 6, 99, 99, 7]))
'''
Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False
'''
def has22(nums):
for i in nums:
if nums[i] == 2 and nums[i+1] == 2:
return True
else:
return False
#print(has22([1, 2, 1, 2])) |
d3b72253c5aad86dcff61d706444521bdf67be76 | Anas2-L/Projects | /2ndhighest.py | 301 | 3.875 | 4 | def secondhigh(list1):
new_list=set(list1)
new_list.remove(max(new_list))
return max(new_list)
list1=[]
n=int(input("enter list size "))
for i in range(n):
x=input("\nenter the element ")
list1.append(x)
print("original list\n",list1)
print(secondhigh(list1))
|
86b4a2b74893cb40f1e19f469d059be178b838cc | Anas2-L/Projects | /extractdigits.py | 176 | 3.984375 | 4 | num=int(input("Enter a number"))
temp=num
while (temp>=1):
if(temp%10==0):
print(0)
else:
print(int(temp%10))
temp=int(temp/10)
print(num) |
600ef001b64ebd30b8687ab622b9e7549f714437 | MaX-Lo/ProjectEuler | /116_red_green_blue_tiles.py | 1,313 | 3.640625 | 4 | """
idea:
"""
import copy
import time
# 122106096, 5453760
def main():
max_row_len = 50
print('row length:', max_row_len)
if max_row_len % 2 == 0:
start = 2
combinations = 1
else:
combinations = 0
start = 1
for gaps in range(start, max_row_len-1, 2): # step 2 because only even num of gaps is possible
tmp_combinations = get_gap_combinations(gaps, max_row_len)
combinations += tmp_combinations
# print('gaps', gaps, 'combs', tmp_combinations)
print('all combinations for block len 2:', combinations)
def increasing_nums(nums, max_num):
max_num += 1
count = {i: 1 for i in range(max_num)}
for i in range(1, nums):
tmp_count = {}
for num in range(max_num):
tmp_count[num] = 0
for j in range(num, max_num):
tmp_count[num] += count[j]
count = copy.deepcopy(tmp_count)
res = 0
for num in count:
res += count[num]
return res
def get_gap_combinations(gaps, row_len):
if (row_len-gaps) % 2 != 0:
print("blocks can't be even")
max_jumps = (row_len - gaps) // 2
return increasing_nums(gaps, max_jumps)
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time) |
ff5a073e2083ce23400d787e87907011818b01c6 | MaX-Lo/ProjectEuler | /035_circular_primes.py | 1,284 | 3.75 | 4 | """
Task:
"""
import time
import primesieve as primesieve
def main():
primes = set(primesieve.primes(1000000))
wanted_nums = set()
for prime in primes:
str_prime = str(prime)
all_rotations_are_prime = True
for rotation_num in range(len(str_prime)):
str_prime = str_prime[1:] + str_prime[0]
if int(str_prime) not in primes or str_prime in wanted_nums:
all_rotations_are_prime = False
break
if all_rotations_are_prime:
wanted_nums.add(prime)
print(wanted_nums)
print("num of these primes:", len(wanted_nums))
def all_primes(limit):
# list containing for every number whether it has been marked already
numbers = {}
for x in range(3, limit, 2):
numbers[x] = False
primes = [2, 3]
p = 3
while p < limit:
for i in range(p, limit, p):
numbers[i] = True
for i in range(p, limit, 2):
if not numbers[i]:
p = i
numbers[i] = True
primes.append(i)
break
else:
p += 1
return primes
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
53161d215504eeb7badb8105197bd926091b971b | MaX-Lo/ProjectEuler | /074_digit_factorial_chains.py | 696 | 3.734375 | 4 | """
idea:
"""
import time
import math
def main():
t0 = time.time()
count = 0
for i in range(1, 1000000):
if i % 10000 == 0:
print('{}%, {}sec'.format(i / 10000, round(time.time() - t0), 3))
if get_chain_len(i) == 60:
count += 1
print('wanted num:', count)
def get_chain_len(num):
chain = set()
element = num
while element not in chain:
chain.add(element)
tmp = 0
for digit in str(element):
tmp += math.factorial(int(digit))
element = tmp
return len(chain)
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
2e9c25015e590a2139ab7e423d23ab8402a941be | MaX-Lo/ProjectEuler | /helpers_inefficient.py | 2,442 | 3.828125 | 4 |
def all_primes(limit):
segment_size = 20000000
if limit <= segment_size:
return primes_euklid(limit)
primes = primes_euklid(segment_size)
iteration = 1
while limit > segment_size * iteration:
print("progress, at:", segment_size * iteration)
start = segment_size*iteration
end = segment_size * (iteration + 1)
primes = segmented_primes(start, end, primes)
iteration += 1
start = segment_size*iteration
end = limit
if start == end:
return primes
else:
return segmented_primes(start, end, primes)
def primes_euklid(limit):
# list containing for every number whether it has been marked already
numbers = {}
for x in range(3, limit, 2):
numbers[x] = False
primes = [2, 3]
p = 3
while p < limit:
for i in range(p, limit, p):
numbers[i] = True
for i in range(p, limit, 2):
if not numbers[i]:
p = i
numbers[i] = True
primes.append(i)
break
else:
p += 1
return primes
def segmented_primes(n, limit, primes):
"""
:param n: start value to search for primes
:param limit: end value to search for primes
:param primes: primes smaller than n
:return:
"""
if n % 2 == 0:
n -= 1
# create dict with numbers in that segment
numbers = {}
for x in range(n, limit, 2):
numbers[x] = False
# Todo marking takes like forever...
# mark all numbers that are multiples of primes in the given list of primes for smaller numbers
for num in numbers:
for prime in primes:
if num % prime == 0:
numbers[num] = True
if numbers[num]:
break
# find the first prime in this segment to start with
p = -1
for num in numbers:
if not numbers[num]:
p = num
primes.append(p)
break
if p == -1:
print("Error, no prime in segment found...")
# sieve primes in the segment
while p < limit:
for i in range(p, limit, p):
numbers[i] = True
for i in range(p, limit, 2):
if not numbers[i]:
p = i
numbers[i] = True
primes.append(i)
break
else:
p += 2
return primes |
72a56a90e4a26e0f1423c95f5d517a07eade3e5d | MaX-Lo/ProjectEuler | /061_cyclical_figurate_numbers.py | 3,131 | 3.640625 | 4 | """
idea:
"""
import time
def main():
# lists containing 4-digit polygonal numbers as strings
triangles = generate_figurate_nums(1000, 10000, triangle)
squares = generate_figurate_nums(1000, 10000, square)
pentagonals = generate_figurate_nums(1000, 10000, pentagonal)
hexagonals = generate_figurate_nums(1000, 10000, hexagonal)
heptagonals = generate_figurate_nums(1000, 10000, heptagonal)
octagonals = generate_figurate_nums(1000, 10000, octagonal)
# for every number in squares:
# - check in other polygonal lists for numbers beginning with
# the last two digits of this square number
# - repeat that 5 times
# all in all that should be some recursion algorithm
lists_to_check_in = [squares, pentagonals, hexagonals, heptagonals, octagonals]
for current_num in triangles:
first_num = current_num
last_two = first_num[-2:]
for polygonal_list in lists_to_check_in:
for next_num in polygonal_list:
first_two = next_num[:2]
if first_two == last_two:
new_to_check_list = list(lists_to_check_in)
new_to_check_list.remove(polygonal_list)
ist, elements = is_cyclic(first_num, next_num, new_to_check_list)
elements = list(elements)
elements.insert(0, first_num)
if ist:
print(elements)
print('sum:', sum([int(ele) for ele in elements]))
def is_cyclic(first_num, current_num, lists_to_check_in):
# recursion termination condition
if len(lists_to_check_in) == 0:
last_two = current_num[-2:]
first_two = first_num[:2]
cyclic = last_two == first_two
if cyclic:
print('cyclic, start num:', first_num)
return True, [current_num]
else:
return False, [current_num]
# recursive check elements in remaining polygonal lists
last_two = current_num[-2:]
for polygonal_list in lists_to_check_in:
for next_num in polygonal_list:
first_two = next_num[:2]
if first_two == last_two:
new_to_check_list = list(lists_to_check_in)
new_to_check_list.remove(polygonal_list)
ist, elements = is_cyclic(first_num, next_num, new_to_check_list)
if ist:
elements.insert(0, current_num)
return ist, elements
return False, []
def triangle(n):
return n * (n + 1) / 2
def square(n):
return n**2
def pentagonal(n):
return n*(3*n-1)/2
def hexagonal(n):
return n*(2*n-1)
def heptagonal(n):
return n*(5*n-3)/2
def octagonal(n):
return n*(3*n-2)
def generate_figurate_nums(n_min, n_max, func):
nums = []
n = 0
i = 1
while func(i) < n_max:
n = func(i)
if n >= n_min: # Todo n_min:
nums.append(str(int(n)))
i += 1
return nums
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time) |
6f71761903964bc4431f50a80a58665eb926749b | MaX-Lo/ProjectEuler | /549_divisibility_of_factorials.py | 1,718 | 3.671875 | 4 | """
idea:
"""
import time
import math
import primesieve
def main():
limit = 10**8
primes = primesieve.primes(limit)
primes_s = set(primes)
# key: (prime^power), value: s(prime^power)
cache = dict()
for prime in primes:
power = 1
while prime ** power < limit:
fac = prime
k = prime
while fac % prime**power != 0:
k += prime
fac *= k
cache[(prime, power)] = k
power += 1
print('finished building cache')
# approach with calculating factorization for every single number
res = 0
time0 = time.time()
for i in range(2, limit+1):
if i % 100000 == 0:
print('prog', i, round(time.time() - time0, 2), 'sec')
if i in primes_s:
res += i
else:
tmp = s(i, primes, cache)
res += tmp
print('result', res)
def s(n, primes, cache):
#factors = factorint(n)
factors = factorization(n, primes)
return max([cache[(factor, factors[factor])] for factor in factors])
def factorization(n, primes):
"""
:param n: number to factorize
:param primes: list with primes
:return: dictionary with primes that occur (and count of them)
"""
factors = {}
while n != 1:
for prime in primes:
if n % prime == 0:
#print(n)
n //= prime
if prime in factors:
factors[prime] += 1
else:
factors[prime] = 1
break
return factors
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
a3bc3257a40b563f88fae09094d1b2de401d4d6f | MaX-Lo/ProjectEuler | /005_evenly_divisible.py | 639 | 3.609375 | 4 | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import time
def main():
start = time.time()
# n=20 > 26.525495767593384, >232792560
n = 9699690 #2*3*5*7*11*13*17*19
print(n)
while not is_devisible(n):
n += 9699690
print(time.time()-start)
print(n)
def is_devisible(n):
devisible = True
for i in range(11, 20):
if n % i != 0:
devisible = False
return devisible
if __name__ == '__main__':
main() |
b1631d263871aaeaa21ed313eefa8ab8f9c2326a | MaX-Lo/ProjectEuler | /102_triangle_containment.py | 1,835 | 3.6875 | 4 | """
idea:
"""
import time
def main():
data = read_file('102_triangles.txt')
count = 0
#print(contains_origin([-340, 495, -153, -910, 835, -947]))
for triangle in data:
print(contains_origin(triangle))
if contains_origin(triangle):
count += 1
print('count:', count)
def contains_origin(points):
"""
idea: check whether one line is above origin and one line is under
it if yes the triangle has to contain the origin
"""
above = False
under = False
x1, y1, x2, y2, x3, y3 = points
t_above, t_under = check_line([x1, y1, x2, y2])
if t_above:
above = True
if t_under:
under = True
t_above, t_under = check_line([x1, y1, x3, y3])
if t_above:
above = True
if t_under:
under = True
t_above, t_under = check_line([x2, y2, x3, y3])
if t_above:
above = True
if t_under:
under = True
return above and under
def check_line(points):
above = False
under = False
if points[0] > points[2]:
xb, yb = points[0], points[1]
xs, ys = points[2], points[3]
else:
xb, yb = points[2], points[3]
xs, ys = points[0], points[1]
if xb >= 0 and xs <= 0:
m = (yb - ys) / (xb - xs)
f0 = ys + m * abs(xs)
if f0 > 0:
above = True
elif f0 < 0:
under = True
else:
above = True
under = True
return above, under
def read_file(filename):
data_file = open(filename)
data_set = []
for line in data_file.readlines():
values = [int(x) for x in line.strip().split(',')]
data_set.append(values)
return data_set
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
7abf47c117213f72142f2bb9daeaaffe0cf58de4 | MaX-Lo/ProjectEuler | /034_digit_factorials.py | 406 | 3.6875 | 4 | """
Task:
"""
import time
import math
def main():
wanted_nums = []
for i in range(3, 1000000):
num_sum = 0
for digit in str(i):
num_sum += math.factorial(int(digit))
if i == num_sum:
wanted_nums.append(i)
print(wanted_nums)
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
b17f9bb2ee4cc729989a34c3631f53961fc450f8 | MaX-Lo/ProjectEuler | /106_special_subset_sums_meta_testing.py | 2,005 | 3.578125 | 4 | """
idea:
"""
import copy
import time
import itertools
import math
def main():
sets = [
[1], # 1
[1, 2], # 2
[2, 3, 4], # 3
[3, 5, 6, 7], # 4
[6, 9, 11, 12, 13], # 5
[11, 18, 19, 20, 22, 24], # 6
[47, 44, 42, 27, 41, 40, 37], # 7
[81, 88, 75, 42, 87, 84, 86, 65], # 8
[157, 150, 164, 119, 79, 159, 161, 139, 158], # 9
[354, 370, 362, 384, 359, 324, 360, 180, 350, 270], # 10
[673, 465, 569, 603, 629, 592, 584, 300, 601, 599, 600], # 11
[1211, 1212, 1287, 605, 1208, 1189, 1060, 1216, 1243, 1200, 908, 1210] # 12
]
i = 1
for my_set in sets:
count = test(my_set)
print(i, ' len needs tests:', count)
i += 1
def test(nums: list):
""" list is sorted ascending"""
# check if a subset with more nums than another subset has also a greater sum
nums.sort()
count = 0
for subset_len in range(2, len(nums)//2 + 1):
for subset1 in itertools.combinations(nums, subset_len):
remaining = copy.deepcopy(nums)
for num in subset1:
remaining.remove(num)
for subset2 in itertools.combinations(remaining, subset_len):
l1 = list(subset1)
l1.sort()
l2 = list(subset2)
l2.sort()
l1_ascending = False
l1_descending = False
for i in range(len(l1)):
if l1[i] < l2[i]:
if l1_ascending:
count += 1
break
l1_descending = True
elif l1[i] > l2[i]:
if l1_descending:
count += 1
break
l1_ascending = True
return count / 2
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
0fe3da6717019161da1ef5c1d3b1bbb451299b30 | MaX-Lo/ProjectEuler | /064_odd_period_square_roots.py | 950 | 3.984375 | 4 | """
idea:
"""
import time
import math
def main():
num_with_odd_periods = 0
for i in range(2, 10001):
if math.sqrt(i) % 1 == 0:
continue
count = continued_fraction(i)
if count % 2 == 1:
num_with_odd_periods += 1
print('rep len for {}: {}'.format(i, count))
print('count of nums with odd periods:', num_with_odd_periods)
def continued_fraction(num):
"""
square root of any natural number that is not a perfect square
e.g. 3, 5, 6, 7... but not 4, or 9
"""
s = num
sqrtS = math.sqrt(num)
a0 = math.floor(sqrtS)
m = 0
d = 1
a = a0
count = 0
while True:
m = d * a - m
d = (s - m**2) / d
a = math.floor((a0 + m) / d)
count += 1
if a == 2*a0:
break
return count
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
f31fcec47d734feaf6f5d680b6625e88acaa1048 | MaX-Lo/ProjectEuler | /039_integer_right_triangles.py | 1,453 | 3.828125 | 4 | """
idea:
"""
import time
import math
def main():
p_with_max_solutions = -1
max_solutions = -1
for perimeter in range(1, 1001):
print(perimeter)
wanted_nums = []
a = 0
b_and_c = perimeter
while b_and_c >= a:
b_and_c -= 1
a += 1
for i in range(b_and_c):
b = i
c = b_and_c - i
if b >= a or c >= a:
continue
if is_right_angle_triangle(a, b, c):
wanted_nums.append((a, b, c))
num_solutions = len(wanted_nums) / 2 # every triplet
if num_solutions > max_solutions:
p_with_max_solutions = perimeter
max_solutions = num_solutions
print("max solutions num:", max_solutions)
print("p with max solutions:", p_with_max_solutions)
def is_right_angle_triangle(a, b, c):
hypothenus = -1
n1 = -1
n2 = -1
if a >= b and a >= c:
hypothenus, n1, n2 = a, b, c
elif b >= a and b >= c:
hypothenus, n1, n2 = b, a, c
elif c >= a and c >= b:
hypothenus, n1, n2 = c, a, b
angle1 = math.degrees(math.asin(n1 / hypothenus))
angle2 = math.degrees(math.asin(n2 / hypothenus))
angle_3 = 180 - angle1 - angle2
return math.fabs(90 - angle_3) < 0.0000001
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time) |
de55784264f1f52758efe3b09550520df5be25c1 | MaX-Lo/ProjectEuler | /119_digit_power_sum.py | 711 | 3.640625 | 4 | """
idea:
"""
import time
import math
def main():
upper_limit = 10**13
found_nums = []
for x in range(2, int(math.sqrt(upper_limit))):
if x % 100000 == 0:
print('prog:', x)
p = x
while p < upper_limit:
p *= x
if digit_sum(p) == x:
found_nums.append(p)
found_nums.sort()
print('found {} nums'.format(len(found_nums)))
print(found_nums)
if len(found_nums) >= 30:
print('30th:', found_nums[29])
def digit_sum(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
if __name__ == '__main__':
start_time = time.time()
main()
print("time:", time.time() - start_time)
|
65298718ef4f0c1af6cc574f2d9aba856412af29 | itCatface/idea_python | /py_pure/src/catface/introduction/04_functional_programming/3_lambda.py | 509 | 3.90625 | 4 | # -匿名函数
# --ex1
l = [1, 3, 5, 7, 9]
r = map(lambda x: x * x, l)
print(list(r))
# --ex2
print('匿名函数结果:', list(map((lambda x: x * 2), l)))
# --ex3. 可以把匿名函数作为返回值返回
f = lambda x, y: x * y
print('使用匿名函数计算:', f(2, 3))
# lambda x: x * x --> def f(x): return x * x
# --ex4. 改造以下代码
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
print(L)
r = filter(lambda x: x % 2 == 1, range(1, 20))
print(list(r))
|
67d1cde085301b30592e61152369c2609144305a | itCatface/idea_python | /py_pure/src/catface/introduction/06_oo_junior/2_access_restrict.py | 864 | 3.96875 | 4 | # -访问限制
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
# 检查分数
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
return ValueError('invalid score!')
def get_score(self):
return self.__score
def print(self):
print('name: %s, score: %s' % (self.__name, self.__score))
s = Student('kobe', 8)
print('s.get_name:', s.get_name())
print('s.get_score:', s.get_score())
s.set_score(24)
print('s.get_score:', s.get_score())
print(s.set_score(-1))
# 这里只是给实例s新增了__score变量
s.__score = 99
print('s.get_score:', s.get_score(), ' || s.__score:', s.__score)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.