blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6f73326550aaf5df694ad98f31e0b1dd69a29a22 | scxbx/docx_project | /my_docx.py | 877 | 3.640625 | 4 | from docx import Document
# 读取文档
doc = Document('C:/Users/sc/Desktop/test_docx/sample.docx') # filename为word文档
# 获取文档中的表格
doc.tables # 获取文档的表格个数 len(doc.tables)
# 读取第1个表格
tb1 = doc.tables[0]
# 获取第一个表格的行
tb1.rows # 获取表格的行数len(tb1.rows)
# 读取表格的第一行的单元格
row_cells = tb1.rows[0].cells
# 读取第一行所有单元格的内容
# for cell in row_cells:
# print(cell.text)
print(tb1.cell(2, 1).text)
print(tb1.cell(20, 0).text)
headcount = 0
# to judge whether a string contains all keys in a list
def checkAllKeysInAString(my_list, my_str):
for key in my_list:
if key not in my_str:
return False
return True
for table in doc.tables:
print(table.cell(0, 0).text)
print(len(doc.tables))
print(table.cell(26, 1).text)
|
718b737fbde5747a0d832f53aff99868dd2cb1df | jingong171/jingong-homework | /袁权/2017310415-第三次作业-金工17-1-袁权/1.py | 3,087 | 3.640625 | 4 | def getTotalDaysFrom1990(year,month):
"""返回1990年1月1日的天数"""
for month in range(1,month):
m=month
y=year
if(m==4 or m==6 or m==9 or m==11):
d=30
elif(m==2):
d=28
else:
d=31
sum=0
sum=sum+d
if((y-1990)%4==0):
day=(y-1990)*365+sum+int((y-1990)/4)+1
else:
day=(y-1990)*365+sum+int((y-1990)/4)
return day
year=input("请输入年份:")
month=input("请输入月份:")
year=int(year)
month=int(month)
m=month
y=year
d=getTotalDaysFrom1990(year,month)
t=d%7
print("Sun"+" "+"Mon"+" "+"Tue"+" "+"Wed"+" "+"Thu"+" "+"Fri"+" "+"Sat")
if(m==4 or m==6 or m==9 or m==11):
for n in range(0,t):
print(" ",end=" ")
for n in range(1,7-t+1):
print(n,end=" ")
print(" ")
for n in range(7-t+1,14-t+1):
print(n,end=" ")
print(" ")
for n in range(14-t+1,21-t+1):
print(n,end=" ")
print(" ")
for n in range(21-t+1,28-t+1):
print(n,end=" ")
print(" ")
if(t>5):
for n in range(28-t+1,35-t+1):
print(n,end=" ")
print(" ")
for n in range(35-t+1,31):
print(n,end=" ")
else:
for n in range(28-t+1,31):
print(n,end=" ")
elif(m==2 and (y-1990)%4==0):
for n in range(0,t):
print(" ",end=" ")
for n in range(1,7-t+1):
print(n,end=" ")
print(" ")
for n in range(7-t+1,14-t+1):
print(n,end=" ")
print(" ")
for n in range(14-t+1,21-t+1):
print(n,end=" ")
print(" ")
for n in range(21-t+1,28-t+1):
print(n,end=" ")
print(" ")
if(t>6):
for n in range(28-t+1,35-t+1):
print(n,end=" ")
print(" ")
for n in range(35-t+1,30):
print(n,end=" ")
else:
for n in range(28-t+1,30):
print(n,end=" ")
elif(m==0 and (y-1990)%4!=0):
for n in range(0,t):
print(" ",end=" ")
for n in range(1,7-t+1):
print(n,end=" ")
print(" ")
for n in range(7-t+1,14-t+1):
print(n,end=" ")
print(" ")
for n in range(14-t+1,21-t+1):
print(n,end=" ")
print(" ")
for n in range(21-t+1,28-t+1):
print(n,end=" ")
print(" ")
for n in range(28-t+1,29):
print(n,end=" ")
else:
for n in range(0,t):
print(" ",end=" ")
for n in range(1,7-t+1):
print(n,end=" ")
print(" ")
for n in range(7-t+1,14-t+1):
print(n,end=" ")
print(" ")
for n in range(14-t+1,21-t+1):
print(n,end=" ")
print(" ")
for n in range(21-t+1,28-t+1):
print(n,end=" ")
print(" ")
if(t>4):
for n in range(28-t+1,35-t+1):
print(n,end=" ")
print(" ")
for n in range(35-t+1,32):
print(n,end=" ")
else:
for n in range(28-t+1,32):
print(n,end=" ")
|
ee31fd98ceb838b7e07f196f749c756bd246f14d | kirtymeena/DSA | /6.Sorting/10.quick sort(with lomuto partiton).py | 717 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 08:44:06 2020
@author: kirty
"""
# arr = [10,80,30,90,40,50,70]
arr=[10,50,100,200]
def quickSort(arr,l,h):
if l<h:
p = partition(arr,l,h)
quickSort(arr,l,p-1)
quickSort(arr,p+1,h)
return arr
def partition(arr,l,h):
pi=arr[h]
i=l-1
j=l
while j<=h-1:
if arr[j]<pi:
i=i+1
arr[i],arr[j] = arr[j],arr[i]
j+=1
arr[i+1],arr[h] = arr[h],arr[i+1]
return i+1
print(quickSort(arr,0,len(arr)-1))
# worst case - O(n2)
# best and avg case - O(nlogn)
# aux space - O(1)
# lomuto and hoare partitioning does not provide stability
# naive partitioning provides stability |
b39602c1c69761cffe433f4619911d49235d009b | SinCatGit/leetcode | /01061/test_lexicographically_smallest_equivalent_string.py | 538 | 3.609375 | 4 | import unittest
from lexicographically_smallest_equivalent_string import Solution, TreeNode
class TestSolution(unittest.TestCase):
def test_Calculate_Solution(self):
sol = Solution()
self.assertEqual('makkek', sol.smallestEquivalentString('parker', 'morris', 'parser'))
self.assertEqual('hdld', sol.smallestEquivalentString('hello', 'world', 'hold'))
self.assertEqual('aauaaaaada', sol.smallestEquivalentString('leetcode', 'programs', 'sourcecode'))
if __name__ == '__main__':
unittest.main()
|
0d721bfdbd77a9f97d9f926fb414a1661089aacb | Sbrown19/Module3 | /Module6/hourly_employee_input.py | 816 | 3.96875 | 4 | # Program: Hourly Employee input
# Author: Skyler Brown
# Date: 06/17/2020
def get_user_input():
name = input("Enter your name")
hours_worked = int(input("Please enter your hours for the week"))
hourly_pay = float(input("What is your hourly wage."))
print(name, " Worked", hours_worked,"hours this week and make", hourly_pay, "hourly.")
if __name__== '__main__':
try:
get_user_input()
except ValueError as err:
print("ValueError encountered! ")
# Call function using negative numbers
if __name__== '__main__':
try:
get_user_input()
except ValueError as err:
print("ValueError encountered! ")
# Call function using bad input
if __name__== '__main__':
try:
get_user_input()
except ValueError as err:
print("ValueError encountered! ")
|
00abe858e7fc5c33f652fdc536be6bcc59663dbc | hide-hub/PythonTest | /linear_regression/multi_regression_test.py | 1,677 | 3.890625 | 4 | # multi regression test
# The data (X1, X2, X3) are for each patient
# X1 : systolic blood pressure
# X2 : age in years
# X3 : weight in pounds
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
df = pd.read_excel( 'mlr02.xls' )
X = df.as_matrix()
# 3D show
fig = plt.figure()
ax = fig.add_subplot( 111, projection='3d' )
ax.scatter( df.X1, df.X2, df.X3 )
plt.show()
# 2D show for X1 and X2
plt.scatter( X[:,1], X[:,0] )
plt.show()
# 2D show for X1 and X3
plt.scatter( X[:,2], X[:,0] )
plt.show()
df['ones'] = 1
Y = df['X1'] # estimate blood pressure
# there are 3 ways for the selection of explanatory values
X = df[[ 'X2', 'X3', 'ones']] # both X2 and X3 are explanatory values
X2only = df[['X2', 'ones']] # only X2 is explanatory value
X3only = df[['X3', 'ones']] # only X3 is explanatory value
# calculate each weights
w_both = np.linalg.solve( np.dot( X.T, X ), np.dot( X.T, Y ) )
w_x2only = np.linalg.solve( np.dot( X2only.T, X2only ), np.dot( X2only.T, Y ) )
w_x3only = np.linalg.solve( np.dot( X3only.T, X3only ), np.dot( X3only.T, Y ) )
# the function for calculating R-Squared value
def calcR2( Y, Y_hat ):
d1 = Y - Y_hat
d2 = Y - Y.mean()
R2 = 1 - np.dot( d1.T, d1 ) / np.dot( d2.T, d2 )
return R2
# compare R-Squared value of them
Yh_both = X.dot( w_both )
Yh_x2only = X2only.dot( w_x2only )
Yh_x3only = X3only.dot( w_x3only )
print( 'compare the result of regressions' )
print( 'using both X2 and X3 \t:', calcR2( Y, Yh_both ) )
print( 'using X2 only \t:', calcR2(Y, Yh_x2only) )
print( 'using X3 only \t:', calcR2(Y, Yh_x3only) )
|
6b520d682b8d90938b9b5a529339f6f5b44c62ac | bendardenne/spendee-sankey | /spendee-sankey.py | 3,642 | 3.984375 | 4 | #!/usr/bin/env python3
# http://sankeymatic.com/build/
import pandas
# Regroup several Spendee categories to more general categories.
# Spendee categories become subcategories here.
# Don't use category names that conflict with the Spendee categories.
CATEGORIES = {
"Housing": ["Rent", "Utilities"],
"Living": ["Groceries", "Healthcare", "Clothing"],
"Leisure": ["Entertainment", "Brewing", "Music", "Reading", "Drinks", "Take Away & Restaurant", "Cinema"],
}
# Spendee categories not explicitely listedd in the above map will be joined in this category
DEFAULT_CATEGORY = "Misc"
# This is the category that holds all expenses. Savings + expenses = income.
EXPENSES_CATEGORY = "Expenses"
# Print a line suitable for Sankeymatic
def sankey(source, flow, dest):
print(source + " [" + str(flow) + "] " + dest)
# Write flows from category to all subcategories and return the total of flow created from category to subcategories
def divide(df, category, subcategories):
divided = 0
grouped = df.groupby('Category Name').sum().filter(subcategories, axis=0).sort_values("Amount")
for subcategory in grouped.iterrows():
flow = abs(subcategory[1][0])
divided += flow
sankey(category, flow, subcategory[0])
return divided
# Same as above, but going from several categories to a single one. Can we use a common function for both things?
def merge(df, subcategories, category):
merged = 0
grouped = df.groupby('Category Name').sum().filter(subcategories, axis=0).sort_values("Amount")
for subcategory in grouped.iterrows():
flow = abs(subcategory[1][0])
merged += flow
sankey(subcategory[0], flow, category)
return merged
df = pandas.read_csv("test.csv")
# Remove useless data just clean up output when printing
for col in ['Surname', 'First Name', 'Place', 'Address', 'Wallet', 'Currency']:
del df[col]
# Gifts can be both income and expense in spendee but we need to use another name in sankey, otherwise the two conflict.
df.loc[(df["Category Type"] == "income") & (df["Category Name"] == "Gifts"), "Category Name"] = "Gifted"
# Aggregate expenses and incomes
balances = df.groupby('Category Type').sum()
# Savings is expenses + incomes
savings = balances.sum()['Amount']
# Also add savings listed as expenses (e.g. savings accounts)
savings -= df.groupby('Category Name').sum().loc['Savings', 'Amount']
income_types = df[(df['Category Type'] == "income")]
merge(income_types, income_types["Category Name"].unique(), "Income")
sankey("Income", savings, "Savings")
sankey("Income", balances.loc['income', 'Amount'] - savings, EXPENSES_CATEGORY)
# expenses without incomes or savings
actual_expenses = df[(df['Category Type'] == "expense") & (df['Category Name'] != 'Savings')]
# Sort categories by largest first
categories_total_amount = lambda map_entry: df[df["Category Name"].isin(map_entry[1])]["Amount"].sum()
for category, subcategories in sorted(CATEGORIES.items(), key=categories_total_amount):
flow = divide(actual_expenses, category, subcategories)
sankey(EXPENSES_CATEGORY, flow, category)
# Unassigned categories should go to Disposable directly
# Or should they all go to an "Other" Category?
assigned_subcategories = [i for x in CATEGORIES.values() for i in x]
all_categories = actual_expenses["Category Name"].unique()
flow = divide(actual_expenses, DEFAULT_CATEGORY, [x for x in all_categories if x not in assigned_subcategories])
sankey(EXPENSES_CATEGORY, flow, DEFAULT_CATEGORY)
# test
pie = actual_expenses.groupby("Category Name").sum().abs().plot.pie("Amount")
pie.get_figure().savefig("test.pdf")
|
bf87a5e5cbffcbb7c6bb4c3efe0fda04a565a092 | jgardner8/Bounce | /MixIns/CollisionsMixIn.py | 5,967 | 3.546875 | 4 | from math import floor, fabs
class CollisionsMixIn(object):
"""handles collisions with the level"""
def __init__(self, start_position, start_velocity, bounce_factor, bounce_volume_factor, level):
"""Bounce factor controls how much speed is lost when bouncing. 1 = no speed lost, 0 = all speed lost.
Bounce volume factor controls the volume of the bounces, which is multiplied by the ball velocity. 0 is no sound."""
self.position = list(start_position)
self.velocity = list(start_velocity)
self.bounce_factor = bounce_factor
self.bounce_volume_factor = bounce_volume_factor
self.level = level
def collide(self, position, velocity, axis=-1):
"""axis defines the axis to check for collisions on. -1 = both, 0 = x, 1 = y"""
def calculate_volume(speed):
IMPACT_SCALE = 1500 #used to translate impact into a range approximately 0-1 for set_volume()
MIN_IMPACT = 28 #smallest impact that can create sound
return (fabs(speed) - MIN_IMPACT) / IMPACT_SCALE * self.bounce_volume_factor
def bounce(axis):
vol = calculate_volume(self.velocity[axis])
self.BOUNCE_SOUND.set_volume(vol)
self.BOUNCE_SOUND.play()
self.velocity[axis] = -self.velocity[axis] * self.bounce_factor
def normalise_position(position):
"""object position measured in tiles"""
return floor(position[0] / self.level.tile_size), floor(position[1] / self.level.tile_size)
def collide_on_left(pos):
#Collide with screen boundary
if self.position[0] < 0: #hit edge of screen
bounce(0)
self.position[0] = 0 #set position to collision position
return
#Collide with tile
if pos[1] < self.level.size()[1]: #y pos not outside level
if self.level[pos[0], pos[1]].solid: #hit tile on left
if not self.level[pos[0] + 1, pos[1]].solid: #tile to right (current tile) is not solid
bounce(0) #bounce on x axis
self.position[0] = (pos[0] + 1) * self.level.tile_size #set position to collision position
def collide_on_right(pos):
#Collide with screen boundary
if pos[0] >= self.level.size()[0] - 1: #hit edge of screen
bounce(0) #bounce on x axis
self.position[0] = (self.level.size()[0] - 1) * self.level.tile_size #set position to collision position
return
#Collide with tile
if pos[1] < self.level.size()[1]: #y pos not outside level
if self.level[pos[0] + 1, pos[1]].solid: #hit tile on right
if not self.level[pos[0], pos[1]].solid: #tile to left (current tile) is not solid
bounce(0) #bounce on x axis
self.position[0] = pos[0] * self.level.tile_size #set position to collision position
def collide_on_top(pos):
#Collide with screen boundary
if self.position[1] < 0: #hit edge of screen
bounce(1)
self.position[1] = 0 #set position to collision position
return
#Collide with tile
if pos[0] < self.level.size()[0]: #x pos not outside level
if self.level[pos[0], pos[1]].solid: #hit tile above
if not self.level[pos[0], pos[1] + 1].solid: #tile below (current tile) is not solid
bounce(1) #bounce on y axis
self.position[1] = (pos[1] + 1) * self.level.tile_size #set position to collision position
def collide_on_bottom(pos):
#Collide with screen boundary
if pos[1] >= self.level.size()[1] - 1: #hit edge of screen
bounce(1) #bounce on y axis
self.position[1] = (self.level.size()[1] - 1) * self.level.tile_size #set position to collision position
return
#Collide with tile
if pos[0] < self.level.size()[0]: #x pos not outside level
if self.level[pos[0], pos[1] + 1].solid: #hit tile below
if not self.level[pos[0], pos[1]].solid: #tile above (current tile) is not solid
bounce(1) #bounce on y axis
self.position[1] = pos[1] * self.level.tile_size #set position to collision position
if axis != 1:
if velocity[0] < 0:
collide_on_left(normalise_position(position))
elif velocity[0] > 0:
collide_on_right(normalise_position(position))
if axis != 0:
if velocity[1] < 0:
collide_on_top(normalise_position(position))
elif velocity[1] > 0:
collide_on_bottom(normalise_position(position))
def special_collisions(self):
"""Returns any special objects hit, such as a level end."""
test = self.position[0] // self.level.tile_size, self.position[1] // self.level.tile_size
if (self.position[0] // self.level.tile_size == self.level.level_end[0]
and self.position[1] // self.level.tile_size == self.level.level_end[1]):
return 'level_end'
def update(self):
"""Calculates bouncing for every collision, and returns any special objects hit, such as a level end."""
#As ball can be between tiles, there is 2 extra collision checks, one for x and one for y axis
self.collide(self.position, self.velocity) #collision 1
self.collide((self.position[0], self.position[1] + self.level.tile_size), self.velocity, 0)
self.collide((self.position[0] + self.level.tile_size, self.position[1]), self.velocity, 1)
return self.special_collisions() |
f5eed9c2b7d9dcbbb4c6108e65c06a03e74ce452 | Ediel96/platzi-python | /recorrer.py | 273 | 4 | 4 |
def example1():
# name = input('Write your name: ')
# for word in name:
# print(word)
words = input('Write your words: ')
for character in words:
print(character.upper())
def run():
example1()
if __name__ == '__main__':
run()
|
9b79f5429ad3353da6c2ab0d17351bd3cb41e977 | forza111/Learn_Python | /calculator.py | 1,281 | 4.28125 | 4 | '''Напишите простой интерпретатор математического выражения.
На вход подаётся строка с выражением, состоящим из двух чисел,
объединённых бинарным оператором: a operator b, где вместо operator
могут использоваться следующие слова: plus, minus, multiply, divide для,
соответственно, сложения, вычитания, умножения и целочисленного деления.
пайтон своифункции
Формат ввода:
Одна строка, содержащая выражение вида a operator b
, 0≤a,b≤1000
. Оператор может быть plus, minus, multiply, divide.
Формат вывода:
Строка, содержащая целое число −
результат вычисления.'''
def calculator(a, operator, b):
if a>0 and b<1000:
if operator == 'plus':
return round(a+b)
if operator == 'minus':
return round(a-b)
if operator == 'multiply':
return round(a*b)
if operator == 'divide':
return a//b
else:
print('Ошибка')
print(calculator())
|
317e28fa9371e54c3b3224f184d44b621fdb253e | ShaoChenHeng/learnpython | /array/array_test.py | 1,948 | 3.578125 | 4 | import array
#初始化一个数祖
#array.array(typecode,[initializer])
# --typecode:元素类型代码;
# initializer:初始化器,若数组为空,则省略初始化器
n = 10
a = array.array('i',[0,1,2,3])
b = array.array('i',[0,1,2,3,4])
c = array.array('i',[n])
myList = [5,5,5,6,6,6]
def test_through(arr):
#遍历
for i in arr:
print(i)
def test_typecode():
#输出数组的数据类型
print(a.typecode)
def test_len():
#输出数组长度 len(a)
print(a.itemsize)
def test_append():
#添加新值到末尾
a.append(5)
print(a)
def test_append2():
#给数组赋值
for i in range(0,10):
c.append(i)
def test_count():
#array.count(x) -- 对象方法 获取元素x在数组中出现的次数
print(a.count(4))
def test_merge(_arr,_list):
#将_list合并到arr1末尾
_arr.fromlist(_list)
def others(arr):
#array.index(x) --对象方法:返回数组中x的最小下标
print('\n返回数组中1的最小下标:')
print(arr.index(1))
#array.insert(1) --对象方法:在下表i(负值表示倒数)之前插入值x
print('\n在下表1(负值表示倒数)之前插入值0:')
arr.insert(1,0)
print(arr)
#array.pop(i) --对象方法:删除索引为i的项,并返回它
print('\n删除索引为4的项,并返回它:')
print(arr.pop(4))
print(arr)
#array.remove(x) --对象方法:删除第一次出现的元素x
print('\n删除第一次出现的元素5:')
arr.remove(5)
print(arr)
#array.reverse() --对象方法:反转数组中的元素值
print('\n将数组arr中元素的顺序反转:')
arr.reverse()
print(arr)
#array.tolist():将数组转换为具有相同元素的列表(list)
print('\n将数组arr转换为已给具有相同元素的列表:')
li = arr.tolist()
print(li)
|
7d8574643fb59d2ad32afe9ff15c59a8c50a2b34 | Pablomos2501/ejercios_logica | /años.py | 1,724 | 3.703125 | 4 | from tkinter import *
from tkinter import messagebox
def comparar():
diferencia = fecha1.get() - fecha2.get()
if diferencia == 1:
messagebox.showinfo("",f"Desde el año {fecha2.get()} ha pasado 1 año.")
elif diferencia > 1:
messagebox.showinfo("",f"Desde el año {fecha2.get()} han pasado {fecha1.get()-fecha2.get()} años.")
elif diferencia == -1:
messagebox.showinfo("",f"Para llegar al año {fecha2.get()} falta 1 año.")
elif diferencia < -1:
messagebox.showinfo("",f"Para llegar al año {fecha2.get()} faltan {fecha2.get()-fecha1.get()} años.")
else:
messagebox.showinfo("",f"¡Son el mismo año!")
interfaz=Tk()
interfaz.geometry("500x300+100+100")
interfaz.title("Años")
lbltitulo=Label(text="cuantos años faltan").pack()
valor1=Label(text="ingresa el año actual").place(x=10,y=40)
fecha1=IntVar()
ingreso=Entry(interfaz,textvariable=fecha1).place(x=150,y=45)
valor2=Label(text="ingresa un año cualquiera").place(x=10,y=70)
fecha2=IntVar()
ingreso=Entry(interfaz,textvariable=fecha2).place(x=150,y=78)
respuesta=Button(interfaz,text="comparar", command=comparar).place(x=10,y=90)
interfaz.mainloop()
"""
fecha_1 = int(input("¿En qué año estamos?: "))
fecha_2 = int(input("Escriba un año cualquiera: "))
diferencia = fecha_1 - fecha_2
if diferencia == 1:
print(f"Desde el año {fecha_2} ha pasado 1 año.")
elif diferencia > 1:
print(f"Desde el año {fecha_2} han pasado {diferencia} años.")
elif diferencia == -1:
print(f"Para llegar al año {fecha_2} falta 1 año.")
elif diferencia < -1:
print(f"Para llegar al año {fecha_2} faltan {-diferencia} años.")
else:
print("¡Son el mismo año!")
""" |
0844a36e70c3e3672d577dfcf10532c342336e61 | SorawatSiangpipop/Python | /condition2.py | 804 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 13:44:36 2019
@author: ssiangpipop
"""
def ticket(age):
if age <= 5:
return 0
else:
return 100
def ticket2(age):
if age <= 5 or age>=60:
return 0
else:
return 100
def ticket3(age, is_local):
if (age <= 5 or age>=60) and is_local:
return 0
else:
return 100
def ticket2a(age):
return 0 if age <= 5 or age>=60 else 100 #ternary
def demo(a):
if a >= 10 and a<= 20:
print("ok")
else:
print("not ok")
def demo2(a):
if 10 <= a <= 20:
print("ok")
else:
print("not ok")
demo2(15)
print(ticket(4))
print(ticket2(70))
print(ticket2(35))
print(ticket2(3))
print(ticket3(3, False))
print(ticket2a(3)) |
0e16b9ba6570f7cb2f8bb55eaedf59a04eb43b57 | dutchakam/rock_paper_scissors | /rock_paper_scissors.py | 1,750 | 4.09375 | 4 | # @Time : 2021/03/29
# @Author : alexanderdutchak@gmail.com
# @Software: PyCharm
import random
import time
print('Welcome to Rock, Paper, Scissors!!\n')
time.sleep(1)
print('Make your choice!!\n')
time.sleep(1)
plays = ['Rock', 'Paper', 'Scissors']
player_score = 0
pc_score = 0
total_games = 0
while total_games < 9:
pc_play = random.choice(plays)
play = input('Rock, Paper, Scissors or Quit: ')
time.sleep(1)
if play == pc_play:
print(f'Draw! {play}\n')
elif play == 'Rock':
if pc_play == 'Paper':
print(f'PC Wins! Paper beats Rock\n')
pc_score += 1
total_games += 1
else:
print('Player Wins! Rock beats Scissors\n')
player_score += 1
total_games += 1
elif play == 'Paper':
if pc_play == 'Scissors':
print('PC Wins! Scissors beats Paper\n')
pc_score += 1
total_games += 1
else:
print('Player Wins! Paper beats Rock\n')
player_score += 1
total_games += 1
elif play == 'Scissors':
if pc_play == 'Rock':
print('PC Wins! Rock beats Scissors\n')
pc_score += 1
total_games += 1
else:
print('Player Wins! Scissors beats Paper\n')
player_score += 1
total_games += 1
elif play == 'Quit':
print('You Quit\n')
break
else:
print('Invalid Play\n')
pass
print(f'Player Score: {player_score}, PC Score: {pc_score}\n')
time.sleep(1)
print(f'Final Score --> Player: {player_score}, PC: {pc_score}\n')
time.sleep(1)
if player_score > pc_score:
print('Player wins the game!!!')
else:
print('PC wins the game!!!')
|
01e2778c876b720ab89c5b167ce3f646daabd4a2 | neodark/Hactoberfest-Special | /Python/network_hostname_ip.py | 264 | 3.796875 | 4 | # Identify your computer hostname and ip address on the local network
import socket
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
print("********************")
print("Hostname: " + hostname)
print("IP: " + ip)
print("********************")
|
c2cfe5630d22a80ae6c60fb47b747f7a43aade28 | tiesu/python_practice | /quiz01.py | 262 | 3.84375 | 4 | #words = "Connect Foundation"
#
#if 'F' in words:
# words.lower()
# words_change = words.replace(' ', '&')
#else:
# print(words)
#
#print(words_change)
words = ['Hello', 'World']
print(words)
words.append(['Connect', 'Foundation', 'Education'])
print(words)
|
4f2897ddac5f1d0e2091c7078ad2bb686a1f939b | Jaysparkexel/Array-1 | /Problem2.py | 2,929 | 3.578125 | 4 | # Time Complexity : O(MN)
# Space Complexity : O(MN)
# Did this code successfully run on Leetcode : Yes
# Three line explanation of solution in plain english:
# - Start with row zero and column zero and keep variable rowchanges and columns changes that occures everytime in the loop.
# - Check for all 4 cases when 1) row is at -1 2) row is at length of row 3) col is at -1 2) col is at length of col
# - Run the while loop till row and col reach their respective length and after exit append last element.
# Your code here along with comments explaining your approach
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
# Taking length of row and if it is zero return empty array
maxrow = len(matrix)
if maxrow == 0:
return []
# Taking length of column and if it is zero return empty array
maxcol = len(matrix[0])
if maxcol == 0:
return []
# start with row 0 and colum 0
row, col = 0, 0
# First we want to move up diagonaly so initialize row and column changes to reflect that
rowchange, colchange = -1, 1
# initilizing answer array
ans = []
# running the loop till we reach at the last element of last row.
while(row != maxrow-1 or col != maxcol-1):
# Handling the case when col crosses upper bound
if(col == maxcol):
# reducing the column and incresing row by 2
row += 2
col -= 1
# Flipping the changes.
rowchange = 1
colchange = -1
continue
# Handling the case when row crosses lower bound
if (row == -1):
# Just needs to incraese the row
row += 1
# Flipping the changes.
rowchange = 1
colchange = -1
continue
# Handling the case when row crosses upper bound
if(row == maxrow):
# reducing the row and incresing column by 2
col += 2
row -= 1
# Flipping the changes.
rowchange = -1
colchange = 1
continue
# Handling the case when column crosses lower bound
if (col == -1):
# Just needs to incraese the column
col += 1
# Flipping the changes.
rowchange = -1
colchange = 1
continue
# Appending element to the array
ans.append(matrix[row][col])
# Updating row and column
row += rowchange
col += colchange
# Appending last element to the array
ans.append(matrix[maxrow-1][maxcol-1])
return ans
|
8df654ae5d9c2ead52f723c0b893a12e54eb9bdb | heitorchang/learn-code | /battles/challenges/latticePoints.py | 14,226 | 4.0625 | 4 | '''
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None):
r"""
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
the prime factors of ``n`` as keys and their respective multiplicities
as values. For example:
>>> from sympy.ntheory import factorint
>>> factorint(2000) # 2000 = (2**4) * (5**3)
{2: 4, 5: 3}
>>> factorint(65537) # This number is prime
{65537: 1}
For input less than 2, factorint behaves as follows:
- ``factorint(1)`` returns the empty factorization, ``{}``
- ``factorint(0)`` returns ``{0:1}``
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
Partial Factorization:
If ``limit`` (> 3) is specified, the search is stopped after performing
trial division up to (and including) the limit (or taking a
corresponding number of rho/p-1 steps). This is useful if one has
a large number and only is interested in finding small factors (if
any). Note that setting a limit does not prevent larger factors
from being found early; it simply means that the largest factor may
be composite. Since checking for perfect power is relatively cheap, it is
done regardless of the limit setting.
This number, for example, has two small factors and a huge
semi-prime factor that cannot be reduced easily:
>>> from sympy.ntheory import isprime
>>> from sympy.core.compatibility import long
>>> a = 1407633717262338957430697921446883
>>> f = factorint(a, limit=10000)
>>> f == {991: 1, long(202916782076162456022877024859): 1, 7: 1}
True
>>> isprime(max(f))
False
This number has a small factor and a residual perfect power whose
base is greater than the limit:
>>> factorint(3*101**7, limit=5)
{3: 1, 101: 7}
Visual Factorization:
If ``visual`` is set to ``True``, then it will return a visual
factorization of the integer. For example:
>>> from sympy import pprint
>>> pprint(factorint(4200, visual=True))
3 1 2 1
2 *3 *5 *7
Note that this is achieved by using the evaluate=False flag in Mul
and Pow. If you do other manipulations with an expression where
evaluate=False, it may evaluate. Therefore, you should use the
visual option only for visualization, and use the normal dictionary
returned by visual=False if you want to perform operations on the
factors.
You can easily switch between the two forms by sending them back to
factorint:
>>> from sympy import Mul, Pow
>>> regular = factorint(1764); regular
{2: 2, 3: 2, 7: 2}
>>> pprint(factorint(regular))
2 2 2
2 *3 *7
>>> visual = factorint(1764, visual=True); pprint(visual)
2 2 2
2 *3 *7
>>> print(factorint(visual))
{2: 2, 3: 2, 7: 2}
If you want to send a number to be factored in a partially factored form
you can do so with a dictionary or unevaluated expression:
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
{2: 10, 3: 3}
>>> factorint(Mul(4, 12, evaluate=False))
{2: 4, 3: 1}
The table of the output logic is:
====== ====== ======= =======
Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict mul dict mul
n mul dict dict
mul mul dict dict
====== ====== ======= =======
Notes
=====
Algorithm:
The function switches between multiple algorithms. Trial division
quickly finds small factors (of the order 1-5 digits), and finds
all large factors if given enough time. The Pollard rho and p-1
algorithms are used to find large factors ahead of time; they
will often find factors of the order of 10 digits within a few
seconds:
>>> factors = factorint(12345678910111213141516)
>>> for base, exp in sorted(factors.items()):
... print('%s %s' % (base, exp))
...
2 2
2507191691 1
1231026625769 1
Any of these methods can optionally be disabled with the following
boolean parameters:
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
``factorint`` also periodically checks if the remaining part is
a prime number or a perfect power, and in those cases stops.
If ``verbose`` is set to ``True``, detailed progress is printed.
See Also
========
smoothness, smoothness_p, divisors
"""
factordict = {}
if visual and not isinstance(n, Mul) and not isinstance(n, dict):
factordict = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False)
elif isinstance(n, Mul):
factordict = dict([(int(k), int(v)) for k, v in
list(n.as_powers_dict().items())])
elif isinstance(n, dict):
factordict = n
if factordict and (isinstance(n, Mul) or isinstance(n, dict)):
# check it
for k in list(factordict.keys()):
if isprime(k):
continue
e = factordict.pop(k)
d = factorint(k, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
for k, v in d.items():
if k in factordict:
factordict[k] += v*e
else:
factordict[k] = v*e
if visual or (type(n) is dict and
visual is not True and
visual is not False):
if factordict == {}:
return S.One
if -1 in factordict:
factordict.pop(-1)
args = [S.NegativeOne]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(factordict.items())])
return Mul(*args, evaluate=False)
elif isinstance(n, dict) or isinstance(n, Mul):
return factordict
assert use_trial or use_rho or use_pm1
n = as_int(n)
if limit:
limit = int(limit)
# special cases
if n < 0:
factors = factorint(
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
factors[-1] = 1
return factors
if limit and limit < 2:
if n == 1:
return {}
return {n: 1}
elif n < 10:
# doing this we are assured of getting a limit > 2
# when we have to compute it later
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
factors = {}
# do simplistic factorization
if verbose:
sn = str(n)
if len(sn) > 50:
print('Factoring %s' % sn[:5] + \
'..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
else:
print('Factoring', n)
if use_trial:
# this is the preliminary factorization for small factors
small = 2**15
fail_max = 600
small = min(small, limit or small)
if verbose:
print(trial_int_msg % (2, small, fail_max))
n, next_p = _factorint_small(factors, n, small, fail_max)
else:
next_p = 2
if factors and verbose:
for k in sorted(factors):
print(factor_msg % (k, factors[k]))
if next_p == 0:
if n > 1:
factors[int(n)] = 1
if verbose:
print(complete_msg)
return factors
# continue with more advanced factorization methods
# first check if the simplistic run didn't finish
# because of the limit and check for a perfect
# power before exiting
try:
if limit and next_p > limit:
if verbose:
print('Exceeded limit:', limit)
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
if n > 1:
factors[int(n)] = 1
return factors
else:
# Before quitting (or continuing on)...
# ...do a Fermat test since it's so easy and we need the
# square root anyway. Finding 2 factors is easy if they are
# "close enough." This is the big root equivalent of dividing by
# 2, 3, 5.
sqrt_n = integer_nthroot(n, 2)[0]
a = sqrt_n + 1
a2 = a**2
b2 = a2 - n
for i in range(3):
b, fermat = integer_nthroot(b2, 2)
if fermat:
break
b2 += 2*a + 1 # equiv to (a+1)**2 - n
a += 1
if fermat:
if verbose:
print(fermat_msg)
if limit:
limit -= 1
for r in [a - b, a + b]:
facs = factorint(r, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose)
factors.update(facs)
raise StopIteration
# ...see if factorization can be terminated
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
# these are the limits for trial division which will
# be attempted in parallel with pollard methods
low, high = next_p, 2*next_p
limit = limit or sqrt_n
# add 1 to make sure limit is reached in primerange calls
limit += 1
while 1:
try:
high_ = high
if limit < high_:
high_ = limit
# Trial division
if use_trial:
if verbose:
print(trial_msg % (low, high_))
ps = sieve.primerange(low, high_)
n, found_trial = _trial(factors, n, ps, verbose)
if found_trial:
_check_termination(factors, n, limit, use_trial, use_rho,
use_pm1, verbose)
else:
found_trial = False
if high > limit:
if verbose:
print('Exceeded limit:', limit)
if n > 1:
factors[int(n)] = 1
raise StopIteration
# Only used advanced methods when no small factors were found
if not found_trial:
if (use_pm1 or use_rho):
high_root = max(int(math.log(high_**0.7)), low, 3)
# Pollard p-1
if use_pm1:
if verbose:
print(pm1_msg % (high_root, high_))
c = pollard_pm1(n, B=high_root, seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
# Pollard rho
if use_rho:
max_steps = high_root
if verbose:
print(rho_msg % (1, max_steps, high_))
c = pollard_rho(n, retries=1, max_steps=max_steps,
seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
low, high = high, high*2
"""
'''
"""
from sympy import factorint
def latticePointsOnCircle(n):
r = 1
for p, e in factorint(n).items():
if p%4 == 1: r *= 2*e + 1
return 4*r if n > 0 else 0
"""
from collections import defaultdict
def primes(size):
sieve = [0] * (size+1)
for i in range(2, int(size ** 0.5) + 1): # remember + 1
if not sieve[i]:
for j in range(i * 2, size+1, i):
sieve[j] = 1
primes = []
for i in range(2, size+1):
if not sieve[i]:
primes.append(i)
return primes
def factorint(n):
p = primes(n)
ans = defaultdict(int)
while n > 1:
for pp in p:
found = False
if pp > n:
break
if n % pp == 0:
ans[pp] += 1
n //= pp
break
return ans
|
14fe7fd000dba0b0b85b7f1886594e382d252eb5 | zubroide/turfik | /turfik/centroid.py | 555 | 3.5625 | 4 | from .helpers import point
def centroid(geojson, options: dict = None):
"""
Takes one or more features and calculates the centroid using the mean of all vertices.
This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons
"""
if options is None:
options = {}
x_sum = 0
y_sum = 0
length = 0
for coord in geojson:
x_sum += coord[0]
y_sum += coord[1]
length += 1
return point([x_sum / length, y_sum / length], options.get('properties'))
|
234d7768f12fc0f164f3177897614c853060a49c | Sid1298/ADA | /fibonacci-non-recursive.py | 147 | 3.75 | 4 | def fibonacci(n):
arr = [0, 1]
for i in range(1, n+1):
arr.append(arr[i] + arr[i-1])
return arr
print(fibonacci(75))
|
5facf21ba6890bcef402188803e056ef9e232ec6 | DaryaFotina/Python | /4.py | 376 | 3.828125 | 4 | print("Кто он?")#пользователь вводит профессию
a=input()
print("Кто он?")#пользователь вводит профессию
b=input()
print("Кто он?")#пользователь вводит профессию
c=input()
print("Введите способ разделения")
d=input()
print("Он-",a,d,b,d,c, sep=" ") |
c6633eff331dab05ebd56edeaa4be8a9c639156c | eurosa/DigilineSystem-new | /buttonAdd/bitpositon.py | 1,168 | 4.4375 | 4 |
# Python 3 program to find position
# of only set bit in a given number
# A utility function to check whether
# n is power of 2 or not
def isPowerOfTwo(n) :
return (n and ( not (n & (n-1))))
# Returns position of the only set bit in 'n'
def findPosition(n) :
if not isPowerOfTwo(n) :
return -1
count = 0
# One by one move the only set bit to
# right till it reaches end
while (n) :
n = n >> 1
# increment count of shifts
count += 1
return count
# Driver program to test above function
if __name__ == "__main__" :
n = 0
pos = findPosition(n)
if pos == -1 :
print("n =", n, "Invalid number")
else :
print("n =", n, "Position", pos)
n = 12
pos = findPosition(n)
if pos == -1 :
print("n =", n, "Invalid number")
else :
print("n =", n, "Position", pos)
n = 128
pos = findPosition(n)
if pos == -1 :
print("n =", n, "Invalid number")
else :
print("n =", n, "Position", pos)
# This code is contributed by ANKITRAI1
|
1b751581982b715e07a247ae73555e525cbc4ad5 | tomboxfan/PythonExample | /exercise/python_1032_local_variable_override_global_variable.py | 1,180 | 4.6875 | 5 |
# I define a global variable str_a
str_a = 'Hello Python!' # scope: global
# I define a method with a parameter named str_a
# IMPORTANT!!! All parameters are local variables with the method scope.
def print_msg1(str_a):
# Python sees you are using variable str_a
# Firstly, Python tries to see whether str_as has been defined inside the current scope - print_msg1(str_a)
# Find it!
print(f'I am using a local variable "str_a": {str_a}')
print_msg1("Good Day!")
def print_msg2():
str_a = "Hello Singapore!"
# Python sees you are using variable str_a
# Firstly, Python tries to see whether str_a has been defined inside the current scope - print_msg2()
# Find it!
print(f'I am using a local variable "str_a": {str_a}')
print_msg2()
def print_msg3():
# Python sees you are using variable str_a
# Firstly, Python tries to see whether str_a has been defined inside the current scope - print_msg3()
# Nope!
# Secondly, Python tries to see whether str_a has been defined globally?
# Find it!
print(f'I am using a global variable "str_a": {str_a}')
print_msg3()
# GLobal variable is visible everywhere.
print(str_a) |
cdee5e35cd5a89d12b1116dd2e522adb6e7d1a72 | hudefeng719/uband-python-s1 | /homeworks/A16202/final_homework/homework1.py | 3,806 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# 任务一:词汇出现频率统计分析
# 数一数文本中各个词汇出现的次数,输出词汇的出现频率
# 1. 先用 data1/dt01.txt 的文档数据,大概200个单词,实现单词读取的类 WordReader
# 这个类的功能有几个
# 1)从一个路径里读取txt文件
# 2)把txt的文件分割成一个个单词
# 3) 对单词进行统计计数
# 4)排序
# 3)输出csv
# 2. 扩展项目,使用 data2 种的所有文件,进行第 1 步的操作,并输出成为 csv 文件
# 一般的话,我们输出成一个csv文件,方便我们能够查看到各个文件的出现次数
import codecs
import os
import csv
# 1 读取文件—————————————————————————————————————————————————
# 1.1 以“-”分割单词
def word_split(words):
new_list = []
for word in words:
if '-' not in word:
new_list.append(word)
else:
lst = word.split('-')
new_list.extend(lst)
return new_list
# 1.2 读取单个文件
def read_file(file_path):
f = codecs.open(file_path,'r',"utf-8")
lines = f.readlines()
word_list = []
for line in lines:
line = line.strip()
words = line.split(" ")
words = word_split(words)
word_list.extend(words)
return word_list
# 1.3 读取多文件里的单词
def read_files(file_paths):
final_words = []
for path in file_paths:
final_words.extend(read_file(path))
return final_words
# 1.4 读取文件夹中的文件路径
def get_file_from_folder(folder_path):
file_paths = []
for root,dirs,files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root,file)
file_paths.append(file_path)
return file_paths
# 2 格式化单词——————————————————————————————————————————————————
def format_word(word):
# word = word.lower()
fmt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'
for char in word:
if char not in fmt:
word = word.replace(char,'')
return word.lower()
def format_words(words):
word_list = []
for word in words:
wd = format_word(word)
if wd:
word_list.append(format_word(word))
return word_list
# 3 统计单词数目———————————————————————————————————————————————————————
def statistics_words(words):
s_word_dict = {}
for word in words:
if s_word_dict.has_key(word):
s_word_dict[word] = s_word_dict[word] + 1
else:
s_word_dict[word] = 1
# 按照单词出现的次数从多到少排列,出现次数相同的单词按照字母顺序排
sorted_word_list = sorted(s_word_dict.items(),key=lambda kv:(-kv[1],kv[0]))
return sorted_word_list
# 4 list输出到csv————————————————————————————————————————————————————————
def printlist_to_csv(fileName="", dataList=[]):
with open(fileName, "wb") as csvFile:
csvWriter = csv.writer(csvFile)
csvWriter.writerow(['单词','词频'])
for data in dataList:
csvWriter.writerow(data)
csvFile.close
# main————————————————————————————————————————————————————
def main():
words = read_files(get_file_from_folder('data2'))
print '获取了未格式化的单词 %d 个' %(len(words))
f_words = format_words(words)
print '获取了已格式化的单词 %d 个' %(len(f_words))
word_dic = statistics_words(f_words)
printlist_to_csv("output/test.csv", word_dic)
if __name__ == "__main__":
main()
|
5e67419cfd2cb9c92687013dbda15e365fe04186 | j3nnn1/pyj3nnn1 | /tarea02/exercise02.py | 1,160 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# j3nnn1
"""
2- Crear la clase Vehiculo con los metodos encender, apagar, acelerar y frenar. La clase debe ser lo suficientemente inteligente para que sepa que no puede:
- Apagar sin estar encendido
- Frenar sin estar acelerando
- Encender sin estar apagado
- Acelerar si no esta detenido
"""
class vehiculo:
def __init__(self):
self.encendido =0
self.detenido =1
def encender(self):
if self.encendido:
print 'No se puede encender, ups Vehículo ya está encendido'
else:
self.encendido =1
def apagar(self):
if self.encendido==0:
print 'No se puede apagar, ups Vehículo ya esta apagado!!'
else:
self.encendido=0
def acelerar(self):
if self.detenido==0 or self.encendido==0:
print 'No se puede acelerar, ups Vehículo ya esta acelerando o esta apagado'
else:
self.detenido=0
def frenar(self):
if self.detenido or self.encendido==0:
print 'No se puede frenar, wow Vehículo esta detenido!'
else:
self.detenido=1
|
9b8437075363b1573d2cf326351e9766ce26f140 | TaumarT/python | /DecimoTerceiro_exercicio.py | 211 | 3.765625 | 4 | print("calculo de peso")
sexo = input("")
altura = float(input("digite sua altura: "))
peso_ideal = (72.7*altura)-58
peso_ideal < 76.300
print("acima do peso")
print("Seu peso é: {:05.3f}".format(peso_ideal)) |
1656e2f974381266e000b9d2af5aab5de7d6b3ee | Bondarev2020/infa_2019_Bondarev2020 | /Kontr2_9.py | 665 | 3.578125 | 4 | c = int(input())
A=[]*c
B=[]*2*c
for i in range (c):
A.append(input().split(' '))
for i in range (c):
A[i][0] = float(A[i][0])
A[i][1] = float(A[i][1])
def insert_sort(A):
N = len(A)
for top in range(1, N):
k = top
while k > 0 and A[k-1][1] > A[k][1]:
A[k], A[k-1] = A[k-1], A[k]
k -= 1
insert_sort(A)
for i in range (1, c):
if A[i - 1][1] == A[i][1]:
if A[i - 1][0] < A[i][0]:
A[i], A[i - 1] = A[i - 1], A[i]
for i in range (c):
print("{:.2f}".format(A[i][0]), "{:.3f}".format(A[i][1]), end='\n')
|
8349855685db97bc90e58bd9baf3028c1f182f2a | vipmunot/HackerRank | /Data Structures/Linked Lists/Insert a node at a specific position in a linked list.py | 645 | 3.984375 | 4 | """
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
#This is a "method-only" submission.
#You only need to complete this method.
def InsertNth(head, data, position):
start = head
if position == 0:
return Node(data, head)
while position > 1:
head = head.next
position -= 1
head.next = Node(data, head.next)
return start
|
b219bd2cce6ed53e9503334cebcb2edc174b50a7 | TaimurGhani/School | /CS1134/Homework/hw02/tg1632_hw2_q5.py | 499 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tg1632_hw2_q5.py
Taimur Ghani
29 September 2017
This program puts all of the odd
numbers at the front of a given list
and puts all of the even numbers in
the back.
"""
def split_parity(lst):
ind = 0
for i in range(len(lst)):
if (lst[i] % 2 == 1):
lst[ind], lst[i] = lst[i], lst[ind]
ind += 1
return lst
def main():
test = [1, 2, 3, 4]
print (split_parity(test))
main()
|
07c3ba7805185dcb407307f2b6f4b69432755036 | HenriFeinaj/Simple_Python_Programs | /Odd_Even_Using_Functions.py | 201 | 4.28125 | 4 | def odd_even():
number = int(input("Enter number: "))
if (number % 2) == 0:
return number, "is an even! "
else:
return number, "is an odd! "
print (odd_even())
|
9bfce4bebaac1e43b5c3bcd48cfd285b54359027 | joshmosby/screendisplay | /csvparse.py | 749 | 3.59375 | 4 | import csv
import time
names = []
year = []
def current_date():
day = int(time.strftime("%d"))
month = int(time.strftime("%m"))
year = int(time.strftime("%Y"))
date = [day, month, year]
return date
def find_anniversary():
with open('AnniversaryData.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
for row in readCSV:
doh = row[2]
doh = doh.split("-")
for i in doh:
try:
i = int(i)
except ValueError:
if i == 'DOH':
break
print (i)
'''print (doh)'''
def returnppl():
|
a8a0e3bb4932a43452cb8a27ccba70698639dba6 | Piumika9631/L4-Module1 | /envelop_recogniser/remove_background/roi_extraction.py | 1,344 | 3.796875 | 4 | import cv2
def get_largest_element(original_image):
image_copy = original_image.copy()
image_draw_copy = original_image.copy()
gray = cv2.cvtColor(image_copy, cv2.COLOR_BGR2GRAY)
# Blurring to reduce high frequency noise to make our contour detection process more accurate
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# cv2.imshow('blur', blurred)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Not necessary to draw, only for visualizing purpose
cv2.drawContours(image_draw_copy, contours, -1, (0, 0, 255), 3)
contours_list = []
for i in contours:
area = cv2.contourArea(i)
my_object = {'contour': i, 'area': area}
# print('AREA: ' + str(area))
contours_list.append(my_object)
max_area = 0
max_obj = contours_list[0]
for obj in contours_list:
if obj['area'] > max_area:
max_area = obj['area']
max_obj = obj
# print('MAX AREA: ' + str(max_area))
# cv2.drawContours(image_draw_copy, max_obj['contour'], -1, (0, 0, 255), 2)
# visualize the largest area using red color contour
# 'envelop' label is use to only visualizing purposes
max_obj['envelop'] = image_draw_copy
return max_obj
|
3f8d51638354557bf912a88d56e3485a34535de2 | CalumDoughtyYear3/Functions | /strings5.py | 263 | 4.09375 | 4 | import string
fruit = "banana"
index = str.find(fruit, "a")
print(index)
print(str.find("banana", "na"))
print(str.find("banana", "na", 3))
print(str.find("bob", "b", 1, 2)) #when -1 is returned it means that nothing was found
print(str.find("bbo", "b", 1, -1)) |
7500c78f05411c7da8c0fa86ed2f0945306c7fb8 | osmarsalesjr/AtividadesProfFabioGomesEmPython3 | /Atividades6/At6Q5.py | 612 | 3.859375 | 4 |
def main():
data = input("Digite uma da e veja o mes por extenso: DD MM AAAA (Somente numeros)--> ")
mes = data[3 : 5]
if int(mes) >= 1 and int(mes) <= 12:
data = data[0 : 3] + escreva_data(mes) + data[5 : len(data)]
print(data)
else:
print("Mes esta incorreto.")
def escreva_data(mes):
meses = ["Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"]
for i in range(len(meses)):
if int(mes) == i + 1:
return meses[i]
if __name__ == '__main__':
main() |
eda0a5562fdbae86543aead72d5152667993dcf5 | kabir-gujral/lucky-seven-with-betting | /test2.py | 3,629 | 4.0625 | 4 | #betting feature, ask player how much to bet, min bet 50,purse 500 and whenever game ends i need to specify how much money left
from random import shuffle
yourvalue=None
outputDice1=None
outputDice2=None
totalmoney=500
bet=None
winnings=None
lose=None
addmore=None
extra=None
totalloss=None
wins=0
loses=0
dice1=[1,2,3,4,5,6]
dice2=[1,2,3,4,5,6]
def betting():
global totalmoney,bet,addmore,extra
bet=int(input("enter the amount you want to bet : "))
def add():
global totalmoney,addmore
addmore=int(input("enter the amount you wanna add more : "))
if addmore > 500:
print('enter a value less than 500')
add()
totalmoney=totalmoney+addmore
def takeInput():
global yourvalue
yourvalue=input("enter above 7, below 7 or equal to 7 : ")
def diceRoll1():
shuffle(dice1)
outputDice1=dice1[0]
return outputDice1
def diceroll2():
global dice2,outputDice2
shuffle(dice2)
outputDice2=dice2[0]
return outputDice2
def checkWin():
a=diceRoll1()
b=diceroll2()
global winnings,lose,totalmoney,totalloss,wins,loses
if a+b > 7 and yourvalue=="above 7":
print(f"you won you number was :{a+b}")
wins+=1
winnings=totalmoney+bet
totalmoney=totalmoney+bet
if totalmoney==0:
print("game ended add more money to play ")
add()
print(f"you won :{bet} money left:{winnings} wins :{wins} loses :{loses}")
elif a+b < 7 and yourvalue=="below 7":
print(f"you won you number was :{a+b}")
wins+=1
winnings=totalmoney+bet
totalmoney=totalmoney+bet
if totalmoney==0:
print("game ended add more money to play ")
add()
print(f"you won :{bet} money left:{winnings} wins :{wins} loses :{loses}")
elif a+b==7 and yourvalue=="equal":
print(f"you won you number was :{a+b}")
wins+=1
winnings=totalmoney+bet
totalmoney=totalmoney+bet
if totalmoney==0:
add()
print(f"you won :{bet} money left:{winnings} wins :{wins} loses :{loses}")
else:
print(f"you lost you number was :{a+b}")
loses+=1
totalloss=totalmoney-bet
totalmoney=totalmoney-bet
if totalmoney==0:
print("game ended add more money to play ") # how to end the gamne now
add()
print(f"you lost :{bet} money left:{totalloss} wins :{wins} loses :{loses}")
while True:
while True:
takeInput()
betting()
if bet <= 50:
print("enter a vlaid bet ")
break
if bet ==0:
print("enter a valid bet ")
break
if bet > totalmoney:
print("you cant bet more than what you have ")
break
checkWin()
break
playAgain=input("do you want to play again : ")
if playAgain=="yes":
pass
else:
break
print("game ended")
|
adae210a303d58160eee0c20cf8b83486e9f6f0e | cikent/Portfolio | /CodeSamples-Python/LPTHW-PythonCourse-ex11-AskingQuestions-StoringUserInput.py | 786 | 4.09375 | 4 | # print to screen a question for Age
print("How old are you?", end=' ')
# Save input as variable
age = int(input())
print(">>>> age=", repr(age))
# print to scren a question for Height
print("How tall are you?", end=' ')
# Save input as variable
height = input()
# print to screen a question for Weight
print("How much do you weigh?", end=' ')
# Save input as variable
weight = input()
# print to screen the values saved in each variable from input
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
'''
print("Ready for another question?", end=' ')
proceed = input()
if proceed = "no"
exit()
else
print("What is your favorite Activity?", end=' ')
activity = input()
print(f"So you really like to {activity}, that's awesome!")
''' |
585ae3439d5ac0f381329f4166084ae9983bf071 | maverick-zhang/Algorithms-Leetcode | /leetcode_day12/Q144_preorder.py | 494 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def traverse(self, node, record):
if node is None:
return
record.append(node.val)
self.traverse(node.left, record)
self.traverse(node.right, record)
def preorderTraversal(self, root: TreeNode) -> list:
res = []
self.traverse(root, res)
return res
|
34c0b533f75ffe870a7419818e15a2ba10e6f720 | ivo172/Python_academy_Brno_2020 | /39_Find.py | 268 | 3.734375 | 4 | def my_find(sequence, object):
for index, element in enumerate(sequence):
if element == object:
return (index)
else:
continue
return ('-1')
print(my_find(['pear', 'apple', (23, 45), 653, {'name': 'John'}], ('apple')))
|
8ecc8a5055cb35ce7ea6dc6070b5f80ea4d0c938 | daniel-reich/ubiquitous-fiesta | /AeWbFdxSwAf5nhQpG_15.py | 205 | 3.609375 | 4 |
def persistence(num):
counter = 0
str_num = str(num)
while len(str_num) > 1:
prod = 1
for d in str_num:
prod *= int(d)
str_num = str(prod)
counter += 1
return counter
|
22c8873419235b7d20362cb833934226573449c2 | anna-zverkova/Rose_scrape | /DA_scrape_onerose_2url_white.py | 2,947 | 3.515625 | 4 | import urllib.request
from bs4 import BeautifulSoup
import requests
import csv
# Creating csv
filename = "DA_white.csv"
with open(filename,'w',newline='',encoding='utf-8') as f:
w = csv.writer(f)
headers = 'Rose_name Category Url Price Colour Family Fragrance_Strength Flowering Notes Color2 Height'
bytes_headers = bytes(headers, 'utf-8')
w.writerow(headers.split())
source = requests.get('https://www.davidaustinroses.co.uk/colour-white-+-cream').text
# Parsing in BeautifulSoup
soup = BeautifulSoup(source, 'lxml')
# Getting first rose
# No iteration just yet. The goal is to check that we are getting data for one item.
rose = soup.find("li", {"class":"item last"})
print(rose.prettify())
rose_item = rose.find("div", {"class":"product-info"}).a
# Getting data for the first rose
try:
name = rose_item.get('title')
except Exception as e:
name = 'None'
try:
url = rose_item.get('href')
except Exception as e:
url = 'None'
try:
category = rose.find("div", {"class":"category"}).text
except Exception as e:
category = 'None'
try:
price = rose.find("div", {"class":"price-box"}).span.text
except Exception as e:
price = 'None'
color = 'white'
# Printing rose data in Terminal
print(name)
print(url)
print(category)
print(price)
print(color)
# Scraping from associated page
linked_page = url
class AppURLopener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
opener = AppURLopener()
response2 = opener.open(linked_page)
page2_soup = BeautifulSoup(response2, 'lxml')
rose2 = page2_soup.find("li", {"class":"characteristics"})
print(rose2.prettify())
# Getting extra data from scraped url and adding it to dictionary
results = {}
for item in rose2.find_all(class_='characteristics-wrapper')[0].find_all("li"):
try:
characteristic = item.h4.text
except Exception as e:
characteristic = 'None'
try:
type = item.p.text
except Exception as e:
type = 'None'
results[characteristic] = type
print('Characteristic : {}'.format(characteristic), 'Type : {}'.format(type))
print(results)
# Printing data to csv file
# Had to change encoding of name as it was not in utf-8
family = results.get('Family:')
print(family)
fragrance = results.get('Fragrance Strength:')
print(fragrance)
flowering = results.get('Flowering:')
print(flowering)
notes = results.get('Fragrance Notes:')
print(notes)
color2 = results.get('Colour:')
print(color2)
height = results.get('Height:')
print(height)
w.writerow([(name.encode('ascii','ignore')).decode('utf-8'),url,category,(price.encode('ascii','ignore')).decode('utf-8'),color,family,fragrance,flowering,notes,color2,height])
|
1056e461534d75599d10892113e50f2f470b6bbe | wkwkgg/atcoder | /abc/problems010/003/b.py | 424 | 3.65625 | 4 | S = input()
T = input()
K = list("atcoder")
ans = True
for s,t in zip(S,T):
if s == t:
continue
else:
if s == "@":
if t not in K:
ans = False
break
elif t == "@":
if s not in K:
ans = False
break
else:
ans = False
break
print("You can win" if ans else "You will lose")
|
a110479f198abaeef6092d743d3ea36b420bf6a1 | findgriffin/euler | /prob003/prob.py | 748 | 4.15625 | 4 | #! /usr/bin/python
""" Find the largest prime factor of NUMBER """
import math
NUMBER = 600851475143
NUMBER = 600851475143
NO_OF_FACTORS = 100000
def p_test(num):
"""A test for primality."""
i = 2
sqrt_num = math.sqrt(num);
# print "about to start while loop half_num=%d \n" % half_num
while i <= sqrt_num:
if p_test(i) and num % i == 0:
return 0
i += 1
return 1
def main(num):
i = 2
while i < num/2:
if i % 10000000 == 0:
print 'looping for %s' % i
if num % i == 0:
if p_test(i) == 1:
print "%d is a prime factor of %d\n" % (i, num)
i += 1
return 0
if __name__ == "__main__":
main(NUMBER)
|
8e58c3297ec0455d2deea03b11454077f1382604 | ProgrammAbelSchool/Programming-Challenges | /_68.py | 204 | 3.625 | 4 | import turtle
import random
window = turtle.Screen()
for line in range(random.randint(10, 20)):
turtle.right(random.randint(0, 360))
turtle.forward(random.randint(1, 100))
turtle.exitonclick()
|
e35b76f9f7980dec84e9e37821eb890f03567d44 | ARN0LD-2019/Ejercicios_Python_2020 | /unidad3/ejercicio5.py | 490 | 4.0625 | 4 | # Realiza un programa que pida al usuario escribir un numero del 0 al 9
# en dado caso de que no lo escriba repetir el ciclo
numeros = [1, 3, 6, 9]
while True:
numero = int(input("digite un numero del 0 al 9: "))
# if numero >= 0 and numero <= 9:
# print("bien hecho")
# break
if numero in numeros:
print("el numero", numero, "se encuentra en la lista", numeros)
else:
print("el numero", numero, "NO se encuentra en la lista", numeros)
break
|
a9cf978c8ce41cfe6f6507b320248387e9dad865 | aatish70468/Python-Programs | /7_12_merge_sort.py | 1,185 | 3.984375 | 4 | def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
print(str(n1) + " " + str(n2))
#create arrays
Left = [0] * (n1)
Right = [0] * (n2)
#copy data to arrays
for i in range(0, n1):
Left[i] = arr[l + i]
print(Left)
for j in range(0, n2):
Right[j] = arr[m + 1 + j]
print(Right)
i = 0 #first half of array
j = 0 #second half of array
k = l #merges two halves
while i<n1 and j<n2:
if Left[i]<=Right[j]:
arr[k] = Left[i]
i += 1
else:
arr[k] = Right[j]
j += 1
k += 1
#copy the left out elements of left half
while i<n1:
arr[k] = Left[i]
i += 1
k += 1
#copy the left out elements of right half
while j<n2:
arr[k] = Right[j]
j += 1
k += 1
print(arr)
def mergeSort(arr, l, r):
if l<r:
#getting the mid value
mid = (l+(r-1))//2
mergeSort(arr, l, mid)
mergeSort(arr, mid+1, r)
merge(arr, l, mid, r)
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
mergeSort(arr, 0, n-1)
print("Sorted Array: ")
for i in range(n):
print(arr[i], end = " ")
|
fe21519bf1f0706c80bb7517204eb13f5baf0a5d | yogeshdewangan/Python-Excersise | /practice.py | 1,054 | 4.03125 | 4 | import sys
# Selection sort
# list = [6, 3, 4, 2, 1, 8, 9]
list = [6, 3, 4, 2, 1, 8, 9]
for i in range(len(list)):
smallest =i
for j in range(i+1, len(list)):
if list[j]< list[smallest]:
smallest =j
list[i], list[smallest]= list[smallest], list[i]
print list
# Insertion sort
"""
list = [7, 6, 5, 4, 3, 2]
for i in range(1, len(list)):
key = list[i]
j = i -1
while j >=0 and key< list[j]:
list[j+1]= list[j]
j -=1
list[j+1] = key
print(list)
"""
# Bubble sort
"""
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
list = [5, 4, 3, 2, 1, -3]
count = 0
for i in range(len(list)):
swapped = False
for j in range(len(list) - i - 1):
if list[j + 1] < list[j]:
list[j + 1], list[j] = list[j], list[j + 1]
swapped = True
count += 1
if not swapped:
break;
count += 1
print list
print count
"""
|
ea06e601ff75c51f183a8e0c6464bd5ae32cbe53 | a100kpm/daily_training | /problem 0158.py | 1,093 | 4.09375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Slack.
You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the bottom right corner?
You can only move right and down. 0 represents an empty space while 1 represents a wall you cannot walk through.
For example, given the following matrix:
[[0, 0, 1],
[0, 0, 1],
[1, 0, 0]]
Return two, as there are only two ways to get to the bottom right:
Right, down, down, right
Down, right, down, right
The top left corner and bottom right corner will always be 0.
'''
import numpy as np
matrice = np.array([[0, 0, 1],
[0, 0, 1],
[1, 0, 0]])
def number_path(matrice,pos=[0,0]):
N,M=np.shape(matrice)
if pos==[N-1,M-1]:
return 1
if matrice[pos[0],pos[1]]==1:
return 0
a=0
b=0
if pos[0]<N-1:
a=number_path(matrice,[pos[0]+1,pos[1]])
if pos[1]<M-1:
b=number_path(matrice,[pos[0],pos[1]+1])
return a+b
|
82ce760d3f28ae73eaea582ce62594e1fdbf589a | jiyglee/Python | /Ch04/p100.py | 752 | 4.09375 | 4 | """
chapter04.lecture.step05_dict.py
"""
# (1) dict 생성 방법 1
dic = dict(key1 = 100, key2 = 200, key3 = 300)
print(dic)
# (2) dict 생성 방법2
person = {'name' : '홍길동', 'age': 35, 'address' : '서울시'}
print(person)
print(person['name'])
print(type(dic), type(person))
# (3) 원소 수정, 삭제, 추가
# dict 원소 수정
person['age'] =45
print(person)
# dict 원소 삭제
del person['address']
print(person)
# dict 원소 추가
person['pay'] = 350
print(person)
# (1) 요소 검사
print(person['age'])
print('age' in person)
# (2) 요소 반복
for key in person.keys() : # key 넘김
print(key)
for v in person.values() : # value 넘김
print(v)
for i in person.items() : # (key, value) 넘김
print(i) |
d204c6d0c9df2012be877a0fa44b57f61f10953f | geoffder/learning | /LP_logistic_regression/l1_regularization.py | 1,074 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
N = 50
D = 50 # extra T H I C C matrix
# np.random.random creates uniform dist from 0 to 1
X = (np.random.random((N, D)) - .5) * 10 # -.5 to centre on zero. Range now -5 to 5
ones = np.ones((N,1))
Xb = np.concatenate((X, ones), axis=1) # add bias column
true_w = np.array([1, .5, -.5] + [0]*(D-2)) # only first three dimensions actually matter, add bias
T = np.round(sigmoid(Xb @ true_w + np.random.randn(N)*.5)) # targets, shaped by true w, plus noise
learning_rate = .0001
l1 = 4 # L1 regularization lambda
w = np.random.randn(D+1) / np.sqrt(D+1) # initialize random weights
def costDeriv(X, T, Y):
return X.T @ (Y - T)
def crossEntropy(Y, T, w):
return -(T * np.log(Y) + (1 - T) * np.log(1 - Y)).mean() + l1*np.abs(w).mean()
costs = []
for i in range(1000):
Y = sigmoid(Xb @ w)
costs.append(crossEntropy(Y, T, w))
w -= learning_rate * (costDeriv(Xb, T, Y) + l1 * np.sign(w))
plt.plot(costs)
plt.show()
plt.plot(true_w)
plt.plot(w)
plt.show()
|
24f250d75a9ef1be2c321dc22765306163e26c21 | tannerb9/petting_zoo | /creatures/cthulhu.py | 514 | 3.609375 | 4 | from datetime import date
from .creature import Creature
from movements.swimming import Swimming
class Cthulhu(Creature, Swimming):
def __init__(self, name, species, food, chip_num, **shift):
Creature.__init__(self, name, species, food, chip_num, **shift)
Swimming.__init__(self)
def feed(self):
print(f"{self.name} tossed their {self.food} into the air for fun before devouring it on {date.today()}.")
def __str__(self):
return f"{self.name}, the {self.species}."
|
fd3fd08164943a607d98ac68947f9f417db080cb | JinnieJJ/leetcode | /97-Interleaving String.py | 620 | 3.53125 | 4 | class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
def dfs(i, j, k):
if (i, j, k) not in memory:
memory[(i, j, k)] = (k >= l3) or \
(i < l1 and s3[k] == s1[i] and dfs(i+1, j, k+1)) or \
(j < l2 and s3[k] == s2[j] and dfs(i, j+1, k+1))
return memory[(i, j, k)]
l1, l2, l3, memory = len(s1), len(s2), len(s3), {}
if l3 != l1 + l2:
return False
return dfs(0, 0, 0)
|
ead9ed18aa07846be86d0429ec74df5b86cede70 | AdrianoKim/ListaDeExerciciosPythonBrasilAdrianoKim | /PythonBrasil/5. Exercicios Strings/4. ex 4.py | 246 | 4.375 | 4 | """ 4. Nome na vertical em escada. Modifique o programa anterior de forma a mostrar
o nome em formato de escada.
F
FU
FUL
FULA
FULAN
FULANO
"""
nome = str.upper(input('Digite um nome: '))
for x in range(0, len(nome) + 1):
print(nome[:x])
|
ffc5d77ca0220d274719b1699c9432fe574e2c2b | shreyagoswami/akashtechnolabs | /new 11.py | 147 | 3.625 | 4 | d = {1: "Shreya", 2: "Goswami", "key" : 15}
print(type(d))
print("d[1] = ", d[1])
print("d[2] = ", d[2])
print("d[key] = ", d["key"])
|
f09c969c500fb264ff0bebe8bc0b3fba4cc394f9 | JimLyCode/python | /python-normal/object-oriented/myfunc.py | 375 | 3.84375 | 4 | """
module: function defined
author: answer
time: 2018-5-28 10:00:23
"""
sum = lambda arg1, args2: arg1 + args2
print(sum(args2=20, arg1=3))
def sub(arg1, arg2):
return arg1 - arg2
print(sub(12, 1))
def printinfo(arg1, *params):
print("arg1:", arg1)
for param in params:
print(param)
return
printinfo(112)
printinfo(12, 13, 14, 15, 16)
|
5491ef56f7c9d9e1801267ad078b51e680a2af19 | saniyaadeel/Convolutional-Neural-Networks | /cnn_using_numpy.py | 2,659 | 4.3125 | 4 |
"""CNN using Numpy
CNN in libraries like keras are very easy to implement. In this notebook, we will implement a convolution layer used in CNN using numpy library.
We will use a numeric example and find out the result with and without padding.
"""
import numpy as np
"""It is known that despite any number of channels, the output of convolution layer is a single channel, until and unless we use multiple number of filter layers to retain the actual channel size.
In this code, we use one filter layer.
Writing the convolution function:
"""
def Conv(InpImg, Fltr):
m = InpImg.shape[1] # rows of input
l = InpImg.shape[2] # columns of input
d = InpImg.shape[0] # channels of input and channels of filter
k = Fltr.shape[1] # rows/columns of filter
o1 = m-k+1 # rows of output
o2 = l-k+1 # columns of output
#if considering m = l, output dimensions = m-k+1 = o1 = o2
out = np.zeros((o1,o2)) # output will result in a single channel image so we define it as a matrix
for r in range(0,o1):
kr = r+k
for c in range(0, o2):
kc = c+k
out[r,c] = ((InpImg[:, r:kr, c:kc])*Fltr).sum()
return out
"""Let's look at an example"""
i = np.array([[[1,0,0], [1,1,0], [0,1,0]], [[1,0,2], [1,2,0], [2,1,2]]])
f = np.array([[[0,0], [2,0]], [[1,2], [2,0]]])
print('Shape of input image:', i.shape)
print('Shape of filter:', f.shape)
#Applying convolution:
Conv(i,f)
"""We can see that the dimensions have reduced. This is because of border effect. This can result in information loss. Therefore one strategy to prevent this is to do padding.
Convolution with padding
To retain the dimensions of the input image, we use padding strategy. Padding adds margins of zeros around the axes of the input image.
The number of margins of zeros to be added depends on the kernel size. The best practice is to pad using (k-1)/2 zeros, where k is the kernel size (which is usually odd). Basically, the selection of the parameters is such that the image size is retained.
Let's write a function that returns a padded input upon which we can then perform convolution:
"""
# top, bottom, left and right are positions where we want to add desired number of layers of zeros
def ZeroPadding(inp, top, bottom, left, right):
return np.pad(inp, ((0,0), (top,bottom), (left,right)), mode='constant')
"""By visualizing, we can see that to obtain th eoutput image of the same dimensions as of the input image provided with the filter of kernel size 2, we will have to make the shape (2,4,4)"""
InpPad = ZeroPadding(i, 1,0,1,0)
InpPad
Conv(InpPad, f)
"""Since the spatial dimensions have been retained, there is no information loss.""" |
1b01bb37cb37f5017c7fe892daab1d4726cb04f6 | LeoTsui/ML_NTU | /MLF/hw1.py | 5,983 | 3.625 | 4 | #!user/bin/env python3
# _*_ coding: utf-8 _*_
"""
Question 15
For Questions 15-20, you will play with PLA and pocket algorithm. First, we use an artificial data set to study PLA. The data set is in
https://d396qusza40orc.cloudfront.net/ntumlone%2Fhw1%2Fhw1_15_train.dat
Each line of the data set contains one (xn,yn) with xn∈R4. The first 4 numbers of the line contains the components of xn orderly, the last number is yn.
Please initialize your algorithm with w=0 and take sign(0) as −1
Implement a version of PLA by visiting examples in the naive cycle using the order of examples in the data set. Run the algorithm on the data set. What is the number of updates before the algorithm halts?
31 - 50 updates
Question 16
Implement a version of PLA by visiting examples in fixed, pre-determined random cycles throughout the algorithm. Run the algorithm on the data set. Please repeat your experiment for 2000 times, each with a different random seed. What is the average number of updates before the algorithm halts?
31 - 50 updates
Question 17
Implement a version of PLA by visiting examples in fixed, pre-determined random cycles throughout the algorithm, while changing the update rule to be
wt+1←wt+ηyn(t)xn(t)
with η=0.5. Note that your PLA in the previous Question corresponds to η=1. Please repeat your experiment for 2000 times, each with a different random seed. What is the average number of updates before the algorithm halts?
31 - 50 updates
Question 18
Next, we play with the pocket algorithm. Modify your PLA in Question 16 to visit examples purely randomly, and then add the `pocket' steps to the algorithm. We will use
https://d396qusza40orc.cloudfront.net/ntumlone%2Fhw1%2Fhw1_18_train.dat
as the training data set D, and
https://d396qusza40orc.cloudfront.net/ntumlone%2Fhw1%2Fhw1_18_test.dat
as the test set for ``verifying'' the g returned by your algorithm (see lecture 4 about verifying). The sets are of the same format as the previous one.
Run the pocket algorithm with a total of 50 updates on D, and verify the performance of wPOCKET using the test set. Please repeat your experiment for 2000 times, each with a different random seed. What is the average error rate on the test set?
<0.2
Question 19
Modify your algorithm in Question 18 to return w50 (the PLA vector after 50 updates) instead of w^ (the pocket vector) after 50 updates. Run the modified algorithm on D, and verify the performance using the test set. Please repeat your experiment for 2000 times, each with a different random seed. What is the average error rate on the test set?
0.2 - 0.4
Question 20
Modify your algorithm in Question 18 to run for 100 updates instead of 50, and verify the performance of wPOCKET using the test set. Please repeat your experiment for 2000 times, each with a different random seed. What is the average error rate on the test set?
<0.2
"""
import numpy as np
import random
def read_file(f):
x_d = []
y_d = []
with open(f, 'r') as d:
for line in d:
l = line.split()
x = [1.0] + [float(v) for v in l[: -1]]
x_d.append(x)
y_d.append(int(l[-1]))
return np.array(x_d), np.array(y_d)
def native_pla(x_d, y_d, is_rand=False, repeat=1, eta=1.0):
total_update = 0
for rpt in range(0, repeat):
w = np.zeros(len(x_d[0]))
update_count = 0
all_pass = False
index = [i for i in range(len(x_d))]
if is_rand:
random.shuffle(index)
while not all_pass:
all_pass = True
for t in index:
if np.sign(np.inner(x_d[t], w)) != y_d[t]:
w += eta * y_d[t] * x_d[t]
all_pass = False
update_count += 1
total_update += update_count
return w, total_update / repeat
def pocket_pla(x_d, y_d, x_t, y_t, update, repeat=1, eta=1.0):
error = 0
random.seed()
for rpt in range(0, repeat):
w = np.zeros(len(x_d[0]))
wg = w
err_wg = test_pocket_pla(x_d, y_d, wg)
# index = [i for i in range(len(x_d))]
# random.shuffle(index)
for i in range(update):
#for t in index:
find_err = False
while not find_err:
t = random.randint(0, (len(x_d) - 1))
if np.sign(np.inner(x_d[t], w)) != y_d[t]:
w += eta * y_d[t] * x_d[t]
find_err = True
err_w = test_pocket_pla(x_d, y_d, w)
if err_w < err_wg:
wg = w
err_wg = err_w
error += test_pocket_pla(x_t, y_t, wg)
# Q 19
# error += test_pocket_pla(x_t, y_t, w)
return wg, error / repeat
def test_pocket_pla(x_t, y_t, w):
err = 0
for i in range(len(x_t)):
if np.sign(np.inner(x_t[i], w)) != y_t[i]:
err += 1
return err / len(x_t)
def main():
# Q 15-17
data15 = "hw1_15_train.dat"
x_data, y_data = read_file(data15)
# Q 15, native PLA
print("Q 15: ", native_pla(x_data, y_data)[1])
# Q 16, fixed, pre-determined random cycles
# print("Q 16: ", native_pla(x_data, y_data, True, 2000)[1])
# Q 17, fixed, pre-determined random cycles, with η=0.5
# print("Q 17: ", native_pla(x_data, y_data, True, 2000, 0.5)[1])
# Q 18-20
data18_train = "hw1_18_train.dat"
data18_test = "hw1_18_test.dat"
x_data, y_data = read_file(data18_train)
x_test, y_test = read_file(data18_test)
# Q 18, purely randomly, total 50 updates, repeat 2000
print("Q 18: ", pocket_pla(x_data, y_data, x_test, y_test, 50, 100)[1])
# Q 19, purely randomly, total 50 updates, repeat 2000, w = w50
# print("Q 19: ", pocket_pla(x_data, y_data, x_test, y_test, 50, 100)[1])
# Q 20, purely randomly, total 100 updates, repeat 2000
# print("Q 20: ", pocket_pla(x_data, y_data, x_test, y_test, 100, 100)[1])
if __name__ == "__main__":
main()
|
6093a063a32810042e7d8343a6c95e413df4360b | emmas0507/leetcode | /permuation_sequence.py | 565 | 3.5 | 4 | import math
def func(n, k):
seq = range(1, n+1)
k = k - 1
def permutation_sequence(seq, k):
print('seq is{}, k is {}'.format(seq, k))
if len(seq) == 1:
return [seq[0]]
else:
val_index = k / math.factorial(len(seq)-1)
val = seq[val_index]
seq = [seq[i] for i in range(len(seq)) if i != val_index]
k = k - val_index * math.factorial(len(seq))
return [val] + permutation_sequence(seq, k)
return permutation_sequence(seq, k)
n = 4
k = 17
print(func(n, k))
|
544e6870692687fba23d67faa8862cdbff6d79c5 | MithilRocks/Master-Python-Study | /Regular Expressions/main.py | 1,354 | 4.0625 | 4 | # All main re definitions
import re
# this matches only at beginning. Returns None otherwise
x = re.match("an", "anand")
print(x.start(), x.end())
# this matches at any point in the string just once
y = re.search("na", "anand")
print(y.start(), y.end())
# this returns all matches in a list
z = re.findall("a", "anand")
print(z)
# this returns all matches in the form of an iterable.
# the iterable is a collection of sre objects
a = re.finditer("a", "anand")
for i in a:
print(i.start(), i.end())
# splits at the specified pattern and returns a list.
# you can specify how many splits to make
b = re.split("an", "andAN", 1, flags=2)
print(b)
# replace pattern with string. specify count to how many times to replace
c = re.sub("an", "1", "anand", 1)
print(c)
# no difference from sub. just that it returns a tuple (new_string, count).
# count is number of substitutions made
d = re.subn("a", "1", "anand")
print(d)
# using flags, we can ignore case
# in this case flags=2 should be used
e = re.match("a", "Anand", flags=2)
print(e.start(), e.end())
# same as before. just a different way
f = re.match("a", "Anand", re.IGNORECASE)
print(f.start(), f.end())
# create an object of the regex expression.
# now we can use the above definitions in the object directly
g = re.compile("a")
print(g)
print(g.match("anand"))
print(g.split("anand"))
|
598b3309028ecb99b2a0de2168414047f921d73b | chenlanlan/leetcode | /Reverse Linked List II.py | 1,841 | 3.6875 | 4 | #!/usr/bin/python
class Solution:
# @param {ListNode} head
# @param {integer} m
# @param {integer} n
# @return {ListNode}
def reverseBetween(self, head, m, n):
if head == None or head.next == None or m == n:
return head
p1 = head
count = 1
length = n - m + 1
if m == 1:
p1 = head
p2, p3 = head.next, head.next
while count < length:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
count += 1
head.next = p2
return p1
else:
while count < m - 1:
p1 = p1.next
count += 1
count = 1
preStart = p1
start = p1.next
p1 = p1.next
p2 = p1.next
p3 = p2
while count < length:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
count += 1
preStart.next = p1
start.next = p2
return head
def reverseBetween2(self, head, m, n):
if head == None or head.next == None or m == n:
return head
p1 = head
preStart = None
count = 1
while count < m:
preStart = p1
p1 = p1.next
count += 1
p2 = p1.next
p3 = p2
start = p1
count = 1
length = n - m + 1
while count < length:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
count += 1
start.next = p2
if preStart:
preStart.next = p1
else:
head = p1
return head
|
4f99f850bb90ce79862bb97f17433f73518c9e6b | lgigek/alura | /python3/games/guess.py | 1,421 | 4.03125 | 4 | import random
def play():
print("*************************")
print("Welcome to the guess game")
print("*************************")
secret_number = random.randrange(1, 101)
points = 1000
print("Choose the difficulty level:")
print("(1) Easy \n(2) Medium \n(3) Hard")
difficulty_level = int(input("Difficulty: "))
if difficulty_level == 1:
max_tries = 20
elif difficulty_level == 2:
max_tries = 10
else:
max_tries = 5
for current_try in range(1, max_tries + 1):
print("Current try: {} of {}".format(current_try, max_tries))
guess_str = input("Input a number in the range of 1 to 100: ")
guess = int(guess_str)
if guess < 1 or guess > 100:
print("You must input a number in the range of 1 to 100: ")
continue
print("You inputted number: ", guess)
if secret_number == guess:
print("You inputted the right number. Score: {}".format(points))
break
else:
points_to_be_removed = abs(secret_number - guess)
points = points - points_to_be_removed
if guess > secret_number:
print("You inputted a number greater than the secret one")
else:
print("You inputted a number lesser than the secret one")
print("End of the game")
if __name__ == "__main__":
play()
|
2edf1469b31d10fbda608b387b6f7923c9271af7 | Near-River/leet_code | /121_130/123_best_time_to_buy_and_sell_stock_iii.py | 2,689 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
"""
使用“局部最优和全局最优解法”
我们维护两种变量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),
另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])
递推式:
global[i][j] = max(local[i][j], global[i-1][j])
local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff)
(注:diff = prices[i] - prices[i-1])
"""
# solution one: Dynamic Programming
# if not prices: return 0
# _global = [0, 0, 0]
# _local = [0, 0, 0]
#
# for i in range(1, len(prices)):
# diff = prices[i] - prices[i - 1]
# _gs, _ls = [0, 0, 0], [0, 0, 0]
# for j in range(1, 3):
# _ls[j] = max(_global[j - 1] + max(diff, 0), _local[j] + diff)
# _gs[j] = max(_ls[j], _global[j])
# _global = _gs
# _local = _ls
# return _global[-1]
# optimization
if not prices: return 0
_global = [0] * 3
_local = [0] * 3
for i in range(1, len(prices)):
diff = prices[i] - prices[i - 1]
j = 2
while j >= 1:
_local[j] = max(_global[j - 1] + max(diff, 0), _local[j] + diff)
_global[j] = max(_local[j], _global[j])
j -= 1
# return _global[-1]
n = len(prices)
if n < 2: return 0
p1 = [0] * n
p2 = [0] * n
minV = prices[0]
for i in range(1, n):
minV = min(minV, prices[i])
p1[i] = max(p1[i - 1], prices[i] - minV)
maxV = prices[-1]
for i in range(n - 2, -1, -1):
maxV = max(maxV, prices[i])
p2[i] = max(p2[i + 1], maxV - prices[i])
ret = 0
for i in range(n): ret = max(ret, p1[i] + p2[i])
return ret
if __name__ == '__main__':
solution = Solution()
print(solution.maxProfit([3, 2, 6, 5, 0, 3]))
print(solution.maxProfit([6, 1, 3, 2, 4, 7]))
|
13079fba396894d2af74f37238235c72f7d68d1c | Aersum/py-learning | /ex3/ex3.py | 663 | 3.859375 | 4 | #PE(M&D)(A&S)
print("I will now count my chicken")
#Deviding 30/6 and then adding 25printing result.
#25*3 then remainder(modulus) of the division of 75 to 4.
#75 devided by 4 with 3 remaining
print("Hens",25.0+30.0/6.0)
print("Roosters",100.0-25.0*3.0%4.0)
print("Now i Will count the eggs")
#3+21-5+reminder of 4%2=0-0.25+6
print(3.0+21.0-5.0+4.0%2.0-1.0/4.0+6.0)
#5<-2 is false
print("It's true that 3+2<5-7?")
#prinnting result
print(3+2<5-7)
print("What is 3+2?",3+2)
print("What is 5-7?",5-7)
print("Oh that's why it's False")
print("How about some more")
print("Is it grater?",5>2)
print("Is it grater or equal?",5>=2)
print("Is it less or equal",5<=2)
|
296eb70fe9e31ff7a31208c286320dcaf86b3b36 | spectro30/guessTheNumber | /GuessTheNumberGame.py | 594 | 3.890625 | 4 | import random
secretNumber = random.randint(1,100)
print('I have choosen a number between 1 and 100.')
print('Can you guess the number within 7 guesses?')
for guessTaken in range(1,8) :
print('Make a guess')
x = int(input())
if x > secretNumber :
print('Your guess is too high')
elif x < secretNumber :
print('Your guess is too low')
else :
break
if x == secretNumber :
print('Good job Bro! You guesssed my number in ' + str(guessTaken) + ' moves')
else :
print('Boka***da! Eidao parli na? The number was ' + str(secretNumber))
s = input()
|
a35dc9fffb749f3d9e98421eba3274da34b43f9f | speciallan/algorithm | /leetcode/problem771/problem771.py | 435 | 3.515625 | 4 | import time
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
total = 0
for i in J:
for j in S:
if i == j:
total += 1
return total
if __name__ == "__main__":
J = "aA"
S = "aAAbbbb"
s = Solution()
result = s.numJewelsInStones(J, S)
print(result) |
2aba288710c0cbb9e67c74e7b0c4f3f13da82866 | gkc23456/BIS-397-497-CHANDRATILLEKEGANA | /Assignment 2/Assignment 2 - Excercise 3.10.py | 150 | 3.546875 | 4 | # Exercise 3.10
principal = 1000.0
rate = 0.07
for year in range(1, 31):
print(f'Amount after {year} year(s): {principal * (1 + rate) ** year:}') |
0117c98e7bf9fe8c267ea538eb4eb8f617c18140 | GayathriSappa/HackerRank | /Algorithms/_02_Implementation/_20_Designer_PDF_Viewer/solution.py | 281 | 3.828125 | 4 | #!/bin/python3
import sys
h = list(map(int, input().strip().split(' ')))
word = input().strip()
maximum_height = 0
for char in word:
height = h[ord(char)-97]
if height > maximum_height:
maximum_height = height
area = len(word) * 1 * maximum_height
print(area)
|
948408c74e135b6f5008585c035b6a827540a581 | Pelusharaz/Python-Basics | /dictionary.py | 2,344 | 4.5 | 4 | '''creating a dictionary
with integer keys'''
Dict={1:'welcome',2:' to sharaz',3:'codes'}
print("\nwiththe use of integer keys:")
print(Dict)
#with mixed keys
Dict={'programmer':'sharaz','integers':[1,2,3]}
print("\nwith mixed keys:")
print(Dict)
#empy dictionary
Dict={}
print("empty dictionary:")
print(Dict)
#with dict()method
Dict=dict({1:'you',2:'sleep',3:'i code'})
print(Dict)
Dict=dict([(1,'programmer'),(2,'sharaz')])
print("\nDictionary with each item as pair")
print(Dict)
#creating nested Dictionary
Dict={1:'sharaz',2:'codes',
3:{'p':'are','Q':'the best'}}
print(Dict)
#Adding elements to a Dictionary
Dict={}
print("empty dictionary")
print(Dict)
#adding elements one at a time
Dict[0]='you'
Dict[1]='sleep'
Dict[2]=3
print("\nafter adding 3 elements")
print(Dict)
'''Adding a set of values to a single
key'''
Dict['value_set']='we', 'code'
print("\nafter adding a set of values")
print(Dict)
#updating an exixting key's value
Dict[0]='they'
print("\nupdated:")
print(Dict)
#addding nested values
Dict[4]={'Nested':{'1':'geeks','2':'for','3':'life'}}
print("\nafter adding nested value")
print(Dict)
#Acessing elements from a dictionary
Dict={1:'welcome',2:' to sharaz',3:'codes'}
print("\naccesing elements using key:")
print(Dict[3])
#using get method
Dict={1:'welcome',2:' to sharaz',3:'codes'}
print("\nAccessing elements using get:")
print(Dict.get(1))
#Accessing elements from a nested dictionary
Dict={'Dict1':{1:'sharaz',2:'codes'},
3:{'p':'are','Q':'the best'}}
print(Dict['Dict1'])
print(Dict['Dict1'][2])
print(Dict[3]['Q'])
'''Deleting elements from a dictionary
del dict-deletes the entire dictionary'''
#initial dictionary
Dict={'Dict1':{1:'sharaz',2:'codes'},
3:{'p':'are','Q':'the best'}}
print("\nintial dictionary:")
print(Dict)
#deleting deleting keys
del Dict['Dict1'][2]
del Dict[3]['p']
print("\nafater deletion")
print(Dict)
#using pop
Dict={1:'sharaz',2:'codes',
3:{'p':'are','Q':'the best'}}
print("\nintial dictionary:")
print(Dict)
pop_ele=Dict.pop(1)
print('\nafter deletion:'+str(Dict))
print('value associated with the popped key is'+str(pop_ele))
#using clear
Dict={1:'sharaz',2:'codes',
3:{'p':'are','Q':'the best'}}
print("\nintial dictionary:")
print(Dict)
#deleting entire dictionary
Dict.clear()
print("\nDeleting entire dictionary")
print(Dict)
|
7a395e9d9a779340e15896f5c8e8c5e229a5077b | Gporfs/Python-s-projects | /fungols.py | 309 | 3.59375 | 4 | def ficha(n='', g='0'):
if n.strip() == '':
n = '<desconhecido>'
if g.isnumeric():
g = int(g)
else:
g = 0
return f'O jogador {n} marcou {g} gol(s) no campeonato.'
nome = str(input('Nome: '))
marcados = str(input('Gol(s): '))
print(ficha(nome, marcados))
|
8caa4c693424667392e20f5d6f302d98870b7f84 | xuyitian123/CP1404-demo | /file1.py | 268 | 3.734375 | 4 | def main():
centsperkwh = int(input("Enter cents per kWh"))
dailyuse = int(input("Enter daily use in kWh"))
numofbilling = int(input("Enter number of billing days"))
estimatedfuel = centsperkwh * dailyuse * numofbilling
print(estimatedfuel)
main()
|
452a6fb9b4aa9498ef388fc710ff09701eef8377 | Geokenny23/Basic-python-batch5-c | /casting.py | 461 | 3.59375 | 4 | x = 7.8
print(x)
print(type(x))
#float to integer
int_x= int(x)
print(int_x)
print(type(int_x))
y= int(3)
print(y)
print(type(y))
#integer to float
float_x = float(int_x)
print(float_x)
print(type(float_x))
float_y= float(y)
print(float_y)
print(type(float_y))
#float to string
desimal = 33.33
print(desimal)
print(type(desimal))
string_desimal = str(desimal)
print(string_desimal)
print(type(string_desimal))
print(string_desimal * 3)
print(desimal*5)
|
6ccfcfa918fe9ae853458d0fd69b146263593d3a | nik24g/Python | /Function caching.py | 503 | 3.859375 | 4 | import time
from functools import lru_cache
# lru_cache() is used to cache a function.
# it takes a argument maxsize which represents that for how many arguments we want function caching.
@lru_cache(maxsize=2)
def work(n):
time.sleep(n)
return "I am work function"
if __name__ == '__main__':
print("Running work function")
work(3)
print(work(3))
print(work(3))
print(work(4))
print(work(4))
print(work(5))
print(work(5))
print(work(6))
print(work(6)) |
f4eab99fb99d8d255635a60a03f1201109ba223e | flyuqian/Python_s_01 | /01/ds_refrence.py | 265 | 3.765625 | 4 |
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
my_list = shoplist
del shoplist[0]
print('shop_list', shoplist)
print('my list', my_list)
my_list = shoplist[:]
del shoplist[0]
print('shop_list', shoplist)
print('my list', my_list) |
3b42de0ed4eaa704a414a0680342ae5b0eb1943b | binnwong/PythonDemo | /base_demo/try_except_demo.py | 1,163 | 4.09375 | 4 | # try:
# print(arg)
# except:
# print("参数未定义!")
# try:
# arg = 'Python 碎片'
# print(arg)
# except:
# print("参数为定义!")
# else:
# print("代码质量很高,没有异常!")
# try:
# num_str = "10.0"
# num = int(num_str)
# print(num)
# except ValueError as e:
# print(e)
# else:
# print("代码质量很高,没有异常!")
# finally:
# print("最终执行的代码")
# try:
# try:
# num_str = "10.0"
# num = int(num_str)
# print(num)
# except (NameError, SyntaxError) as e:
# print(e)
# finally:
# print('代码结束')
# except Exception as e:
# print("天网恢恢:{}".format(e))
class MoneyException(Exception):
'''自定义的异常类'''
def __init__(self, money):
self.money = int(money)
def __str__(self):
if self.money > 0:
return "Good!"
else:
return "Gun!"
try:
money = -100
if money > 0:
exc = MoneyException(money)
print(exc)
else:
raise MoneyException(money)
except MoneyException as e:
print("自己留着吧!", e)
|
a455beed5514587b5313e377edae5800d50d08b0 | lachlankuhr/AdventOfCode2017 | /4/part1.py | 233 | 3.703125 | 4 | with open("input.txt") as textFile:
data = [line.split() for line in textFile]
sum = 0
for item in data:
if len(item) == len(set(item)):
sum = sum + 1
else:
sum = sum + 0
print("The sum is {}".format(sum)) |
f825e823e21f0b5504d5b1960b893160648bbc45 | Helcya/Exercicios-4 | /Helcya_Franco_Q3.py | 273 | 3.640625 | 4 | partidas = int(input('Quantos jogos você deseja?'))
mega_sena = []
jogo = []
mega_sena.append(jogo[:])
from random import sample
def jogo():
return sorted(sample(range(1, 60), 6))
i = 0
for i in range(partidas):
print('Jogo',i+1,':',jogo())
i += 1
|
3311550117463f91aae321f042704b431de31e41 | vincent507cpu/Comprehensive-Algorithm-Solution | /LeetCode/easy - Hash Table/720. Longest Word in Dictionary/solution.py | 483 | 3.890625 | 4 | # solution
# https://leetcode.com/problems/longest-word-in-dictionary/discuss/367203/easy-peasy-python-solution-using-sorting-and-set
class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort()
st, res = set(), ""
st.add("") # set('') will be equal to set()
for word in words:
if word[:-1] in st:
if len(word) > len(res):
res = word
st.add(word)
return res |
b6cc2c6e20ea189b95b19091b7be54e71ada9b3e | umair-gujjar/threes-clone | /Threes.py | 13,293 | 3.765625 | 4 | __author__ = 'Peter_000'
from random import randint
import random
import json
class Tile(object):
def __init__(self, value=0, position=(0, 0), an_id=0):
"""
:type an_id: int
"""
self.value = value
self.row = position[0]
self.col = position[1]
self.id = an_id
def set_position(self, position):
self.row = position[0]
self.col = position[1]
def get_position(self):
return self.row, self.col
def get_id(self):
return self.id
def get_row(self):
return self.row
def get_col(self):
return self.col
def get_value(self):
return self.value
def get_score(self):
# 3^(log(value/3)/log(2) + 1)
return
def move_right(self):
self.col += 1
def move_left(self):
self.col -= 1
def move_up(self):
self.row -= 1
def move_down(self):
self.row += 1
def can_be_combined_with(self, tile):
"""
Can be combined if one of the values is blank
The sum of the value is 3
The values are the same and greater than or equal to 3.
"""
that_value = tile.get_value()
this_value = self.get_value()
if (this_value + that_value == 3) or (this_value == that_value and (this_value >= 3 and that_value >= 3)):
return True
else:
return False
# else:
# return False
def combine_into(self, tile):
"""
if can be combined then combine
"""
if self.can_be_combined_with(tile):
self.value += tile.get_value()
self.set_position(tile.get_position())
def to_json(self):
return {'position': {'row': self.get_row(), 'col': self.get_col()}, 'value': self.get_value(), 'id': self.get_id()}
def __str__(self):
if self.value == 0:
value = ""
else:
value = self.value
return " {0:5s} |".format(str(value))
def get_random_tile_value():
return random.choice([1, 2, 3]) # even split between 1, 2, 3
# once 48 is the highest, then 6's become a possibility
# once 96 is the highest, then 12's become a possibility
class Board(object):
def __init__(self, nrows=4, ncols=4, next_id=1):
self.nrows = nrows
self.ncols = ncols
self.tiles = list()
self.next_tile_value = get_random_tile_value() # picks random number from list
self.next_id = next_id
def is_full(self):
if len(self.tiles) >= self.nrows * self.ncols:
return True
else:
return False
def get_random_col(self):
return randint(0, self.ncols - 1)
def get_random_row(self):
return randint(0, self.nrows - 1)
def get_tiles_in_row(self, row):
"""
Return the tiles in the given row from left to right
"""
tiles = [tile for tile in self.tiles if tile.get_row() == row]
tiles.sort(key=lambda x: x.get_col())
return tiles
def get_tiles_in_col(self, col):
"""
Return the tiles in the given col from top to bottom
"""
tiles = [tile for tile in self.tiles if tile.get_col() == col]
tiles.sort(key=lambda x: x.get_row())
return tiles
def get_tile_at(self, row, col):
tiles_in_row = self.get_tiles_in_row(row)
match = [tile for tile in tiles_in_row if tile.get_col() == col]
if match == list():
return None
else:
return match[0]
def is_space_filled(self, row, col):
if self.get_tile_at(row, col):
return True
else:
return False
def add_tile(self, tile):
self.tiles.append(tile)
pass
def add_random_tile_in_col(self, col):
possible_locations = list()
for n in range(0, self.nrows):
if not self.is_space_filled(n, col):
possible_locations.append(n)
if possible_locations:
self.add_tile(Tile(value=self.next_tile_value, position=(random.choice(possible_locations), col),
an_id=self.next_id))
self.next_id += 1
self.next_tile_value = get_random_tile_value()
pass
def add_random_tile_in_row(self, row):
possible_locations = list()
for n in range(0, self.nrows):
if not self.is_space_filled(row, n):
possible_locations.append(n)
if possible_locations:
self.add_tile(Tile(value=self.next_tile_value, position=(row, random.choice(possible_locations)),
an_id=self.next_id))
self.next_id += 1
self.next_tile_value = get_random_tile_value()
pass
def add_random_tile(self):
"""
:type self: Board
"""
if not self.is_full():
placed = False
while not placed:
row = self.get_random_row()
col = self.get_random_col()
if not self.is_space_filled(row, col):
self.tiles.append(Tile(value=randint(1, 2), position=(row, col), an_id=self.next_id))
self.next_id += 1
placed = True
pass
def up(self):
"""
Shift up
"""
# iterate through each col
for n in range(0, self.ncols):
col = self.get_tiles_in_col(n)
combine_limit_reached = False
if col: # only do something if the row isn't empty
for tile in col:
# start at top most tile
# can it move up? if yes, move
new_row = tile.get_row() - 1
if new_row >= 0: # is it within the edges of the board
tile_at_destination = self.get_tile_at(new_row, n)
if not tile_at_destination: # is the destination empty?
tile.move_up()
elif tile.can_be_combined_with(
tile_at_destination) and not combine_limit_reached: # if not empty and can be combined, then combine
tile.combine_into(tile_at_destination)
combine_limit_reached = True
assert isinstance(tile, Tile)
self.tiles.remove(tile_at_destination) # trust that tile will be garbage collected.
self.add_random_tile_in_row(self.nrows-1)
def down(self):
"""
Shift down
"""
# iterate through each col
for n in range(0, self.ncols):
col = self.get_tiles_in_col(n)
combine_limit_reached = False
if col: # only do something if the row isn't empty
for tile in reversed(col):
# start at bottom most tile
# can it move down? if yes, move
new_row = tile.get_row() + 1
if new_row < self.nrows: # is it within the edges of the board
tile_at_destination = self.get_tile_at(new_row, n)
if not tile_at_destination: # is the destination empty?
tile.move_down()
elif tile.can_be_combined_with(
tile_at_destination) and not combine_limit_reached: # if not empty and can be combined, then combine
tile.combine_into(tile_at_destination)
combine_limit_reached = True
assert isinstance(tile, Tile)
self.tiles.remove(tile_at_destination) # trust that tile will be garbage collected.
self.add_random_tile_in_row(0)
def right(self):
"""
Shift right
"""
# iterate through each row
for n in range(0, self.nrows):
row = self.get_tiles_in_row(n)
combine_limit_reached = False
if row: # only do something if the row isn't empty
for tile in reversed(row):
# start at right most tile
# can it move right? if yes, move
new_col = tile.get_col() + 1
if new_col < self.ncols: # is it within the edges of the board
tile_at_destination = self.get_tile_at(n, new_col)
if not tile_at_destination: # is the destination empty?
tile.move_right()
elif tile.can_be_combined_with(
tile_at_destination) and not combine_limit_reached: # if not empty and can be combined, then combine
tile.combine_into(tile_at_destination)
combine_limit_reached = True
assert isinstance(tile, Tile)
self.tiles.remove(tile_at_destination) # trust that tile will be garbage collected.
self.add_random_tile_in_col(0)
pass
def left(self):
"""
Shift left
"""
# iterate through each row
for n in range(0, self.nrows):
row = self.get_tiles_in_row(n)
combine_limit_reached = False
if row: # only do something if the row isn't empty
for tile in row:
# start at left most tile
# can it move left? if yes, move
new_col = tile.get_col() - 1
if new_col >= 0: # is it within the edges of the board
tile_at_destination = self.get_tile_at(n, new_col)
if not tile_at_destination: # is the destination empty?
tile.move_left()
elif tile.can_be_combined_with(
tile_at_destination) and not combine_limit_reached: # if not empty and can be combined, then combine
tile.combine_into(tile_at_destination)
combine_limit_reached = True
self.tiles.remove(tile_at_destination) # trust that tile will be garbage collected.
self.add_random_tile_in_row(self.ncols-1)
pass
def to_json(self):
"""
Convert object to a json-serializable dictionary
"""
return {'ncols': self.ncols, 'nrows': self.nrows,
'tiles': [tile.to_json() for tile in self.tiles],
'next_tile': {'value': 3},
'next_id': self.next_id}
def string_board(self):
rows = list()
for n in range(0, self.nrows):
row = '|'
for m in range(0, self.ncols):
match = self.get_tile_at(n, m)
if match:
row += " {0:5s} |".format(str(match.get_value()))
else:
row += " {0:5s} |".format('')
rows.append(row)
return '\n'.join(rows) + '\n'
def get_score(self):
return 0
def print_board(self):
print self.string_board()
def create_board_from_json(json_board_definition):
'''
Assumes json_board_definition is of form:
CreateBoardFromJson('{"nrows": 4, "tiles": [{"position": {"col": 2, "row": 0}, "value": 1}, {"position": {"col": 3, "row": 2}, "value": 1}, {"position": {"col": 0, "row": 1}, "value": 1}, {"position": {"col": 0, "row": 2}, "value": 2}, {"position": {"col": 2, "row": 2}, "value": 1}, {"position": {"col": 1, "row": 0}, "value": 1}, {"position": {"col": 0, "row": 3}, "value": 2}], "next_tile": {"value": 3}, "ncols": 4}')
'''
obj = json.loads(json_board_definition)
board = Board(nrows=obj['nrows'], ncols=obj['ncols'], next_id=obj['next_id'])
for tile in obj['tiles']:
board.add_tile(Tile(position=(tile['position']['row'], tile['position']['col']), value=tile['value'], an_id=tile['id']))
return board
if __name__ == '__main__':
b = create_board_from_json('{"nrows": 4, "tiles": [{"position": {"col": 2, "row": 0}, "value": 1, "id": 1}, {"position": {"col": 3, "row": 2}, "value": 1, "id": 2}, {"position": {"col": 0, "row": 1}, "value": 1, "id": 3}, {"position": {"col": 0, "row": 2}, "value": 2, "id": 4}, {"position": {"col": 2, "row": 2}, "value": 1, "id": 5}, {"position": {"col": 1, "row": 0}, "value": 1, "id": 6}, {"position": {"col": 0, "row": 3}, "value": 2 , "id": 7}], "next_tile": {"value": 3}, "ncols": 4, "next_id": 8}')
# b = Board(4, 4)
# b.add_random_tile()
# #b.print_board()
# b.add_random_tile()
# b.add_random_tile()
# b.add_random_tile()
# b.add_random_tile()
# b.add_random_tile()
# #b.print_board()
# b.add_random_tile()
print json.dumps(b.to_json())
a = ''
while not a == 'q':
b.print_board()
a = raw_input("wasd to move, q to quit:")
if a == 'w':
b.up()
elif a == 's':
b.down()
elif a == 'a':
b.left()
elif a == 'd':
b.right()
|
d2443569c7f7034531e8f55af04a1eb9cde957fa | 8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions | /Chapter11/0044_rev12_calendar_clock.py | 1,063 | 4.3125 | 4 | """
Review Question 12
Create two base classes named clock and calendar. Based on these two
classes define a class calendarclock, which inherits from both the
classes which displays month details, date and time
"""
class Clock:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def display_time(self):
print(f"{self.hour}:{self.minute}:{self.second}")
class Calendar:
def __init__(self, month, date):
self.month = month
self.date = date
def display_date(self):
print(f"{self.date} {self.month}")
class CalendarClock(Clock, Calendar):
def __init__(self, month, date, hour, minute, second):
Clock.__init__(self, hour, minute, second)
Calendar.__init__(self, month, date)
def display_datetime(self):
self.display_date()
self.display_time()
def main():
calendar_clock = CalendarClock("January", 30, 12, 32, 47)
calendar_clock.display_datetime()
if __name__ == "__main__":
main()
|
d9c7e5b72726f6c46b62b7a904ea6d189097b2da | sofiia-tesliuk/Tic-tac-toe | /binary_realization/btnode.py | 789 | 3.5625 | 4 | from basicboard import BasicBoard
class BTnode(BasicBoard):
def __init__(self, state, last_move):
# In state: True -- computer char
# False -- player char
# None -- empty
self.state = state
self.last_move = last_move
self.free_cells = []
for i, row in enumerate(state):
for j, el in enumerate(row):
if el is None:
self.free_cells.append(i * 3 + j + 1)
self.left = None
self.right = None
self.points = 0
# Current state is the last of possible
self.last_state = False
def __gt__(self, other):
if isinstance(other, BTnode):
return self.points > other.points
else:
return self
|
f060ef4e649941b50eaa7001a305f3b92f110b1a | crazydreamer/LanguageIdentification | /report.py | 2,456 | 3.5625 | 4 | def avg(list):
"""compute the average of a list of numbers"""
return sum(list)/float(len(list))
def standard_deviation(list):
"""compute the standard deviation of a list of numbers"""
length, total, squared = len(list), sum(x for x in list), sum(x*x for x in list)
return sqrt((length * squared - total * total)/(length * (length - 1)))
def mad(list):
"""compute the mean absolute deviation of a list of numbers"""
mean = avg(list)
return avg([abs(n - mean) for n in list])
def aggregate(results, result):
import collections
data = munch(result, [
('cv', '%2.2f', lambda e: avg(e['cv'])),
('Test error', '%2.2f', lambda e: e['test'])
])
headers = next(data)
for name, *row in data:
if name not in results:
results[name] = collections.defaultdict(list)
for k, v in zip(headers[1:], row):
results[name][k].append(v)
return results
def munch(results, columns=[], missing='-'):
"""
this method is intended to munch a list of dicts down to a list of lists
"""
args = sorted(list(set([a for e in results for a in e['args']])))
yield ['name'] + [c[0] for c in columns]
for e in results:
# output row
prev = e['model'].__name__
ps = ', '.join(['%s=%s' % a for a in sorted(e['args'].items(), key=lambda e: len(e[0]))])
row = ['%s(%s)' % (e['model'].__name__, ps)]
for header, format, func in columns:
row.append(format % func(e))
yield row
def tabulate(results):
"""
format a list of lists into tables
"""
import prettytable
import itertools
data = munch(results, [
('CV error', '%2.5f', lambda e: avg(e['cv'])),
('Test error', '%2.5f', lambda e: e['test'])
])
data = itertools.groupby(data, key=lambda e: e[0].split('(')[0])
table = prettytable.PrettyTable(list(next(data)[1])[0])
table.align['name'] = 'l'
for key, group in data:
for row in list(group):
table.add_row(row)
print(table)
def to_csv(results, filename):
"""format a list of experiment results into a csv file"""
import csv
data = list(munch(results, [
('E(cv)', '%2.5f', lambda e: avg(e['cv'])),
('E(test)', '%2.5f', lambda e: e['test'])
]))
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for row in data:
writer.writerow(row)
|
bed3c1b30be24bc213807f0a5376cee1b24344e5 | burakbayramli/books | /Practical_Numerical_Methods_with_Python_Barba/CFD_Codes/wind_theory/pysrc/applets/ideal_wake_rotation_model.py | 2,117 | 3.546875 | 4 | """
Author: Rohan
Date: 19/12/16
This file contains a simple model to consider ideal turbines with annular wake rotation
"""
import numpy as np
from matplotlib import pyplot as plt
def get_induction_factor(lambda_r):
"""
This function calculates the maximum induction factor of the turbine from the tip speed ratio
:param lambda_r: Ratio of blade velocity to incoming wind velocity: wr/U
:return:
"""
lambda_r_squared = lambda_r ** 2
tip_speed_squared = lambda a: (1 - a) * (1 - 4 * a) ** 2 / (1 - 3 * a)
TOL = 1e-8
# Physical values are constrained between 0.25 and 0.333
a_min = 0.25
a_max = 1.0 / 3.0
max_num_iter = 1000
iter_num = 0
while iter_num < max_num_iter:
a_mid = (a_max + a_min) / 2.0
lambda_guess = tip_speed_squared(a_mid)
if np.abs(lambda_guess - lambda_r_squared) < TOL:
return a_mid
if lambda_guess < lambda_r_squared:
a_min = a_mid
else:
a_max = a_mid
iter_num += 1
raise RuntimeError("Induction Factor failed to converge!")
def calculate_C_p(tip_speed_ratio):
"""
This function calculates the power coefficient for a given tip speed ratio
:param tip_speed_ratio: Ratio of blade velocity to incoming wind velocity at blade tip: wR/U
:return:
"""
a_min = get_induction_factor(0.0)
a_max = get_induction_factor(tip_speed_ratio)
# Calculate integral
integral = lambda a: ((1 - a) * (1 - 2 * a) * (1 - 4 * a) / (1 - 3 * a)) ** 2
a = np.linspace(a_min, a_max, 100000)
da = a[1] - a[0]
dCp = integral(a) * da
Cp = np.sum(dCp) * 24.0 / tip_speed_ratio ** 2
return Cp
def example():
num_pts = 100
tip_speed_ratios = np.linspace(0.01, 10.0, num_pts)
Cp = np.zeros(num_pts)
for i, tsr in enumerate(tip_speed_ratios):
Cp[i] = calculate_C_p(tsr)
plt.figure()
plt.plot(tip_speed_ratios, Cp)
plt.ylabel("Power Coefficient (Cp)")
plt.xlabel("Tip Speed Ratio")
plt.axhline(16.0 / 27.0, color='k')
plt.show()
if __name__ == '__main__':
example() |
2da80541efc43affea47c422f6be7642f802825e | cscoder99/CS.Martin | /imp_tri_class_ortecho.py | 222 | 3.703125 | 4 | from triangle_class import *
triangle1 = Triangle(3, 4, 5)
triangle_angles = angle(triangle1)
print triangle1
print triangle_angles
tri_scaled = scale(triangle1)
print tri_scaled
tri_scaled = triangle2
print triangle2
|
2e8c4b6c5dd45b3017c63655f9e2409cd7e89546 | MaxwellVale/CS01 | /cs1_final/rubiks_cube.py | 6,200 | 3.65625 | 4 | # Name: Maxwell Vale
# Login: mvale
'''
Rubik's cube class.
'''
import copy, random
import rubiks_utils as u
import rubiks_rep as r
class InvalidCube(Exception):
'''
This exception is raised when a cube has been determined to be in
an invalid configuration.
'''
pass
class RubiksCube:
'''
This class implements all Rubik's cube operations.
'''
def __init__(self, size):
'''Initialize the cube representation.'''
# Cube representation.
self.rep = r.RubiksRep(size)
# Number of moves, quarter-turn metric.
self.count = 0
def get_state(self):
'''
Return a copy of the internal state of this object.
'''
rep = copy.deepcopy(self.rep)
return (rep, self.count)
def put_state(self, rep, count):
'''
Restore a previous state.
'''
self.rep = rep
self.count = count
### Basic operations.
def rotate_cube(self, axis, dir):
'''
Rotate the cube as a whole.
The X axis means in the direction of an R turn.
The Y axis means in the direction of a U turn.
The Z axis means in the direction of an F turn.
The + direction is clockwise.
The - direction is counterclockwise.
Arguments:
axis -- one of ['X', 'Y', 'Z']
dir -- one of ['+', '-']
Return value: none
'''
assert axis in ['X', 'Y', 'Z']
assert dir in ['+', '-']
turns = 1
if dir == '-':
turns += 2
for i in range(turns):
if axis == 'X':
self.rep.rotate_cube_X()
elif axis == 'Y':
self.rep.rotate_cube_Y()
else:
self.rep.rotate_cube_Z()
def move_face(self, face, dir):
'''
Move the specified face.
Arguments:
-- face: one of ['U', 'D', 'L', 'R', 'F', 'B']
-- dir: '+' for clockwise or '-' for counterclockwise
Return value: none
'''
assert face in ['U', 'D', 'F', 'B', 'L', 'R']
assert dir in ['+', '-']
turns = 1
self.count += 1
if dir == '-':
turns += 2
self.face_to_F(face)
for i in range(turns):
self.rep.move_F()
self.F_to_face(face)
def face_to_F(self, face):
'''
Rotates the cube so that 'face' is now facing forward (on the F face)
'''
d = {'U' : ('X', '-'), 'D' : ('X', '+'), 'R' : ('Y', '+'), 'L' : ('Y', '-'), 'B' : ('Y', '+')}
if face == 'F':
return
turn, dir = d[face]
if face == 'B':
self.rotate_cube(turn, dir)
self.rotate_cube(turn, dir)
def F_to_face(self, face):
'''
Rotates the current F face to 'face' (one of UDFBRL)
'''
self.face_to_F(face)
if face != 'B':
for i in range(2):
self.face_to_F(face)
def random_rotations(self, n):
'''
Rotate the entire cube randomly 'n' times.
Arguments:
n -- number of random rotations to make
Return value: none
'''
for _ in range(n):
rot = random.choice('XYZ')
dir = random.choice('+-')
self.rotate_cube(rot, dir)
def random_moves(self, n):
'''
Make 'n' random moves.
Arguments:
n -- number of random moves to make
Return value: none
'''
for _ in range(n):
face = random.choice('UDFBLR')
dir = random.choice('+-')
self.move_face(face, dir)
def scramble(self, nrots=10, nmoves=50):
'''
Scramble the cube.
Arguments:
nrots -- number of random cube rotations to make
nmoves -- number of random face moves to make
Return value: none
'''
self.random_rotations(nrots)
self.random_moves(nmoves)
# Reset count before solving begins.
self.count = 0
def is_solved(self):
'''
Return True if the cube is solved.
If the cube appears solved but is invalid, raise an
InvalidCube exception with an appropriate error message.
'''
opposites = {'w' : 'y', 'y' : 'w', 'r' : 'o', 'o' : 'r', 'g' : 'b', 'b' : 'g'}
faceColor = {}
for f in ['U', 'D', 'F', 'B', 'L', 'R']:
face = self.rep.get_face(f)
colors = set(sum(face, []))
if len(colors) != 1:
return False
faceColor[f] = colors.pop()
if set(faceColor.values()) != {'w', 'y', 'g', 'b', 'r', 'o'}:
raise InvalidCube("Not all colors represented on the cube.")
if opposites[faceColor['U']] != faceColor['D']:
raise InvalidCube("Top and bottom faces do not have a valid pair of colors.")
elif opposites[faceColor['R']] != faceColor['L']:
raise InvalidCube("Right and left faces do not have a valid pair of colors.")
elif opposites[faceColor['F']] != faceColor['B']:
raise InvalidCube("Front and back faces do not have a valid pair of colors.")
else:
ufrCombos = ['wgr', 'wrb', 'wbo', 'wog',
'goy', 'gyr', 'grw', 'gwo',
'ygo', 'yob', 'ybr', 'yrg',
'rwg', 'rgy', 'ryb', 'rbw',
'bwr', 'bry', 'byo', 'bow',
'owb', 'oby', 'oyg', 'ogw']
last = self.rep.size - 1
u = self.rep.get_face('U')[last][last]
f = self.rep.get_face('F')[0][last]
r = self.rep.get_face('R')[0][0]
ufr = u + f + r
if ufr not in ufrCombos:
raise InvalidCube('U, F, and R faces in illegal configuration.')
return True
def display(self):
'''
Return a string version of the cube representation.
'''
return self.rep.display()
if __name__ == '__main__':
cube = RubiksCube(3)
cube.rep.test_faces()
print(cube.display())
# cube.scramble()
# print(cube.display())
|
a4147f85d952ce1dae9883f4b6b3d1c693a4e388 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/62_16.py | 2,298 | 4.1875 | 4 | Python – Triple quote String concatenation
Sometimes, while working with Python Strings, we can have problem in which we
need to perform concatenation of Strings which are constructed by Triple
quotes. This happens in cases we have multiline strings. This can have
applications in many domains. Lets discuss certain way in which this task can
be performed.
**Input** : test_str1 = """mango
is"""
test_str2 = """good
for health
"""
**Output** : mango good
is for health
**Input** : test_str1 = """Gold
is"""
test_str2 = """important
for economy
"""
**Output** : Gold important
is for economy
**Method : Usingsplitlines() + strip() + join()**
The combination of above functions can be used to perform this task. In this,
we perform the ask of line splitting using splitlines(). The task of
concatenation is done using strip() and join().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Triple quote String concatenation
# Using splitlines() + join() + strip()
# initializing strings
test_str1 = """gfg
is"""
test_str2 = """best
for geeks
"""
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Triple quote String concatenation
# Using splitlines() + join() + strip()
test_str1 = test_str1.splitlines()
test_str2 = test_str2.splitlines()
res = []
for i, j in zip(test_str1, test_str2):
res.append(" " + i.strip() + " " + j.strip())
res = '\n'.join(res)
# printing result
print("String after concatenation : " + str(res))
---
__
__
**Output :**
The original string 1 is : gfg
is
The original string 2 is : best
for geeks
String after concatenation : gfg best
is for geeks
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
be92fb31d893be5cc162a4f1f320175da40283a9 | shuvo14051/python-data-algo | /Problem-solving/HackerRank/Project Euler 179 Consecutive positive divisors.py | 134 | 3.5625 | 4 | test = int(input())
for i in range(test):
n = int(input())
for j in range(2, n):
if n % j == 0:
print(j)
|
c6255504180df7b5ca950e27ef0b3e05e67e3b71 | Sakamotto/IFES_Prog2 | /Programas/Exercicio 5.py | 1,379 | 3.9375 | 4 | """
Construa a função intersec(<texto>, <texto>) que retorna uma lista com o conjunto intersecção das palavras
que acorrem em <texto1> e <texto2>
Construa a função uniao(<texto>, <texto>) que retorna uma lista com o conjunto união das palavras
que acorrem em <texto1> e <texto2>
"""
def separaPal(pTexto):
strSeparadores = ' ,.:;!?'
strBuffer = ""
lstPalavras = []
for i in range(len(pTexto)):
if pTexto[i] not in strSeparadores:
strBuffer += pTexto[i]
elif strBuffer != "":
lstPalavras.append(strBuffer)
strBuffer = ""
#
#
if strBuffer != "":
lstPalavras.append(strBuffer)
#
return lstPalavras
#
def intersec(pTexto1, pTexto2):
lstTexto1 = separaPal(pTexto1)
lstTexto2 = separaPal(pTexto2)
inter = []
for texto1 in lstTexto1:
for texto2 in lstTexto2:
if texto1 == texto2:
if texto1 not in inter:
inter.append(texto1)
#
#
#
#
return inter
#
def uniao(pTexto1, pTexto2):
lstTexto1 = separaPal(pTexto1)
lstTexto2 = separaPal(pTexto2)
u = []
for texto1 in lstTexto1:
if texto1 not in u:
u.append(texto1)
#
#
for texto2 in lstTexto2:
if texto2 not in u:
u.append(texto2)
#
#
return u
#
def main():
texto1 = "Oi, eu sou Goku e Gohan"
texto2 = "Mentira, eu sou Gohan!"
print(intersec(texto1, texto2))
print(uniao(texto1, texto2))
return 0
if __name__ == '__main__':
main()
|
bd764be4473be690e6a45abd03376001f2e08dd2 | Lafungo/koenigsberg | /p41.py | 774 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 9 08:11:09 2017
@author: Lafungo
"""
import datetime
from sympy.ntheory import prevprime
start = datetime.datetime.now()
def is_pan(n):
s_n = str(n)
if set(s_n) == set(['1', '2', '3', '4', '5', '6', '7']):
return True
else:
return False
# if len(s_n) != 9:
# return False
# digits = []
#
# for digit in s_n:
# if digit == '0' or digit in digits:
# return False
#
# digits.append(digit)
#
# return True
found = False
p = prevprime(10**7)
while not found:
if is_pan(p):
pan_prime = p
found = True
p = prevprime(p)
print(pan_prime)
end = datetime.datetime.now()
print(end - start)
|
cb2437c7e9c79bc1a644b79868d6612c48c89fc9 | NancyHui/ZSXQ | /pig_latin.py | 440 | 3.859375 | 4 | # 屏幕输入
word = input('Please enter a word')
# 检查用户输入是否为英文单词:word不为空,并且使用isalpha()方法检查是否为英文单词
if len(word) > 0 and word.isalpha():
pyg = 'ay'
lower_word = word.lower()
first = lower_word[0]
new_word = lower_word + first + pyg
new_word = new_word[1:]
print("The Pig Latin word is {}".format(new_word.lower()))
else:
print("Invalid input")
|
e0087da1e86fb09168f9a2435f7cb40162b4cd98 | Lennoard/ifpi-ads-algoritmos2020 | /Fabio01_Parte01/f1_q16_area_quadrado.py | 114 | 3.609375 | 4 | l = float(input('Insira o valor do lado do quadrado: '))
area = pow(l, 2)
print(f'A area do quadrado e: {area}') |
50743bf4fb2b7ceca2d1742a482aeb47c7db9bd2 | RobRcx/algorithm-design-techniques | /recursion/factorial_recursive.py | 133 | 3.921875 | 4 | # calculates factorial of a positive integer
def factorial(n):
if n == 0:
return 1
return n*factorial(n-1)
print factorial(6)
|
efbf27d1b483a94a40bf83312f721d28815ff636 | HongyuS/Vegetable-Market | /CSC1001/Assignment_3/q1.py | 1,412 | 4.09375 | 4 | class Flower:
def __init__(self, name, petals, price):
self.name = name
self.petals = petals
self.price = price
def setName(self):
self.name = input('Please enter the name of the flower:\n> ')
def setPetals(self):
while True:
value = input('Please enter the number of petals:\n> ')
try:
self.petals = int(value)
if self.petals < 0:
print('Number of petals cannot be negative!')
raise ValueError()
except ValueError:
print('Invalid input ...\nPlease try again!')
else:
break
def setPrice(self):
while True:
value = input('Please enter the price of the flower:\n> ')
try:
self.price = float(eval(value))
if self.price < 0:
print('The price cannot be negative!')
raise ValueError()
except ValueError:
print('Invalid input ...\nPlease try again!')
else:
break
def show(self):
print('The name of the flower is', self.name)
print('The number of petals is', self.petals)
print('The price of the flower is', self.price)
f = Flower('flower', 0, 0.0)
f.setName()
f.setPetals()
f.setPrice()
f.show()
|
6ea2f1e91bfa2f1ea3ac23dd9c3afd49086708ec | Almentoe/Euler-2 | /EulerProgramPython/Euler7.py | 275 | 3.734375 | 4 | import math
from math import *
def is_prime(n):
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
N = 1000000
primes = ()
for num in range(2,N):
if is_prime(num):
primes = primes + (num,)
A = primes
print(A[10000]) |
7e5a0f35997abde1473591375864a0958166c9fc | alxgurjev/isiku_check | /005_functional_programming/tester.py | 192 | 3.78125 | 4 | def squares(number, multiplier):
result = number ** multiplier
return result
x = 5
y = 3
#
# print(squares(x, y))
# print(type(squares(x, y)))
squares(x, y)
print(squares(x, y) * 10)
|
3f8cd5fcb611fa4e343c5aff29f92988b87fd2f8 | dineshbhonsle14/master | /coding/1.1_isUnique.py | 728 | 3.609375 | 4 | import unittest
def isunique(string):
char_set=[False for _ in range(128)]
for chr in string:
val=ord(chr)
if char_set[val] is False:
char_set[val]=True
else:
print "{} {}".format(chr,char_set[val])
return False
print "{} {}".format(chr,char_set[val])
return True
class Test(unittest.TestCase):
dataT=[('helo'),('dinesh')]
dataF=['hello','dineshh']
def test_1(self):
for test_string in self.dataT:
tres=isunique(test_string)
self.assertTrue(tres)
def test_2(self):
for test_string in self.dataF:
tres=isunique(test_string)
self.assertFalse(tres)
if __name__=='__main__':
unittest.main()
|
8f90c668f3c0f4dee6f9ba0fa4df1a0e09e7aa66 | mines-nancy-tcss5ac-2018/td1-mcsweenyclementine | /TD1.py | 1,660 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 16:16:14 2018
@author: clemcsweeny
"""
#### PROBLEM 16: Power digit sum ####
def problem16(n):
k=0
while n!=0:
k+=(n%10)
n=n//10
return k
#### PROBLEM 22: Names scores ####
def problem22():
f=open('p022_names.txt','r')
for line in f:
l=line.split(",")
L=sorted(l)
S=0 ### S est le score total de la liste
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for nom in L:
s=0 ### s est le score d'un nom de la liste
for j in range(len(nom)): ### calcul du score grace aux lettres du nom
for i in range(len(alpha)):
if alpha[i]==nom[j]:
s+=i+1
for k in range(len(L)): ### recherche du placement du nom dans la liste
if L[k]==nom:
c=k+1
S+=(s*c)
return S
##### PROBLEM 55: Nombre de Lychrel #####
# Fonction qui inverse les chiffres d'un nombre :
def reverse(n):
N=str(n)
L=''
for k in N:
L=k+L
return int(L)
# Fonction qui verifie si un nombre est palyndrome :
def palyndrome(n):
return n==reverse(n)
# Fonction qui verifie si un nombre est un nombre de Lychrel :
def lychrel(n):
for k in range(50):
if palyndrome(n+reverse(n)):
return False
else:
n+=reverse(n)
return True
# Fonction qui compte les nombres de Lychrel inferieurs a 10 000 :
def problem55():
k=0
for j in range(10**4):
if lychrel(j):
k+=1
return k
### Resultat: 249 |
20231208f853838967a1f7fe70fb0bbf9817ffee | pancakewaffles/Stuff-I-learnt | /Python Refresher/Python Math/2 Graphs, Gravitation, Projectile Motion, Fibonacci Visualised/fibo.py | 726 | 3.609375 | 4 | #! fibo.py
from matplotlib import pyplot as plt;
def fibo(n):
if(n==1):
return [1];
if(n==2):
return [1,1];
#n>2
a = 1;
b = 1;
series = [a,b];
for i in range(n):
c = a+b;
series.append(c);
a = b;
b = c;
return series;
def ratio(a,b):
return b/a;
def draw_graph(x,y):
plt.plot(x,y);
plt.xlabel("No.");
plt.ylabel("Ratio");
plt.title("Ratio between consecutive Fibonacci numbers");
plt.show();
n = 100000;
series = fibo(n);
list_of_ratios = [];
for i in range(len(series)-1):
r = ratio(series[i],series[i+1]);
list_of_ratios.append(r);
draw_graph(range(n+1),list_of_ratios);
|
af6827d046e27854cccd46e711094c19111d61a0 | Federico-PizarroBejarano/Don-Mills-Online-Judge | /Imperative French.py | 1,652 | 3.5 | 4 | first = ["le", "la", "les"]
second = ["moi", "toi", "nous", "vous", "lui", "leur"]
vowels = ("a", "e", "i", "o", "u", "y")
for i in range(int(raw_input())):
line = raw_input().split(":")
if line[0][-2:] == "er" and line[1][0:3] == " Tu" and line[1][-2:] == "s.":
line = line[1][0:-2].split()
else:
line = line[1][0:-1].split()
del line[0]
line = " ".join(line).replace("l'", "le ").split()
line = " ".join(line).replace("m'", "me ").split()
line = " ".join(line).replace("t'", "te ").split()
for i in range(len(line)):
if line[i] == "me":
line[i] = "moi"
elif line[i] == "te":
line[i] = "toi"
n1 = []
n2 = []
n3 = []
n4 = []
for i in line:
if i in first:
n1.append(i)
elif i in second:
n2.append(i)
elif i == "y":
n3.append(i)
elif i == "en":
n4.append(i)
newline = [line[-1].capitalize()] + n1 + n2 + n3 + n4
for i in range(len(newline)-1):
if newline[i] in ("le", "la") and newline[i+1][0] in vowels:
newline[i] = "DEL"
newline[i+1] = "l'" + newline[i+1]
if newline[i] in ("me", "moi") and newline[i+1][0] in vowels:
newline[i] = "DEL"
newline[i+1] = "m'" + newline[i+1]
if newline[i] in ("te", "toi") and newline[i+1][0] in vowels:
newline[i] = "DEL"
newline[i+1] = "t'" + newline[i+1]
newline[:] = [x for x in newline if x != "DEL"]
print "-".join(newline) + " !"
|
af32ed226a766a9d584bd21b6255e568c5cd28f7 | linshaoyong/leetcode | /python/divide_and_conquer/0932_beautiful_array.py | 644 | 3.765625 | 4 | class Solution(object):
def beautifulArray(self, N):
"""
:type N: int
:rtype: List[int]
"""
return self.divide_conquer(list(range(1, N + 1)))
def divide_conquer(self, arr):
if len(arr) < 3:
return arr
ls, hs = [], []
for i, v in enumerate(arr):
if i % 2 == 0:
hs.append(v)
else:
ls.append(v)
return self.divide_conquer(ls) + self.divide_conquer(hs)
def test_beautiful_array():
s = Solution()
assert [2, 4, 1, 3] == s.beautifulArray(4)
assert [2, 4, 3, 1, 5] == s.beautifulArray(5)
|
81326371f8653132e6a618ac0c61a89a75e92ec2 | deepika087/CompetitiveProgramming | /Leetcode_Challenge/Oct 1/Longest Palindrome.py | 1,245 | 3.859375 | 4 |
"""
95 test cases passed. Absolutely correct
"""
def longestPalindrome(s):
charcount = dict()
n = 0
for i in s:
if (charcount.get(i, -1) == -1):
charcount[i] = 1
n = 1
else:
charcount[i] = charcount[i] + 1
n = n + 1
print charcount
result = 0
taken = False #Because only one single occrence character can be taken
someExtraCanBeAdded = False
#print "Total number of element = ", n
if (len(charcount.items()) == 1):
return charcount.items()[0][1]
for (k, v) in charcount.items():
if (v % 2 ==0 ):
result = result + v
elif ( v %2 != 0 and v > 1):
result = result + (v - 1)
someExtraCanBeAdded = True # It means some character was ignored to keep it palin added for test case ababababa.
elif ( v%2 != 0 and v == 1 and not taken):
taken = True
result = result + 1
if ( not taken and someExtraCanBeAdded): #Added for test case ababababa
result = result + 1
return result
if __name__ == '__main__':
s = ["ccc"]
s.append("ababababa")
s.append("abccccdd")
for i in s:
print i , " " , longestPalindrome(i) |
ae2de45fbda1910e934523ddf26404e46486e349 | alvina2912/CodePython | /PlusMinus/PlusMinus.py | 564 | 3.796875 | 4 | #PlusMinus
#Given an array of integers, calculate which fraction of the elements are positive, negative, and zeroes, respectively.
#Print the decimal value of each fraction.
n=int(raw_input("Enter the limit"))
li=[]
for i in range(n):
num=raw_input()
li.append(num)
count=0
count1=0
count2=0
li=map(int, li)
for i in li:
if i==0:
count+=1
elif i>0:
count1+=1
elif i<0:
count2+=1
print li
print count1,round(float(count1)/n,6)
print count2,round(float(count2)/n,6)
print count,round(float(count)/n,6)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.