blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2a1a5b65f5ef8f270450832c2586b36e073dcfb9 | VICIWUOHA/Pycharm-Project | /Mapping.py | 387 | 3.765625 | 4 | import numpy as np
import pandas as pd
from pandas import Series, DataFrame
df = DataFrame({'Country': ['Afghanistan', 'Albania', 'Nigeria'],
'Code': ['89', '345', '213']
})
GDP_map = {'Afghanistan': '20', 'Albania': '12.8', 'Algeria': '215'}
print(GDP_map)
# Mapping values in df to values in GDP_map
df['GDP'] = df['Country'].map(GDP_map)
print(df)
|
7ee24e3c040a7624f1657e954ed35aeb8ed6e091 | nineties/prml-seminar | /prog/prog3-4-5.py | 1,337 | 3.796875 | 4 | # -*- coding: utf-8 -*-
from numpy import *
from scipy import stats
from matplotlib.pyplot import *
# 真の値(台形近似で. N=100だと4桁は合うはず.)
def answer():
N = 100
x = linspace(0, 2, N+1)
fx = stats.norm.pdf(x)
return 0.5 - (sum(2*fx)-fx[0]-fx[-1])*2/(2*N)
answer = answer()
def integrate1(n):
x = random.randn(n)
return float(count_nonzero(x >= 2))/n
#重点的サンプリング
def integrate2(n):
x = random.exponential(size=n) + 2
return average( stats.norm.pdf(x) / stats.expon.pdf(x, loc=2) )
M = 100
# 近似値の絶対誤差をM個の平均をプロット
n = arange(1000, 50001, 1000)
mae1 = vectorize(
lambda n: average([abs(answer - integrate1(n)) for i in range(M)])
)(n)
mae2 = vectorize(
lambda n: average([abs(answer - integrate2(n)) for i in range(M)])
)(n)
plot(n, mae1, label="sampling from N(0,1)")
plot(n, mae2, label="sampling from expon")
plot(n, [0.001]*len(n))
xlabel('number of samples (N)')
ylabel('mean absolute error (MAE)')
legend(loc=1)
show()
# より詳細なプロット
n = arange(10, 1001, 10)
mae = vectorize(
lambda n: average([abs(answer - integrate2(n)) for i in range(M)])
)(n)
plot(n, mae)
plot(n, [0.001]*len(n))
xlabel('number of samples (N)')
ylabel('mean absolute error (MAE)')
show()
|
7009549410254ccb70e5625b830963e5eef0495f | gitbrian/lpthw | /ex13.py | 399 | 3.59375 | 4 | from sys import argv
script, first, second, third, fourth, fifth = argv
print "The script is called:", script
print "Your first variable is", first
print "Your second variable is", second
print "Your third variable is", third
print "Your fourth variable is", fourth
print "Your fifth variable is", fifth
print ""
like_questions = raw_input("Do you like asking questions? ")
print "Good to know!"
|
2b12c0ed7a5c2bc4ced81d12101a6e209cc58917 | garibaal/isat252 | /lab5.py | 868 | 3.9375 | 4 | """
lab 5
"""
# 3.1
alien_color = 'green'
if alien_color == 'green' :
print('you got 5 points')
# 3.2
alien_color = 'green'
if alien_color == 'green':
print('shot alien! you got 5 points')
else:
print('player earned 10 points')
# 3.3
favorite_fruits = ['apple','banana','strawberry']
if 'apple' in favorite_fruits:
print('I really like apples')
if 'blueberry' in favorite_fruits:
print('I really like blueberries')
if 'orange' in favorite_fruits:
print('I really like oranges')
if 'banana' in favorite_fruits:
print('I really like bananas')
if 'raspberry' in favorite_fruits:
print('I really like raspberries')
# 3.4
age = 20
if age<10:
print('the person is a kid')
elif age<20:
print('the person is a teenager')
else:
print('the person is an adult')
if age>65:
print('the person is an elder')
|
84a3e699b22083c960d19dc2fbceaae76dbfd719 | Shishir-rmv/oreilly_math_fundamentals_data_science | /calculus_and_functions/15_log_function.py | 120 | 3.59375 | 4 | from math import log
# 2 raised to what exponent gives us 8?
exponent = log(8,2)
# The answer is 3.0
print(exponent)
|
4f70eadf87247e93252d7c70425215fb3e792353 | irasemarivera/Curso_python_cice | /Historial/strings.py | 3,722 | 4.375 | 4 | #strings
"""
mi_nombre = "Hola Irasema"
print(mi_nombre)
mi_nombre = "Hola Irasema, 'buenos dìas'!"
print(mi_nombre)
mi_nombre = "Hola Irasema, \"buenos dìas\"!"
print(mi_nombre)
mi_nombre = 'Hola Irasema, "buenos dìas"!'
print(mi_nombre)
mi_nombre = '''linea uno
otra màs
esta es la tercera linea!
ahora una cuarta
no hay quinto malo
'''
print(mi_nombre)
#numero1 = 20
#numero2 = 20
#if (numero1 < numero2):
# print("numero1 es menor")
#else:
# if numero1 > numero2:
# print("numero2 es menor")
# else:
# print("son iguales")
nombre = "Irasema"
apellido = "Rivera"
nombre_completo = nombre + " " + apellido
print(nombre_completo)
print(nombre, apellido)
print("nombre_completo[0]: ",nombre_completo[0])
print("nombre_completo[1]: ",nombre_completo[1])
print("nombre_completo[2]: ",nombre_completo[2])
print("nombre_completo[3]: ",nombre_completo[3])
print("\n")
print("nombre_completo[-3]: ",nombre_completo[-3])
print("nombre_completo[-2]: ",nombre_completo[-2])
print("nombre_completo[-1]: ",nombre_completo[-1])
print("Metodos String-----------------------------")")
course = "Curso"
my_string = "INTENSIVO de PyThOn"
result = 'Bienvenidos al {a} {b} del cice'.format(a=course, b=my_string)
print("original: "+ result)
result = result.lower()
# print("lower: "+ result)
# result = result.upper()
# print("upper: " + result)
# result = result.title()
# print("title: " + result)
print("Métodos de búsqueda-----------------------------")")
busqueda = result.find('curso')
print("find: ", busqueda)
count = result.count('c')
print("count: ", count)
replace = result.replace('c','w')
print("replace: ", replace)
split = result.split(" ")
print("split: ", split)
print(len(split))
print("LISTAS-----------------------------")")
mi_lista = ["palabra", 12, 12.9, True]
frutas = ["platano", "manzana", "kiwi", "uva", "piña"]
print(frutas)
# print(frutas[0])
# print(frutas[1])
# print(frutas[2])
# print(frutas[3])
frutas.append("arandano")
frutas.insert(1, "fresa")
print(frutas)
frutas.remove("fresa")
print(frutas)
frutas.pop()
print(frutas)
mi_lista1 = [51, 6.1, 72, 3, 11]
mi_lista2 = [100, 80, 40, 50]
mi_lista1.sort() #ordena ascendentemente
print("mi_lista1 sort", mi_lista1)
mi_lista1.sort(reverse=True)
print("mi_lista1 sort reverse", mi_lista1)
# frutas.sort()
# print(frutas)
mi_lista1.extend(mi_lista2)
print(mi_lista1)
mi_lista1.extend([1001,1002])
print(mi_lista1)
mi_lista1.append(mi_lista2)
print(mi_lista1)
print("TUPLAS-----------------------------")")
mi_tupla = (1, "palabra", True)
print(mi_tupla)
print(mi_tupla[0])
#mi_tupla[1] = 1 -- no es posible
mi_lista1.extend(mi_tupla)
print(mi_lista1)
mi_lista1.append(mi_tupla)
print(mi_lista1)
print("DICCIONARIO-----------------------------")
diccionario = {'a': 55,
1: "esto es un string",
"cice": ["AULA1", "AULA2", "AULA3", "AULA4", "AULA5"]}
print(diccionario)
diccionario['a'] = 60
diccionario['c'] = "Un nuevo string"
print(diccionario)
diccionario['a'] = False
print(diccionario)
print("diccionario.keys(): ", diccionario.keys())
print("diccionario.values()", diccionario.values())
lista1 = list(diccionario.keys())
print("lista1: ", lista1)
lista2 = tuple(diccionario.values())
print("lista2: ", lista2)
diccionario2 = {'a': 123,
'y': 456,
'z': 789}
diccionario.update(diccionario2)
print(diccionario)
"""
print("FUNCIONES ---------------------------")
def nombreFuncion():
print("Dentro de nombreFuncion")
pass
def suma(a, b):
return a + b
#funcion con valores por defecto
def suma2(a = 1, b = 2):
c = a + b
return c
print(suma2(a=6))
a = int(input("valor de a: "))
b = int(input("valor de b: "))
print(suma2(a,b))
|
9a38531ece8e74ff50ac885e28c44e94abf946f8 | hayleymathews/data_structures_and_algorithms | /Arrays/dynamic_array.py | 1,636 | 3.6875 | 4 | """python implementation of ADT Dynamic Array"""
import ctypes
from Arrays._array_abstract import Array
class DynamicArray(Array):
"""
implementing ADT Dynamic Array
"""
def __init__(self):
self.size = 0
self.capacity = 1
self.values = (self.capacity * ctypes.py_object)(*([None] * self.capacity))
def __len__(self):
"""
size of Array O(1)
"""
return self.size
def __iter__(self):
for item in self.values:
yield item
def __repr__(self):
return 'DynamicArray: [{0:s}]'.format(', '.join(map(str, self)))
def __getitem__(self, index):
"""
get item from Array O(1)
"""
if not 0 <= index < self.size:
raise IndexError('invalid index')
return self.values[index]
def __setitem__(self, index, value):
"""
set item in Array O(1)
"""
if not 0 <= index < self.size:
raise IndexError('invalid index')
else:
self.values[index] = value
def append(self, item):
"""
add item to Array amortized O(1) with resize
"""
if self.size == self.capacity:
self.resize(2 * self.capacity)
self.values[self.size] = item
self.size += 1
def resize(self, capacity):
"""
double size of array when at capacity O(n)
"""
new_array = (capacity * ctypes.py_object)(*([None] * capacity))
for i in range(self.size):
new_array[i] = self.values[i]
self.values = new_array
self.capacity = capacity
|
85080444f8a6342deede9262a73bde8542a2541d | jczhangwei/leetcode_py | /121.买卖股票的最佳时机.py | 1,823 | 3.9375 | 4 | #
# @lc app=leetcode.cn id=121 lang=python3
#
# [121] 买卖股票的最佳时机
#
# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
#
# algorithms
# Easy (54.19%)
# Likes: 1027
# Dislikes: 0
# Total Accepted: 224.4K
# Total Submissions: 413.7K
# Testcase Example: '[7,1,5,3,6,4]'
#
# 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
#
# 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
#
# 注意:你不能在买入股票前卖出股票。
#
#
#
# 示例 1:
#
# 输入: [7,1,5,3,6,4]
# 输出: 5
# 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
# 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
#
#
# 示例 2:
#
# 输入: [7,6,4,3,1]
# 输出: 0
# 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
#
#
#
# @lc code=start
from typing import *
class Solution:
def maxProfit2(self, prices: List[int]) -> int:
min_price = float("inf")
max_profit = 0
for price in prices:
max_profit = max(max_profit, price - min_price)
min_price = min(min_price, price)
return max_profit
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 0:
return 0
dp = [0] * len(prices)
min_price = prices[0]
for i in range(1, len(prices)):
dp[i] = max(dp[i-1], prices[i] - min_price)
min_price = min(min_price, prices[i])
return dp[len(prices) - 1]
print(Solution().maxProfit([1,2]))
# @lc code=end
|
8a1ff44f9c2f11a2c714f265850ff8e8d3bce970 | MiningXL/ggj2020 | /render.py | 7,415 | 3.671875 | 4 | from abc import ABCMeta, abstractmethod
import pygame
import math
from map import Grid
import os
SQRT3 = math.sqrt( 3 )
class Render( pygame.Surface ):
__metaclass__ = ABCMeta
def __init__( self, map, radius=24, *args, **keywords ):
self.map = map
self.radius = radius
# Colors for the map
self.GRID_COLOR = pygame.Color( 50, 50, 50 )
super( Render, self ).__init__( ( self.width, self.height ), *args, **keywords )
self.cell = [( .5 * self.radius, 0 ),
( 1.5 * self.radius, 0 ),
( 2 * self.radius, SQRT3 / 2 * self.radius ),
( 1.5 * self.radius, SQRT3 * self.radius ),
( .5 * self.radius, SQRT3 * self.radius ),
( 0, SQRT3 / 2 * self.radius )
]
@property
def width( self ):
return self.map.cols * self.radius * 1.5 + self.radius / 2.0
@property
def height( self ):
return ( self.map.rows + .5 ) * self.radius * SQRT3 + 1
def get_surface( self, row, col ):
"""
Returns a subsurface corresponding to the surface, hopefully with trim_cell wrapped around the blit method.
"""
width = 2 * self.radius
height = self.radius * SQRT3
top = ( row - math.ceil( col / 2.0 ) ) * height + ( height / 2 if col % 2 == 1 else 0 )
left = 1.5 * self.radius * col
return self.subsurface( pygame.Rect( left, top, width, height ) )
# Draw methods
@abstractmethod
def draw( self ):
"""
An abstract base method for various render objects to call to paint
themselves. If called via super, it fills the screen with the colorkey,
if the colorkey is not set, it sets the colorkey to magenta (#FF00FF)
and fills this surface.
"""
color = self.get_colorkey()
if not color:
magenta = pygame.Color( 255, 0, 255 )
self.set_colorkey( magenta )
color = magenta
self.fill( color )
# Identify cell
def get_cell( self, x, y ):
"""
Identify the cell clicked in terms of row and column
"""
# Identify the square grid the click is in.
row = math.floor( y / ( SQRT3 * self.radius ) )
col = math.floor( x / ( 1.5 * self.radius ) )
# Determine if cell outside cell centered in this grid.
x = x - col * 1.5 * self.radius
y = y - row * SQRT3 * self.radius
# Transform row to match our hex coordinates, approximately
row = row + math.floor( ( col + 1 ) / 2.0 )
# Correct row and col for boundaries of a hex grid
if col % 2 == 0:
if y < SQRT3 * self.radius / 2 and x < .5 * self.radius and \
y < SQRT3 * self.radius / 2 - x:
row, col = row - 1, col - 1
elif y > SQRT3 * self.radius / 2 and x < .5 * self.radius and \
y > SQRT3 * self.radius / 2 + x:
row, col = row, col - 1
else:
if x < .5 * self.radius and abs( y - SQRT3 * self.radius / 2 ) < SQRT3 * self.radius / 2 - x:
row, col = row - 1 , col - 1
elif y < SQRT3 * self.radius / 2:
row, col = row - 1, col
return ( row, col ) if self.map.valid_cell( ( row, col ) ) else None
def fit_window( self, window ):
top = max( window.get_height() - self.height, 0 )
left = max( window.get_width() - map.width, 0 )
return ( top, left )
class RenderUnits( Render ):
"""
A premade render object that will automatically draw the Units from the map
"""
def __init__( self, map, *args, **keywords ):
super( RenderUnits, self ).__init__( map, *args, **keywords )
if not hasattr( self.map, 'units' ):
self.map.units = Grid()
def draw( self ):
"""
Calls unit.paint for all units on self.map
"""
super( RenderUnits, self ).draw()
units = self.map.units
for position, unit in units.items():
surface = self.get_surface(*position )
unit.paint( surface )
class RenderGrid( Render ):
def get_surface_pos(self, pos):
"""
Returns a subsurface corresponding to the surface, hopefully with trim_cell wrapped around the blit method.
"""
row = pos[0]
col = pos[1]
width = 2 * self.radius
height = self.radius * SQRT3
midy = (row - math.ceil(col / 2.0)) * height + (height / 2 if col % 2 == 1 else 0) + height/2
midx = 1.5 * self.radius * col + width/2
return (midx, midy)
def draw( self ):
"""
Draws a hex grid, based on the map object, onto this Surface
"""
super( RenderGrid, self ).draw()
# A point list describing a single cell, based on the radius of each hex
for col in range( self.map.cols ):
# Alternate the offset of the cells based on column
offset = self.radius * SQRT3 / 2 if col % 2 else 0
for row in range( self.map.rows ):
# Calculate the offset of the cell
top = offset + SQRT3 * row * self.radius
left = 1.5 * col * self.radius
# Create a point list containing the offset cell
points = [( x + left, y + top ) for ( x, y ) in self.cell]
# Draw the polygon onto the surface
pygame.draw.polygon( self, (255,255,0), points, 0 )
pygame.draw.polygon(self, self.GRID_COLOR, points, 2)
class RenderFog( Render ):
OBSCURED = pygame.Color( 255, 00, 00, 128 )
SEEN = pygame.Color( 255, 00, 00, 128 )
VISIBLE = pygame.Color( 255, 00, 00, 128 )
def __init__( self, map, *args, **keywords ):
super( RenderFog, self ).__init__( map, *args, flags=pygame.SRCALPHA, **keywords )
if not hasattr( self.map, 'fog' ):
self.map.fog = Grid( default=self.OBSCURED )
def draw( self ):
#Some constants for the math
height = self.radius * SQRT3
width = 1.5 * self.radius
offset = height / 2
self.fill( self.OBSCURED )
for cell in self.map.cells():
row, col = cell
surface = self.get_cell(*cell )
# Calculate the position of the cell
top = row * height - offset * col
left = width * col
#Determine the points that corresponds with
points = [( x + left, y + top ) for ( x, y ) in self.cell]
# Draw the polygon onto the surface
pygame.draw.polygon( self, self.map.fog[ cell ], points, 0 )
def trim_cell( surface ):
pass
if __name__ == '__main__':
from map import Map, MapUnit
import sys
class Unit( MapUnit ):
color = pygame.Color( 200, 200, 200 )
def paint( self, surface ):
radius = surface.get_width() / 2
# draw Biene
current_path = os.path.dirname(__file__)
bee_surface = pygame.image.load(os.path.join(current_path, "bee_small_2.png"))
surface.blit(bee_surface, ((int(radius), int( SQRT3 / 2 * radius )),(0,0)) )
#pygame.draw.circle( surface, self.color, ( int(radius), int( SQRT3 / 2 * radius ) ), int( radius - radius * .3 ) )
m = Map( 5, 12 )
grid = RenderGrid( m, radius=32 )
units = RenderUnits( m, radius=32 )
fog = RenderFog( m, radius=32 )
# Bienen Position
m.units[( 0, 0 ) ] = Unit( m )
m.units[( 3, 2 ) ] = Unit( m )
m.units[( 5, 3 ) ] = Unit( m )
m.units[( 5, 4 ) ] = Unit( m )
for cell in m.spread( ( 3, 2 ), radius=2 ):
m.fog[cell] = fog.SEEN
for cell in m.spread( ( 3, 2 ) ):
m.fog[cell] = fog.VISIBLE
print( m.ascii() )
try:
pygame.init()
fpsClock = pygame.time.Clock()
window = pygame.display.set_mode( ( 640, 480 ), 1 )
from pygame.locals import QUIT, MOUSEBUTTONDOWN
#Leave it running until exit
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
print( units.get_cell( event.pos ) )
window.fill( pygame.Color( 'white' ) )
grid.draw()
units.draw()
fog.draw()
window.blit( grid, ( 0, 0 ) )
window.blit( units, ( 0, 0 ) )
window.blit( fog, ( 0, 0 ) )
pygame.display.update()
fpsClock.tick( 10 )
finally:
pygame.quit()
|
175d165d0d4ef780c7ae4c140950477f0bae4bc5 | THACT3001/PhamTienDung-c4t3 | /hahaha/filehw11.py | 983 | 3.875 | 4 | sizes = [5, 7, 300, 90, 24, 50, 75]
print("Hello my name is Dung and these are my ship sizes: ", *sizes, end = " ")
print()
print("Now my biggest sheep has size", max(sizes),"let's shear it")
print()
sizes[sizes.index(max(sizes))] = 8
print("After shearing, here is my flock:", *sizes, end = " ")
print()
sizes = [size + 50 for size in sizes]
print("One month has passed, now here is my flock:", *sizes, end = " ")
print()
month = int(input("Month? "))
for i in range(month):
print("MONTH", i + 1, ":")
sizes = [size + 50 for size in sizes]
print("One month has passed, now here is my flock:", *sizes, end=" ")
print()
print("Now my biggest sheep has size", max(sizes), "let's shear it")
print()
sizes[sizes.index(max(sizes))] = 8
print("After shearing, here is my flock:", *sizes, end=" ")
print()
print("The total size of my flock is: ", sum(sizes))
print("I would get", sum(sizes), "* 2$ =", sum(sizes) * 2, "$ if I sell all of my sheeps") |
b5ddea7b34e379aecc176b8818cf191239b5e4e9 | ArtemDud10K/Homework | /TMSHomeWork-3/z15.py | 229 | 3.765625 | 4 | first_list = [1, 2, [5, 6, 7 , 8], 3, 4]
for i in first_list:
if isinstance(i, list):
second_list = i
index = first_list.index(second_list)
first_list.pop(index)
first_list.extend(second_list)
print(first_list)
|
3f20cce7eed0d738a57e5c198dfda17b2dbae3cf | Zzpecter/Coursera_AlgorithmicToolbox | /week2/7_last_digit_partial_sum_of_fib_numbers.py | 787 | 4.125 | 4 | # Created by: René Vilar S.
# Algorithmic Toolbox - Coursera 2021
def get_fibonacci_rene(n):
pisano_period = get_pisano_period(10)
remainder_n = n % pisano_period
if remainder_n == 0:
return 0
previous, current = 0, 1
for _ in range(remainder_n - 1):
previous, current = current, previous + current
return current % 10
def get_pisano_period(m):
previous, current = 0, 1
for i in range(m ** 2):
previous, current = current, (previous + current) % m
# Pisano Period always starts with 01
if (previous == 0 and current == 1):
return i + 1
if __name__ == '__main__':
input = input()
from_, to = map(int, input.split())
print((get_fibonacci_rene(to + 2) - get_fibonacci_rene(from_ + 1)) % 10)
|
cb638e40fba6d5edeb377e2d9a67636c5e2ee2b7 | frostbooks/newbee-python | /二进制转化.py | 371 | 3.90625 | 4 | def trans(num):
temp = str(num)
if not temp.isdigit():
print('please enter a number!')
else:
list1 = []
result = ' '
while num :
a = num % 2
num = num //2
list1.append(a)
while list1:
result += str(list1.pop())
print(result)
|
aa71fd3d1f05d7eaaef2bb87d66ac2cd38ad3004 | rcrick/python-designpattern | /Singleton/SingletonSimple.py | 902 | 3.625 | 4 | # -*- coding: utf-8 -*-
# 使用__new__
class Singleton(object):
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance
def __init__(self, status_number):
self.status_number = status_number
s1 = Singleton(2)
s2 = Singleton(5)
print s1
print s2
print s1.status_number
print s2.status_number
#
# -------output-------
# <__main__.Singleton object at 0x7f7e2f776390>
# <__main__.Singleton object at 0x7f7e2f776390>
# 5
# 5
# -------output-------
#
# 使用装饰器
#
#
def Singleton(cls):
_instance = {}
def _singleton(*args, **kw):
if cls not in _instance:
_instance[cls] = cls(*args, **kw)
return _instance[cls]
return _singleton
@Singleton
class MyClass(object):
pass
print(MyClass() == MyClass())
|
2c890715e3cfbc4dd62a65ed763a34e7e1883996 | sungjun-ever/algorithm | /chap6/bubble_sort3.py | 546 | 3.6875 | 4 | def bubble_sort(a) -> None:
n = len(a)
l = 0
while l < n - 1:
print('사이클')
last = n - 1
for j in range(n - 1, l, -1):
if a[j-1] > a[j]:
a[j-1], a[j] = a[j], a[j-1]
last = j
print(''.join(str(a)))
l = last
print('버블 정렬')
num = int(input('원소 수를 입력하세요.: '))
x = [None] * num
for i in range(num):
x[i] = int(input(f'x[{i}]: '))
print('정렬 전')
print(''.join(str(x)))
print('\n정렬 후')
bubble_sort(x) |
33e5c5bd567f31cf822362aa6a599f0478e8c26e | torstenschenk/BeuthDevML | /Visual_n_Scientific_Comp/jupyter_files/vsc-05/k_nearest_neighbors.py | 2,373 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import glob
from collections import Counter
def distance(a, b):
"""calculates the distance between two vectors (or matrices)"""
# 2.1.1 Berechnen Sie die Distanz zwischen zwei Matritzen/Bildern
...
def knn(query, data, labels, k):
"""
Calculates the k-NN and returns the most common label appearing in the k-NN
and the number of occurrences.
For each data-record i the record consists of the datapoint (data[i]) and
the corresponding label (label[i]).
:param query: ndarray representing the query datapoint.
:param data: list of datapoints represents the database together with labels.
:param labels: list of labels represents the database together with data.
:param k: Number of nearest neighbors to consider.
:return: the label that occured the most under the k-NN and the number of occurrences.
"""
# 2.1 Berechnen Sie die Distanzen von query zu allen Elementen in data
# Implementieren Sie dazu die Funktion distance
...
# 2.2 Finden Sie die k nächsten datenpunkte in data
# 2.3 Geben Sie das Label, welches am häufigsten uner den k nächsten Nachbar
# vorkommt und die Häufigkeit als tuple zurück.
# Tipp: Counter(["a","b","c","b","b","d"]).most_common(1)[0]
# returned das häufigste Element der Liste und deren Anzahl also ("b", 3)
# ---------------------------------------------------------------------------
# k Nearest Neighbors
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# 1. Bauen Sie die Datenbank auf. Sie besteht aus zwei Listen.
# Einmal die Datenpunkte (die Bilder) und die dazugehörigen Label.
# Die beiden Listen werden seperat gespeichert, aber gehören zusammen, dh.
# Liste_der_Datenpunkte[i] gehört zu Liste_der_Labels[i].
# Die Listen sind also gleich lang.
# Tipp:
# mit glob.glob("images/db/test/*") bekommen Sie eine Liste mit allen Dateien in dem angegebenen Verzeichnis
...
# 2. Implementieren Sie die Funktion knn.
# 3. Laden Sie die Testbilder aus dem Ordner "images/db/test/" und rufen Sie
# auf der Datenbank knn auf. Geben Sie zu jedem Testbild das prognostizierte Label aus.
# Varieren Sie den Parameter k.
# Hinweis: Mit k = 5 sollte das beste Ergebnis erzielt werden.
|
c2b4bb0915c7b542c581bf4ba2749844dcaa2925 | rcsolis/data_algs_python | /lambdafunc.py | 965 | 3.828125 | 4 | # Lamba function is a one line anonymous function (without name)
# Define unsing lambda keyword
square = lambda x: x ** 2
print(square(2))
mult = lambda x, y: x ** y
print(mult(2, 4))
# Sorted method
persons = [("Rafael", 35), ("Emi", 15), ("Sof", 8), ("Sam", 20)]
sort_people = sorted(persons)
print(sort_people)
age_sort_people = sorted(persons, key=lambda x: x[1])
print(age_sort_people)
# Map method: Transforms each element whit a function
persons_map = map(lambda x: (x[0].upper(), x[1]), persons)
print(list(persons_map))
# Filter method: Returns all the elements that the function provided evaluates
# to True, the function always must returns true or false
persons_minors = filter(lambda x: x[1] < 18, persons)
print(list(persons_minors))
# Reduce method: Repeatedly applies the function to the elements and returns
# a single value
from functools import reduce
average_age = reduce(lambda x, y: x+y[1], persons, 0) // len(persons)
print(average_age)
|
90461d044cb0578aff8546760cf37c15103bfc1d | an4p/python_learning | /homework_02/hw02_02.py | 202 | 3.65625 | 4 | userInput = str(input("Please input something: "))
userInput1 = userInput[0:(len(userInput)+1)//2]
userInput2 = userInput[(len(userInput)+1)//2:]
userInputNew = userInput2+userInput1
print(userInputNew) |
2154784bf89a91358401cd6b342e3fa976e78475 | sahiti0707/Python_Learning | /15.py | 178 | 3.5 | 4 | print("Enter your name:")
x = input()
print("Hello,", x)
print("How are you?")
y = input()
print("Good.")
print("Which school?:")
x = input()
print("Okay . It's a good school ")
|
1a23a66365875d08ea398f9125ff5d730d7fca4d | ghost9023/DeepLearningPythonStudy | /DeepLearning/DeepLearning/02_Deep_ChoTH/deep_learning_1.py | 969 | 3.703125 | 4 | # 넘파이
# 넘파이의 산술연산
import numpy as np
x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 4.0, 6.0])
x + y
x - y
x * y
x / y
x = np.array([1.0, 2.0, 3.0])
x / 2.0
A = np.array([[1,2], [3,4]])
print(A)
A.shape
A.dtype
B = np.array([[3,0], [0,6]])
A + B
A * B # 배열연산
print(A)
A * 10
# 브로드캐스트
A = np.array([[1,2], [3,4]])
B = np.array([10, 20])
A * B
X = np.array([[51,55], [14,19], [0,4]])
print(X)
X[0]
X[0][1]
for row in X:
print(row)
X > 15
X[X>15] # 트루인 애들만 출력
# matplotlib
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,6,0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
x = np.arange(0, 6, 0.1) # 0 ~ 6, 0.1 간격으로 생성
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='sin')
plt.plot(x ,y2, linestyle='--', label='cos')
plt.xlabel('x') # x축 이름
plt.ylabel('y') # y축 이름
plt.title('sin & cos') # 제목
plt.show() # 안해도 그래프 그려짐 |
c4813b6ad6ca642f48c3c37a30b8dde0f0c14914 | carlos1500/Curso_Full-Stack_Blue | /Modulo 1/Exercícios de Aula/Aula 17/Exercício 1.py | 904 | 4.21875 | 4 | #1) Utilizando os conceitos de Orientação a Objetos (OO) vistos na aula anterior, crie um lançador de dados e moedas em que o usuário deve escolher o objeto a ser lançado. Não esqueça que os lançamentos são feitos de forma randômica.
import random
class Lançador():
def __init__(self, escolha):
self.escolha = escolha.upper()
self.escolher()
def lançarDado (self):
r = random.randint(1,6)
print(f"O dado sorteou o numero {r}.")
def lançarMoeda(self):
r = random.randint(1,2)
if r == 1:
r = "Cara"
else:
r = "Coroa"
print(f"Moeada caiu {r}.")
def escolher (self):
if self.escolha == "DADO":
self.lançarDado()
else:
self.lançarMoeda()
l = input("Escolha oque vc deseja lançar. DADO ou MOEDA: ")
lançar = Lançador(l)
|
767e3ea49510fe817906249ca65083c5595641cf | annaymj/LeetCode | /RemoveDuplicateInOrder.py | 435 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 14:34:33 2019
@author: annameng
input = [4,4,3,6,6,7,7,7],output = [4,3,6,7]
"""
input1 = [4,4,3,6,6,7,7,7]
def removeDuplicate_inOrder(nums):
dict_n = {}
for num in nums:
if num not in dict_n.keys():
dict_n[num] = 1
else:
dict_n[num] += 1
return list(dict_n.keys())
removeDuplicate_inOrder(input1) |
064544effad27ec442c7df4fe9b6ff282071a13c | aboubacardiawara/apprentissage | /c++/createFile.py | 1,349 | 3.53125 | 4 | #!/bin/python3
import re
if __name__ == '__main__':
import sys, re, os
def isValidArguments(args):
"""
CARACTERISTICS OF VALIDS ARGUMENTS:
- SIZE: 3
- ARGUMENT 1: ALPHANUMERIC CARACTERS.
- ARGUMENT 2: NUMERIC CARACTER.
- ARGUMENT 3: NUMERIC CARACTER.
- argument 2 must be higher than argument 1.
- argument can't be lower than 0.
"""
if len(args) != 3:
return False
arg1, arg2, arg3 = args
if not isAlphanumeric(arg1):
return False
if not isNumeric(arg2) or not isNumeric(arg3):
return False
if int(arg3) < int(arg3):
return False
return True
def isNumeric(chaine):
"""
"""
regex = "^[0-9]+$"
if re.match(regex, chaine):
return True
return False
def isAlphanumeric(chaine):
"""
"""
regex = "^[a-zA-Z0-9_]+$"
if re.match(regex, chaine):
return True
return False
if not isValidArguments(sys.argv[1:]):
print("usage: createFile <base> <i_0> <i_n>")
else:
base, arg1, arg2 = sys.argv[1:]
for i in range(int(arg1), int(arg2)+1):
os.system(f'mkdir {base}{i}')
|
bcba750a8fafe1da684cc82f03154c5247d50cd3 | avvRobertoAlma/esercizi-introduzione-algoritmi | /esame_14_01_2019.py | 345 | 3.671875 | 4 | def massimo(lista):
max_val = 0
if len(lista) == 1:
return lista[0]
else:
tmp = lista[len(lista)-1]
max_val = massimo(lista[:-1])
if tmp > max_val:
return tmp
else:
return max_val
if __name__ == "__main__":
l = [12, 45, 23, 88, 1, 9, 67]
print(massimo(l)) |
c49bce2c3d23370bceba6a49de2dd227c7cc2e4b | ScottSko/Python---Pearson---Third-Edition---Chapter-7 | /Chapter 7 - Programming Exercises - # 3 Rainfall Statistics.py | 507 | 3.890625 | 4 | def main():
index = 0
months = 12
total = 0
list = []
for x in range(months):
value = int(input("What was the total rainfall for the month? "))
list.append(value)
total += value
print("The total amount of rainfall was", total)
print("The average rainfall was", total / 12)
print("The lowest amount of rainfall during the year was", min(list))
print("The highest amount of rainfall during the year was", max(list))
main() |
c0e50bacea3ac7b13b570a4157bd021d541d3f08 | abby501198/Programming-for-Bussiness-Computing | /hw1(1).py | 572 | 3.71875 | 4 | # abby chang
# input
# 有五行input,一行一個數字
adult_num = int(input()) # 全票數量
adult_price = int(input()) # 全票售價
student_num = int(input()) # 學生票數量
student_price = int(input()) # 學生票售價
money = int(input()) # 給付櫃台的金額
ttl_price = adult_num * adult_price + student_num * student_price # 總應付金額
remaining = money - ttl_price # 櫃台找回來的錢
# output
if money < ttl_price: # 假設錢不夠
print("-1")
else: # 假設錢夠
print("$" + str(remaining))
|
4206f808de54f1bedf62a684ce6e0636719851af | RxDx/playfair | /cifrador.py | 4,456 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
def constroiListaAlfabeto():
alfabeto = "abcdefghiklmnopqrstuvwxyz"
lista = []
for letra in alfabeto:
lista.append(letra)
return lista
def normalizaTextoOriginal(textoOriginal):
posicaoAtual = 0
novoTexto = ""
textoOriginal = textoOriginal.lower()
textoOriginal = textoOriginal.replace(" ","")
textoOriginal = textoOriginal.replace(",","")
textoOriginal = textoOriginal.replace(".","")
while (posicaoAtual < len(textoOriginal)-1):
primeiraLetra = textoOriginal[posicaoAtual]
segundaLetra = textoOriginal[posicaoAtual+1]
if (primeiraLetra == segundaLetra):
novoTexto += primeiraLetra + "x"
posicaoAtual += 1
else:
novoTexto += primeiraLetra + segundaLetra
posicaoAtual += 2
if (posicaoAtual < len(textoOriginal)):
novoTexto += textoOriginal[posicaoAtual] + "x"
return novoTexto
def normalizaTextoDecifrado(textoDecifrado):
posicaoAtual = 0
novoTexto = ""
textoDecifrado = textoDecifrado.replace(" ", "")
# while (posicaoAtual < len(textoDecifrado)):
# primeiraLetra = textoDecifrado[posicaoAtual]
# segundaLetra = textoDecifrado[posicaoAtual+1]
#
# proximaLetra = ""
# if (posicaoAtual+2 < len(textoDecifrado)):
# proximaLetra = textoDecifrado[posicaoAtual+2]
#
# if (primeiraLetra == proximaLetra):
# novoTexto += primeiraLetra
# else:
# novoTexto += primeiraLetra + segundaLetra
#
# posicaoAtual += 2
novoTexto = textoDecifrado.replace("x", "")
if (novoTexto[len(novoTexto)-1] == "x"):
novoTexto = novoTexto[0:len(novoTexto)-1]
return novoTexto
def constroiMatriz(key):
alfabeto = constroiListaAlfabeto()
matriz = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
linha = 0
coluna = 0
posicao = 0
for letra in key:
linha = posicao / 5
coluna = posicao % 5
if (letra in alfabeto):
alfabeto.remove(letra)
matriz[linha][coluna] = letra
posicao += 1
while (len(alfabeto) > 0):
linha = posicao / 5
coluna = posicao % 5
matriz[linha][coluna] = alfabeto.pop(0)
posicao += 1
return matriz
def indiceDoElementoNaMatriz(matriz, elemento):
posicaoMatriz = 0
for linha in matriz:
for coluna in linha:
if (coluna == elemento):
return [posicaoMatriz/5, posicaoMatriz%5] # retorna [linha, coluna]
posicaoMatriz += 1
def cifraTextoClaro(textoClaro, matriz):
posicaoAtual = 0;
textoCifrado = ""
while (posicaoAtual < len(textoClaro)):
primeiraLetra = textoClaro[posicaoAtual]
segundaLetra = textoClaro[posicaoAtual+1]
indicePrimeiraLetra = indiceDoElementoNaMatriz(matriz, primeiraLetra)
indiceSegundaLetra = indiceDoElementoNaMatriz(matriz, segundaLetra)
if (indicePrimeiraLetra[0] == indiceSegundaLetra[0]): # estao na mesma linha
textoCifrado += matriz[indicePrimeiraLetra[0]][(indicePrimeiraLetra[1]+1)%5] + matriz[indiceSegundaLetra[0]][(indiceSegundaLetra[1]+1)%5]
if (indicePrimeiraLetra[1] == indiceSegundaLetra[1]): # estao na mesma coluna
textoCifrado += matriz[(indicePrimeiraLetra[0]+1)%5][indicePrimeiraLetra[1]] + matriz[(indiceSegundaLetra[0]+1)%5][indiceSegundaLetra[1]]
if (indicePrimeiraLetra[0] != indiceSegundaLetra[0] and indicePrimeiraLetra[1] != indiceSegundaLetra[1]): # estao em linhas e colunas diferentes
textoCifrado += matriz[indicePrimeiraLetra[0]][indiceSegundaLetra[1]] + matriz[indiceSegundaLetra[0]][indicePrimeiraLetra[1]]
posicaoAtual+=2
return textoCifrado
# CIFRADOR.PY
if (len(sys.argv) != 2):
print "Modo de uso: $ python cifrador chave"
exit()
entrada = open("textoclaro.txt", "r")
textoClaro = entrada.read()
f = open("textocifrado.txt", "w")
matriz = constroiMatriz(sys.argv[1])
# print matriz
textoCifrado = cifraTextoClaro(normalizaTextoOriginal(textoClaro), matriz)
print "Texto cifrado: " + textoCifrado
f.write(textoCifrado)
f.close() |
33bdec1d542048fcd2468d74f217981fdf8c70e0 | Vladarbinyan/GeekPython | /Lesson04/func_tools.py | 328 | 3.5625 | 4 | import functools
user_balances = {'Vasya': 500, 'Petya': 300, 'Nina': 1000}
def my_balance(total, amount):
return total + amount
# users_total = functools.reduce(my_balance, user_balances.values())
users_total = functools.reduce(
lambda total, amount: total+amount,
user_balances.values())
print(users_total)
|
944ec02f9589edac89d2c837e14938705fa6de71 | geunwooahn-dev/PythonAlgorithms | /Python_bj/etc/bj1181.py | 248 | 3.65625 | 4 | # 21.01.31 baekjoon 1181 단어정렬
n = int(input())
result = []
for i in range(n):
result.append(input())
result = list(set(result))
sorted_result = sorted(result, key = lambda x : (len(x), x))
for word in sorted_result:
print(word) |
4c35f0b024b36bed18a8e93996215e82285044f9 | jaresj/Python-Coding-Project | /Check Files Project/check_files_main.py | 2,213 | 3.703125 | 4 | # Python Ver: 3.8.2
#
# Author: Justice
#
# Purpose: Check Files
#
#
# Tested OS: This code was written and tested to work with windows 10.
from tkinter import *
import tkinter as tk
from tkinter import messagebox
# Be sure to import out other modules
# so we can have access to them
import check_files_gui
import check_files_func
# Frame is the tkinter frame class that our own class will inherit from
class ParentWindow(Frame):
def __init__(self, master, *args, **kwargs):
Frame.__init__(self, master, *args, *kwargs)
# define our master frame configuration
self.master = master
self.master.minsize(500,200) #(Height, Width)
self.master.maxsize(500,200)
# This CenterWindow method will center our app on the user's screen
check_files_func.center_window(self,500,200)
self.master.title("Check file")
self.master.configure(bg="#F0F0F0")
# This protocol method is a tkinter built-in method to catch if
# the user clicks the upper corner, "X" on Windows OS.
self.master.protocol("WM_DELETE_WINDOW", lambda: check_files_func.ask_quit(self))
arg = self.master
# load in the GUI widgets from a separeate module,
# keeping your code compartmentalized and clutter free
check_files_gui.load_gui(self)
"""
It is from these few lines of code that python will begin our gui and application
The (if __name__ == "__main__":) part is basically telling Python that if this script
is ran, it should start by running the code below this line....in this case we have
instructed Python to run the following in this order
root = tk.Tk() #This instantiates the Tk.() root frame (window into being
App = ParentWindow(root) #This instantiates our own class as an App object
root.mainloop() #This ensures the Tkinter class object, our window, to keep looping
#meaning, it will stay open until we instruct it to close
"""
if __name__ == "__main__":
root = tk.Tk()
App = ParentWindow(root)
root.mainloop()
|
c176a045c9fde53886e74233de87abc92dc02af5 | AravindVasudev/datastructures-and-algorithms | /problems/leetcode/prefix-and-suffix-search.py | 599 | 3.53125 | 4 | # https://leetcode.com/problems/prefix-and-suffix-search/
class WordFilter:
def __init__(self, words: List[str]):
self.mappings = {}
for weight, word in enumerate(words):
prefix = ""
for pre in [""] + list(word):
prefix += pre
suffix = ""
for suf in [""] + list(word[::-1]):
suffix += suf
self.mappings[f"{prefix}.{suffix[::-1]}"] = weight
def f(self, prefix: str, suffix: str) -> int:
return self.mappings.get(f"{prefix}.{suffix}", -1)
|
3137b8c7198220568d9584234085ffa0355a1d43 | matthewgiem/Socratica.py | /Python/class.py | 1,251 | 4 | 4 | import datetime
class User:
pass
user1 = User()
user1.first_name = 'Matt'
user1.last_name = 'Giem'
print(user1.last_name) # 'Giem'
first_name = 'Author'
last_name = 'Clarke'
print(user1.first_name, user1.last_name)
# "Matt Giem"
print(first_name, last_name)
# "Author Clarke"
user2 = User()
user2.first_name = 'Frank'
user2.last_name = 'Poole'
class User:
'''A member of FriendFace. For now we are
only storing their name and birthday
But soon we sill stroe an uncomfortable
amount of user information.'''
def __init__(self, full_name, birthday):
self.name = full_name
self.birthday = birthday # YYYMMDD
# extract first and last name
name_pieces = full_name.split(' ')
self.first_name = name_pieces[0]
self.last_name = name_pieces[-1]
def age(self):
"""Return the age of the user in years."""
today = datetime.date(2001, 5, 12)
yyyy = int(self.birthday[0:4)]
mm = int(self.birthday[4:6])
dd = int(self.birthday[6:8])
dob = datetime.date(yyyy, mm, dd) # Date of birthday
age_in_days = (today-dob).days
age_in_years = age_in_days/365
return age_in_years
user = User('Matthew Giem', '19850130')
|
7eee90f2a36945713d64a7a04d2ae47fccd268b8 | ja-vu/pythonProjects | /dice_roll/dice_roll.py | 438 | 4.03125 | 4 | from random import randint
min_val = 1
max_val = 6
# Dice needs to return a random value between 1 and 6
def roll_dice(low, high):
print(randint(low, high))
def start():
""" ASK USER IF THEY WANT TO ROLL A DICE """
roll_again = True
while roll_again:
roll_dice(min_val, max_val)
print("Do you want to re-roll? Y/N")
roll_again = "Y" in input().upper()
if __name__ == "__main__":
start()
|
e96d915151e03c215ed230b825bb378c631af9e2 | gotoindex/python-course | /tasks/task7/method1.py | 925 | 4.375 | 4 | import argparse
import math
class Sequence:
"""Displays all natural numbers whose square is less than n.\n
Any negative inputs will be converted into positive ones.
### Params:
- n - a positive integer. The square of each number in
the result will be smaller than this number.
"""
def __init__(self, n:int):
self.max = math.ceil(math.sqrt(n))
def __str__(self):
return ', '.join(tuple(str(i) for i in range(1, self.max)))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Display all natural numbers \
whose square is less than n.')
parser.add_argument('n', type=int,
help='a positive integer. The square of each number in \
the result will be smaller than this number')
args = parser.parse_args()
print(Sequence(abs(args.n)))
|
1a8f43068200b80588545093501318fc9e9c8f7b | romulofff/SD_2018 | /aula_invertida_data/json_example.py | 801 | 3.796875 | 4 | '''
############ SISTEMAS DISTRIBUÍDOS ############
Aula Invertida - Representação de Dados
GRUPO: Rômulo Férrer Filho, Rhaniel Magalhães, Marcus Vinicius, Pablo Grisi
'''
# Inicialmente importamos o pacote 'json' do Python
import json
# Agora devemos criar objetos que serão transformados em JSON
contacts = [
{
"nome": "Romulo",
"cidade": "Fortaleza",
"idade": 20
},
{
"nome": "Pablo",
"cidade": "Rio de Janeiro",
"idade": 20
},
{
"nome": "Rhaniel",
"cidade": "Itapipoca",
"idade": 21
},
{
"nome": "Marcus",
"cidade": "Fortaleza",
"idade": 21
}
] # fim contacts
# Convertendo para JSON
toJSON = json.dumps(contacts)
print(toJSON)
# Lendo JSON
fromJSON = json.loads(toJSON)
print(fromJSON[3]["idade"]) |
aa9cdcf475fd22e2e7e06f5bb640ffae2082090f | laukikk/Data-Structures | /Python/tree.py | 674 | 3.59375 | 4 | class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self .children.append(child)
def print_tree(self):
print
Tree = TreeNode('Pokemon')
Grass = TreeNode('Grass')
Fire = TreeNode('Fire')
Water = TreeNode('Water')
Grass.add_child(TreeNode('Bulbasaur'))
Grass.add_child(TreeNode('Ivysaur'))
Fire.add_child(TreeNode('Charmander'))
Fire.add_child(TreeNode('Charmeleon'))
Water.add_child(TreeNode('Squirtle'))
Water.add_child(TreeNode('Wartortle'))
Tree.add_child(Grass)
Tree.add_child(Water)
Tree.add_child(Fire) |
c0fefb996aca5adcb1ebc13d717c4b2cff1993da | guprahul7/leetcode | /DesignTicTacToe.py | 2,102 | 3.765625 | 4 |
class TicTacToeGame(object):
def __init__(self,n,p1,p2):
self.size = n
self.board = [[None for i in range(n)] for i in range(n)]
self.p1 = p1
self.p2 = p2
def playGame(self):
r,c = 0,0
turn = self.p1
result = False
nTurns = 0
while not result:
x = input()
nTurns += 1
draw = False
if turn == self.p1:
self.move(r,c,self.p1)
lastplayed = self.p1
turn = self.p2
else:
self.move(r,c,self.p2)
lastplayed = self.p2
turn = self.p1
if nTurns >= self.size:
result = self.checkResult()
if result:
if not draw:
winner = lastplayed
else:
winner = 'Draw'
def move(self,r,c,player):
self.board[r][c] = player
def checkResult(self):
for row in self.board:
if len(set(row)) == 1:
return True
break
for j in range(self.size):
st = set()
for i in range(self.size):
st.add(self.board[i][j])
if len(st) == 1:
return True
break
i,j = 0,0
x,y = 0,self.size-1
while (i<self.size and j<self.size) or (x<self.size and y>=0):
st_ij = set()
st_ij.add(self.board[i][j])
i += 1
j += 1
st_xy = set()
st_ij.add(self.board[x][y])
x += 1
y -= 1
if len(st_ij) == 1 or len(st_xy)==1:
return True
if nTurns == self.size * self.size:
draw = True
result = True
board = [[None for i in range(3)] for i in range(3)]
board[1][1] = 'x'
print(board[1][1],board[0][1])
|
0a6506bfda63c39cc3bf90d778a09ce0fefdf830 | dukeqiu/practicePython | /createCsv/outputCsvFile.py | 458 | 3.75 | 4 | import csv
a = "What's you name?"
b = "What's your company?"
c = "How old are you?"
info1 = [a,b,c]
def create(x,y,z):
with open(x,y) as f:
w = csv.writer(f, delimiter=",")
w.writerow(z)
create("../Desktop/info.csv","w",info1)
for i in range(1,5):
a1= input("What's you name: ")
b1= input("What's your company: ")
c1= input("How old are you: ")
info2 = [a1,b1,c1]
create("../Desktop/info.csv","a",info2)
|
ee3bdbe0e58b210b33e43504e5d8b53907925e7d | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_04/day04_Assignment7.py | 552 | 4.40625 | 4 | '''
7)Identify the missing piece of code in below program and write the correct answer to remove the error which we get when print statements are called
'''
def decorator(func):
def wrapper():
print("I am the decorator")
func()
return wrapper
@decorator
def function():
print("I am the function")
function()
'''
Explanation:
When we execute the above code, we get the error "TypeError: 'NoneType' object is not callable" but the expected output is
I am the decorator
I am the function.
Hint:
Decorators are expected to return "something".
'''
|
c57400522749fb76508c2ee5681f85eed6416bcb | tayloa/CSCI1100_Fall2015 | /Homeworks/hw3/hw3_util/hw3_part1.py | 1,560 | 3.625 | 4 | import hw3_util
teams = hw3_util.read_fifa()
team1 = int(raw_input("Team 1 id => "))
print team1
team2 = int(raw_input("Team 2 id => "))
print team2
points1 = teams[team1][2]*3 + teams[team1][3]
points2 = teams[team2][2]*3 + teams[team2][3]
gf1 = teams[team1][5]
gf2 = teams[team2][5]
diff1 = gf1 - teams[team1][6]
diff2 = gf2 - teams[team2][6]
space1 = " "*(20 - (len(teams[team1][0])))
space2 = " "*(20 - (len(teams[team2][0])))
if int(team2) == 7:
gf2 = 45
if int(team2) == 19:
gf2 = 43
print
print "Team".ljust(20)+"Win".ljust(6)+"Draw".ljust(6)+"Lose".ljust(6)+"GF".ljust(6)+"GA".ljust(6)+"Pts".ljust(6)+"GD".ljust(6)
print str(teams[team1][0]).ljust(20)+str(teams[team1][2]).ljust(6)+str(teams[team1][3]).ljust(6)+str(teams[team1][4]).ljust(6)+str(gf1).ljust(6)+str(teams[team1][6]).ljust(6)+str(points1).ljust(6)+str(diff1).ljust(6)
print str(teams[team2][0]).ljust(20)+str(teams[team2][2]).ljust(6)+str(teams[team2][3]).ljust(6)+str(teams[team2][4]).ljust(6)+str(gf2).ljust(6)+str(teams[team2][6]).ljust(6)+str(points2).ljust(6)+str(diff2).ljust(6)
if points1 > points2:
print teams[team1][0],"is better"
elif points2 > points1:
print teams[team2][0],"is better"
elif points1 == points2 and diff1 > diff2:
print teams[team1][0],"is better"
elif points1 == points2 and diff2 > diff1:
print teams[team2][0],"is better"
elif diff1 == diff2 and gf1 > gf2:
print teams[team1][0],"is better"
elif diff1 == diff2 and gf2 > gf1:
print teams[team2][0],"is better"
else:
print "Both teams are tied" |
6a76a58abee6342a13270b3edaddf5c1e2519ee1 | toasty-toast/project-euler | /python/euler_005.py | 242 | 3.5 | 4 | #!/usr/bin/env python2.7
"""
Problem 5: Smallest multiple
"""
import sys
if __name__ == "__main__":
num = 2520
while True:
for i in xrange(1, 21):
if num % i != 0:
break
if i == 20:
print num
sys.exit(0)
num += 2520
|
992ea444ea6bdd249c052c814088be5a7df142df | xvrdm/pmpac | /pmp003_01.py | 170 | 3.875 | 4 | import re
word = input("Please enter a word: ")
#if word[0] in 'aeiou':
if re.match('[aeiou]', word):
print(word + 'way')
else:
print(word[1:] + word[0] + 'ay')
|
d931893327697584c7ef2b118df294b134864eaf | Lehcs-py/guppe | /Seção_07/parte_1/Exercício_26.py | 381 | 3.96875 | 4 | print("""
26. Faça um programa que calcule o desvio padrão de um matriz v contendo n = 10 números, onde m é A media do matriz.
Desvio Padrão = d= √[(v1-m)²+...(v10-m)²]/(10-1)
""")
v = [36, 70, 7, 73, 45, 19, 22, 25, 90, 92]
m = sum(v)/len(v) # media
mq = 0 # media dos quadrados da diferença
for num in v:
mq += (m - num)**2
d = (mq/len(v))**0.5
print(d)
|
a78ba91de86fb1c092dbebc9d509dbef59284c1a | qwert19981228/P4 | /课件/0218/tcp_s.py | 479 | 3.5625 | 4 | # 导包
import socket
# 创建套接字对象
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定ip和端口号
sock.bind(('',8090))
# 监听 队列
sock.listen()
# 接收 sock对象,客户端地址
s,addr = sock.accept()
data = s.recv(1024)
print(data.decode('utf-8'))
s.send('HTTP/1.1 200 OK\r\n'.encode('utf-8'))
s.send('Content-Type: text/html\r\n'.encode('utf-8'))
s.send('\r\n'.encode('utf-8'))
s.send('hello'.encode('utf-8'))
# 关闭套接字
sock.close() |
ecd257cfba3fb2015533329abd4d39416c3be48a | apiccone/Euler-Problems | /Problem 3.py | 691 | 3.84375 | 4 | """
Ashley Piccone
Euler Problem 3: Largest Prime Factor
"""
import numpy as np
def prime_test(num):
# determines if a number is prime
arr = []
for k in range(2,num):
# for k from 2 until the user's entry num
# append the remainder of dividing num by k
arr.append(num % k)
if (arr.count(0) == 0):
# if that remainder is never zero, the num is prime
return True
else:
return False
n = np.long(600851475143)
arr = []
for k in range(2,int(np.sqrt(n)+1)):
if (n % k == 0 and prime_test(k) == True):
arr.append(k)
print ( "Problem 2: The greatest prime factor of 600851475143 is", arr[-1]) |
ebbafc97e7086a80fd2cb183fe712f1e9856e3d9 | winstonfy/python_life | /base_py/5 object-oriented/8 metaclass.py | 17,117 | 4.34375 | 4 | #__author__ = 'Winston'
#date: 2020/4/2
# 元类
# 什么是元类呢?一切源自于一句话:python中一切皆为对象。让我们先定义一个类,然后逐步分析
class StanfordTeacher(object):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
# 所有的对象都是实例化或者说调用类而得到的(调用类的过程称为类的实例化),
# 比如对象t1是调用类StanfordTeacher得到的
t1=StanfordTeacher('winston',18)
print(type(t1)) #查看对象t1的类是<class '__main__.StanfordTeacher'>
# 如果一切皆为对象,那么类StanfordTeacher本质也是一个对象,既然所有的对象都是调用类得到的,
# 那么StanfordTeacher必然也是调用了一个类得到的,这个类称为元类
print(type(StanfordTeacher)) # 结果为<class 'type'>,
# 证明是调用了type这个元类而产生的StanfordTeacher,即默认的元类为type
# class关键字创建类的流程分析
# class关键字在帮我们创建类时,必然帮我们调用了元类StanfordTeacher=type(...),
# 那调用type时传入的参数是什么呢?必然是类的关键组成部分,一个类有三大组成部分,分别是
# 1、类名class_name='StanfordTeacher'
# 2、基类们class_bases=(object,)
# 3、类的名称空间class_dic,类的名称空间是执行类体代码而得到的
# 调用type时会依次传入以上三个参数
# 综上,class关键字帮我们创建一个类应该细分为以下四个过程
# 一个类没有声明自己的元类,默认他的元类就是type,
# 除了使用内置元类type,我们也可以通过继承type来自定义元类,
# 然后使用metaclass关键字参数为一个类指定元类
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
pass
# StanfordTeacher=Mymeta('StanfordTeacher',(object),{...})
class StanfordTeacher(object,metaclass=Mymeta):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
# 自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程,
# 即StanfordTeacher=Mymeta('StanfordTeacher',(object),{...}),
# 调用Mymeta会先产生一个空对象StanfordTeacher,
# 然后连同调用Mymeta括号内的参数一同传给Mymeta下的__init__方法,完成初始化,于是我们可以
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
def __init__(self,class_name,class_bases,class_dic):
# print(self) #<class '__main__.StanfordTeacher'>
# print(class_bases) #(<class 'object'>,)
# print(class_dic) #{'__module__': '__main__', '__qualname__': 'StanfordTeacher', 'school': 'Stanford', '__init__': <function StanfordTeacher.__init__ at 0x102b95ae8>, 'say': <function StanfordTeacher.say at 0x10621c6a8>}
super(Mymeta, self).__init__(class_name, class_bases, class_dic) # 重用父类的功能
if class_name.islower():
raise TypeError('类名%s请修改为驼峰体' %class_name)
if '__doc__' not in class_dic or len(class_dic['__doc__'].strip(' \n')) == 0:
raise TypeError('类中必须有文档注释,并且文档注释不能为空')
# StanfordTeacher=Mymeta('StanfordTeacher',(object),{...})
class StanfordTeacher(object,metaclass=Mymeta):
"""
类StanfordTeacher的文档注释
"""
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
# 自定义元类控制类StanfordTeacher的调用
# 储备知识:__call__
class Foo:
def __call__(self, *args, **kwargs):
print(self)
print(args)
print(kwargs)
obj=Foo()
#1、要想让obj这个对象变成一个可调用的对象,需要在该对象的类中定义一个方法__call__方法,该方法会在调用对象时自动触发
#2、调用obj的返回值就是__call__方法的返回值
res=obj(1,2,3,x=1,y=2)
# 由上例得知,调用一个对象,就是触发对象所在类中的__call__方法的执行,
# 如果把StanfordTeacher也当做一个对象,
# 那么在StanfordTeacher这个对象的类中也必然存在一个__call__方法
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
def __call__(self, *args, **kwargs):
print(self) #<class '__main__.StanfordTeacher'>
print(args) #('lili', 18)
print(kwargs) #{}
return 123
class StanfordTeacher(object,metaclass=Mymeta):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
# 调用StanfordTeacher就是在调用StanfordTeacher类中的__call__方法
# 然后将StanfordTeacher传给self,溢出的位置参数传给*,溢出的关键字参数传给**
# 调用StanfordTeacher的返回值就是调用__call__的返回值
t1=StanfordTeacher('lili',18)
print(t1) #123
# 默认地,调用t1=StanfordTeacher('lili',18)会做三件事
#
# 1、产生一个空对象obj
#
# 2、调用__init__方法初始化对象obj
#
# 3、返回初始化好的obj
#
# 对应着,StanfordTeacher类中的__call__方法也应该做这三件事
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
#1、调用__new__产生一个空对象obj
obj=self.__new__(self) # 此处的self是类OldoyTeacher,必须传参,代表创建一个StanfordTeacher的对象obj
#2、调用__init__初始化空对象obj
self.__init__(obj,*args,**kwargs)
#3、返回初始化好的对象obj
return obj
class StanfordTeacher(object,metaclass=Mymeta):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
t1t1=StanfordTeacher('lili',18)
print(t1.__dict__) #{'name': 'lili', 'age': 18}
# 上例的__call__相当于一个模板,
# 我们可以在该基础上改写__call__的逻辑从而控制调用StanfordTeacher的过程,
# 比如将StanfordTeacher的对象的所有属性都变成私有的
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
#1、调用__new__产生一个空对象obj
obj=self.__new__(self) # 此处的self是类StanfordTeacher,必须传参,代表创建一个StanfordTeacher的对象obj
#2、调用__init__初始化空对象obj
self.__init__(obj,*args,**kwargs)
# 在初始化之后,obj.__dict__里就有值了
obj.__dict__={'_%s__%s' %(self.__name__,k):v for k,v in obj.__dict__.items()}
#3、返回初始化好的对象obj
return obj
class StanfordTeacher(object,metaclass=Mymeta):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
t1=StanfordTeacher('lili',18)
print(t1.__dict__) #{'_StanfordTeacher__name': 'lili', '_StanfordTeacher__age': 18}
# 属性的查找顺序
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
n=444
def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
obj=self.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Bar(object):
n=333
class Foo(Bar):
n=222
class StanfordTeacher(Foo,metaclass=Mymeta):
n=111
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
print(StanfordTeacher.n) #自下而上依次注释各个类中的n=xxx,然后重新运行程序,发现n的查找顺序为StanfordTeacher->Foo->Bar->object->Mymeta->type
# 属性查找应该分成两层,一层是对象层(基于c3算法的MRO)的查找,
# 另外一个层则是类层(即元类层)的查找
#查找顺序:
#1、先对象层:StanfordTeacher->Foo->Bar->object
#2、然后元类层:Mymeta->type
# 析下元类Mymeta中__call__里的self.__new__的查找
class Mymeta(type):
n=444
def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
obj=self.__new__(self)
print(self.__new__ is object.__new__) #True
class Bar(object):
n=333
# def __new__(cls, *args, **kwargs):
# print('Bar.__new__')
class Foo(Bar):
n=222
# def __new__(cls, *args, **kwargs):
# print('Foo.__new__')
class StanfordTeacher(Foo,metaclass=Mymeta):
n=111
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
# def __new__(cls, *args, **kwargs):
# print('StanfordTeacher.__new__')
StanfordTeacher('lili',18) #触发StanfordTeacher的类中的__call__方法的执行,进而执行self.__new__开始查找
# 总结,
# Mymeta下的__call__里的self.__new__在StanfordTeacher、Foo、Bar里都没有
# 找到__new__的情况下,会去找object里的__new__,而object下默认就
# 有一个__new__,所以即便是之前的类均未实现__new__,也一定会
# 在object中找到一个,根本不会、也根本没必要再去找元类Mymeta->type中查找__new__
# 在元类的__call__中也可以用object.__new__(self)去造对象
# 但我们还是推荐在__call__中使用self.__new__(self)去创造空对象,
# 因为这种方式会检索三个类StanfordTeacher->Foo->Bar,而object.__new__则是直接跨过了他们三个
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
n=444
def __new__(cls, *args, **kwargs):
obj=type.__new__(cls,*args,**kwargs) # 必须按照这种传值方式
print(obj.__dict__)
# return obj # 只有在返回值是type的对象时,才会触发下面的__init__
return 123
def __init__(self,class_name,class_bases,class_dic):
print('run。。。')
class StanfordTeacher(object,metaclass=Mymeta): #StanfordTeacher=Mymeta('StanfordTeacher',(object),{...})
n=111
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.name)
print(type(Mymeta)) #<class 'type'>
# 产生类StanfordTeacher的过程就是在调用Mymeta,而Mymeta也是type类的一个对象,那么Mymeta之所以可以调用,一定是在元类type中有一个__call__方法
# 该方法中同样需要做至少三件事:
# class type:
# def __call__(self, *args, **kwargs): #self=<class '__main__.Mymeta'>
# obj=self.__new__(self,*args,**kwargs) # 产生Mymeta的一个对象
# self.__init__(obj,*args,**kwargs)
# return obj
# 在元类中控制把自定义类的数据属性都变成大写
class Mymetaclass(type):
def __new__(cls,name,bases,attrs):
update_attrs={}
for k,v in attrs.items():
if not callable(v) and not k.startswith('__'):
update_attrs[k.upper()]=v
else:
update_attrs[k]=v
return type.__new__(cls,name,bases,update_attrs)
class Chinese(metaclass=Mymetaclass):
country='China'
tag='Legend of the Dragon' #龙的传人
def walk(self):
print('%s is walking' %self.name)
print(Chinese.__dict__)
'''
{'__module__': '__main__',
'COUNTRY': 'China',
'TAG': 'Legend of the Dragon',
'walk': <function Chinese.walk at 0x0000000001E7B950>,
'__dict__': <attribute '__dict__' of 'Chinese' objects>,
'__weakref__': <attribute '__weakref__' of 'Chinese' objects>,
'__doc__': None}
'''
# 在元类中控制自定义的类无需__init__方法
#
# 1.元类帮其完成创建对象,以及初始化操作;
#
# 2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
#
# 3.key作为用户自定义类产生对象的属性,且所有属性变成大写
class Mymetaclass(type):
# def __new__(cls,name,bases,attrs):
# update_attrs={}
# for k,v in attrs.items():
# if not callable(v) and not k.startswith('__'):
# update_attrs[k.upper()]=v
# else:
# update_attrs[k]=v
# return type.__new__(cls,name,bases,update_attrs)
def __call__(self, *args, **kwargs):
if args:
raise TypeError('must use keyword argument for key function')
obj = object.__new__(self) #创建对象,self为类Foo
for k,v in kwargs.items():
obj.__dict__[k.upper()]=v
return obj
class Chinese(metaclass=Mymetaclass):
country='China'
tag='Legend of the Dragon' #龙的传人
def walk(self):
print('%s is walking' %self.name)
p=Chinese(name='lili',age=18,sex='male')
print(p.__dict__)
# 在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
#控制类Foo的创建
super(Mymeta,self).__init__(class_name,class_bases,class_dic)
def __call__(self, *args, **kwargs):
#控制Foo的调用过程,即Foo对象的产生过程
obj = self.__new__(self)
self.__init__(obj, *args, **kwargs)
obj.__dict__={'_%s__%s' %(self.__name__,k):v for k,v in obj.__dict__.items()}
return obj
class Foo(object,metaclass=Mymeta): # Foo=Mymeta(...)
def __init__(self, name, age,sex):
self.name=name
self.age=age
self.sex=sex
obj=Foo('lili',18,'male')
print(obj.__dict__)
#步骤五:基于元类实现单例模式
# 单例:即单个实例,指的是同一个类实例化多次的结果指向同一个对象,用于节省内存空间
# 如果我们从配置文件中读取配置来进行实例化,在配置相同的情况下,就没必要重复产生对象浪费内存了
#settings.py文件内容如下
HOST='1.1.1.1'
PORT=3306
#方式一:定义一个类方法实现单例模式
import settings
class Mysql:
__instance=None
def __init__(self,host,port):
self.host=host
self.port=port
@classmethod
def singleton(cls):
if not cls.__instance:
cls.__instance=cls(settings.HOST,settings.PORT)
return cls.__instance
obj1=Mysql('1.1.1.2',3306)
obj2=Mysql('1.1.1.3',3307)
print(obj1 is obj2) #False
obj3=Mysql.singleton()
obj4=Mysql.singleton()
print(obj3 is obj4) #True
#方式二:定制元类实现单例模式
import settings
class Mymeta(type):
def __init__(self,name,bases,dic): #定义类Mysql时就触发
# 事先先从配置文件中取配置来造一个Mysql的实例出来
self.__instance = object.__new__(self) # 产生对象
self.__init__(self.__instance, settings.HOST, settings.PORT) # 初始化对象
# 上述两步可以合成下面一步
# self.__instance=super().__call__(*args,**kwargs)
super().__init__(name,bases,dic)
def __call__(self, *args, **kwargs): #Mysql(...)时触发
if args or kwargs: # args或kwargs内有值
obj=object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
return self.__instance
class Mysql(metaclass=Mymeta):
def __init__(self,host,port):
self.host=host
self.port=port
obj1=Mysql() # 没有传值则默认从配置文件中读配置来实例化,所有的实例应该指向一个内存地址
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3)
obj4=Mysql('1.1.1.4',3307)
#方式三:定义一个装饰器实现单例模式
import settings
def singleton(cls): #cls=Mysql
_instance=cls(settings.HOST,settings.PORT)
def wrapper(*args,**kwargs):
if args or kwargs:
obj=cls(*args,**kwargs)
return obj
return _instance
return wrapper
@singleton # Mysql=singleton(Mysql)
class Mysql:
def __init__(self,host,port):
self.host=host
self.port=port
obj1=Mysql()
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3) #True
obj4=Mysql('1.1.1.3',3307)
obj5=Mysql('1.1.1.4',3308)
print(obj3 is obj4) #False |
fcbacd6e4e24808e6f40d4fa26c6529c8842d170 | christophersousa/Primeiro-Periodo | /APE/ape/Terceira semana/questão 2.py | 510 | 3.78125 | 4 | m = int(input('Matrícula do operário: '))
p = int(input('Quantidades de peças fabricadas no mês : '))
peças = p - 30
bonus = peças * 10
sm = 1045
if p > 30:
salario = bonus + sm
print(f' O empregado de matrícula {m} \n classificado na classe B \n receberá um bônus salarial de R${bonus}')
print(f' Salario = {salario: .2f}')
else:
print(f' O empregado de matrícula {m} \n classificado na classe A \n receberá um bônus salarial de R$ 0')
print(f' Salario = {sm: .2f}')
|
9deee0f4effcbe6c525ad0393b97ae74d886dcfa | UserWangjn/JieYueProject | /Test/Demo/打印松树.py | 112 | 3.734375 | 4 | i = 0
while i < 5:
u = 0
while u < 5:
print("*"),
u = u +1
print("")
i = i + 1 |
4a6df3699b00e3a74f800db90439554db97d09f1 | mrinalmayank7/python-programming | /CLASSES & OBJECTS/M_Overloading.py | 467 | 3.6875 | 4 | class CSE8:
def __init__(self,o1,o2):
self.o1=o1
self.o2=o2
def arithmetic(self , a=None,b=None,c=None):
add,mul=0,0
if a!=None and b!=None and c!=None:
add = a+b+c
mul = a*b*c
elif a!=None and b!=None:
add = a+b
mul = a*b
else:
add = a
mul = a
return add , mul
s1 = CSE8(58,60)
print(s1.arithmetic(2,3,4))
|
cfd18aae6837149ce0b01136cdc5bf15bec2275c | phillib/P4E-Python- | /Loops/counting.py | 191 | 3.890625 | 4 | zork = 0
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + 1
print zork, thing
print 'After', zork
# This loop will count the total number of objects in a list
|
9a7be3e60f7cf8c13ded8982a9aa60bdb2cb1685 | joycetan12/NLP_Fall2020 | /NLP_HW1/NLP_HW1.py | 13,143 | 3.59375 | 4 | # Author: Joyce Tan
# NLP Fall 2020 - HW1
import math
# this method pads each sentence and lowercase all words
# returns a processed sentence
def preprocess(text):
cleanText = '<s> '
text = text.lower()
cleanText += text
cleanText += ' </s>'
return cleanText
# this method pads and lowercase each sentence in a file
# returns a list of processed sentences
def create_processed_list(filename):
processed_list_of_lines = []
with open(filename) as file:
for line in file:
line = preprocess(line)
split_line = line.split()
processed_list_of_lines.append(split_line)
return processed_list_of_lines
# this method calculates the the log probability under the unigram maximum likelihood model
def log_probability_unigram(unigram, total_tokens, sentence, print_param):
log_probability = 0
undefined = False
for word in sentence:
if word not in unigram:
undefined = True
if print_param:
print('p(', word, ') = 0')
print('log(p(', word, ')) = NaN')
else:
if print_param:
print('p(', word, ') =', (unigram[word] / total_tokens))
print('log(p(', word, ')) =', math.log((unigram[word] / total_tokens), 2))
log_probability += math.log((unigram[word] / total_tokens), 2)
if undefined:
return 'NaN'
return log_probability
# this method calculates the the log probability under the bigram maximum likelihood model
def log_probability_bigram(bigram, unigram, sentence,print_param):
log_probability = 0
undefined = False
for i in range(len(sentence)):
word = sentence[i]
if word != '</s>':
nextWord = sentence[i+1]
if (word,nextWord) not in bigram:
undefined = True
if print_param:
print('p(', nextWord, '|', word, ') = 0')
print('log(p(', nextWord, '|', word, ')) = NaN')
else:
if print_param:
print('p(', nextWord, '|', word, ') =', bigram[(word,nextWord)]/unigram[word])
print('log(p(', nextWord, '|', word, ')) =', math.log(bigram[(word,nextWord)]/unigram[word], 2))
log_probability += math.log(bigram[(word,nextWord)]/unigram[word], 2)
if undefined:
return 'NaN'
return log_probability
# this method is used to calculate the the log probability under the bigram model add-one smoothing
def log_probability_bigram_smoothing(bigram, unigram, sentence, print_param):
log_probability = 0
V = len(unigram)
for i in range(len(sentence)):
numerator = 1
denominator = V
word = sentence[i]
if word != '</s>':
nextWord = sentence[i+1]
if (word,nextWord) in bigram:
numerator = bigram[(word, nextWord)] + 1
if word in unigram:
denominator = unigram[word] + V
if print_param:
print('p(', nextWord, '|', word, ') =', numerator/denominator)
print('log(p(', nextWord, '|', word, ')) =', math.log(numerator/denominator, 2))
log_probability += math.log(numerator/denominator, 2)
return log_probability
# this method is used to calculate perplexity
def perplexity(total_tokens,log_prob_sentence):
if log_prob_sentence == 'NaN':
return 'NaN'
l = log_prob_sentence/total_tokens
p = 2**(l*-1)
return p
# create processed list of sentences
processed_sentences_train = create_processed_list('train.txt')
processed_sentences_test = create_processed_list('test.txt')
# create training corpus unigram before mapping <unk>
train_unigram = {}
train_unigram_tokens = 0
for line in processed_sentences_train:
for i in range(len(line)):
train_unigram_tokens += 1
word = line[i]
if word in train_unigram:
train_unigram[word] += 1
else:
train_unigram[word] = 1
# create training corpus unigram after mapping <unk>
train_unigram_with_unk = {}
train_with_unk_tokens = 0
for line in processed_sentences_train:
for i in range(len(line)):
train_with_unk_tokens += 1
word = line[i]
if train_unigram[word] == 1:
word = '<unk>'
if word in train_unigram_with_unk:
train_unigram_with_unk[word] += 1
else:
train_unigram_with_unk[word] = 1
print('# of word types in training corpus after mapping <unk>:', len(train_unigram_with_unk))
print('# of word tokens in training corpus:', train_with_unk_tokens)
# find words in test corpus that do not occur in training corpus
test_unigram = {}
test_total_tokens = 0
test_tokens_not_in_train = 0
word_not_in_train = [] # words not in training corpus before mapping <unk>
word_not_in_train_with_unk = [] # words not in training corpus after mapping <unk>
for line in processed_sentences_test:
for i in range(len(line)):
test_total_tokens += 1
word = line[i]
if word not in train_unigram:
test_tokens_not_in_train += 1
if word not in test_unigram:
word_not_in_train.append(word)
if word not in train_unigram_with_unk:
if word not in test_unigram:
word_not_in_train_with_unk.append(word)
if word in test_unigram:
test_unigram[word] += 1
else:
test_unigram[word] = 1
# calculate percentage of word tokens in test corpus that did not occur in training corpus
test_token_not_in_train_percentage = test_tokens_not_in_train/test_total_tokens
test_token_not_in_train_percentage = "{:.1%}".format(test_token_not_in_train_percentage)
# calculate percentage of unique words in test corpus that did not occur in training corpus
test_word_not_in_train_percentage = len(word_not_in_train)/len(test_unigram)
test_word_not_in_train_percentage = "{:.1%}".format(test_word_not_in_train_percentage)
print('percentage of word tokens in test corpus not in training corpus before mapping <unk> =', test_token_not_in_train_percentage)
print('percentage of word types in test corpus not in training corpus before mapping <unk> =', test_word_not_in_train_percentage)
# create test corpus unigram after mapping <unk>
test_unigram_with_unk = {}
test_with_unk_tokens = 0
for line in processed_sentences_test:
for i in range(len(line)):
test_with_unk_tokens += 1
if line[i] in word_not_in_train_with_unk:
line[i] = '<unk>'
if line[i] in test_unigram_with_unk:
test_unigram_with_unk[line[i]] += 1
else:
test_unigram_with_unk[line[i]] = 1
# create training corpus bigram after mapping <unk>
train_bigram_with_unk = {}
train_bigram_token_with_unk = 0
for line in processed_sentences_train:
for i in range(len(line)):
if line[i] != '</s>':
word = line[i]
nextWord = line[i + 1]
train_bigram_token_with_unk += 1
if train_unigram[word] == 1:
word = '<unk>'
if train_unigram[nextWord] == 1:
nextWord = '<unk>'
if (word, nextWord) in train_bigram_with_unk:
train_bigram_with_unk[word, nextWord] += 1
else:
train_bigram_with_unk[word, nextWord] = 1
# create test corpus bigram after mapping <unk> words not observed in the training corpus (with mapped <unk>)
test_bigram_with_unk = {}
test_bigram_tokens_with_unk = 0
for line in processed_sentences_test:
for i in range(len(line)):
if line[i] != '</s>':
word = line[i]
nextWord = line[i + 1]
test_bigram_tokens_with_unk += 1
if word in word_not_in_train_with_unk:
word = '<unk>'
if nextWord in word_not_in_train_with_unk:
nextWord = '<unk>'
if (word, nextWord) in test_bigram_with_unk:
test_bigram_with_unk[word, nextWord] += 1
else:
test_bigram_with_unk[word, nextWord] = 1
# find bigrams in test corpus (with mapped <unk>) that do not occur in training corpus (with mapped <unk>)
bigrams_not_in_train = []
test_bigram_types_not_in_train = 0
test_bigram_tokens_not_in_train = 0
for bigram in test_bigram_with_unk:
if bigram not in train_bigram_with_unk:
bigrams_not_in_train.append(bigram)
test_bigram_types_not_in_train += 1
test_bigram_tokens_not_in_train += test_bigram_with_unk[bigram]
# calculate the percentage of word tokens in test corpus did not occur in training corpus
test_bigram_tokens_not_in_train_percentage = test_bigram_tokens_not_in_train/test_bigram_tokens_with_unk
test_bigram_tokens_not_in_train_percentage = "{:.1%}".format(test_bigram_tokens_not_in_train_percentage)
# calculate the percentage of word types in test corpus did not occur in training corpus
test_bigram_types_not_in_train_percentage = test_bigram_types_not_in_train/len(test_bigram_with_unk)
test_bigram_types_not_in_train_percentage = "{:.1%}".format(test_bigram_types_not_in_train_percentage)
print('percentage of bigram tokens in test corpus not in training corpus =', test_bigram_tokens_not_in_train_percentage)
print('percentage of bigram types in test corpus not in training corpus =', test_bigram_types_not_in_train_percentage)
print('')
# process sentence
sentence = "• I look forward to hearing your reply ."
sentence = preprocess(sentence).split()
# calculate the log probability of the sentence under the unigram maximum likelihood model
print('Sentence log probability unigram parameters:')
log_prob_sentence_unigram = log_probability_unigram(train_unigram_with_unk, train_with_unk_tokens, sentence, True)
print('Sentence log probability: unigram =', log_prob_sentence_unigram)
print('')
# calculate the log probability of the sentence under the bigram maximum likelihood model
print('Sentence log probability bigram parameters:')
log_prob_sentence_bigram = log_probability_bigram(train_bigram_with_unk, train_unigram_with_unk, sentence, True)
print('Sentence log probability: bigram =', log_prob_sentence_bigram)
print('')
# calculate the log probability of the sentence under the bigram model with add-one smoothing
print('Sentence log probability bigram add one smoothing parameters:')
log_prob_sentence_bigram_smoothing = log_probability_bigram_smoothing(train_bigram_with_unk, train_unigram_with_unk, sentence, True)
print('Sentence log probability: bigram add one smoothing =', log_prob_sentence_bigram_smoothing)
print('')
# calculate the perplexity of the sentence under the unigram maximum likelihood model
print('Perplexity of sentence under unigram model =', perplexity(len(sentence),log_prob_sentence_unigram))
# calculate the perplexity of the sentence under the bigram maximum likelihood model
print('Perplexity of sentence under bigram model =', perplexity(len(sentence),log_prob_sentence_bigram))
# calculate the perplexity of the sentence under the bigram model with add-one smoothing
print('Perplexity of sentence under bigram add one smoothing model =', perplexity(len(sentence),log_prob_sentence_bigram_smoothing))
print('')
# calculate perplexity of the entire test corpus under the unigram maximum likelihood model
log_prob_test_unigram = 0
for sentence in processed_sentences_test:
if log_probability_unigram(train_unigram_with_unk, train_with_unk_tokens, sentence, False) == 'NaN':
log_prob_test_unigram = 'NaN'
break
else:
log_prob_test_unigram += log_probability_unigram(train_unigram_with_unk, train_with_unk_tokens, sentence, False)
perplexity_test_unigram = perplexity(test_with_unk_tokens, log_prob_test_unigram)
print('Perplexity of test corpus under unigram model =', perplexity_test_unigram)
# calculate perplexity of the entire test corpus under the bigram maximum likelihood model
log_prob_test_bigram = 0
for sentence in processed_sentences_test:
if log_probability_bigram(train_bigram_with_unk, train_unigram_with_unk, sentence, False) == 'NaN':
log_prob_test_bigram = 'NaN'
break
else:
log_prob_test_bigram += log_probability_bigram(train_bigram_with_unk, train_unigram_with_unk, sentence, False)
perplexity_test_bigram = perplexity(test_with_unk_tokens, log_prob_test_bigram)
print('Perplexity of test corpus under bigram model =', perplexity_test_bigram)
# calculate perplexity of the entire test corpus under the bigram model with add-one smoothing
log_prob_test_bigram_smoothing = 0
for sentence in processed_sentences_test:
if log_probability_bigram_smoothing(train_bigram_with_unk, train_unigram_with_unk, sentence, False) == 'NaN':
log_prob_test_bigram_smoothing = 'NaN'
break
else:
log_prob_test_bigram_smoothing += log_probability_bigram_smoothing(train_bigram_with_unk, train_unigram_with_unk, sentence, False)
perplexity_test_bigram_smoothing = perplexity(test_with_unk_tokens, log_prob_test_bigram_smoothing)
print('Perplexity of test corpus under bigram add one smoothing model =', perplexity_test_bigram_smoothing)
|
8affa414845860649e7a97f93a87dff5a367e92e | jsadsad/aA_Python | /w1/d3/input_ex.py | 113 | 3.75 | 4 | print("hello world")
answer = input("how are you? ") # <== notice space before closing quote
print("I am fine")
|
85a719e6a32a3da63e0c355dd3980d644e2faa93 | abipriebe/CSE111 | /Week 2/week 2 notes.py | 773 | 4.03125 | 4 | #if statements
x = 5
y = 6
print(x < y)
favoriteNumbersList = [3,4,5,6,7,8]
if (4 in favoriteNumbersList):
print("this was true")
if (10 not in favoriteNumbersList):
print("this was true")
name = "Joey"
if("j" in name):
print("J is in the name")
else:
print("j is not in the name")
print(x < y and y < 3)
print(x < y or y < 3)
#error checking - repeating commands/traversing data
userWantsMore = True
while(userWantsMore):
userInput = input("Do you have another tire? (y/n)")
if(userInput == "n"):
userWantsMore = False #you could also use break here
#functions
import math
def computeCircumference(radius):
return 2 * math.pi * radius
userRadius = float(input("Please enter a radius: "))
print(computeCircumference(userRadius)) |
3aef37bb61835ad76fc8a88afbe6cda0b1c2bdab | abelvdavid/100DaysofCode | /day11/reverselinkedList.py | 960 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def printList(self):
curr = self.head
while(curr):
print(curr.data)
curr = curr.next
def isPalindrome(ll):
if(ll.head is None):
return True
reversedLinkedList = reverse(ll)
curr = ll.head
rcurr = reversedLinkedList.head
while(curr):
if curr.data != rcurr.data:
return False
curr = curr.next
rcurr = rcurr.next
return True
def reverse(ll):
prev = None
curr = ll.head
while(curr):
next = curr.next
curr.next = prev
prev = curr
curr = next
ll.head = prev
result = LinkedList()
temp = ll.head
while(temp):
result.push(temp.data)
temp = temp.next
return result
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(4)
llist.push(20)
print(isPalindrome(llist)) |
5bf318be65dea2bcf86ed0f785e0e943a8981667 | Muhammad-Hammad-Ur-Rehman/MITx6.86x | /Projects/Digit Recognition (Project 2-3)/part1/svm.py | 2,003 | 3.578125 | 4 | import numpy as np
from sklearn.svm import LinearSVC
### Functions for you to fill in ###
def one_vs_rest_svm(train_x, train_y, test_x, C):
"""
Trains a linear SVM for binary classifciation
Args:
train_x - (n, d) NumPy array (n datapoints each with d features)
train_y - (n, ) NumPy array containing the labels (0 or 1) for each training data point
test_x - (m, d) NumPy array (m datapoints each with d features)
Returns:
pred_test_y - (m,) NumPy array containing the labels (0 or 1) for each test data point
Reference: https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC
"""
# Initialize the 'One-vs-Rest' LinearSVC class considering the hinge loss formulation
svc = LinearSVC(C=C, random_state=0)
# Trains the LinearSVC Class
svc.fit(train_x, train_y)
# Prediction
return svc.predict(test_x)
def multi_class_svm(train_x, train_y, test_x):
"""
Trains a linear SVM for multiclass classifciation using a one-vs-rest strategy
Args:
train_x - (n, d) NumPy array (n datapoints each with d features)
train_y - (n, ) NumPy array containing the labels (int) for each training data point
test_x - (m, d) NumPy array (m datapoints each with d features)
Returns:
pred_test_y - (m,) NumPy array containing the labels (int) for each test data point
Reference: https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC
Obs.: The LinearSVC is robust enough to use the multi-class SVM when the input labels are multi-class
"""
# Initialize the 'One-vs-Rest' LinearSVC class considering the hinge loss formulation
svc = LinearSVC(C=0.1, random_state=0)
# Trains the LinearSVC Class
svc.fit(train_x, train_y)
# Prediction
return svc.predict(test_x)
def compute_test_error_svm(test_y, pred_test_y):
return 1 - np.mean(pred_test_y == test_y)
|
66b3a58599b94c4a4f48e444496788782001d78d | NavigationLab/warehouse-teleporting | /data_collection/src/experiments.py | 2,580 | 3.5 | 4 | """
File: experiments.py
Descr: Represents a full study experiment and contains
all the participants run in that experiment
Developed 2/13/2019 by Alec Ostrander
"""
import os
from participants import Participant
class Experiment:
def __init__(self, name):
"""
:param name: string, a name given to the experiment.
e.g. "Individual Differences Study"
Experiment objects hold any experiment-wide data above,
but are primarily a container for Participant objects.
"""
# store experiment information
self.name = name
self.participants = []
def add_participant(self, participant):
self.participants.append(participant)
def pull_data(self, fs="Interface/Conditions/Participant"):
"""
Parses the folders in the Data folder and populates the
experiment with newly generated Participant objects.
:param fs: string, may be provided to specify a different folder structure.
(Environment is assumed to the be the 1st condition, separated by underscores)
"""
# If fs was changed, make sure it still has all the necessary parts
for level in ("Interface", "Conditions", "Participant"):
assert level in fs
# Find the folder structure level for participants
level = fs.split("/").index("Participant")
# Initialize a temporary data structure for participant info
participants = {}
# Recursively loop through the data directory to find all participants
for path, dirs, files in os.walk("../Data"):
if not dirs: # Once at the bottom level,
# grab the participant info from folder names
p_id = path[len("../Data")+1:].split("\\")[level]
# If it's the first time seeing this participant, add them
if p_id not in participants:
participants[p_id] = []
# Add the current directory to the list for this participant
participants[p_id].append(path)
# Once we have all participants in the experiment, simply create
# each object, populate it, and add it to the experiment
for p in sorted(participants.keys()):
_id, gender = p.split("_")
if _id[0] == "P":
_id = _id[1:]
part = Participant(_id, gender)
part.pull_data(participants[p], fs)
self.add_participant(part)
def __iter__(self):
yield from self.participants
|
70c99029b44c6898008b846ddfbe34be5107c653 | alvaroeletro/DimAmostra | /ListaGeradora.py | 1,571 | 3.84375 | 4 |
print("Bem vindo\n")
print("Calculo do Tamanho de uma amostra necessária\n")
print("V.0.01 versão inicial\n")
print(".....::: Admita as seguintes condições :::.....\n")
contador = 0
erro=float(input("Inserir erro pré-fixado "))
x=0
s=0
espacoamostral = []
somax=0
somaXi=0
n0=int(input("Insira a qntd. da Amostra Piloto "))
gl = (n0-1)
t=input("Verifique na tabela o valor de talpha/2 ")
#NECESSITA SER CONSULTADO EM TABELA
print("Certifique-se de que os valores inseridos correponder a curva T-student")
while contador<n0:
contador+=1
x=(int(input("X{}".format(contador))))
espacoamostral.append(x)
print("Término da inserção de valores")
print("Lista gerada{}".format(espacoamostral))
print("\n Início do calculo\n ")
contador = 0
#CALCULO DO SOMATÓRIO DE X
while contador<n0:
x=0
x=espacoamostral[(contador)]
somax=somax+x
contador += 1
#CALCULO DA MEDIA
media = somax/n0
print(" A média calculada é de {}".format(media))
#CALCULO DO DESVIO PADRÃO
Xi=0
contador = 0
somaparcelas = 0
#somatório da parcela
while contador<n0:
Xi=espacoamostral[(contador)]
Xi= (Xi-media)**2
somaXi += Xi
contador+=1
#print("Soma das parcelas {}".format(somaparcelas))
#calculo do desvio padrao com o Somatório pronto
s= (somaXi/(gl))
s= (s**(0.5))
print("Desvio padrão calculado {}".format(s))
#FINALMENTE
#CALCULO DA AMOSTRA MÍNIMA
amostramin=float(t)*float(s)
amostramin=amostramin/erro
amostramin=amostramin**2
print("A amostra minima para esse experimento é de {}".format(amostramin))
|
3b1a089c2a806b789e9ec31496e36ec0432a472d | PakhnovaMaria/Pakhnova1sem | /praktika_3/eleven.py | 252 | 3.734375 | 4 | import turtle
turtle.shape('turtle')
def cir():
for i in range(1,181):
turtle.forward(1)
turtle.right(1)
for b in range(1,10):
turtle.forward(1)
turtle.right(18)
turtle.left(90)
for a in range (10):
cir()
|
6ee768afc8f04d2a989874bf0c7903c46c73eb8a | shuai-z/LeetCode | /valid-sudoku.py | 594 | 3.546875 | 4 | class Solution(object):
def isValidSudoku(self, board):
s = [[], [], []]
for x in range(3):
s[x] = [[] for _ in range(9)]
for i in range(9):
s[x][i] = [False for _ in range(10)]
for i, r in enumerate(board):
for j, c in enumerate(r):
if c == '.': continue
ci = int(c)
b = 3 * (i/3) + j/3
if s[0][i][ci] or s[1][j][ci] or s[2][b][ci]:
return False
s[0][i][ci] = s[1][j][ci] = s[2][b][ci] = True
return True
|
f5d0d4cfbc994d6a27dd077121917a1465fb234c | thecoder-co/sorting | /bubble sort.py | 2,982 | 3.96875 | 4 | import tkinter as tk
import random
import time
def swap_two_pos(pos_0, pos_1):
"""This does the graphical swapping of the rectangles on the canvas
by moving one rectangle to the location of the other, and vice versa
"""
x1, _, _, _ = canvas.coords(pos_0)
x2, _, _, _ = canvas.coords(pos_1)
diff = x1 - x2
canvas.move(pos_0, -diff, 0)
canvas.move(pos_1, +diff, 0)
def sort_two(pos_0, pos_1):
x1, y1, _, _ = canvas.coords(pos_0)
x2, y2, _, _ = canvas.coords(pos_1)
diff = x1 - x2
# moves each rectangle to the x position of the other; y remains unchanged
if y2 < y1:
canvas.move(pos_0, -diff, 0)
canvas.move(pos_1, +diff, 0)
return True
else:
return False
def rand_sort():
for i in range(50000):
rd1 = random.randint(0, 68)
rd2 = random.randint(0, 68)
pos_1 = barList[rd1]
pos_2 = barList[rd2]
if sort_two(pos_1, pos_2):
barList[rd1], barList[rd2] = barList[rd2], barList[rd1]
def sort ():
n = len(barList)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if sort_two(barList[j], barList[j+1]):
barList[j], barList[j+1] = barList[j+1], barList[j]
window.update()
time.sleep(0.1)
def random_swap():
"""Not a sort yet, but you have the bare bones operations
so the swap is executed
"""
for i in range(500):
rd1 = random.randint(0, 68)
rd2 = random.randint(0, 68)
pos_0 = barList[rd1]
pos_1 = barList[rd2]
swap_two_pos(pos_0, pos_1)
# it is necessary to swap the values in the list too
barList[rd1], barList[rd2] = barList[rd2], barList[rd1]
def generate_colors():
rgb_values = []
rgb = (255, 0, 0)
for i in range(23):
rgb_values.append(rgb)
rgb = 255, round(rgb[1] + 11), 0
for i in range(23):
rgb_values.append(rgb)
rgb = round(rgb[0] - 11), 255, 0
for i in range(24):
rgb_values.append(rgb)
rgb = 0, round(rgb[1] - 11), rgb[0] + 10
return rgb_values
def from_rgb(tup):
return "#%02x%02x%02x" % (tup[0], tup[1], tup[2])
colors = generate_colors()
window = tk.Tk()
window.title('Sorting')
window.geometry('1045x700')
# button to command the swap
tk.Button(window, text='swap', command=random_swap).pack()
tk.Button(window, text='sort', command=sort).pack()
xstart = 5
xend = 20
canvas = tk.Canvas(window, width='1045', height='700')
canvas.pack()
barList = []
lengthList = []
Y = 5
for x in range(1,70):
bar = canvas.create_rectangle(xstart, Y, xend, 700, fill=from_rgb(colors[x]))
barList.append(bar)
xstart += 15
xend += 15
Y += 9
for bar in barList:
x = canvas.coords(bar)
length = x[3]-x[1]
lengthList.append(length)
window.mainloop() |
9076b16442e9bbc174e43cf5b1656ba0efac9165 | AlexisAndresGarcia/Programacion-grupo-2 | /input.py | 218 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 12:19:08 2020
@author: Alexis Garcia
"""
nombre=input("Ingrese su nombre:")
print("Hola"+nombre+"!")
edad=input("Ingrese su edad:")
print("Usted es mayor de edad") |
20043033fea1034e1b88e251d6bf2486f519e0bc | GinnyGaga/PY-3 | /ex36-1.py | 1,307 | 4 | 4 | from sys import exit
def play():
print("so,how much money do you have?")
money=input(">")
if "0" in money or "1" in money:
how_much=int(money)
else:
quit("just type the money you have.")
if how_much < 100:
print("I'll go to Disney myself.")
exit(0)
else:
quit("you are the poor.")
def he():
print("But how is him?")
not_available=False
while True:
next=input(">")
if "love" in next:
print("I love you ,too.")
elif "happy" in next and not not_available:
print("we can date!!!")
not_available=True
elif "happy" in next and not_available:
print ("it is the same!")
else:
quit("fuck!")
def plan():
print("it is not raining,so i have two plan.")
plan=input(">")
if "date" in plan:
print("I'll date with him.")
he()
elif "play" in plan:
print("I have to play myself.")
play()
else:
print("excuse me? what are you want to say?")
def rain():
print("what's the weather?")
weather=input(">")
if "not_rain" == weather:
print("I am so happy!")
plan()
else:
print("I go to sleep.")
exit(0)
def quit(why):
print(why,"you!!")
exit(0)
def start():
print("are you over_worked or not over_worked?")
chooce=input(">")
if "not" in chooce:
print("I have festivel!")
rain()
else:
print("I have no festivel.")
exit(0)
start()
|
6eb4a1cc74fa0772b5450c5be0f025af07fe9e12 | ideologysec/practicepython | /exercise2.py | 742 | 4.0625 | 4 | # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html
# modulo practice, mostly
incomingNumber = int(input(
"Please enter a number (and I'll tell you if it's even or odd: "))
if (not incomingNumber % 2):
if (not incomingNumber % 4):
print("Your number was a multiple of four (and therefore even)!")
else:
print("You entered an even number.")
else:
print("You entered an odd number.")
num = int(input("Now, let's get fancy. Please enter a dividend: "))
check = int(input("Please enter your divisor: "))
if (not num % check):
print("Your dividend is evenly divisible by your divisor (the remainder is 0)")
else:
print("No even diviision here! Your remainder is ", (num % check))
|
c94e12186f9ef8abaf3b3a9948acbd73cda904d6 | skilldisk/Python_Basics_Covid19 | /exercises/exercise9.py | 402 | 4.1875 | 4 | print("******* Fibonacci Sequences *******")
nterms = int(input("how many terms ? : "))
current = 0
previous = 1
count = 0
next_term = 0
if nterms <= 0:
print("Enter a positive number")
elif nterms == 1:
print('0')
else:
while count < nterms:
print(next_term)
current = next_term
next_term = previous + current
previous = current
count += 1
|
368f3f8228eb395325c092185523baa6ffe1cb82 | sritampatnaik/find-your-way | /distanceAngleCalculation.py | 831 | 3.75 | 4 | import math
# distance formula
def distance(x1, y1, x2, y2):
return math.sqrt((int(x2) - int(x1)) ** 2 + (int(y2) - int(y1)) ** 2)
# returns the angle between 2 points,
# with respect to magnetic north
def calcAngle(x1, y1, x2, y2, northAt):
angle = 0
xprime = x2 - x1
yprime = y2 - y1
if xprime == 0 or yprime == 0:
if x2 > x1:
angle = 90
elif x2 < x1:
angle = 270
elif y2 > y1:
angle = 0
elif y2 < y1:
angle = 180
# degree obtained via reverse tan2 inputs and add 360 if angle < 0
else:
angle = math.degrees(math.atan2(xprime, yprime))
if angle < 0:
angle += 360
angle -= northAt
if angle > 180:
angle -= 360
elif angle <= -180:
angle += 360
return angle |
681d6327c4cbd8ee87311a828ce9bde0f9d484e0 | jcomicrelief/text_RPG | /main.py | 3,071 | 3.515625 | 4 | """TEXT RPG GAME - JCOMICRELIEF"""
from command import *
from variables import *
# help command (usage: help)
def aid():
lst = []
for command in commands:
lst.append(command)
lst.sort()
lst = ", ".join(lst)
print(lst)
# dictionary of commands
commands = {
"help": aid,
"check": check,
"quit": escape,
"look": look,
"read": read,
"go": go,
"search": search,
"take": take,
}
# dictionary of invisible commands
# for the purpose of giving player commands as they learn
invisible = {
"temp": look,
}
# setting up commands
def is_valid_cmd(cmd):
if cmd in commands:
return True
return False
# run commands
def run_cmd(cmd, args, player):
commands[cmd](player, args)
"""MAIN GAME FILE"""
# defines the main menu for the player before launching into the game
def main_menu():
# temporary usage
print("TEXT RPG GAME")
print("========")
# Sets the player's beginning location
def set_location():
# begins in the hall for now
player.location = hall
# Connect the rooms
def connect_rooms():
hall.connect(east=bedroom)
bedroom.connect(west=hall, south=bathroom)
kitchen.connect(north=hall)
bathroom.connect(north=bedroom)
# Setting doors
def set_doors():
hall.sdoor = "closed"
# Add objects into rooms
def add_objects():
# hall objects
hall.add(table)
hall.add(lamp)
hall.add(closet)
# bedroom objects
bedroom.add(bed)
bedroom.add(desk)
# kitchen objects
kitchen.add(fridge)
kitchen.add(microwave)
# bathroom objects
bathroom.add(hamper)
bathroom.add(toilet)
# Add items to objects
def add_items():
# hall items
hall.add(notebook)
table.add(flashlight)
closet.add(blanket)
# bedroom items
desk.add(batteries)
# kitchen items
# bathroom items
# Performs an intro for the player
def intro():
print("Your vision is blurry when you open your eyes, but you're not "
"worried. After the nightmare of being kidnapped and brought to a "
"strange house, you doubt that anything is out of the ordinary. "
"Until your vision clears and you find yourself still in the house.")
# for testing purposes
def show_room():
# print the player's current location
print("-------------------------")
print("You are in the {0}.".format(player.location.name))
print("Interactive objects: {0}".format(", ".join(player.location.inside.keys())))
# print the current inventory
print("Inventory: {0}".format(player.inventory.inside.keys()))
# the main game call
def main():
main_menu()
set_location()
connect_rooms()
set_doors()
add_objects()
add_items()
intro()
while not player.dead:
# testing (START)
show_room()
# testing (END)
line = raw_input(">> ")
user = line.split()
user.append("EOI")
if is_valid_cmd(user[0]):
run_cmd(user[0], user, player)
else:
print("Not a valid command.")
main()
|
14b125aca63cd0a93498d12891d3cd1f37470aa7 | Swathygsb/DataStructuresandAlgorithmsInPython | /DataStructuresandAlgorithmsInPython/com/kranthi/Algorithms/challenges/medium/permitationOfString.py | 780 | 4.15625 | 4 | """
Write a program to print all permutations of a given string
Last Updated: 03-12-2020
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an
ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB
"""
def toString(lst:list) -> str:
return "".join(lst)
def permute(a, l, r):
if l == r:
print(toString(a))
else:
for i in range(l, r+1):
a[l], a[i] = a[i], a[l]
permute(a, l+1, r)
a[l], a[i] = a[i], a[l]
string = "ABC"
n = len(string)
lst = list(string)
permute(lst, 0, n-1)
|
bd0bb990728589e47141afff2c6b709661cab470 | johnfwitt/rosalind | /subs.py | 829 | 4.125 | 4 | # http://rosalind.info/problems/subs/
sample = input("sample = ")
substring = input("substring = ")
start = 0
stop = len(substring) # create a search space the same size as the substring
results = []
def SubstringSearch(sample,substring,start,stop,results):
if sample[start:stop] == substring: # if the search space contains the substring
results.append(str(start + 1)) # add the location of the first letter to the results
start += 1
stop += 1 # move the search space one letter to the right
if stop <= len(sample): # if the entire sample hasn't been searched yet
SubstringSearch(sample,substring,start,stop,results) # search the new search space
SubstringSearch(sample,substring,start,stop,results)
print(" ".join(results)) # print the results formatted per the instructions
|
ad620a464f3632a5a24f1561118718ce87c06321 | taobupt/pycompete | /Trie.py | 1,106 | 4.09375 | 4 | class TrieNode:
def __init__(self):
self.isEnd=False
self.children=['*']*26 #we can judge wheather there is a children node
self.word='' # every node store string from root to this node
class Trie:
def __init__(self):
self.root=TrieNode()
def insert(self,word):
cur=self.root
for i in range(0,len(word)):
if cur.children[ord(word[i])-97]=='*':
cur.children[ord(word[i])-97]=TrieNode()
cur.children[ord(word[i])-97].word=cur.word+word[i]
cur=cur.children[ord(word[i])-97]
cur.isEnd=True
def search(self,word):
cur=self.root
for i in range(0,len(word)):
if cur.children[ord(word[i])-97]=='*':
return False
cur=cur.children[ord(word[i])-97]
return cur.isEnd
def startsWith(self,prefix):
cur = self.root
for i in range(0, len(prefix)):
if cur.children[ord(prefix[i]) - 97] == '*':
return False
cur = cur.children[ord(prefix[i]) - 97]
return True
|
926d7abbbe6f063b2bc30eb3a2843d1f989722a1 | kokot300/python-core-and-advanced | /oddnumbers.py | 612 | 3.96875 | 4 | while True:
x=input("enter min number:\n")
y=input("enter max number:\n")
try:
xx=int(x)
try:
yy=int(y)
if xx%2!=0:
while xx<=yy:
print(xx)
xx+=2
#return 3
else:
xx+=1
while xx <= yy:
print(xx)
xx+=2
#return 4
except ValueError:
ValueError: ("you haven't introduced numbers")
#return 2
except ValueError:
print("you haven't introduced numbers") |
88c207be1647faf33d124172763aec3cc1fd015c | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/115/15210/submittedfiles/decimal2bin.py | 203 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=input('digite um número:')
b=n
d=0
while b>0:
b=b//10
d=d+1
s=0
for i in range(0,d,1):
c=n%10
s=s+c*(2)**i
n=n//10
print(s)
|
90e4175e7e08afe3014531e7d0c4f54e7c294946 | Silvernitro/DSaA | /search_trees.py | 18,618 | 3.609375 | 4 | class Tree():
class Position():
def element(self):
raise NotImplementedError('must be implemented by subclass')
def __eq__(self, other):
raise NotImplementedError('must be implemented by subclass')
def __ne__(self, other):
return not(self==other)
def root(self):
raise NotImplementedError('must be implemeneted by subclass')
def is_root(self, p):
return (p==self.root())
def parent(self, p):
raise NotImplementedError('must be implemeneted by subclass')
def num_children(self, p):
raise NotImplementedError('must be implemeneted by subclass')
def children(self, p):
raise NotImplementedError('must be implemeneted by subclass')
def is_leaf(self, p):
return (self.num_children(p)==0)
def __len__(self):
raise NotImplementedError('must be implemeneted by subclass')
def is_empty(self):
return (self.len()==0)
def iter(self):
raise NotImplementedError('must be implemeneted by subclass')
def depth(self, p):
if self.is_root(p):
return 0
else:
return 1+self.depth(self.parent(p))
def _height_aux(self, p):
if self.is_leaf(p):
return 0
else:
return 1+max(self._height_aux(child) for child in self.children(p))
def height(self, p=None):
if p is None:
p=self.root()
return _height_aux(p)
def _subtree_preorder(self, p):
"""A utility generator for preorder traversal of a subtree at p"""
yield p
for c in self.children(p):
for other in self._subtree_preorder(c):
yield other
def preorder(self):
"""Preorder generator of all positions in the tree"""
if not self._is_empty():
for p in self._subtree_preorder(self.root()):
yield p
def positions(self):
"""Generates a preorder iteration of all positions in the tree"""
return self.preorder()
def _subtree_postorder(self, p):
"""A utility generator for postorder traversal of a subtree at p"""
for c in self.children(p):
for other in self._subtree_postorder(c):
yield other
yield p
def postorder(self):
"""Postorder generator for all positions in the tree"""
if not self._is_empty:
for p in self._subtree_postorder(self.root()):
yield p
class BinaryTree(Tree):
def left(self, p):
raise NotImplementedError('must be implemeneted by subclass')
def right(self, p):
raise NotImplementedError('must be implemeneted by subclass')
def sibling(self, p):
parent=self.parent(p)
if parent is None:
return None
else:
if p==self.left(parent):
return self.right(parent)
else:
return self.left(parent)
def children(self, p):
if self.left(p) is not None:
yield self.left(p)
if self.right(p) is not None:
yield self.right(p)
def num_children(self, p):
"""Returns the number of children for position p"""
count=0
for child in self.children(p):
count+=1
return count
class LinkedBinaryTree(BinaryTree):
class _Node:
def __init__(self, element, parent=None, left=None, right=None):
self._element=element
self._parent=parent
self._left=left
self._right=right
class Position(BinaryTree.Position):
def __init__(self, node, container):
self._container=container
self._node=node
def element(self):
return self._node._element
def __eq__(self, other):
return type(self) is type(other) and self._node is other._node
def _validate(self, p):
if not isinstance(p, self.Position):
raise TypeError("input is not a valid Position")
if p._container is not self:
raise ValueError("position given is not part of this tree")
if p._node._parent is p._node:
raise ValueError("this position has been deprecated")
else:
return p._node
def _make_position(self, node):
"""Wraps a node in a Position and returns it if the node is not the
root"""
return Position(node, self) if node is not None else None
def __init__(self):
self._root=None
self._size=0
def __len__(self):
return self._size
def root(self):
return self._make_position(self._root)
def parent(self, p):
node=self._validate(p)
return self._make_position(node._parent)
def left(self, p):
node=self._validate(p)
return self._make_position(node._left)
def right(self, p):
node=self._validate(p)
return self._make_position(node._right)
def num_children(self, p):
node=self._validate(p)
child_count=0
if node._left is not None:
child_count+=1
if node._right is not None:
child_count+=1
return child_count
def _add_root(self, e):
if self._root is not None:
raise ValueError("Tree is not empty, a root exists!")
self._root=self._Node(e)
self._size=1
return self._make_position(self._root)
def _add_left(self, p, e):
node=self._validate(p)
if node is None:
raise ValueError("cannot add element to an invalid node")
if node._left is not None:
raise ValueError("node already has a left child")
node._left=self._Node(e, parent=node)
self._size+=1
return self._make_position(node._left)
def _add_right(self, p, e):
node=self._validate(p)
if node is None:
raise ValueError("cannot add element to an invalid node")
if node._right is not None:
raise ValueError("node already has a right child")
node._right=self._Node(e, parent=node)
self._size+=1
return self._make_position(node._right)
def _delete(self, p):
node=self._validate(p)
if node is None:
raise ValueError("cannot delete an invalid node")
if self.num_children(p)==2:
raise ValueError("node with 2 children cannot be deleted")
child=node._left if node._left else node._right
if node is self._root:
self._root=child
parent=node._parent
child._parent=parent
if node is parent._left:
parent._left=child
else:
parent._right=child
node._parent=node
self._size-=1
return node._element
def _replace(self, p, e):
node=self._validate(p)
if node is None:
raise ValueError("the node is invalid")
old=node._element
node._element=e
return old
def _subtree_inorder(self, p):
"""Utility generator for inorder traversal of a binary subtree at p"""
if self.left(p):
yield self._subtree_inorder(self.left(p))
yield p
if self.right(p):
yield self._subtree_inorder(self.right(p))
def inorder(self):
"""Generator for inorder traversal of the binary subtree"""
if not self._is_empty():
for other in _subtree_inorder(self.root()):
yield other
def positions(self):
"""Generates an iteration of all positions. Overrides parent method to
use inorder traversal instead"""
return self.inorder()
class MapBase(MutableMapping):
"""Serves as a the abstract base class for all maps."""
class _Item:
__slots__='_key', '_value'
def __init__(self, k ,v):
self._key=k
self._value=k
def __eq__(self, other):
return self._key==other._key
def __ne__(self, other):
return not (self==other)
def __It__(self, other):
return self._key<other._key
class TreeMap(LinkedBinaryTree, MapBase):
"""Sorted map implementation using a Binary Search Tree."""
class Position(LinkedBinaryTree.Position):
def key(self):
return self.element()._key
def value(self):
return self.element()._value
#Non-public utilities
def _subtree_search(self, p, k):
"""Returns Position of p's subtree that contains k, or last node search
if k does not exist."""
if p._key == k:
return p
elif p._key < k:
if self.left(p) is not None:
self._subtree_search(self.left(p), k)
else:
if self.right(p) is not None:
self._subtree_search(self.right(p), k)
return p
def _subtree_search_v2(self, p, k):
while p._key != k and p is not None:
if p._key < k:
p = self.left(p)
else:
p = self.right(p)
return p
def _subtree_first_position(self, p):
walk = p
while self.left(p) is not None:
walk = self.left(p)
return walk
def _subtree_last_position(self, p):
walk = p
while self.right(p) is not None:
walk = self.right(p)
return walk
#Balancing utilities
def _rebalance_insert(self, p):
pass
def _rebalance_delete(self, p):
pass
def _rebalance_access(self, p):
pass
def _relink(self, parent, child, is_child_left):
"""Links child node to parent node. is_child_left is a boolean that determines if
child is left child of the parent or not."""
if is_child_left:
parent._left = child
else:
parent._right = child
if child is not None:
child._parent = parent
def _rotate(self, p):
"""Rotates node at position p above its parent."""
x = p._node
y = x._parent
z = y._parent
if z is None:
self._root = x
else:
self._relink(z, x, y == self.left(z))
if x == y._left:
self._relink(y, self.right(x), True)
self._relink(x, y, False)
else:
self._relink(y, self.left(x), False)
self._relink(x, y, True)
def _restructure(self, x):
"""Performs a trinode restructure of Position x with its
parent/grandparent."""
y = self.parent(x)
z = self.parent(y)
#checks if x,y,z are aligned
if ((self.right(z) == y) and (self.right(y) == x))\
or ((self.left(z) == y) and (self.left(y) == x)):
self._rotate(x)
return z
else:
self._rotate(x)
self._rotate(x)
return x
#Public utilities
def first(self):
if len(self) > 0:
return self._subtree_first_position(self.root())
else:
return None
def last(self):
if len(self) > 0:
return self._subtree_last_position(self.root())
else:
return None
def after(self, p):
self._validate(p)
if self.right(p):
return self._subtree_first_position(self.right(p))
else:
walk = p
ancestor = self.parent(walk)
while walk is not None and walk == self.right(ancestor):
walk = ancestor
ancestor = self.parent(walk)
return ancestor
def before(self, p):
self._validate(p)
if self.left(p):
return self._subtree_last_position(self.left(p))
else:
walk = p
ancestor = self.parent(walk)
while walk is not None and walk == self.left(ancestor):
walk = ancestor
ancestor = self.parent(walk)
return ancestor
def find_position(self, k):
if self._is_empty():
return None
p = self._subtree_search(self.root(), k)
self._rebalance_access(p)
return p
def find_position(self, k):
"""Returns the Position of k in tree, or neightbour if k does not
exist."""
if self.is_empty():
return None
else:
p = self._subtree_search(self.root(), k)
self._rebalance_access(p)
return p
def find_min(self):
"""Returns key-value pair of the smallest key in the tree."""
if self.is_empty():
return None
else:
p = self.first()
return (p.key(), p.value())
def find_ge(self, k):
"""Returns the key-value pair of the smallest key greater than or equal
to k."""
if self.is_empty():
return None
else:
p = self._subtree_search(self.root(), k)
if self.key(p) < k:
p = self.after(p)
return (p.key(), p.value()) if p is not None else None
def find_range(self, start, stop):
"""Generates an iteration of all Positions with start <= key < stop.
If start is None, iteration starts from smallest key.
If stop is None, iteration continues till largest key."""
if self.is_empty():
return None
else:
if start is None:
p = self.first()
else:
p = self.find_position(start)
if p.key() < start:
p = self.after(p)
while p is not None and (stop is None or p.key() < stop):
yield p
p = self.after(p)
#Private core map utilities
def __getitem__(self, k):
if self.is_empty():
raise KeyError("Key Error: " +k)
p = self._subtree_search(self.root(), repr(k))
self._rebalance_access(p)
if p.key() != k:
raise KeyError("Key Error: " + repr(k))
return p.value()
p = self._subtree_search(self.root(), start)
def __setitem__(self, k, v):
if self.is_empty():
leaf = self._add_root(self._Item(k, v))
else:
p = self._subtree_search(self.root(), k)
if p.key() == k:
p.element()._value = v
p._rebalance_access(p)
return
else:
item = self._Item(k, v)
if p.key() < k:
leaf = self._add_right(p, item)
else:
leaf = self._add_left(p, item)
self._rebalance_insert(leaf)
def __iter__(self):
if not self.is_empty:
p = self.first()
while p is not None:
yield p
p = self.after(p)
def delete(self, p):
"""Utility function to delete a position in a tree."""
self._validate(p)
if self.left(p) and self.right(p):
replacement = self._subtree_last_position(self.left(p))
self._replace(p, replacement.element())
p = replacement
parent = self.parent(p)
self._delete(p)
self._rebalance_delete(parent)
def __del__(self, k):
if self.is_empty():
raise KeyError("Key Error: " + repr(k))
p = self._subtree_search(self.root(), k)
self._rebalance_access(p)
if p.key() != k:
raise KeyError("Key Error: " + repr(k))
else:
self.delete(p)
return
class AVLTreeMap(TreeMap):
"""Sorted Map implementation using an AVL Tree."""
class _Node(TreeMap._Node):
"""Node class for AVL tree to maintain height value for balancing."""
__slots__ = "_height"
def __init__(self, element, parent=None, left=None, right=None):
super().__init__(element, parent, left, right)
self._height = 0
def left_height(self):
return self._left._height if self._left else 0
def right_height(self):
return self.right._height if self._right else 0
#Positional-based utilities for balancing
def _recompute_height(self, p):
p._node._height = 1 + max(p._node.left_height(), p._node.right_height())
def _is_balanced(self, p):
return abs(p._node.left_height() - p._node.right_height()) <= 1
def _tall_child(self, p, favorleft = False):
"""Returns the tallest child of Position p. In case of a tie, favorleft
acts as a tie-breaker."""
if p._node.left_height + (1 if favorleft else 0) >
p._node.right_height:
return self.left(p)
else:
return self.right(p)
def _tall_grandchild(self, p):
"""Returns tallest grandchild of Position p."""
child = self._tall_child(p)
alignment = (child == self.left(p))
return self._tall_child(p, alignement)
def _rebalance(self, p):
"""Rebalances the AVL Tree."""
ancestor = p
while ancestor is not None:
old_height = self._node._height
if not self._is_balanced(ancestor):
ancestor = self._restructure(self._tall_grandchild(ancestor))
self._recompute_height(self.left(ancestor))
self._recompute_height(self.right(ancestor))
new_height = self._recompute_height(ancestor)
if old_height == new_height:
p = None
ancestor = self.parent(ancestor)
#Override balancing hooks
def _rebalance_insert(self, p):
self._rebalance(p)
def _rebalance_delete(self, p):
self._rebalance(p)
class SplayTreeMap(TreeMap):
"""Sorted Map implementation using a Splay Tree."""
def _splay(self, p):
while p != self.root():
parent = self.parent(p)
grandparent = self.parent(parent)
if grandparent is None:
#zig operation
self._rotate(p)
elif (p == self.left(parent)) == (parent ==
self.left(grandparent)):
#zig-zig operation
self._rotate(parent)
self._rotate(p)
else:
#zig-zag operation
self._rotate(p)
self._rotate(p)
def _rebalance_access(self, p):
self._splay(p)
def _rebalance_insert(self, p):
self._splay(p)
def _rebalance_delete(self, p):
if p is not None:
self._splay(p)
|
9302ddfcb4609eeb1e80ed7185115c1a0dcad828 | katiewilkinson/pythonmultiply | /helloworld.py | 251 | 4.0625 | 4 | #Part 1 of code prints all the odd numbers from 1 to 1000
#Part 2 of code prints all the multiples of 5 from 5 to 1000000
for i in range (1,1001):
if(i % 2 == 1):
print i
for i in range(5, 1000001):
if(i % 5 == 0):
print i
|
d00a31d49e8bc5d0f58f517925bc84c619b2f0a5 | alisher0v/MeFirstPrograms | /if,else,elif.py | 229 | 4 | 4 | e = 6
f = 5
if e < f :
print('e меньше переменной f')
else :
if e == f :
print("переменная е равен с переменной f ")
else :
print("e больше f")
|
403a039276e60f8423041e4b42230c8212fdcf83 | dheerajdlalwani/PythonPracticals | /Experiment1/code/question1.py | 1,031 | 4.34375 | 4 | # Question: Write a python program to print the following lines in a specific format
# Using only one print function
# Twinkle Twinkle Little Star,
# "How I wonder what you are!"
# Up above the world so high
# Like a diamond in the sky.
# 'Twinkle Twinkle' Little star
# How I wonder what you are
print("\n\n")
print("---------------------Method 1---------------------")
following_lines = '''
Twinkle Twinkle Little Star,
"How I wonder what you are!"
Up above the world so high
Like a diamond in the sky.
'Twinkle Twinkle' Little star
How I wonder what you are '''
print(following_lines)
print("--------------------------------------------------\n")
print("---------------------Method 2---------------------\n")
print("Twinkle Twinkle Little Star,\n\t\"How I wonder what you are!\"\n\t\tUp above the world so high\n\t\tLike a diamond in the sky.\n\'Twinkle Twinkle\' Little star\n\tHow I wonder what you are")
print("--------------------------------------------------\n\n")
|
ba2a454866f5fa4b755383bad93dbeb3c175c96f | ravi4all/PythonWE_Morning_2020 | /Chat_3.py | 1,021 | 3.5625 | 4 | from datetime import datetime
import glob,os,random
print("Welcome",name := input("Enter your name : "))
helloIntent = ["hi","hello","hey","hi there","hello there","hey there"]
timeIntent = ["time","tell me time","what's the time","time please"]
dateIntent = ["date","tell me date","what's the date","date please"]
musicIntent = ["play music","play song","start music","please play music"]
while (msg := input("Enter your message : ")) != "bye":
if msg in helloIntent:
print("Hey",name)
elif msg in timeIntent:
curr_time = datetime.now().time()
print("Time is",curr_time.strftime("%H:%M:%S,%p"))
elif msg in dateIntent:
curr_date = datetime.now().date()
print("Date is",curr_date.strftime("%d/%m/%y,%a"))
elif msg in musicIntent:
os.chdir(r'C:\Users\asus\Music')
songs = glob.glob('*.mp3')
song = random.choice(songs)
os.startfile(song)
else:
print("I don't understand")
print("Bye",name)
|
cc84ac426106b9f91008bc981037e6e8b5e26ab2 | the-potato-man/lc | /2019/go/127-word-ladder.py | 2,182 | 3.78125 | 4 | '''
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
'''
import string
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
def isOneAway(word1, word2):
numDiff = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
numDiff += 1
if numDiff > 1:
break
return True if numDiff == 1 else False
# Getting neighbors, so don't have to traverse entire dictionary
def getNeighbors(word, wordListSet):
neighbors = []
for i in range(len(word)):
for c in string.ascii_lowercase: # a-z
temp = word[:i] + c + word[i+1:]
if temp in wordListSet:
neighbors.append(temp)
return neighbors
# Changing dictionary's word list to a set for faster lookup
wordListSet = set()
for word in wordList:
wordListSet.add(word)
visited = set()
visited.add(beginWord)
queue = [(beginWord, 1)]
while queue:
temp, steps = queue.pop(0)
if temp == endWord:
return steps
neighbors = getNeighbors(temp, wordListSet)
for word in neighbors:
if isOneAway(temp, word) and word not in visited:
queue.append((word, steps + 1))
visited.add(word)
return 0
|
2df91ab53f923726a1d6c25ddb952d0d231ff1f7 | jPUENTE23/ESTRUCTURA-DE-BASES-DE-DATOS-Y-SU-PROCESAMIENTO-3ER-SEMESTRE | /02 FEBRERO/03 DE FEB/02-modulo.datetime.py | 1,882 | 4.0625 | 4 |
# funciones con modulo datetime
import datetime
import time
# la funcion de datetime.time, lo que hace es ayudarnos a combertir un tipo de dato str
# a uno datetime, solo deaccuerdo a una hora espesificada (HH-MM-SS) dentro de los argumentos
hora = datetime.time(22,10,10)
print("El tipo de datos de la hora es {}".format(type(hora)))
print("La hora es {} ".format(hora))
print("La hora de {} es {}".format(hora,(hora.hour))) # limitado a 23
print("Los minutos de {} son {}".format(hora,(hora.minute))) # limitado a 59
print("Los segundos de {} son {}".format(hora,(hora.second))) # limitado a 59
# determinar la fecha del sistema
fecha = datetime.date.today()
print("El tipo de datos de ña fecha es {} ".format(type(fecha)))
print("La fecha es {} ".format(fecha))
print("El año actual es {}".format(fecha.year))
print("El mes actuañ es {}".format(fecha.month))
print("El dia actuañ es {}".format(fecha.day))
# convertir un str a fecha
fecha_capturada = input("Ingrese un fecha (DD/MM/AAAA): ")
# la funcion strptime es la que nos ayudara a convertir un string a un tipo de datos fecha...
# dentro de lla pondremos los argumentos que es la variable donde guardamos la fehca anteriormente...
# y el formato de fecha al que lo queremos converitr.
fecha_procesada = datetime.datetime.strptime(fecha_capturada, "%d/%m/%Y").date()
print(type(fecha_capturada))
print(type(fecha_procesada))
print("La fecha es {} ".format(fecha_procesada))
# aritmetica de fechas
cant_dias = int(input("Dame la cantidad de dias a extender: "))
# la sig funcion nos permite agregar mas dias de acuerdo a la fehca ingresada anteriormente...
# Ejemplo: si la fehca es 26/12/20201 y la extension de dias que queremos son 5...
# nos devolvera la fecha 31/12/20201.
nueva_fecha = fecha_procesada + datetime.timedelta(days=+cant_dias)
print("La nueva fecha es: {} ".format(nueva_fecha)) |
af49a548f21f3e5590b799a4917451fc135cf60e | Sagbeh/Database-Manager | /DisplaySingleRecord.py | 1,792 | 4.21875 | 4 | __author__='Sam'
# Imports sqlite3 library for database use
import sqlite3
# Defines displaySingleRecord function
def displaySingleRecord():
while True:
try:
sqlite_file = 'NewDatabase.db' # name of the sqlite database file
# User enters product ID of the records they want to view
while True:
try:
productID = int(input('\nEnter the ID of the product you want to view: \n'))
except ValueError:
print('\nProdcut ID must be an integer and cannot be blank.\n')
else:
break
# Connecting to database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# variables that contain the query and parameters used for the sql query
sql = "SELECT * FROM PRODUCTS WHERE ID = ?"
arg = (productID,)
# executes the sql query
c.execute(sql,arg)
# If database doesn't exist, informs user and prompts them to create the database first
except sqlite3.OperationalError:
print("\nPRODUCTS table does not exist\n")
print("\nCreate the database first \n")
break
else:
# for loop used to display the specified record
for row in c:
print("\nID = ", row[0])
print("PRODUCTNAME = ", row[1])
print("QUANTITY = ", row[2])
print("PRICE = ", row[3])
print("WEIGHT = ", row[4])
print("CATEGORY = ", row[5])
print("SOLD = ", row[6], "\n")
# Commit changes and close database connection
conn.commit()
conn.close()
break
|
39096da1dc5d9abe8ff72cc4a077523aa3b8d445 | shui190/uband-python-s1 | /homeworks/B21413/Checkin-09/day13-homework1.py | 638 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
week_overnight = [False, True, False, False, False] #包含判断的列表
for index,is_overnight in enumerate(week_overnight):
print '今天星期%d' % (index + 1)
try:
check(is_overnight)
except Exception,e: #若没有这一段,就会出现报错。
print '发生错误:%s' % (e)
print '老妈骂了老爸一顿,然后当然选择原谅了他'
else:
print '又是平和的一天'
def check(is_overnight):
if is_overnight:
raise Exception('离婚') #中断程序,手动报错
else:
print '正常'
if __name__ == '__main__':
main() |
a25bb6b92dcc945399675ff18999dd810223b75a | chandneepuri/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 434 | 3.84375 | 4 | """numeric_operators.py."""
__author__ = "730228106"
left: str = input("Left-hand side:")
right: str = input("Right-hand side:")
number1: int = int(left)
number2: int = int(right)
print(left + " ** " + right + " is " + str(number1 ** number2))
print(left + " / " + right + " is " + str(number1 / number2))
print(left + " // " + right + " is " + str(number1 // number2))
print(left + " % " + right + " is " + str(number1 % number2)) |
972a5a73b77a64060cd4f317f815c4bb50318d22 | cmry/seqmod | /seqmod/misc/early_stopping.py | 4,119 | 3.546875 | 4 |
import heapq
class pqueue(object):
def __init__(self, maxsize, heapmax=False):
self.queue = []
self.maxsize = maxsize
self.heapmax = heapmax
def push(self, item, priority):
if self.heapmax:
priority = -priority
heapq.heappush(self.queue, (priority, item))
if len(self.queue) > self.maxsize:
# print("Popped {}".format(self.pop()))
self.pop()
def pop(self):
p, x = heapq.heappop(self.queue)
if self.heapmax:
return -p, x
return p, x
def __len__(self):
return len(self.queue)
def get_min(self):
if self.heapmax:
p, x = max(self.queue)
return -p, x
else:
p, x = min(self.queue)
return p, x
def get_max(self):
if self.heapmax:
p, x = min(self.queue)
return -p, x
else:
p, x = max(self.queue)
return p, x
def is_full(self):
return len(self) == self.maxsize
def is_empty(self):
return len(self.queue) == 0
class EarlyStoppingException(Exception):
def __init(self, message, data={}):
super(EarlyStopping, self).__init__(message)
self.message = message
self.data = data
class EarlyStopping(pqueue):
"""Queue-based EarlyStopping that caches previous versions of the models.
Early stopping takes place if perplexity increases a number of times
higher than `patience` over the lowest recorded one without resulting in
the buffer being freed. On buffer freeing, the number of fails is reset but
the lowest recorded value is kept. The last behaviour can be tuned by
passing reset_patience equal to False.
Parameters
----------
maxsize: int, buffer size
Only consider so many previous checkpoints before raising the
Exception, buffer will be freed after `maxsize` checkpoints are
introduced. After freeing the buffer the previously best checkpoint is
kept in the buffer to allow for comparisons with checkpoints that are
far in the past. The number of failed attempts will however be freed
alongside the buffer.
patience: int (optional, default to maxsize)
Number of failed attempts to wait until finishing training.
reset_patience: bool, default True
"""
def __init__(self, maxsize, patience=None, tolerance=1e-4,
reset_patience=True):
"""Set params."""
self.tolerance = tolerance
self.patience, self.fails = patience or maxsize - 1, 0
self.reset_patience = reset_patience
self.stopped = False
self.checks = [] # register losses over checkpoints
if self.patience >= maxsize:
raise ValueError("patience must be smaller than maxsize")
super(EarlyStopping, self).__init__(maxsize, heapmax=True)
def find_smallest(self):
return sorted(enumerate(self.checks), key=lambda i: i[1])[0][0] + 1
def add_checkpoint(self, checkpoint, model=None):
"""Add loss to queue and stop if patience is exceeded."""
if not self.is_empty():
smallest, best_model = self.get_min()
if (checkpoint + self.tolerance) > smallest:
self.fails += 1
if self.fails == self.patience:
self.stopped = True
msg = "Stop after {} checkpoints. ".format(len(self.checks))
msg += "Best score {:.4f} ".format(smallest)
msg += "at checkpoint {} ".format(self.find_smallest())
msg += "with patience {}.".format(self.patience)
raise EarlyStoppingException(
msg, {'model': best_model, 'smallest': smallest})
self.push(model, checkpoint)
self.checks.append(checkpoint)
if self.is_full():
checkpoint, best_model = self.get_min()
self.queue = []
if self.reset_patience:
self.fails = 0
self.add_checkpoint(checkpoint, model=best_model)
|
76829bb3d375f31cfbd39dc7ba5216d24f9ae872 | chasegan/pixiepython | /pixiepython/utils.py | 3,391 | 4.4375 | 4 | import math
import datetime as dt
import numbers
def is_a_digit(char):
"""
Check if the provided character is a digit.
Returns a boolean result.
"""
if (char == '0' or char == '1'
or char == '2' or char == '3'
or char == '4' or char == '5'
or char == '6' or char == '7'
or char == '8' or char == '9'):
return True
else:
return False
def first_non_digit(string):
"""
Finds the first non-digit character in the provided string.
Returns the location and the char.
"""
for i in range(len(string)):
if not is_a_digit(string[i]):
return [i, string[i]]
return [-1, ' ']
def parse_date(datestring):
"""
Parses a date string into a datetime object.
It expects no more than 2 digits for the day, and uses this
to determine whether the format is dmy or ymd. The delimit
character is automatically determined.
Returns the datetime or None.
"""
[delimit_loc, delimit_char] = first_non_digit(datestring)
if (delimit_loc < 3):
formatter = "%d" + delimit_char + "%m" + delimit_char + "%Y"
else:
formatter = "%Y" + delimit_char + "%m" + delimit_char + "%d"
answer = dt.datetime.strptime(datestring, formatter)
return answer
def parse_value(valuestring):
"""
Parses a string to a float value. Whitespaces are parsed as nan.
Returns a float.
"""
s = valuestring.strip()
if (s == ""):
s = "nan"
return float(s)
def is_data_row(row):
"""
Guesses if a csvreader 'row' object contains data, i.e. not
headder information. It does this by checking if the zeroth
char of the zeroth element is a digit (which would be a date).
Returns boolean result.
"""
if (not row or len(row) == 0):
return False
zeroth_element = row[0]
if (len(zeroth_element) == 0):
return False
else:
zeroth_char = zeroth_element[0]
return is_a_digit(zeroth_char)
def count_missing(data):
"""
Counts the number of nan in a list of float.
Return an integer.
"""
answer = 0
for d in data:
if math.isnan(d):
answer = answer + 1
return answer
def period_length(start_datetime, end_datetime, interval=dt.timedelta(1)):
"""
Calculates the number of intervals (default interval = 1 day) between
two datetimes. The function returns the number of days as a float, which
may be non-integer and/or negative.
"""
answer = (end_datetime - start_datetime) / interval
return answer
def days_in_month(year, month):
"""
Calculates the number of days in a month. This is a bit hacky but doesn't
require any new libraries and it works.
"""
date1 = dt.datetime(year, month, 1)
date2 = None
if month == 12:
date2 = dt.datetime(year + 1, 1, 1)
else:
date2 = dt.datetime(year, month + 1, 1)
answer = (date2 - date1).days
return answer
def last_day_in_month(date):
"""
Returns a datetime set to the last day in the month
"""
x = days_in_month(date.year, date.month)
answer = dt.datetime(date.year, date.month, x)
return answer
def is_a_number(var):
"""
Tests if a variable is an instance of a numberself (i.e. int, float, etc)
"""
answer = isinstance(var, numbers.Number)
return answer
|
7561bf29a034167ce7ac3f94c990bdf487b8bef9 | heartdance/learn-python | /src/basic/the_tuple.py | 447 | 4.1875 | 4 | animals = ("dog", "pig", "sheep")
print("type(animals) =", type(animals))
# 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符
numbers = (1)
print("type((1)) =", type(numbers))
numbers = (1,)
print("type((1,)) =", type(numbers))
animalsList = list(animals)
print("type(animalsList) = ", type(animalsList))
animalsTuple = tuple(animalsList)
print("type(animalsTuple) = ", type(animalsTuple))
|
4ec016182b1b4314e2970c58480184f10b433f65 | zllion/ProjectEuler | /p035.py | 702 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 15:06:58 2020
@author: zhixia liu
"""
"""
Project Euler 35: Circular primes
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
"""
from helper import EratisthenesSieve, isPrime
from tqdm import tqdm
result = []
primelist = EratisthenesSieve(1000000)
for i in tqdm(primelist):
if all([isPrime(n) for n in [int(str(i)[-j:]+str(i)[:-j]) for j in range(1,len(str(i)))] ]):
result.append(i)
print(result)
print(len(result)) |
6a1bb3a5882d85b3a6a7c549f3ae4570be22d716 | vivekgsheth/Python_CodeBasics | /doubly_linkedList.py | 3,655 | 4.0625 | 4 | class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.prev = prev
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def print_forward(self):
print("LinkedList is empty")
if self.head is None:
return
llstr = ''
itr = self.head
while itr:
llstr += str(itr.data) + '-->'
itr = itr.next
print(llstr)
def print_backward(self):
if self.head is None:
print("LinkedList is empty")
return
llstr = ''
itr = self.get_last_node()
while itr:
llstr += itr.data + '-->'
itr = itr.prev
print('LL in reverse: ', llstr)
def get_last_node(self):
if self.head is None:
return
itr = self.head
while itr.next:
itr = itr.next
return itr
def insert_at_begining(self, data):
if self.head is None:
self.head = Node(data, None, None)
else:
node = Node(data, self.head, None)
self.head.prev = node
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None, itr)
def insert_values(self, data_list):
self.head = None
for data in data_list:
self.insert_at_end(data)
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def remove_at(self, index):
if index<0 or index>=self.get_length():
raise Exception("Invalid index")
if index == 0:
self.head = self.head.next
self.head.prev = None
return
count = 0
itr = self.head
while itr:
if count == index:
itr.prev.next = itr.next
if itr.next:
itr.next.prev = itr.prev
break
itr = itr.next
count += 1
def insert_at(self, index, data):
if index<0 or index>self.get_length():
raise Exception("Invalid index")
if index == 0:
self.insert_at_begining(data)
return
count = 0
itr = self.head
while itr:
if count == index-1:
node = Node(data, itr.next, itr)
if node.next:
node.next.prev = node
itr.next = node
break
itr = itr.next
count += 1
def insert_after_value(self, data_after, data_to_insert):
if self.head is None:
return
if self.head.data == data_after:
self.head.next = Node(data_to_insert, self.head.next)
return
itr = self.head
while itr:
if data_after == itr.data:
itr.next = Node(data_to_insert, itr.next)
break
itr = itr.next
def remove_by_value(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
count = 0
itr = self.head
while itr:
if data == itr.data:
self.remove_at(count)
break
itr = itr.next
count += 1
|
5f74215428e0884b9be1f1bf3d42f34e886f5a41 | ALLProject2/Project2 | /P2 V9.py | 22,488 | 3.875 | 4 | ###########financial position search#################
def financial_position_search(): #define code for financial statement as function
#menu
print "1. Search by business name" #display option 1
print "2. Search business from sector" #display option 2
print " " #print blank line
search_selection = input("Enter a number: ") #declare option input for menu
if search_selection == 1: #if the user selects 1 from the menu
user_response = raw_input("Type the business name to search:" + " ") #ask for user input
import urllib2 #import library
import json #import json
if statement == 1: #if the user has selected financial position from the main menu
FPurl = "http://dev.c0l.in:5984/financial_positions/_all_docs" #set the api url to financial position
elif statement == 2: #if the user selected income statement
FPurl = "http://dev.c0l.in:5984/income_statements/_all_docs" #set the api url to income statement
response = urllib2.urlopen(FPurl).read() #delcare response: open, read url library
data = json.loads(response) #delcare data: read response
counter = 0 #set counter variable to 0
a = [] #delcare blank list
for item in data['rows']: #start loop for every record in data
if statement == 1: #if the user has selected financial position from the main menu
FPurl2 = "http://dev.c0l.in:5984/financial_positions/" + item['id'] #use financial position api and add on the id from the record
elif statement ==2: #if the user selected income statement
FPurl2 = "http://dev.c0l.in:5984/income_statements/" + item['id'] #use income statement api and add on the id from the record
response2 = urllib2.urlopen(FPurl2).read() #delcare response
data2 = json.loads(response2) #delcare data
try: #set try as when at the end of the list the key won't be found
while user_response == data2['company']['name']: #if the business name entered matches one in the api
if statement == 1: #if the user selected financial position from the main menu
data_string = data2['sector'] + ", " + data2['company']['name'] + ", " + data2['date'] + ", " + "id:" + str(data2['id']) #set the string
elif statement == 2: #if the user selected income statement from the main menu
data_string = data2['sector'] + ", " + data2['company']['name'] + ", " + str(data2['fiscal_year_beginning']) + ", " + "id:" + str(data2['id']) #set the string
counter = counter + 1 #set counter to add one to count number of records found
print counter #print the counter value to display record number found
a.append(data_string) #add the value of the variable data_string to the empty list before it changes
break
except KeyError: #when at the end of api list there will be a KeyError
print "All records retrieved!" #print response
print " " #print blank line
print "Sorting retrieved records..." #print sorting prompt
print " " #print blank line
a.sort() #sort the list in alphabetical order
for val in a:
print val
id_search_financial_position() #run the id search
elif search_selection == 2: #if the user selects search by sector
print " " #
print "Available sectors:" #
print " " #
print "utilities" #
print "consumer goods" # ###print sector values###
print "healthcare" #
print "basic materials" #
print "services" #
print "technology" #
print "industry goods" #
print "financial" #
print " " #print blank line
sector_selection = raw_input("Enter a sector: ") #ask for user input
if sector_selection == "utilities":
print "Searching for all business records in the UTILITIES industry"
elif sector_selection == "consumer goods":
print "Searching for all business records in the CONSUMER GOODS industry"
elif sector_selection == "healthcare":
print "Searching for all business records in the HEALTHCARE industry"
elif sector_selection == "basic materials":
print "Searching for all business records in the BASIC MATERIALS industry"
elif sector_selection == "services":
print "Searching for all business records in the SERVICES industry"
elif sector_selection == "technology":
print "Searching for all business records in the TECHNOLOGY industry"
elif sector_selection == "industry goods":
print "Searching for all business records in the INDUSTRY GOODS industry"
elif sector_selection == "financial":
print "Searching for all business records in the FINANCIAL industry"
else:
financial_position_search()
import urllib2 #import library
import json #import json
if statement == 1: #if the user selected financial position from the main menu
FPurl = "http://dev.c0l.in:5984/financial_positions/_all_docs" #use financial statement api
elif statement ==2: #if the user selected the income statement from the main menu
FPurl = "http://dev.c0l.in:5984/income_statements/_all_docs" #use the income statement api
response = urllib2.urlopen(FPurl).read() #delcare resonse variable
data = json.loads(response) #delcare data variable
counter = 0 #set counter variable value to 0
a = [] #declare empty list
for item in data['rows']: #for each record in the api
if statement == 1: #if the user selected financial position from the main menu
FPurl2 = "http://dev.c0l.in:5984/financial_positions/" + item['id'] #use financial statement api with record id on the end
elif statement ==2:
FPurl2 = "http://dev.c0l.in:5984/income_statements/" + item['id'] #use income statenemt api with recprd id on the end
response2 = urllib2.urlopen(FPurl2).read() #declare resonse
data2 = json.loads(response2) #declare data
try:
while sector_selection == data2['sector']: #start loop
#while the users sector selection matches one in the api record
if statement ==1: #if the user selected financial position from the menu
data_string = data2['company']['name'] + ", " + data2['date'] + ", " + "id:" + str(data2['id']) #declare data string variable
elif statement == 2: #if the user selected income statement from the main menu
data_string = data2['sector'] + ", " + data2['company']['name'] + ", " + str(data2['fiscal_year_beginning']) + ", " + "id:" + str(data2['id']) #declare data string variable
counter = counter + 1 #add one to counter everytime a record matching criteria is found
print counter #print the counter value to represent the number of records found matching the criteria
a.append(data_string) #add the data string value to the list
break
except KeyError:
print "All records retrieved!" #print response
print " " #print blank line
a.sort() #sort list in alphabetical order
for val in a:
print val
id_search_financial_position() #run the id search
else:
print " "
print "Invalid input"
print "Please try again"
print " "
financial_position_search()
def id_search_financial_position(): #define id search function
input_id = raw_input("Enter ID from the list displayed above:" + " ") #ask for user to input id
print "Searching......please wait....."
import urllib2
import json
if statement == 1:
FPurl3 = "http://dev.c0l.in:5984/financial_positions/_all_docs"
else:
FPurl3 = "http://dev.c0l.in:5984/income_statements/_all_docs"
response3 = urllib2.urlopen(FPurl3).read()
global data3
data3 = json.loads(response3)
for items in data3['rows']:
if statement == 1:
FPurl4 = "http://dev.c0l.in:5984/financial_positions/" + items['id']
else:
FPurl4 = "http://dev.c0l.in:5984/income_statements/" + items['id']
response4 = urllib2.urlopen(FPurl4).read()
global data4
data4 = json.loads(response4)
try:
while input_id == str(data4['id']):
global data_string2
if statement ==1:
data_string2 = data4['company']['name'] + ", " + data4['date'] + ", " + "id:" + str(data4['id'])
elif statement == 2:
data_string2 = data4['sector'] + ", " + data4['company']['name'] + ", " + str(data4['fiscal_year_beginning']) + ", " + "id:" + str(data4['id'])
print " "
print data_string2
print " "
print "Please wait..."
if statement == 1:
#define non_current_assets variable
global non_current_assets
non_current_assets = float(data4['company']['non_current_assets'])
#define current_assets variable
global current_assets
current_assets = float(data4['company']['current_assets'])
#define and calculate total_assets
global total_assets
total_assets = non_current_assets + current_assets
#define equity variable
global equity
equity = float(data4['company']['equity'])
#define non_current_liabilities
global non_current_liabilities
non_current_liabilities = float(data4['company']['non_current_liabilities'])
#define current_liabilities
global current_liabilities
current_liabilities = float(data4['company']['current_liabilities'])
#define and calculate total_equity_liabilities
global total_equity_liabilities
total_equity_liabilities = equity + non_current_liabilities + current_liabilities
else:
#define sales variable
global sales
sales = float(data4['company']['sales'])
#define opening_stock variable
global opening_stock
opening_stock = float(data4['company']['opening_stock'])
#define purchases
global purchases
purchases = float(data4['company']['purchases'])
#define closing_stock
global closing_stock
closing_stock = float(data4['company']['closing_stock'])
#define expenses
global expenses
expenses = float(data4['company']['expenses'])
#define interest_payable
global interest_payable
interest_payable = float(data4['company']['interest_payable'])
#define interest_receivable
global interest_receivable
interest_receivable = float(data4['company']['interest_receivable'])
#define and calc cost_of_sales
global cost_of_sales
cost_of_sales = opening_stock + purchases - closing_stock
#define and calc gross profit
global gross_profit
gross_profit = sales - cost_of_sales
#define and calc net profit
global net_profit
net_profit = gross_profit - expenses
#define and calc profit for period
global profit_for_period
profit_for_period = net_profit - interest_payable + interest_receivable
#define name
global name
name = str(data4['company']['name'])
#define sector
global service_name
service_name = data4['sector']
break
except KeyError:
print " "
print "All records retrieved!"
financial_statement_display()
def financial_statement_display():
if statement == 1:
print" "
print "=========================DISPLAY========================="
print ("Financial position information for record:") , data_string2
print " "
print ("non current assets are:" " " ""), non_current_assets #print the result
print "" #print blank line
print ("current assets are:" " " ""), current_assets #print the result
print "" #print blank line
print ("Total assets are:" " " ""), total_assets #print the result
print "" #print blank line
print ("Equity is:" " " ""), equity #print the result
print "" #print blank line
print ("non current liabilities are:" " " ""), non_current_liabilities #print the result
print "" #print blank line
print ("current liabilities are:" " " ""), current_liabilities #print the result
print "" #print blank line
print ("Total equity and liabilities are:" " " ""), total_equity_liabilities #print the result
print "" #print blank line
export_csv = raw_input("Do you want to export to CSV? Y/N" + " ")
export_csv = export_csv.upper()
if export_csv == "Y":
#build list value for CSV export
financial_position = [non_current_assets, current_assets, total_assets, equity, non_current_liabilities, current_liabilities, total_equity_liabilities]
#build title list for CSV export
title_list = ["Non Current Assets", "Current Assets", "Total Assets", "Equity", "Non Current Liabilities", "Current Liabilities", "Total Equity and Liabilities"]
import csv
resultFile = open("FinancialPosition" + name +".csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(["Sector: " + service_name]) #write first row as sector name
wr.writerow(["Company Name: " + name]) #write company name row
wr.writerow(title_list) #Write second row as title_list values
wr.writerow(financial_position) #write third row as financial_position values
print("Export successful")
system_main()
else:
print "OK"
financial_position_search()
else:
print " "
print "=========================DISPLAY========================="
print ""
print ("Sales are:" " " ""), sales #print value
print "" #print blank
print ("Purchases are:" " " ""), purchases #print the result
print "" #print blank line
print ("Closing Stock is:" " " ""), closing_stock #print the result
print "" #print blank line
print ("Cost of Sales are:" " " ""), cost_of_sales #print the result
print "" #print blank line
print ("Gross Profit is:" " " ""), gross_profit #print the result
print "" #print blank line
print ("Expenses are:" " " ""), expenses #print the result
print "" #print blank line
print ("Net Profit is:" " " ""), net_profit #print the result
print "" #print blank line
print ("Interest Payable is:" " " ""), interest_payable #print the result
print "" #print blank line
print ("Interest Receivable is:" " " ""), interest_receivable #print the result
print "" #print blank line
print ("Profit for the Period is:" " " ""), profit_for_period #print the result
print "" #print blank line
export_csv = raw_input("Do you want to export to CSV? Y/N" + " ")
export_csv = export_csv.upper()
if export_csv == "Y":
#build list value for CSV export
income_statement = [purchases, closing_stock, cost_of_sales, gross_profit, expenses, net_profit, interest_payable, interest_receivable, profit_for_period]
#build title list for CSV export
title_list = ["Purchases", "Closing Stock", "Cost of Sales", "Gross Profit", "Expenses", "Net Profit", "Interest Payable", "Interest Receivable", "Profit For The Period"]
#build list for service name
import csv
resultFile = open("IncomeStatement"+name+".csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(service_name) #write first row as sector name
wr.writerow(["Company Name: " + name]) #write company name row
wr.writerow(title_list) #Write second row as title_list values
wr.writerow(income_statement) #write third row as financial_position values
print("Export successful")
system_main()
else:
print "OK"
financial_position_search()
########Start System Main#############
def system_main():
print ("1. Financial statement") #display option 1
print ("2. Income statement") #display option 2
print ("3. Shutdown") #display option 3
print(" ")
selection = input("Enter number: ") #declare user selection variable
print (" ")
global statement
if selection == 1: #if user selects option 1
statement = 1
financial_position_search() #call financial statement function
elif selection == 2: #if user selects 2
statement = 2
financial_position_search() #call income statement function
elif selection == 3:
quit()
else:
print("You have entered an invalid number")
print "Please try again"
print(" ")
system_main()
##########Login Req####################
#Username and Password database
#User = [Username, Password]
User1 = [["admin"], ["Password1"]]
User2 = [["simran"], ["Password2"]]
User3 = [["callum"], ["Password3"]]
User4 = [["cj"], ["Password4"]]
User5 = [["jamie"], ["Password5"]]
User6 = [["ben"], ["Password6"]]
User7 = [["guest"], ["Guest"]]
#Code
#Existing Users
def existing():
global lock1
global lock2
global Guest
#Locks on access to program
lock1 = "locked"
lock2 = "locked"
Iden = "User"
Guest = False
#Keeps the username lower case to avoid grammar issues
Username = raw_input("Please enter your username ").lower()
#Checks Username input against database
if Username in User1[0]:
lock1 = "unlocked"
Iden = "Admin"
elif Username in User2[0]:
lock1 = "unlocked"
Iden = "Simran"
elif Username in User3[0]:
lock1 = "unlocked"
Iden = "Callum"
elif Username in User4[0]:
lock1 = "unlocked"
Iden = "CJ"
elif Username in User5[0]:
lock1 = "unlocked"
Iden = "Jamie"
elif Username in User6[0]:
lock1 = "unlocked"
Iden = "Ben"
elif Username in User7[0]:
lock1 = "unlocked"
Iden = "Guest"
else:
lock1 = "locked"
#Checks Password input against database
Password = raw_input("Please enter your password ")
if Password in User1[1]:
lock2 = "unlocked"
elif Password in User2[1]:
lock2 = "unlocked"
elif Password in User3[1]:
lock2 = "unlocked"
elif Password in User4[1]:
lock2 = "unlocked"
elif Password in User5[1]:
lock2 = "unlocked"
elif Password in User6[1]:
lock2 = "unlocked"
elif Password in User7[1]:
lock2 = "unlocked"
Guest = True
else:
lock2 = "locked"
#Action for locked program
if lock1 == "locked" and lock2 == "locked":
print "Incorrect Username"
print "Incorrect Password"
existing()
elif lock1 == "locked":
print "Incorrect Username"
existing()
elif lock2 == "locked":
print "Incorrect Password"
existing()
#Action for unlocked program
if lock1 == "unlocked" and lock2 == "unlocked" and Guest == False:
print ""
print "Welcome back " + Iden
print ""
system_main()
elif lock1 == "unlocked" and lock2 == "unlocked" and Guest == True:
print ""
print "Welcome " + Iden
print "Please contact an administartor for a permanent login"
print ""
system_main()
#Non-registered users
def new():
print("Please use our Guest Account ")
print("Username: Guest")
print("Password: Guest")
print("Note: Password is Case Sensitive")
print("")
existing()
#Start menu
def Menu():
repeat = 1
while repeat == 1:
check = raw_input("Welcome, are you registered with this software? y/n ").lower()
if check == "y":
existing()
repeat = 0
elif check == "n":
new()
repeat = 1
else:
print("Please answer y/n ")
print("")
repeat = 1
#Launching program
Menu()
|
6723a1b4262244c04ba650d900a66fd267f7537b | Eugene-twj/python_train | /dictionary.py | 3,039 | 3.8125 | 4 | alien_0 = {'color': 'green', 'point': 5}
print(alien_0['color'])
print(alien_0['point'])
favorite_languages = {
'jen': 'python',
'sarah': 'C',
'edward': 'ruby',
'phil': 'python',
}
# 按字母顺序遍历字典键-值对
for name, language in sorted(favorite_languages.items()):
print(name.title() + "'s favorite language is " + language)
# 按键值遍历字典
print("\nThe following language have been mentioned")
for language in favorite_languages.values():
print(language.title())
vocabulary = {
'sex': 'it means person',
'github': 'it is a version control',
'vs': 'it means two person competition',
'python': 'it is a programme language',
'eugene': 'it is a person',
}
for voc, mean in vocabulary.items():
print(voc + "\nit represent " + mean)
# 添加键-值对
vocabulary['ss'] = 'double s'
vocabulary['rr'] = 'double r'
vocabulary['tt'] = 'double t'
vocabulary['gg'] = 'double g'
vocabulary['yy'] = 'double y'
# 列表中嵌套字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', "point": 10}
alien_2 = {'color': 'red', 'point': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
aliens = [alien_1]
for _ in range(30):
new_alien = {'color': 'green', 'point': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['point'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['point'] = 15
for alien in aliens[:5]:
print(alien)
# 字典中存储列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print('\t' + language.title())
# 字典中嵌套字典
users = {
'eugene': {
'name': 'tang',
'location': 'hunan',
'phone': 1228,
},
'fu': {
'name': 'fuy',
'location': 'xin',
'phone': 110,
},
}
for user, info in users.items():
print("\n" + user + "'s detail information")
for info_1, info_2 in info.items():
if info_1 == 'name':
print('\tThat name is ' + info_2.title())
elif info_1 == 'location':
print("\t" + user + "'s location is in " + info_2)
elif info_1 == 'phone':
print("\tHis phone is " + str(info_2))
# 练习6-7
people_1 = {
'first_name': 'tang',
'last_name': 'eugene',
'age': 23,
'city': 'hy',
}
people_2 = {
'first_name': 'fu',
'last_name': 'fuy',
'age': 23,
'city': 'xj',
}
people_3 = {
'first_name': 'zhou',
'last_name': 'mao',
'age': 22,
'city': 'xj',
}
peoples = [people_1, people_2, people_3]
for people in peoples:
print(people)
|
c4e8960c5c6bd1ea34ad9ab7f9616453c4e1208a | Ved005/project-euler-solutions | /code/ambiguous_numbers/sol_198.py | 1,067 | 3.625 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\ambiguous_numbers\sol_198.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #198 :: Ambiguous Numbers
#
# For more information see:
# https://projecteuler.net/problem=198
# Problem Statement
'''
A best approximation to a real number x for the denominator bound d is a rational number r/s (in reduced form) with s ≤ d, so that any rational number p/q which is closer to x than r/s has q > d.
Usually the best approximation to a real number is uniquely determined for all denominator bounds. However, there are some exceptions, e.g. 9/40 has the two best approximations 1/4 and 1/5 for the denominator bound 6.
We shall call a real number x ambiguous, if there is at least one denominator bound for which x possesses two best approximations. Clearly, an ambiguous number is necessarily rational.
How many ambiguous numbers x = p/q,
0 < x < 1/100, are there whose denominator q does not exceed 108?
'''
# Solution
# Solution Approach
'''
'''
|
351c3bb82700da890f0284405b8c6aff0f0bade2 | daniel-reich/turbo-robot | /Kk5Ku4CtipaFtATPT_14.py | 1,470 | 4.15625 | 4 | """
* "coconuts" has 8 letters.
* A byte in binary has 8 bits.
* A byte can represent a character.
We can use the word "coconuts" to communicate with each other in binary if we
use upper case letters as 1s and lower case letters as 0s.
**Create a function that translates a word in plain text, into Coconut.**
### Worked Example
The binary for "coconuts" is
01100011 01101111 01100011 01101111 01101110 01110101 01110100 01110011
c o c o n u t s
Since 0s are lowercase and 1s are uppercase, we can map the binary like this.
cOConuTS cOCoNUTS cOConuTS cOCoNUTS cOCoNUTs cOCOnUtS cOCOnUts cOCOnuTS
coconut_translator("coconuts") ➞ "cOConuTS cOCoNUTS cOConuTS cOCoNUTS cOCoNUTs cOCOnUtS cOCOnUts cOCOnuTS"
### Examples
coconut_translator("Hi") ➞ "cOcoNuts cOCoNutS"
coconut_translator("edabit") ➞ "cOConUtS cOConUts cOConutS cOConuTs cOCoNutS cOCOnUts"
coconut_translator("123") ➞ "coCOnutS coCOnuTs coCOnuTS"
### Notes
* All inputs will be strings.
* Make sure to separate the _coconuts_ with spaces.
"""
def coconut_translator(txt):
ans = list(map(lambda x:bin(ord(x))[2:].rjust(8,'0'),list(txt)))
def c(x):
t = list('coconuts')
ans = ''.join(list(map(lambda y: t.pop(0).upper() if y == '1' else t.pop(0), x)))
t = list('coconuts')
return ans
return ' '.join(list(map(lambda x:c(x),ans)))
|
8b7a7d89b09ed8643b84fcca229df57910da6ee2 | nixeagle/euler | /utilities/euler.py | 748 | 3.765625 | 4 | # (C) 2010 zc00gii (zc00gii@gmail.com)
# Do not copy or modify without crediting
# MIT compatible
def prime_factors(n)
w = 2
a = []
while w < n+1:
if n%w == 0:
n = n / w
a.append[w]
else:
w = w + 1
def factors(n):
w = 2
a = []
while w < sqrt(n):
if n%w == 0 and w < sqrt(n):
a.append[w]
w = w + 1
def fibonacci(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
def fibonacci_list(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
def evenp(n):
if n%2 == 0:
return True
elif n%2 == 1:
return False
else:
print "Error: only integars are accepted"
def oddp(n):
if n%2 == 1:
return True
elif n%2 == 0:
return False
else:
print "Error: only integars are accepted"
|
44e919a0432ff687a4d01d57070b39d2188adf50 | AkashManiar/python-basics | /class.py | 439 | 3.625 | 4 | class Animal(object):
name = ""
def eat(self):
print("%s is eating.." % self.name)
def sleep(self):
print("%s is sleeping..." % self.name)
class Mammal(Animal):
hasBackBone = True
hasHair = True
def growHair(self):
print("%s is Growing Hair" % self.name)
cat = Mammal()
dog = Mammal()
snake = Animal()
cat.name = "Shakespear"
dog.name = "Molly"
cat.eat()
cat.growHair()
dog.sleep() |
c4f3159fffe8df180fd208a6040f55997a367a74 | daniel-reich/ubiquitous-fiesta | /GaJkMnuHLuPmXZK7h_10.py | 275 | 3.5625 | 4 |
def letters(word1, word2):
w1 = set(list(word1))
w2 = set(list(word2))
intersect = sorted(w1.intersection(w2))
unique1 = sorted(w1.difference(intersect))
unique2 = sorted(w2.difference(intersect))
return ["".join(intersect), "".join(unique1), "".join(unique2)]
|
c236286e8fa828ba8f5fc0c6d1f473213908a298 | AvneetHD/little_projects | /encryptor.py | 693 | 3.84375 | 4 | import random
result = ""
message = ""
choice = ""
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while choice != '0':
number = random.choice(numbers)
choice = input('Do you want to encrypt or decrypt\nEnter 1 to encrypt, 2 to decrypt, and 0 to exit.')
if choice == '1':
message = input('Enter Message for Encryption.')
for i in range(0, len(message)):
result = result + chr(ord(message[i])-2)
print(result)
result = ''
elif choice == '2':
message = input('Enter Message for Decryption.')
for i in range(0, len(message)):
result = result + chr(ord(message[i])+2)
print(result)
result = ''
|
49b4ee5d4141665d212e01ca24e7f33228a62c24 | muhammadegaa/xzceb-flask_eng_fr | /final_project/machinetranslation/tests/tests.py | 882 | 3.625 | 4 | import unittest
from translator import english_to_french, french_to_english
class TestTranslateEnToFr(unittest.TestCase):
"""
Class to test the function english_to_french
"""
def test1(self):
"""
Function to test the function english_to_french
"""
self.assertIsNone(english_to_french(None))
self.assertEqual(english_to_french("Hello"), "Bonjour")
self.assertNotEqual(english_to_french("Bonjour"), "Hello")
class TestTranslateFrToEn(unittest.TestCase):
"""
Class to test the function french_to_english
"""
def test1(self):
"""
Function to test the function french_to_english
"""
self.assertIsNone(french_to_english(None))
self.assertEqual(french_to_english("Bonjour"), "Hello")
self.assertNotEqual(french_to_english("Hello"), "Bonjour")
unittest.main() |
8baef38728c2320d081ccc73f3623c9f5665cbaf | DSC-Sharda-University/Python | /data-structure/doublylinked.py | 1,608 | 4.3125 | 4 | """
To create doubly link list with the operation insert at the first location and
also insert at the last location.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# creation of doulbly linked list
class doublylink:
def __init__(self):
self.head = None
def insert_last(self, data):
if self.head is None:
node = Node(data)
node.prev = None
self.head = node
else:
node = Node(data)
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
node.prev = temp
node.next = None
def insert_first(self, data):
if self.head is None:
node = Node(data)
node.prev = None
self.head = node
else:
node = Node(data)
self.head.prev = node
node.next = self.head
self.head = node
node.prev = None
def display(self):
temp = self.head
while temp:
print(temp.data, '==>', end='')
temp = temp.next
link = doublylink()
while(True):
print("1-Insert first\n 2-Insert last\n 3-Display\n")
choice = int(input("Enter your choice:\n"))
if choice == 1:
link.insert_first(int(input(" \nEnter the value to insert:\n")))
elif choice == 2:
link.insert_last(int(input("Enter the value to insert at the last\
postion:\n")))
elif choice == 3:
link.display()
|
7262eabc34c7cf8de127e574b3af5cfac40a208b | faiderfl/algorithms | /recursion/CapitalizeFirst.py | 664 | 4 | 4 | def capitalize_first(arr):
len_arr=len(arr)
if len(arr)==1:
aux=''
aux=arr[len_arr-1][0].upper()
aux = aux+ arr[len_arr-1][1:]
arr[len_arr-1]=aux
return [arr[len_arr-1]]
else:
aux=''
aux=arr[0][0].upper()
aux= aux + arr[0][1:]
arr[0]=aux
return [arr[0]] + capitalize_first(arr[1:])
print(capitalize_first(['car','taco','banana']))
def capitalize_first2(arr):
result = []
if len(arr) == 0:
return result
result.append(arr[0][0].upper() + arr[0][1:])
return result + capitalize_first2(arr[1:])
print(capitalize_first2(['car','taco','banana'])) |
e13dc2562d9f6e8ce5dbf64adbbd50afc7205ede | sairabhur/Py-Me-Up-Charlie-python | /main.py | 2,115 | 3.6875 | 4 |
# coding: utf-8
# In[1]:
import os
import csv
import locale
locale.setlocale( locale.LC_ALL, '' )
months = []
revenue = []
revenue_change = []
# In[2]:
file_path = os.path.join("budget_data.csv")
with open(file_path,'r') as csvfile:
csvdata = csv.reader(csvfile, delimiter=",")
next(csvdata, None)
for row in csvdata:
months.append(row[0])
revenue.append(int(row[1]))
unique_months = set(months)
total_revenue = sum(revenue)
# Calculate Change in Revenue
for i in range(0,len(revenue) -1):
revenue_change.append(int(revenue[i+1]) - int(revenue[i]))
avg_rev_change = sum(revenue_change)/len(revenue_change)
# find maximum and minumum revenue
max_revenue = max(revenue)
min_revenue = min(revenue)
# find the associated date of maximum and minimm revenue
max_revenue_date = months[revenue.index(max_revenue)]
min_revenue_date = months[revenue.index(min_revenue)]
print("Financial Analysis")
print("---------------------------")
print("Total Months: " + str(len(unique_months)))
print("Total Revenue: $" + str(total_revenue))
print("Average Revenue Change: $" + str(avg_rev_change))
print("Greatest Increase in Revenue: " + max_revenue_date + " ($" + str(max_revenue)+ ")")
print("Greatest Decrease in Revenue: " + min_revenue_date + " ($" + str(min_revenue)+ ")")
# In[3]:
path = os.path.join("PyBank", "Fin_Result_"+file_path[7:13]+".txt")
with open(path, "w", newline='') as txtfile:
txtfile.write("Financial Analysis\n")
txtfile.write("----------------------------\n")
txtfile.write("Total Months: " + str(len(unique_months)) + "\n")
txtfile.write("Total Revenue: $" + str(total_revenue) + "\n")
txtfile.write("Average Revenue Change: $" + str(avg_rev_change)+"\n")
txtfile.write("Greatest Increase in Revenue: " + max_revenue_date + " ($" + str(max_revenue) + ")" + "\n")
txtfile.write("Greatest Decrease in Revenue: " + min_revenue_date + " ($" + str(min_revenue) + ")")
|
a54d08843545df7e6f9dcdc93ef975d3669359b1 | igortereshchenko/amis_python | /km73/Zeleniy_Dmytro/5/task1.py | 485 | 3.828125 | 4 | heights = []
n = int(input("Enter number of pupil: "))
for i in range(n):
new_height = int(input("Enter hight pupil less than previous: "))
heights.append(new_height)
height = int(input("Enter height of Petya: "))
heights.append(height)
if height < 200:
heights.sort()
heights = heights[::-1]
same_height = heights.count(height)
answer = heights.index(height) + same_height
else:
answer = "Not correct data"
print("Place of Petya is " + str(answer))
|
b91704b00a6d8f9a064f89d18a8fcc0d70afc6fb | lo1cgsan/rok202021 | /3A/konto.py | 783 | 3.515625 | 4 | class Konto:
def __init__(self, ile = 0):
self.bilans = ile
def wplata(self, ile):
self.bilans += ile
return self.bilans
def wyplata(self, ile):
self.bilans -= ile
return self.bilans
class KontoStart(Konto):
def __init__(self, ile = 0, debet = 0):
Konto.__init__(self, ile)
self.debet = debet
def wyplata(self, ile):
if self.bilans - ile < self.debet:
print("Brak środków")
return self.bilans
else:
return Konto.wyplata(self, ile)
o1 = KontoStart(100, 20)
o2 = KontoStart(50, 10)
print("Stan konta:", o1.wplata(50))
print("Stan konta:", o2.wplata(50))
print("Stan konta:", o1.wyplata(100))
print("Stan konta:", o2.wyplata(150))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.