blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
f67473adfd19b3970bff592ccbd9cfe165e15341 | Jason171096/Udemy_Python | /20-Proyecto/login.py | 1,570 | 3.515625 | 4 | import bd
import menu
import getpass
import datetime
date = datetime.datetime.now()
def loguear(op):
if op == 1:
print("¡Ok, vamos a registrarte!")
nom = input(" Nombre: ")
ape = input(" Apellido: ")
email = input(" Introduce Email: ")
password = getpass.getpass(" Introduce contraseña: ")
checkpass = getpass.getpass(" Verificar contraseña: ")
if password != checkpass:
print("¡ERROR!")
print("¡CONTRASEÑAS NO COINCIDEN INTENTE DE NUEVO!")
loguear(1)
else:
boolean = bd.insertUser(nom, ape, email, password)
if(boolean):
print(f"Registro completo {nom}")
else:
print(f"Error en el registro")
elif op == 2:
print("¡Ok vamos a iniciar sesion!")
email = input("Introduce Email: ")
password = getpass.getpass("Introduce contraseña: ")
boolean = bd.checkUser(email, password)
if(boolean):
usuario = bd.returnName(email)
idusuario = 0
nombreusuario = ""
for detailsUsuario in usuario:
idusuario = int(detailsUsuario[0])
nombreusuario = str(detailsUsuario[1])
print("------------------------------")
print(f"Bienvenido {nombreusuario} Fecha: {date}")
print("------------------------------")
menu.notas(idusuario, nombreusuario)
else:
print(f"Error al iniciar sesion")
loguear(2) |
6f5d24b8fae1750836b9092d832ec7906db27995 | GwenStacey/DBScan | /dbscan.py | 3,382 | 3.90625 | 4 | from scipy.spatial.distance import cdist
import numpy as np
class DBScan():
"""This is a simple implementation of clustering using the
DBScan algorithm.
My algorithm will return labels for clusters, -1 indicating
an outlier"""
def __init__(self, max_dist, min_pts):
self.data = None
self.max_dist = max_dist
self.min_pts = min_pts
self.labels = None
"""The following list will hold the final label assignments
I'll initialize it with 0's, but cluster assignment will start
at 1"""
"""Next for each point P in data, I'll run a function to
determine if a point is a valid seed, then fill out the cluster
with reachable points"""
def fit(self, data):
self.data = data
self.labels = [0] * len(self.data)
cluster = 0
for P in range(0,len(self.data)):
reachable = self.find_reachable(P)
"""If a point isn't a valid seed, it's an outlier, this is the only
condition when a label is set to outlier it may still be claimed
as a boundary point for a cluster later"""
if len(reachable)<self.min_pts:
self.labels[P] = -1
elif self.labels[P]==0:
cluster+=1
self.create_cluster(P, cluster, reachable)
return self.labels
def predict(self, P):
"""Given a new point of data, P assign it a cluster label"""
for i in range(0, len, self.data):
if cdist(np.reshape(P,(-1,2)), np.reshape(self.data[i],(-1,2))) < self.max_dist:
return self.labels[i]
def create_cluster(self, P, cluster, reachable):
"""Given a valid seed point, create the cluster with
every point that belongs according to distance threshold"""
self.labels[P] = cluster
"""Run a while loop, to step through each point in our seed's
list of reachable, checking for each of their neighbors, adding them
to this cluster, if they aren't already in another cluster"""
i=0
while i < len(reachable):
next_point = reachable[i]
#If the label was previously noise, it's not a valid branch
#So we'll just add it to the cluster and move on
if self.labels[next_point] == -1:
self.labels[next_point] = cluster
#If the point was unclaimed, let's claim it, and grow from there
elif self.labels[next_point] == 0:
self.labels[next_point] = cluster
next_point_reachable = self.find_reachable(next_point)
#If this point is a valid branch, let's get it's neighbors in here too
if len(next_point_reachable)>self.min_pts:
reachable = reachable + next_point_reachable
i+=1
def find_reachable(self, P):
"""The following function will take a point in data
and find reachable points from it"""
reachable = []
for i in range(0, len(self.data)):
if cdist(np.reshape(self.data[P],(-1,2)), np.reshape(self.data[i],(-1,2)))<self.max_dist:
"""If the distance between the point and a given point in data
let's add it to a list of reachable points"""
reachable.append(i)
return reachable |
d433900396d4fecd6631b5756518e22f4787e8f6 | hrssurt/lintcode | /lintcode/628 Maximum Subtree.py | 1,438 | 3.703125 | 4 | """*************************** TITLE ****************************"""
"""628 Maximum Subtree.py"""
"""*************************** DESCRIPTION ****************************"""
"""
Given a binary tree, find the subtree with maximum sum. Return the root of the subtree.
"""
"""*************************** EXAMPLES ****************************"""
"""
Input:
{1,-5,2,0,3,-4,-5}
Output:3
Explanation:
The tree is look like this:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
The sum of subtree 3 (only one node) is the maximum. So we return 3.
"""
"""*************************** CODE ****************************"""
class Solution:
def findSubtree(self, root):
def dfs(root):
if not root:
return None, 0, float("-inf") # max node, sum of tree, max_sum
root_val = root.val
left_node, left_sum, left_max = dfs(root.left)
right_node, right_sum, right_max = dfs(root.right)
sum_of_tree = left_sum + root_val + right_sum
max_sum = max(sum_of_tree, left_max, right_max)
if max_sum == left_max:
return left_node, sum_of_tree, left_max
elif max_sum == right_max:
return right_node, sum_of_tree, right_max
else: # this root is the new max
return root, sum_of_tree, max_sum
return dfs(root)[0]
|
b5fd1d2c7f48c4e0cc234e0ffbf9066336d888b8 | Coliverfelt/Desafios_Python | /Desafio010.py | 281 | 4.125 | 4 | # Exercício Python 010: Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
# e mostre quantos dólares ela pode comprar.
reais = float(input('Quantos R$ você possui na carteira?\n'))
print('Com R${:.2f} você pode comprar U${:.2f}.'.format(reais, reais/3.27)) |
567c180c33b1909937b58e3810b5b9d70d96cd0c | Rowlandgh/python | /python_study/测试用例/name_function.py | 512 | 3.921875 | 4 | def get_formatted_name(firstname,lastname):
full_name = firstname + ' ' + lastname
return full_name.title()
def get_formatted_name_2(firstname,middlename,lastname):
full_name_2 = firstname + ' ' + middlename + ' ' + lastname
return full_name_2.title()
def get_formatted_name_3(firstname,lastname,middlename=''):
if middlename:
full_name_3 = firstname + ' ' + middlename + ' ' + lastname
else:
full_name_3 = firstname + ' ' + lastname
return full_name_3.title()
|
3a8936ce1b627ad70cec7c5ab1f962eab754a526 | leohong1106/my_python | /gugudan.py | 191 | 3.703125 | 4 | #구구단 2단
for i in range(1,10):
print('{}x{}={}'.format(2,i,2*i))
#구구단 2~9단
for x in range(2,10):
for y in range(1,10):
print('{}x{}={}'.format(x,y,x*y)) |
37ccf299958755d6d94c0900d567f2d584527df2 | jonathangriffiths/Euler | /Page1/CollatzSequence.py | 1,309 | 4 | 4 | __author__ = 'Jono'
#iterative: n even --> n/2; n odd --> 3n+1
#ends at 1
#which number under 1,000,000 has longest chain
#Thoughts: whenever we hit an a number we know (3n+1 or n/2) can simply refer back to the known chain length
def max_length_collatz(n):
#create list of numbers that need testing
num_to_test = range(1,n+1)
#create list of lengths for each number (i.e. position 0 is for 1, 200 is for 201 etc)
terms_for_num = []
for i in num_to_test:
value = i
terms = 1
while value != 1:
#if the value has already been calculated we can just add on the number of terms already found
if value <= len(terms_for_num) :
#minus 1 to remove the duplicated 1
terms += (terms_for_num[value-1] - 1)
break
#Otherwise we just proceed to next term
elif value % 2 == 0:
value /= 2
terms += 1
elif value % 2 == 1:
value = 3*value + 1
terms += 1
#Then we add the number of terms for the number to the list of answers
terms_for_num.append(terms)
#want to return the number with the most terms:
return terms_for_num.index(max(terms_for_num))+1
print max_length_collatz(1000000) |
bea91c2ceaaee796479797ce0dda05ae270f10a7 | tangjikuo/studentsmanage | /common/database.py | 1,917 | 3.515625 | 4 | import pymysql
from common.Config import config
class Database:
"""
this class is defined a database connection which can
execute QUERY INSERT UPDATE DELETE options
"""
def __init__(self):
self.db = pymysql.connect(host=config["host"], port=config["port"], user=config["username"],
passwd=config["password"], db=config["schema"], charset='utf8')
self.cursor = self.db.cursor()
def query(self, sql):
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
print("query success,the result is:{}".format(result))
except Exception as e:
print("query failed! the reason is: {}".format(e))
def update(self, sql):
try:
self.cursor.execute(sql)
self.db.commit()
print("update data success.")
except Exception as e:
self.db.rollback()
print("update failed.the reason is: {}".format(e))
def insert(self, sql):
try:
self.cursor.execute(sql)
self.db.commit()
print("insert data success.")
except Exception as e:
self.db.rollback()
print("insert failed.the reason is: {}".format(e))
def delete(self, sql):
try:
self.cursor.execute(sql)
self.db.commit()
print("delete data success.")
except Exception as e:
self.db.rollback()
print("delete failed.the reason is: {}".format(e))
def quit(self):
self.cursor.close()
self.db.close()
if __name__ == "__main__":
database = Database()
# test query function
sql = "select * from student"
database.query(sql)
# test insert
sql = "insert into student(name,sex,stu_no,tea_no,score) values('test2','man','123453','123','23')"
database.insert(sql)
|
30fed9007f137e81267b412d32b04ccc00f9de55 | Potatology/coding | /sorting/merge_sort.py | 667 | 3.609375 | 4 | A = [4,8,2,7,5,5,5]
def merge_sort(A):
if len(A)>1:
left = merge_sort(A[:len(A)//2])
right = merge_sort(A[len(A)//2:])
merge(A, left, right)
return A
def merge(A, Aleft, Aright):
i = 0
j = 0
k = 0
while i < len(Aleft) and j < len(Aright):
if Aleft[i] < Aright[j]:
A[k] = Aleft[i]
i+=1
k+=1
else:
A[k] = Aright[j]
k+=1
j+=1
while i < len(Aleft):
A[k] = Aleft[i]
i+=1
k+=1
while j < len(Aright):
A[k] = Aright[j]
j+=1
k+=1
return A
print(merge_sort(A))
|
1206e1c8500de540d8f92986d8fcc913864b0a8a | KLDistance/py3_simple_tutorials | /Fundamentals/OOM/inheritance.py | 601 | 3.890625 | 4 | class BaseClass :
base_var = 100
def __init__(self, input_var) :
self.base_var += input_var
print("base class constructor is called!")
def BaseFunc(self) :
print("base member function is called!")
class SubClass(BaseClass) :
sub_var = 400
def __init__(self) :
BaseClass.__init__(self, 200)
print("sub class constructor is called!")
def SubFunc(self) :
print("sub member function is called!")
subclass = SubClass()
subclass.BaseFunc()
subclass.SubFunc()
print(subclass.base_var)
print(subclass.sub_var)
|
b70b3b8141f71fc342a4e3c0bddbf6335f93b3b7 | mydios/Dollar-Cost-Averaging | /graphs.py | 559 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module containing graphing functions
"""
__author__ = 'Dylan Van Parys'
__copyright__ = 'Copyright 2020'
__license__ = 'MIT'
import pandas as pd
import seaborn
import matplotlib.pyplot as plt
def graph_lineplot(df, xn=None, yn=None):
seaborn.lineplot(data = df, x=xn, y=yn)
plt.show()
def graph_barplot(df, xn=None, yn=None, ylim=None, title=None):
seaborn.barplot(data = df, x=xn, y=yn)
if ylim is not None:
plt.ylim(ylim)
if title is not None:
plt.title(title)
plt.show()
|
e8fe7f6f2559b455eb01681fac442095f45e60e1 | guynaor05/Snake | /main.py | 8,310 | 3.53125 | 4 | import pygame
import random
import tkinter as tk
from tkinter import messagebox
pygame.init()
screen_width = 1000
screen_height = 1000
display = pygame.display.set_mode((screen_width, screen_height))
snake_block = 25
red_color = (255, 0, 0)
rows = screen_height // snake_block
running = True
def draw_bored():
x, y = 0, 0
for _ in range(rows):
x += snake_block
y += snake_block
# draws a line from start point given in parameter 3 to end point given in parameter 4
pygame.draw.line(display, (128, 128, 128), (x, 0), (x, screen_width))
pygame.draw.line(display, (128, 128, 128), (0, y), (screen_width, y))
def redraw_window():
display.fill((0, 0, 0))
snake.draw()
snack.draw(display)
draw_bored()
pygame.display.update()
class Cube(object):
def __init__(self, start, color=(255, 0, 0)):
self.pos = start
self.dirnx = 0
self.dirny = 0
self.color = color
def move(self, dirnx, dirny):
self.dirnx = dirnx
self.dirny = dirny
# change the position of the cube
self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)
def draw(self, eyes=False):
i = self.pos[0]
j = self.pos[1]
# draws the snake without eyes
pygame.draw.rect(display, self.color,
(i * snake_block + 1, j * snake_block + 2, snake_block - 2, snake_block - 2))
# draws with eyes if the eyes == True
if eyes:
center = snake_block // 2
radius = 4
# making both of the eyes for the head of the snake
circle_middle = (i * snake_block + center - radius, j * snake_block + 6)
circle_middle2 = (i * snake_block + snake_block - radius * 2, j * snake_block + 6)
# drawing the eyes on the head
pygame.draw.circle(display, (0, 0, 0), circle_middle, radius)
pygame.draw.circle(display, (0, 0, 0), circle_middle2, radius)
class Snake(object):
body = []
turns = {}
def __init__(self, color, pos, game_finished):
self.color = color
self.game_finished = game_finished
self.head = Cube(pos)
self.body.append(self.head)
self.dirnx = 0
self.dirny = 1
self.score = 0
def move(self):
movingx = self.dirnx
movingy = self.dirny
# searches for a movement on keyboard
for snake_event in pygame.event.get():
if snake_event.type == pygame.QUIT:
self.game_finished = True
if snake_event.type == pygame.KEYDOWN:
if snake_event.key == pygame.K_UP and len(self.body) == 1:
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_DOWN and len(self.body) == 1:
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_LEFT and len(self.body) == 1:
self.dirnx = -1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_RIGHT and len(self.body) == 1:
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
if snake_event.key == pygame.K_UP and movingy != 1 and movingx != 0 and len(self.body) > 1:
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_DOWN and movingx != 0 and movingy != -1 and len(self.body) > 1:
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_LEFT and movingx != 1 and movingy != 0 and len(self.body) > 1:
self.dirnx = -1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif snake_event.key == pygame.K_RIGHT and movingx != -1 and movingy != 0 and len(self.body) > 1:
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
# checks for turns and move the snake
for i, c in enumerate(self.body):
p = c.pos[:]
if p in self.turns:
turn = self.turns[p]
c.move(turn[0], turn[1])
if i == len(self.body) - 1:
self.turns.pop(p)
# checks if the snake touches the walls and end the game if the snake does
else:
if c.dirnx == -1 and c.pos[0] <= 0:
message_box(self.score)
snake.reset((10, 10))
elif c.dirnx == 1 and c.pos[0] >= rows - 1:
message_box(self.score)
snake.reset((10, 10))
elif c.dirny == 1 and c.pos[1] >= rows - 1:
message_box(self.score)
snake.reset((10, 10))
elif c.dirny == -1 and c.pos[1] <= 0:
message_box(self.score)
snake.reset((10, 10))
else:
c.move(c.dirnx, c.dirny)
# draws the snake
def draw(self):
for i, c in enumerate(self.body):
if i == 0:
c.draw(True)
else:
c.draw()
# reset game
def reset(self, pos):
self.head = Cube(pos)
self.body = []
self.body.append(self.head)
self.turns = {}
self.dirnx = 0
self.dirny = 1
def add_cube(self):
tail = self.body[-1]
dx, dy = tail.dirnx, tail.dirny
# checks where to add a snake part
if dx == 1 and dy == 0:
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1])))
elif dx == -1 and dy == 0:
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1])))
elif dx == 0 and dy == 1:
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1)))
elif dx == 0 and dy == -1:
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1)))
self.body[-1].dirnx = dx
self.body[-1].dirny = dy
self.score += 1
def random_snack(item):
positions = item.body
while True:
# random x and y
x = random.randrange(rows)
y = random.randrange(rows)
# makes sure that the snack is not on the snake
if len(list(filter(lambda z: z.pos == (x, y), positions))) > 0:
continue
else:
break
return x, y
# i dont really know
def message_box(score):
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
messagebox.showinfo('You Lost!', f'Score: {score}\nPlay again...')
snake.score = 0
try:
root.destroy()
except:
pass
snake = Snake((255, 0, 0), (10, 10), False)
snack = Cube(random_snack(snake), color=(0, 255, 0))
clock = pygame.time.Clock()
while running:
pygame.time.delay(50)
clock.tick(10)
if snake.body[0].pos == snack.pos:
snake.add_cube()
# new snack
snack = Cube(random_snack(snake), color=(0, 255, 0))
# checks if a part of the body touches an other part of it
snake_body = snake.body.copy()
snake_body.remove(snake.head)
for body_cube in snake_body:
if snake.head.pos == body_cube.pos:
# moved body cube that was hit, so we can see the snake head
snake.body.remove(body_cube)
redraw_window()
message_box(snake.score)
snake.reset((10, 10))
snake.move()
if snake.game_finished:
break
redraw_window()
|
40e678b0644215dceac1b83cdc41d3816c7a6904 | ArmandoRuiz2019/Python | /POO/POO03/cuenta.py | 343 | 3.546875 | 4 | '''
Created on Agosto,2019
@author: Armando Ruiz
'''
class Cuenta:
def __init__(self, valor):
self.cantidad = valor
def depositar(self, valor):
if valor > 0:
self.cantidad = self.cantidad + valor
else:
print ("El valor para depositar es erroneo::")
def mostrarDetalles(self):
print ("La cantidad de la cuenta::", self.cantidad) |
437e06511357f23b243a6b47cdda7c3fcf0bcd00 | mzamanian/Rosalind-problems | /ros03_REVC.py | 341 | 4.03125 | 4 | #!/bin/python
DNA = raw_input("> Enter Sequence ")
DNAb = list(DNA)
DNAr = DNAb[::-1]
DNAc = []
for base in DNAr:
if base == 'A':
DNAc.append('T')
elif base == 'C':
DNAc.append('G')
elif base == 'G':
DNAc.append('C')
elif base == 'T':
DNAc.append('A')
else:
print "non-DNA character in string!"
exit()
print ''.join(DNAc) |
d52bdbd1ee5f5d3fd9bd747f1c5b6eb2b43619e4 | Meercat33/hailstone_sequence | /hailstone.py | 304 | 4.03125 | 4 | userNum = int(input("Enter a number: "))
def hailstone(num):
if num % 2 == 0:
num //= 2
elif num % 2 == 1:
num*=3
num+=1
return num
while userNum != 1:
print(hailstone(userNum))
userNum = hailstone(userNum)
print("Press enter to close")
input()
|
5b0afac17e63474f608ad990ca306f06f080e6e7 | uniqueDevelop/Introduction-to-Computer-Science-and-Programming-Using-Python-MIT- | /Bisection Search | 598 | 4.03125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 10:33:14 2018
@author: elenachumakova
"""
# Bisection search
# Compute square root of a number using bisection search
x = 25
epsilon = 0.01
numGuesses = 0
low = 1.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))
|
64db7ee4d6cf1d36c60a49f289875b5215de2653 | zackcpetersen/data_structures_algorithms | /graphs/implement_graph.py | 1,154 | 3.765625 | 4 | class Graph:
def __init__(self):
self.number_of_nodes = 0
self.adjacent_list = {}
def add_vertex(self, node):
self.adjacent_list[node] = []
self.number_of_nodes += 1
def add_edge(self, node1, node2):
keys = self.adjacent_list.keys()
if node1 in keys and node2 in keys:
self.adjacent_list[node1].append(node2)
self.adjacent_list[node2].append(node1)
def show_connections(self):
for node in self.adjacent_list.keys():
node_connections = self.adjacent_list[node]
connections = ''
for vertex in node_connections:
connections += vertex + ' '
print('{} --> {}'.format(node, connections))
my_graph = Graph()
for i in range(7):
my_graph.add_vertex(str(i))
my_graph.add_edge('3', '1')
my_graph.add_edge('3', '4')
my_graph.add_edge('4', '2')
my_graph.add_edge('4', '5')
my_graph.add_edge('1', '2')
my_graph.add_edge('1', '0')
my_graph.add_edge('0', '2')
my_graph.add_edge('6', '5')
my_graph.show_connections()
# Answer:
# 0-->1 2
# 1-->3 2 0
# 2-->4 1 0
# 3-->1 4
# 4-->3 2 5
# 5-->4 6
# 6-->5
|
d4a27ffdb924664f2f33cb2bc05a990b36d17d31 | ewuerfel66/DS-Unit-3-Sprint-1-Software-Engineering | /SC/acme_test.py | 1,489 | 3.546875 | 4 | # Imports
import unittest
from acme import Product
from acme_report import generate_products, prefix, suffix
# Test my Product class
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default product price being 10."""
prod = Product('Test Product')
self.assertEqual(prod.price, 10)
def test_default_weight(self):
"""Test default product weight being 20"""
prod = Product('Test Product')
self.assertEqual(prod.weight, 20)
def test_stealability(self):
"""Test that stealability method works fine"""
prod = Product('Test Product')
prod.price = 100
prod.weight = 10
self.assertEqual(prod.stealability(), "Very stealable!")
# Test my acme_report module
class AcmeReportTests(unittest.TestCase):
"""Ensuring Acme Execs get the best information!"""
def test_default_num_products(self):
"""Test default length"""
self.assertEqual(len(generate_products()), 30)
def test_legal_names(self):
"""Test that all generated names are legal"""
# Find product names
names = [prod.name for prod in generate_products()]
for name in names:
first = name.split()[0]
last = name.split()[1]
self.assertIn(first, prefix)
self.assertIn(last, suffix)
# Call tests
if __name__ == '__main__':
unittest.main() |
096eb2df71222bceb4377ef851d078fcfbe84488 | gonghuiyun/Baimian-camp | /week1/2_fix.py | 1,543 | 3.546875 | 4 | '''
快速选择、堆排序(题号:215):
https://leetcode.com/problems/kth-largest-element-in-an-array/description/
'''
from collections import deque
from math import log
L = deque([50, 16, 30, 10, 60, 90, 2, 80, 70])
L.appendleft(0)
L2 = deque([3,2,1,5,6,4])
L2.appendleft(0)
def swap(L,i,j):
L[i], L[j] = L[j],L[i]
return L
#输入要调整的节点的index
#将此节点与其子节点按堆的规则排序
#node为节点的序号
def node_adjust(L,node):
#先判断node的子节点,将值更大的调到左边
if node*2>len(L)-1:
return L
#只有左子节点
elif node*2+1>len(L)-1:
if L[node]<L[node*2]:
L[node], L[node*2] = L[node*2], L[node]
return L
else:
if L[node*2]<L[node*2+1]:
swap(L,node*2,node*2+1)
#比较node与左子节点的值
if L[node]<L[node*2]:
L[node], L[node*2] = L[node*2], L[node]
return L
def heap_struct(L):
mid = int((len(L)-1)/2)
for i in range(mid):
node_adjust(L,mid-i)
for i in range(mid):
node_adjust(L,i+1)
return L
def findKthLargest(L, k):
if len(L) == 2:
return L[1]
if len(L) == 3:
node_adjust(L, 1)
return L[k]
else:
heap_struct(L)
for i in range(k - 1):
if len(L) == 2:
return L[1]
L[1], L[len(L) - 1] = L[len(L) - 1], L[1]
L.pop()
heap_struct(L)
tmp = L[1]
return tmp
print(findKthLargest(L2,2))
|
2058542d0ce11a22833198088cf4f58e0d627d94 | 7er/gfx | /exercises.py | 1,002 | 3.796875 | 4 | import sys
def print_starline(number):
for each in '*' * number:
sys.stdout.write('%s ' % each)
print
def print_numberline(number):
for each in range(number):
sys.stdout.write('%s ' % each)
print
def print_static_numberline(number):
for each in range(10):
sys.stdout.write('%s ' % number)
print
def print_increasing(number):
for each in range(number + 1):
sys.stdout.write('%s ' % each)
print
def print_decreasing(number):
for each in range(abs(number - 9)):
sys.stdout.write(' ')
for each in range(number + 1):
sys.stdout.write('%s ' % each)
print
# for each in range(9, -1, -1):
# print_decreasing(each)
def print_table(number):
for each in range(1, 10):
product = number * each
if len(str(product)) < 2:
sys.stdout.write(' ')
sys.stdout.write(str(product))
sys.stdout.write(' ')
print
# for each in range(1, 10):
# print_table(each)
|
1e76003e158483555c8535dd765a5c9534e6d587 | oksmina/hyperskill | /Problems/Searching in a descending-sorted list/main.py | 364 | 3.71875 | 4 | numbers = [int(n) for n in input().split()]
target = int(input())
left, right = 0, len(numbers) - 1
result = -1
while left <= right:
middle = (right + left) // 2
if target == numbers[middle]:
result = middle
right = middle - 1
elif target < numbers[middle]:
left = middle + 1
else:
right = middle - 1
print(result)
|
783a01add026b5ac57dedba409ad5e1e061e5751 | hydraer/Python_stydy | /fx/fx_10_公共方法1.py | 1,097 | 4.03125 | 4 | # 公共方法、顾名思义、容器共有的方法
str1 = 'namez'
list1 = [1, 2, 3]
tuple1 = (4, 5, 6)
set1 = {7, 8, 9}
dict1 = {'name': 'circle', 'age': 19}
# 1、运算符 + * in not in
str2 = ' circle'
str3 = str1 + str2
print(str3)
# 2、公共方法len()、del或del()、max()、min()、range(start,end,step)、enumerate()
# len()
print(len(str1))
print(len(list1))
print(len(set1))
print(len(tuple1))
print(len(dict1))
# del()或del()
# del str1[1]
# del list1[1]
# del tuple1[1]
# del set1[1]
# del dict1[1]
# max()
print(max(str1), end= '\t')
print(max(list1), end= '\t')
print(max(tuple1), end= '\t')
print(max(set1), end= '\t')
print(max(dict1))
# min()
print(min(str1), end= '\t')
print(min(list1), end= '\t')
print(min(tuple1), end= '\t')
print(min(set1), end= '\t')
print(min(dict1))
# range(start,end,step)
for i in range(2,0):
print(i)
# enumerate()
for i, j in enumerate(str1):
print(f'下标为{i}的数据为{j}')
# 3、容器类型转换list、set、tuple
list2 = list(str1)
print(list2)
set2 = set(str1)
print(set2)
tuple2 = tuple(str1)
print(tuple2) |
d7f229ff6f972a4129995f3a1682de12217bc976 | shrividhatri/bio231-computational-biology | /Sequence-Analysis-and-Alignments/section3-q1.py | 1,742 | 4.125 | 4 | '''
Naive Pattern Matching - PYTHON
Implement naive pattern matching for DNA sequences in Python/Perl using for/while loops.
Do NOT use regular expressions.
Text should be read from a file whereas the pattern should be read from standard input.
Your programme should identify all occurrences of the pattern in the text.
'''
retry = 'r'
while(retry == 'r'):
pattern = input("Enter pattern to search: ") # input by user
filename = input("Enter name of text file to search in (e.g. example.txt): ")
# open file with given filename with read and text flag then read string from it
text = open(filename,'r').read()
index_found_list = [] # a list storing the integer indexes for the positions in the text string where the pattern matched, initially empty
times_found = 0 # variable to count the number of times the shorter sequence finds a matching pattern in the longer sequence
for i in range(len(text)-len(pattern)+1): # specific range to check indexes so that the pattern is not checked out of bounds in the text string
text_substr = text[i:len(pattern)+i] # substring of text of same length as pattern starting from index i
if pattern == text_substr: # if the pattern matches the text substring, increment the counter times_found
times_found += 1
index_found_list.append(i) # and add the current index where it matched to the index_found_list by appending
print("The pattern %s was found %i times in the text %s by naive pattern matching at indexes:" % (pattern, times_found, text), index_found_list)
retry = input('Enter \'r\' to do another search, any other key to terminate the program: ') # retry input
print('\n')
|
f7793e64da8f93753566f552cdaa95c51cdae26e | SOFIAGYRYKOVYCH/lab_alghoritms | /lab2/2.9/2_9.py | 223 | 3.734375 | 4 | import random
def search(array, x):
for i in range(len(array)) :
if x <= array[i] :
return i
return -1
array = [1,2,3,4,6,10]
x = random.randint(0,10)
print(x)
print(search(array,x))
|
495c1de80bea1e48413152256efe806cec57c020 | ayush-programer/pythoncode | /compositioninheritance.py | 1,299 | 4.25 | 4 | # Using composition to build complex objects
class Tractor():
def __init__(self, model, make, engine=None):
self.model = model
self.make = make
# Use references to other objects, like Engine and Implement
self.engine = engine
self.implements = []
def addimplement(self, implement):
self.implements.append(implement)
def get_tractor_implements(self):
return self.implements
class Engine():
def __init__(self, cylinders, horsepower):
self.cylinders = cylinders
self.horsepower = horsepower
def __str__(self):
return f"{self.cylinders} cylinder {self.horsepower} horsepower"
class Implement():
def __init__(self, attachment_type):
self.attachment_type = attachment_type
engine1 = Engine(3, 25)
tractor1 = Tractor("John Deere", "1025R", engine1)
tractor1.addimplement(Implement("Loader"))
tractor1.addimplement(Implement("Backhoe"))
tractor1.addimplement(Implement("Mowing Deck"))
tractor1.addimplement(Implement("Snowblower"))
print(f"This is a {tractor1.model} tractor.")
print(f"It has {tractor1.engine} engine.")
attachments = tractor1.get_tractor_implements()
print("The attachments it has include: ")
for attachment in attachments:
print(" - " + attachment.attachment_type) |
e4d28860dd1fe0bf41ef5e57584e55f77c7df1ca | jfarizano/LCC | /1_año/ProgII/Python/p1/ej1.py | 140 | 3.59375 | 4 | def primeros25(n = 1):
if n < 25:
print(n*2)
primeros25(n+1)
else:
print(n*2)
primeros25()
|
3b982596e998ab21438fae28cb97a79fe2c8e433 | cdelachica/Requirments | /string manipulation.py | 347 | 4.34375 | 4 | your_name = input ("enter your name:")
name = ""
based_name = "Christian"
print("Your name should not have the same letter with Christan")
for letter in your_name:
if letter not in based_name:
name += letter
print("\nAnalyzing letters at your name :", name)
print("\nYour new name is :", name)
input("\nEnter to exit") |
586fdfb3baa2f8d4b7ade513e01ae84265a4a7cc | besmelh/international-schools-scraper | /dataToCsv.py | 1,781 | 3.734375 | 4 | import csv
class NESA_CSV:
#create the csv file, and write the info of all the advisors to it
def writeFile(self, advList):
fileName = 'NESA.csv'
try:
with open(fileName, 'w+', newline='') as csvfile:
fieldnames = ['name','title' ,'location', 'email']
thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
thewriter.writeheader()
for adv in advList:
thewriter.writerow({'name': adv.name, 'title': adv.title, 'location': adv.location, 'email': adv.email})
# csvfile = open('nesa.csv', 'a+', newline='')
# writer = csv.writer(csvfile)
# for adv in advList:
# writer.writerow({'name': adv.name, 'title': adv.title, 'location': adv.location, 'email': adv.email})
csvfile.close()
print(f"Writing {fileName} succeeded.")
except:
print(f"Writing {fileName} failed.")
class ISD_CSV:
#create the csv file, and write the info of all the advisors to it
def writeFile(self, schList):
fileName = 'ISD.csv'
try:
with open(fileName, 'w+', newline='') as csvfile:
fieldnames = ['location', 'name', 'curriculum' ,'language', 'ages', 'fees']
thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
thewriter.writeheader()
for sch in schList:
thewriter.writerow({'location': sch.location, 'name': sch.name, 'curriculum': sch.curriculum, 'language': sch.language, 'ages': sch.ages, 'fees': sch.fees})
csvfile.close()
print(f"Writing {fileName} succeeded.")
except:
print(f"Writing {fileName} failed.") |
96428f70379cbea3ff44130a007b1e1afc32c5db | leemutai/google_opener | /main.py | 675 | 3.515625 | 4 | #importing web browser module
import webbrowser
#importing tkinter
from tkinter import *
#creating root
root = Tk()
#setting a GUI title
root.title("webBrowser")
#setting GUI geometry
root.geometry("300*200")
#function to open copyassignmet.com in browser
def copyassignment():
webbrowser.open("www.copyassignment.com")
#function to open google in browser
def google():
webbrowser.open("www.google.com")
#function to call copyassignment function
copyassignment = Button(root,text="visit copyassignment",command = copyassignment).pack(pady=20)
#button to call google function
mygoogle = Button(root, text="open Google",command=google).pack(pady=20)
root.mainloop() |
03d69ff98fa7cc04897e64232c3d8eb9da868209 | Covax84/Coursera-Python-Basics | /power_of_2.py | 355 | 4.15625 | 4 | # По данному числу N распечатайте все целые степени двойки,
# не превосходящие N, в порядке возрастания.
# Операцией возведения в степень пользоваться нельзя!
n = int(input())
m = 1
while m <= n:
print(m, end=' ')
m *= 2
|
6e4ed1c01c7d0eefd315405f6179f2a5574b796d | KarthikUdyawar/Bubble-Sort | /bubblesort.py | 455 | 4.15625 | 4 | # Main function
def bubblesort(list):
for i in range(len(list) - 1,0,-1):
for x in range(i):
if list[x] > list[x+1]:
temp = list[x]
list[x] = list[x+1]
list[x+1] = temp
return list
# Input loop
sort = []
num = int(input("Enter number of inputs: "))
for n in range(0,num):
ele = int(input("Element : "))
sort.append(ele)
print("After sorted ",bubblesort(sort)) # Output
|
28f839e5953efd90b971b7d8fa00b8a6130206a9 | 0885872/INFDEV02-1_0885872 | /drawFigures/drawFigures/drawFigures.py | 1,628 | 4.15625 | 4 | import sys
star = "*"
space = " "
saveWidth = ""
saveWidthSec = ""
enter = "\n"
print "Let's get happy, let's draw figures!"
figureChoice = raw_input("""Choose what kind of figure you want to draw:
1square, 2square, 1triangle, 2triangle, circle or smiley? : """)
# Let's draw a square of stars
if figureChoice == "1square":
figureHeight = int(raw_input("height of the figure should be: "))
figureWidth = int(raw_input("width of the figure shoud be: "))
for x in range(0,figureWidth):
saveWidth = saveWidth + star
for t in range(0,(figureHeight)):
print saveWidth
# Let's draw a square with empty space inside
if figureChoice == "2square":
figureHeight = int(raw_input("height of the figure should be: "))
figureWidth = int(raw_input("width of the figure shoud be: "))
for x in range(0,figureWidth + 2):
saveWidth = saveWidth + star
for t in range(0,(figureWidth - 2)):
saveWidthSec = saveWidthSec + space
for s in range(0,(figureHeight + 1)):
if s== 0 or s == figureHeight:
print saveWidth
else:
print star, saveWidthSec, star
# Let's draw a triangle(like stairs)
elif figureChoice == "1triangle":
figureWidth = int(raw_input("width of the figure shoud be: "))
for x in range(0, figureWidth):
saveWidth = saveWidth + star
print saveWidth
# Let's draw a triangle(like a spike)
elif figureChoice == "2triangle":
figureWidth = int(raw_input("width of the figure shoud be: "))
for t in range(0, figureWidth):
saveWidthSec = saveWidthSec + star
|
0b0e6da8c4826b8af42e4fd4876b846333f3da46 | MerinAlex23/PythonProject | /largestnumber.py | 120 | 4.0625 | 4 |
numbers =[0,2,3,8,9,6]
max = numbers[2]
for number in numbers:
if number > max:
max = number
print(max)
|
44852cd79d0797c0dda575e47ff13fd9d74c5df0 | Swiftal13/Tkinter-Projects | /Daniel_or_Elyas.py | 884 | 3.8125 | 4 | from tkinter import *
root = Tk()
root.title("Who is the smarter brother?")
root.geometry("400x200")
root.configure(bg = "#cedbdb")
label_1 = Label(root, text = "Who is smarter Daniel or Elyas:", bg = "#cedbdb" )
label_1.place(x = 120, y = 25)
stringvar = StringVar()
displaylabel = Label(root, textvariable = stringvar)
displaylabel.pack()
#functions
def eod():
stringvar.set("You are wrong!")
root.configure(bg = "#f23838")
def doe():
stringvar.set("You are correct!")
root.configure(bg = "#4af74d")
#buttons
button_daniel = Button(root, text="Daniel", width=7, height=2, command = eod, fg = "#c19df2", bg = "#756f6f")
button_daniel.place(x = 126, y = 105)
button_elyas = Button(root, text="Elyas", width=7, height=2, command = doe, fg = "#c19df2", bg = "#756f6f")
button_elyas.place(x = 220, y = 105)
mainloop() |
344cdb802f7fb423d0d20fcc5bd32f04fc3443d8 | Fu-James/AI-Project-1 | /repeated_Astar.py | 6,749 | 3.734375 | 4 | from func_Astar import *
from gridworld import Gridworld
class Repeated_Astar():
"""
Create a Repeated A* agent with the given unexplored maze, dimension, start, and goal cell.
Parameters:
----------
dim : Dimension of the gridworld as a int.
start : cell to start from.
goal : goal cell to search for.
maze: An (dim) * (dim) unexplored maze.
Returns:
-------
agent: Unexplored Gridworld as a 2-D cell array. Dimension is (dim) * (dim).
The knowledge of the agent increases as it explored through the maze to find path between the start and goal cell.
"""
def __init__(self, dim: int, start: list, goal: list, maze: Gridworld, backtrack: bool = False, flag: int = 0):
self._dim = dim
self._start = start
self._goal = goal
self._maze = maze
# Create an unblocked gridworld
self._knowledge = Gridworld(self._dim, 0.0)
self._backtrack = backtrack
self._flag = flag
def backtrack(self, current: Cell) -> Cell:
"""
This function is designed for Q8.
When the agent walk to the end of a hallway, it would backtrack to the other end.
Therefore we would get to a better point restarting the A* search.
Returns:
-------
restart_cell: Returns a cell that is not in the hallway.
"""
trajectory_backtrack = 1
while current.get_parent() is not None:
blocked_neighbors_count = current.get_no_of_blocked_neighbors()
neibors_count = current.get_no_of_neighbors()
if 4 - neibors_count + blocked_neighbors_count >= 2:
current = current.get_parent()
else:
return current, trajectory_backtrack
trajectory_backtrack += 1
return current, trajectory_backtrack
def is_end_of_hallway(self, current: Cell) -> bool:
"""
This function is designed for Q8.
It returns True if the agent walk to the end of a hallway.
Otherwise, False.
"""
blocked_neighbors_count = current.get_no_of_blocked_neighbors()
neibors_count = current.get_no_of_neighbors()
if 4 - neibors_count + blocked_neighbors_count >= 3:
return True
else:
return False
def path_walker(self, path: list):
"""
This function checks whether the path has any blocked cell. If the cell is not blocked, we will update the unexplored
maze and add this cell to out knowledge grid.
Returns:
-------
blocked cell, status_string: Returns the parent of the blocked cell, if a blocked cell present in the path, along with a status string to indicate.
If no blocked cell is found the return None.
"""
trajectory = -1
while path:
current = path.pop()
if self._maze.get_cell(current.x, current.y).get_flag() == 1:
return current.get_parent(), 'blocked', trajectory
trajectory += 1
children = current.get_children()
for child in children:
self._knowledge.update_cell(self._maze.get_cell(child[0], child[1]),
child[0], child[1])
return None, 'unblocked', trajectory
def path_walker_backtrack(self, path: list):
"""
This function checks whether the path has any blocked cell. If the cell is not blocked, we will update the unexplored
maze and add this cell to out knowledge grid.
If the cell is blocked and the agent is at the end of a hallway, it will backtrack to the nearest exit.
Returns:
-------
blocked cell, status_string: Returns the parent of the blocked cell, if a blocked cell present in the path, along with a status string to indicate.
If no blocked cell is found the return None.
"""
trajectory = -1
while path:
current = path.pop()
if self._maze.get_cell(current.x, current.y).get_flag() == 1:
current = current.get_parent()
if current.get_parent() is not None and self.is_end_of_hallway(current):
current, trajectory_backtrack = self.backtrack(current.get_parent())
return current, 'blocked', trajectory + trajectory_backtrack
else:
return current, 'blocked', trajectory
trajectory += 1
children = current.get_children()
blocked_neighbors_count = 0
for child in children:
child_cell = self._maze.get_cell(child[0], child[1])
self._knowledge.update_cell(child_cell, child[0], child[1])
if child_cell.get_flag() == 1:
blocked_neighbors_count += 1
current.update_no_of_neighbors(len(children))
current.update_no_of_blocked_neighbors(blocked_neighbors_count)
return None, 'unblocked', trajectory
def generate_path(self, current) -> list:
"""
This function will help the agent to find the path between current and their parent cell.
Returns:
-------
path: Returns a path between the current cell and it's parent until the hightes hierarchical parent is found.
"""
path = []
path.append(current)
while current.get_parent() is not None:
current = current.get_parent()
path.append(current)
return path
def find_path(self):
"""
Main function which will help the agent to find the path between start and goal cell.
Returns:
-------
path, status_string: Returns a path between the start and goal node if found, otherwise will return None.
The status string indicates if the solution is found or not.
"""
start_cell = Cell(self._start[0], self._start[1], 0, self._dim, None, self._flag)
overall_trajectory = 0
while True:
goal_cell, status = func_Astar(start_cell, self._goal, self._knowledge, self._dim, self._flag)
if status == 'no_solution':
return None, 'no_solution', overall_trajectory
path = self.generate_path(goal_cell)
if self._backtrack:
start_cell, node_status, trajectory = self.path_walker_backtrack(path)
else:
start_cell, node_status, trajectory = self.path_walker(path)
overall_trajectory += trajectory
if node_status == 'unblocked':
return self.generate_path(goal_cell), 'solution', overall_trajectory |
2f1cf4ef6f61b3f91f0d077d4e9dc50630b34e0d | HLozano12/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 598 | 3.78125 | 4 | #!/usr/bin/python3
"""List all cities from DB"""
if __name__ == "__main__":
import MySQLdb
from sys import argv
db_connection = MySQLdb.connect("localhost",
argv[1],
argv[2],
argv[3])
with db_connection.cursor() as cursor:
cursor.execute("""SELECT cities.id, cities.name, states.name FROM cities
JOIN states ON cities.state_id = states.id""")
cities = cursor.fetchall()
for h in range(len(cities)):
print(cities[h])
|
6925f3c71330c3c6dd5a1e899ddff9d51dffc94c | Aasthaengg/IBMdataset | /Python_codes/p02993/s452232855.py | 131 | 3.6875 | 4 | lst = input().split()
if lst[0][0]==lst[0][1] or lst[0][1]==lst[0][2] or lst[0][2]==lst[0][3]:
print('Bad')
else:
print('Good') |
982ef78cc9b7632eb39ab4a7dac0c165db639f6c | dipanjan44/Python-Projects | /ProgramPractise/find_element_rotatearray.py | 1,196 | 4.28125 | 4 |
def find_element (arr, size, element):
pivot = get_pivot_element (arr,size - 1);
# If we didn't find a pivot,
# then array is not rotated at all
if pivot == -1:
return binarySearch (arr, 0, size - 1, element);
if arr[pivot] == element:
return pivot
if arr[0] <= element:
return binarySearch (arr, 0, pivot - 1, element);
return binarySearch (arr, pivot + 1, size - 1, element);
def get_pivot_element (arr,length):
count=0
while count < length:
if arr[count] > arr[count+1]:
return count
else:
count=count+1
return -1
# Standard Binary Search function*/
def binarySearch (arr, low, high, key):
if high < low:
return -1
mid = int ((low + high) / 2)
if key == arr[mid]:
return mid
if key > arr[mid]:
return binarySearch (arr, (mid + 1), high,
key);
return binarySearch (arr, low, (mid - 1), key);
# Driver program to check above functions */
# Let us search 3 in below array
rsa = [3, 4, 5, 6, 1, 2]
n = len (rsa)
#print(len(arr1))
key = 4
print ("Index of the element is : ",
find_element (rsa, n, key))
|
501637cf5248b4aa6cdbeabe4a6a15a753baad52 | toberge/python-exercises | /warmup/beautiful.py | 1,131 | 3.625 | 4 | #!/usr/bin/env python3
'''
https://www.youtube.com/watch?v=OSGv2VnC0go
just some notes about sweet&consise things in Python
'''
# after 6:43
# Using iter() with a sentinel (stop) value!
# partial() takes function with many args + those args and creates function with no args!
things = []
for thing in iter(partial(f.read, 32), ''):
things.append(thing)
# I know of for-else, yay
# stuff about looping over dicts, keys by default, use of iteritems() ++
###########################################
# Creating dict from 2 arrays:
keys = ['abc', 'def', 'ghi']
values = [2, 4, 9]
dictionary = dict(izip(keys, values))
# instead of setdefault: d[k] = d.get(k, 0) + 1
# that will set d[k] to zero if not present
# even better:
d1 = defaultdict(int)
for key in keys:
d1[key] += 1
# defaultdica sets default, int w/o arg resolves to 0
# in case of lists:
names = ['Roger', 'Pete', 'Susan', 'Gabrielle', 'Lydia']
d2 = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
# becomes
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)
# leaving off after 28:00
|
07da7d5d3a8ca8efa1619ec26f9e9687f4e2c0b7 | ReDi-school-Berlin/git_intro | /my_first_assignment.py | 455 | 3.796875 | 4 | ###############################
## #
## MY FIRST PYTHON ASSIGNMENT #
## #
## \o/ #
###############################
# YOUR ASSIGNMENT:
# 1. Change the code below to print "Hello, I am {your_name}. Nice to meet you!"
print("Hello, I am ReDi School!")
# 2. Add a new line of code hire that prints "Coding is awesome!!!"
# 3. RUN YOUR CODE TO MAKE SURE EVERYTHING IS WORKING!
|
9f88403bd09b969be0ebb948fe791942ebca62ba | nitarsh/PycharmProjects | /testPython/myarrays/test.py | 2,526 | 3.578125 | 4 | def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
def multiple(n, m):
if (n % m != 0):
return False
else:
return True
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, "?"
print "-- I'm sorry, we're all out of", kind
for arg in arguments:
print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
import sys
from collections import deque
# num = int(input("Gimme a number, Dawg!"))
# print "Heres what I got:" , fact(num)
# m = int(input("Gimme a number, Dawg!"))
# n = int(input("Now give a multiple, Yo!"))
#
# if(multiple(n,m)):
# print "You got brains son! "
# else:
# print n," aint multiple of ",m, " fool!"
class GameEntry:
def __init__(self, name, score):
self._name = name
self._score = score
def get_name(self):
return self._name
def get_score(self):
return self._score
def __str__(self):
return ({0}, {1}).__format__(self._name, self._score) # e.g., (Bob, 98)
somelist = [1, 2, 4, 8, 16, 32, 64, 128, 256]
# somelist.append("ff")
#
# sometup = (1, 2, 2, 8, 16, 32, 64, 128, 256)
#
# this_set = {1, 2, 13, 24, 7}
#
# str = "Hi my name is Shrinath"
#
# ge = GameEntry(name="Shrinath",score=12)
# print ge.get_name()
#
# print sys.getsizeof(sometup)
#
# for x in this_set:
# print x, " then"
# words = ['cat', 'window', 'defenestrate']
# for w in words:
# if len(w) > 6 and len(words)<15 :
# #words.insert(0, w)
# words.remove(w)
#
# for w in words:
# print w
# cheeseshop("Limburger", "It's very runny, sir.","It's really very, VERY runny, sir.", shopkeeper='Michael Palin',client="John Cleese",sketch="Cheese Shop Sketch")
somelist.append(512)
somelist.append(1024)
somelist.pop()
def fil1(ffun, list):
new_list = []
for l in list:
if (ffun(l)):
new_list.append(l)
return new_list
def f(x): return x == 2 or x == 64
def cube(x): return x * x * x
def add(x1,x2,x3): return x1+x2+x3
def mul(*arg):
result=1;
for a in arg:
result*=a
return result
def mymap(fun, *arg):
return [fun(*(array[a] for array in arg)) for a in range(len(arg[0]))]
# print fil1(f, somelist)
#
# print filter(f,map(cube,somelist))
print somelist
print mymap(mul,somelist,somelist,somelist)
# for w in somelist:
# print w
#
# queue = deque(("name1","name2",'name3'))
# for de in queue:
# print de
|
c98c36155d81c0ce5c19e473ae8b3a72fdbeca9b | ryanfwy/sudoku | /recognition.py | 2,790 | 3.59375 | 4 | '''Number recognition model.'''
from keras.models import model_from_json, Model
from keras.layers import Input, Dense, Dropout, Flatten
import numpy as np
import cv2
class _NumberModel(object):
'''The recognition model for number 0-9.
Instance Methods:
load_model: Load the model.
predict_number: Prediction.
'''
def __init__(self):
self.__model = None
@staticmethod
def __define_model():
inputs = Input(shape=(28, 28, 1))
x = Flatten()(inputs)
x = Dense(512, activation='relu')(x)
x = Dropout(0.2)(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.2)(x)
outputs = Dense(11, activation='softmax')(x)
model = Model(inputs=inputs, outputs=outputs)
return model
@staticmethod
def __resize_image(img):
h, w = img.shape
fx, fy = 28.0 / h, 28.0 / w
fx = fy = min(fx, fy)
img = cv2.resize(img, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)
outimg = np.ones((28, 28), dtype=np.uint8) * 255
h, w = img.shape
x, y = (28 - w) // 2, (28 - h) // 2
outimg[y:y+h, x:x+w] = img
return outimg
def load_model(self, weight_path, model_path=None):
'''Load the model.'''
# Load model
if model_path is None:
self.__model = self.__define_model()
else:
print('Loaded model from json.')
with open(model_path, 'r') as f:
self.__model = model_from_json(f.read())
# Load weight
self.__model.load_weights(weight_path)
return self.__model
def predict_number(self, img):
'''Prediction.'''
if img is None:
return None
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, img_gray = cv2.threshold(img_gray, 200, 255, cv2.THRESH_BINARY)
kernel = np.ones((3, 3), np.uint8)
img_gray = cv2.morphologyEx(img_gray, cv2.MORPH_OPEN, kernel)
img_gray = self.__resize_image(img_gray) # Resizing to 28*28
img_gray = np.resize(img_gray, (1, 28, 28, 1)) # Expand
y_pred = self.__model.predict(img_gray)
y_pred = np.argmax(y_pred)
return y_pred
_MODEL = _NumberModel()
def load(weight_path, model_path=None):
'''Load the model.
Args:
weight_path: The path of model weight.
model_path: The path of model json. Pass `None` to build it directly.
Returns:
The recognition model.
'''
return _MODEL.load_model(weight_path, model_path)
def predict(img):
'''Prediction.
Args:
img: The image of number 0-9.
Returns:
The result of recognition.
'''
return _MODEL.predict_number(img)
if __name__ == '__main__':
pass
|
5a59bdaa5167abfd4df17577d10ba2ba89dec233 | jabzer/pyCode | /系统/读取txt变成1行/readtxt.py | 295 | 3.59375 | 4 | #!/usr/bin/python3
import sys
with open('txt.txt', 'r',encoding='utf8') as f:
allline = f.readlines()
linestr = []
for line in allline:
line = "'{}'".format(line.replace('\n', '').replace(' ',''))
if len(line) > 2:
linestr.append(line)
out = ",".join(linestr)
print(out)
|
5eb1e07984b772b88295f825b9e18da5954dc5ae | YuyaKagawa/random_public | /string_manipulation/alternate/alternate.py | 1,033 | 3.875 | 4 | import numpy as np # 行列操作
def main():
print("交互にかみ合わせたい複数の文字列を入れてください: ")
n=int(input("文字列は何個ですか: "))
string_list=[] # 元の文字列のリストの初期化
# n個の文字列を入力してもらう
for i in range(n):
string_list.append(input("{}番目の文字列を入力してください: ".format(i+1))) # 元の文字列のリストに追加
maxlen=len(max(string_list,key=len)) # 最も長い文字列の長さ
# それぞれの文字列について、長さをmaxlenに揃えるようにする
for i in range(n):
s=string_list[i] # 文字列
string_list[i]=list(s+" "*(maxlen-len(s))) # 長さがmaxlenになるように" "(スペース)を追加
output="".join(np.array(string_list).T.flatten()).replace(" ","") # 1列に1つの文字列を入れ、行の方向に読み込み、最後にスペースを削除
print("出力: ",output)
if __name__=="__main__":
main() |
cd785fed4a5ad72579cb00897f8110fe5ff4161e | sn003/python-learning | /named_tuple.py | 980 | 4.90625 | 5 | """
Below examples discusses about namedtuple from collections module
"""
import collections
#Declaring a namedtuple
employee = collections.namedtuple("Employee", ["Name", "Age", "DOB"])
#Adding Values
emp = employee("Johnny Depp", "35", "02011983")
#initializing iterable
ex_list = ["Abraham", "24", "20091994"]
#initializing dict
ex_dict = {"Name" : "Moti", "Age" : 29, "DOB" : "16091987"}
#Below 3print statements print Same output
print(emp.Name) #Access by key
print(emp[0]) #Access by index
print(getattr(emp, "Name")) #Access via getattr
#using _make() to return namedtuple()
print ("The namedtuple instance using iterable is : ")
print(employee._make(ex_list))
#using _asdict() to return an OrderedDict()
print("The OrderedDict instance using namedtuple is :")
print(emp._asdict())
#using ** operator to return namedtuple from dictionary
print("The namedtuple instance from dict is :")
print(employee(**ex_dict))
#print fields of the named tuple
print(emp._fields)
|
7c28e8ef75cae9770f139cc1e13f1e8e19060418 | ahridin-synamedia/intro-to-python-typing | /examples/15_static_duck_typing.py | 298 | 3.5625 | 4 | """
MyPy can duck-type objects, regardless of inheritance!
"""
from typing import Sized
# Has no superclass, or metaclass!
class Foobar:
# But does has a __len__() method that returns ints
def __len__(self) -> int:
return 5
def print_length(object: Sized):
print(len(object))
|
cb191704b41164f485bfebafdaa99b9090b2516d | flatironinstitute/spikeforest2 | /working/website_upload/make_website_data_directory.py | 2,271 | 3.515625 | 4 | #!/usr/bin/env python
import argparse
import os
import json
help_txt = """
This script saves collections in the following .json files in an output directory
Algorithms.json
Sorters.json
SortingResults.json
StudySets.json
StudyAnalysisResults.json
"""
def main():
parser = argparse.ArgumentParser(description=help_txt, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('path', help='Path to the assembled website data in .json format')
parser.add_argument('--output_dir', '-o', help='The output directory for saving the files.')
args = parser.parse_args()
output_dir = args.output_dir
if os.path.exists(output_dir):
raise Exception('Output directory already exists: {}'.format(output_dir))
os.mkdir(output_dir)
print('Loading spike-front results object...')
with open(args.path, 'r') as f:
obj = json.load(f)
StudySets = obj['StudySets']
SortingResults = obj['SortingResults']
Sorters = obj['Sorters']
Algorithms = obj['Algorithms']
StudyAnalysisResults = obj['StudyAnalysisResults']
General = obj['General']
print('Saving {} study sets to {}/StudySets.json'.format(len(StudySets), output_dir))
with open(output_dir + '/StudySets.json', 'w') as f:
json.dump(StudySets, f)
print('Saving {} sorting results to {}/SortingResults.json'.format(len(SortingResults), output_dir))
with open(output_dir + '/SortingResults.json', 'w') as f:
json.dump(SortingResults, f)
print('Saving {} sorters to {}/Sorters.json'.format(len(Sorters), output_dir))
with open(output_dir + '/Sorters.json', 'w') as f:
json.dump(Sorters, f)
print('Saving {} algorithms to {}/Algorithms.json'.format(len(Algorithms), output_dir))
with open(output_dir + '/Algorithms.json', 'w') as f:
json.dump(Algorithms, f)
print('Saving {} study analysis results to {}/StudyAnalysisResults.json'.format(len(StudySets), output_dir))
with open(output_dir + '/StudyAnalysisResults.json', 'w') as f:
json.dump(StudyAnalysisResults, f)
print('Saving general info to {}/General.json'.format(output_dir))
with open(output_dir + '/General.json', 'w') as f:
json.dump(General, f)
if __name__ == "__main__":
main()
|
d77ee68b8954b48bb5d02b1b1f2dda633b370cb0 | kmkkj/store | /猜数.py | 977 | 4.125 | 4 | '''
猜字游戏
需求:
1、猜的数字是系统产生的,不是自己定义的
2、键盘输入的 操作完填入:input(“提示”)
3、判断 操作完填入:if判断条件 elif 判断条件。。。。。。Else
4、循环 操作完填入:while 条件循环
任务:你的初始资金为100 每猜一次减10 资金为0时或者猜成功游戏结束
猜大 如果你输入的数字和随机数对比 大于随机数 打印一句话为 猜大了
猜小 如果你输入的数字和随机数对比 小于随机数 打印一句话为 猜小了
'''
import random
num=random.randint(0, 1000)
i = 100
while 1:
i = int(i)
a = input("请输入一个数字")
a = int(a)
if a > num:
print("猜大了")
elif a < num:
print("猜小了")
i = i - 10
print("初始值剩余", i)
if a == num :
print("游戏结束",a)
break
elif i == 0:
print("游戏结束",a)
break
|
5681620657df5fb5d9b5f5cdf496210eb0be52e4 | UCMHSProgramming16-17/final-project-anqi1999 | /idea-two/map.py | 3,006 | 3.96875 | 4 | # How much longer am I expected to live, given my sex, age, and country?
import requests
import csv
import datetime
import math
# PARAMETERS:
# sex
s = ['male', 'female']
sex = input('Are you male or female? Apologies for the forced gender norms. :( ')
while sex not in s:
sex = input('Male or female? ')
# country
c_url = 'http://api.population.io:80/1.0/countries' # get the available list of countries
c = requests.get(c_url)
c_list = c.json()
countries = c_list['countries']
# age
age = []
for num in range(81):
age.append(str(num) + 'y')
actual_age = [0] # this one will be used for 'uglylifechart'
num = 0
while num != 83:
actual_age.append(num)
num += 1
actual_age.append(num)
# date
date = str(datetime.date.today())
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# FUNCTION TO CONVERT FROM YEARS DECIMAL TO 'YEARS, MONTHS, DAYS':
# set empty variable
life_expectancy = 'blah'
# define function
def years(remaining):
global life_expectancy
rem = float(remaining) # convert 'remaining' to a float
year = math.floor(rem) # number of full years
m = (rem - year) * 12 # months left over
month = math.floor(m) # number of full months
d = (m - month) * 30.4375 # days left over (30.4375 is the average number of days per month)
day = math.floor(d) # number of full days
life_expectancy = str(year) + ' years, ' + str(month) + ' months, ' + str(day) + ' days'
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# FUNCTION FOR THE REMAINING LIFE API:
# set empty variable
remaining = 'blah'
# define function
def api():
global remaining
endpoint = 'http://api.population.io:80/1.0/life-expectancy/remaining/' # remaining lifetime api
url = endpoint + s + '/' + country + '/' + date + '/' + a
r = requests.get(url)
stats = r.json()
remaining = stats['remaining_life_expectancy']
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# CSV:
# new csv file
lifechart = open('lifechart.csv', 'w', newline='')
# create the writer
w = csv.writer(lifechart, delimiter=',')
# write to the file
w.writerow(['age', 'sex', 'life remaining'])
for a in age:
for s in sex:
api() # call api function for remaining life expectancy
years(remaining) # call years converter function
w.writerow([a, s, life_expectancy]) # write 'age', 'sex', and 'remaining life expectancy' to the file
# close file
lifechart.close()
print('Open the lifechart, and scroll through until you reach your age. Happy searching.')
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# UGLIER CSV FILE:
# new file
uglylifechart = open('uglylifechart.csv', 'w', newline='')
# create the writer
u = csv.writer(uglylifechart, delimiter=',')
# write to the file
u.writerow(['age', 'sex', 'life remaining'])
u_remaining = []
for a in age:
for s in sex:
api()
u_remaining.append(remaining)
for x in range(162):
u.writerow([actual_age[x], u_sex[x], u_remaining[x]])
uglylifechart.close() |
b246434bf6dfb82f2a5c01174548b5d711ff52cc | marcheliks/EDIBO | /Python/milzigs_skaitlis.py | 951 | 3.765625 | 4 | #!/usr/bin/python3.6
print("Ievadiet skaitli")
# a=2**2000000
#te ir trīs darbības - vertības sagadīšana,
# vērtības pārveidošanas piešķiršinas
#argument = input()
#int(arguments)
#a = int(arguments)
#pildot int(input()) "bez izmeiģinājuma" programma var vienkārši izlidot...
# tāpēc, lai "nelidotu" mēs izmantosim try ... except .. finally konstruktoru
paziime = False
while not paziime:
#while paziiime == False:
#while paziime !== True:
try:
a= int( input() )
paziime = True
except:
print("Diemžēl, cienijamais lietotāj, to, kas ievadīts nevar",\
"pārveidot par vesela tipa skaitli")
print("lūidzu, ievadiet s_k_a_i_t_l_i vēlreiz")
#if (a == int): print("a**100")
if (a ==5):
print(a ** 100)
print("Apreiķins ir gatavs")
print("Šis teksts atrodas ārpus darbību bloka - pierakstīts",\
"atstarpēs priekšā, tāpēc tas paradīsies jebkurā darumā")
#print ("Atstarpes šeit vairs nedrīkst būt")
|
c0cebd1a4f7be8d299c333a8cb3fc2aa92c91742 | adii1207/family-tree | /relation_maternal_aunt.py | 329 | 3.6875 | 4 | def maternal_aunt(name):
#looks for sibling of mother with gender female
if len(name.parent) > 0 and len(name.parent[1].parent) > 0:
for i in name.parent[1].parent[0].child:
if i.gender == "female" and i != name.parent[1]:
print(i, end=" ")
else:
print("PERSON NOT FOUND") |
9e6b8101bf0ffd61d5d4299c01087b2387505f77 | jlalford/scripts | /googlecsvuploader.py | 544 | 3.5 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('csv',type=str,help='The name of the file we are importing into Google')
args = parser.parse_args()
mypath = args.csv
myfile = open(mypath)
mytext = myfile.read()
myfile.close()
thelines = mytext.split("\n")
for line in thelines:
thisline = line.split(',')
counter = 0
while counter < len(thisline):
if (thisline[counter] == '' or thisline[counter] == ','):
thisline.pop(counter)
else:
counter += 1
print thisline
|
d9fa057a1505721ac91a1903110a9a62c1e92ef3 | TitanicThompson1/FPRO | /Testes/PE2/201706860/caesar.py | 788 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 11:36:48 2018
@author: Ricardo Nunes
"""
import math
def caesar(message):
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result=""
for i,letter in enumerate(message):
if letter in alphabet:
swift=int((((1+math.sqrt(5))**i)-((1-math.sqrt(5))**i))/((2**i)*math.sqrt(5)))
new_letter=do_swift(letter,swift)
else:
new_letter=letter
result+=new_letter
return result
def do_swift(letter,swift):
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
idx=alphabet.index(letter)
new_letter=alphabet[idx-swift%26]
return new_letter
print(caesar("FIBONACCI SEQUENCE"))
|
ef57ad55510a50cd075c2afefc0457182d45e908 | lisaover/MITxCompSciPython | /SimplePrograms/wk2_recursion.py | 2,849 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
power = 1
if exp == 0:
return 1
else:
for i in range(exp):
power *= base
return power
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp == 0:
return 1
else:
return base*recurPower(base, exp-1)
base = 2
exp = 0
#print(iterPower(base, exp))
#print(recurPower(base, exp))
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
if a == b:
return a
elif a < b:
test = a
else:
test = b
while test > 0:
if a%test == 0 and b%test == 0:
return test
else:
test -= 1
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
The Euclidean algorithm is based on the principle that the greatest common
divisor of two numbers does not change if the larger number is replaced by
its difference with the smaller number.
https://en.wikipedia.org/wiki/Euclidean_algorithm#Worked_example
'''
if a < b:
pass
else:
temp = a
a = b
b = temp
if b%a == 0:
return a
else:
return gcdRecur(b%a, a)
a = 462
b = 1071
#print(gcdIter(a, b))
#print(gcdRecur(a, b))
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
First, test the middle character of a string against the character you're
looking for (the "test character"). If they are the same, we are done.
If they're not the same, check if the test character is "smaller" than the
middle character. If so, we need only consider the lower half of the
string; otherwise, we only consider the upper half of the string.
Implement the function isIn(char, aStr) which implements the above idea
recursively to test if char is in aStr. char will be a single character
and aStr will be a string that is in alphabetical order. The function
should return a boolean value.
'''
if len(aStr) <= 1:
if char == aStr:
return True
else:
return False
i = len(aStr)//2
if char == aStr[i]:
return True
else:
if char < aStr[i]:
aStr = aStr[:i]
return isIn(char, aStr)
else:
aStr = aStr[i:]
return isIn(char, aStr)
print(isIn('z', '')) |
ee1eadf0938f0dff9726eba33c38509956cf0165 | Nataliia-L/python_course | /lesson2.py | 218 | 3.671875 | 4 | import random
integer = random.randint (1,100)
print("Integer number: " ,integer)
float = random.uniform (1,50)
print ("Float number: " ,float)
answer1 = integer > float
print("Is integer bigger than float?", answer1)
|
33246ea00c6a42a19999ef17623c341f9beda3d7 | habibor144369/python-all-data-structure | /list-even_odd.py | 273 | 4.15625 | 4 | # find out even number and odd number in list----
list = [11, 45, 41, 60, 66, 10, 20, 13, 14, 26]
even_list = []
odd_list = []
for even in list:
if even % 2 == 0:
even_list.append(even)
else:
odd_list.append(even)
print(even_list)
print(odd_list) |
11d0f691006699d08f35c17c1bd396f1b80ea111 | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Lists/Listas e Repetição - AVA/ThiagoD/04.py | 448 | 3.625 | 4 | lista = list(map(float, input().split()))
media = sum(lista) / len(lista)
menorQueMedia, maiorQueMedia = 0, 0
for i in lista:
if i > media:
maiorQueMedia += 1
else:
menorQueMedia += 1
print("O valor médio da lista: ", end="")
for i in lista:
print(i, end=" ")
print(f" é: {media:.6f}")
print("")
print(f"Existem {menorQueMedia} valores menores ou iguais a média e {maiorQueMedia} valores maiores que a média.")
|
9ac8cfe4a901becf50f94ef10fbe96a2e7e66677 | anmolrajaroraa/python-wknd-sept | /patterns.py | 9,874 | 3.796875 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(0,10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(0,10,1))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(0,10,-1))
[]
>>> list(range(10,0,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(reversed(range(0,10,1)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
>>> '''
*
**
***
****
*****
'''
'\n*\n**\n***\n****\n*****\n'
>>> counter = 1
>>> for i in range(10):
for j in range(counter):
print('*')
*
*
*
*
*
*
*
*
*
*
>>> for i in range(10):
print('j loop started')
for j in range(counter):
print('*')
print('j loop ended')
counter += 1
j loop started
*
j loop ended
j loop started
*
*
j loop ended
j loop started
*
*
*
j loop ended
j loop started
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
*
*
*
*
j loop ended
j loop started
*
*
*
*
*
*
*
*
*
*
j loop ended
>>> for i in range(10):
print('j loop started')
for j in range(counter):
print('*',end='')
print('j loop ended')
counter += 1
j loop started
***********j loop ended
j loop started
************j loop ended
j loop started
*************j loop ended
j loop started
**************j loop ended
j loop started
***************j loop ended
j loop started
****************j loop ended
j loop started
*****************j loop ended
j loop started
******************j loop ended
j loop started
*******************j loop ended
j loop started
********************j loop ended
>>> counter = 1
>>> for i in range(10):
print('j loop started')
for j in range(counter):
print('*',end='')
print('j loop ended')
counter += 1
j loop started
*j loop ended
j loop started
**j loop ended
j loop started
***j loop ended
j loop started
****j loop ended
j loop started
*****j loop ended
j loop started
******j loop ended
j loop started
*******j loop ended
j loop started
********j loop ended
j loop started
*********j loop ended
j loop started
**********j loop ended
>>> for i in range(10):
for j in range(counter):
print('*',end='')
counter += 1
***********************************************************************************************************************************************************
>>> counter = 1
>>> for i in range(10):
for j in range(counter):
print('*',end='')
print('\n')
counter += 1
*
**
***
****
*****
******
*******
********
*********
**********
>>> counter = 1
>>> for i in range(10):
for j in range(counter):
print('*',end='')
print()
counter += 1
*
**
***
****
*****
******
*******
********
*********
**********
>>> for i in range(10):
for j in range(i + 1):
print('*',end='')
print()
*
**
***
****
*****
******
*******
********
*********
**********
>>> for i in range(10):
for j in range(i + 1):
print('*',end='')
print()
*
**
***
****
*****
******
*******
********
*********
**********
>>> '''
*
**
***
****
*****
'''
'\n *\n **\n ***\n ****\n*****\n'
>>> for i in range(10):
for j in range(i + 1):
print(' ',end='*')
print()
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
>>>
>>> '''
i = [0,1,2,3,4] 4 - i
$$$$*
$$$**
$$***
$****
*****
'''
'\ni = [0,1,2,3,4] 4 - i\n$$$$*\n$$$**\n$$***\n$****\n*****\n'
>>> for i in range(10):
for j in range(9 - i):
print('$', end='')
print()
$$$$$$$$$
$$$$$$$$
$$$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$
>>> for i in range(10):
for j in range(9 - i):
print('$', end='')
for k in range(i + 1):
print(' ',end='*')
print()
$$$$$$$$$ *
$$$$$$$$ * *
$$$$$$$ * * *
$$$$$$ * * * *
$$$$$ * * * * *
$$$$ * * * * * *
$$$ * * * * * * *
$$ * * * * * * * *
$ * * * * * * * * *
* * * * * * * * * *
>>> for i in range(10):
for j in range(9 - i):
print('$', end='')
for k in range(i + 1):
print('*',end='')
print()
$$$$$$$$$*
$$$$$$$$**
$$$$$$$***
$$$$$$****
$$$$$*****
$$$$******
$$$*******
$$********
$*********
**********
>>> for i in range(10):
for j in range(9 - i):
print(' ', end='')
for k in range(i + 1):
print('*',end='')
print()
*
**
***
****
*****
******
*******
********
*********
**********
>>> for i in range(10):
for j in range(9 - i):
print(' ', end='')
for k in range(i + 1):
print(' *',end='')
print()
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
>>> '''
$$$$*
$$$***
$$*****
$*******
*********
'''
'\n$$$$*\n$$$***\n$$*****\n$*******\n*********\n'
>>> for i in range(10):
for j in range(10 - i):
print('$', end='')
print()
$$$$$$$$$$
$$$$$$$$$
$$$$$$$$
$$$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$
>>> for i in range(10):
for j in range(10 - i):
print('$', end='')
for k in range(i + 2)
print()
SyntaxError: invalid syntax
>>> for i in range(10):
for j in range(10 - i):
print('$', end='')
for k in range(i + 2):
print('*',end='')
print()
$$$$$$$$$$**
$$$$$$$$$***
$$$$$$$$****
$$$$$$$*****
$$$$$$******
$$$$$*******
$$$$********
$$$*********
$$**********
$***********
>>> for i in range(10):
for j in range(10 - i):
print('$', end='')
for k in range(i * 2):
print('*',end='')
print()
$$$$$$$$$$
$$$$$$$$$**
$$$$$$$$****
$$$$$$$******
$$$$$$********
$$$$$**********
$$$$************
$$$**************
$$****************
$******************
>>> for i in range(10):
for j in range(10 - i):
print('$', end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
$$$$$$$$$$*
$$$$$$$$$***
$$$$$$$$*****
$$$$$$$*******
$$$$$$*********
$$$$$***********
$$$$*************
$$$***************
$$*****************
$*******************
>>> for i in range(10):
for j in range(10 - i):
print(' ', end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
>>> '''
$$$$*
$$$***
$$*****
$*******
*********
$*******
$$*****
$$$***
$$$$*
'''
'\n$$$$*\n$$$***\n$$*****\n$*******\n*********\n$*******\n$$*****\n$$$***\n$$$$*\n'
>>> for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
>>> for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
print()
$$$$$$$$$$
$$$$$$$$$
$$$$$$$$
$$$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$
>>> for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
print()
else:
for j2 in range(i - 10)
SyntaxError: invalid syntax
>>> for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
print()
$$$$$$$$$$
$$$$$$$$$
$$$$$$$$
$$$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
>>> for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
print()
$$$$$$$$$$*
$$$$$$$$$***
$$$$$$$$*****
$$$$$$$*******
$$$$$$*********
$$$$$***********
$$$$*************
$$$***************
$$*****************
$*******************
*********************
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
>>> #11 -> 19
>>> #12 -> 17
>>> #13 -> 15
>>> #14 -> 13
>>> #15 -> 11
>>> #16 -> 9
>>> #17 -> 7
>>> #18 -> 5
>>> #19 -> 3
>>> #20 -> 1for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
for k2 in range((20 - i) * 2):
print('*',end='')
print()
SyntaxError: unexpected indent
#20 -> 1for i in range(20):
if i <= 10:
for j in range(10 - i):
print('$',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
for k2 in range((20 - i) * 2):
print('*',end='')
print()
>>> if i <= 10:
for j in range(10 - i):
print('$',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
for k2 in range((20 - i) * 2):
print('*',end='')
print()
SyntaxError: unindent does not match any outer indentation level
>>>
>>> for i in range(21):
if i <= 10:
for j in range(10 - i):
print('$',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print('$',end='')
for k2 in range((20 - i) * 2):
print('*',end='')
print()
$$$$$$$$$$*
$$$$$$$$$***
$$$$$$$$*****
$$$$$$$*******
$$$$$$*********
$$$$$***********
$$$$*************
$$$***************
$$*****************
$*******************
*********************
$******************
$$****************
$$$**************
$$$$************
$$$$$**********
$$$$$$********
$$$$$$$******
$$$$$$$$****
$$$$$$$$$**
$$$$$$$$$$
>>> for i in range(21):
if i <= 10:
for j in range(10 - i):
print(' ',end='')
for k in range((i * 2) + 1 ):
print('*',end='')
print()
else:
for j2 in range(i - 10):
print(' ',end='')
for k2 in range(((20 - i) * 2 ) + 1):
print('*',end='')
print()
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
>>>
|
7f1089706138fbf006a6df8df26f3d73ee918091 | willtuna/Python_Folder | /OpenCourse/UdemyPython/tkinter_Action.py | 242 | 3.875 | 4 | #! /usr/bin/env python3
from tkinter import *
root = Tk()
def printName():
print("Hello there, this is Will.\n Welcome to login")
button1 = Button(root, text="Click Me", command=printName)
button1.grid(columnspan=2)
root.mainloop()
|
c000241bd810c5656c19e573880039caa1f5d4df | DanielMalheiros/geekuniversity_programacao_em_python_essencial | /Exercicios/secao07_colecoes_python_parte2/exercicio20.py | 1,395 | 4.28125 | 4 | """20- Faça um programa que leia uma matriz 3x6 com valores reais.
a) Imprima a soma de todos os elementos das colunas ímpares.
b) Imprima a média aritmética dos elementos da segunda e quarta coluna.
c) Substitua os valores da sexta coluna pela soma dos valores das colunas 1 e 2.
d) Imprima a matriz modificada.
"""
matriz = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
somaimpar = 0
soma = 0
divisor = 0
for i in range(3):
for j in range(6):
matriz[i][j] = int(input(f"Defina um valor para a posição [{i}][{j}] da matriz 3 x 6: "))
print("Coluna 0\tColuna 1\tColuna 2\tColuna 3\tColuna 4\tColuna 5:")
for i in range(3):
for j in range(6):
print(f"[{matriz[i][j]:^10}]", end='')
print( )
for i in range(3):
for j in range(6):
if j % 2 != 0:
somaimpar += matriz[i][j]
if j == 1 or j == 3:
soma += matriz[i][j]
divisor += 1
if j == 5:
matriz[i][j] = matriz[i][0] + matriz[i][1]
mediaaritmetica = soma / divisor
print(f"Soma de todos os elementos nas colunas impares: {somaimpar}\nMédia aritmética dos elementos da segunda e"
f" quarta coluna: {mediaaritmetica}\nMatriz modificada: ")
print("Coluna 0\tColuna 1\tColuna 2\tColuna 3\tColuna 4\tColuna 5:")
for i in range(3):
for j in range(6):
print(f"[{matriz[i][j]:^10}]", end='')
print( )
|
de25784b3ef0c51d252667541ac09709e196bc05 | pandorakgz/python_itc | /day2/day24/class_1.py | 767 | 3.90625 | 4 | class Panda:
name = input('Введите имя Панды: ')
weight = int(input('Введите вес Панды: '))
age = int(input('Введите возраст Панды: '))
color = input('Введите цвет Панды: ')
speed = int(input('Введите скорость Панды: '))
power = int(input('Введите мощность Панды: '))
def to_walk(self):
print('Томолоп кеттат')
panda = Panda()
print('Имя Панды', panda.name)
print('Вес Панды', panda.weight)
print('Скорость Панды', panda.speed)
print('Мощность Панды', panda.power)
print('Цвет Панды', panda.color)
print('Возраст Панды', panda.age)
panda.to_walk() |
79c80d6076569641eb605a3aeab7075de87178a9 | alperencucen/GlobalAIHubPythonHomework | /odev2.py | 410 | 4 | 4 | list1 = []
firstname = str(input("Firstname:"))
lastname = str(input("lastname:"))
age = int(input("Age:"))
dateofbirth = int(input("Date of birth:"))
list1.append(firstname)
list1.append(lastname)
list1.append(age)
list1.append(dateofbirth)
for i in list1:
print(i)
if (age < 18):
print("You can't go out because it's too dangerous")
else:
print("You can go out to the street") |
fdbc25c269bc8c29e8b2d3ea981a66bdf51e79c0 | gyang274/leetcode | /src/0600-0699/0663.equal.sum.partition.bt.py | 871 | 3.828125 | 4 | from config.treenode import TreeNode, listToTreeNode
class Solution:
def recursive(self, node):
xl = self.recursive(node.left) if node.left else 0
xr = self.recursive(node.right) if node.right else 0
xs = xl + xr + node.val
# in case xs == 0 and node is root..
if node is not self.root:
self.xsum.add(xs)
return xs
def checkEqualTree(self, root: TreeNode) -> bool:
self.root = root
# xsum: subtree sum
self.xsum = set([])
s = self.recursive(root)
return (s & 1 == 0) and (s // 2 in self.xsum)
if __name__ == '__main__':
solver = Solution()
cases = [
[0,-1,1],
[1,None,2,3],
]
cases = [
listToTreeNode(x) for x in cases
]
rslts = [
solver.checkEqualTree(root) for root in cases
]
for cs, rs in zip(cases, rslts):
print(f"case:\n{cs.display() if cs else None} | solution: {rs}")
|
e34c12cea0dd7b2d4555c3edb0268c1a33c46ebf | jmuguerza/adventofcode | /2017/day2.py | 3,662 | 3.828125 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PART 1
We have to repair the corruption in a spreadsheet. The spreadsheet
consists of rows of apparently-random number. To make sure the
recovery is possible, we need to calculate the CHECKSUM. For each
row, determine the difference between the largest number and the
smallest value; the checksum is the sum of all these differences.
PART 2
The goal now is to find the only two numbers in each row where one
evenly divides the other. The checksum of each line is said division.
"""
INPUT = '''5048 177 5280 5058 4504 3805 5735 220 4362 1809 1521 230 772 1088 178 1794
6629 3839 258 4473 5961 6539 6870 4140 4638 387 7464 229 4173 5706 185 271
5149 2892 5854 2000 256 3995 5250 249 3916 184 2497 210 4601 3955 1110 5340
153 468 550 126 495 142 385 144 165 188 609 182 439 545 608 319
1123 104 567 1098 286 665 1261 107 227 942 1222 128 1001 122 69 139
111 1998 1148 91 1355 90 202 1522 1496 1362 1728 109 2287 918 2217 1138
426 372 489 226 344 431 67 124 120 386 348 153 242 133 112 369
1574 265 144 2490 163 749 3409 3086 154 151 133 990 1002 3168 588 2998
173 192 2269 760 1630 215 966 2692 3855 3550 468 4098 3071 162 329 3648
1984 300 163 5616 4862 586 4884 239 1839 169 5514 4226 5551 3700 216 5912
1749 2062 194 1045 2685 156 3257 1319 3199 2775 211 213 1221 198 2864 2982
273 977 89 198 85 1025 1157 1125 69 94 919 103 1299 998 809 478
1965 6989 230 2025 6290 2901 192 215 4782 6041 6672 7070 7104 207 7451 5071
1261 77 1417 1053 2072 641 74 86 91 1878 1944 2292 1446 689 2315 1379
296 306 1953 3538 248 1579 4326 2178 5021 2529 794 5391 4712 3734 261 4362
2426 192 1764 288 4431 2396 2336 854 2157 216 4392 3972 229 244 4289 1902'''
import itertools
def iterate_input(input):
""" Iterate every line of input """
for line in input.split('\n'):
yield(list(map(int, line.rstrip().split('\t'))))
def get_row_division(row):
""" Get the only possible division by two elements of a row """
for a, b in itertools.combinations(row, 2):
if a % b == 0:
return int(a/b)
if b % a == 0:
return int(b/a)
def get_row_diff(row):
""" Get the difference between the max and the min of a row """
min, max = sorted(row)[::len(row)-1]
return max - min
def get_checksum(spreadsheet, row_check_func):
""" Get the spreadsheet checksum """
return sum((row_check_func(row) for row in spreadsheet))
def test(truth, row_check_func):
for spreadsheet, result in truth:
# Test row by row
for i in range(len(spreadsheet)):
try:
assert(row_check_func(spreadsheet[i]) == result[i])
except AssertionError:
print("Error trying to assert {}('{}') == {}".format(
row_check_func.__name__, spreadsheet[i], result[i]))
# Test spreadsheet
try:
assert(get_checksum(spreadsheet, row_check_func) == result[-1])
except AssertionError:
print("Error trying to assert get_row_diff('{}', {}) == {}".format(
spreadsheet, row_check_func.__name__, result[-1]))
if __name__ == "__main__":
# Test for PART 1
GROUND_TRUTH = (
(((5,1,9,5),(7,5,3),(2,4,6,8)), (8,4,6,18)),
)
test(GROUND_TRUTH, get_row_diff)
# Test for PART 2
GROUND_TRUTH = (
(((5,9,2,8),(9,4,7,3),(3,8,6,5)), (4,3,2,9)),
)
test(GROUND_TRUTH, get_row_division)
# RUN
print('PART 1 result: {}'.format(get_checksum(iterate_input(INPUT), get_row_diff)))
print('PART 2 result: {}'.format(get_checksum(iterate_input(INPUT), get_row_division)))
|
70bba8b2c468b287caba595e29b4f55a950d1c32 | hmanjarawala/Python | /Functional Programming/Recursion/Sum Of Fibbonacci Nos.py | 433 | 4.1875 | 4 | """""
This script will calculate nth fibbonacci numbers
"""""
def fibbonacci(n):
if n == 0 or n == 1:
return 1
else:
return fibbonacci(n-1) + fibbonacci(n-2)
intNumber = 5
try:
intNumber = int(input("Enter the number: "))
except ValueError:
print("Entered value is not valid integer number")
print("continue program with default value 5")
print("Value of %dth fibbonacci number is %d"%(intNumber+1, fibbonacci(intNumber))) |
0315f76992f821d0b3deb93f80a0f5694c939865 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 04/capitulo 04/capitulo 04/exercicio-04-04.py | 1,031 | 4.40625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 04\exercicio-04-04.py
##############################################################################
salário = float(input("Digite seu salário:"))
pc_aumento = 0.15
if salário > 1250:
pc_aumento = 0.10
aumento = salário * pc_aumento
print("Seu aumento será de: R$ %7.2f" % aumento)
|
660adb39836155ea79f2d76ed330fe8c8df59a6b | Nikolas2001-13/Universidad | /Nikolas_ECI_191/AYED/ultra.py | 642 | 3.71875 | 4 | from sys import stdin
def insertionSort(alist):
p=0
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
p+=1
alist[position]=currentvalue
return p
def main():
n=int(stdin.readline().strip())
r=[]
while n!=0:
p=0
for i in range(n):
a=int(stdin.readline().strip())
r.append(a)
print(insertionSort(r))
n=int(stdin.readline().strip())
r=[]
main()
|
1d3693ecff3945901e5bb8a8fa6bc8d765457237 | darkknight161/crash_course_projects | /favorite_languages1.py | 432 | 3.5 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
polling_list = ['jen', 'sarah', 'edward', 'phil', 'josh', 'brandie',\
'jonas', 'ian', 'sunny', 'natalia']
for invitee in sorted(polling_list):
if invitee not in favorite_languages.keys():
print(f'{invitee.title()}, please come and take our poll!')
else:
print(f'{invitee.title()}, thank you for taking the poll!')
|
b20a4be156bc635062b928b3e7b307f0ec1e16e0 | remir88/leetcode_cn | /(TLE)~5.最长回文子串.py | 545 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子串
#
# @lc code=start
class Solution:
def isPalindrome(self, s: str) -> bool:
for x in range(0, len(s)//2):
if s[x]!=s[len(s)-(x+1)]:
return False
return True
def longestPalindrome(self, s: str) -> str:
for length in range(len(s), 0, -1):
for i in range(0, len(s)-length+1):
if self.isPalindrome(s[i:length+i]):
return(s[i:length+i])
return(s)
# @lc code=end
|
544caf69be49399b3cc7cac471458504ad59cbac | aishwarya34/Python | /numpy/sum_numpy.py | 1,044 | 3.703125 | 4 | import numpy as np
# need sum s+b as scalar
W = np.random.randn(4, 4, 3)
b = np.random.randn(1, 1, 1)
s = np.sum(W) # np.sum() gives integer
print(s)
print(b) # b is still array
print(s+b) #will result in an 3D array output of this sum
print(float(s+b)) # need to use float to cast array to scalar
print( s + float(b) , "\n") #will not result in an 3D array output of this sum, but a scalar output
# need sum s+b as scalar when b is obtained from new_b
new_b = np.random.randn(1, 1, 1, 10)
print(new_b)
b = new_b[:,:,:,1] # on slicing b , it's still a 3D array
print(b)
print(s+b) #will result in an 3D array output of this sum
print( s + float(b) ) #will not result in an 3D array output of this sum, but a scalar output
"""
Output:
3.4050427852171303
[[[0.46932232]]]
[[[3.8743651]]]
3.874365100386826
3.874365100386826
[[[[ 1.18973494 -1.39765882 0.09553642 0.61802283 -2.2521763
2.12645673 0.49754439 -0.96717106 0.91325472 -1.10083306]]]]
[[[-1.39765882]]]
[[[2.00738396]]]
2.0073839643048403
""" |
352c985ddce5f567f3a60218679253f077168936 | erkin98/Python-ile-Veri-Bilimi-Uygulamalar- | /veri_manipulasyonu_Numpy.py | 5,298 | 3.921875 | 4 | # Numpy (Numerical Python)
'''
# Döngülerden Vektörel Operasyonlara
# Array ve matrisler üzerinde yüksek performanslı çalışma imkanı sağlar
# Python'ın analitik dünyasının zeminidir. Ana kütüphane olarak nitelendirilebilir
'''
a = [1,2,3,4]
b = [2,3,4,5]
ab = []
for i in range(0, len(a)):
ab.append(a[i]*b[i])
ab
import numpy as np
a = np.array([1,2,3,4])
b = np.array([2,3,4,5])
a*b
'''
* ?np ile başına ? koyarak dokümantasyona ulaşabiliriz
* Python C dili ile yazılmıştır.
'''
# Numpy Arrayleri Oluşturma
## Listelerden Arrey Oluşturmak
import numpy as np
np.array([12,33,4,5])
a=np.array([12,33,4,5])
a
type(a)
np.array([3.14,4,5,1.2])
# Array oluşturduğumda köşeli parantez kullan
# Sıfırlardan oluşan bir seri
np.zeros(10, dtype = int)
# Satır ve sütunları belirtilen 1'lerden oluşan matris
np.ones((2,3))
np.full((2,3),9)
np.arange(0,10,2)
np.linspace(0,1,30)
np.random.normal(0,1,(3,4))
np.random.randint(0,10,(2,2))
np.eye(3)
## Numpy Biçimlendirme
'''
ndim: Boyut Sayısı
shape: Boyut Bilgisi
size: Toplam Eleman Sayısı
dtype: Array Veri Tipi
'''
import numpy as np
a = np.random.randint(10, size = 10)
a.ndim
a.shape
a.size
a.dtype
a = np.random.randint(10, size = (10,5))
a.ndim
a.shape
a.size
a.dtype
# Reshaping
np.arange(1,10).reshape((3,3))
a = np.array([1,2,3])
a
# Elimizdeki arrayi matrixe çevirme işlemi
b = a.reshape((1,3))
b
b.ndim
a[np.newaxis,:]
a[:,np.newaxis]
## Array Birleştirme İşlemi
x = np.array([1,2,3])
y = np.array([4,5,6])
x
y
np.concatenate([x,y])
z = [1,2,3]
np.concatenate([x,y,z])
# İki Boyutlu
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a
np.concatenate([a,a])
np.concatenate([a,a],axis=1)
# Farklı boyutlu
a = np.array([1,2,3])
b = np.array([[9,8,7],[6,5,4]])
a
b
np.vstack([a,b])
a = np.array([[99],[99]])
a
np.hstack([a,b])
## Splitting(Ayırma İşlemi)
x = [1,2,3,9,99,3,2,1]
x
np.split(x,[3,5])
a,b,c = np.split(x,[3,5])
m = np.arange(16).reshape((4,4))
m
# Dikey
np.vsplit(m,[2])
ust, alt = np.vsplit(m,[2])
ust
alt
# Yatay
np.hsplit(m, [2])
sag, sol = np.hsplit(m, [2])
v = np.array([2,3,1,5,3,2])
v
np.sort(v)
v
# Bu şekilde v değişkenini güncelleyebilirsin(sort)
v.sort()
v = np.array([2,3,1,5,3,2])
np.sort(v)
# Yaptığımız sıralama işlemi sonrasında index değişklkleri
# Sıralama indexleri
i = np.argsort(v)
i
# Numpy Eleman İşlemleri
import numpy as np
a = np.random.randint(10,size = 10)
a
a[0]
a[-2]
a[0] = 1
a
a = np.random.randint(10,size = (3,5))
a
a[0,0]
a[0,0] = 2
a
a[0,0] = 2.2
a
## Slicing ile Array Alt Kümelerine Erişmek
a = np.arange(20,30)
a
a[0:3]
a[3:]
a[::2]
a[1::2]
a[2::2]
a[1::3]
a = np.random.randint(10, size = (5,5))
a
a[:,0]
a[:,1]
a[0,:]
a[0]
a[:2,:3]
a[0:2,0:3]
a[::,:2]
a[1:3,0:2]
# Array Alt Kümelerini Bağımsızlaştırmak
a = np.random.randint(10, size = (5,5))
a
alt_a = a[0:3,0:2]
alt_a
alt_a[0,0] = 9999
alt_a[1,1] = 9999
alt_a
a
#alt_a da yapılan değişiklikler a yı da etkiledi
a = np.random.randint(10, size = (5,5))
a
alt_b = a[0:3,0:2].copy()
alt_b
alt_b[0,0] = 9999
alt_b[1,1] = 9999
alt_b
## Fancy Index ile Eleman Islemleri
v = np.arange(0,30,3)
v
v[1]
v[3]
[v[1],v[3]]
al_getir = [1,3,5]
v[al_getir]
m = np.arange(9).reshape((3,3))
m
satir = np.array([0,1])
sutun = np.array([1,2])
m[satir,sutun]
# Kesişimleri
m[0,[1,2]]
m[0:,[1,2]]
v = np.arange(10)
v
index = np.array([0,1,2])
index
v[index] = 99
v
v[[0,1]] = [4,6]
v
## Koşullu Eleman İşlemleri
v = np.array([1,2,3,4,5])
v>3
v <= 3
v == 3
v != 3
(2*v)
v**2
#ufunc
np.equal(3,v)
np.equal([0,1,3],np.arange(3))
v = np.random.randint(0,10,(3,3))
v > 5
np.sum(v>5)
np.sum((v>3) | (v<7))
np.sum(v > 4, axis = 1)
# Verideki tüm elemanlar 4ten büyük mü değil mi?
np.all(v>4)
np.any(v>4)
# axis = 0 sütun 1 satır bazında işlem yapar
np.any(v>4, axis = 1)
v = np.array([1,2,3,4,5])
v[v>3]
v[(v>1) & (v<5)]
# Numpy Hesaplamalı İşlemler
a = np.array([0,1,2,3,4])
a
np.add(a,2)
np.subtract(a,1)
np.divide(a,3)
a = np.arange(1,6)
a
np.add.reduce(a)
np.add.accumulate(a)
a = np.random.normal(0,1,30)
a
np.mean(a)
np.std(a)
np.median(a)
np.min(a)
a = np.random.normal(0,1,(3,3))
a
# Satır Bazında toplamlar
a.sum(axis=1)
# Farklı Boyutlu Arrayler ile Çalışmak(Broadcasting)
# Broadcasting yaymak anlamına gelmektedir
import numpy as np
a = np.array([1,2,3])
b = np.array([1,2,3])
a+b
m = np.ones((3,3))
m
a+m
a = np.arange(3)
a
b = np.arange(3)[:,np.newaxis]
b
a+b
# Hello and Goodbye Numpy!
isim = ['ali', 'veli','isik']
yas = [25,22,19]
boy = [168,159,172]
import numpy as np
data = np.zeros(3,dtype = {'names':('isim','yas','boy'),
'formats':('U10','i4','f8')})
data
data ['isim'] = isim
data ['yas'] = yas
data ['boy'] = boy
data
data[0]
data[data['yas'] < 25]['isim']
|
e5dc836a7dda9daa6f8e96304fb845a4fca8b7c5 | mida-hub/hobby | /atcoder/python/beginner/abc243/C/main.py | 1,456 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
YES = "Yes" # type: str
NO = "No" # type: str
def solve(N: int, X: "List[int]", Y: "List[int]", S: str):
check_dict = {}
for i in range(N):
if check_dict.get(Y[i]) is None:
check_dict[Y[i]] = {S[i]: [X[i]]}
elif check_dict[Y[i]].get(S[i]) is not None:
ys = check_dict[Y[i]].get(S[i])
ys.append(X[i])
else:
y = check_dict[Y[i]]
y[S[i]] = [X[i]]
# print(check_dict)
for c in check_dict:
if len(check_dict[c]) >= 2:
# print(check_dict[c])
min_r = min(check_dict[c].get('R'))
max_l = max(check_dict[c].get('L'))
if min_r < max_l:
print(YES)
return
print(NO)
return
# Generated by 2.12.0 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
X = [int()] * (N) # type: "List[int]"
Y = [int()] * (N) # type: "List[int]"
for i in range(N):
X[i] = int(next(tokens))
Y[i] = int(next(tokens))
S = next(tokens) # type: str
solve(N, X, Y, S)
if __name__ == '__main__':
main()
|
75473d0a1399179e16a9db8b48cfb6259618b546 | yfractal/cs61a | /labs/lab4.py | 2,179 | 3.96875 | 4 | def make_rat(num, den):
return (num, den)
def num(rat):
return rat[0]
def den(rat):
return rat[1]
def mul_rat(a, b):
new_num = num(a) * num(b)
new_den = den(a) * den(b)
return make_rat(new_num, new_den)
def div_rat(a,b):
new_num = num(a) * den(b)
new_den = den(a) * num(b)
return make_rat(new_num, new_den)
def str_rat(x):
#from lecture notes
"""Return a string 'n/d' for numerator n and denominator d."""
return '{0}/{1}'.format(num(x), den(x))
#Ex 5
#x,y
#c
def make_point(x,y):
return (x,y)
#s
def x_coord(p):
return p[0]
def y_coord(p):
return p[1]
def dist(s,e):
dx = x_coord(e) - x_coord(s)
dy = y_coord(e) - y_coord(s)
return square_root( square(dx) + square(dy) )
#segment
#c
def make_segment(start_p,end_p):
return (start_p,end_p)
#s
def start_segment(segment):
return segment[0]
def end_segment(segment):
return segment[1]
def mid_point(segment):
s = start_segment(segment)
e = end_segment(segment)
new_x = (x_coord(s) + x_coord(e)) / 2
new_y = (y_coord(s) + y_coord(e)) / 2
return make_point(new_x,new_y)
def square(x):
return x * x
def square_root(x):
assert x >= 0 ,"give me a possible number please"
return x ** 0.5
#Ex 6
def make_pair(x, y):
"""Return a function that behaves like a pair."""
def dispatch(m):
assert m <= 2,"Message not recognized"
if m == 0:
return x
elif m == 1:
return y
return dispatch
#Ex 7
def make_rectangle(p1,p2,p3):
return (p1,p2,p3)
def first_point(rectangle):
return rectangle(0)
def second_point(rectangle):
return rectangle(1)
def third_point(rectangle):
return rectangle(2)
def perimeter(rectangle):
p1 = first_point(rectangle)
p2 = second_point(rectangle)
p3 = third_point(rectangle)
d1 = dist(p1,p2)
d2 = dist(p2,p3)
e3 = dist(p3,p1)
return d1 + d2 + d3
def area(rectangle):
# S=√[p(p-a)(p-b)(p-c)] [p=1/2(a+b+c)](海伦--秦九韶公式)
p1 = first_point(rectangle)
p2 = second_point(rectangle)
p3 = third_point(rectangle)
d_a = dist(p1,p2)
d_b = dist(p2,p3)
e_c = dist(p3,p1)
p = d_a + d_b + d_c
return square_root(p * (p - d_a) * (p - d_b) * p_c )
|
65379d76926e65d25ab0b165b0e80513f70984fc | thosamanitha/python | /python/accpractice.py | 1,825 | 3.59375 | 4 | class Employee:
raise_amt=1.04
def __init__(self,first,last,pay):
self.first=first
self.last=last
self.pay=pay
self.email=first+ "."+ last+ "@gmail.com"
def fullname(self):
return "{} {}".format(self.first,self.last)
def apply_raise(self):
self.pay=int(self.pay*self.raise_amt)
return self.pay
class developer(Employee):
raise_amt=1.10
def __init__(self,first,last,pay,prog_lang):
super().__init__(first,last,pay)
self.prog_lang=prog_lang
class manager(Employee):
def __init__(self,first,last,pay,employees=None):
super().__init__(first,last,pay)
if(employees is None):
self.employees=[]
else:
self.employees=employees
def add_emp(self,emp):
if(emp not in self.employees):
self.employees.append(emp)
def remove_emp(self,emp):
if(emp in self.employees):
self.employees.remove(emp)
def print_emp(self):
for emp in self.employees:
print("-->", emp.fullname())
dev_1=developer("anu","thosam",50000,"python")
dev_2=developer("chinni","thosam",60000,"java")
mgr_1=manager("anu","chinni",90000,[dev_1])
print(isinstance(mgr_1,manager))
print(issubclass(manager,Employee))
print(mgr_1.email)
mgr_1.add_emp(dev_2)
mgr_1.remove_emp(dev_1)
mgr_1.print_emp()
#print(dev_1.prog_lang)
#print(dev_1.anitha)
#print(dev_1.first,dev_1.pay)
#print(dev_2.email)
#print(dev_1.fullname())
#print(dev_1.apply_raise())
#d=developer("suni","suji",90000)
#print(d.apply_raise())
print(dev_1.pay)
print(dev_1.apply_raise())
print(dev_1.pay) |
36a69c724fb6f3bf6128e9522fe51b2de9653144 | pecata83/soft-uni-python-solutions | /Programing Basics Python/While Loop Exercise copy/06.py | 394 | 4.09375 | 4 | width = int(input())
length = int(input())
cake_peaces = width * length
while True:
if cake_peaces >= 0:
_input = input()
if _input == "STOP":
print(f"{cake_peaces} pieces are left.")
break
else:
cake_peaces -= int(_input)
else:
print(f"No more cake left! You need {abs(cake_peaces)} pieces more.")
break
|
5baf5eedb19409f8f1c79f59b649bb53c31586d3 | kvoss/trie | /trie.py | 1,633 | 3.5625 | 4 | """ Trie in Python based on dict
author: K.Voss
"""
class Trie(object):
MAGIC_KEY = 'value'
def __init__(self):
self.tree = dict()
def __str__(self):
return str(self.tree)
def insert(self, key, val=None):
node = self.tree
for c in key:
parent = node
node = node.setdefault(c, dict())
node[self.MAGIC_KEY] = val
def get(self, key):
node = self.tree
for c in key:
node = node.get(c)
if not node:
break
return node
def remove(self, key):
if not self.has(key): return
node = self.get(key)
del node[self.MAGIC_KEY]
rprefixes = reversed([key[:l] for l in range(1,len(key)+1)])
delk = None
for rp in rprefixes:
node = self.get(rp)
if delk: del node[delk]
if len(node.keys()) > 0: return
else: delk = rp[-1]
del self.tree[delk]
def has(self, key):
node = self.get(key)
if node and self.MAGIC_KEY in node.keys():
return True
return False
import unittest
class TestTrie(unittest.TestCase):
def test_ops(self):
t = Trie()
t.insert('ann', 24)
t.insert('aneta', 25)
t.insert('monica', 25)
# self.assertEqual(25, t.get('an'))
self.assertTrue(t.has('ann'))
self.assertTrue(not t.has('anna'))
t.remove('aneta')
self.assertTrue(not t.has('aneta'))
t.remove('ann')
self.assertTrue(not t.has('ann'))
if __name__ == '__main__':
unittest.main()
|
0d7a542492e499b1f25f397cd42434a58b6fcaf1 | HenryHdez/ASIGNATURAS | /Diseño_Digital_Avanzado/Python_proyectos/Python_Unicamente/Interfaz-Grafica/Cambiar_Tamana.py | 950 | 3.71875 | 4 | #Asignar una función a los botones
import sys
from Tkinter import*
app=Tk()
#Tamano en pixeles
app.geometry("400x800")
app.title("Función en Python")
#Configurar la ventana principal
vp=Frame(app,background="yellow")
vp.grid(column=10, row=20)
vp.columnconfigure(0,weight=1)
vp.rowconfigure(0,weight=1)
#Establecer Valores por defecto
#Declarar etiqueta
#Con el comando Foreground cambian el color de la letra
Salida_Label="Ingrese dato"
etiqueta=Label(vp, text=Salida_Label, foreground="blue")
etiqueta.grid(column=1, row=1)
#Declarar Botón
#Con width y heigh cambian el ancho y alto de algo
boton=Button(vp, text="Pulse Aqui",width=2,heigh=3)
#Fija ubicación
boton.grid(column=3,row=2)
#Declarar Caja de Texto
#Con background cambian su color (debe estar su nombre en ingles)
Salida=" "
Nombre_de_la_Caja=Entry(vp, textvariable=Salida,background="red")
Nombre_de_la_Caja.grid(column=4,row=1)
#Bucle infinito de la aplicación
app.mainloop()
|
a12612eb23899fc04071cf3a1c571b269d046c8c | ynskardas/university_projects | /IE 310/Assignment3/main3.py | 10,837 | 4.40625 | 4 | from sys import exit
import sys
import math
# Python 3 program to find rank of a matrix
class rankMatrix(object):
def __init__(self, Matrix):
self.R = len(Matrix)
self.C = len(Matrix[0])
# Function for exchanging two rows of a matrix
def swap(self, Matrix, row1, row2, col):
for i in range(col):
temp = Matrix[row1][i]
Matrix[row1][i] = Matrix[row2][i]
Matrix[row2][i] = temp
# Function to Display a matrix
def Display(self, Matrix, row, col):
for i in range(row):
for j in range(col):
print (" " + str(Matrix[i][j]))
print ('\n')
# Find rank of a matrix
def rankOfMatrix(self, Matrix):
rank = self.C
for row in range(0, rank, 1):
# Before we visit current row
# 'row', we make sure that
# mat[row][0],....mat[row][row-1]
# are 0.
# Diagonal element is not zero
if Matrix[row][row] != 0:
for col in range(0, self.R, 1):
if col != row:
# This makes all entries of current
# column as 0 except entry 'mat[row][row]'
multiplier = (Matrix[col][row] /
Matrix[row][row])
for i in range(rank):
Matrix[col][i] -= (multiplier *
Matrix[row][i])
# Diagonal element is already zero.
# Two cases arise:
# 1) If there is a row below it
# with non-zero entry, then swap
# this row with that row and process
# that row
# 2) If all elements in current
# column below mat[r][row] are 0,
# then remvoe this column by
# swapping it with last column and
# reducing number of columns by 1.
else:
reduce = True
# Find the non-zero element
# in current column
for i in range(row + 1, self.R, 1):
# Swap the row with non-zero
# element with this row.
if Matrix[i][row] != 0:
self.swap(Matrix, row, i, rank)
reduce = False
break
# If we did not find any row with
# non-zero element in current
# columnm, then all values in
# this column are 0.
if reduce:
# Reduce number of columns
rank -= 1
# copy the last column here
for i in range(0, self.R, 1):
Matrix[i][row] = Matrix[i][rank]
# process this row again
row -= 1
# self.Display(Matrix, self.R,self.C)
return (rank)
def transposeMatrix(m):
rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
return rez
def getMatrixMinor(m,i,j):
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]
def getMatrixDeternminant(m):
#base case for 2x2 matrix
if len(m) == 2:
return m[0][0]*m[1][1]-m[0][1]*m[1][0]
determinant = 0
for c in range(len(m)):
determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))
return determinant
def getMatrixInverse(m):
determinant = getMatrixDeternminant(m)
#special case for 2x2 matrix:
if len(m) == 2:
return [[m[1][1]/determinant, -1*m[0][1]/determinant],
[-1*m[1][0]/determinant, m[0][0]/determinant]]
#find matrix of cofactors
cofactors = []
for r in range(len(m)):
cofactorRow = []
for c in range(len(m)):
minor = getMatrixMinor(m,r,c)
cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor))
cofactors.append(cofactorRow)
cofactors = transposeMatrix(cofactors)
for r in range(len(cofactors)):
for c in range(len(cofactors)):
cofactors[r][c] = cofactors[r][c]/determinant
return cofactors
def display(M):
for i in range(len(M)):
print(M[i])
def displayTable(M):
for i in range(len(M)):
for j in range(len(M[i])):
M[i][j] = "| " + str(M[i][j]) + " |"
display(M)
def multiplication(X, Y):
len1 = len(X)
len2 = len(Y[0])
result = []
for i in range(len1):
temp = []
for j in range(len2):
temp.append(0)
result.append(temp)
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result
def recursionX(A, b, x, j):
n = len(x)
if j == 0:
return x
else:
total = 0
for i in range(j, n, 1):
total += A[j-1][i] * x[i]
x[j-1] = (b[j-1] - total) / A[j-1][j-1]
return recursionX(A, b, x, j-1)
def arbitrary(A, b):
n = len(b)
x = []
for i in range(n):
x.append(0)
for i in range(len(A)):
for j in range(len(A[0])):
if (A[i][i] == 0 and b[i] == 0):
x[j] = 0
x = recursionX(A, b, x, j)
return x
def floatReg(X):
for i in range(0, len(X)):
for j in range(1, len(X[i])):
X[i][j] = float("%.3f" % X[i][j])
return X
def matrixId(n):
result = []
for i in range(n):
temp = []
for j in range(n):
if i == j:
temp.append(1)
else:
temp.append(0)
result.append(temp)
return result
def vecToMat(v):
k = []
k.append(v)
return k
def matToVec(m):
v = []
for i in range(len(m)):
for j in range(len(m[0])):
v.append(m[i][j])
return v
def elementSwap(A, a, B, b):
A1 = transposeMatrix(A)
B1 = transposeMatrix(B)
hold = A1[a]
hold2 = B1[b]
A1[a] = hold2
B1[b] = hold
A = transposeMatrix(A1)
B = transposeMatrix(B1)
return (A, B)
def simplexOpps(M, col, row, X):
pivot = M[row][col]
M[row][0] = X[col]
for i in range(1, len(M[row])):
M[row][i] = M[row][i] / pivot
for i in range(0, len(M)):
k = (-1) * M[i][col]
if i != row:
for j in range(1, len(M[0])):
M[i][j] = M[row][j] * k + M[i][j]
return M
OUTPUT_FILE = "output.txt"
INPUT_FILE = ""
inp = ["Assignment3_Spring2020_Data1.txt", "Assignment3_Spring2020_Data2.txt", "Assignment3_Spring2020_Data3.txt"]
numOfFile = len(inp)
f = open(OUTPUT_FILE, "w")
for ii in range(numOfFile):
INPUT_FILE = inp[ii]
n = 0
m = 0
A = []
X = []
A_B1 = []
z = 0
B1 = []
b = []
nonbasis = []
basis = []
bVec = []
cB = []
cN = []
xMx = []
Table = []
with open(INPUT_FILE) as file:
line = file.readline()
m, n = line.strip().split("\t")
m = int(m)
n = int(n)
line = file.readline()
cN1 = line.strip().split("\t")
for i in range(len(cN1)):
cN1[i] = -1 * float(cN1[i])
cN = cN1
for line in file:
listAB = line.strip().split("\t")
for i in range(len(listAB)):
listAB[i] = float(listAB[i])
A_B1.append(listAB)
for i in range(m):
rowMofA = []
rowMofB1 = []
for j in range(n + 1):
if j < n:
rowMofA.append(A_B1[i][j])
else:
rowMofB1.append(A_B1[i][j])
A.append(rowMofA)
B1.append(rowMofB1)
for i in range(len(B1)):
for j in range(len(B1[0])):
bVec.append(B1[i][j])
b = B1
for i in range(n+m+1):
xMx.append("x" + str(i))
xMx.append("RHS")
for i in range(m+1):
k = []
if i == 0:
k.append("z")
for j in range(n):
k.append(cN[j])
for j in range(m + 1):
k.append(0)
elif i < m+1:
k.append("x" + str(n+i))
for j in range(len(A[0])):
k.append(A[i-1][j])
for j in range(n+1, n+m+1):
if i + n == j:
k.append(1.0)
else:
k.append(0)
k.append(b[i-1][0])
Table.append(k)
check = True
t = 0
while(check):
indRow = 0
indCol = 0
minNeg = 0
minPos = -1
for i in range(1, len(Table[0])):
if Table[0][i] < 0:
if Table[0][i] < minNeg:
minNeg = Table[0][i]
indCol = i
if indCol == 0:
break
ctrl = True
for i in range(1, len(Table)):
top = Table[i][n+m+1]
bot = Table[i][indCol]
# print((top,bot))
if bot > 0:
if ctrl:
# print("ctrl works")
minPos = top / bot
indRow = i
ctrl = False
else:
if top / bot < minPos:
minPos = top / bot
indRow = i
# print((minPos, indRow))
if indRow == 0:
break
t = t + 1
if(t == 5):
check = False
Table = simplexOpps(Table, indCol, indRow, xMx)
# print("\n-------------------")
# # print((indRow, indCol))
# # print("\n")
# display(Table)
Table = floatReg(Table)
z = Table[0][n+m+1]
xSol = [0]*n
for i in range(1, len(Table)):
for j in range(1, n+1):
if Table[i][0] == "x" + str(j):
xSol[j-1] = Table[i][n+m+1]
f.write("{}\n".format("Optimal Variable Vector: " + str(xSol)))
f.write("{}\n\n\n".format("Optimal Result: "+ str(z)))
|
2cc3e9393a9b70734f8c68b6de8bb1caa0f1513f | kq-li/stuy | /pclassic/2016f/stubs/Treasons.py | 1,423 | 4.03125 | 4 | def getCharIndex(c):
return ord(c) - ord('a')
def anagram_tester(word_list):
"""
:param word_list: list of words
:return: largest set of words that are all anagrams in alphabetical order
"""
# TODO: implement
primes = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29,
31, 37, 41, 43, 47,
53, 59, 61, 67, 71,
73, 79, 83, 89, 97,
101]
word_dict = {}
for word in word_list:
product = 1
for c in word:
product *= primes[getCharIndex(c)]
if product in word_dict:
word_dict[product].append(word)
else:
word_dict[product] = [word]
maxWords = 0
maxWordProduct = 0
for product in word_dict:
curWords = len(word_dict[product])
if curWords > maxWords:
maxWords = curWords
maxWordProduct = product
return sorted(word_dict[maxWordProduct])
def parse_file_and_call_function():
with open("TreasonsIN.txt", "r") as f:
line = f.readline()
test_cases = line.split('|')
for test_case in test_cases:
test_case = [s for s in test_case.split(' ') if len(s.strip()) > 0]
if len(test_case) > 0:
ans = anagram_tester(test_case)
print '[{}]'.format(', '.join(ans))
if __name__ == "__main__":
parse_file_and_call_function()
|
e7d22d823a46bd592eab454dee667a287ad56fbd | Rusty89/Encrypt | /encrypt.py | 9,654 | 3.796875 | 4 | import re
import random
def main():
try:
def encrypt(string,level,degree):
if level==0:
return(string)
new_string=""
alphabet=("abEFefghABCDmnopq&*()tuvwxy_+{}rszGHIJKLM"+
"RSTU3NOPQ45678VWXY90~!@#$%|Zi `12:<c>?[jkld];,\/.'""^")
for chop in range(0,len(string),degree):
for letter in string[chop:chop+degree-1]:
for i in range(len(alphabet)):
if letter==alphabet[i]:
new_string+=alphabet[i-1]
new_string+=string[chop+degree-1:chop+degree]
if level>0:
return(encrypt(new_string,level-1,degree))
salt=["afunzd","andzs","rtheg","dfsa","treyrtg","aFcgE", "Tscghe","apotoatoD","32cg","234cgeDwe","dscg2346","1325", "elephafant"]
save=""
file_read=""
encrypt_decrypt=(input("Type Decrypt(D) or Encrypt(E) to begin, type Exit to leave>>> ")).capitalize()
print("")
if encrypt_decrypt=="Encrypt" or encrypt_decrypt=="E":
message=input("Enter message you want encrypted or type Encrypt(E) again to\nopen a txt file"+
" located in the same folder as this program>>> ")
print("")
if message.capitalize()=="E" or message.capitalize()=="Encrypt":
provided_file=open(input("Enter the name of file you want encrypted>>> ")+".txt","r")
print("")
message=(provided_file.read())
message=message.replace('.', 'peRioD')
message=message.replace('"', 'qUotE')
message=message.replace(',', 'cOMmA')
message=message.replace('?', 'queStIoNMarK')
message=message.replace('\n', ' ').replace('\r', ' ')
message= re.sub('[^0-9a-zA-Z]+', ' ', message)
#add salt
while(" " in message):
for i in range(len(message)):
if (message[i]==" "):
indice=random.randint(0,len(salt)-1)
message = message[:i]+salt[indice]+message[i+1:]
provided_file.close()
encryption_level=int(input("Enter encryption key>>> "))
while encryption_level>91:
print("")
encryption_level=int(input("Encryption level too high enter lower value>>> "))
print("")
encryption_degree=int(input("Enter encryption degree>>> "))
while encryption_degree<1:
print("")
encryption_degree=int(input("Encryption degree to low>>> "))
print("")
encrypted_message=encrypt(message,encryption_level,encryption_degree)
file_read="True"
if file_read!="True":
encryption_level=int(input("Enter encryption key>>> "))
while encryption_level>91:
print("")
encryption_level=int(input("Encryption level too high enter lower value>>> "))
print("")
encryption_degree=int(input("Enter encryption degree>>> "))
while encryption_degree<1:
print("")
encryption_degree=int(input("Encryption degree to low>>> "))
print("")
### replace periods, commas and quotes, remove newlines, get rid of any remaining non alphanumerics.
message=message.replace('.', 'peRioD')
message=message.replace('"', 'qUotE')
message=message.replace(',', 'cOMmA')
message=message.replace('?', 'queStIoNMarK')
message=message.replace('\n', ' ').replace('\r', ' ')
message= re.sub('[^0-9a-zA-Z]+', ' ', message)
#add salt
while(" " in message):
for i in range(len(message)):
if (message[i]==" "):
indice=random.randint(0,len(salt)-1)
message = message[:i]+salt[indice]+message[i+1:]
print(message)
encrypted_message=encrypt(message,encryption_level,encryption_degree)
print("Encrypted message is as follows>>> ",encrypted_message)
print("")
save=input("Would you like to save your encrypted message?(Y/N)>>>")
print("")
if save.upper()=="Y":
encrypted_file=open(input("Enter the name of the new encrypted file>>> ")+".txt","w")
encrypted_file.write(str(encryption_level)+"\n"+str(encryption_degree)+"\n")
encrypted_file.write(encrypted_message)
encrypted_file.close()
print("")
print("Message encrypted and saved.")
print("")
if encrypt_decrypt=="Decrypt" or encrypt_decrypt=="D":
message=input("Enter message you want decrypted or type Decrypt(D) again to\nopen previously recorded encryption>>> ")
print("")
if message.capitalize()=="D" or message.capitalize()=="Decrypt":
encrypted_file=open(input("Enter the name of the encrypted file>>> ")+".txt","r")
print("")
encryption_level=int(encrypted_file.readline())
encryption_degree=int(encrypted_file.readline())
message=(encrypted_file.readline())
encrypted_file.close()
decrypted_message=encrypt(message,92-encryption_level,encryption_degree)
### replace periods and quotes
decrypted_message=decrypted_message.replace('peRioD', '.')
decrypted_message=decrypted_message.replace('qUotE', '"')
decrypted_message=decrypted_message.replace('cOMmA',',')
decrypted_message=decrypted_message.replace("queStIoNMarK",'?')
#remove salt
for i in salt:
decrypted_message = decrypted_message.replace(i, " ")
print("Decrypted message is as follows>>> ",decrypted_message)
print("")
save=input("Would you like to save your decrypted message?(Y/N)>>>")
print("")
if save.upper()=="Y":
decrypted_file=open(input("Enter the name of the new decrypted file>>> ")+".txt","w")
decrypted_file.write(decrypted_message)
decrypted_file.close()
print("")
print("Message decrypted and saved.")
print("")
file_read="True"
if file_read!="True":
encryption_level=int(input("Enter encryption key>>> "))
while encryption_level>91:
print("")
encryption_level=int(input("Encryption level too high enter lower value>>> "))
print("")
encryption_degree=int(input("Enter encryption degree>>> "))
while encryption_degree<1:
print("")
encryption_degree=int(input("Encryption degree to low>>> "))
print("")
decrypted_message=encrypt(message,92-encryption_level,encryption_degree)
### replace periods and quotes
decrypted_message=decrypted_message.replace('peRioD', '.')
decrypted_message=decrypted_message.replace('qUotE', '"')
decrypted_message=decrypted_message.replace('cOMmA',',')
decrypted_message=decrypted_message.replace('queStIoNMarK','?')
##remove gibberish
for i in salt:
decrypted_message = decrypted_message.replace(i, " ")
print("Decrypted message is as follows>>> ",decrypted_message)
print("")
save=input("Would you like to save your decrypted message?(Y/N)>>>")
print("")
if save.upper()=="Y":
decrypted_file=open(input("Enter the name of the new decrypted file>>> ")+".txt","w")
decrypted_file.write(decrypted_message)
decrypted_file.close()
print("")
print("Message decrypted and saved.")
print("")
if encrypt_decrypt=="Exit":
global run
run="exit"
except ValueError:
print("\nAn incorrect value was entered causing an error, program restarting...\n")
main()
except TypeError:
print("\nAn incorrect value was entered causing an error, program restarting...\n")
main()
except FileNotFoundError:
print("\nUnable to locate file specified, program restarting...\n")
main()
run="run"
while run!="exit":
main()
|
f6e422b07c5e5445758ad9a4a66328dccb437bf2 | aadilmeymon/100-days-of-python | /100 days of python day 4/day4_project.py | 1,032 | 4.125 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
game_images=[rock,paper,scissors]
user_choice=int(input("What do you choose. Type '0' for Rock, '1' for Paper, '2' for Scissors\n"))
if user_choice>=3 or user_choice<0:
print("Invalid choice!")
else:
print(game_images[user_choice])
computer_choice = random.randint(0, 2)
print(f"Computer Chose: {computer_choice} ")
print(game_images[computer_choice])
if user_choice==0 and computer_choice==2:
print("You Win!")
elif computer_choice==0 and user_choice==2:
print("You Lose!")
elif computer_choice>user_choice:
print("You Lose!")
elif computer_choice<user_choice:
print("You Win!")
else:
print("draw! try once more")
|
083467be8d67bc4fcf1a9788d690fa0fdf3b364b | fanliu1991/LeetCodeProblems | /2_Add_Two_Numbers.py | 3,852 | 3.640625 | 4 | '''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
'''
import sys, optparse, os
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
'''
Algorithm
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 0…9, summing two digits may "overflow". For example 5+7=12. In this case, we set the current digit to 2 and bring over the carry=1 to the next iteration. carry must be either 0 or 1 because the largest possible sum of two digits (including the carry) is 9+9+1=19.
The pseudocode is as following:
--- Initialize current node to dummy head of the returning list.
--- Initialize carry to 000.
--- Initialize ppp and qqq to head of l1l1l1 and l2l2l2 respectively.
--- Loop through lists l1l1l1 and l2l2l2 until you reach both ends.
* Set xxx to node ppp's value. If ppp has reached the end of l1l1l1, set to 000.
* Set yyy to node qqq's value. If qqq has reached the end of l2l2l2, set to 000.
* Set sum=x+y+carrysum = x + y + carrysum=x+y+carry.
* Update carry=sum/10carry = sum / 10carry=sum/10.
* Create a new node with the digit value of (summod10)(sum \bmod 10)(summod10) and set it to current node's next, then advance current node to next.
* Advance both ppp and qqq.
--- Check if carry=1carry = 1carry=1, if so append a new node with digit 111 to the returning list.
--- Return dummy head's next node.
Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head's value.
Take extra caution of the following cases:
// l1=[0,1],
l2=[0,1,2]
When one list is longer than the other.
//l1=[]
l2=[0,1]
When one list is null, which means an empty list.
//l1=[9,9]
l2=[1]
The sum could have an extra carry of one at the end, which is easy to forget.
'''
carry = 0
root = n = ListNode(0) # means first root = ListNode(0) then n point to the same address, which means point to root
while l1 or l2 or carry:
v1, v2 = 0, 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, node_val = divmod(v1 + v2 + carry, 10)
n.next = ListNode(node_val)
n = n.next
# ****** Without using v1 and v2 ******
# while l1 or l2 or carry:
# if l1:
# carry += l1.val
# l1 = l1.next
# if l2:
# carry += l2.val
# l2 = l2.next
# carry, val = divmod(carry, 10)
# n.next = n = ListNode(val)
return root.next
l1 = LinkedList([2, 4, 3])
l2 = LinkedList([5, 6, 4])
solution = Solution()
result = solution.addTwoNumbers(nums, target)
print result
'''
Complexity Analysis
Time complexity : O(max(m,n)).
Assume that m and n represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m,n) times.
Space complexity : O(max(m,n)).
The length of the new list is at most max(m,n)+1.
''' |
98c8b2df121d693f02d9de3f82f93e643e143553 | aktech/pydsa | /pydsa/insertion_sort.py | 416 | 4.0625 | 4 | def insertion_sort(a):
"""
Sorts the list 'a' using insertion sort algorithm
>>> from pydsa import insertion_sort
>>> a = [3, 4, 2, 1, 12, 9]
>>> insertion_sort(a)
[1, 2, 3, 4, 9, 12]
"""
for i in range(1, len(a)):
element = a[i]
j = i
while j > 0 and a[j - 1] > element:
a[j] = a[j - 1]
j = j - 1
a[j] = element
return a
|
ad079284a2450708838d462bedc41c35fcabecd2 | rigratz/rigratz-linkedin | /Portfolio/Blackjack/main/Players.py | 1,224 | 3.53125 | 4 | class Player(object):
def __init__(self):
self.hand = []
def getTotal(self):
sum = 0
aces = 0
for c in self.hand:
if c.getName() == "Ace":
aces += 1
sum += 11
elif c.getName() == "Jack" or c.getName() == "Queen" or c.getName() == "King":
sum += 10
else:
val = c.getValue()
sum += val
while aces > 0:
aces -= 1
if sum > 21:
sum -= 10
else:
break
return sum
def addToHand(self, card):
self.hand.append(card)
def showHand(self, type):
if type == "DealerH":
print ("Dealer Cards: ", self.hand[0].getName(), "of", self.hand[0].getSuit())
elif type == "Player" or "Dealer":
print (type, "Cards: ",)
for c in self.hand:
print (c.getName(), "of", c.getSuit(),)
print ()
print ("Total: ", self.getTotal())
def dealerHand(self, deck):
if self.getTotal() < 17:
self.addToHand(deck.cards.pop())
return True
else:
return False
|
d256e3af8b9eab3c140e876fb01ac2a998fee656 | eprj453/algorithm | /프로그래머스(자료구조, 코딩테스트)/LinkedList/LinkedList1.py | 5,192 | 4.09375 | 4 | # Node
# - data (어떤 데이터를 가지고 있는가)
# - link (다음 데이터와 이어지는 link가 무엇인가)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.nodeCount = 0
self.tail = None
# Dummy node 전
# self.head = None
# Dummy node 후
self.head = Node(None)
self.head.next = self.tail
def getValue(self, value):
nc = self.nodeCount
print('nc :', nc)
i = 0
curr = self.head
while i <= nc:
if curr.data == value:
return i
else:
curr = curr.next
i += 1
def getInputIdx(self, value):
nc = self.nodeCount
i = 0
curr = self.head
while i <= nc:
if curr.data and curr.data > value:
return i
else:
curr = curr.next
i += 1
return i
def getAt(self, pos):
# Dummy node 전
# if pos < 1 and pos > self.nodeCount:
# return None
# i = 1
# curr = self.head
# while i < pos:
# curr = curr.next
# i += 1
# return curr
# Dummy node 후
if pos < 0 or pos > self.nodeCount:
return None
i = 0
curr = self.head
while i < pos:
curr = curr.next
i += 1
return curr
def traverse(self):
answer = []
curr = self.head
# while curr != None:
# Dummy node 전
# while curr != None:
# answer.append(curr.data)
# curr = curr.next
# Dummy node 후
while curr and curr.next:
curr = curr.next
answer.append(curr.data)
# curr = curr.next
return answer
def insertAt(self, pos, newNode):
# Dummy node 삽입 전
# if pos <= 0 or pos > self.nodeCount+1:
# return False
# if pos == 1: # 맨 처음 노드에 삽입하려고 할때
# newNode.next = self.head #
# self.head = newNode
#
# else:
# if pos == self.nodeCount+1:
# prev = self.tail
# else:
# prev = self.getAt(pos-1) # 현재 삽입하고자 하는 원소의 앞 원소
# newNode.next = prev.next # 새로운 원소의 다음 원소를 앞 원소의 다음 원소로 끼워넣기
# prev.next = newNode # 기존 앞 원소의 다음 원소는 새로운 원소로
#
# if pos == self.nodeCount+1:
# self.tail = newNode
# self.nodeCount += 1
# return True
# Dummy node 삽입 후
if pos < 1 or pos > self.nodeCount+1:
return False
if pos != 1 and pos == self.nodeCount+1: # 맨 마지막 노드를 골랐을때
prev = self.tail
else:
prev = self.getAt(pos-1)
return self.insertAfter(prev, newNode)
def insertAfter(self, prev, newNode):
newNode.next = prev.next
if prev.next == None:
self.tail = newNode
prev.next = newNode
self.nodeCount += 1
return True
def popAt(self, pos):
# popNode = self.getAt(pos)
if pos < 1 or pos > self.nodeCount: # 0 미만 원소 길이 이상
raise IndexError
return False
if self.nodeCount == 1: # node 길이가 1일때
popNode = self.head
self.head = None
self.tail = None
else:
if pos == 1: # 맨 앞 node의 삭제
popNode = self.head
self.head = self.head.next
elif pos == self.nodeCount: # 맨 끝 node의 삭제
popNode = self.tail
prev = self.getAt(pos-1)
prev.next = None
self.tail = prev
else: # 그렇지 않은 경우
popNode = self.getAt(pos)
prev = self.getAt(pos-1)
# popAfterNode = self.getAt(pos+1)
prev.next = popNode.next
self.nodeCount -= 1
return popNode.data
def concat(self, L): # 연결 리스트 합치는 연산
self.tail.next = L.head
if L.tail:
self.tail = L.tail
self.nodeCount += L.nodeCount
return True
def solution(n, k, cmd):
L = LinkedList()
for i in range(n):
node = Node(i)
L.insertAt(i, node)
print(L.traverse())
# solution(8, 2, ["D 2","C","U 3","C","D 4","C","U 2","Z","Z"])
L = LinkedList()
a = Node(12)
b = Node(30)
c = Node(47)
d = Node(68)
L.insertAt(1, a)
L.insertAt(2, b)
L.insertAt(3, c)
L.insertAt(4, d)
L.popAt(3)
print(L.traverse())
# L.popAt(1)
# print(L.getValue(12))
idx = L.getInputIdx(50)
L.insertAt(idx, Node(50))
print(L.traverse())
# print(L.traverse())
|
df2628336a415e07b38f1b1bed611f2484128ba3 | srishtishukla-20/function | /Q3(String reverse).py | 357 | 4.0625 | 4 | def string_reverse(n):
str1=''
index=len(n)
while index>0:
str1+=n[index-1]
index-=1
return str1
print(string_reverse('abncgu123'))
#reverse
def var():
print("welcome")
if len(a)>len(b):
print(a)
elif len(a)==len(b):
print(a)
else:
print(b)
a=input("en")
b=input("en")
var()
#print string which has greater length
|
d4d7440b7fb85dc1b09458a75f8c78da2aee6b93 | HYnam/MyPyTutor | /W6_dict_iterate.py | 989 | 4.875 | 5 | """
Iterating Over a Dictionary
A dictionary is an iterable object and so a for loop can be used to iterate over the entries in a dictionary. The loop
for k in dict:
body_code
will iterate over the keys of the dictionary dict setting k in turn to each key of dict.
Consider a dictionary that has strings as keys and integers as values -
e.g.
{'a':24, 'e':30, 't':12, 'n':10}
Write a function big_keys that takes such a dictionary as the first argument and an integer as the second argument and returns the list of keys all of whose values are bigger than the second argument.
You must use a for loop to iterate over the dictionary.
Example:
>>> big_keys({'a':24, 'e':30, 't':12, 'n':10}, 15)
['a', 'e']
"""
def big_keys(dictionary, y: int):
big_keys_list = []
for k, v in dictionary.items(): #iterating the dict items
if v > y: # checking the condition
big_keys_list.append(k) #append to list if meets the rule
return big_keys_list |
1c4a8547faa4121529cea99b6972f16a448ff855 | lapnd/fuzzingbook | /code/core/convertOperatorsEBNF.py | 2,256 | 3.5 | 4 | import re
from .grammarUtils import *
# # function to __convert_ebnf_parentheses
def __convert_ebnf_parentheses(ebnf_grammar):
"""Convert a grammar in extended BNF to BNF"""
grammar = extend_grammar(ebnf_grammar)
for nonterminal in ebnf_grammar:
expansions = ebnf_grammar[nonterminal]
for i in range(len(expansions)):
expansion = expansions[i]
while True:
parenthesized_exprs = parenthesized_expressions(expansion)
if len(parenthesized_exprs) == 0:
break
for expr in parenthesized_exprs:
operator = expr[-1:]
contents = expr[1:-2]
new_sym = new_symbol(grammar)
expansion = grammar[nonterminal][i].replace(
expr, new_sym + operator, 1)
grammar[nonterminal][i] = expansion
grammar[new_sym] = [contents]
return grammar
# # function to __convert_ebnf_operators
def __convert_ebnf_operators(ebnf_grammar):
"""Convert a grammar in extended BNF to BNF"""
grammar = extend_grammar(ebnf_grammar)
for nonterminal in ebnf_grammar:
expansions = ebnf_grammar[nonterminal]
for i in range(len(expansions)):
expansion = expansions[i]
extended_symbols = extended_nonterminals(expansion)
for extended_symbol in extended_symbols:
operator = extended_symbol[-1:]
original_symbol = extended_symbol[:-1]
new_sym = new_symbol(grammar, original_symbol)
grammar[nonterminal][i] = grammar[nonterminal][i].replace(
extended_symbol, new_sym, 1)
if operator == '?':
grammar[new_sym] = ["", original_symbol]
elif operator == '*':
grammar[new_sym] = ["", original_symbol + new_sym]
elif operator == '+':
grammar[new_sym] = [
original_symbol, original_symbol + new_sym]
return grammar
# # All together
def convert_ebnf_grammar(ebnf_grammar):
return __convert_ebnf_operators(__convert_ebnf_parentheses(ebnf_grammar))
|
7075c6827792d06a58220de0a2b1e42a562041ee | kabilasudhannc/Python-Turtle-Programs | /HexagonSpiral.py | 213 | 3.5 | 4 | from turtle import *
colors = ['red', 'purple', 'blue', 'green', 'yellow', 'white']
speed(0)
bgcolor('black')
for x in range(200):
pencolor(colors[x % 6])
width(2)
forward(x*1.2)
left(59)
|
7d95d2a7fa5849841f65b29e6caf193a0d0b011b | MariaLuiza17/PEOO_Python | /Lista_06/Luis M_Guilherme Melo/Questao_03.py | 1,468 | 4.28125 | 4 | """
3. Crie um diagrama de classes que represente uma classe Pessoa com os atributos privados identificador, nome e CPF, e uma classe Endereço com os atributos número da casa, rua, cidade, estado e pais. Nesse caso uma pessoa deve “agregar” um ou vários endereços. Implemente métodos para representar esse relacionamento.
• Cardinalidades:
o Uma Pessoa agrega um ou vários endereços (1 para muitos).
"""
class Pessoa:
def __init__(self, rg, nome, cpf):
self.__rg = rg
self.__nome = nome
self.__cpf = cpf
self.lista = []
@property
def rg(self):
return self.__rg
@property
def nome(self):
return self.__nome
@property
def cpf(self):
return self.__cpf
def inserir_endereco(self, endereco):
self.lista.append(endereco)
def listar_enderecos(self):
for endereco in self.lista:
print(endereco.numero, endereco.rua, endereco.cidade, endereco.estado, endereco.pais)
class Endereco:
def __init__(self, numero, rua, cidade, estado, pais):
self.numero = numero
self.rua = rua
self.cidade = cidade
self.estado = estado
self.pais = pais
gente = Pessoa(69420, "luis", 704)
print(gente.nome, gente.rg, gente.cpf)
p1= Endereco(294, "cap jose", "cm", "RN", "Brazil")
p2= Endereco(294, "cap jose", "cm", "PB", "Brazil")
p3= Endereco(294, "cap jose", "cm", "SP", "Brazil")
gente.inserir_endereco(p1)
gente.inserir_endereco(p2)
gente.inserir_endereco(p3)
gente.listar_enderecos()
|
8f9549e7d2b40ea8a746f9c7c02f7a3cbc854fa0 | XyliaYang/Leetcode_Record | /python_version/L23.py | 1,907 | 3.609375 | 4 | # @Time : 2020/3/30 19:48
# @Author : Xylia_Yang
# @Description :
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution_1:
def mergeKLists(self, lists):
if not lists:
return
node=None
min_node=None
min_index=-1
for i in range(len(lists)):
if not lists[i]:
continue
if not min_node:
min_node=lists[i]
min_index=i
else:
if lists[i].val<min_node.val:
min_node=lists[i]
min_index=i
if min_node:
node = min_node
lists[min_index] = lists[min_index].next
node.next = self.mergeKLists(lists)
return node
class Solution_2:
def mergeKLists(self, lists):
if not lists:
return
amount=len(lists)
interval=1
while interval<amount:
for i in range(0,amount-interval,interval*2):
lists[i]=self.mergeSort(lists[i],lists[i+interval])
interval*=2
return lists[0]
def mergeSort(self,list1,list2):
if not list1 and not list2:
return None
if not list1:
return list2
if not list2:
return list1
if list1.val<list2.val:
node=list1
node.next=self.mergeSort(list1.next,list2)
else:
node=list2
node.next=self.mergeSort(list1,list2.next)
return node
if __name__=='__main__':
solution=Solution_2()
node1=ListNode(1)
node1.next=ListNode(4)
node1.next.next=ListNode(5)
node2=ListNode(1)
node2.next=ListNode(3)
node2.next.next=ListNode(4)
node3=ListNode(2)
node3.next=ListNode(6)
lists=[node1,node2,node3]
print(solution.mergeKLists(lists)) |
84f254d48a3c4ae59040b9a7cf57b75d9700fb77 | prem4589/competetive_programming | /week-1/Day_1/threeproduct.py | 1,911 | 3.640625 | 4 | import unittest
def pro3(array):
highest_number = max(array[0], array[1])
lowest_number = min(array[0], array[1])
pro2 = array[0]* array[1]
lpro2 = array[0]* array[1]
pro3 = array[0]* array[1] * array[2]
for i in xrange(2, len(list_of_ints)):
current = list_of_ints[i]
pro3 = max(pro3,
current * pro2,
current * lpro2)
pro2 = max(pro2,
current * highest,
current * lowest)
lpro2 = min(lpro2,
current * highest,
current * lowest)
highest = max(highest, current)
lowest = min(lowest, current
return pro3
# Tests
class Test(unittest.TestCase):
def test_short_list(self):
actual = pro3([1, 2, 3, 4])
expected = 24
self.assertEqual(actual, expected)
def test_longer_list(self):
actual = pro3([6, 1, 3, 5, 7, 8, 2])
expected = 336
self.assertEqual(actual, expected)
def test_list_has_one_negative(self):
actual = pro3([-5, 4, 8, 2, 3])
expected = 96
self.assertEqual(actual, expected)
def test_list_has_two_negatives(self):
actual = pro3([-10, 1, 3, 2, -10])
expected = 300
self.assertEqual(actual, expected)
def test_list_is_all_negatives(self):
actual = pro3([-5, -1, -3, -2])
expected = -6
self.assertEqual(actual, expected)
def test_error_with_empty_list(self):
with self.assertRaises(Exception):
pro3([])
def test_error_with_one_number(self):
with self.assertRaises(Exception):
pro3([1])
def test_error_with_two_numbers(self):
with self.assertRaises(Exception):
pro3([1, 1])
unittest.main(verbosity=2)
|
fe44723e18928ed08a4c5c22d80e6d630e8d4c16 | apdaza/bookprogramming | /ejercicios/python/ejercicio073.py | 360 | 3.90625 | 4 | def contador_recursivo(numero):
if (numero == 0):
return 0
else:
return 1 + contador_recursivo(int(numero/10))
if __name__ == "__main__":
numero = int(input("ingrese el numero : "))
if (numero >= 0):
print(str(numero)+" tiene "+str(contador_recursivo(numero))+" digitos")
else:
print("Error el numero debe ser positivo") |
f8a3a84e08ccdba5e50dce2a5767c3ee5decd2ea | sarahvbogaert/blackjack | /black_jack.py | 1,954 | 3.6875 | 4 | from card_game import Deck
from player import Player, Dealer
class BlackJack:
def __init__(self, name, balance, bet):
"""
:param: name: name of player
:param: balance: initial balance of player
:param: bet: bet per play
"""
self.player = Player(name, balance)
self.dealer = Dealer()
self.deck = Deck()
self.bet = bet
def game(self):
"""
Several rounds of player and dealer playing one after another
"""
self.deck.shuffle()
while True:
enough_balance = self.player.pay(self.bet) # check if balance high enough
if not enough_balance:
break
sum_player, burst_player = self.player.play(self.deck)
if burst_player:
print(f"Player {self.player.name} Looses!")
else:
sum_dealer, burst_dealer = self.dealer.play(self.deck)
if sum_player > sum_dealer or burst_dealer:
print(f"Player {self.player.name} Wins!")
self.player.win(2*self.bet)
elif sum_player == sum_dealer:
print(f"Nobody Wins!")
self.player.win(self.bet)
else:
print(f"Player {self.player.name} Looses!")
print(self.player)
if not self.game_on(): # asks user if he wants to continue playing
break
@staticmethod
def game_on():
"""
Asks user if he wants to continue playing
:return: True or False
"""
while True:
cont = input(f"Do you want to continue playing? (Y or N): ")
if cont not in ['Y', 'N']:
print("Wrong input. Please try again.")
continue
break
return cont == "Y"
if __name__ == "__main__":
bj = BlackJack('Sarah', 100, 20)
bj.game()
|
14361bd8ab8b360068fa0a3e6d4539687d1697af | teperwoman/DevOps0909 | /class_1/homework/answer_class_1.py | 933 | 4.03125 | 4 | # ANSWER A.
# 1. Create a variable name first with value 7.
# 2. Create a variable name second with value 44.3.
# 3. Print result of adding first to second.
# 4. Print result of multiplying first by second
# 5. Print result of dividing second by first
first = 7
seconde = 44.3
print(first + seconde)
print(first * seconde)
print(seconde / first)
# ANSWER B
# What will be the values of a, b, c at the end?
a = 8
a = 17
a = 9
b = 6
c = a+b
b = c+a
b = 8
print(a)
print(b)
print(c)
# a = 9
# b = 8
# c = 15
# ANSWER C.
#Is there a difference between the two lines below? Why?
# no difference
# What is the issue with the code below?
#error
#Suggest an edit.
my_number = 5+5
print("result is: " + str(my_number))
# ANSWER D.
# What will be the output?
x = 5
y = 2.36
print(x+int(y))
# 7
#ANSWER CHALLENGE:
# Fix the following code, without changing a or b
a = 8
b = "123"
print(str(a) + b)
#or
print(a + int(b)) |
ea75c3eebf1c72e9ce4d7cb67c09469e63ab076f | geekzeek/Artificial_Intelligence | /Assignment 2 - Pentago Vs AI/AI.py | 8,059 | 3.578125 | 4 | """
# File: AI.py
# Author: Zeeshan Karim
# Date: 5/15/2017
# Course: TCSS 435 - Artificial Intelligence
# Purpose: Implementation of Search Tree, and Minimax / Alpha-Beta Algorithms
"""
import random
from copy import deepcopy
import pentago
# Depth limit of search tree
maxDepth = 3
# Search method to use, 'AlphaBeta' or 'MiniMax'
searchMethod = 'AlphaBeta'
# Game node class used to create tree
class gameNode:
state = None
lastMove = None
depth = 0
value = 0
children = []
# Populates list of children from current game state
def getChildren(self, color):
# Get list of possible moves
moves = self.state.possibleMoves()
# Create a child for each move and add it to the list
for move in moves:
child = gameNode()
child.state = pentago.game()
child.state.board = deepcopy(self.state.board)
child.state.placeItem(color, move)
child.state.rotateBlock(move)
child.lastMove = move
child.depth = self.depth + 1
child.children = []
# Check if the new board state already exists
exists = False
for existing in self.children:
if child.state == existing.state:
exists = True
break
# Add the new state if it does not exist yet
if not exists:
self.children.append(child)
# AI player class containing MiniMax and AlphaBeta search algorithms
class player:
gameTree = None
currentNode = None
maxcolor = ''
mincolor = ''
depthLimit = -1
# Testing Variables
nExpanded = 0
# Get a random valid move for testing
def getTestMove(self, current):
valid = False
while not valid:
move = ''
move += str(random.randint(1, 4))
move += '/'
move += str(random.randint(1, 9))
move += ' '
move += str(random.randint(1, 4))
move += ['r', 'l'][random.randint(0,1)]
valid = current.validMove(move)
return move
# Get an intelligent move using game tree search
def getMove(self, current):
# Create the tree or update current node if it already exists
if self.gameTree == None:
self.gameTree = gameNode()
self.gameTree.state = current
self.gameTree.depth = 0
self.gameTree.lastMove = ''
self.currentNode = self.gameTree
else:
for child in self.currentNode.children:
if child.state == current:
self.currentNode = child
break
# Update depth limit for this search
self.depthLimit = self.currentNode.depth + maxDepth
# Find optimal state
if searchMethod == 'AlphaBeta':
nextNode = self.alphaBetaSearch(self.currentNode)
else:
nextNode = self.miniMaxSearch(self.currentNode)
# Display and reset nExpanded for testing
# print self.nExpanded
self.nExpanded = 0
# Update current node to the optimal state
self.currentNode = nextNode
# Return the move used to get to optimal state
return nextNode.lastMove
def alphaBetaSearch(self, node):
#If there are no children yet, get them
if(len(node.children) == 0):
node.getChildren(self.maxcolor)
self.nExpanded += 1
# Start a new AlphaBeta search from the current state
beta = float('inf')
alpha = -float('inf')
bestChild = node.children[0]
# Find the maximum value child
for child in node.children:
# Determine value by minimizing next depth level
child.value = self.AB_minimize(child, alpha, beta)
if child.value > alpha:
alpha = child.value
bestChild = child
return bestChild
def AB_maximize(self, node, alpha, beta):
# If we haven't hit depth limit and children don't exist yet, get them
if node.depth < self.depthLimit:
if len(node.children) == 0:
node.getChildren(self.maxcolor)
self.nExpanded += 1
# If node is terminal, return its utility
if len(node.children) == 0:
return node.state.getUtility(self.maxcolor, self.mincolor)
# Find the maximum value child
value = -float('inf')
for child in node.children:
# Determine value by minimizing next depth level
child.value = self.AB_minimize(child, alpha, beta)
value = max(value, child.value)
if value >= beta:
# Prune nodes and return current value
return value
alpha = max(alpha, value)
return value
def AB_minimize(self, node, alpha, beta):
# If we haven't hit depth limit and children don't exist yet, get them
if node.depth < self.depthLimit:
if len(node.children) == 0:
node.getChildren(self.mincolor)
self.nExpanded += 1
# If node is terminal, return its utility
if len(node.children) == 0:
return node.state.getUtility(self.maxcolor, self.mincolor)
# Find the minimum value child
value = float('inf')
for child in node.children:
# Determine value by maximizing next depth level
child.value = self.AB_maximize(child, alpha, beta)
value = min(value, child.value)
if value <= alpha:
# Prune nodes and return current value
return value
beta = min(beta, value)
return value
def miniMaxSearch(self, node):
# If there are no children yet, get them
if(len(node.children) == 0):
node.getChildren(self.maxcolor)
self.nExpanded += 1
# Start a new MiniMax search from the current state
bestValue = self.MM_maximize(node)
bestChild = node.children[0]
# Find the child with optimal value and return it
for child in node.children:
if child.value == bestValue:
bestChild = child
break
return bestChild
def MM_maximize(self, node):
# If we haven't hit depth limit and children don't exist yet, get them
if node.depth < self.depthLimit:
if len(node.children) == 0:
node.getChildren(self.maxcolor)
self.nExpanded += 1
# If node is terminal, return its utility
if len(node.children) == 0:
return node.state.getUtility(self.maxcolor, self.mincolor)
# Find the maximum value child
maxValue = -float('inf')
for child in node.children:
# Determine value by minimizing next depth level
child.value = self.MM_minimize(child)
maxValue = max(maxValue, child.value)
return maxValue
def MM_minimize(self, node):
# If we haven't hit depth limit and children don't exist yet, get them
if node.depth < self.depthLimit:
if len(node.children) == 0:
node.getChildren(self.mincolor)
self.nExpanded += 1
# If node is terminal, return its utility
if len(node.children) == 0:
return node.state.getUtility(self.maxcolor, self.mincolor)
# Find the minimum value child
minValue = float('inf')
for child in node.children:
# Determine value by maximizing next depth level
child.value = self.MM_maximize(child)
minValue = min(minValue, child.value)
return minValue
|
d980c79d96e944d9a091f8b94fbc1a4e1132b38e | Python-lab-cycle/Akhila-P-M | /CO4_03_RectangleAreaOperatorOverloading.py | 668 | 3.96875 | 4 |
class area:
def __init__(self, m1, m2): #initialization
self.l = m1
self.b = m2
def __gt__(self, other): #comparing the two objects
r1 = self.l * self.b
r2 = other.l * other.b
if(r1 > r2):
return True
else:
return False
a=int(input("Enter length of first triangle:"))
b=int(input("Enter breadth of first triangle:"))
c=int(input("Enter length of second triangle:"))
d=int(input("Enter breadth of second triangle:"))
s1 = area(a,b)
s2 = area(c,d)
if (s1 > s2):
print ("area of rect1 is greatr")
else:
print ("area of rect2 is greater")
|
7e19fe8b29163701bb2b74ed2f9b9e586932df79 | samuelpordeus/algorithms-lib | /dynamic/box_stacking.py | 2,517 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from collections import namedtuple
from itertools import permutations
dimension = namedtuple("Dimension", "height length width")
# Gera dimensões usando como base permutações das
# dimensões com comprimento maior que altura
def rotations(dimensions):
rotations = []
for dim in dimensions:
# Permuta
for (height, length, width) in permutations((dim.height, dim.length, dim.width)):
if length >= width:
rotations.append(dimension(height, length, width))
return rotations
def box_stack(dimensions):
# Ordena as caixas com base nas dimensões
boxes = sorted(
rotations(dimensions),
key=lambda dim: dim.length * dim.width,
reverse=True)
T = [rotation.height for rotation in boxes]
R = [i for i in range(len(boxes))]
for i in range(1, len(boxes)):
for j in range(0, i):
if (boxes[i].length < boxes[j].length
and boxes[i].width < boxes[j].width):
height = T[j] + boxes[i].height
if height > T[i]:
T[i] = height
R[i] = j
return max(T)
class TestBoxStack(unittest.TestCase):
def test_1(self):
self.assertEqual(box_stack([
dimension(5, 3, 5),
dimension(8, 2, 6),
dimension(7, 6, 8),
dimension(5, 8, 4),
dimension(5, 7, 5),
]), 22)
def test_2(self):
self.assertEqual(box_stack([
dimension(5, 5, 1),
dimension(8, 8, 2),
dimension(7, 4, 8),
dimension(1, 8, 3),
dimension(8, 2, 10),
]), 22)
def test_3(self):
self.assertEqual(box_stack([
dimension(2, 1, 4),
dimension(7, 2, 7),
dimension(5, 2, 8),
dimension(3, 6, 3),
dimension(3, 3, 3),
]), 17)
def test_4(self):
self.assertEqual(box_stack([
dimension(9, 3, 3),
dimension(8, 8, 6),
dimension(5, 7, 1),
dimension(9, 9, 9),
dimension(2, 7, 1),
]), 34)
def test_5(self):
self.assertEqual(box_stack([
dimension(1, 1, 1),
dimension(8, 2, 1),
dimension(6, 4, 2),
dimension(5, 5, 5),
dimension(3, 1, 5),
]), 19)
# Executa a suite de teste
if __name__ == '__main__':
unittest.main()
|
6ef3c777cdc45ef7beb62085fcc9ac596228a3e1 | stuart727/edx | /edx600x/L04_Functions/l4_p8_fourth_power.py | 223 | 3.578125 | 4 | '''
Created on Feb 21, 2013
@author: ira
'''
def square(x):
'''
x: int or float.
'''
return x*x
def fourthPower(x):
'''
x: int or float.
'''
return square(x)*square(x)
print fourthPower(5) |
08d4a0efc9bbcb3d0043f8a6385d985d77daaf5f | Faraaz54/python_training_problems | /hacker_earth/python_problems/factorial.py | 174 | 3.703125 | 4 | inp = raw_input()
fact = 1
for i in range(1, int(inp)+1):
fact = fact * i
print fact
'''a = int(raw_input())
b=1
for i in range(1,a+1):
b = b*i
print b''' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.