blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ca2127b47e71189b3f7a90cfe31a881fb0a78065 | bobeezy/python_tutorials | /verify_leap_year.py | 761 | 4.25 | 4 | # Prompt user to enter starting year
start_year = int(input("What year do you want to start with? "))
# Prompt user to enter the number of years to be checked
number_of_years = int(input("How many years do you want to check? "))
end_year = start_year + number_of_years
# For leap years, year must be evenly divisible by 4. Not a leap year if evenly divisible by 100 unless also by 400
for i in range(start_year, end_year):
if i % 4 == 0:
if i % 100 == 0:
if i % 400 == 0:
print('Year: ' + str(i) + ' is a leap year')
else:
print('Year: ' + str(i) + ' is not a leap year')
else:
print('Year: ' + str(i) + ' is a leap year')
else:
print('Year: ' + str(i) + ' is not a leap year') |
649bcb64593ad97eef3bf0d94e5089e355518829 | pyreiz/pyliesl | /liesl/show/textplot.py | 5,669 | 3.640625 | 4 | """
Visualize data in the terminal
------------------------------
"""
from time import sleep
import os
from typing import List
from liesl.api import open_streaminfo, RingBuffer
from math import floor
from array import array
def cla():
"clear the terminal"
os.system("cls" if os.name == "nt" else "clear")
def linspace(a: int, b: int, n: int = 80) -> List[float]:
"return a list of n evenly spaced values spanning from a to b"
if n < 2:
return b
diff = (float(b) - a) / (n - 1)
return [int(diff * i + a) for i in range(n)]
def plot(y: List[float], x: List[float] = None, width: int = 79, height: int = 18):
"""
Print a crude ASCII art plot
"""
y_raw = y.copy()
width -= 6 # because of left margin
if x is None:
x_raw = [x for x in range(len(y))]
else:
x_raw = x.copy()
if len(x_raw) != len(y_raw):
raise ValueError("Unequal len of x and y")
ma = max(y_raw)
mi = min(y_raw)
a = min(x_raw)
b = max(x_raw)
# Normalize height to screen space
x = linspace(0, len(x_raw) - 1, width)
if ma == mi:
if ma:
mi, ma = sorted([0, 2 * ma])
else:
mi, ma = -1, 1
y = []
for ix in x:
new_y = int(float(height) * (y_raw[ix] - mi) / (ma - mi))
y.append(new_y)
for h in range(height - 1, -1, -1):
s = [" "] * width
for x in range(width):
if y[x] == h:
if (x == 0 or y[x - 1] == h - 1) and (
x == width - 1 or y[x + 1] == h + 1
):
s[x] = "/"
elif (x == 0 or y[x - 1] == h + 1) and (
x == width - 1 or y[x + 1] == h - 1
):
s[x] = "\\"
else:
s[x] = "."
# Print y values
if h == height - 1:
prefix = "{0:4.1f}".format(ma)
elif h == height // 2:
prefix = "{0:4.1f}".format((mi + ma) / 2)
elif h == 0:
prefix = "{0:4.1f}".format(mi)
else:
prefix = " " * 4
s = "".join(s)
if h == height // 2:
s = s.replace(" ", "-")
print(prefix + " | " + s)
# Print x values
bottom = " "
bottom += "{0:<10.0f}".format(a[0])
bottom += "{0:^58.1f}".format(((a + b) / 2)[0])
bottom += "{0:>10.0f}".format(b[0])
print(bottom)
def zoom_plot(y: List[float], x: List[float] = None, width: int = 80, height: int = 10):
"""Print a crude ASCII art plot"""
y_raw = y.copy()
if x is None:
x_raw = [x for x in range(len(y))]
else:
x_raw = x.copy()
if len(x_raw) != len(y_raw):
raise ValueError("Unequal len of x and y")
# smoothen and downsample because we have only <width> char available and
# too many samples cause aliasing and outlier issues
if len(y_raw) > width * 100:
step = len(y_raw) // 79
smooth_y = []
smooth_x = []
for ixa, ixb in zip(
range(0, len(y_raw) - step, step), range(step, len(y_raw), step)
):
smooth_y.append(sum(y_raw[ixa:ixb]) / step)
smooth_x.append(x[ixa])
smooth_x[-1] = max(x_raw)
smooth_x[0] = min(x_raw)
y_raw = smooth_y
x_raw = smooth_x
ma = max(y_raw)
mi = min(y_raw)
a = min(x_raw)
b = max(x_raw)
# Normalize height to screen space
x = linspace(0, len(x_raw) - 1, width)
if ma == mi:
if ma:
mi, ma = sorted([0, 2 * ma])
else:
mi, ma = -1, 1
y = []
for ix in x:
new_y = (y_raw[ix] - mi) / (ma - mi)
new_y = floor(new_y * (height - 1))
y.append(new_y)
canvas = []
for lix in range(height):
line = array("u", " " * width)
canvas.append(line)
def put(canvas, xpos, ypos, symbol):
canvas[len(canvas) - ypos - 1][xpos] = symbol
for xix, (pre, val, post) in enumerate(zip([y[0]] + y, y, y[1:] + [y[-1]])):
# canvas[val][xix] = '─'
if val < post:
for l in range(val, post):
put(canvas, xix, l, "│")
put(canvas, xix, post, "╭")
put(canvas, xix, val, "╯")
if val > post:
for l in range(post, val):
put(canvas, xix, l, "│")
put(canvas, xix, post, "╰")
put(canvas, xix, val, "╮")
if val == post:
put(canvas, xix, val, "─")
for line in canvas:
print(line.tounicode())
bottom = ""
bottom += "{:<{width}g}".format(a, width=(width // 2) - 3)
bottom += "{:^5g}".format((a + b) / 2) # .ljust(width//2)
bottom += "{:>{width}g}".format(b, width=(width // 2) - 2)
print(bottom)
def show(**kwargs):
if "channel" in kwargs:
channel = kwargs.get("channel")
del kwargs["channel"]
else:
channel = 0
if "frate" in kwargs:
frate = kwargs.get("frate")
del kwargs["frate"]
else:
frate = 20
fsleep = 1 / frate
sinfo = open_streaminfo(**kwargs)
if sinfo is None:
print("No streams found")
exit()
duration = 80 * 1000 / sinfo.nominal_srate()
buffer = RingBuffer(sinfo, duration_in_ms=duration)
buffer.start()
buffer.await_running()
try:
while buffer.is_running:
sleep(fsleep)
cla()
chunk, tstamps = buffer.get()
plot(chunk[:, channel], tstamps, width=79)
sleep(fsleep)
except KeyboardInterrupt:
pass
finally:
buffer.stop()
exit(0)
|
179038f8961f2c181557345614c30707743601a9 | korchalovsky/python-learn | /str_Aa.py | 210 | 3.625 | 4 | S1 = "HeLlO WoRdD! 123"
S2 = ""
for i in S1:
if ord('Z') >= ord(i):
if ord(i) <= ord('A'):
S2 += i
else:
S2 += chr(ord(i) + 32)
else:
S2 += i
print(S2)
|
170180b87700aa89214f8ef06ca50c1fe7c66f15 | roni-kemp/python_programming_curricula | /CS2/9900_diepio/to_share_with_students/enemy.py | 3,985 | 3.546875 | 4 | import pygame, ship
from constants import *
class EnemyCritter(ship.Ship):
def __init__(self, screen, x, y, color, radius, name):
super().__init__(screen, x, y, color, radius, name)
#Override super class's update function
def update(self, sprites_in_range):
super().update()
#Avoid an error
if len(sprites_in_range)==0:
return
'''You can only use one of the next 7 movement
functions per turn.
Moves you toward the given target sprite.
self.moveToward(target)
Moves you toward the given x,y coordinates.
self.moveTowardLocation(x,y)
Moves you away from the given target sprite.
self.fleeFrom(target)
Moves you away from the given x,y coordinates
self.fleeFromLocation(x,y)
Moves you in the given direction. direction must
be in degrees between 0 and 360.
self.moveTowardDirection(direction)
Orbit counterclockwise around the given target
at the given distance.
self.orbitCounterclockwise(target,distance)
Orbit clockwise around the given target at the
given distance.
self.orbitClockwise(target,distance)
Fires in the direction you are currently facing if
shooting is off cooldown.
self.shoot()
Fires at the given x,y coordinates if shooting is
off cooldown.
self.shootAt(x,y)
Fires at the given sprite if shooting is
off cooldown.
self.shootAt(target)
Returns the closest sprite in range that shares
a type with a type in type_list. If none found,
returns None.
self.getClosestSprite(sprites_in_range, type_list)
For example to get the nearest food or player you
could use
type_list = [TYPE_CRITTER,TYPE_FOOD]
closest = self.getClosestSprite(sprites_in_range, type_list)
#Returns the closest player or None
p = self.getClosestPlayer(sprites_in_range)
#Returns the closest bullet that is not your own or None
b = self.getClosestBullet(sprites_in_range)
#Returns the closest food or None
f = self.getClosestFood(sprites_in_range)
#Returns the closest powerup or None
p = self.getClosestPowerup(sprites_in_range)
Returns a list of all the sprites in range that share
a type with a type in type_list. If none found,
returns an empty list.
self.getAllSpritesInRange(sprites_in_range, type_list)
For example to get all the nearest food and powerups
you could use
type_list = [TYPE_POWERUP,TYPE_FOOD]
food_and_ups = self.getAllSpritesInRange(sprites_in_range, type_list)
Returns a list of all the players in range, not
including yourself.
players = self.getPlayersInRange(sprites_in_range)
Returns a list of all the bullets in range, not
including your own.
bullets = self.getBulletsInRange(sprites_in_range)
Returns a list of all the food in range.
foods = self.getFoodsInRange(sprites_in_range)
Returns a list of all the powerups in range.
ups = self.getPowerupsInRange(sprites_in_range)
Get the distance in pixels to the given sprite named
closest.
distance = self.distanceTo(closest)
Returns True if this ship is currently under some
effect such as a powerup.
self.hasEffect()
Returns True if this ship is currently invincible.
self.isInvincible()
Sets your angle to face the given sprite. This will
happen automatically if you shoot at the sprite.
self.faceTarget(target)
Sets your angle to face away from the given sprite.
This can be useful in order to move toward the
target faster by using recoil from shooting.
self.faceAwayFromTarget(target)
'''
pass #Your code goes here |
72e774b5308cd790b1d097ab6dd7eb47bed8509e | khuongsatou/OCRPython | /python-basic/No_6_Square.py | 164 | 3.625 | 4 | # Viết một method tính giá trị bình phương của một số.
mInput = int(input("Input key:"))
def Square(num):
return num**2
print(Square(mInput)) |
9600f952a18d347b49d67ae0f47a5f88a7bc4ffc | yanghongkai/yhkleetcode | /dynamic/bag/coin_change_322.py | 1,498 | 3.5625 | 4 |
# 322 零钱兑换 https://leetcode-cn.com/problems/coin-change/
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
memo = {}
# dp[i] 凑成金额为 i 需要的最少的硬币个数
def dp(n):
if n in memo:
return memo[n]
if n == 0:
return 0
if n < 0:
return -1
res = float("inf")
for coin in coins:
sub_problem = dp(n-coin)
if sub_problem == -1:
continue
res = min(res, sub_problem+1)
memo[n] = res if res!= float("inf") else -1
return memo[n]
return dp(amount)
class Solution2:
def coinChange(self, coins: List[int], amount: int) -> int:
# dp[i] 凑成金额为 i 需要的最少的硬币个数
# amount + 1 相当于正无穷
dp = [amount+1 for i in range(amount+1)]
# base case
dp[0] = 0
for i in range(1, amount+1, 1):
for coin in coins:
if i - coin < 0:
continue
else:
dp[i] = min(dp[i], dp[i-coin]+1)
return -1 if dp[amount] == amount+1 else dp[amount]
coins = [1, 2, 5]
amout = 11
coins = [2]
amout = 3
coins = [1]
amout = 0
coins = [2, 5, 10, 1]
amout = 27
coins = [186, 419, 83, 408]
amout = 6249
print(Solution2().coinChange(coins, amout))
|
1d70b78c84d450e824fc41e40b7eb2afed2a797b | aprilyichenwang/small_projects | /coding_exercise/binary_icecream_parlor.py | 1,492 | 3.78125 | 4 | # import itertools
#
# def get_flavors(m, a, n):
# '''
#
# :param m: total money to be spent
# :param a: a list of each flavor's cost
# :param n: total number of flavors
# :return: id1, id2
# '''
# combos=list(itertools.combinations(a,2))
# combos_sum=[cost[0]+cost[1] for cost in combos]
# cost_pair=combos[combos_sum.index(m)]
# cost1,cost2=cost_pair[0],cost_pair[1] # I need to return the id number, I am return the cost number
# ids=[i for i in range(n) if a[i]==cost1 or a[i]==cost2]
# ids.sort()
# return ids[0],ids[1]
#
#
#
# t = int(raw_input().strip()) # num_trips
# for a0 in xrange(t):
# m = int(raw_input().strip()) # m dollars
# n = int(raw_input().strip()) # n flavors
# a = map(int, raw_input().strip().split(' ')) # the cost list of each flavor
#
# flavor_id1, flavor_id2=get_flavors(m, a,n)
# print flavor_id1+1, flavor_id2+1
t = int(raw_input().strip()) # num_trips
for a0 in xrange(t):
m = int(raw_input().strip()) # m dollars
n = int(raw_input().strip()) # n flavors
a = map(int, raw_input().strip().split(' ')) # the cost list of each flavor
cost_map={} # used to track index
for i, cost in enumerate(a):
# 1. use enumerator
# 2. smaller ID prints first (id is basically index of the list)
sunny=cost
jonny=m-cost
if jonny in cost_map:
print cost_map[jonny]+1, i+1
else:
cost_map[sunny]=i
|
c10460b7d9f50a80f07cea65add9c7f4e0ad6059 | mymysuzy/Python | /StartCamp/day1/lunch.py | 397 | 3.640625 | 4 | menu = ['예향정','착한통큰오리삼겹','장가계']
#print(menu)
#print(menu[0], menu[-1])
phone_book = {'예향정':'123-123', '착한통큰오리삼겹':'456-456', '장가계':'789-789'}
# print(phone_book)
# print(phone_book['장가계'])
import random
my_menu = random.choice(menu)
print(my_menu + '의 전번은'+ phone_book[my_menu]+'입니다')
print(f'{my_menu}의 전번은?')
|
7c3207ad9c5554397b73f236870e3c1500291b1f | IM-MC/LCsol | /40.py | 898 | 3.734375 | 4 | def combinationSum2(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
arr = []
def backtrack(n, target, index, candidates, curr, arr):
if n == target:
listCopy = list(curr)
listCopy.sort()
if listCopy not in arr:
arr.append(listCopy)
return
for i in range(index, len(candidates)):
if n + candidates[i] > target:
continue
n += candidates[i]
curr.append(candidates[i])
backtrack(n, target, i+1, candidates, curr, arr)
n -= candidates[i]
del curr[-1]
backtrack(0, target, 0, candidates, [], arr)
return arr
print(combinationSum2([10,1,2,7,6,1,5], 8))
|
2c67c3c47d5178da165625302d7849c114bf92aa | KEVINBARRIOS128/PARCIAL-VIRTUAL-1 | /parcial-virtual-1.py | 7,491 | 3.75 | 4 | ListaClientes = []
ListaDeProyecto = []
ListaDepartamentos = []
ListaMunicipios = []
ListaResgistro = []
import os
def ingresarCliente(Codigo, Nombre, Direccion, Telefono):
ListaClientes.append([Codigo, Nombre, Direccion, Telefono])
print("Cliente Ingresado Exitosamente")
def mostrarclientes():
datos = len(ListaClientes)
if datos != 0:
for clientes in ListaClientes:
print(clientes[0], clientes[1])
else:
print("Lista vacia")
def ingresarProyecto(nombreProyecto):
# almacenando el proyecto a la lista de proyectos
# mostrando la lista de clientes registrados
mostrarclientes()
codigoCliente = input("Ingrese El Codigo Del Cliente Para El Proyecto: ")
posicion = buscarCliente(codigoCliente)
if posicion != -1:
print("Cliente Encontrado")
mostrardepartamentos()
departamento = input("Ingres El Nombre Del departamento Para El Proyecto: ")
nombreDepar = buscardepartamento(departamento)
if nombreDepar != "vacio":
print("Departamento Encontrado")
mostrarmunicipios()
municipio = input("Ingrese el nombre del municipio para el proyecto: ")
nombreMunicipio = buscarmunicipio(municipio)
if nombreMunicipio != "vacio":
print("Municipio encontrado")
ListaDeProyecto.append([nombreProyecto, ListaClientes[posicion][0], ListaClientes[posicion][1],
nombreDepar, nombreMunicipio, "ACTIVO"])
print("Proyecto Registrado Satisfactoriamente")
else:
print("Municipio no encontrado volviendo al menu")
else:
print("Departamento no nencontrado volvinedo al menu")
else:
print("Cliente No Encontrado Volviendo Al Menu")
print("Proyecto Ingresado Exitosamente")
def verproyectos():
for proyectos in ListaDeProyecto:
print(proyectos)
def ingresarDepartamentos(nombreDepartamento):
ListaDepartamentos.append(nombreDepartamento)
print("Departamento agregado Exitosamente")
def mostrardepartamentos():
for departamento in ListaDepartamentos:
print(departamento)
def buscardepartamento(buscar):
nombre = "vacio"
encontrado = False
for departamento in ListaDepartamentos:
if departamento == buscar:
nombre = departamento
encontrado = True
break
return nombre
def ingresarMunicipios(nombreMunicipio):
ListaMunicipios.append(nombreMunicipio)
print("Municipio ingresado exitosamente")
def mostrarmunicipios():
for municipio in ListaMunicipios:
print(municipio)
def buscarmunicipio(buscar):
nombre = "vacio"
encontrado = False
for municipio in ListaMunicipios:
if municipio == buscar: # si el nombre coincide almacenamos el nombre
nombre = municipio
encontrado = True
break # rompemos el bucle
return nombre
def buscarCliente(buscar):
print("Datos del cliente")
posicion = 0 # EL PROGRAMA BUSCA LA UBICACION DEL CODIGO
encontrado = False # SI NO LO ENCUENTRA SE TIRA AL FOR PARA EL RECORRID
Codigo = "Codigo"
Nombre = "Nombre"
Direccion = "Direccion"
Telefono = "Telefono"
Nombre_del_proyecto = "Nombre del Proyecto"
Estado_del_proyecto = "Estado del Proyecto"
Departamento = "Departamento"
Municipio = "Municipio"
print("{:10} {:10} {:10} {:10} {:10} {:10} ".format(Codigo, Nombre, Direccion, Telefono, Nombre_del_proyecto, Estado_del_proyecto ))
for clientes in ListaClientes:
print("{:10} {:10} {:10} {:10} {:10} {:10}".format(clientes[0], clientes[1], clientes[2], clientes[3], clientes[0][0], clientes[0][1]))
#print(clientes)
for Cliente in ListaClientes:
if Cliente[0] == buscar: # SI LO ENCUENTRA EN LA EL DATO EN LA POCION 0 ENTONCES SE TIRA A VERDADERO Y PARA
encontrado = True
break
else:
posicion = posicion + 1 #
if not encontrado:
posicion = - 1 # CUANDO TERMINO EL RECORRIDO Y NO LO TERMINO EL REGRESA A UNA POSICON ANTERIOR
return posicion
def modificarCliente():
print("ingrese el codigo del cliente")
def eliminarCliente(busqueda):
print("ingrese el codigo del cliente: ")
nombre = "vacio"
encontrado = False
for clientes in ListaClientes:
print(clientes[0])
if clientes[0] == busqueda:
nombre = clientes
encontrado = True
ListaClientes.remove(nombre)
break
return nombre
def Salir():
print("****SALIENDO DEL PROGRAMA******")
def menu():
opcion = 0
while opcion != 8:
print("***************************************************************")
print( " BIENVENIDOS A PRINTADOS EXPRESS\n POR FAVOR INGRESA TUS DATOS")
print("1: Registrar Cliente ")
print("2: Ingresar Proyecto ")
print("3. Ingresar Departametos ")
print("4. Ingresar Municipios ")
print("5. Buscar el cliente ")
print("6. Eliminar Cliente ")
print("7. Modificar cliente ")
print("8. salir")
print("9. Ver Proyectos")
opcion = int(input("Digite Opcion: "))
if opcion == 1:
Codigo = input("Ingrese El Codigo: ")
Nombre = input("Ingrese el Nombre ")
Direccion = input("Ingrese la Direccion ")
Telefono = input(" Ingrese la Telefono ")
ingresarCliente(Codigo, Nombre, Direccion, Telefono)
elif opcion == 2:
nombreProyecto = input("Nombre del proyecto ")
ingresarProyecto(nombreProyecto)
elif opcion == 3:
nombreDepartamento = input("Nombre del Departamento ")
ingresarDepartamentos(nombreDepartamento)
elif opcion == 4:
nombreMunicipio = input("Nombre del Municipio ")
ingresarMunicipios(nombreMunicipio)
elif opcion == 5:
datos = len(ListaClientes)
if datos != 0:
buscar = input("Ingrese El Codigo Del Cliente ")
NOMBRE_PROYECTO = "NOMBRE DEL PROYECTO"
CODIGO = "CODIGO"
NOMBRE = "NOMBRE"
DEPARTAMENTO = "DEPARTAMENTO"
MUNICIPIO = "MUNICIPIO "
ESTADO = "ESTADO"
print("{:10} {:10} {:10} {:10} {:10} {:10} ".format(NOMBRE_PROYECTO, CODIGO, NOMBRE, DEPARTAMENTO, MUNICIPIO, ESTADO))
for clientes in ListaDeProyecto:
if clientes[1]==buscar:
print("{:20} {:10} {:10} {:10} {:10} {:10}".format(clientes[0],clientes[1],clientes[2],clientes[3],
clientes[4],clientes[5]))
break
respuesta = input("Desea volver al menu Principal 1:SI 0:NO")
if respuesta == 1:
menu()
else:
print("Lista vacia")
menu()
elif opcion == 6:
codigoCliente = input("Ingrese el Codigo del Cliente")
eliminarCliente(codigoCliente)
print("Supuestamente se borro el cliente")
elif opcion == 7:
print("hola")
elif opcion == 8:
Salir()
elif opcion == 9:
verproyectos()
menu() |
c9b17e12e46d4b54789934382854b1e7df812f4e | osundiranay/py-12-----12Mysql-Python-Tkinter | /finished work, but demo/example.py | 2,307 | 3.78125 | 4 | from tkinter import *
import tkinter as ttk
root = Tk()
root.title("Tk dropdown example")
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
# Create a Tkinter variable
tkvar = StringVar(root)
from tkinter import messagebox
import pymysql.cursors
from tkinter import *
import tkinter as tk
import os
connection = pymysql.connect(host='localhost', user='root', password='Atleticomadrid2002',
database='session',
cursorclass=pymysql.cursors.DictCursor)
with connection:
with connection.cursor() as cursor:
actor_count = 'select count(name) from Actor'
cursor.execute(actor_count)
lol = cursor.fetchall()
result = lol[0]['count(name)']
choices = []
for i in range(result):
choices.append(i)
tkvar.set('Id ') # set the default option
popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Выберите Id актрера").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
name = StringVar()
surname = StringVar()
age = IntVar()
country = StringVar()
name_label = Label(text="Введите имя:")
surname_label = Label(text="Введите фамилию:")
age_label = Label(text="Введите возраст:")
country_label = Label(text="Введите страну:")
name_label.grid(row=0, column=0, sticky="w")
surname_label.grid(row=1, column=0, sticky="w")
age_label.grid(row=2, column=0, sticky="w")
country_label.grid(row=3, column=0, sticky="w")
name_entry = Entry(textvariable=name)
surname_entry = Entry(textvariable=surname)
age_entry = Entry(textvariable=age)
country_entry = Entry(textvariable=country)
name_entry.grid(row=0,column=1, padx=5, pady=5)
surname_entry.grid(row=1,column=1, padx=5, pady=5)
age_entry.grid(row=2,column=1, padx=5, pady=5)
country_entry.grid(row=3,column=1, padx=5, pady=5)
message_button = Button(text="Click Me", command=insert_into)
message_button.grid(row=5,column=1, padx=5, pady=5, sticky="e")
def change_dropdown(*args):
print( tkvar.get() )
# link function to change dropdown
tkvar.trace('w', change_dropdown)
root.mainloop()
|
798f2b627a88c7fd233f4c15e5541baac8556201 | Roman-Sarchuk/Chat | /cezar_coding.py | 1,642 | 3.703125 | 4 | alphabet_ENG = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
alphabet_UA = 'абвгґдеєжзиіїйклмнопрстуфхцчшщьюяабвгґдеєжзиіїйклмнопрстуфхцчшщьюя'
alphabet_ENG_caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
alphabet_UA_caps = 'АБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ'
number = '01234567890123456789'
# message = str(input('Ведіть текст... '))
def encryption(text, key=1):
code = ''
text = str(text)
key = key
for sps in text:
if sps in alphabet_ENG:
position = alphabet_ENG.find(sps)
new_position = position + key
code = code + alphabet_ENG[new_position]
elif sps in alphabet_UA:
position = alphabet_UA.find(sps)
new_position = position + key
code = code + alphabet_UA[new_position]
elif sps in alphabet_ENG_caps:
position = alphabet_ENG_caps.find(sps)
new_position = position + key
code = code + alphabet_ENG_caps[new_position]
elif sps in alphabet_UA_caps:
position = alphabet_UA_caps.find(sps)
new_position = position + key
code = code + alphabet_UA_caps[new_position]
elif sps in number:
position = number.find(sps)
new_position = position + key
code = code + number[new_position]
else:
code = code + sps
return code
# encryption(message, 1)
|
426e7004ca1cbbcf145e1572104fe0914385bef3 | patrick-doumont/module2_3 | /initials_mod.py | 1,381 | 4.5625 | 5 | full_name = input('Enter your name separated by spaces:')
names = full_name.strip().split()
print(names)
initials = []
for name in names:
initials.append(name[0])
print("Your initials are:", end=' ')
for i in initials:
print(f'{i.upper()}', end='') # I like the f string format better too!
print('')
# This is a comment to test windows GUI app.
# Another way to write the above code (lines 5-8) is below
# with list comprehension; the code reads 'put the first
# element of name into the resulting list for each name in the
# iterable names (in this case also a list)'
initials = [name[0] for name in names]
# I could also write it like this (though its less desirable)
initials = [my_var_name[0] for my_var_name in names]
# ---------------------------------------------------------------
# Rewriting the whole program combining list comprehension and
# printing into 1 step
full_name = input('Enter your name separated by spaces: ')
names = full_name.strip().split()
print(names)
print("Your initials are:", end=' ')
print(''.join(name[0].upper() for name in names))
# the join function does just what the name implies:
# give it a list of strings and a string to put between
# each element. another example below:
my_strs = ['this', 'is', 'a', 'test', 'using', 'join']
print(' * '.join(my_strs))
# output > this * is * a * test * using * join
# ~ Doug
|
467ae24a2b184caacb42a22b68be5010d0a77b97 | hu-lf/LeetCode | /LRU缓存.py | 950 | 3.734375 | 4 |
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.lruCache = OrderedDict() # 内置一个 有序字典 或 将该类继承自 有序字典类
def get(self, key: int) -> int:
if key in self.lruCache:
self.lruCache.move_to_end(key) # get到该值 放到最前
return self.lruCache[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.lruCache:
self.lruCache.move_to_end(key) # put到该值 放到最前
self.lruCache[key] = value
if len(self.lruCache) > self.capacity:
self.lruCache.popitem(last=False)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
41350eae4bbd478fda6b47e6af53cdce1ca4384e | richnakasato/epi-py | /5.9.enumerate_all_primes_to_n.0.py | 686 | 3.5 | 4 | from test_framework import generic_test
# Given n, return all primes up to and including n.
def generate_primes(n):
# TODO - you fill in here.
root = 1
while root * root < n:
root += 1
primes = [True for i in range(n+1)]
primes[0] = primes[1] = False
for i in range(2, root+1):
if primes[i]:
for j in range(i*i, n+1, i):
primes[j] = False
res = list()
for i in range(n+1):
if primes[i]:
res.append(i)
return res
if __name__ == '__main__':
exit(
generic_test.generic_test_main("prime_sieve.py", "prime_sieve.tsv",
generate_primes))
|
5485485a8a433fef747826765d60089e70a374fb | erikxt/leetcode | /python/LRUCache.py | 1,036 | 3.671875 | 4 | class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.record = []
self.cache = {}
# @return an integer
def get(self, key):
if self.cache.has_key(key):
self.record.remove(key)
self.record.append(key)
return self.cache.get(key)
else:
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if self.cache.has_key(key):
self.record.remove(key)
del self.cache[key]
if len(self.record) >= self.capacity:
lru = self.record.pop(0)
del self.cache[lru]
self.record.append(key)
self.cache[key]=value
def main():
s=LRUCache(10)
s.set(10,13)
s.set(3,17)
s.set(6,11)
s.set(10,5)
s.set(9,10)
s.get(13)
s.set(2,19)
s.get(2)
print s.get(3)
if __name__ == "__main__":
main()
|
2fdb0b805e5b3835414afa177593181ee56e036a | potdarmrunal/Python | /Python_Basic_Program/TrianglePattern.py | 881 | 4.03125 | 4 | #print Following Pattern
#1
#1 2
#1 2 3
#1 2 3 4
#1 2 3 4 5
def PrintTriangle1(x):
num = 1
for i in range(0,x):
num = 1
for j in range(0,i+1):
print(num,end=" ")
num=num+1
print("\r")
PrintTriangle1(5)
#print Following Pattern
#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
def PrintTriangle2(x):
num = 1
for i in range(0,x):
for j in range(0,i+1):
print(num,end=" ")
num = num + 1
print("\r")
PrintTriangle2(5)
#print Following Pattern
#A
#A B
#A B C
#A B C D
#A B C D E
def PrintTriangle3(x):
num = 65;
for i in range(0,x):
num = 65
for j in range(0,i+1):
ch = chr(num)
print(ch, end=" ")
num = num + 1
print("\r")
PrintTriangle3(5)
|
405014ba61b9f379182d14a746f55807176e3915 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2741/60766/252028.py | 520 | 3.5625 | 4 | class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
c=1
max_c=1
for i in range(len(nums)-1):
if nums[i] < nums[i+1]:
c+=1
if c>max_c:
max_c=c
else:
c=1
return max_c
if __name__ == '__main__':
num=eval(input())
s=Solution()
print(s.findLengthOfLCIS(num)) |
2e502e115dd7a4badc5b2f7fc12283b1567bed30 | CameronSA/RaceTrackerAI | /RaceTrackerAI/CommonFunctions.py | 121 | 3.59375 | 4 | def AddToDict(dict,key,value):
if key in dict:
dict[key].append(value)
else:
dict[key] = [value]
|
88dd97c2980683b3c906c15711173701c6c27cc6 | aysunakarsu/molecule_parser | /molecule_parser.py | 3,166 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
This module is counting the number of atoms of each element
contained in the molecule and return a dict for a given
chemical formula represented by a string.
Examples:
>>> water = 'H2O'
>>> parse_molecule(water)
{'H': 2, 'O': 1}
>>> magnesium_hydroxide = 'Mg(OH)2'
>>> parse_molecule(magnesium_hydroxide)
{'Mg': 1, 'O': 2, 'H': 2}
>>> fremy_salt = 'K4[ON(SO3)2]2'
>>> parse_molecule(fremy_salt)
{'K': 4, 'O': 14, 'N': 2, 'S': 4}
"""
import re
from collections import OrderedDict
import json
OPEN_BRACKETS = '[({'
CLOSE_BRACKETS = '])}'
def find_multiplier(var_submolecule):
var_multiplier = 1
digits = re.search(r'(?<=^[\]\)\}])(\d+)', var_submolecule)
if digits is not None:
var_multiplier = int(digits.group(0))
return var_multiplier
def add_to_dict(old_dict, new_dict):
for element, value in new_dict.items():
if element in old_dict:
old_dict[element] += value
else:
old_dict[element] = value
def convert_submolecule_to_atoms_dict(var_submolecules_dict):
dict_atoms = OrderedDict()
for item, multiplier in var_submolecules_dict.items():
search_list = re.findall(r'([A-Z][a-z]?)(\d*)', item)
for element, value in search_list:
if value == '':
value = 1 * multiplier
else:
value = int(value) * multiplier
add_to_dict(dict_atoms, OrderedDict([(element, value)]))
return dict_atoms
def parse_submolecule_multiplier(var_submolecules, multiplier=1):
dict_submolecules = OrderedDict()
stack = []
submolecule_multiplier = 1
for index_submolecule, submolecule in enumerate(var_submolecules):
if submolecule in OPEN_BRACKETS:
stack.append(index_submolecule)
elif submolecule[0] in CLOSE_BRACKETS:
index_start = stack.pop() + 1
submolecule_multiplier = find_multiplier(submolecule) * multiplier
if not stack:
add_to_dict(
dict_submolecules,
parse_submolecule_multiplier(
var_submolecules[index_start:index_submolecule],
submolecule_multiplier))
else:
parse_submolecule_multiplier(
var_submolecules[index_start:index_submolecule],
submolecule_multiplier)
elif not stack:
add_to_dict(dict_submolecules,
OrderedDict([(submolecule, multiplier)]))
return dict_submolecules
def parse_molecule(molecule):
pattern_submolecule = re.compile("([\[\(\{]|[\]\)\}][\d]*)")
list_submolecules = [
x.strip() for x in pattern_submolecule.split(molecule) if x
]
submolecule_dict = parse_submolecule_multiplier(list_submolecules)
submolecule_dict_to_atoms_dict = convert_submolecule_to_atoms_dict(
submolecule_dict)
print("{}".format(
json.dumps(submolecule_dict_to_atoms_dict).replace('"', '\'')))
if __name__ == '__main__':
import doctest
count, _ = doctest.testmod()
if count == 0:
print('*** ALL TESTS PASS ***')
|
39ebe486b2816d19ee1524178d4946c64d50ec71 | Kephren-Delannay/AdventOfCode | /CustomUtilities.py | 484 | 3.703125 | 4 | def ReadFileBlanks(filename):
"""
Reads a file that contains data separated by
blank spaces, returns data in a list
"""
with open(file=filename) as f:
data = f.read().split('\n')
processeddata = []
cur = 0
for i in range(len(data)):
if data[i] == "":
processeddata.append(data[cur:i])
cur = i
return processeddata
def FlattenList(l):
return [item for sublist in l for item in sublist] |
0b3c77d4617aae49006c1f3e3b8875c6fae35c61 | Ghaithdabash/Game | /newgame.py | 1,150 | 4.28125 | 4 | # 1. The computer will think of 3 digit number that has no repeating digits.
import random
def generat_num():
digits = list(range(10))
random.shuffle(digits)
shuf_num = digits[:3]
arr1 = [str(digits[1]), str(digits[2]), str(digits[3])]
return(arr1)
# 2. You will then guess a 3 digit number
def guessing():
guess = input("What is your guess? ")
arr2 = [guess[0], guess[1], guess[2]]
return(arr2)
# 3. The possible clues are:
def cluesg(user, com):
finish = ""
if user == com:
finish = "CODE CRACKED!"
print(finish)
else:
arr3 = []
for ind,i in enumerate(user):
if i == com[ind]:
arr3.append("match")
elif i in com:
arr3.append("close")
else:
arr3.append("not even close")
print (arr3)
if finish != "CODE CRACKED!":
first_function_call(guessing(), com)
else:
print("Good Game")
def first_function_call(a, b):
cluesg(a, b)
cmp_code = generat_num()
print(cmp_code)
user_code = guessing()
print(user_code)
first_function_call(user_code, cmp_code)
|
b330e13996ca531420b67fcd7a62cbb366eb2b22 | CodeGolfWhatsapp/Respostas | /031-SOMAPARES/Pares-Breno.py | 86 | 3.625 | 4 | x=input()
if x%2==0: print sum(range(x,x+10,2))
else: print sum(range(x+1,x+10,2))
|
6d6dbd6f189d461bcee44687ef791c6aa3da1b68 | FaisalAhmed64/Python-Basic-Course | /Arithmatic operation.py | 224 | 3.578125 | 4 | Secret_number=9
guess_count=0
guess_limit=3
#while guess_count<guess_limit:
guss=int(input("guess: "))
guess_count +=1
if guss==Secret_number:
print("you win")
break
else:
print("you failed") |
e34be75de88f3be5938f34e619532fd32b36dd39 | Kunal-Upadhyay/my-first-ml-program | /My first AI rps.py | 1,676 | 3.90625 | 4 | def invalid():
print("\n\t!!!!!!!!!!!!!!!!!!!invalid choice!!!!!!!!!!!!!!!!!!!!\n")
import random
PL=[]
CL=[]
RL=[]
x=0
y=0
print("----------Rock Paper Sissor ML Game By Kunal Upadhyay----------")
while True:
if y==0:
if x!=0:
print("\t\t\t<1> Play again ")
else:
print("\t\t\t<1> Play Game")
print("\t\t\t <2> Exit")
c=input("Enter your choice : ")
if c=='1':
L=["R","P","S"]
y=1
print("\t\t\t< R > Rock \n\t\t\t< P > Paper \n\t\t\t< S > Sissor")
player=input("Enter Your choice : ")
if player=="r" or player=="p"or player=="s":
player=player.upper()
if player!="R" and player!="P"and player!="S" :
invalid()
continue
PL.append(player)
for i in range(0,len(RL)):
if player==PL[i] and RL[i]=="W":
L.remove(CL[i])
elif player==CL[i] and RL[i]=="W":
L=[]
L.append(PL[i])
if player==PL[i] and RL[i]=="L":
L=[]
L.append(CL[i])
computer=random.choice(L)
CL.append(computer)
print("Computer : ",computer)
if (player=="P" and computer=="R")or(player=="S" and computer=="P")or(player=="R" and computer=="S"):
print("You Win")
RL.append("W")
elif(player==computer):
print("Tie")
RL.append("W")
else:
print("You Lose")
RL.append("L")
elif c=='2':
break;
else:
invalid()
continue
x=1
y=0
|
661d9c2b28e52591e6fd0b03b182204852035c3b | dnealio/python_online2 | /week_03/labs/07_lists/Exercise_06.py | 568 | 3.96875 | 4 | '''
This exercise pertains to the so-called Birthday Paradox,
which you can read about at
http://en.wikipedia.org/wiki/Birthday_paradox
If there are 23 students in your class, what are the chances that two
of you have the same birthday? You can estimate this probability by
generating random samples of 23 birthdays and checking for matches.
Hint: you can generate random birthdays with the randint function in
the random module.
Source: http://greenteapress.com/thinkpython2/html/thinkpython2011.html#sec128
Solution: http://thinkpython2.com/code/birthday.py
'''
|
e1ca8b2262637771a85c62f75004fd43593ca904 | nravikanth/python_class | /programs/even_odd.py | 108 | 4.125 | 4 | a=input("enter the number: ")
if a%2==0:
print "its even"
else:
print "its odd"
print "out of the block"
|
6c7354be80f9c9a2186f9dae1bc09ddc30c449aa | RazLandau/ML | /Back Propagation/backprop_network.py | 7,141 | 3.96875 | 4 | """
backprop_network.py
"""
import random
import numpy as np
import math
class Network(object):
def __init__(self, sizes):
"""The list ``sizes`` contains the number of neurons in the
respective layers of the network. For example, if the list
was [2, 3, 1] then it would be a three-layer network, with the
first layer containing 2 neurons, the second layer 3 neurons,
and the third layer 1 neuron. The biases and weights for the
network are initialized randomly, using a Gaussian
distribution with mean 0, and variance 1. Note that the first
layer is assumed to be an input layer, and by convention we
won't set any biases for those neurons, since biases are only
ever used in computing the outputs from later layers."""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
def SGD(self, training_data, epochs, mini_batch_size, learning_rate,
test_data, calc_train_stats = False, calc_gradient_norms = False):
"""Train the neural network using mini-batch stochastic
gradient descent. The ``training_data`` is a list of tuples
``(x, y)`` representing the training inputs and the desired
outputs. """
test_accuracies, train_accuracies, train_loss, gradient_norms = [], [], [], []
print("Initial test accuracy: {0}".format(self.one_label_accuracy(test_data)))
n = len(training_data)
for j in range(epochs):
random.shuffle(list(training_data))
mini_batches = [
training_data[k:k+mini_batch_size]
for k in range(0, n, mini_batch_size)]
for mini_batch in mini_batches:
gradient_norms.append(self.update_mini_batch(mini_batch, learning_rate, calc_gradient_norms))
print ("Epoch {0} test accuracy: {1}".format(j, self.one_label_accuracy(test_data)))
test_accuracies.append(self.one_label_accuracy(test_data))
if calc_train_stats:
train_accuracies.append(self.one_hot_accuracy(training_data))
train_loss.append(self.loss(training_data))
return test_accuracies, train_accuracies, train_loss, gradient_norms
def update_mini_batch(self, mini_batch, learning_rate, calc_gradient_norms):
"""Update the network's weights and biases by applying
stochastic gradient descent using backpropagation to a single mini batch.
The ``mini_batch`` is a list of tuples ``(x, y)``."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w - (learning_rate / len(mini_batch)) * nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b - (learning_rate / len(mini_batch)) * nb
for b, nb in zip(self.biases, nabla_b)]
if calc_gradient_norms:
return [np.linalg.norm(db) / len(mini_batch) for db in nabla_b]
def _calc_a_and_z_values(self, x):
a_values = [np.zeros((size, 1)) for size in self.sizes]
z_values = [np.zeros((size, 1)) for size in self.sizes]
z_values[0] = x
a_values[0] = x
for t in range(1, self.num_layers - 1):
z_values[t] = self.weights[t - 1].dot(a_values[t - 1]) + self.biases[t - 1]
a_values[t] = sigmoid(z_values[t])
z_values[self.num_layers - 1] = \
self.weights[self.num_layers - 2].dot(a_values[self.num_layers - 2]) + \
self.biases[self.num_layers - 2]
return a_values, z_values
def backprop(self, x, y):
"""The function receives as input a 784 dimensional
vector x and a one-hot vector y.
The function should return a tuple of two lists (db, dw)
as described in the assignment pdf. """
a_values, z_values = self._calc_a_and_z_values(x)
db = [np.zeros(b.shape) for b in self.biases]
dw = [np.zeros(w.shape) for w in self.weights]
# delta_L
db[self.num_layers - 2] = self.loss_derivative_wr_output_activations(z_values[self.num_layers - 1], y)
for i in range(self.num_layers - 3, -1, -1):
dot_product = np.dot(self.weights[i + 1].transpose(), db[i + 1])
db[i] = dot_product * sigmoid_derivative(z_values[i + 1])
for i in range(0, self.num_layers - 1):
dw[i] = db[i] * a_values[i].transpose()
return (db, dw)
def one_label_accuracy(self, data):
"""Return accuracy of network on data with numeric labels"""
output_results = [(np.argmax(self.network_output_before_softmax(x)), y)
for (x, y) in data]
return sum(int(x == y) for (x, y) in output_results)/float(len(data))
def one_hot_accuracy(self,data):
"""Return accuracy of network on data with one-hot labels"""
output_results = [(np.argmax(self.network_output_before_softmax(x)), np.argmax(y))
for (x, y) in data]
return sum(int(x == y) for (x, y) in output_results) / float(len(data))
def network_output_before_softmax(self, x):
"""Return the output of the network before softmax if ``x`` is input."""
layer = 0
for b, w in zip(self.biases, self.weights):
if layer == len(self.weights) - 1:
x = np.dot(w, x) + b
else:
x = sigmoid(np.dot(w, x)+b)
layer += 1
return x
def loss(self, data):
"""Return the loss of the network on the data"""
loss_list = []
for (x, y) in data:
net_output_before_softmax = self.network_output_before_softmax(x)
net_output_after_softmax = self.output_softmax(net_output_before_softmax)
loss_list.append(np.dot(-np.log(net_output_after_softmax).transpose(),y).flatten()[0])
return sum(loss_list) / float(len(data))
def output_softmax(self, output_activations):
"""Return output after softmax given output before softmax"""
output_exp = np.exp(output_activations)
return output_exp/output_exp.sum()
def loss_derivative_wr_output_activations(self, output_activations, y):
"""Return derivative of loss with respect to the output activations before softmax"""
return self.output_softmax(output_activations) - y
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
def sigmoid_derivative(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
|
3b30e1df2ca709f7105bc6eb71e7cbe3f960ac9e | jn7163/pyinaction | /lesson7/calc_input.py | 476 | 3.8125 | 4 |
def add(a, b):
return a + b
def mul(a, b):
return a * b
def sub(a, b):
return a - b
def div(a, b):
return a / b
op_dict = {
'+': add,
'*': mul,
'-': sub,
'/': div
}
if __name__ == "__main__":
while True:
s = input('please enter(+ 1 2): ')
s_list = s.split()
func = op_dict.get(s_list[0])
result = func(int(s_list[1]), int(s_list[2]))
print('result:', result)
|
f17400ab41ef4363f9bbd20adf14cf2849888fb7 | wangxingruby/learnpython | /testpython/bool.py | 179 | 3.71875 | 4 | print(1==1)
# TODO 在Python中表示复数
#超长的字符串,需要换行,用三引号
import matplotlib.pyplot as plt
square = [1,1,2,3,5]
plt.plot(square)
plt.show() |
40524c6e94487c7361573d219224de077327a5a5 | magdychserg/lesson1 | /task 1-2.py | 265 | 4.09375 | 4 | # Перевод введеных секунд в часы, минуты и секунды
time = int(input("Enter the time in seconds: "))
hour = time // 3600
minute = (time // 60) % 60
seconds = time % 60
print(f"Your time ", hour,"h ", minute,"m ", seconds, "s") |
51fead984ce4d6a90238e544ce041969363ed9ef | viplix3/Essential-ML | /Regression/Linear Regression/linear_regression.py | 2,862 | 4.40625 | 4 | """ Linear Regression is a supervised optimisation algorithm which tries to
find the best fit line of the form Y = m*X + b for the given data set """
import numpy as np # numpy library for working with tensors
import matplotlib.pyplot as plt # matplotlib library for plotting purposes
import pandas as pd # for importing and using data from csv file
# Reading training and testing data
train = pd.read_csv('./Dataset/train.csv')
test = pd.read_csv('./Dataset/test.csv')
X = train['x']
Y = train['y']
test_X = test['x']
test_Y = test['y']
print('Shape of training data:\tX = {} Y = {}'.format(X.shape, Y.shape))
print('Shape of testing data:\tX = {} Y = {}'.format(test_X.shape, test_Y.shape))
# plotting the data points using matplotlib scatter plot function
plt.xlim(0, 110.0)
plt.ylim(0, 110.0)
plt.scatter(X, Y)
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.title('Training Data')
plt.show()
# defining random values for the regression line Y = m*X + b
m = np.random.rand() # m will act as the slope of the regression line
b = np.random.rand() # b will act as the Y-intercept of the regression line
def gradient_descent_optimizer(slope, intercept, learning_rate, x_train, y_train, num_iter):
for i in range(num_iter):
# setting gradient of slope and intercept 0 for each interation of gradient descent
grad_slope = 0
grad_intercept = 0
for i in range(len(x_train)):
# using sum of squared as loss function i.e. loss = y_pred - y_true
grad_slope = - ((y_train[i] - slope*x_train[i] + intercept)
* x_train[i]) # gradient for slope
grad_intercept = y_train[i] - slope*x_train[i] + intercept # gradient for intercept
# averaging over all training examples
grad_slope = 1/len(x_train) * grad_slope
grad_intercept = 1/len(x_train) * grad_intercept
# updating the parameters according to the given learning rate
slope = slope - learning_rate*grad_slope
intercept = intercept - learning_rate*grad_intercept
return slope, intercept
print('Randomly initialized slope before any training: %f\nRandomly initialized intercept before any training: %f'
% (m, b))
slope, intercept = gradient_descent_optimizer(m, b, 0.01, X, Y, 1000)
print('Slope after training: %f\nIntercept after training: %f' % (slope, intercept))
# plotting the result on training data
plt.xlim(0, 110.0)
plt.ylim(0, 110.0)
plt.plot(X, slope*X+intercept, color='r')
plt.scatter(X, Y)
plt.title('Resuts on Training Data')
plt.show()
# plotting the result on testing data using trained prameters i.e. slope and intercept
plt.xlim(0, 110.0)
plt.ylim(0, 110.0)
plt.plot(test_X, slope*test_X+intercept, color='r')
plt.scatter(test_X, test_Y)
plt.title('Resuts on Testing Data')
plt.show()
|
594ce839a0c98961b86ac32835f796d1e09b72fe | kaioaresi/HPD | /Python/Scripts/day_3/exercicio_1.py | 773 | 3.609375 | 4 | #!/usr/bin/env python3
import requests
'''
Realizar um get em uma api para capturar a quantidade de pessoas no espaço e o nome dos astronautas
Saida: Neste momento temos x pessoas no espaço são eles : X,y,z,w
'''
def nome_astronautas():
lista_nomes = []
url = "http://api.open-notify.org/astros.json"
resposta = requests.get(url)
saida_completa = resposta.json()
# Pegando o numero de astronautas
n_pessoas = saida_completa['number']
# Capturando dados astronautas
dados_people = saida_completa['people']
# Criando uma lista com os nomes dos astronautas
for i in range(0, n_pessoas):
nome = dados_people[i]['name']
lista_nomes.append(nome)
i += 1
return lista_nomes
print(nome_astronautas())
|
0ce41c1c0ff2ba02ef42ae637163fbe4806c6c4b | Spideyboi21/jash_python_pdxcode | /python learning/day8.py | 1,070 | 3.796875 | 4 | class BankAccount:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def withdraw(self, amount):
if self.balance - amount >0:
self.balance -= amount
print("Thanks {n}! You withdrew ${am}".format(n=self.name, am=amount))
else:
print('You don\'t have enough money to withdraw $ {am} fool!'.format(am))
class MinimumbalanceAccount(BankAccount):
def__init__(self, amount):
if self.balance - amount < self.Minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
BankAccount.withdraw(self, amount)
account1 = BankAccount('Chelsea', 1000)
account2 = MinimumbalanceAccount(100)
account2.deposit(50)
class person:
def__init__(self, name):
self.name = name
self.health = 100
player1 = Person('Jash')
player2 = Person('Nisa')
def fight(p1, p2):
p1.health -= random.randint(1, 10)
p2.health -= random.randint(1, 10)
fight(player1, player2)
print(player1.name, player1.health)
print(player2.name, player2.health)
|
e33a7c3583bda23c2e70bca4016ed67ec58600f9 | Wonjuny0804/leetcodechallenge | /September11th.py | 533 | 3.5 | 4 | """
Bulls and Cows?
"""
class Solution:
def getHint(self, secret, guess):
g = []
A = 0
B = 0
for i in guess:
g.append(i)
for i in range(0, len(secret)):
if secret[i] == guess[i]:
A += 1
g.remove(guess[i])
else:
if secret[i] in g:
B += 1
return str(A)+"A"+str(B)+"B"
a = Solution()
print(a.getHint("1807", "7810"))
print(a.getHint("1123", "0111"))
print(a.getHint("11", "10"))
|
e42a3badbb92805cc4d0e59d473d4ab357f7bb08 | Nigecat/Rock-Paper-Scissors | /src/utils.py | 2,493 | 3.609375 | 4 | #
#
# This file is used for storing the utility function, these are general use functions
#
#
from json import load
from time import process_time
from tkinter import PhotoImage
from random import choices as rndchoice
class setTimer(object):
'''Function to create a timer object
This is just interesting data on how the game is going
'''
def __init__(self):
self.startTime = 0
self.stopTime = 0
self.totalTime = 0
def start(self):
'''Start the timer'''
self.startTime = process_time()
def stop(self):
'''Stop the timer'''
self.stopTime = process_time()
self.totalTime = self.stopTime - self.startTime
def loadImage(file):
'''Formats a file and returns it as an image
file -- the input file
'''
return PhotoImage(file=".\\images\\{}".format(file))
def readConfig(file):
'''Function to read the config file
file -- the config file to read (json)
'''
with open("config.json") as f:
data = load(f)
return data
def rndmove(**args):
'''Function to return a random move
args -- arguments for the functions, if no weights are included, it will default to 33/33/33
'''
if "weights" in args.keys():
return ''.join(rndchoice(population=["rock", "paper", "scissors"], weights=args["weights"]))
else:
return ''.join(rndchoice(population=["rock", "paper", "scissors"], weights=[0.3333, 0.3334, 0.3333]))
def queryName(num):
'''Function to return the name of the action that corresponds to a number
num -- the number of the action to get the name of
'''
if num == 0:
return "rock"
elif num == 1:
return "paper"
elif num == 2:
return "scissors"
def queryNum(action):
'''Function to return the number of the action that corresponds to a name
action -- the action to get the number of
'''
if action == "rock":
return 0
elif action == "paper":
return 1
elif action == "scissors":
return 2
def beats(action):
'''Function to return what beats what
action -- the action that is played, whatever beats this action will be returned
'''
if action == 0 or action == "rock":
return "paper"
elif action == 1 or action == "paper":
return "scissors"
elif action == 2 or action == "scissors":
return "rock"
if __name__ == '__main__':
from os import system
system("gui.py") |
c210bf060beb002b0f5e37e589cfceed33c215a1 | xinshuoyang/algorithm | /src/680_SplitString/solution.py | 1,003 | 3.734375 | 4 | #!/usr/bin/python
################################################################################
# NAME : solution.py
#
# DESC :
#
# AUTH : Xinshuo Yang
#
# DATE : 20180326
#
################################################################################
class Solution:
"""
@param: : a string to be split
@return: all possible split string array
"""
def splitString(self, s):
# write your code here
if len(s) == 0:
return [[]]
if len(s) == 1:
return [[s[0]]]
res = []
self.helper([], s, res)
return res
def helper(self, prev, s, res):
if len(s) == 1:
res.append(prev + [s])
elif len(s) == 2:
res.append(prev + [s])
res.append(prev + [s[0]] + [s[1]])
else:
self.helper(prev + [s[0]], s[1:], res)
self.helper(prev + [s[:2]], s[2:], res)
if __name__ == '__main__':
sol = Solution()
print sol.splitString("1234")
|
3cb0a4724d90cc19b4c2ba731955dd1ce8b5955f | aaronize/pooryam | /examples/functional/functional_programming.py | 932 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
函数式编程
案例:
有数组numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],编写程序完成以下目标:
- 1. 将numberList中的每个元素加1得到一个新的数组
- 2. 将numberList中的每个元素乘2得到一个新的数组
- 3. 将numberList中的每个元素模3得到一个新的数组
'''
numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 定义map函数。对,就是map/reduce中的map
def map(func, numList):
newList = []
for num in numList:
newList.append(func(num))
return newList
# 1. 将numberList中的每个元素加1得到一个新的数组
print "1:", map(lambda x: x + 1, numberList)
# 2. 将numberList中的每个元素乘2得到一个新的数组
print "2:", map(lambda x: x * 2, numberList)
# 3. 将numberList中的每个元素模3得到一个新的数组
print "3:", map(lambda x: x % 3, numberList)
|
940a5c4c4822bc887547ef0ed39bd5f13b39f22c | DBULL7/python-guessing-game | /guessingGame.py | 1,726 | 4.03125 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
import os
import random
TotalAttempts = 5
os.system('clear')
print('Hello what is your name?')
name = input()
os.system('clear')
print('Enter a number between 1 and 100')
randomNumber = random.randint(1, 100)
guess = int(input())
def keepPlaying(attempts):
print('Want to keep playing? y/n')
keepPlaying = input()
if keepPlaying == 'y':
attempts = 5
makeGuess(attempts)
else:
print('Thanks for playing!')
exit()
def makeGuess(attempts):
if attempts == 0:
print('You lose')
keepPlaying(attempts)
else:
guess2 = int(input())
checkRange(guess2, attempts)
def playAgain(attempts):
print('Play Again? y/n')
playAgain = input()
if playAgain == 'y':
resetAttempts = 5
randomNumber = random.randint(1, 100)
os.system('clear')
print('Enter a number between 1 and 100')
newGuess = int(input())
checkRange(newGuess , resetAttempts)
def compareGuess(guess, attempts):
if guess == randomNumber:
print('Congratulations ' + name + ' you won!')
playAgain(attempts)
elif guess > randomNumber:
print('Too high, lives remaining: ', attempts - 1)
newAattempts = attempts - 1
makeGuess(newAattempts)
elif guess < randomNumber:
print('Too low, lives remaining: ', attempts - 1)
newAattempts = attempts - 1
makeGuess(newAattempts)
def checkRange(guess, attempts):
if guess > 100:
print('Way too high')
elif guess < 1:
print('Way too low')
else:
compareGuess(guess, attempts)
checkRange(guess, TotalAttempts)
|
a096bdb97c95ae4ecf3f0f763ffdffa9f4111c20 | henriquecl/Aprendendo_Python | /Exercícios/Lista 6 - Seção 13 - Leitura e escrita em arquivo/Questão 17 - Enunciado no código.py | 2,503 | 4.5625 | 5 | """
Questão 17 - Faça um programa que leia um arquivo que contenha as dimensões de uma matriz (linha x coluna), a quantida
de de posições que serão anuladas, e as posições a serem anuladas.
O programa lê esse arquivo, e em seguida, produz um novo arquivo com a matriz com as dimensões dadas no arquivo lido, e
todas as posições especificadas no arquivo ZERADAS e o restante recebendo valor 1.
3 3 2 / 3 tamanho de linhas, 3 tamanho de colunas, 2 posições a serem anuladas
1 0 / posição a ser anulada
1 2 / posição a ser anulada
"""
def lista_em_int(lista, lista_inteiro):
"""
:param lista: Tem uma lista como entrada
:param lista_inteiro: A lista de sáida
:return: Converte os itens que estão contidos na lista de 'str' para 'int' se forem APENAS números.
"""
for i in range(len(lista)):
lista_inteiro.append(int(lista[i]))
return lista_inteiro
def matriz_tamanho_usuário(matriz, tamanho):
"""
:param matriz : A matriz cuja você deseja criar
:param tamanho: Tamanho da matriz desejada pelo usuário
:return: Uma matriz do tamanho que o usuário desejar
"""
for i in range(tamanho):
matriz.append([])
def preenche_matriz(matriz):
"""
Essa função preenche todos os itens de uma matriz por 1
:param matriz: Matriz que deseja ser preenchida
:return: None
"""
for i in range(len(matriz)):
for j in range(len(matriz)):
matriz[i].append(1)
matriz_nova = []
with open('matrix.txt', 'r', encoding='UTF-8') as arquivo:
linha0 = arquivo.readline()
linha1 = arquivo.readline()
linha2 = arquivo.readline()
# Convertendo todas as linhas em lista, e depois em lista de inteiros
tamanho_matrix = linha0.split()
anula_1 = linha1.split()
anula_2 = linha2.split()
tamanho_matrix_inteiro = []
anula_1_inteiro = []
anula_2_inteiro = []
lista_em_int(tamanho_matrix, tamanho_matrix_inteiro)
lista_em_int(anula_1, anula_1_inteiro)
lista_em_int(anula_2, anula_2_inteiro)
# Criando uma matrix do tamanho digitado pelo usuário
matriz_tamanho_usuário(matriz_nova, tamanho_matrix_inteiro[0])
# Preenchendo a matriz com numeros 1
preenche_matriz(matriz_nova)
# Substituindo pelos valores desejados
matriz_nova[anula_1_inteiro[0]][anula_1_inteiro[1]] = 0
matriz_nova[anula_2_inteiro[0]][anula_2_inteiro[1]] = 0
a = str(matriz_nova)
# Criando um novo arquivo com a matriz_nova
with open('questao17.txt', 'w', encoding='UTF-8') as arquivo2:
arquivo2.write(a)
|
31d0d132f1a14976f350027068096ec478a32451 | gokou00/python_programming_challenges | /codesignal/numberOfClans.py | 524 | 3.71875 | 4 | def numberOfClans(divisors, k):
numDict = {}
for i in range(1,k+1):
numDict[i] = ""
for i in numDict:
for j in divisors:
if i % j == 0:
numDict[i] += str(j) + "is a div"
else:
numDict[i] += str(j) + "is not a div"
#print(numDict)
groups = []
test4 = {}
for key,val in numDict.items():
test4[val] = 0
return len(test4)
print(numberOfClans([1, 3] , 10))
|
69d341cb85a75bee47c69685ee8f7161381ddddf | ecpark4545/algorithms | /programmers/programmers_connect-islands.py | 750 | 3.71875 | 4 | """
https://programmers.co.kr/learn/courses/30/lessons/42861
1. union-find
2. kruskal
"""
def solution(n, costs):
def find(n1, parent):
if parent[n1] == n1:
return n1
parent[n1] = find(parent[n1], parent)
return parent[n1]
def union(n1, n2, parent, rank):
# root가 다른 상황만 union
root1 = find(n1, parent)
root2 = find(n2, parent)
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
parent[root1] = root2
if rank[root1] == rank[root2]:
rank[root2] += 1
result = 0
parent = {i: i for i in range(n)}
rank = {i: 0 for i in range(n)}
for n1, n2, w in sorted(costs, key=lambda x: x[2]):
if find(n1, parent) != find(n2, parent):
union(n1, n2, parent, rank)
result += w
return result |
c28c647415ddb94325801b8b48a80632b244d1e6 | diegotupino/TUPINO_HANGAROO | /Hangaroo.py | 1,232 | 4.0625 | 4 | def hangaroo(secretWord):
print("Hangarooo!")
length = len(secretWord)
print("The word has", length,"letters. ")
chances = 5
i = 0
lettersGuessed = []
while (chances!= 0):
if secretWord != getGuessedWord(secretWord, lettersGuessed):
print(chances, "guesses left. ")
print("Available Letters: ", getAvailableLetters(lettersGuessed))
guess = input("Type letter: ")
guessInLowerCase = guess.lower()
if guessInLowerCase in lettersGuessed:
print("You already guessed this letter. Try again! ", getGuessedWord(secretWord, lettersGuessed))
elif guessInLowerCase not in secretWord:
print("Incorrect guess. Try again! ", getGuessedWord(secretWord, lettersGuessed))
chances -= 1
else:
lettersGuessed.append(guessInLowerCase)
print("You found a correct letter! ", getGuessedWord(secretWord, lettersGuessed))
elif secretWord == getGuessedWord(secretWord, lettersGuessed):
print("You guessed it right! ")
break
else:
print("No guesses left. The word is " + secretWord) |
926e8ff75d1850a149778bfb2712a6e853cfd7b6 | LuckyStrike-zhou/LearnPython | /LearnPython3TheHardWay/ex1.py | 1,479 | 4.34375 | 4 |
# 这是一个注释
# print("Hello World!!")#这也是一个注释
# print("Hello Again")
# ex3
# 数学计算
# print("I will now count my chickens:")#固定输入
#
# print("Hens", 25 + 30 / 6)
# print("Roosters", 100 - 25 * 3 % 4)
#
# print("Now Iwill count my the eggs:")
#
# print(3 + 2 + 1 - 5 + 4 % 2 - 1 /4 + 6)#输出数字结果
#
# print("Is it ture that 3 + 2 < 5 - 7?")
#
# print(3 + 2 < 5 - 7)#判断真假
#
# print("What is 3 + 2?", 3 + 2)
# print("What is 5 - 7?", 5 - 7)
#
# print("Oh, that's why it's False")
#
# print("How about some more.")
#
# print("Is it greater?", 5 > -2)
# print("Is it greater or equal?", 5 >= -2)
# print("Is it less or equal?", 5 <= -2)
# 浮点数运算
# print(30.00 + 20 * 3 / 2 - 20 / 2)
# ex4
# cars = 100
# space_in_a_car = 4.0
# drivers = 30
# passengers = 90
# cars_not_driven = cars - drivers
# cars_driven = drivers
# carpool_capacity = cars_driven * space_in_a_car
# average_passengers_per_car = passengers / cars_driven
#
#
# print("There are", cars, "cars available.")
# print("There are only", drivers, "drivers available.")
# print("There will be", cars_not_driven, "empty cars today.")
# print("We can transport", carpool_capacity, "people today.")
# print("We have", passengers, "to carpool today.")
# print("We need to put about", average_passengers_per_car, "in each car.")
# ex5
# 格式化字符串,双引号前加f,字符串中的变量用{}包裹
name = 'Zed A. Shaw'
print(f"Let's talk about {name}.")
|
26737dc85716452f27e8b4f378da004efc8fdfd3 | agee5/Python | /Assignments/Object-Oriented/Spinning_picture.py | 493 | 3.859375 | 4 | #Aaron Gee
#11/29/2018
#program 202
#Spinning a picture by dropping it from a turning table
#############################################
def mainFn():
pic=makePicture(pickAFile())
canvas=makeEmptyPicture(1500,1500)
spinAPicture(pic,canvas)
explore(pic)
explore(canvas)
#############################################
def spinAPicture(pic,canvas):
ted = Turtle(canvas)
for i in range(0,360):
ted.drop(pic)
ted.forward(10)
ted.turn(20)
return (canvas)
|
4b05fea4e9eaf044ae742ebbeb61b49147724622 | ermidebebe/Python | /read n lines.py | 404 | 3.765625 | 4 | def main():
try:
n=int(input('n='))
except ValueError:
print('please enter enter 0 or positive integer')
main()
line=[]
file=open('financial.txt','r')
while True:
lines=file.readline()
if lines=='':
break
line.append(lines)
line=line[len(line)-n:-1]
for i in line:
print(i.strip('\n'))
main()
|
a6c7ef14d232f79dcfd9385df94127049f50bb0e | chudichen/quant_learn | /demo_learn/numpy/demo_6.py | 319 | 3.703125 | 4 | import numpy as np
"""
数组操作
"""
# 还是拿矩阵作为例子,首先来看矩阵转置:
a = np.random.rand(2, 4)
print("a: \n", a)
a = np.transpose(a)
print("a is an array, by using transpose(a): \n", a)
b = np.random.rand(2, 4)
b = np.mat(b)
print("b:\n", b)
print("b is a matrix, by using b.T: \n", b.T) |
db0ea6c28850951f89afd4db06890fd54e837524 | divyanshvinayak/My-Python-Scripts | /interpolation.py | 545 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 25 12:00:00 2019
@author: divyanshvinayak
"""
n = int(input('Enter number of points: '))
print('Enter values of x and y in space separated form')
x = [0 for i in range(n)]
y = [0 for i in range(n)]
for i in range(n):
x[i], y[i] = map(float, input().split())
X = float(input('X = '))
Y = 0
Q = [1 for i in range(n)]
for i in range(n):
for j in range(n):
if i!=j:
Q[i] *= (X-x[j])/(x[i]-x[j])
for i in range(n):
Y += y[i]*Q[i]
print('Y =', Y)
|
123be789ddd9be778625a57fd405fe96860d5851 | jeffdeng1314/Algo_Projects | /insertion.py | 724 | 4.0625 | 4 | # Insertion Sort
def non_decreasing(arr):
for i in range(1,len(arr)):
key = arr[i]
prev = i-1
while key < arr[prev] and prev >= 0:
arr[prev+1] = arr[prev]
prev = prev - 1
arr[prev+1] = key
return arr
def non_increasing(arr):
for i in range(1,len(arr)):
key = arr[i]
prev = i-1
while key > arr[prev] and prev >= 0:
arr[prev+1] = arr[prev]
prev = prev - 1
arr[prev+1] = key
return arr
def main():
a = [31,41,59,26,41,58,1]
print('Non Decreasing: ' + str(non_decreasing(a)))
print('Non Increasing: ' + str(non_increasing(a)))
if __name__ == "__main__":
main()
|
55f6be3f973575be22ad2322b2d7692a3cf31199 | NgoDinh/Data-science | /data_science_practice/python/crawler_python/githubrepos.py | 837 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 00:18:49 2017
@author: vu.ngo
"""
import requests
import json
import sys
def get_data(user_name):
len_name = len(user_name)
link = 'https://api.github.com/users/{}/repos'.format(user_name)
json_data = requests.get(link).text
data_dict = json.loads(json_data)
list_repos = []
for element in data_dict:
repos_link = element['issues_url']
start = repos_link.find(user_name) + len_name + 1
end = repos_link.find('/', start)
repos = repos_link[start:end]
list_repos.append(repos)
return list_repos
def main():
user_name = sys.argv[1]
try:
print(get_data(user_name))
except:
print("We can't find your input user_name at github")
if __name__ == "__main__":
main()
|
10555ec68cade752030035557eaec474877c81ee | ypmoraes/Curso_em_video | /ex061.py | 1,167 | 4.0625 | 4 | '''
########################################################################################
## Enunciado:Rafaca o desafio 051, lendo o primeiro termo e a razao de uma PA, ##
## mostrando os 10 primeiros termos da progressao usando a estrutura while. ##
## ##
## Criado por: Yuri Moraes ##
## Data:09/06/20 ##
## Email:yuri_ppm@hotmail.com ##
########################################################################################
'''
termo=int(input('Insira o primeiro termo da PA:'))
razao=int(input('Insira a razao desta PA:'))
c=0
pa = 0
while c <= 9:
pa = termo + (razao * c)
c = c+1
print(pa)
print('Fim')
'''Versao Guanabara
print('Gerador de PA')
print('-=' * 10)
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razao da PA: '))
termo = primeiro
cont = 1
while cont <= 10:
print('{} -> '.format(termo), end='')
termo += razao
cont += 1
print('FIM')'''
|
4d3ec5bbfd854000501c209cbbbac94e57ff5308 | schellenberg/ccc_solutions | /2021-junior/j3-secret-instructions.py | 413 | 3.671875 | 4 | #j3 - secret instructions (2021)
instructions = ""
while True:
instructions = input()
if instructions == "99999":
break
direction_sum = int(instructions[0]) + int(instructions[1])
if direction_sum % 2 == 1:
direction = "left"
elif direction_sum % 2 == 0 and direction_sum != 0:
direction = "right"
message = f"{direction} {instructions[2:]}"
print(message)
|
a60c287b85c7f18a102cc329d8557d14d4ec53f7 | sohanghanti/LearningPython | /Lists/list_methods.py | 810 | 4.25 | 4 | l1 = ['hi', 'hello', 'howdy', 'heyas', 'hi']
print(l1.index('hi'))
print('hi' in l1)
# append method
l1.append('cat')
print(l1)
# insert method
l1.insert(1, 'chicken')
print(l1)
# remove and delete
# remove when you do not know the index of a member in a list
# del when you know the index of a member in a list
l1.remove('chicken')
print(l1)
del l1[3]
print(l1)
print(l1.count('cat'))
l1.append(2)
print(l1)
l1.append((1,2,3,4))
print(l1)
l2 = l1.copy()
print(l2)
l3 = l1
print(l3)
l1[2] = 'man'
print(l1)
print(l3)
l1.pop(2)
print(l1)
l1.clear()
print(l1)
print(l3)
print(l2)
def changeMe(anyList):
# This changes a passed list into this function
anyList.append([1, 2, 3, 4])
print(anyList)
return
myList = [10, 20, 30]
changeMe(myList)
str1 = 's oan'
print(str1.split())
|
942b0ee78413c3de2e27a1dae50ed21ae971df4d | cgscreamer/UdemyProjects | /Python/whilemypythongentlyweeps.py | 116 | 3.84375 | 4 | for i in range(10):
print("i is now {}".format(i))
i=0
while i <10:
print("i is now {}".format(i))
i+=1 |
0f3566321520c98bec8565f8ece9454d8c81aef1 | 04pallav/PythonScikitLearnMiniProjects | /LinearClassificationIrisDataset.py | 4,218 | 3.78125 | 4 |
# coding: utf-8
# # Using a linear classifier to classify Iris Dataset
# In[1]:
get_ipython().magic('pylab inline')
# Import scikit-learn, numpy and pyplot
# In[2]:
import sklearn as sk
import numpy as np
import matplotlib.pyplot as plt
# Load Iris dataset
# In[3]:
from sklearn import datasets
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
print X_iris.shape, y_iris.shape
print X_iris[0], y_iris[0]
# Create training and testing partitions and standarize data.
# In[4]:
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
# Get dataset with only the first two attributes
X, y = X_iris[:,:2], y_iris
# Split the dataset into a trainig and a testing set
# Test set will be the 25% taken randomly
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
print X_train.shape, y_train.shape
# Standarize the features
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# Plot the training data.
# In[5]:
colors = ['red', 'greenyellow', 'blue']
for i in xrange(len(colors)):
px = X_train[:, 0][y_train == i]
py = X_train[:, 1][y_train == i]
plt.scatter(px, py, c=colors[i])
plt.legend(iris.target_names)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
# Fit a Linear Classification method.
# In[6]:
# create the linear model classifier
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier()
# fit (train) the classifier
clf.fit(X_train, y_train)
# print learned coeficients
print clf.coef_
print clf.intercept_
# Plot the three decision curves. Note that Class 0 is linearly separable, while Class 1 and Class 2 are not
# In[7]:
x_min, x_max = X_train[:, 0].min() - .5, X_train[:, 0].max() + .5
y_min, y_max = X_train[:, 1].min() - .5, X_train[:, 1].max() + .5
xs = np.arange(x_min,x_max,0.5)
fig, axes = plt.subplots(1,3)
fig.set_size_inches(10,6)
for i in [0,1,2]:
axes[i].set_aspect('equal')
axes[i].set_title('Class ' + str(i) + ' versus the rest')
axes[i].set_xlabel('Sepal length')
axes[i].set_ylabel('Sepal width')
axes[i].set_xlim(x_min, x_max)
axes[i].set_ylim(y_min, y_max)
sca(axes[i])
for j in xrange(len(colors)):
px = X_train[:, 0][y_train == j]
py = X_train[:, 1][y_train == j]
plt.scatter(px, py, c=colors[j])
ys = (-clf.intercept_[i]-xs*clf.coef_[i,0])/clf.coef_[i,1]
plt.plot(xs,ys,hold=True)
# Evaluate a particular instance
# In[8]:
print clf.predict(scaler.transform([[4.7, 3.1]]))
print clf.decision_function(scaler.transform([[4.7, 3.1]]))
# Measure accuracy on the training set
# In[9]:
from sklearn import metrics
y_train_pred = clf.predict(X_train)
print metrics.accuracy_score(y_train, y_train_pred)
# Measure accuracy on the testing set
# In[10]:
y_pred = clf.predict(X_test)
print metrics.accuracy_score(y_test, y_pred)
# Evaluate results using Precision, Recall and F-score, and show the confusion matrix
# In[11]:
print metrics.classification_report(y_test, y_pred, target_names=iris.target_names)
print metrics.confusion_matrix(y_test, y_pred)
# Create a new classifier: a pipeline of the standarizer and the linear model. Measure the cross-validation accuracy.
# In[12]:
from sklearn.cross_validation import cross_val_score, KFold
from sklearn.pipeline import Pipeline
# create a composite estimator made by a pipeline of the standarization and the linear model
clf = Pipeline([
('scaler', StandardScaler()),
('linear_model', SGDClassifier())
])
# create a k-fold croos validation iterator of k=5 folds
cv = KFold(X.shape[0], 5, shuffle=True, random_state=33)
# by default the score used is the one returned by score method of the estimator (accuracy)
scores = cross_val_score(clf, X, y, cv=cv)
print scores
# Calculate the mean and standard error of cross-validation accuracy
# In[13]:
from scipy.stats import sem
def mean_score(scores):
"""Print the empirical mean score and standard error of the mean."""
return ("Mean score: {0:.3f} (+/-{1:.3f})").format(
np.mean(scores), sem(scores))
print mean_score(scores)
# In[13]:
|
cdaa5c967030ae1fd83a2775f3c14cb15cc5fc61 | lihujun101/LeetCode | /DataStructureBinaryTree/L116_populating-next-right-pointers-in-each-node.py | 1,196 | 3.75 | 4 | class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# 方法:自顶向下
# 1、根据格式要求,应使用广度搜索,但是广度不大适合递归。这里使用的是先序遍历
# 2、每次走到根节点,node.left.next = node.right,node.right.next = node.next.left(right到底后,next指向上一个节点的左节点)
def connect(self, root):
if not root:
return None
elif root.left and root.right:
root.left.next = root.right
if root.next:
if root.next.left :
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
if __name__ == '__main__':
a1 = TreeLinkNode(1)
a2 = TreeLinkNode(2)
a3 = TreeLinkNode(3)
a4 = TreeLinkNode(4)
a5 = TreeLinkNode(5)
a6 = TreeLinkNode(6)
a7 = TreeLinkNode(7)
# a5 = TreeNode(5)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
a3.left = a6
a3.right = a7
s = Solution()
m = s.connect(a1)
print(m)
|
bf5febe52da61f3d44206bd83a7384e8402d046f | XyK0907/for_work | /LeetCode/Offer/对称的二叉树.py | 783 | 3.796875 | 4 | """
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
示例1
输入
{8,6,6,5,7,7,5}
返回值
true
示例2
输入
{8,6,9,5,7,7,5}
返回值
false
"""
class Solution:
def isSymmetrical(self, pRoot):
if not pRoot:
return True
return self.isMirror(pRoot.left, pRoot.right)
def isMirror(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
outside = self.isMirror(left.left, right.right)
inside = self.isMirror(left.right, right.left)
return outside and inside
|
5e3f884f91c81434b544b4b98f4d469973df2e1d | ashutosh82348/Jarvis | /modules/speak_listen.py | 874 | 3.640625 | 4 | from gtts import gTTS
import speech_recognition as sr
import os
def listen():
# Speech to text
r = sr.Recognizer() # initialize recognizer
with sr.Microphone() as source: # mention source it will be either Microphone or audio files.
print("Speak: ")
audio = r.listen(source) # listen to the source
try:
querry = r.recognize_google(
audio
) # use recognizer to convert our audio into text part.
return querry.lower()
except:
response = "I don't understand"
return response
def speak(response, language, output_file):
# Passing the text and language to the engine
text = gTTS(text=response, lang=language, slow=False)
# Saving the converted audio in a mp3 file in .cache
text.save(output_file)
# Playing the converted file
os.system(f"play {output_file}")
|
bc62b30be465777bf38b553ff881892ed458c28d | etherware-novice/allprojects | /python/genexp.py | 702 | 3.625 | 4 | import textwrap
from itertools import zip_longest
def split_bar(right, left):
txt_width = 10
l_d = ""
for l, r in zip(left, right):
r = textwrap.fill(r, width=txt_width).splitlines()
l = textwrap.fill(l, width=txt_width).splitlines()
for x, y in zip_longest(l, r, fillvalue=""):
yield f"{x.rjust(txt_width)} ! {y.ljust(txt_width)}"
right = ["stringgggggggg", "str2", "*"]
left = ["this is a very long string for testing", "user", "#3"]
for x in split_bar(left, right):
pass
#print(x)
l0 = "time"
l1 = "chn"
l2 = "usr"
l_disp = f"{l0} ! {l1.center(10)} ! {l2}"
r = "a str"
out = f" {l_disp.rjust(30)} ! {r.ljust(20)}"
print(out)
|
29df44aef5346ca8b238771bb736e8ea46b3d046 | dgranillo/Projects | /Classic Algorithms/collatz.py | 901 | 4.46875 | 4 | #!/usr/bin/env python2.7
"""
Collatz Conjecture - Start with a number n > 1. Find the number of steps it
takes to reach 1 using the following process. If 'n' is even, divide by 2. If
'n' is odd, multiply by 3 and add 1.
Author: Dan Granillo <dan.granillo@gmail.com>
"""
class CollatzNumber(object):
steps = 0
def __init__(self, num):
self.num = num
def num_sort(self):
while True:
if self.num > 1:
self.steps += 1
if self.num % 2 == 0:
self.even_func(self.num)
elif self.num % 2 == 1:
self.odd_func(self.num)
else:
break
print self.steps
def even_func(self, i):
self.num = i / 2
def odd_func(self, i):
self.num = i * 3 + 1
if __name__ == '__main__':
n = CollatzNumber(int(raw_input("Enter number: ")))
n.num_sort()
|
99afa3a2716e241b7c5dbeb885507bde2d03d549 | ushanirtt55/python | /Python Basics/Python_proj/codewars/6u/X_pattern.py | 120 | 3.65625 | 4 | def pattern(n):
for i in range(n,0,-1):
print " "*(n-i) + str(i) + " "*(i) + str(i) + " "*(n-i)
pattern(5)
|
16b5e7c44f72823d272b51a896c5794623b38f37 | johanloones/ga-learner-dsmp-repo | /Project-Clustering-Customer-Segmentation/code.py | 4,675 | 3.9375 | 4 | # --------------
# import packages
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Load Offers
offers=pd.read_excel(path,sheet_name=0)
# Load Transactions
transactions=pd.read_excel(path,sheet_name=1)
#Add a new column 'n' to transactions and set the value as 1 across all observations.
#This is done to identify customers who have purchased a particular offer
transactions['n']=1
# Merge dataframes
df=offers.merge(right=transactions)
# Look at the first 5 rows
display(offers.head())
display(transactions.head())
df.head()
# --------------
#Create a pivot table matrix using on df with arguments
#index='Customer Last Name', columns='Offer #' and values='n'
matrix=pd.pivot_table(data=df,index='Customer Last Name',columns=['Offer #'],values='n' )
#Since every customer did not purchase all the offers
#Fill in the missing values by 0s.
matrix.fillna(0,inplace=True)
#The last names of customers are on the index; translate it to a column using .reset_index(inplace=True)
#so that it is a column now
matrix.reset_index(inplace=True)
#Print out the first five rows of matrix now
display(matrix.head())
# --------------
# import packages
from sklearn.cluster import KMeans
#Initialize a KMeans object cluster
cluster=KMeans(n_clusters=5,init='k-means++',max_iter=300,n_init=10,random_state=0)
#Create a new column 'cluster' in the dataframe matrix where you store the cluster centers for every observation from matrix.
matrix['cluster']=cluster.fit_predict(matrix[matrix.columns[1:]])
#Print out first five rows using .head() method of matrix
display(pd.DataFrame(cluster.cluster_centers_))
display(matrix.head())
# --------------
from sklearn.decomposition import PCA
#Initialize a PCA object pca using PCA(n_components=2, random_state=0)
pca=PCA(n_components=2,random_state=0)
#Create a new column 'x' for matrix dataframe which denotes the X co-ordinates of every
#observation in decomposed form using .fit_transform(matrix[matrix.columns[1:])[:,0] method of pca
matrix['x']=pca.fit_transform(matrix[matrix.columns[1:]])[:,0]
#Similarly create a new column 'y' which denotes the decomposed Y-co-ordinates of every observation
matrix['y']=pca.fit_transform(matrix[matrix.columns[1:]])[:,1]
#Create a new dataframe clusters containing the column numbers 'Customer Last Name','cluster','x','y'.
clusters=matrix[['Customer Last Name','cluster','x','y']]
#Visualize clusters using scatter plot
clusters.plot.scatter(x='x',y='y',c='cluster',colormap='viridis')
# --------------
#First merge dataframes clusters and transactions on Customer Last Name column and save it as data
data=clusters.merge(right=transactions)
#Merge offers and data and save it as data
data=data.merge(right=offers)
#Initialize an empty dictionary champagne
champagne={}
counts_max=0
#Iterate using a for loop over the cluster numbers
for i in data['cluster'].sort_values(ascending=False).unique():
print('iterator / cluster',i)
#Create a new dataframe new_df
new_df=data[data['cluster']== i]
#Initialize a variable counts where you will sort the counts for every value of 'Varietal' column of new_df in a descending order
counts=new_df['Varietal'].value_counts(ascending=False)
counts_max=counts.max()
print('First Entry counts',counts[0],'for iterator / cluster',i)
#Now you will check if the first entry of counts index is 'Champagne'.
if (counts.index[0]=='Champagne'):
print('champagne count',counts[0],'iterator / cluster',i)
print('===='*20)
champagne.update({i:counts[0]})
#Save the cluster number as cluster_champagne with the maximum value.
cluster_champagne=max(champagne,key=champagne.get)
#Print out cluster_champagne to see which cluster purchases the most champagne!
print('cluster champagne',cluster_champagne)
# --------------
#Create an empty dictionary discount
discount={}
#Iterate over all the clusters using a for loop and create a dataframe new_df for every cluster
#within the loop
for i in data['cluster'].sort_values(ascending=False).unique():
new_df=data[data['cluster']== i]
#Calculate the average percentage of discounts for new_df by first adding all the discount values
#and then dividing the total by total number of observations of new_df. Store it in counts
counts=new_df['Discount (%)'].sum()/len(new_df)
#Add the cluster number as key and its value counts as value to dictionary discount
discount.update({i:counts})
#Now find out the cluster number with the maximum average discount percentage from cluster_discount
#and save it as cluster_discount
cluster_discount=max(discount,key=discount.get)
print(cluster_discount)
|
8166bf0a2543a595a57a32f3ec79de05aed040a0 | Ayushchaudhary-Github/Python_Practice | /Crash Course Python/week-2/Functions/Code Style.py | 584 | 4.125 | 4 | """
This function to calculate the area of a rectangle is not very readable.
Can you refactor it, and then call the function to calculate the area with base of 5 and height of 6?
Tip: a function that calculates the area of a rectangle should probably be called rectangle_area,
and if it's receiving base and height, that's what the parameters should be called.
"""
# Question:
"""
def f1(x, y):
z = x*y # the area is base*height
print("The area is " + str(z))
"""
# Answer:
def rectangle_area(base,height):
area=base*height
print("The area is",area)
rectangle_area(5,6) |
7d88a195b67ef2f2190d4b711289bb8f14edbd8f | lovingstr/my_text | /NH4HCO3.py | 298 | 3.625 | 4 | from random import shuffle
n = 6 # 人数
list1 = [x for x in range(1, n + 1)]
list_people = ["狼", "狼", "预言", "猎人", "女巫", "白狼"] # 神职
shuffle(list_people)
result = {}
for x in range(n):
result[list1[x]] = list_people[x]
print(result)
##
##
quit()
|
66bb8957a12492e175fd1a9ef96f3a98fbcf7a7b | joelgarzatx/portfolio | /python/Lesson09_Homework/src/inputter.py | 412 | 3.59375 | 4 | f = open('v:/inputter.txt','a')
f.close()
filetext = open('v:/inputter.txt','r').read()
print(filetext)
string_input = 'Enter text: '
while True:
inp = input(string_input)
if inp == '':
break
else:
f = open('v:/inputter.txt','a')
f.write(inp)
f.close()
filetext = open('v:/inputter.txt','r').read()
print(filetext)
|
11f1e11ef13a958404a504050a98e3f81c219717 | lucasbflopes/codewars-solutions | /6-kyu/grouped-by-commas/python/solution.py | 195 | 3.75 | 4 | def group_by_commas(n):
s = ''
for i, d in enumerate(str(n)[::-1]):
if i % 3 == 0 and i != 0:
s += ',' + d
else:
s += d
return s[::-1]
|
8386bc4727f20f5a825e0361dcaf978ca21cdc46 | ghostghost664/CP3-Chinnawat-Pitisuwannarat | /Exercise5_2_Chinnawat_P.py | 103 | 3.640625 | 4 | s = int(input("Distance(km.) ="))
t = int(input("Time(hr.) ="))
v = int(s/t)
print(v, "km/hr")
|
f896e1c95a347c2e645b4502919231387abdb1b6 | abhiaswale/Python | /practice.py | 442 | 3.5625 | 4 | user_info2={
'name':'Abhi',
'age':24,
'Fav_movies':['inception','intersteller'],
'Fav_songs':['understanding','hanging tree']
}
# if ['inception','intersteller'] in user_info2.values():
# print('present')
# else:
# print('not present')
# for i in user_info2.values():
# print(i)
# v1=user_info2.values()
# print(v1)
for i in user_info2.items():
# print(f"key is {i} and value is {j}")
print(i)
|
fe2c68a6b18c169b2060101e34630bc1508c8209 | DuffmanBE/BoredGame-Server | /player.py | 1,077 | 3.71875 | 4 | #!/usr/bin/env python
CHARACTERS = ["char1", "char2", "char3", "char3", "char5"]
AVAILABLE_CHARACTERS = CHARACTERS[:]
def makePlayer(character):
global AVAILABLE_CHARACTERS
if character in AVAILABLE_CHARACTERS:
AVAILABLE_CHARACTERS.remove(character)
return {'player' : True , 'character' : character , 'points' : 0 , 'items' : list() }
else:
return False
def getAvailableCharactgers():
global AVAILABLE_CHARACTERS
return AVAILABLE_CHARACTERS
def playerDecrPoints(player):
player['points'] = player['points']-1
def playerIncrPoints(player):
player['points'] = player['points']+1
def playerAddPoints(player, p):
player['points'] = player['points']+p
def playerAddItem(player ,item):
player['items'].append(item)
def playerUseItem(player ,item):
if item in player['items']:
player['items'].remove(item)
return True
else:
return False
def simpleTest():
p = makePlayer("roodkapje")
incrPoints(p)
addItem(p ,"CuveeDesTrolls")
addItem(p ,"MacChouffe")
addItem(p ,"CuveeDesTrolls")
print p
useItem(p ,"CuveeDesTrolls")
print p
#simpleTest() |
bbba2cb900535fed90c46d8315e61ffff50963cf | UdeM-LBIT/polytomy-solver-web | /cgi-bin/utils/TreeLib/memorize.py | 933 | 3.828125 | 4 | import collections
import functools
class memorize(object):
"""Cache function output when it's called and return it
later when the same function is called with the same input,
in this case, memorize use a hash to determine value to reevalute
"""
def __init__(self, function):
self.function=function
self.cache={}
def __call__(self, hash, *args, **kwargs):
"""Call to memorize, (as decorator)"""
if hash in self.cache:
return self.cache[hash]
elif not isinstance(hash, collections.Hashable) or hash is None:
#hash is None or uncachable
return self.function(*args, **kwargs)
else:
output = self.function(*args, **kwargs)
self.cache[hash]=output
return output
def __repr__(self):
"""Return cached data"""
for hash, data in self.cache:
print hash, '=============>\n', data
def __get__(self, obj, objtype):
"""Instance methods support"""
return functools.partial(self.__call__,obj ) |
b4b7831ecc5bd2e71800bcf5d36bd7d046a84763 | danbros/py_things | /src/find_url.py | 1,994 | 3.546875 | 4 | #!/usr/bin/env python3
# @author: danbros
"""
Find all links in a url
"""
import re
import urllib.request
def mod_page(x_url):
"""Open a page with a modified user-agent
Args:
x_url: A url in 'string' format with http://
"""
#create a list
mod_headers = {}
#mod_headers[user-agent] now is OS X Safari 9.1
mod_headers['User-Agent'] = "Mozilla / 5.0 (Maacintosh; Intel Mac OS X 10_10_5) AppleWebKit / 601.7.7 (KHTML, como o Gecko) Versão / 9.1.2 Safari / 601.7.7"
#assign a request of a url('x_url') with the header user-agent modified('mod_headers') to 'req'
mod_req = urllib.request.Request(x_url, headers = mod_headers)
#assign the response of 'mod_req' to the variable 'page'
page = urllib.request.urlopen(mod_req)
return page
x_url = input('\nEnter a url (example: "https://www.google.com"): ')
#x_url = "https://www.google.com"
#assign page with function mod_page
page = mod_page(x_url)
#assign source with source of page converted binary to str
source = str(page.read())
#re to find links in source
links = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', source)
print(*links, sep='\n')
#Create a file with links
#obj_file = open('url_list.txt', 'w')
#for link in links:
# obj_file.write(link + '\n')
#obj_file.close()
#Source:
#https://www.pythonforbeginners.com/code-snippets-source-code/regular-expression-re-findall/
#https://pythonprogramming.net/urllib-tutorial-python-3/
#Problems:
#regular expression for string:
#https://docs.python.org/3/howto/regex.html#regex-howto
#https://stackoverflow.com/questions/839994/extracting-a-url-in-python
#print list:
#https://stackoverflow.com/questions/22556449/print-a-list-of-space-separated-elements-in-python-3
#string file vs binary file:
#https://stackoverflow.com/questions/5618988/regular-expression-parsing-a-binary-file
#binary to string:
#https://stackoverflow.com/questions/606191/convert-bytes-to-a-string |
cc7a059a33c4429fd5bec83304c0d95882d492e3 | atreids/pyCalculator | /calculator.py | 1,352 | 4.0625 | 4 |
#This function adds 2 numbers
def add(cur_num, add_amount):
cur_num += add_amount
return cur_num
#This functions subtracts two numbers
def subtract(cur_num, sub_amount):
cur_num -= sub_amount
return cur_num
def multiple(cur_num, mul_amount):
cur_num *= mul_amount
return cur_num
def divide(cur_num, div_amount):
cur_num /= div_amount
return cur_num
def square(cur_num):
cur_num **= 2
return cur_num
def exit():
print("Exiting...")
return False
running = True
while running == True:
print("""
Please enter operation:
1. Add
2. Subtract
3. Multiple
4. Divide
0. Exit
""")
operation = int(input("Entry:"))
if operation == 0:
running = exit()
break
num1 = float(input("Please enter number 1: "))
num2 = float(input("Please enter number 2: "))
if operation == 1:
print(str(num1) + " + " + str(num2) + " = " + str(add(num1,num2)))
elif operation == 2:
print(str(num1) + " - " + str(num2) + " = " + str(subtract(num1,num2)))
elif operation == 3:
print(str(num1) + " * " + str(num2) + " = " + str(multiple(num1,num2)))
elif operation == 4:
print(str(num1) + " / " + str(num2) + " = " + str(divide(num1,num2)))
else:
print("Invalid input")
|
243b0e8fd19ab8bbf1ea4d5395574b9203df1dc9 | CSToWEB/test1 | /decorator.py | 679 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import time, functools
def metric(fn):
@functools.wraps(fn)
def printtime(*args,**kw):
t0=time.time()
fn(*args,**kw)
t1=time.time()
t=(t1-t0)*1000
print('%s executed in %f ms' % (fn.__name__,t))
return fn(*args,**kw)
return printtime
# 测试
@metric #相当于是 fast=metric(fast)
def fast(x, y):
#time.sleep(0.0012)
return x + y;
@metric
def slow(x, y, z):
#time.sleep(0.1234)
return x * y * z;
f = fast(11, 22)
print(f)
s = slow(11, 22, 33)
print(s)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
else:
print('测试成功!')
|
3910bb9e7286f932ace4b13dadb6a2671f8c4839 | VamsiKrishna04/Hacktoberfest-2021 | /FMoment_of_force.py | 10,239 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 13:12:18 2019
@author: Suyash
"""
def Moment_of_force():
#qs1,qs2,qs3 for simple force qs1=0 then qs2 will run else qs3 will run
# (m for magnitude) and (M for moment) and (Ch=Choice)
import math
# sum_Fx=0 #initialization
# sum_Fy=0 #initialization
angle=0 #initialization
M1=0 #initialization
# M2x=0 #initialization
M2y=0 #initialization
C3=0 #initialization
M4=0 #initialization
M5=0 #initialization
M6=0 #initialization
M7=0 #initialization
MF=0 #initialization
MF1=0 #initialization
MF2=0 #initialization
MF3=0 #initialization
MF4=0 #initialization
MF5=0 #initialization
MF6=0 #initialization
MF7=0 #initialization
# cos=math.cos #assigning for simplification
sin=math.sin #assigning for simplification
pi=math.pi #assigning for simplification
QS1=int(input("Please enter the total number of elements in the force system: "))
print("\nPlease enter the following numerals for the forces or moment as follows: ")
print("\n1=Simple force \t\t\t\t2=Inclined force \n3=Couple \t\t\t\t4=Rectangular Lamina\n5=Uniformly Distributed Load \t\t6=Triangular lamina(UVL) \n7=Trapezoidal Lamina(UVL)")
for i in range(0,QS1):
Ch=int(input("Please enter choice from the given numerals of your chosen corresponding element: "))
#1. SIMPLE FORCE
if Ch==1:
m1=float(input("Please enter the magnitude in newton: "))
D1=float(input("Please enter the distance: "))
Q1=int(input("Please enter 0 if force is horizontal and 1 if Vertical: "))
if Q1==0:
Q11=int(input("Please enter 0 if force is in right direction and 1 if left: "))
else:
Q12=int(input("Please enter 0 if force is in up direction and 1 if down: "))
if Q1==0 and Q11==0:
F1=m1*1
elif Q1==0 and Q11==1:
F1=m1*(-1)
elif Q1==1 and Q12==0:
F1=m1*1
elif Q1==1 and Q12==1:
F1=m1*(-1)
M1=F1*D1
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if M1>0 and cra==0:
M1=M1*1
elif M1<0 and cra==0:
M1=M1*(-1)
elif M1>0 and cra==1:
M1=M1*(-1)
elif M1<0 and cra==1:
M1=M1*1
MF1=MF1+M1
print(MF1)
#2. INCLINED FORCE
elif Ch==2:
m2=float(input("Please enter the magnitude in newton: "))
D2=float(input("Please enter the distance: "))
A2=float(input("Please enter the angle in degree: "))
Quad=int(input("Please enter the Quadrant in which the force lie: "))
xry=int(input("Please enter 0 if the angle is with x-axis and 1 if y-axis: "))
if Quad == 1:
if xry==0:
angle=A2
else :
angle=90-A2
elif Quad==2 :
if xry==0:
angle=180-A2
else :
angle=90+A2
elif Quad==3:
if xry==0:
angle=180+A2
else :
angle=270-A2
elif Quad==4:
if xry==0:
angle=360-A2
else :
angle=270+A2
# Ax=m2*cos((pi/180)*angle)
Ay=m2*sin((pi/180)*angle)
# M2x=Ax*D2 #statements for finding M2x, but M2x=0 due to principle of transmissibility.
# M2x=round(M2x)
# print(M2x)
# MF=MF+M2x
# print(MF)
M2y=Ay*D2
M2y=round(M2y,2)
# if cra==0:
# M2y=M2y*1
# else:
# M2y=M2y*(-1)
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if M2y<0 and cra==0:
M2y=M2y*(-1)
elif M2y>0 and cra==0:
M2y=M2y*1
elif M2y>0 and cra==1:
M2y=M2y*(-1)
elif M2y<0 and cra==1:
M2y=M2y*1
MF2=MF2+M2y
# print(M2y)
print(MF2)
#3. COUPLE #(C- capital) & (Couple = Force*distance) "so no need of multiplying with distance"
elif Ch==3:
C3=float(input("Please enter the magnitude of couple: ")) #(in KNm or Nm)
Q3=int(input("Please enter 0 if couple is clockwise and 1 if anticlockwise: "))
if Q3==0:
C3=C3*1
else:
C3=C3*(-1)
# print(C3)
MF3=MF3+C3
print(MF3)
#4. RECTANGULAR LAMINA (C6=centroid of Rectangular Lamina) (S6=side residing on the rod)
#("For centroid of rectangle the side of rectangle to be taken is the one residing on the rod" )
elif Ch==4:
L4=float(input("Please enter the length of Rectangular Lamina: "))
B4=float(input("Please enter the breadth of Rectangular Lamina: "))
A4=L4*B4
D4=float(input("Please enter the distance of Rectangular Lamina from one end of the rod: "))
S4=float(input("Please enter the magnitude of the side residing on the rod: ")) #it may be L6/B6
C4=S4/2
D41=D4+C4
M4=A4*D41
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if cra==0 and M4>0:
M4=M4*1
elif cra==0 and M4<0:
M4=M4*(-1)
elif cra==1 and M4<0:
M4=M4*1
elif cra==1 and M4>0:
M4=M4*(-1)
# print(M4)
MF4=MF4+M4
print(MF4)
#5. (UDL-UNIFORMLY DISTRIBUTED LOAD)
elif Ch==5:
m5=float(input("Please enter the magnitude of force acting per unit length of UDL: ")) #(in KN/m or N/m)
d5=float(input("Please enter the distance over which the UDL is spread: "))
D5=float(input("Please enter the distance of UDL from one end of the rod: "))
m51=m5*d5
C5=d5/2
D51=D5+C5
M5=m51*D51
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if cra==0 and M5>0:
M5=M5*1
elif cra==0 and M5<0:
M5=M5*(-1)
elif cra==1 and M5<0:
M5=M5*1
elif cra==1 and M5>0:
M5=M5*(-1)
# print(M5)
MF5=MF5+M5
print(MF5)
#6. (UVL-TRIANGULAR LAMINA)
elif Ch==6:
B6=float(input("Please enter the magnitude of base of triangular lamina: "))
H6=float(input("Please enter the magnitude of height of triangular lamina: "))
D6=float(input("Please enter the distance of the triangular lamina from one end of the rod: "))
Q6=int(input("Please enter 0 if toe of triangle is towards left and 1 if towards right: "))
if Q6==0:
C6=0.6666666667*B6
else:
C6=B6-(0.6666666667*B6)
C6=round(C6,2)
D61=D6+C6
A6=0.5*B6*H6
m6=A6 #in(N or KN)
M6=m6*D61
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if cra==0 and M6>0:
M6=M6*1
elif cra==0 and M6<0:
M6=M6*(-1)
elif cra==1 and M6>0:
M6=M6*(-1)
elif cra==1 and M6<0:
M6=M6*1
# print(M6)
MF6=MF6+M6
print(MF6)
#7. (UVL-TRAPEZOIDAL LAMINA) #(C5=centroid of Trapezoidal Lamina)
elif Ch==7:
A7=float(input("Please enter the magnitude of base(a) of Trapezoidal Lamina: "))
B7=float(input("Please enter the magnitude of base(b) of Trapezoidal lamina: "))
H7=float(input("Please enter the magnitude of height of Trapezoidal lamina: "))
D7=float(input("Please enter the distance of the triangular lamina from one end of the rod: "))
A71=0.5*(A7+B7)*H7
C7=((B7+2*A7)/(B7+A7))*(0.333333333*H7)
C71=(round(C7,3))
D71=D7+C71
M7=round(A71*D71,3)
# (for the direction of forces conditions are given below)
Q7=int(input("Please enter 0 if forces in Trapezoidal Lamina are horizontal and 1 if Vertical: "))
if Q7==0:
Q71=int(input("Please enter 0 if forces are in right direction and if 1 left: "))
else:
Q72=int(input("Please enter 0 if forces are in up direction and if 1 down: "))
if Q7==0 and Q71==0:
M7=M7*1
elif Q7==0 and Q71==1:
M7=M7*(-1)
elif Q7==1 and Q72==0:
M7=M7*1
elif Q7==1 and Q72==1:
M7=M7*(-1)
cra=int(input("Check and answer 0 if force is Clockwise and 1 if Anticlockwise: "))
if cra==0 and M7>0:
M7=M7*1
elif cra==0 and M7<0:
M7=M7*(-1)
elif cra==1 and M7<0:
M7=M7*1
elif cra==1 and M7>0:
M7=M7*(-1)
# print(M7)
MF7=MF7+M7
print(MF7)
MF=MF1+MF3+MF2+MF4+MF5+MF6+MF7
print("Momment of Force with respect to one end : ",MF)
|
7091db0947e84e60023d465406e5db3d49df1030 | xwang322/Coding-Interview | /uber/uber_ood/LC380InsertDeleteGetRandomO(1).py | 995 | 3.859375 | 4 | class RandomizedSet(object):
def __init__(self):
self.stack = []
self.dictionary = {}
def insert(self, val):
if val in self.dictionary:
return False
else:
self.stack.append(val)
self.dictionary[val] = len(self.stack)-1
return True
def remove(self, val):
if val not in self.dictionary:
return False
else:
temp = self.stack[-1]
position = self.dictionary[val]
self.dictionary[temp] = position
self.stack[position] = temp
self.stack.pop()
self.dictionary.pop(val, 0)
return True
def getRandom(self):
return self.stack[random.randint(0, len(self.stack)-1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
|
ac3d269ea56060205c3408fd0fdee0c26c4d6bf7 | Slyvred/Bad-Text-Encryptor | /Bad_Text_Encryptor.py | 1,560 | 4.25 | 4 | import os
alpha = " ',.;:/\!?@#(){}[]°\"=+-_*%0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzàéêëôîùç" # This is what characters we can accept and return in our encrypted cipher
def encrypt(text, key):
for i in range(len(text)):
cipher_text = ""
for letter in text:
if (alpha.find(letter) + key) >= len(alpha):
cipher_text += alpha[(alpha.find(letter) + key) - len(alpha)]
else:
cipher_text += alpha[alpha.find(letter) + key]
text = cipher_text
return cipher_text
def decrypt(text, key):
for i in range(len(text)):
plain_text = ""
for letter in text:
if (alpha.find(letter) - key) >= len(alpha):
plain_text += alpha[(alpha.find(letter) - key) - len(alpha)]
elif (alpha.find(letter) - key) < 0:
plain_text += alpha[(alpha.find(letter) - key) + len(alpha)]
else:
plain_text += alpha[alpha.find(letter) - key]
text = plain_text
return plain_text
def main():
input_msg = input("Enter some text: ")
choice = int(input("\n(1) Encrypt\n(2) Decrypt\nChoose an option (1/2): "))
output = ""
key = len(input_msg) % len(alpha)
if choice == 1:
output = encrypt(input_msg, key)
elif choice == 2:
output = decrypt(input_msg, key)
print(f"\nThe processed text is: \"{output}\"\n")
os.system('pause')
if __name__ == "__main__":
main()
|
e5881309e4a52e6ab35ab120e2640b01757a4460 | bikram947/sorting-comparison | /bubble sort.py | 1,677 | 3.890625 | 4 | import matplotlib.pyplot as plt
import time
from random import randint
#BUBBLE SORT FUNCTION
def bubble_sort(arr,n):
for i in range(n-1):
for j in range(n-i-1):
if(arr[j]>arr[j+1]):
t=arr[j]
arr[j]=arr[j+1]
arr[j+1]=t
#FOR RANDOM DATA
arr_no_of_data=[]
arr_time=[]
for i in range(1,11):
arr_nos=[]
for j in range(i*100):
arr_nos.append(randint(0,i*100))
start_time=time.time()
bubble_sort(arr_nos,i*100)
end_time=time.time()
arr_no_of_data.append(i*100)
arr_time.append(int((end_time-start_time)*1000))
plt.plot(arr_no_of_data,arr_time,marker='o', markersize=5, label='random data')
#FOR INCREASING DATA
arr_no_of_data=[]
arr_time=[]
for i in range(1,11):
arr_nos=[]
for j in range(i*100):
arr_nos.append(j)
start_time=time.time()
bubble_sort(arr_nos,i*100)
end_time=time.time()
arr_no_of_data.append(i*100)
arr_time.append(int((end_time-start_time)*1000))
plt.plot(arr_no_of_data,arr_time,marker='o', markersize=5, label='increasing data')
#FOR DECREASING DATA
arr_no_of_data=[]
arr_time=[]
for i in range(1,11):
arr_nos=[]
for j in range(i*100):
arr_nos.append(i*100-j)
start_time=time.time()
bubble_sort(arr_nos,i*100)
end_time=time.time()
arr_no_of_data.append(i*100)
arr_time.append(int((end_time-start_time)*1000))
plt.plot(arr_no_of_data,arr_time,marker='o', markersize=5, label='decreasing data')
#PLOTTING
plt.xlabel('No of Data')
plt.ylabel('Time in milisec')
plt.title('Bubble_Sort')
plt.legend()
plt.show()
|
d500cd6ff09c0db74398a325db5ad9f99568d2f9 | LeqiaoP1/PythonBeginner | /src/introduction_to_computer_science_and_programming/assn04/ps4.py | 6,610 | 4 | 4 | # Problem Set 4
# Name:
# Collaborators:
# Time:
#
# Problem 1
#
def nestEggFixed(salary, save, growthRate, years):
"""
- salary: the amount of money you make each year.
- save: the percent of your salary to save in the investment account each
year (an integer between 0 and 100).
- growthRate: the annual percent increase in your investment account (an
integer between 0 and 100).
- years: the number of years to work.
- return: a list whose values are the size of your retirement account at
the end of each year.
"""
records = [0.0 for y in range(years)]
if (len(records) > 0):
records[0] = salary*save*0.01
for y in range(1, years):
records[y] = records[y-1]*(1.0+0.01*growthRate) + salary*save*0.01
return records
def testNestEggFixed():
salary = 10000
save = 10
growthRate = 15
years = 5
savingsRecord = nestEggFixed(salary, save, growthRate, years)
print savingsRecord
# Output should have values close to:
# [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]
savingsRecord = nestEggFixed(salary, save, growthRate, 0)
print savingsRecord
# Output should be empty list []
savingsRecord = nestEggFixed(salary, save, 0, 2)
print savingsRecord
# Output should be empty list [1000.0, 2000.0]
savingsRecord = nestEggFixed(salary, 0, 100, 2)
print savingsRecord
# Output should be empty list [0.0, 0.0]
#
# Problem 2
#
def nestEggVariable(salary, save, growthRates):
"""
- salary: the amount of money you make each year.
- save: the percent of your salary to save in the investment account each
year (an integer between 0 and 100).
- growthRate: a list of the annual percent increases in your investment
account (integers between 0 and 100).
- return: a list of your retirement account value at the end of each year.
"""
num_years = len(growthRates)
records = [ 0.0 for y in range(num_years) ]
if (len(records) > 0):
records[0] = salary*save*0.01
for y in range(1, num_years):
records[y] = records[y-1]*(1.0+0.01*growthRates[y]) + salary*save*0.01
return records
def testNestEggVariable():
salary = 10000
save = 10
growthRates = [3, 4, 5, 0, 3]
savingsRecord = nestEggVariable(salary, save, growthRates)
print savingsRecord
# Output should have values close to:
# [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]
savingsRecord = nestEggVariable(salary, save, [])
print savingsRecord
# Output should be empty list []
savingsRecord = nestEggVariable(salary, save, [3])
print savingsRecord
# Output should be empty list [1000.0]
#
# Problem 3
#
def postRetirement(savings, growthRates, expenses):
"""
- savings: the initial amount of money in your savings account.
- growthRate: a list of the annual percent increases in your investment
account (an integer between 0 and 100).
- expenses: the amount of money you plan to spend each year during
retirement.
- return: a list of your retirement account value at the end of each year.
"""
num_years = len(growthRates)
records = [0.0 for y in range(num_years)]
if (num_years > 0):
records[0] = savings*(1 + 0.01*growthRates[0]) - expenses
for y in range(1, num_years):
records[y] = records[y-1]*(1 + 0.01*growthRates[y]) - expenses
return records
def testPostRetirement():
savings = 100000
growthRates = [10, 5, 0, 5, 1]
expenses = 30000
savingsRecord = postRetirement(savings, growthRates, expenses)
print savingsRecord
# Output should have values close to:
# [80000.000000000015, 54000.000000000015, 24000.000000000015,
# -4799.9999999999854, -34847.999999999985]
savingsRecord = postRetirement(savings, [], expenses)
print savingsRecord
#
# Problem 4
#
def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
epsilon):
"""
- salary: the amount of money you make each year.
- save: the percent of your salary to save in the investment account each
year (an integer between 0 and 100).
- preRetireGrowthRates: a list of annual growth percentages on investments
while you are still working.
- postRetireGrowthRates: a list of annual growth percentages on investments
while you are retired.
- epsilon: an upper bound on the absolute value of the amount remaining in
the investment fund at the end of retirement.
"""
if (len(postRetireGrowthRates) == 0):
return -1 # in this case, definition "expense" has no practical meaning
savings_records = nestEggVariable(salary, save, preRetireGrowthRates);
total_of_savings = savings_records[-1]
print 'total of savings:', total_of_savings
# binary search algorithms
# initial right end: (all savings)
exp_right = total_of_savings
# initial left end : 0$
exp_left = 0.0
guess = (exp_right + exp_left)/2.0
remains = postRetirement(total_of_savings, postRetireGrowthRates, guess)
diff = epsilon - remains[-1]
while ( diff < 0.0 or diff >= 0.01 ): # if not limited to the upper bound
if (diff < 0.0 ):
exp_left = guess
else:
exp_right = guess
new_guess = (exp_left + exp_right)/2.0
if (abs(new_guess - guess) < 0.001):
break
else:
guess = new_guess
remains = postRetirement(total_of_savings, postRetireGrowthRates, guess)
diff = epsilon - remains[-1]
print 'remaining of fund:', remains[-1]
return guess
def testFindMaxExpenses():
salary = 10000
save = 10
preRetireGrowthRates = [3, 4, 5, 0, 3]
postRetireGrowthRates = [10, 5, 0, 5, 1]
epsilon = .01
expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
postRetireGrowthRates, epsilon)
print expenses
# Output should have a value close to:
# 1229.95548986
expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
[0], epsilon)
print expenses
# Output should be a value close to the maximal saving record
expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
postRetireGrowthRates, 10000000)
print expenses
# Output should be a value close to 0.0, because the "epsilon" is set too high
|
881b1fda39407db1227c1c17a58c409530a0afd9 | RamachandiranVijayalakshmi/String-swap-case | /swap.py | 146 | 3.765625 | 4 | def fun(a):
b=a.swapcase()
print('the original string:',a)
print('the swapcase string is:',b)
x=input('Enter the string:')
fun(x) |
a7f30862de7e74b734bbf44cd78902155d73034a | iwharris/queens-py | /queens_functional.py | 426 | 3.609375 | 4 | __author__ = 'iwharris'
base_state = [[0 for x in range(8)] for y in range(8)] # Blank state
def solve(state, queen_count=0, solutions=[]):
return solutions + [state]
def print_states(states):
for state in states:
print '\n'.join([''.join(['Q' if state[x][y]==1 else 'x' if state[x][y]==-1 else '.' for x in range(8)]) for y in range(8)])
if __name__ == '__main__':
print_states(solve(base_state, [])) |
80b581084235b6350e9c2473c841d3c21f58d2c5 | ultimate010/codes_and_notes | /178_graph-valid-tree/graph-valid-tree.py | 819 | 3.578125 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/graph-valid-tree
@Language: Python
@Datetime: 16-06-28 07:11
'''
class Solution:
# @param {int} n an integer
# @param {int[][]} edges a list of undirected edges
# @return {boolean} true if it's a valid tree, or false
def validTree(self, n, edges):
# Write your code here
root = range(n)
def find(root, n):
while root[n] != n:
root[n] = root[root[n]]
n = root[n]
return n
for e in edges:
p = find(root, e[0])
q = find(root, e[1])
if p == q: # same group
return False
root[p] = q
return len(edges) == n - 1 |
f7fa8783683b370edfcf6e7373b2ca2bc820d194 | guanfuchen/CodeTrain | /SwordOffer/Algorithm/Python/fibonacci_array.py | 719 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# 递归方法
# class Solution:
# def Fibonacci(self, n):
# # write code here
# if n==0 or n==1:
# return 1
# else:
# return self.Fibonacci(n-2)+self.Fibonacci(n-1)
# 动态规划方法
class Solution:
def Fibonacci(self, n):
# write code here
if n==0:
return 0
elif n==1 or n==2:
return 1
else:
s = []
s.append(1)
s.append(1)
for i in range(2, n):
s.append(s[i-2]+s[i-1])
return s[-1]
if __name__ == '__main__':
s = Solution()
for n in range(39):
print(s.Fibonacci(n))
|
e827cd319af1c5ba327fb1a2d2d4605f3ca5e06b | Lakhan671/python | /string/StringFunctions.py | 310 | 3.78125 | 4 | name="Lakhan singh";
print(name.title())
print(name.upper())
print(name.lower())
print(name.swapcase())
d="10"
print(d.isdigit())
print(d.isalpha())
print(d.isalnum())
s=""
print(s.isspace())
s1=" s "
print(s1.lstrip())
print(s1.rstrip())
print(s1.strip())
print(name.startswith("La"))
print(name.endswith("ingh")) |
d9aabbc9a3e63ec8d48091ab8f49ce9a49f1f799 | Ashish-Surve/Learn_Python | /Training/Day5/Functional Programming/1_map_demo_in_python3.py | 1,232 | 4.21875 | 4 |
nums = [1,2,3]
squareelemnts = [i**2 for i in nums if i<3] #list comprehension
print("Original nums list = ", nums)
print("List of square elemnts = ", squareelemnts) #[1, 4]
def sq_elem(x):
return x**2
squareelemnts2 = [sq_elem(i)for i in nums]
print("List of square elemnts = ", squareelemnts2)#[1, 4, 9]
print("sq_elem(5) = ", sq_elem(5))
#2)alternative solution in map() function call:
map_obj = map(sq_elem, nums) #sq_elem is a func functional programming
print("map_obj = ", map_obj) #<map object at 0x0410AE30> 1,4,9
newlist1 = list(map_obj)
print("List of square elemnts = ",newlist1)
print ("---------------------------------------------------")
print("Output of map with lambda = ",list(map(lambda x : x**2,nums)))
print("filter and map = ",list(map(lambda x : x**2,list(filter(lambda x: x<3,nums)))))
print ("---------------------------------------------------")
#in python 3
words =["abc", "xyz", "lmn"]
upper_words = []
map_ob = map(lambda w :w.upper() , words)
print( "Return value of map in Python 3 = ", map_ob)
upper_words = list(map_ob)
print ("Original sequence list = ", words)
print("Upper words = ", upper_words)
#in Python3 map() function returns map object so pass that as parameter to list
|
e501a23b16b0fa56d7e8d1cbdb99093d49ad844b | jaabee/daily_code | /DesignPattern/state_demo.py | 2,657 | 4.03125 | 4 | # @Time : 2020/10/7 11:33
# @Author : GodWei
# @File : state_demo.py
# 引入 ABCMeta 和 abstractmethod 来定义抽象类和抽象方法
from abc import ABCMeta, abstractmethod
class Water:
"""水"""
def __init__(self, state):
self.__temperature = 25 # 默认常温为25℃
self.__state = state
def setState(self, state):
self.__state = state
def changeState(self, state):
if self.__state:
print("由", self.__state.getName(), "变为", state.getName())
else:
print("初始化为", state.getName())
self.__state = state
def getTemperature(self):
return self.__temperature
def setTemperature(self, temperature):
self.__temperature = temperature
if self.__temperature <= 0:
self.changeState(SolidState("固态"))
elif self.__temperature <= 100:
self.changeState(LiquidState("液态"))
else:
self.changeState(GaseousState("气态"))
def riseTemperature(self, step):
self.setTemperature(self.__temperature + step)
def reduceTemperature(self, step):
self.setTemperature(self.__temperature - step)
def behavior(self):
self.__state.behavior(self)
class State(metaclass=ABCMeta):
"""状态的基类"""
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
def isMatch(self, stateInfo):
"""状态的属性 stateInfo 是否在当前的状态范围"""
return False
@abstractmethod
def behavior(self, water):
"""不同状态下的行为"""
pass
class SolidState(State):
"""固态"""
def __init__(self, name):
super().__init__(name)
def behavior(self, water):
print("当前的温度" + str(water.getTemperature()) + "℃,为固态冰")
class LiquidState(State):
"""液态"""
def __init__(self, name):
super().__init__(name)
def behavior(self, water):
print("当前的温度" + str(water.getTemperature()) + "℃,为液态水")
class GaseousState(State):
"""气态"""
def __init__(self, name):
super().__init__(name)
def behavior(self, water):
print("当前的温度" + str(water.getTemperature()) + "℃,为气态水蒸气")
def testState():
water = Water(LiquidState("液态"))
water.behavior()
water.setTemperature(-4) # 设置温度
water.behavior()
water.riseTemperature(18) # 提升温度18℃
water.behavior()
water.riseTemperature(110) # 提升温度110℃
water.behavior()
testState()
|
308bd9a81ceaf434d122d262ff8c175cb04652ac | iPedriNNz/Exercicios | /ex071.py | 691 | 3.515625 | 4 | r1 = r10 = r20 = r50 = 0
print('=' * 60)
print(' CAIXA ECNÔMICA FEDERAL DAS ARABIA')
print('=' * 60)
valor = int(input('Qual valor você quer sacar ? R$'))
while valor >= 50:
valor -= 50
r50 += 1
while valor >= 20:
valor -= 20
r20 += 1
while valor >= 10:
valor -= 10
r10 += 1
while valor >= 1:
valor -= 1
r1 += 1
if r50 > 0:
print(f'Total de {r50} notas de R$ 50,00 ')
if r20 > 0:
print(f'Total de {r20} notas de R$ 20,00 ')
if r10 > 0:
print(f'Total de {r10} notas de R$ 10,00 ')
if r1 > 0:
print(f'Total de {r1} notas de R$ 1,00 ')
print('=' * 60)
print('Volte sempre a CAIXA ECNÔMICA FEDERAL DAS ARABIA! Tenha um bom dia !')
|
4cd006b34e36a66f5921a757f429fb1030a078fd | Franklyn-S/listas-FUP | /Lista 5 FUP - Matrizes/Códigos Python/1.18.py | 825 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Esse código cria uma matriz 3x3, onde os valores são escolhidos pelo usuário
e após isso a mostra virada 270° no sentido horário
Autor: Franklyn Seabra
Cursando Ciências da computação no 1º semestre
'''
#Cria uma lista para a matriz
m=[]
#preenche a matriz com os valores digitados pelo usuário
for i in range(0,3):
m.append([])
for j in range(0,3):
m[i].append(int(input("Digite o valor da linha %i com a coluna %i: " % (i+1,j+1))))
#imprime a matriz original
print("***Matriz***")
for k in range(0,3):
print(m[k])
#imprime a matriz virada
print("***Matriz Virada***")
for j in range(2,-1,-1):
print("[", end="")
for i in range(0,3):
if i != 2:
print(m[i][j], end=", ")
else:
print(m[i][j], end="]\n") |
72c8f7eee571832ebce7ceb9e921b9cd42a719b2 | jormarsikiu/PracticasPython | /6-Clases/2-respuesta.py | 814 | 4.03125 | 4 | """2)crear una clase llamada persona, que va a tener como atributos "nombre" y "edad", con dos metodos, uno para obtener el nombre (que lo imprima por pantalla) y otro para obtener la edad, y despues una clase llamada alumno, que aparte de tener una edad y un nombre como la clase persona, tambien va a tener el atributo "nota" con un metodo para obtener la nota... usar herencia..."""
class Persona:
def __init__(self):
self.nombre = None
self.edad = None
print 'Se creo la persona'
def obtener_nombre(self):
print 'Nombre es: ', self.nombre
def obtener_edad(self):
print 'Edad es: ', self.edad
class Alumno(Persona):
def __init__(self, nota):
self.nota = nota
print 'Nota es: ', self.nota
P = Persona()
P.nombre = "Luis"
P.edad = 12
P.obtener_nombre()
P.obtener_edad()
A = Alumno(20)
|
976da81d1037da67baaa17b9d5ce6c28ea9b279a | sbtries/Class_Polar_Bear | /Code/Gabe/python/lab_02/loops_practice.py | 1,023 | 3.859375 | 4 | import time
# number = 0
# while number < 5:
# print('Hello World!') # endless loop because number never changes
# while number < 99:
# print(number, 'Hello World!')
# if number == 20:
# break
# number += 1
# while True:
# user_input = input('\nEnter a number: ')
# try:
# user_input = int(user_input)
# break
# except ValueError:
# print('\nInvalid number, try again. ')
# print(f'\nYour number was {user_input}')
# for x in range(5, 10, 2):
# print(x)
# time.sleep(.3)
# class_name = 'Polar Bear'
# for char in class_name:
# # print(char)
# # time.sleep(.3)
# # if char == 'a':
# # break
# if char == 'a':
# continue
# print(char)
# colors = ['green', 'blue', 'red', 'yellow', 'orange']
# for color in colors:
# if color == 'red':
# continue
# print(color)
#### Iterate 5 times using a while loop ####
# counter = 0
# while counter < 5:
# print(counter)
# counter += 1
#### Iterate 5 times using a for loop ####
# for x in range(5):
# print(x)
|
33191b445b5da138e9db884de782534a607e43b6 | sashaobucina/interview_prep | /python/easy/path_crossing.py | 1,019 | 4.46875 | 4 | def is_path_crossing(path: str) -> bool:
"""
# 1496: Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one
unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane
and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time you are on a location
you've previously visited. Return False otherwise.
"""
loc = (0, 0)
visited = {loc}
for direction in path:
if direction == "N":
loc = (loc[0], loc[1] + 1)
elif direction == "W":
loc = (loc[0] - 1, loc[1])
elif direction == "S":
loc = (loc[0], loc[1] - 1)
else:
loc = (loc[0] + 1, loc[1])
if loc in visited:
return True
visited.add(loc)
return False
if __name__ == "__main__":
assert not is_path_crossing("NES")
assert is_path_crossing("NESWW")
print("Passed all tests!")
|
52223d08d2a67e2302d2d0f17d159a9faf6f44f7 | grace-omotoso/CIS-202---Python-Programming | /Chapter 8 - Code/Basic String Operations/concatenate.py | 239 | 4.03125 | 4 | # This program concatenates strings.
def main():
name = 'Carmen'
print(f'The name is: {name}')
name = name + ' Brown'
print(f'Now the name is: {name}')
# Call the main function.
if __name__ == '__main__':
main()
|
c8bf6c1ac6ad65a7f501ec97f8320254f6f4cd14 | L200183174/algostruk_x | /MODUL-7/latihan 7-1.py | 834 | 3.71875 | 4 | ## halaman 65
import re
s = 'sebuah contoh kata:teh !!'
cocok = re.findall(r'kata:\w\w\w',s)
# Pernyataan-IF sesudah findall() akan memeriksa apakah pencarian berhasil
if cocok :
print('menemukan', cocok) #'menemukan [kata:teh]'
else :
print('tidak menemukan')
# latihan 7.1 halaman 68
a = 'sebuah contoh kata:batagor !!'
cocok = re.findall(r'kata:\w\w\w',a)
# Pernyataan-IF sesudah findall() akan memeriksa apakah pencarian berhasil
if cocok :
print('menemukan', cocok) #'menemukan [kata:teh]'
else :
print('tidak menemukan')
b = 'sebuah contoh kata:es teh !!'
cocok = re.findall(r'kata:\w\w\w',b)
# Pernyataan-IF sesudah findall() akan memeriksa apakah pencarian berhasil
if cocok :
print('menemukan', cocok) #'menemukan [kata:teh]'
else :
print('tidak menemukan')
|
0061d75c2f85ed254da9e14758f58014c871bbf1 | hiepxanh/C4E4 | /DauMinhHoa/W3-as6.py | 1,082 | 4 | 4 | #Exercise 1
inventory = {
'gold': 500,
'pouch': ['flint', 'twince', 'gemstone'],
'backpack': ['xylophone', 'dagger', 'bedroll', 'bread loaf']
}
inventory['pocket']=['seashell', 'strange berry', 'lint'] #add key and value
inventory['backpack'].sort() #sort items in the list in 'backpack'
inventory['backpack'].remove('dagger') # remove 'dagger' from the list in 'backpack'
inventory['gold']= 500, 50 #add 50 to 500 in 'gold'
print(inventory)
#Exercise 2
prices = {
'banana': 4,
'apple': 2,
'orange': 1.5,
'pear': 3
}
stock = {
'banana': 6,
'apple': 0,
'orange': 32,
'pear': 15
}
print("in my store:")
print("")
for x in prices:
print(x)
print("price: ", int(prices[x]))
print("stock: ", int(stock[x]))
print("")
def profit(prices, stock):
total=0
for x,y in prices.items():
for a,b in stock.items():
if x==a:
total=total + y*b
return total
print("if we sold out all of them, we can earn:", profit(prices, stock))
|
31854c47bfbea2151b842adc32e8aed64ae082e2 | vhalyolee/PyScripts | /PythonExamples/PythonEssentail/Modules/financial_module/FutureValue.py | 1,809 | 4.21875 | 4 | #!/usr/bin/python
"""
Financial Module
----------------
Background
~~~~~~~~~~
The future value (fv) of money is related to the present value (pv)
of money and any recurring payments (pmt) through the equation::
fv + pv*(1+r)**n + pmt*(1+r*when)/r * ((1+r)**n - 1) = 0
or, when r == 0::
fv + pv + pmt*n == 0
Both of these equations assume the convention that cash in-flows are
positive and cash out-flows are negative. The additional variables in
these equations are:
* n: number of periods for recurring payments
* r: interest rate per period
* when: When payments are made:
- (1) for beginning of the period
- (0) for the end of the period
The interest calculations are made through the end of the
final period regardless of when payments are due.
"""
def future_value(r, n, pmt, pv=0.0, when=1):
"""Future value in "time value of money" equations.
* r: interest rate per payment (decimal fraction)
* n: number of payments
* pv: present value
* when: when payment is made, either 1 (begining of period, default) or
0 (end of period)
"""
return -pv*(1+r)**n - pmt*(1+r*when)/r * ((1+r)**n - 1)
import sys
pymts = float(raw_input("Insert number of pymts per year: "))
years = float(raw_input("Insert number years: "))
pymtmo = float(raw_input("Insert monthly payment: "))
#if len(sys.argv)>1:
# print (float(sys.argv[1]))
# pymts_pyear = float(sys.argv[1])
# print " pymts pyear is : ",test
# pymts_pyear = float(sys.argv[1])
# Future Value Example.
yearly_rate = .0325
monthly_rate = yearly_rate / pymts # 12 pymts
monthly_periods = years * pymts # 5 years
monthly_payment = pymtmo # -$100 per period.
print "future value is ", future_value(monthly_rate, monthly_periods,
monthly_payment)
|
051789cf14bc0952c3c71fcc5f1d2e4205687da1 | wafaharbi/firstLesson | /Ninth Day.py | 647 | 4 | 4 | # __________________ Ninth Day ____________________ #
"""To combine String and numbers
Use the format() method to insert numbers into strings"""
age = 24
txt = "My name is wafa, I am "
print(txt.format(age), "\n")
# The format() method takes unlimited number of arguments
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
# Will print " I want 3 pieces of item 567 for 49.95 dollars."
print(myorder.format(quantity, itemno, price), "\n")
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
|
9441269217781d1f6631cc075cb34cbea018fba9 | wbddxyz/python_sutff | /ex23.py | 1,024 | 4.0625 | 4 |
'''
Colin Anderson
ex23_linear_search.py
27/10/20
J27C76 Software Design and development
Standard Algorithms - linear search
'''
def find_element(data, find):
for d in data: #loop through our data
if d == find:
return True
return False
def find_index(data, find):
for x in range(len(data)): #loop through 0 to end
if data[x] == find:
return x # found
return -1 # not found
def main():
data = [63,43,82,69,92,64,89,42,60,42]
find = int(input('please enter a number to search for:'))
seek_element = find_element(data, find)
if seek_element == True:
print(f"number {find} was found")
else:
print(f"number {find} not found")
#part 2 find element index
element_index = find_index(data,find)
if element_index >= 0:
print(f'The element{find} was found at index {element_index}')
else:
print(f'The element{find} was not found')
if __name__=="__main__":
main()
|
f750dde301b33bfe613e8e0da2d53a280052dd11 | dshue20/interview-prep | /python/mergeLists.py | 1,015 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
if list1.val < list2.val:
finalList = list1
otherList = list2
else:
finalList = list2
otherList = list1
head = finalList
while otherList and finalList.next:
if finalList.next.val < otherList.val:
finalList = finalList.next
else:
nextFinal = finalList.next
finalList.next = otherList
otherList = otherList.next
finalList.next.next = nextFinal
finalList = finalList.next
if otherList:
finalList.next = otherList
return head |
ad3d6b61bb86c956231c6fed61e2ef3a4c8d99ef | vanshikachauhan/Python-Programs | /16.rectangle_random.py | 407 | 3.6875 | 4 | from tkinter import *
import random
root=Tk()
canvas=Canvas(root,width=700,height=700)
canvas.pack()
def rect(num):
for i in range(0,num):
x1=random.randrange(300)
y1=random.randrange(300)
x2=x1+random.randrange(300)
y2=y1+random.randrange(300)
canvas.create_rectangle(x1,x2,y1,y2)
rect(100)
root.mainloop()
|
4f2aabccde6ef425ce6b9453463f11d757fac204 | Frankhe303/learngit | /1.py | 1,529 | 3.546875 | 4 | from socket import *
import threading
def send_date(socket_tcp_client): # 发送数据
while True:
server_date = input()
# 3.发送信息
if server_date == "exit": # 当输入exit时,断开于服务器的连接
break
else:
socket_tcp_client.send(server_date.encode("gbk")) # 发数据,enc1onde为编码 gbk为编码方式
socket_tcp_client.close() # 关闭套接字
def recv_date(socket_tcp_client): # 接收数据
while True:
recv_date = socket_tcp_client.recv(1024) # 接收信息,每次最大为1024
print("接收到的数据为:", recv_date.decode("gbk")) # decode为解码,gbk为解码方式
print("请输入要发送的数据:", end=" ")
def main():
socket_tcp_client = socket(AF_INET, SOCK_STREAM) # 创建一个套接字
# server_ip = input("请输入服务器的IP:")
server_ip = '192.168.3.109'
# server_port = int(input("请输入服务器的port:"))
server_port = 12500
print("请输入要发送的数据,输入exit退出会话:", end=" ")
server_addr = (server_ip, server_port)
socket_tcp_client.connect(server_addr) # 2.绑定连接
send_tcp_date = threading.Thread(target=send_date, args=(socket_tcp_client,)) # 定义两个线程,分别为发送和接收
recv_tcp_date = threading.Thread(target=recv_date, args=(socket_tcp_client,))
send_tcp_date.start()
recv_tcp_date.start() # 开启这两个线程
if __name__ == '__main__':
main()
|
3b3cfac7510f555852d0c834e560ea59111c6ac0 | bexis13/pyp-w1-gw-language-detector | /language_detector/main.py | 1,742 | 4.5 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
def detect_language(text, languages):
"""Returns the detected language of given text."""
# implement your solution here
#for each word in a language, check how many words in there occur in
#the users text
#split string of text into a list of words
new_text = text.lower().split()
#we will store a language and how many times a word from this language
#occur in user text
word_occurence_in_languages = {}
#loop through each language
for language in languages:
single_language = language['name'] # name of language we are dealing with right now
word_occurence_in_languages[single_language] = 0 # initialize the counter for this
#language we are dealing with right now
common_words = language['common_words'] #list of common words in each language
#in each language, loop through every common_word
for word in common_words:
single_common_word = word
#when a match is found from this language,
if single_common_word in new_text:
#add one to the count of this language
word_occurence_in_languages[single_language] += 1
#return the language with the highest count
maxcount=0
maxlanguage=""
#find one with the greatest count
maxcount=(max(word_occurence_in_languages.values()))
#find name of language with maxcount
maxlanguage=[key for key,value in word_occurence_in_languages.items()if value==maxcount][0]
return maxlanguage
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.