blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
294a14bbae4410c0e7de6f126adcd062a4fa0b87 | Brunochavesg/Guanabara | /ex006.py | 176 | 3.953125 | 4 | n1 = int(input("Digite um numero: "))
print (f'O numero digitado foi: {n1} o dobro de {n1} é {n1*2} o triplo de {n1} é {n1*3} e a raiz quadrada de {n1} é {n1**(1/2):.2f}')
|
5b5cf85f74b45e96ddb3eb6d249525ccb3e70f96 | PratikThakkar0/MATH_2305_Final-Project | /uhd_weighted_graphs/functions/Initial_Graph.py | 1,048 | 4.03125 | 4 | import networkx as nx
print('')
print("-----------------PRIM'S ALGORITHIM----------------")
print('')
print('--------------------------------------------------')
print('')
print('The available graphs to select are G1, G2, or G3')
print('')
print("Initialize Prim's Algorithim below")
print('')
print('--------------------------------------------------')
choose_graph = input('Select one of the graphs by typing either G1, G2, or G3 here: ')
# If the user selected G1 then it set the intial graph
if choose_graph == 'G1':
print('')
G = nx.read_weighted_edgelist('data/G1.txt',
nodetype = int)
# If the user selected G2 then it set the intial graph
if choose_graph == 'G2':
print('')
G = nx.read_weighted_edgelist('data/G2.txt',
nodetype = int)
# If the user selected G3 then it set the intial graph
if choose_graph == 'G3':
print('')
G = nx.read_weighted_edgelist('data/G3.txt',
nodetype = int)
|
c7997340fef4396d55f430c1c55ca148f62b4f6f | yukti99/Computer-Graphics | /LAB-4/perspective.py | 4,371 | 3.984375 | 4 | # PARALLEL-ORTHOGRAPHIC PROJECTION ON AN ARBITRARY PLANE IN 3-D COORDINATE SYSTEM
from graphics import *
import numpy as np
from math import *
# draw the 3-D coordinate axis
def drawAxis(win):
xaxis=Line(Point(-500,0),Point(500,0))
yaxis=Line(Point(0,-500),Point(0,500))
zaxis=Line(Point(300,300),Point(-500,-500))
xaxis.setOutline("Blue")
yaxis.setOutline("Blue")
zaxis.setOutline("Blue")
xaxis.draw(win)
yaxis.draw(win)
zaxis.draw(win)
xaxis.setArrow('both')
yaxis.setArrow('both')
zaxis.setArrow('both')
t=Text(Point(500-70,-20),"X-Axis")
t.draw(win)
t.setTextColor('blue')
t=Text(Point(-60,500-70),"Y-Axis")
t.draw(win)
t.setTextColor('blue')
t=Text(Point(-430,-380),"Z-Axis")
t.draw(win)
t.setTextColor('blue')
t=Text(Point(0,0),"(0,0)")
t.draw(win)
return win
def ShiftV(v,tx,ty,tz):
for i in range(len(v)):
v[i] = v[i][0]+tx,v[i][1]+ty,v[i][2]+tz
def drawLine(x1,y1,z1,x2,y2,z2,win,color):
a = x1-(z1*0.3)
b = y1-(z1*0.3)
c = x2-(z2*0.3)
d = y2-(z2*0.3)
line = Line(Point(a,b),Point(c,d));
line.setFill(color)
line.setWidth(2)
line.draw(win)
return win
def drawFigure(no,v1,v2,win):
k=0
colors = ["purple","firebrick","pink","darkcyan","darkgoldenrod","magenta","darkgreen","black","orangered","darkgrey","saddlebrown","midnightblue","red","coral","whitesmoke","navy"]
for i in range(no):
x1,y1,z1 = v1[i][0],v1[i][1],v1[i][2]
x2,y2,z2 = v2[i][0],v2[i][1],v2[i][2]
k = (k+1)%len(colors)
win = drawLine(x1,y1,z1,x2,y2,z2,win,colors[k])
return win
def projectionPoints(v):
P = []
for i in range(len(v)):
x,y,z = v[i]
x=(x*(a*n1+d)+y*a*n2+z*a*n3-a*(d1+d))/(x*n1+y*n2+z*n3-d1)
y=(y*(b*n2+d)+x*b*n1+z*b*n3-b*(d1+d))/(x*n1+y*n2+z*n3-d1)
z=(z*(c*n3+d)+y*c*n2+x*c*n1-c*(d1+d))/(x*n1+y*n2+z*n3-d1)
P.append([x,y,z])
return P
def p():
global a,b,c,d0,d1,n1,n2,n3,d
win = GraphWin("PERSPECTIVE PROJECTION",900,900)
win.setCoords(-500,-500,500,500)
drawAxis(win)
# take input from input file
f = open("projInput.txt")
no = int(f.readline().strip("\n"))
# list of all vertices
v1 = []
v2 = []
i=0
#print("The 3-D coordinates of the Figure : ")
while(i!=no):
pt = f.readline().strip('\n').split(" ")
x,y,z = int(pt[0]),int(pt[1]),int(pt[2])
x1,y1,z1 = int(pt[3]),int(pt[4]),int(pt[5])
v1.append([x,y,z])
v2.append([x1,y1,z1])
i+=1
win = drawFigure(no,v1,v2,win)
t=Text(Point(v1[0][0],v1[0][1]),"Fig1")
t.setTextColor('blue')
t.draw(win)
# translation
pt = f.readline().strip('\n').split(" ")
tx,ty,tz = int(pt[0]),int(pt[1]),int(pt[2])
ShiftV(v1,tx,ty,tz)
ShiftV(v2,tx,ty,tz)
# The normal of arbitrary plane
pt = f.readline().strip('\n').split(" ")
n1,n2,n3 = int(pt[0]),int(pt[1]),int(pt[2])
# Centre of projection
pt = f.readline().strip('\n').split(" ")
a,b,c = int(pt[0]),int(pt[1]),int(pt[2])
# the reference point lying on the arbitrary plane
pt = f.readline().strip('\n').split(" ")
x0,y0,z0 = int(pt[0]),int(pt[1]),int(pt[2])
d1 = a*n1 + b*n2 + c*n3
d0 = n1*x0 + n2*y0 + n3*z0
d = d0-d1
P1 = projectionPoints(v1)
P2 = projectionPoints(v2)
# Vanishing Point in the direction of a given vector-u
u1,u2,u3 = 2,3,4
k = u1*n1+u2*n2+u3*n3
xu = a+(d*u1)/k
yu = b+(d*u2)/k
zu = c+(d*u3)/k
print("Vanishing Point for this Perspective Transformation in given direction :")
print("xu = ",xu)
print("yu = ",yu)
print("zu = ",zu)
# calculating the vanishing points
if (n1==0 and n2==0 and n3==0):
print("NO VANISHING POINTS")
else:
print("PRINCIPLE VANISHING POINTS : ")
cnt=0
if (n1!=0):
cnt+=1
vpx1 = a+d/n1
vpy1 = b
vpz1 = c
print("Vanishing Point-",cnt," : ")
print("x = ",vpx1)
print("y = ",vpy1)
print("z = ",vpz1)
if (n2!=0):
cnt+=1
vpx2 = a
vpy2 = b+d/n2
vpz2 = c
print("Vanishing Point-",cnt," : ")
print("x = ",vpx2)
print("y = ",vpy2)
print("z = ",vpz2)
cnt+=1
if (n3!=0):
cnt+=1
vpx3 = a
vpy3 = b
vpz3 = c+d/n3
print("Vanishing Point-",cnt," : ")
print("x = ",vpx3)
print("y = ",vpy3)
print("z = ",vpz3)
print("This is a ",cnt,"-Point Perspective Projection")
win = drawFigure(no,P1,P2,win)
print("\n*************************************************************")
print("Mouse Click on the Graphics Window to continue !!!")
print("*************************************************************\n")
win.getMouse()
win.close()
|
45cca548dc60cc62036c8e69f54b785d534940fa | qwedsafgt/ex3.py | /ex00.py | 986 | 3.71875 | 4 | class CSV:
def __init__(self,filename,postfix,is_head):
self.filename=filename
self.postfix=postfix
self.is_head=is_head
def is_csv(self):
d=self.filename
b="csv"
if len(d and b )> 2:
return True
else:
return Flase
def is_head(self):
csvfile=open(filename,"r")
a=csvfile.read(0)
arr=a.split()
b=arr[0]
n=["Name","Age","No"]
if len(a and n) > 0:
return True
else:
return Flase
def read(self):
if self.is_csv():
if self.is_head:
csvfile=open(self.filename,"r")
a=csvfile.read()
arr=a.split()
for t in arr:
print(t)
else:
print("只能处理带头部文件")
else:
print("只能处理.csv后缀文件")
csv=CSV("ex0_sample.csv","csv",True)
csv.read()
|
210592aa34d35963b1c151a04f3264d1c5fc8ec3 | hadiyarajesh/LinearRegression-Samples | /SingleVariateLinearRegression.py | 2,186 | 3.765625 | 4 | import pandas as pd
import numpy as np
import seaborn as seaBorn
import matplotlib.pyplot as plot
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
# Load csv file into dataset
dataset = pd.read_csv("D://PYTHON/DATASETS/weather.csv")
print(dataset.shape)
print(dataset.describe())
# Plotting MinTemp vs MaxTemp to analyse pattern
dataset.plot(x='MinTemp', y='MaxTemp', style='o')
plot.title('MinTemp vs MaxTemp')
plot.xlabel('MinTemp')
plot.ylabel('MaxTemp')
plot.show()
# Plotting MaxTemp to analyse average value
plot.figure(figsize=(15,10))
plot.tight_layout()
seaBorn.distplot(dataset['MaxTemp'])
plot.show()
# X contains Independent variable and y contains dependent variable
X = dataset['MinTemp'].values.reshape(-1,1)
y = dataset['MaxTemp'].values.reshape(-1,1)
# Splitting data to 80% as training and 20% as test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Initializing LinearRegression object and training it on training data
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Printing intercept and coefficient
print('Intercept is ', regressor.intercept_)
print('Coefficient', regressor.coef_)
# Predicting output based on test data
y_predict = regressor.predict(X_test)
# Printing Actual vs Predicted data
df = pd.DataFrame({'Actual' : y_test.flatten(), 'Predicted' : y_predict.flatten()})
print(df)
# Getting top 25 value and plotting it
df1 = df.head(25)
df1.plot(kind='bar', figsize=(15,10))
plot.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plot.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plot.show()
# Plotting predicted data with linear line
plot.scatter(X_test, y_test, color='grey')
plot.plot(X_test, y_predict, color='red', linewidth=2)
plot.show()
print('Mean absolute error : ', metrics.mean_absolute_error(y_test, y_predict))
print('Mean squared error : ', metrics.mean_squared_error(y_test, y_predict))
print('Root mean squared error : ', np.sqrt(metrics.mean_squared_error(y_test,y_predict)))
|
b6a9b27955207810b5982b6bb0d206b7a781b25a | jyu001/New-Leetcode-Solution | /solved/347_top_k_frequent_elements.py | 867 | 3.828125 | 4 | '''
347. Top K Frequent Elements
DescriptionHintsSubmissionsDiscussSolution
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
'''
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
dct = {}
for i in range(len(nums)):
a = nums[i]
if a not in dct: dct[a] = 0
dct[a] += 1
count = 0
res = []
for w in sorted(dct, key = dct.get, reverse = True):
res.append(w)
count += 1
if count == k: return res |
2fb09efeb5609775cb51b801c1c222ba03d61816 | ChaoMneg/Offer-python3 | /字符串/String_Permutation.py | 1,019 | 3.734375 | 4 | # -*- coding:utf-8 -*-
"""
题目:字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路:
1、求第一个位置的字符
2、固定第一个字符,求后边所有字符的排列
"""
class Solution:
def Permutation(self, ss):
if len(ss) <= 1:
return ss
res = set()
# 遍历字符串,固定第一个元素,第一个元素可以取a,b,c...,然后递归求解
for i in range(len(ss)):
# 依次固定了元素,其他的全排列(递归求解)
for j in self.Permutation(ss[:i] + ss[i+1:]):
# 集合添加元素的方法add(),集合添加去重(若存在重复字符,排列后会存在相同,如baa,baa)
res.add(ss[i] + j)
return sorted(res) # sorted()能对可迭代对象进行排序,结果返回一个新的list
|
10498ee80c11b6d8c53e0f06c3d33320ff134b82 | abhisheksingh24/random_codes_i_ever_wrote | /Base Change.py | 799 | 3.890625 | 4 | alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#initializing dictionary as empty
val = {}
def repToDecimal(num, base):
#following loop fills in the value for each digit
for i in range(base):
val[alpha[i]] = i
# m here is pow(base, i)
# to avoid raising to power each time
# we multiply m with base in every iteration
m = 1
res = 0
# iterate string in reverse order so that LSB is read first
for i in num[: : -1]:
#dictionary val is used to get corresponding value of current digit
d = val[i.upper()]
res += d * m
m *= base
return res
def main():
print(repToDecimal('10', 10))
print(repToDecimal('10', 8))
print(repToDecimal('10', 2))
print(repToDecimal('10', 16))
main() |
b5ed2f39018616070250e9e6b5565bfcc32627d4 | thephong45/student-practices | /7_Pham_Hoang_Trung/Bai1.3.py | 149 | 4 | 4 |
Bob = input("Nhap vao ten Bob: ")
Alice = input("nhap vao ten Alice:")
if(Bob=="Bob" or Alice == "Alice"):
print("Chao Bob va Alice")
|
aaa147b552683f56ffb3cc7f8624648d005cf794 | bmihovski/soft_uni_python_adv | /polymorphism_lab/instruments_2.py | 552 | 3.71875 | 4 | class Guitar:
def play(self):
return "playing the guitar"
class Piano:
def play(self):
return "pianoto"
def play_instrument(obj: object):
return obj.play()
from unittest import TestCase
class InstrumentsTests(TestCase):
def test_guitar(self):
guitar: Guitar = Guitar()
self.assertEqual("playing the guitar", play_instrument(guitar))
def test_piano(self):
piano: Piano = Piano()
self.assertEqual("pianoto", play_instrument(piano))
if __name__ == 'main':
TestCase.main() |
36a1b326b865a92756c44f9924228b43061d3340 | emrehaskilic/pyt4585 | /introduction/odev1.py/odev1.py | 4,698 | 3.625 | 4 | print("""
*****************
*TELEFON REHBERİ*
*****************
------------------------------
- Kayıt Eklemek İçin : 1 -
- Kayıt Güncellemek İçin: 2 -
- Kayıt Listelemek için : 3 -
- Kayıt Aramak için : 4 -
- Kayıt Silmek için : 5 -
------------------------------
Tuşlayınız...
""")
rehber = [
{
"Id":1,
"İsim":"Emre",
"Soyisim" :"Haskılıç",
"Telefon" :"+905059796816",
"Mail" : "[email protected]"
}
]
i = 1
while i == 1: #KİŞİ EKLEME SEÇENEĞİ
soru = input("Lütfen yapmak istediğiniz işlemi seçiniz:")
if soru == "1":
id = len(rehber)+1
isim = input("İsim:")
soyisim = input("Soyisim:")
telefon = input("Telefon:")
mail = input("Mail:")
rehber.append(
{
"Id":id,
"İsim" :isim ,
"Soyisim" :soyisim,
"Telefon": telefon,
"Mail": mail
}
)
evethayir = str(input("kayıt başarıyla eklendi.✓ \n Devam etmek istiyor musunuz?:(E/H)"))
if evethayir.upper() == "H":
print("""
*************
* Güle Güle *
*************
""")
break
elif soru == "3": #KİŞİ LİSTELEME SEÇENEĞİ
for kisi in rehber:
print("ID:",kisi["Id"])
print("İsim:",kisi["İsim"])
print("Soyisim:",kisi["Soyisim"])
print("Telefon:",kisi["Telefon"])
print("Mail:",kisi["Mail"])
evethayir = str(input("Devam etmek istiyor musunuz?:(E/H)"))
if evethayir.upper() == "H":
print("""
*************
* Güle Güle *
*************
""")
break
elif soru == "5": #KİŞİ SİLME SEÇENEĞİ
for kisi in rehber:
print("ID:",kisi["Id"])
print("İsim:",kisi["İsim"])
print("Soyisim:",kisi["Soyisim"])
print("Telefon:",kisi["Telefon"])
print("Mail:",kisi["Mail"])
index = int(input("Silmek istediğiniz idyi seçiniz:"))
id = index -1
rehber.pop(id)
print("Kayıt Basarıyla Silindi ✓")
evethayir = str(input("\n Devam etmek istiyor musunuz?:(E/H)"))
if evethayir.upper() == "H":
print("""
*************
* Güle Güle *
*************
""")
break
elif soru == "2":
for kisi in rehber:
print("ID:",kisi["Id"])
print("İsim:",kisi["İsim"])
print("Soyisim:",kisi["Soyisim"])
print("Telefon:",kisi["Telefon"])
print("Mail:",kisi["Mail"])
index = int(input("Güncellemek istediğiniz idyi seçiniz:"))
id = index -1
isim = input(kisi["İsim"])
soyisim = input( kisi["Soyisim"])
telefon = input(kisi["Telefon"])
mail = input(kisi["Mail"])
kisi.update(
{
"İsim" :isim,
"Soyisim" :soyisim,
"Telefon": telefon,
"Mail": mail
}
)
evethayir = str(input("\n Devam etmek istiyor musunuz?:(E/H)"))
if evethayir.upper() == "H":
print("""
*************
* Güle Güle *
*************
""")
break
elif soru == "4": #KİŞİ ARAMA SEÇENEĞİ
for kisi in rehber:
name= input("Aramak istediğiniz İsmi Giriniz:")
if name in kisi["İsim"]:
print("ID:",kisi["Id"])
print("İsim:",kisi["İsim"])
print("Soyisim:",kisi["Soyisim"])
print("Telefon:",kisi["Telefon"])
print("Mail:",kisi["Mail"])
evethayir = str(input("\n Devam etmek istiyor musunuz?:(E/H)"))
if evethayir.upper() == "H":
print("""
*************
* Güle Güle *
*************
""")
else:
break
else:
print("Aradığınız Kayıt Bulunamadı")
break |
895bc8301266de7e094ca1c1fd3b4aa8a7d32d3f | tee24/LeetcodeProblems | /Jul 2020/11.07.2020 - 78. Subsets.py | 1,133 | 3.8125 | 4 | def subsets(nums):
output = [[]]
print(output)
for i in nums:
output+=[subset+[i] for subset in output]
return output
# Space, Time: O(N*2^N)
def subsets(nums):
powerset = []
for i in range((2**len(nums))):
subset_repr = bin(i)[2:].zfill(len(nums))
subset = []
for index, value in enumerate(subset_repr):
if value == '1':
subset.append(nums[index])
powerset.append(subset)
return powerset
class Solution:
def subsets(self, nums):
def backtrack(first=0, curr=[]):
if len(curr) == length:
output.append(curr[:])
for i in range(first, n):
curr.append(nums[i])
backtrack(i+1, curr)
curr.pop()
output = []
n = len(nums)
for length in range(n+1):
backtrack()
return output
from itertools import combinations
def powerset(s):
for i in range(0, len(s)+1):
for combination in combinations(s,i):
yield combination
x = powerset([1,2,3])
print(list(x))
|
582f773c72b4e857b96b4d416bfcf02159b88d2c | ramakrishnasonakam/Codewars-kata | /2sumII.py | 303 | 3.546875 | 4 | def twosum(arr, t):
arr = sorted(arr)
d = len(arr)
l=0
r=d-1
while l<r:
if arr[l]+arr[r]==t:
return (arr[l],arr[r])
elif arr[l]+arr[r] > t:
r-=1
else:
l+=1
arr = [1,2,3,4,5,6,7,7]
t = 8
print(twosum(arr, t))
|
1c594f1f365bd067e51bec7758b5c2452fe2b985 | t-yuhao/py | /基本语法/e1.py | 277 | 3.90625 | 4 | i = 5
print (i)
i = i + 1
print (i)
s = "This is a multi-line string.\
This is the second line."
print(s)
print('a', end=' ')
print('b')
print('{0:.3f}'.format(1.0/3))
print('{0:_^11}'.format('hello'))
print('{name} worte {book}'.format(name='TYH',book='A byte of python')) |
968fcdd45d4afa478257d0d6670f40afd8740128 | fhca/ProgramacionAvanzada_2018 | /ProgramaciónAvanzada2018/prueba_paradigmas.py | 382 | 3.65625 | 4 | __author__ = 'fhca'
# suma = 0
#
# for x in range(1, 101):
# suma = suma + x
#
# print("La suma es:", suma)
def sumatoria(a, b):
suma = 0
for x in range(a, b + 1):
suma = suma + x
print("La suma es:", suma)
# 20->30, 70->90, 110->300, 425->440, 12->900
sumatoria(20, 30)
sumatoria(70, 90)
sumatoria(110, 300)
sumatoria(425, 440)
sumatoria(12, 900)
|
4e8ee0ebd00bad7e997302f565b0a1884a967258 | borisbolsh/PyFunTasks | /1.2_MostCommonCharacter.py | 494 | 3.875 | 4 | # s = input("Enter any string: ")
s = "Llorem ipsum dollor sit amet, consectetur adipiscing ellit. Nullla ut ellit iacullis, ulltricies diam sit ametll, consecteturll magnall. Integer sodallles hendreritly orcil, nec pulllvinar orci euismod well."
dect = {}
ans = ''
anscnt = 0
for now in s:
if now not in dect:
dect[now] = 0
dect[now] += 1
if dect[now] > anscnt:
anscnt = dect[now]
ans = now
print("Most common character: %s (%d times)" % (ans, anscnt))
|
a74953a77467630a1cfea273f54334c738b70550 | AlanTurist/quadratic_equation | /details_def.py | 1,404 | 3.984375 | 4 | def detail(a, b, c, D):
if b == 0 and c == 0:
print("\nFor finding the solutions of the equation we must resolve:")
print("\n\t",a,"x^2 = 0")
elif b == 0:
if (a > 0 and c > 0) or (a < 0 and c < 0):
print('\n\tThe equation has no solutions..')
else:
print("\nFor finding the solutions of endless incomplete equation we must resolve:")
print("\n\tx_1,2 = √(-c / a)")
print("\n\tx_1,2 = +/- √(",-c,'/',a,")")
elif c == 0:
print("\nFor finding the solutions of incomplete equation we must resolve:")
print("\n\tx_1 = 0 and x_2 = -b / a")
print("\n\tx_1 = 0 and x_2 =",-b,"/",a)
elif a == 0:
print("\nIt doesn't exist quadratic equation with a = 0..")
elif D < 0:
print("\nThe equation has complex solutions..")
else:
print("\nFor finding the solutions we must resolve:")
print("\n\tx_1,2 = (-b -/+ √Δ) / 2*a, Δ = √((b^2) - 4 * a * c)")
if D == 0:
print("\n\tThe equation has double solution because Δ = 0:")
print("\n\tWe must resolve x_1,2 = -b / 2*a")
print("\n\tx_1,2 =",-b,"/ 2 *",a)
else:
print("\n\tΔ = √(",b**2," - 4*",a,"*",c,") = √",D)
print("\n\tx_1 =",-b,"- √",D,"/ 2 *",a)
print("\n\tx_2 =",-b,"+ √",D,"/ 2 *",a)
|
c812a666e1f15dc6945b6a229638eb628ed5cfe7 | Rositsazz/HackBulgaria-Programming0 | /week2/Simple Algorithms/twin_prime.py | 1,146 | 4.125 | 4 | number = input("Enter number: ")
number = int(number)
def is_prime_number (n):
start = 2
is_prime = True
if n == 1:
is_prime = False
while start < n:
if n % start == 0:
is_prime = False
break
start = start + 1
return is_prime
if is_prime_number(number)==True :
num2 = number + 2
num1 = number - 2
if is_prime_number(num2)==True and is_prime_number(num1)==True :
print("Twin primes with " + str(number) + ":")
print(num1,number)
print(number,num2)
elif is_prime_number(num2)==False and is_prime_number(num1)==False :
print(str(number) + " is prime but:")
print(str(num1)+" and " + str(num2)+ " are not " )
elif is_prime_number(num2)==False and is_prime_number(num1)==True :
print(str(number) + " is prime but:")
print(str(num1)+"is not and " + str(num2)+ " is " )
elif is_prime_number(num2)==True and is_prime_number(num1)==False :
print(str(number) + " is prime but:")
print(str(num2)+"is not and " + str(num1)+ " is " )
else :
print(str(number)+ " is not prime")
|
982c36d530f52c70d75dc5db09d47dcba57338ec | ciesielskiadam98/pp1 | /06-ClassesAndObjects/z14.py | 1,388 | 3.546875 | 4 | class TV():
def __init__(self):
self.is_on = False
self.channel_no = 1
self.channels = []
def on(self):
self.is_on = True
def off(self):
self.is_on = False
def show_status(self):
if self.is_on == True and self.channel_no <= len(self.channels):
print("Telewizor jest załączony, kanał {} ({})".format(int(self.channel_no), self.channels[self.channel_no-1]))
elif self.channel_no > len(self.channels):
print("Telewizor jest załączony, kanał {}".format(int(self.channel_no)))
else:
print("Telewizor jest wyłączony")
def set_channel(self, new_channel_no):
self.channel_no = new_channel_no
def set_channels(self, channels_list):
self.channels = channels_list
def show_channels(self):
print('LISTA KANAŁÓW TV')
for i in range(len(self.channels)):
print("{}. {}".format(i+1, self.channels[i]))
tv1 = TV()
tv1.on()
tv1.set_channels(['TVP1', 'TVP2', 'TVN', 'Polsat', 'TVP3', 'Filmbox', 'TTV'])
tv1.show_status()
tv1.set_channel(2)
tv1.show_status()
tv1.set_channel(3)
tv1.show_status()
tv1.set_channel(4)
tv1.show_status()
tv1.set_channel(5)
tv1.show_status()
tv1.set_channel(6)
tv1.show_status()
tv1.set_channel(7)
tv1.show_status()
tv1.set_channel(8)
tv1.show_status()
|
967c8e042a9055e9fe1973b60925d2c14b6ae66a | nvishwan/Price-Prediction-for-Used-Cars | /Price Prediction Model & Exploring Key Business Insights.py | 18,871 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Step-1 Reading and Understanding Data
# 1)Importing data using the pandas library
# 2)Understanding the structure of the data
# In[127]:
# !pip install numpy
# !pip install pandas
# !pip install matplotlib
# !pip install dataprep
# !pip install sklearn
# !pip install seaborn
# !pip install xgboost
# ## Importing the Libraries
# In[128]:
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from dataprep.eda import create_report
# ## Load data into the data frame
# In[129]:
data = pd.read_csv("C:\\Users\\vishw\\OneDrive\\Desktop\\vehicles.csv")
data.head()
# ## The above dataset is a Vehicle Dataset for 1 month . Main task in this project is to build a Price Prediction Model for various different cars
# ## No. of rows and columns in the dataframe intially
# In[130]:
data.shape
# ## Checking no. of rows and datatype of every column
# In[131]:
data.info()
# In[132]:
data.dtypes
# ## No. of Null Values in every column in the dataframe
# In[133]:
print('Null Values')
print(data.isnull().sum())
# # Step-2 Data Cleaning and Preparation
# ## Checking the duplicate rows in the dataframe
# In[134]:
data.loc[data.duplicated()]
# ## No. of Column with different features
# In[135]:
data.columns
# ## Missing percentage of data for various features
# In[136]:
miss_percent = (data.isnull().sum() / len(data)) * 100
missing = pd.DataFrame({"percent":miss_percent, 'count':data.isnull().sum()}).sort_values(by="percent", ascending=False)
missing.loc[missing['percent'] > 0]
# ## #Removing columns: Passengers, carfax_url, engine, vin, description, trim, province
# In[137]:
data.drop(['passengers', 'carfax_url','engine','vin','description','trim','province'], axis=1, inplace=True)
# ## Removing rows with missing price, year, mileage, drivetrain, transmission, fuel_type
# In[138]:
data.drop(data[data['price'].isna()].index, inplace = True)
data.drop(data[data['year'].isna()].index, inplace = True)
data.drop(data[data['mileage'].isna()].index, inplace = True)
data.drop(data[data['drivetrain'].isna()].index, inplace = True)
data.drop(data[data['transmission'].isna()].index, inplace = True)
data.drop(data[data['fuel_type'].isna()].index, inplace = True)
# ## No. of rows and columns in the dataset after cleaning
# In[139]:
data.shape
# In[140]:
data.head()
# ## Feature Engineering
# ## Calculating difference with first_date_seen and last_date_seen i.e. car arrived and sold/unsold
# In[141]:
data['first_date_seen'] = pd.to_datetime(data['first_date_seen'])
data['last_date_seen'] = pd.to_datetime(data['last_date_seen'])
data['Difference'] = abs(data['first_date_seen'] - data['last_date_seen']).dt.days
# ## Creating age of car from year i.e. car manufactured date
# In[142]:
data['age_of_car'] = 2021 - data['year']
# In[143]:
data.head()
# ## Car Situation i.e. whether the car is sold/unsold based on last_date_seen
# In[144]:
data['Car_situation'] = np.where(data['last_date_seen'] == '2021-05-03' , 'Unsold', 'Sold')
# ## Removing featuress: id, first_date_seen, last_date_seen, model, color, seller_name for model creation
# In[145]:
data.drop(['id', 'first_date_seen','last_date_seen','model','color','seller_name'], axis=1, inplace=True)
# ## Removing Outliers from the data on the basis of years (considering years from 2000 to 2021)
# In[146]:
data = data[data['year'] >= 2000]
data = data[data['year'] <= 2021]
data.shape
# ## Grouping transmission column into Automatic and Manual
# In[147]:
data['transmission'] = data['transmission'].str.replace(r'(^.*Automatic.*$)', 'Automatic')
data['transmission'] = data['transmission'].str.replace(r'(^.*CVT.*$)', 'Automatic')
data['transmission'] = data['transmission'].str.replace(r'(^.*Manual.*$)', 'Manual')
data['transmission'] = data['transmission'].str.replace(r'(^.*Sequential.*$)', 'Manual')
# ## Grouping Fuel Types into Gasoline, Hybrid, Electric, Diesel, Others
# In[148]:
data['fuel_type'] = data['fuel_type'].str.replace(r'(^.*Hybrid.*$)', 'Hybrid')
data['fuel_type'] = data['fuel_type'].str.replace(r'(^.*Gas.*$)', 'Gasoline')
data['fuel_type'] = data['fuel_type'].str.replace(r'(^.*Unleaded.*$)', 'Gasoline')
data['fuel_type'] = data['fuel_type'].str.replace(r'(^.*Flexible.*$)', 'Gasoline')
data['fuel_type'] = data['fuel_type'].str.replace(r'(^.*Other.*$)', 'Other')
# ## Grouping Seller Name into Private Seller and Other Seller
# In[149]:
data['seller_type'] = np.where(data['is_private'] == True, 'Private Seller', 'Other Seller')
# ## Dropping feature: is_private after classifying into binary
# In[150]:
data.drop(['is_private'], axis=1, inplace=True)
# ## Grouping various body types of cars
# In[151]:
data['body_type'] = data['body_type'].str.replace(r'(^.*Truck.*$)', 'Truck')
data['body_type'] = data['body_type'].str.replace(r'(^.*Cab.*$)', 'Cab')
data['body_type'] = data['body_type'].str.replace(r'(^.*Wagon.*$)', 'Wagon')
data[['body_type']] = data[['body_type']] .replace(['Compact','Sedan'],'Sedan')
data[['body_type']] = data[['body_type']] .replace(['Super Crew','Roadster','Avant','Cutaway'],'Others')
# ## Grouping drivetrains feature of cars
# In[152]:
data['drivetrain'] = data['drivetrain'].str.replace(r'(^.*4.*$)', '4WD')
# ## Finding no. of missing values in the dataset
# In[153]:
miss_percent = (data.isnull().sum() / len(data)) * 100
missing = pd.DataFrame({"percent":miss_percent, 'count':data.isnull().sum()}).sort_values(by="percent", ascending=False)
missing.loc[missing['percent'] > 0]
# ## Removing missing values from the dataset
# In[154]:
data = data.dropna(how='any',axis=0)
# ## No. of rows and columns in the dataset after cleaning
# In[155]:
data.shape
# ## Though there are 108 Duplicate rows but cannot be removed because there can be multiple cars with same features after cleaning the data or dealer might have multiple cars
# In[156]:
data.duplicated().sum()
# ## Calculating Price Percentiles to categorize in 'Low','Medium' and 'High' Groups
# In[157]:
print(data.price.describe(percentiles = [0.25,0.33,0.67,0.85,0.90,1]))
# ## Removing Outliers with price <= 1500
# In[158]:
data = data[data['price'] >= 1500]
# In[159]:
#Grouping Price
data['price_category'] = data['price'].apply(lambda x : "Low" if x < 15000
else ("Medium" if 15000 <= x < 30000
else "High"))
# ## Calculating Mileage Percentiles to categorize in 'Low','Medium' and 'High' Groups
# In[160]:
print(data.mileage.describe(percentiles = [0.25,0.50,0.75,0.85,0.90,1]))
# ## Mileage data is divided into three category using priori
# In[161]:
data['mileage_category'] = data['mileage'].apply(lambda x : "Low" if x < 100000
else ("Medium" if 100000 <= x < 200000
else "High"))
# ## No. of rows and columns in the dataset after adding Price_Category and Mileage_Category
# In[162]:
data.shape
data.head()
# ## Quick Exploratory Data Analysis Report with Overview, Interactions, Correlations, Missing Values
# #### Before applying models, looking at the features and also relationship with each other by visualization of data.
# In[163]:
create_report(data)
# ## Key Findings:
# 1)Correlation between Price and Mileage according to Pearson test is 0.37 i.e. moderate relationship.
# 2)Correlation between Price and Age of Car according to Pearson test is 0.39 i.e. moderate relationship.
# 3)Correlation between Age of Car and Mileage according to Pearson test is 0.65 i.e. Strong relationship.
# # Step-3 Exploratory Data Analysis
# ## Finding relationship between Price and Mileage in the dataset
# In[164]:
plt1 = sns.scatterplot(x = 'mileage', y = 'price', data = data)
plt1.set_xlabel('Mileage')
plt1.set_ylabel('Price of Car (Dollars)')
plt.show()
# # Visualizing the data
# ## Finding the distribution of Price and Mileage by creating Distribution Plot
# In[165]:
plt.figure(figsize=(16,4))
plt.subplot(1, 3, 1)
#Distribution plot for Price
axis = sns.distplot(data['price'], color = 'red')
plt.title("Distribution plot for Price")
plt.subplot(1, 3, 2)
#Distribution plot for Mileage
axis = sns.distplot(data['mileage'], color='limegreen')
plt.title("Distribution plot for Mileage")
# #### Findings:
# 1) The plot seems to be right skewed i.e. most prices in the dataset are low.
# 2) There is a significant difference between the mean and median of the price distribution.
# ## Creating Body Class v/s Price plot and Drivetrain v/s Price plot
# In[166]:
#Body Class v/s Price
axis = sns.barplot(x="body_type", y="price", data=data)
for i in axis.patches:
axis.annotate("%.f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='right', va='center', fontsize=11, color='black', xytext=(0, 25), rotation = 90,
textcoords='offset points')
plt.xticks(rotation=45, horizontalalignment='right')
plt.xlabel('Body Classes')
plt.ylabel('Price')
plt.title('Average Price across various Body Types')
plt.show()
#Drive Train Class v/s Price
axis = sns.barplot(x="drivetrain", y="price", data=data)
for i in axis.patches:
axis.annotate("%.f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, -50),
textcoords='offset points')
plt.xlabel('Drive Train Classes')
plt.ylabel('Price')
plt.title('Average Price across various Drive Trains')
plt.show()
# ## Creating Transmission v/s Price plot and Sellers v/s Price plot
# In[167]:
#Transmission v/s Price
axis = sns.barplot(x="transmission", y="price", data=data)
for i in axis.patches:
axis.annotate("%.f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, 7),
textcoords='offset points')
plt.xlabel('Transmission Classes')
plt.ylabel('Price')
plt.title('Transmission w.r.t Price')
plt.show()
#Sellers v/s Price
axis = sns.barplot(x="seller_type", y="price", data=data)
for i in axis.patches:
axis.annotate("%.f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, 5),
textcoords='offset points')
plt.xlabel('Seller Classes')
plt.ylabel('Price')
plt.title('Sellers w.r.t Price')
plt.show()
# ## Creating Body Class v/s Mileage and Drivetrain Class v/s Mileage plot
# In[168]:
#Body Class v/s Mileage
#plt.rcParams["figure.figsize"] = (20,3)
axis = sns.barplot(x="body_type", y="mileage", data=data)
for i in axis.patches:
axis.annotate("%.0f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, -60), rotation = 90,
textcoords='offset points')
plt.xticks(rotation=45, horizontalalignment='right')
plt.xlabel('Body Classes')
plt.ylabel('Mileage')
plt.title('Mileage across various Body Types')
plt.show()
#Drive Train Class v/s Mileage
axis = sns.barplot(x="drivetrain", y="mileage", data=data)
for i in axis.patches:
axis.annotate("%.0f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, -70), rotation = 90,
textcoords='offset points')
plt.xlabel('Drive Train Classes')
plt.ylabel('Mileage')
plt.title('Mileage across various Drive Trains')
plt.show()
# ## Creating Transmission v/s Mileage and Sellers v/s Mileage plot
# In[169]:
#Transmission v/s Mileage
axis = sns.barplot(x="transmission", y="mileage", data=data)
for i in axis.patches:
axis.annotate("%.0f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, 10),
textcoords='offset points')
plt.xlabel('Transmission Classes')
plt.ylabel('Mileage')
plt.title('Transmission w.r.t Mileage')
plt.show()
#Sellers v/s Mileage
axis = sns.barplot(x="seller_type", y="mileage", data=data)
for i in axis.patches:
axis.annotate("%.0f" % i.get_height(), (i.get_x() + i.get_width() / 2., i.get_height()),
ha='center', va='center', fontsize=11, color='black', xytext=(0, 5),
textcoords='offset points')
plt.xlabel('Seller Classes')
plt.ylabel('Mileage')
plt.title('Sellers w.r.t Mileage')
plt.show()
# In[170]:
# Number of cars in different Price Category.
plt.figure(figsize=(16,4))
plt.subplot(1, 2, 1)
axis = sns.countplot(x="price_category", data=data)
for i in axis.patches:
h = i.get_height()
axis.text(i.get_x()+i.get_width()/2.,h+10,
'{:1.0f}%'.format(h/len(data)*100),ha="center",fontsize=10)
plt.xlabel('Price Classes')
plt.ylabel('Number of Cars')
plt.title('Number of cars in different Price Category')
plt.show()
# Number of cars in different Mileage Category
plt.subplot(1, 2, 2)
axis = sns.countplot(x="mileage_category", data=data)
for i in axis.patches:
h = i.get_height()
axis.text(i.get_x()+i.get_width()/2.,h+10,
'{:1.0f}%'.format(h/len(data)*100),ha="center",fontsize=10)
plt.xlabel('Mileage Classes')
plt.ylabel('Number of Cars')
plt.title('Number of cars in different Mileage Category')
plt.show()
# ## No. of cars w.r.t Fuel Classes
# In[171]:
#No. of cars w.r.t Fuel Classes
axis = sns.countplot(x="fuel_type", data=data)
for i in axis.patches:
h = i.get_height()
axis.text(i.get_x()+i.get_width()/2.,h+10,
'{:1.2f}%'.format(h/len(data)*100),ha="center",fontsize=10)
plt.xlabel('Fuel Classes')
plt.ylabel('No. of Cars with particular fuel types')
plt.title('Number of cars w.r.t Fuel Classes')
plt.show()
# ## #Top 20 cars w.r.t Car Types
# In[172]:
axis = sns.countplot(x="make", data=data,order=data.make.value_counts().iloc[:20].index)
for i in axis.patches:
h = i.get_height()
axis.text(i.get_x()+i.get_width()/2.,h+10,
'{:1.0f}%'.format(h/len(data)*100),ha="center",fontsize=10,rotation = 45)
plt.xlabel('Car Types')
plt.xticks(rotation=90)
plt.ylabel('No. of Cars')
plt.title('Number of cars w.r.t Car Types')
plt.show()
# ## Top 20 cities with most cars
# In[173]:
axis = sns.countplot(x="city", data=data,order=data.city.value_counts().iloc[:20].index)
for i in axis.patches:
h = i.get_height()
axis.text(i.get_x()+i.get_width()/2.,h+10,
'{:1.0f}%'.format(h/len(data)*100),ha="center",fontsize=10, rotation = 15)
plt.xlabel('City Names')
plt.xticks(rotation=90)
plt.ylabel('No. of Cars')
plt.title('Number of cars w.r.t City Names')
plt.show()
#
# In[174]:
#data.to_csv(r'C:/Users/vishw/OneDrive/Desktop/try.csv')
# # Model Building
# ## Importing sklearn Library for Model Building and applying functions for fitting the models
# In[175]:
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score,KFold
from sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error
from sklearn.linear_model import LinearRegression
from sklearn import metrics, model_selection
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import GridSearchCV
# ## Creating a dataframe by copying previous dataframe
# In[176]:
df = data.copy()
# ## Creating target and feature variables from the dataframe
# In[177]:
target = data['price']
# In[178]:
feature = df.drop(['year','mileage_category','price','city','longitude','latitude','Difference','price_category'], axis=1)
# ## Performing One Hot encoding on the feature variables for creating training dataset
# In[179]:
feature = pd.get_dummies(feature)
feature.head()
# In[180]:
features=feature.values
target=target.values
# ## Split data in training and testing data in 80-20 form by random allocation:
# In[181]:
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# ## RandomForesting
# In[182]:
RF_regressor=RandomForestRegressor(n_estimators=200,random_state=42,max_depth = 9)
RF_regressor.fit(X_train,y_train)
target_predict=RF_regressor.predict(X_test)
# In[183]:
def printAccuracy(regressor):
print("R2 score of training data: ",r2_score(y_train,regressor.predict(X_train)))
print("R2 score of testing data: ",r2_score(y_test, target_predict))
print("Mean Square error of training data: ",mean_squared_error(y_train,regressor.predict(X_train)))
print("Mean Square error of testing data: ",mean_squared_error(y_test, target_predict))
print("Mean absolute error of training data: ",mean_absolute_error(y_train,regressor.predict(X_train)))
print("Mean Absolute error of testing data: ",mean_absolute_error(y_test, target_predict))
# In[184]:
printAccuracy(RF_regressor)
# ## Checking important features generated in the dataset using Random Forest
# In[185]:
plt.figure(figsize=[12,6])
feat_importances = pd.Series(RF_regressor.feature_importances_, index=feature.columns)
feat_importances.nlargest(36).plot(kind='barh')
plt.show()
# ## XG Boost
# In[186]:
import xgboost as xgb
# In[187]:
xgBoost_regressor = xgb.XGBRegressor(colsample_bytree=1,
learning_rate=0.01,
max_depth=9,
n_estimators=250,
seed=42)
xgBoost_regressor.fit(X_train,y_train)
target_predict=xgBoost_regressor.predict(X_test)
# In[188]:
printAccuracy(xgBoost_regressor)
# ## Understanding Feature Importance for XG Boost
# In[189]:
plt.figure(figsize=[12,6])
feat_importances = pd.Series(xgBoost_regressor.feature_importances_, index=feature.columns)
feat_importances.nlargest(36).plot(kind='barh')
plt.show()
# # Conclusion
# #### 1) Applying Random Forest and XG Boost on the dataset because we are predicting price with nearly 86 features so other algorithms would not fulfil the purpose.
# #### 2) As the test accuracy and train accuracy are pretty similar for both the models so it is neither underfitting nor overfitting.
# # Future Scope
# #### 1) Perform Hyperparameter Tuning while selecting the parameter for Random Forest and XG Boost.
# #### 2) Train the model using Neural Networks.
#
|
ea8ad9636da1a925264c55c553bc3070ec5b1f2a | ardaunal4/My_Python_Lessons | /classes.py | 1,401 | 4.0625 | 4 | import datetime
# class user:
# pass # passes line and that does nothing
# user1 = user() # object
# user1.first_name = "AHmet"
# user1.last_name = "Besr"
# print(user1.first_name)
# first_name = 'Arthur'
# second_name = 'Clark'
# user2 = user()
# user2.first_name, user2.second_name = first_name, second_name
# print(user2.first_name)
#Class Features
class User:
""" Docstring explains the duty of class here when class call with help function"""
#try with help(user)
def __init__(self, full_name, birthday): #initialization function
self.name = full_name
# left birthday represents field that stores the value and right birthday user input
self.birthday = birthday #yyyymmdd
# Extract first and last names
name_pieces = full_name.split(" ")
self.first_name = name_pieces[0]
self.last_name = name_pieces[-1]
def age(self):
"""Return age of user in years."""
today = datetime.date(2001, 5, 12)
yyyy = self.birthday[0:4]
mm = int(self.birthday[4:6])
dd = int(self.birthday[6:8])
dob = datetime.date(int(yyyy), mm, dd)
age_in_days = (today - dob).days
age_in_years = age_in_days / 365
return int(age_in_years)
user = User("Dave Bowman", 19710315)
print(user.name)
print(user.first_name)
print(user.last_name)
print(user.birthday)
print(user.age())
|
2790d78b07aed0ae98a159a11ac5ae5cbf7b76ce | vikingliu/alg | /classic/sqrt.py | 697 | 3.96875 | 4 | # coding=utf-8
e = 1e-15
def sqrt(n):
left = 0
right = n
cnt = 0
while True:
mid = (left + right) / 2.0
x = mid ** 2
delta = abs(n - x)
if delta < e:
break
if x > n:
right = mid
elif x == n:
break
else:
left = mid
cnt += 1
return mid
def newton_sqrt(n):
"""
f(x) = x^2 - n
f'(x) = 2x
xn+1 = xn - f(xn)/f'(xn)
= xn - (xn^2 - n)/2xn
= (xn + n/xn)/2
:param n:
:return:
"""
xn = n
cnt = 0
while abs(xn ** 2 - n) > e:
xn = (xn + n / xn) / 2.0
cnt += 1
return xn
print(newton_sqrt(2))
|
48852a789d3ecebe67d46557f1f34df2bd29f13b | avinashn/programminginpython.com | /number_reverse.py | 341 | 4.1875 | 4 | __author__ = 'Avinash'
input_num = (input("Enter any number: "))
reverse = 0
try:
val = int(input_num)
while val > 0:
reminder = val % 10
reverse = (reverse * 10) + reminder
val //= 10
print('Reverse of given number is : ', reverse)
except ValueError:
print("That's not a valid number, Try Again !")
|
45960acc8eff5c434b300e34996c8ea444560044 | Kepler-XX/Codeself_py | /kepler/demo/case1.py | 45,164 | 3.53125 | 4 | # 100到练习题
"""实例001:数字组合
题目 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析 遍历全部可能,把有重复的剃掉。"""
# 第一种方式
total = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if ((i != j) and (j != k) and (k != i)):
print(i, j, k)
total += 1
print(total)
# 第二种方式
import itertools
sum2 = 0
a = [1, 2, 3, 4]
for i in itertools.permutations(a, 3):
print(i)
sum2 += 1
print(sum2)
"""实例002:“个税计算”
题目 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
20万到40万之间时,高于20万元的部分,可提成5%;
40万到60万之间时高于40万元的部分,可提成3%;
60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,
从键盘输入当月利润I,求应发放奖金总数?
程序分析 分区间计算即可。"""
profit = int(input('Show me the money: '))
bonus = 0
thresholds = [100000, 100000, 200000, 200000, 400000]
rates = [0.1, 0.075, 0.05, 0.03, 0.015, 0.01]
for i in range(len(thresholds)):
if profit <= thresholds[i]:
bonus += profit*rates[i]
profit = 0
break
else:
bonus += thresholds[i]*rates[i]
profit -= thresholds[i]
bonus += profit*rates[-1]
print(bonus)
"""实例003:完全平方数
题目
一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
程序分析
因为168对于指数爆炸来说实在太小了,所以可以直接省略数学分析,用最朴素的方法来获取上限:"""
n = 0
while (n + 1) ** 2 - n * n <= 168:
n += 1
print(n + 1)
"""思路是:最坏的结果是n的平方与(n + 1)
的平方刚好差168,由于是平方的关系,不可能存在比这更大的间隙。
至于判断是否是完全平方数,最简单的方法是:平方根的值小数为0即可。
结合起来:"""
n = 0
while (n + 1) ** 2 - n * n <= 168:
n += 1
for i in range((n + 1) ** 2):
if i ** 0.5 == int(i ** 0.5) and (i + 168) ** 0.5 == int((i + 168) ** 0.5):
print(i - 100)
"""实例004:这天第几天
题目
输入某年某月某日,判断这一天是这一年的第几天?
程序分析
特殊情况,闰年时需考虑二月多加一天:"""
def isLeapYear(y):
return (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0))
DofM = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
res = 0
year = int(input('Year:'))
month = int(input('Month:'))
day = int(input('day:'))
if isLeapYear(year):
DofM[2] += 1
for i in range(month):
res += DofM[i]
print(res + day)
"""实例005:三数排序
题目
输入三个整数x, y, z,请把这三个数由小到大输出。
程序分析
练练手就随便找个排序算法实现一下,偷懒就直接调函数。"""
raw = []
for i in range(3):
x = int(input('int%d: ' % (i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i, len(raw)):
if raw[i] > raw[j]:
raw[i], raw[j] = raw[j], raw[i]
print(raw)
raw2 = []
for i in range(3):
x = int(input('int%d: ' % (i)))
raw2.append(x)
print(sorted(raw2))
"""实例006:斐波那契数列
题目
斐波那契数列。
程序分析
斐波那契数列(Fibonaccisequence),从1, 1
开始,后面每一项等于前面两项之和。图方便就递归实现,图性能就用循环。"""
# 递归实现
def Fib(n):
return 1 if n <= 2 else Fib(n - 1) + Fib(n - 2)
print(Fib(int(input())))
# 简单实现
target = int(input())
res = 0
a, b = 1, 1
for i in range(target - 1):
a, b = b, a + b
print(a)
"""实例007:copy
题目
将一个列表的数据复制到另一个列表中。
程序分析
使用列表[:],拿不准可以调用copy模块。"""
import copy
a = [1, 2, 3, 4, ['a', 'b']]
b = a # 赋值
c = a[:] # 浅拷贝
d = copy.copy(a) # 浅拷贝
e = copy.deepcopy(a) # 深拷贝
a.append(5)
a[4].append('c')
print('a=', a)
print('b=', b)
print('c=', c)
print('d=', d)
print('e=', e)
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c = [1, 2, 3, 4, ['a', 'b', 'c']]
d = [1, 2, 3, 4, ['a', 'b', 'c']]
e = [1, 2, 3, 4, ['a', 'b']]
"""实例008:九九乘法表
题目
输出9 * 9乘法口诀表。
程序分析
分行与列考虑,共9行9列,i控制行,j控制列。"""
for i in range(1, 10):
for j in range(1, i + 1):
print('%d*%d=%2ld ' % (i, j, i * j), end='')
print()
"""实例009:暂停一秒输出
题目
暂停一秒输出。
程序分析
使用time模块的sleep()函数。"""
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)
"""实例010:给人看的时间
题目
暂停一秒输出,并格式化当前时间。
程序分析
同009."""
import time
for i in range(4):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
time.sleep(1)
"""实例011:养兔子
题目
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析
我认为原文的解法有点扯,没有考虑3个月成熟的问题,人家还是婴儿怎么生孩子?考虑到三个月成熟,可以构建四个数据,其中:一月兔每个月长大成为二月兔,二月兔变三月兔,三月兔变成年兔,成年兔(包括新成熟的三月兔)生等量的一月兔。
"""
month = int(input('繁殖几个月?:'))
month_1 = 1
month_2 = 0
month_3 = 0
month_elder = 0
for i in range(month):
month_1, month_2, month_3, month_elder = month_elder + month_3, month_1, month_2, month_elder + month_3
print('第%d个月共' % (i + 1), month_1 + month_2 + month_3 + month_elder, '对兔子')
print('其中1月兔:', month_1)
print('其中2月兔:', month_2)
print('其中3月兔:', month_3)
print('其中成年兔:', month_elder)
"""实例012:
100到200的素数
题目
判断101 - 200之间有多少个素数,并输出所有素数。
程序分析
判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。用else可以进一步简化代码."""
import math
for i in range(100, 200):
flag = 0
for j in range(2, round(math.sqrt(i)) + 1):
if i % j == 0:
flag = 1
break
if flag:
continue
print(i)
print('\nSimplify the code with "else"\n')
for i in range(100, 200):
for j in range(2, round(math.sqrt(i)) + 1):
if i % j == 0:
break
else:
print(i)
"""实例013:所有水仙花数
题目
打印出所有的
"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153
是一个"水仙花数",因为153 = 1的三次方+5的三次方+3的三次方。
程序分析
利用for循环控制100 - 999
个数,每个数分解出个位,十位,百位。"""
for i in range(100, 1000):
s = str(i)
one = int(s[-1])
ten = int(s[-2])
hun = int(s[-3])
if i == one ** 3 + ten ** 3 + hun ** 3:
print(i)
"""实例014:分解质因数
题目
将一个整数分解质因数。例如:输入90, 打印出90 = 233 * 5。
程序分析
根本不需要判断是否是质数,从2开始向数本身遍历,能整除的肯定是最小的质数。"""
target = int(input('输入一个整数:'))
print(target, '= ', end='')
if target < 0:
target = abs(target)
print('-1*', end='')
flag = 0
if target <= 1:
print(target)
flag = 1
while True:
if flag:
break
for i in range(2, int(target + 1)):
if target % i == 0:
print("%d" % i, end='')
if target == i:
flag = 1
break
print('*', end='')
target /= i
break
"""实例015:分数归档
题目
利用条件运算符的嵌套来完成此题:学习成绩 >= 90分的同学用A表示,
60 - 89分之间的用B表示,
60分以下的用C表示。
程序分析
用条件判断即可。"""
points = int(input('输入分数:'))
if points >= 90:
grade = 'A'
elif points < 60:
grade = 'C'
else:
grade = 'B'
print(grade)
"""实例016:输出日期
题目
输出指定格式的日期。
程序分析
使用datetime模块。"""
import datetime
print(datetime.date.today())
print(datetime.date(2333, 2, 3))
print(datetime.date.today().strftime('%d/%m/%Y'))
day = datetime.date(1111, 2, 3)
day = day.replace(year=day.year + 22)
print(day)
"""实例017:字符串构成
题目
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析
利用while 或 for 语句, 条件为输入的字符不为 ‘\n’。"""
string = input("输入字符串:")
alp = 0
num = 0
spa = 0
oth = 0
for i in range(len(string)):
if string[i].isspace():
spa += 1
elif string[i].isdigit():
num += 1
elif string[i].isalpha():
alp += 1
else:
oth += 1
print('space: ', spa)
print('digit: ', num)
print('alpha: ', alp)
print('other: ', oth)
"""实例018:复读机相加
题目
求s = a + aa + aaa + aaaa + aa…a的值,其中a是一个数字。例如2 + 22 + 222 + 2222 + 22222(此时共有5个数相加),几个数相加由键盘控制。
程序分析
用字符串解决。"""
a = input('被加数字:')
n = int(input('加几次?:'))
res = 0
for i in range(n):
res += int(a)
a += a[0]
print('结果是:', res)
"""实例019:完数
题目
一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6 = 1+2+3.编程找出1000以内的所有完数。
程序分析
将每一对因子加进集合,在这个过程中已经自动去重。最后的结果要求不计算其本身。"""
def factor(num):
target = int(num)
res = set()
for i in range(1, num):
if num % i == 0:
res.add(i)
res.add(num / i)
return res
for i in range(2, 1001):
if i == sum(factor(i)) - i:
print(i)
"""实例020:高空抛物
题目
一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
程序分析
无"""
high = 200.
total = 100
for i in range(10):
high /= 2
total += high
print(high / 2)
print('总长:', total)
"""实例021:猴子偷桃
题目
猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析
按规则反向推断:猴子有一个桃子,他偷来一个桃子,觉得不够又偷来了与手上等量的桃子,一共偷了9天。"""
peach = 1
for i in range(9):
peach = (peach + 1) * 2
print(peach)
"""实例022:比赛对手
题目
两个乒乓球队进行比赛,各出三人。甲队为a, b, c三人,乙队为x, y, z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x, z比,请编程序找出三队赛手的名单。
程序分析
找到条件下不重复的三个对手即可。"""
a = set(['x', 'y', 'z'])
b = set(['x', 'y', 'z'])
c = set(['x', 'y', 'z'])
c -= set(('x', 'y'))
a -= set('x')
for i in a:
for j in b:
for k in c:
if len(set((i, j, k))) == 3:
print('a:%s,b:%s,c:%s' % (i, j, k))
"""实例023:画菱形
题目
打印出如下图案(菱形):
*
** *
** ** *
** ** ** *
** ** *
** *
*
程序分析
递归调用即可。"""
def draw(num):
a = "*" * (2 * (4 - num) + 1)
print(a.center(9, ' '))
if num != 1:
draw(num - 1)
print(a.center(9, ' '))
draw(4)
"""实例024:斐波那契数列II
题目
有一分数序列:2 / 1,3 / 2,5 / 3,8 / 5,13 / 8,21 / 13…求出这个数列的前20项之和。
程序分析
就是斐波那契数列的后一项除以前一项。"""
a = 2.0
b = 1.0
s = 0
for n in range(1, 21):
s += a / b
a, b = a + b, a
print(s)
"""实例025:阶乘求和
题目
求1 + 2!+3!+…+20!的和。
程序分析
1 + 2!+3!+…+20 != 1 + 2(1 + 3(1 + 4(…20(1))))"""
res = 1
for i in range(20, 1, -1):
res = i * res + 1
print(res)
"""实例026:递归求阶乘
题目
利用递归方法求5!。
程序分析
递归调用即可。"""
def factorial(n):
return n * factorial(n - 1) if n > 1 else 1
print(factorial(5))
"""实例027:递归输出
题目
利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
程序分析
递归真是蠢方法。"""
def rec(string):
if len(string) != 1:
rec(string[1:])
print(string[0], end='')
rec(input('string here:'))
"""实例028:递归求等差数列
题目
有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
程序分析
就一等差数列。"""
def age(n):
if n == 1:
return 10
return 2 + age(n - 1)
print(age(5))
"""实例029:反向输出
题目
给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
程序分析
学会分解出每一位数, 用字符串的方法总是比较省事。"""
n = int(input('输入一个正整数:'))
n = str(n)
print('%d位数' % len(n))
print(n[::-1])
"""实例030:回文数
题目
一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
程序分析
用字符串比较方便, 就算输入的不是数字都ok。"""
n = input("随便你输入啥啦:")
a = 0
b = len(n) - 1
flag = True
while a < b:
if n[a] != n[b]:
print('不是回文串')
flag = False
break
a, b = a + 1, b - 1
if flag:
print('是回文串')
"""实例031:字母识词
题目
请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
程序分析
这里用字典的形式直接将对照关系存好。"""
weekT = {'h': 'thursday',
'u': 'tuesday'}
weekS = {'a': 'saturday',
'u': 'sunday'}
week = {'t': weekT,
's': weekS,
'm': 'monday',
'w': 'wensday',
'f': 'friday'}
a = week[str(input('请输入第一位字母:')).lower()]
if a == weekT or a == weekS:
print(a[str(input('请输入第二位字母:')).lower()])
else:
print(a)
"""实例032:反向输出II
题目
按相反的顺序输出列表的值。
程序分析
无。"""
a = ['one', 'two', 'three']
print(a[::-1])
"""实例033:列表转字符串
题目
按逗号分隔列表。
程序分析
无。"""
L = [1, 2, 3, 4, 5]
print(','.join(str(n) for n in L))
"""实例034:调用函数
题目
练习函数调用。
程序分析
无。"""
def hello():
print('Hello World!')
def helloAgain():
for i in range(2):
hello()
if __name__ == '__main__':
helloAgain()
"""实例035:设置输出颜色
题目
文本颜色设置。
程序分析
无。"""
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.WARNING + "警告的颜色字体?" + bcolors.ENDC)
"""实例036:算素数
题目
求100之内的素数。
程序分析
用else执行for循环的奖励代码(如果for是正常完结,非break)。"""
lo = int(input('下限:'))
hi = int(input('上限:'))
for i in range(lo, hi + 1):
if i > 1:
for j in range(2, i):
if (i % j) == 0:
break
else:
print(i)
"""实例037:排序
题目
对10个数进行排序。
程序分析
同实例005。"""
raw = []
for i in range(10):
x = int(input('int%d: ' % (i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i, len(raw)):
if raw[i] > raw[j]:
raw[i], raw[j] = raw[j], raw[i]
print(raw)
"""实例038:矩阵对角线之和
题目
求一个3 * 3矩阵主对角线元素之和。
程序分析
无。"""
mat = [[1, 2, 3],
[3, 4, 5],
[4, 5, 6]
]
res = 0
for i in range(len(mat)):
res += mat[i][i]
print(res)
"""实例039:有序列表插入元素
题目
有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
程序分析
首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。"""
lis = [1, 10, 100, 1000, 10000, 100000]
n = int(input('insert a number: '))
lis.append(n)
for i in range(len(lis) - 1):
if lis[i] >= n:
for j in range(i, len(lis)):
lis[j], lis[-1] = lis[-1], lis[j]
break
print(lis)
"""实例040:逆序列表
题目
将一个数组逆序输出。
程序分析
依次交换位置,或者直接调用reverse方法。"""
lis = [1, 10, 100, 1000, 10000, 100000]
for i in range(int(len(lis) / 2)):
lis[i], lis[len(lis) - 1 - i] = lis[len(lis) - 1 - i], lis[i]
print('第一种实现:')
print(lis)
lis = [1, 10, 100, 1000, 10000, 100000]
print('第二种实现:')
lis.reverse()
print(lis)
"""实例041:类的方法与变量
题目
模仿静态变量的用法。
程序分析
构造类,了解类的方法与变量。"""
def dummy():
i = 0
print(i)
i += 1
class cls:
i = 0
def dummy(self):
print(self.i)
self.i += 1
a = cls()
for i in range(50):
dummy()
a.dummy()
"""实例042:变量作用域
题目
学习使用auto定义变量的用法。
程序分析
python中的变量作用域。"""
i = 0
n = 0
def dummy():
i = 0
print(i)
i += 1
def dummy2():
global n
print(n)
n += 1
print('函数内部的同名变量')
for j in range(20):
print(i)
dummy()
i += 1
print('global声明同名变量')
for k in range(20):
print(n)
dummy2()
n += 10
"""实例043:作用域、类的方法与变量
题目
模仿静态变量(static)
另一案例。
程序分析
综合实例041和实例042。"""
class dummy:
num = 1
def Num(self):
print('class dummy num:', self.num)
print('global num: ', self.num)
self.num += 1
n = dummy()
num = 1
for i in range(5):
num *= 10
n.Num()
"""实例044:矩阵相加
题目
计算两个矩阵相加。
程序分析
创建一个新的矩阵,使用
for 迭代并取出 X 和 Y 矩阵中对应位置的值,相加后放到新矩阵的对应位置中。"""
X = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[5, 8, 1],
[6, 7, 3],
[4, 5, 9]]
res = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(res)):
for j in range(len(res[0])):
res[i][j] = X[i][j] + Y[i][j]
print(res)
"""实例045:求和
题目
统计1到100之和。
程序分析
无"""
res = 0
for i in range(1, 101):
res += i
print(res)
"""实例046:打破循环
题目
求输入数字的平方,如果平方运算后小于50则退出。
程序分析
无"""
while True:
try:
n = float(input('输入一个数字:'))
except:
print('输入错误')
continue
dn = n ** 2
print('其平方为:', dn)
if dn < 50:
print('平方小于50,退出')
break
"""实例047:函数交换变量
题目
两个变量值用函数互换。
程序分析
无"""
def exc(a, b):
return (b, a)
a = 0
b = 10
a, b = exc(a, b)
print(a, b)
"""实例048:数字比大小
题目
数字比较。
程序分析
无"""
a = int(input('a='))
b = int(input('b='))
if a < b:
print('a<b')
elif a > b:
print('a>b')
else:
print('a=b')
"""实例049:lambda
题目 使用lambda来创建匿名函数。
程序分析 无"""
Max= lambda x, y: x * (x >= y) + y * (y > x)
Min = lambda x, y: x * (x <= y) + y * (y < x)
a = int(input('1:'))
b = int(input('2:'))
print(Max(a, b))
print(Min(a, b))
"""实例050:随机数
题目
输出一个随机数。
程序分析
使用random模块。"""
import random
print(random.uniform(10, 20))
"""实例051:按位与
题目
学习使用按位与 & 。
程序分析
0 & 0 = 0;
0 & 1 = 0;
1 & 0 = 0;
1 & 1 = 1。"""
a = 0o77
print(a)
b = a & 3
print(b)
b = b & 7
print(b)
"""实例052:按位或
题目
学习使用按位或 | 。
程序分析
0 | 0 = 0;
0 | 1 = 1;
1 | 0 = 1;
1 | 1 = 1"""
a = 0o77
print(a | 3)
print(a | 3 | 7)
"""实例053:按位异或
题目
学习使用按位异或 ^ 。
程序分析
0 ^ 0 = 0;
0 ^ 1 = 1;
1 ^ 0 = 1;
1 ^ 1 = 0"""
a = 0o77
print(a ^ 3)
print(a ^ 3 ^ 7)
"""实例054:位取反、位移动
题目
取一个整数a从右端开始的4~7位。
程序分析
可以这样考虑:
(1)先使a右移4位。
(2)设置一个低4位全为1, 其余全为0的数。可用(0 << 4)
(3)将上面二者进行 & 运算。"""
a = int(input('输入一个数字: '))
b = 0 # 0
b = ~b # 1
b = b << 4 # 10000
b = ~b # 1111
c = a >> 4
d = c & b
print('a:', bin(a))
print('b:', bin(b))
print('c:', bin(c))
print('d:', bin(d))
"""实例055:按位取反
题目
学习使用按位取反
~。
程序分析"""
~0 = 1;
~1 = 0;
print(~234)
print(~~234)
"""实例056:画圈
题目
画图,学用circle画圆形。
程序分析
无。"""
from tkinter import *
canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 1
for i in range(26):
canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
k += j
j += 0.3
mainloop()
"""实例057:画线
题目
画图,学用line画直线。
程序分析
无。"""
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_line(x0, y0, x0, y1, width=1, fill='red')
x0 = x0 - 5
y0 = y0 - 5
x1 = x1 + 5
y1 = y1 + 5
x0 = 263
y1 = 275
y0 = 263
for i in range(21):
canvas.create_line(x0, y0, x0, y1, fill='red')
x0 += 5
y0 += 5
y1 += 5
mainloop()
"""实例058:画矩形
题目
画图,学用rectangle画方形。
程序分析
无。"""
if __name__ == '__main__':
from tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root, width=400, height=400, bg='yellow')
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_rectangle(x0, y0, x1, y1)
x0 -= 5
y0 -= 5
x1 += 5
y1 += 5
canvas.pack()
root.mainloop()
"""实例059:画图(丑)
题目
画图,综合例子。
程序分析
丑。"""
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 150
y0 = 100
canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
import math
B = 0.809
for i in range(16):
a = 2 * math.pi / 16 * i
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)
for k in range(501):
for i in range(17):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 + math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
for j in range(51):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0, y0, x, y, fill='red')
mainloop()
"""实例060:字符串长度
题目
计算字符串长度。
程序分析
无。"""
s = 'zhangguang101'
print(len(s))
"""实例061:杨辉三角
题目
打印出杨辉三角形前十行。
程序分析
无。"""
def generate(numRows):
r = [[1]]
for i in range(1, numRows):
r.append(list(map(lambda x, y: x + y, [0] + r[-1], r[-1] + [0])))
return r[:numRows]
a = generate(10)
for i in a:
print(i)
"""
实例062:查找字符串
题目
查找字符串。
程序分析
无。"""
s1 = 'aabbxuebixuebi'
s2 = 'ab'
s3 = 'xue'
print(s1.find(s2))
print(s1.find(s3))
"""实例063:画椭圆
题目
画椭圆。
程序分析
使用tkinter。"""
if __name__ == '__main__':
from tkinter import *
x = 360
y = 160
top = y - 30
bottom = y - 30
canvas = Canvas(width=400, height=600, bg='white')
for i in range(20):
canvas.create_oval(250 - top, 250 - bottom, 250 + top, 250 + bottom)
top -= 5
bottom += 5
canvas.pack()
mainloop()
"""实例064:画椭圆、矩形
题目
利用ellipse和rectangle画图。。
程序分析
无。"""
if __name__ == '__main__': from tkinter import *
canvas = Canvas(width=400, height=600, bg='white')
left = 20
right = 50
top = 50
num = 15
for i in range(num):
canvas.create_oval(250 - right, 250 - left, 250 + right, 250 + left)
canvas.create_oval(250 - 20, 250 - top, 250 + 20, 250 + top)
canvas.create_rectangle(20 - 2 * i, 20 - 2 * i, 10 * (i + 2), 10 * (i + 2))
right += 5
left += 5
top += 10
canvas.pack()
mainloop()
"""实例065:画组合图形
题目
一个最优美的图案。
程序分析
无。"""
import math
from tkinter import *
class PTS:
def __init__(self):
self.x = 0
self.y = 0
points = []
def LineToDemo():
screenx = 400
screeny = 400
canvas = Canvas(width=screenx, height=screeny, bg='white')
AspectRatio = 0.85
MAXPTS = 15
h = screeny
w = screenx
xcenter = w / 2
ycenter = h / 2
radius = (h - 30) / (AspectRatio * 2) - 20
step = 360 / MAXPTS
angle = 0.0
for i in range(MAXPTS):
rads = angle * math.pi / 180.0
p = PTS()
p.x = xcenter + int(math.cos(rads) * radius)
p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
angle += step
points.append(p)
canvas.create_oval(xcenter - radius, ycenter - radius,
xcenter + radius, ycenter + radius)
for i in range(MAXPTS):
for j in range(i, MAXPTS):
canvas.create_line(points[i].x, points[i].y, points[j].x, points[j].y)
canvas.pack()
mainloop()
if __name__ == '__main__':
LineToDemo()
"""实例066:三数排序
题目
输入3个数a, b, c,按大小顺序输出。
程序分析
同实例005。"""
raw = []
for i in range(3):
x = int(input('int%d: ' % (i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i, len(raw)):
if raw[i] > raw[j]:
raw[i], raw[j] = raw[j], raw[i]
print(raw)
raw2 = []
for i in range(3):
x = int(input('int%d: ' % (i)))
raw2.append(x)
print(sorted(raw2))
"""实例067:交换位置
题目
输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
程序分析
无。"""
li = [3, 2, 5, 7, 8, 1, 5]
li[-1], li[li.index(min(li))] = li[li.index(min(li))], li[-1]
m = li[0]
ind = li.index(max(li))
li[0] = li[ind]
li[ind] = m
print(li)
"""实例068:旋转数列
题目
有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
程序分析
无。"""
from collections import *
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
deq = deque(li, maxlen=len(li))
print(li)
deq.rotate(int(input('rotate:')))
print(list(deq))
"""实例069:报数
题目
有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
程序分析
无。"""
if __name__ == '__main__':
nmax = 50
n = int(input('请输入总人数:'))
num = []
for i in range(n):
num.append(i + 1)
i = 0
k = 0
m = 0
while m < n - 1:
if num[i] != 0: k += 1
if k == 3:
num[i] = 0
k = 0
m += 1
i += 1
if i == n: i = 0
i = 0
while num[i] == 0: i += 1
print(num[i])
"""实例070:字符串长度II
题目
写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。
程序分析
无。"""
def lenofstr(s):
return len(s)
print(lenofstr('tanxiaofengsheng'))
"""实例071:输入和输出
题目
编写input()
和output()
函数输入,输出5个学生的数据记录。
程序分析
无。"""
N = 3
liststudent = []
for i in range(5):
student.append(['','',[]])
def input_stu(stu):
for i in range(N):
stu[i][0] = input('input student num:\n')
stu[i][1] = input('input student name:\n')
for j in range(3):
stu[i][2].append(int(input('score:\n')))
def output_stu(stu):
for i in range(N):
print ('%-6s%-10s' % ( stu[i][0],stu[i][1] ))
for j in range(3):
print ('%-8d' % stu[i][2][j])
if __name__ == '__main__':
input_stu(student)
print (student)
output_stu(student)
"""实例072:创建链表
题目
创建一个链表。
程序分析
原文不太靠谱。
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
class List:
def __init__(self, head):
self.head = head
def is_empty(self):
return self.get_len() == 0
def get_len(self):
length = 0
temp = self.head
while temp is not None:
length += 1
temp = temp.next
return length
def append(self, node):
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index):
if index < 1 or index > self.get_len():
print("给定位置不合理")
return
if index == 1:
self.head = self.head.next
return
temp = self.head
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index - 1:
temp.next = temp.next.next
temp = temp.next
def insert(self, pos, node):
if pos < 1 or pos > self.get_len():
print("插入结点位置不合理")
return
temp = self.head
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos - 1:
node.next = temp.next
temp.next = node
break
temp = temp.next
def reverse(self, head):
if head is None and head.next is None:
return head
pre = head
cur = head.next
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
head.next = None
return pre
def print_list(self, head):
init_data = []
while head is not None:
init_data.append(head.get_data())
head = head.next
return init_data
if __name__ == '__main__':
head = Node('head')
link = List(head)
for i in range(10):
node = Node(i)
link.append(node)
print(link.print_list(head))
"""实例073:反向输出链表
题目
反向输出一个链表。
程序分析
无。"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
class List:
def __init__(self, head):
self.head = head
def is_empty(self):
return self.get_len() == 0
def get_len(self):
length = 0
temp = self.head
while temp is not None:
length += 1
temp = temp.next
return length
def append(self, node):
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index):
if index < 1 or index > self.get_len():
print("给定位置不合理")
return
if index == 1:
self.head = self.head.next
return
temp = self.head
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index - 1:
temp.next = temp.next.next
temp = temp.next
def insert(self, pos, node):
if pos < 1 or pos > self.get_len():
print("插入结点位置不合理")
return
temp = self.head
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos - 1:
node.next = temp.next
temp.next = node
break
temp = temp.next
def reverse(self, head):
if head is None and head.next is None:
return head
pre = head
cur = head.next
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
head.next = None
return pre
def print_list(self, head):
init_data = []
while head is not None:
init_data.append(head.get_data())
head = head.next
return init_data
if __name__ == '__main__':
head = Node('head')
link = List(head)
for i in range(10):
node = Node(i)
link.append(node)
print(link.print_list(head))
print(link.print_list(link.reverse(head)))
"""实例074:列表排序、连接
题目
列表排序及连接。
程序分析
排序可使用sort()方法,连接可以使用 + 号或extend()方法。"""
a = [2, 6, 8]
b = [7, 0, 4]
a.extend(b)
a.sort()
print(a)
"""实例075:不知所云
题目
放松一下,算一道简单的题目。
程序分析
鬼知道是什么。"""
if __name__ == '__main__':
for i in range(5):
n = 0
if i != 1: n += 1
if i == 3: n += 1
if i == 4: n += 1
if i != 4: n += 1
if n == 3: print(64 + i)
"""实例076:做函数
题目
编写一个函数,输入n为偶数时,调用函数求1 / 2 + 1 / 4 +…+1 / n, 当输入n为奇数时,调用函数1 / 1 + 1 / 3 +…+1 / n
程序分析
无。
"""
def peven(n):
i = 0
s = 0.0
for i in range(2, n + 1, 2):
s += 1.0 / i
return s
def podd(n):
s = 0.0
for i in range(1, n + 1, 2):
s += 1.0 / i
return s
def dcall(fp, n):
s = fp(n)
return s
if __name__ == '__main__':
n = int(input('input a number: '))
if n % 2 == 0:
sum = dcall(peven, n)
else:
sum = dcall(podd, n)
print(sum)
"""实例077:遍历列表
题目
循环输出列表
程序分析
无。"""
l = ['moyu', 'niupi', 'xuecaibichi', 'shengfaji', '42']
for i in range(len(l)):
print(l[i])
"""实例078:字典
题目
找到年龄最大的人,并输出。请找出程序中有什么问题。
程序分析
无。"""
if __name__ == '__main__':
person = {"li": 18, "wang": 50, "zhang": 20, "sun": 22}
m = 'li'
for key in person.keys():
if person[m] < person[key]:
m = key
print('%s,%d' % (m, person[m]))
"""实例079:字符串排序
题目
字符串排序。
程序分析
无。"""
l = ['baaa', 'aaab', 'aaba', 'aaaa', 'abaa']
l.sort()
print(l)
"""实例080:猴子分桃
题目
海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。
第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
程序分析
无。"""
if __name__ == '__main__':
i = 0
j = 1
x = 0
while (i < 5):
x = 4 * j
for i in range(0, 5):
if (x % 4 != 0):
break
else:
i += 1
x = (x / 4) * 5 + 1
j += 1
print(x)
for p in range(5):
x = (x - 1) / 5 * 4
print(x)
"""实例081:求未知数
题目
809 *??=800 *??+9 *?? 其中??代表的两位数, 809 *??为四位数,8 *??的结果为两位数,9 *??的结果为3位数。求??代表的两位数,及809 *??后的结果。
程序分析
无。"""
a = 809
for i in range(10, 100):
b = i * a
if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100:
print(b, ' = 800 * ', i, ' + 9 * ', i)
for i in range(10, 100):
if 8 * i > 99 or 9 * i < 100:
continue
if 809 * i == 800 * i + 9 * i:
print(i)
break
"""实例082:八进制转十进制
题目
八进制转换为十进制
程序分析
无。"""
n = eval('0o' + str(int(input('八进制输入:'))))
print(n)
"""实例083:制作奇数
题目
求0—7所能组成的奇数个数。
程序分析
组成1位数是4个。1, 3, 5, 7结尾
组成2位数是7 * 4个。第一位不能为0
组成3位数是784个。中间随意
组成4位数是788 * 4个。"""
if __name__ == '__main__':
sum = 4
s = 4
for j in range(2, 9):
print(sum)
if j <= 2:
s *= 7
else:
s *= 8
sum += s
print('sum = %d' % sum)
"""实例084:连接字符串
题目
连接字符串。
程序分析
无。"""
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
"""实例085:整除
题目
输入一个奇数,然后判断最少几个9除于该数的结果为整数。
程序分析
999999 / 13 = 76923。"""
if __name__ == '__main__':
zi = int(input('输入一个数字:'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1 = 0
else:
m9 *= 10
sum += m9
c9 += 1
print('%d 个 9 可以被 %d 整除 : %d' % (c9, zi, sum))
r = sum / zi
print('%d / %d = %d' % (sum, zi, r))
"""实例086:连接字符串II
题目
两个字符串连接程序。
程序分析
无。"""
a = 'guangtou'
b = 'feipang'
print(b + a)
"""实例087:访问类成员
题目
回答结果(结构体变量传递)。
程序分析
无。"""
if __name__ == '__main__':
class student:
x = 0
c = 0
def f(stu):
stu.x = 20
stu.c = 'c'
a = student()
a.x = 3
a.c = 'a'
f(a)
print(a.x, a.c)
"""实例088:打印星号
题目
读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*。
程序分析
无。"""
for i in range(3):
print('*' * int(input('input a number: ')))
"""实例089:解码
题目
某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5, 然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。
程序分析
无。"""
n = input()
n = str(n)
a = []
for i in range(4):
a.append(int(n[i]) + 5)
a[0], a[3] = a[3], a[0]
a[1], a[2] = a[2], a[1]
print("".join('%s' % s for s in a))
"""实例090:列表详解
题目
列表使用实例。
程序分析
无。"""
# list
# 新建列表
testList = [10086, '中国移动', [1, 2, 4, 5]]
# 访问列表长度
print(len(testList))
# 到列表结尾
print(testList[1:])
# 向列表添加元素
testList.append('i\'m new here!')
print(len(testList))
print(testList[-1])
# 弹出列表的最后一个元素
print(testList.pop(1))
print(len(testList))
print(testList)
# stcomprehension
# 后面有介绍,暂时掠过
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(matrix)
print(matrix[1])
col2 = [row[1] for row in matrix] # get a column from a matrix
print(col2)
col2even = [row[1] for row in matrix if row[1] % 2 == 0] # filter odd item
print(col2even)
"""实例091:time模块
题目
时间函数举例1。
程序分析
无。"""
if __name__ == '__main__':
import time
print(time.ctime(time.time()))
print(time.asctime(time.localtime(time.time())))
print(time.asctime(time.gmtime(time.time())))
"""实例092:time模块II
题目
时间函数举例2。
程序分析
如何浪费时间。"""
if __name__ == '__main__':
import time
start = time.time()
for i in range(3000):
print(i)
end = time.time()
print(end - start)
"""实例093:time模块III
题目
时间函数举例3。
程序分析
如何浪费时间。"""
if __name__ == '__main__':
import time
start = time.clock()
for i in range(100):
print(i)
end = time.clock()
print('different is %6.3f' % (end - start))
"""实例094:time模块IV
题目
时间函数举例4。
程序分析
如何浪费时间。"""
if __name__ == '__main__':
import time
import random
play_it = input('do you want to play it.(\'y\' or \'n\')')
while play_it == 'y':
c = input('input a character:\n')
i = random.randint(0, 2 ** 32) % 100
print('please input number you guess:\n')
start = time.clock()
a = time.time()
guess = int(input('input your guess:\n'))
while guess != i:
if guess > i:
print('please input a little smaller')
guess = int(input('input your guess:\n'))
else:
print('please input a little bigger')
guess = int(input('input your guess:\n'))
end = time.clock()
b = time.time()
var = (end - start) / 18.2
print(var)
# print 'It took you %6.3 seconds' % time.difftime(b,a))
if var < 15:
print('you are very clever!')
elif var < 25:
print('you are normal!')
else:
print('you are stupid!')
print('Congradulations')
print('The number you guess is %d' % i)
play_it = input('do you want to play it.')
"""实例095:转换时间格式
题目
字符串日期转换为易读的日期格式。
程序分析
看看就得了,dateutil是个第三方库。"""
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print(dt)
"""实例096:计算复读次数
题目
计算字符串中子串出现的次数。
程序分析
无。"""
s1 = 'xuebixuebixuebixuebixuebixuebixuebixue'
s2 = 'xuebi'
print(s1.count(s2))
"""实例097:磁盘写入
题目
从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。
程序分析
无。"""
if __name__ == '__main__':
from sys import stdout
filename = input('输入文件名:\n')
fp = open(filename, "w")
ch = input('输入字符串:\n')
while ch != '#':
fp.write(ch)
stdout.write(ch)
ch = input('')
fp.close()
"""实例098:磁盘写入II
题目
从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。
程序分析
无。"""
if __name__ == '__main__':
fp = open('test.txt', 'w')
string = input('please input a string:\n')
string = string.upper()
fp.write(string)
fp = open('test.txt', 'r')
print(fp.read())
fp.close()
"""实例099:磁盘读写
题目
有两个磁盘文件A和B, 各存放一行字母, 要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。
程序分析
无。"""
if __name__ == '__main__':
import string
fp = open('test1.txt')
a = fp.read()
fp.close()
fp = open('test2.txt')
b = fp.read()
fp.close()
fp = open('test3.txt', 'w')
l = list(a + b)
l.sort()
s = ''
s = s.join(l)
fp.write(s)
fp.close()
"""实例100:列表转字典
题目
列表转换为字典。
程序分析
无。"""
i = ['a', 'b']
l = [1, 2]
print(dict(zip(i, l)))
|
d0a959c1b36da882c963cee35c1e591a55238c63 | QI1002/exampool | /Leetcode/271.py | 950 | 3.765625 | 4 |
#271. Encode and Decode Strings
def encode(s):
result = ""
count = 0
word = None
output = False
for c in s:
if (c == word):
count += 1
if (count < 256): continue
count,output = 255, True
else:
if (word != None): output = True
if (output):
result += chr(count)
result += word
output = False
count = 1
word = c
if (word != None):
result += chr(count)
result += word
print(list(result))
return result
def decode(s):
result = ""
for i in range(0,len(s),2):
count = s[i]
word = s[i+1]
result += (word*ord(count))
print(list(result))
return result
data = 'abaabbc'
edata = encode(data)
print("{0}:{1}".format(data, decode(edata)))
data = 'abaaaaaabbc'
edata = encode(data)
print("{0}:{1}".format(data, decode(edata)))
|
d29a064a8e1ab46f25ae6acad5d0d7fd4e4e5f4f | vesteves33/cursoPython | /Exercicios/ex071.py | 634 | 3.71875 | 4 | print('='*30)
print('{:^30}'.format('BANCO VEC'))
print('='*30)
valor = int(input('Quanto quer sacar? '))
total = valor
cedula = 50
totalCedula = 0
while True:
if total >= cedula:
total -= cedula
totalCedula += 1
else:
if totalCedula > 0:
print(f'Total de {totalCedula} cedulas de R${cedula}')
if cedula == 50:
cedula = 20
elif cedula == 20:
cedula = 10
elif cedula == 10:
cedula = 1
totalCedula = 0
if total == 0:
break
print('=' * 30)
print('Volte sempre ao BANCO VEC. Tenha um Bom dia!') |
dda96b2e8de8f863bf25bea2bdfc365ab3a9f820 | clonedSemicolon/ComputerGraphics | /Drawing/Circle/Bresenham.py | 908 | 3.8125 | 4 | import PIL.ImageDraw as ID, PIL.Image as Image
def draw1(x1, y1):
draw.point((x1, y1), fill=(0, 255, 0))
def drawCircle(xc, yc, x, y):
draw1(xc + x, yc + y)
draw1(xc - x, yc + y)
draw1(xc + x, yc - y)
draw1(xc - x, yc - y)
draw1(xc + y, yc + x)
draw1(xc - y, yc + x)
draw1(xc + y, yc - x)
draw1(xc - y, yc - x)
def bresenhamCircleDraw(xc, yc, r):
x = 0
y = r
d = 3 - 2 * r
drawCircle(xc, yc, x, y)
while y >= x:
x = x + 1
if d > 0:
y = y - 1
d = d + 4 * (x - y) + 10
else:
d = d + 4 * x + 6
drawCircle(xc, yc, x, y)
if __name__ == '__main__':
im = Image.new("RGB", (640, 480))
draw = ID.Draw(im)
x = int(input("x-coordinate of centre: "))
y = int(input("y-coordinate of centre: "))
r = int(input("Radius: "))
bresenhamCircleDraw(x, y, r)
im.show()
|
05d63bcd5f14d9d7702d11d357e54e2a48c64605 | nikan1996/LeetCode | /Algorithms/3. Longest Substring Without Repeating Characters.py | 2,073 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author:nikan([email protected])
@file: 3. Longest Substring Without Repeating Characters.py
~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
@time: 31/01/2018 3:35 PM
"""
"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
"""找出最长的子串长度(其中子串不能含有重复字符) 滑窗法1
:type s: str
:rtype: int
"""
if not s:
return 0
sub_start_index = 0
sub_end_index = 0
max_len = 0
sub_string_set = set() # set 判断 新字符是否在子串中, O(1)的平均复杂度
len_s = len(s)
while sub_end_index < len_s:
if s[sub_end_index] in sub_string_set:
sub_string_set.remove(s[sub_start_index])
max_len = max(max_len, sub_end_index - sub_start_index)
sub_start_index += 1
else:
sub_string_set.add(s[sub_end_index])
sub_end_index += 1
return max_len
def lengthOfLongestSubstring2(self, s):
"""找出最长的子串长度(其中子串不能含有重复字符) 滑窗法2
:type s: str
:rtype: int
"""
sub_start_index = -1
max_len = 0
sub_string_dict = {} # dict 判断 新字符是否在子串中, dict: key <- char_index, value <- char
for index, value in enumerate(s):
if value in sub_string_dict:
if sub_string_dict[value] > sub_start_index:
sub_start_index = sub_string_dict[value]
sub_string_dict[value] = index
max_len = max(max_len, index - sub_start_index)
return max_len
|
52497d37047f9a80da51d95c067fa951130eba6e | Miky9/Py-BasicSyntax | /NotCompleted/Grafy_1.py | 579 | 3.546875 | 4 | # Importujeme základní vykreslovací modul
import matplotlib.pyplot as plt
import matplotlib
# A samozřejmě numpy
import numpy as np
# Občas se hodí i matematika
import math
# Vytvoříme jednoduchá data
# (50 bodů rovnoměrně rozmístěných na úseku -1,5)
x = np.linspace(-1, 5, 8)
y = x ** 2
fig = plt.figure()
# U add_axes musíme zadat, jakou část obrázku zabere čtverec se souřadnicemi
# zleva, odspodu, šířka, výška (v relativních hodnotách 0 až 1)
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# Nyní vykreslíme data
print (axes.plot(x, y));
|
bebb24b9decb6114bed99defd8c628036535eae9 | raj13aug/Python-learning | /Course/7-classes/properties.py | 1,038 | 4.1875 | 4 | class Product:
def __init__(self, price):
self.set_price(price)
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self.__price = value
price = property(get_price, set_price)
# A property is an object that sits in front of an attribute and allows us to get or set the value of an attribute.
# We want them to have minimal number of function or method exposed to outside.
product = Product(50)
print(product.price)
# We used a decorator called class method convert an instance method and class a class method.we have another decorator creating a property,
class Product:
def __init__(self, price):
self.price = price
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self.__price = value
product = Product(10)
print(product.price)
|
0f34364276a0f66cb787462c912826809cb8d960 | Ali-2000-prog/Python_MySQL_Cashier_Proj | /PY-Mysql/Amysql.py | 3,855 | 3.578125 | 4 | import mysql.connector
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
)
def createDatabase(db):
print(db)
mycursor=mydb.cursor()
sql="Create Database "+db
mycursor.execute(sql)
print("DataBase",db, "CREATED")
def DropDatabase(db):
print(db)
mycursor=mydb.cursor()
sql="Drop Database "+db
mycursor.execute(sql)
print("DataBase",db, "Droped")
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=""
)
def CreateTable(tname,db):
mydb.database=db
# This function does not create a custom table it creates a table in a database that exists with no parameters special
#It has only id ,name and age: Can be further adltered
mycursor=mydb.cursor()
sql="Create Table "+db+"(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), age INTEGER (10))"
mycursor.execute(sql)
print("Table",tname, "Created")
def IntoTableB(cname,valuesB=list):
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
mycursor=mydb.cursor()
sql="INSERT INTO "+ cname + " (name,price,Stock,Stock_price) VALUES (%s,%s,%s,%s)"
valB=valuesB
mycursor.executemany(sql,valB)
mydb.commit()
#Values takes argument in list form enclosed in tuple
def IntoTable(tname,cname,values=list,valueB=list):
#ace is here is testing database
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
mycursor=mydb.cursor()
sql="INSERT INTO "+ tname + " (name,price,Stock,Catagory,Stock_price) VALUES (%s,%s,%s,%s,%s)"
val=values
mycursor.executemany(sql,val)
mydb.commit()
valB=valueB
IntoTableB(cname,valB)
print("Table",tname, "Added Values")
def DeleteRow(id,arg):
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
arge=str(arg)
mycursor=mydb.cursor()
sql="DELETE FROM "+db+" Where "+id+"="+arge
mycursor.execute(sql)
mydb.commit()
print("Row Deleted Where "+id+"="+arge)
# write update (table_name) SET (column to update)=(update) Where id = (id no)
def UpdateDB(tname,columnUpdate,Update,id_no):
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
id_no=str(id_no)
mycursor=mydb.cursor()
sql="UPDATE "+tname+" SET "+columnUpdate +" = %s Where id = %s"
val=(Update,id_no)
mycursor.execute(sql,val)
mydb.commit()
print("Updated")
def GetData(tname):
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
mycursor=mydb.cursor()
sql="Select * FROM " + tname
mycursor.execute(sql)
print("Got Data")
myresult=mycursor.fetchall()
l=[]
for data in myresult:
l.append(data)
#print(data)
return l
def BillPrice(idno):
db="ace"
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
database=db
)
Billdict={"grocery": 1, "snacks":2, "appliances":3, "total":4}
mycursor=mydb.cursor()
z=str(Billdict[idno])
sql="Select price from bill where id= "+ z
val=1
mycursor.execute(sql)
myresult=mycursor.fetchall()
return myresult[0][0]
def BillPriceUP(price,name):
Billdict={"grocery": 1, "snacks":2, "appliances":3, "total":4}
UpdateDB("bill","price",price,Billdict[name])
|
37ec02bc42a4ccfb6c2700257304c79df4ba1a9f | BhagyashreeKarale/if-else | /dques1.py | 278 | 3.5625 | 4 | # Question 1
# In the further questions, you will see pre-written code.
# You have to debug the incorrect code and submit the correct code.
print ("We will learn debugging by removing all the errors from this python file.")
# Save the correct code in a new file and submit it. |
01d4464cb7c25e8e0baa8fea90a8eb11e691f852 | Kein-Cary/Tools | /normitems/nstep.py | 1,320 | 3.6875 | 4 | # this file use to calculate this type formulation: y = x!; y = x!!
import numpy as np
_all_ = ['n_step', 'n_n_step']
def n_step(x):
"""
x : the data will use to calculate x!, x can be a data, or an array
"""
x = x
try:
gama = np.zeros(len(x), dtype = np.float)
for k in range(len(x)):
gama[k] = 1
for p in range(1,x[k]+1):
gama[k] = gama[k]*p
except TypeError:
gama = 1
for k in range(1,x+1):
gama = gama*k
return gama
def n_n_step(x):
"""
x : the data will use to calculate x!!, x can be a data, or an array
"""
x = x
try:
gama = np.zeros(len(x),dtype = np.float)
for k in range(len(x)):
gama[k] = 1
if x[k] % 2 == 0:
for p in range(1,np.int0(x/2+1)):
gama[k] = gama[k]*(p*2)
if x[k] % 2 == 1:
for p in range(1,np.int0((x+1)/2)):
gama[k] = gama[k]*(2*p+1)
except TypeError:
if x % 2 == 0:
gama = 1
for k in range(1,np.int0(x/2+1)):
gama = gama*(k*2)
if x % 2 == 1:
gama = 1
for k in range(1,np.int0((x+1)/2)):
gama = gama*(2*k+1)
return gama
|
5c0ae4f27ab24fc9b22b2f5255d9124fe0523eb1 | ISPC2020/tscdprog2020_g2-tscdprog2020_g2 | /Banco_Jose/Clases/Cuenta.py | 1,629 | 3.90625 | 4 | class Cuenta:
@staticmethod
def menu_cuenta(cuenta):
opcion = None
while opcion != 5:
print("""
Opciones:
1. Depositar
2. Extraer
3. Consultar saldo
4. Constitucion de plazo fijo
5. Salir
""")
opcion = int(input("Ingrese una opcion: "))
if opcion == 1:
cuenta.deposito(float(input("Ingrese el monto a depositar: $")))
elif opcion == 2:
cuenta.extraccion(float(input("Ingrese el monto a depositar: $")))
elif opcion == 3:
print(cuenta.saldo())
elif opcion == 4:
cuenta.plazo_fijo(
float(input("Ingrese el monto del capital a invertir: $")),
int(input("Ingrese la cantidad de dias: ")),
float(input("Ingrese la tasa de interes: "))
)
elif opcion == 5:
break
def __init__(self):
self._saldo = 0
def deposito(self, monto):
self._saldo += monto
def extraccion(self, monto):
self._saldo -= monto
def saldo(self):
return self._saldo
def plazo_fijo(self, capital, tiempo, tasa_interes):
interes = (capital * tasa_interes) / 100
print(f'Plazo fijo'.center(25, '-'))
print(f'Capital invertido ${capital}')
print(f'Disponible en: {tiempo} dias')
print(f'Ganancia de ${interes}')
# test
if __name__ == '__main__':
cuenta = Cuenta()
cuenta.menu_cuenta(cuenta)
|
bb1aac41202c1ba8e4a6cc13813754477405ec41 | chenfancy/PAT_Python | /Chapter2/2-10.py | 228 | 3.78125 | 4 | lower,upper=input().split()
lower,upper=int(lower),int(upper)
if upper<lower:
print('Invalid.')
else:
print('fahr celsius')
for i in range(lower,upper+1,2):
print('{0}{1:>6.1f}'.format(i,5*(i-32)/9))
|
30827734d7cf45cc91ce5b5fdcd7da91ca1417cb | kuldeep27396/DataStructuresandAlgorithmsInPython | /com/kranthi/Algorithms/sorting/InsertionSort.py | 328 | 4.03125 | 4 |
def insertionSort(arr: list, size: int) -> list:
i, key, j = 0,0,0
for i in range(size):
key = arr[i]
j = i-1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j = j-1
arr[j+1] = key
return arr
arr = [2, 6, 3, 12, 56, 8]
print(insertionSort(arr, len(arr))) |
7b5f80ffabc8ef25b0ac34cf9110a1cd9838252c | msrocka/pslink | /pslink/backs.py | 852 | 3.5 | 4 | import csv
class ProductInfo(object):
"""Instances of this class describe a product in a background database."""
def __init__(self):
self.process_uuid = ''
self.process_name = ''
self.product_uuid = ''
self.product_name = ''
self.product_unit = ''
def read_products(fpath: str) -> list:
"""Read the list of product information from the given file. """
infos = []
with open(fpath, 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter='\t')
next(reader)
for row in reader:
pinfo = ProductInfo()
pinfo.process_uuid = row[0]
pinfo.process_name = row[1]
pinfo.product_uuid = row[2]
pinfo.product_name = row[3]
pinfo.product_unit = row[4]
infos.append(pinfo)
return infos
|
a5f8f274c494de16e1e30da66bfb773b4b3e49cf | hscspring/The-DataStructure-and-Algorithms | /CodingInterview2/31_StackPushPopOrder/stack_push_pop_order.py | 1,830 | 4.125 | 4 | """
面试题 31:栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是
否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1、2、3、4、
5 是某栈的压栈序列,序列 4、5、3、2、1 是该压栈序列对应的一个弹出序列,但
4、3、5、1、2 就不可能是该压栈序列的弹出序列。
"""
def is_pop_order(push_order: list, pop_order: list) -> bool:
"""
Whether the pop order is for the push order.
Parameters
-----------
push_order: list
pop_order: list
Returns
---------
out: bool
If the pop order is for the push order.
Notes
------
All the numbers are not the same.
"""
if not push_order or not pop_order:
return False
stack = []
for pop in pop_order:
s_top = stack[-1] if stack else None
if push_order and pop != s_top:# pop not in stack:
x = push_order.pop(0)
while x != pop:
stack.append(x)
if push_order:
x = push_order.pop(0)
else:
return False
else:
if stack.pop() != pop:
return False
return True
def is_pop_order2(push_order, pop_order):
if not push_order or not pop_order:
return False
stack = []
for i in pop_order:
if stack and stack[-1] == i:
stack.pop()
else:
while push_order and push_order[0] != i:
x = push_order.pop(0)
stack.append(x)
if push_order:
push_order.pop(0)
else:
return False
return True
if __name__ == '__main__':
pass
|
146ecd947f42b9276abc6291717848cb1075c8c2 | Xevion/exercism | /python/tournament/tournament.py | 1,379 | 3.625 | 4 | def tally(rows):
# Subcommand that adds teams if not yet added, and processes the result from them
def process(team, result):
if team not in teams.keys():
teams[team] = {'MP' : 0, 'W' : 0, 'D' : 0, 'L' : 0, 'P' : 0}
if result == 'win':
teams[team]['W'] += 1
teams[team]['P'] += 3
elif result == 'draw':
teams[team]['D'] += 1
teams[team]['P'] += 1
elif result == 'loss':
teams[team]['L'] += 1
teams[team]['MP'] += 1
teams, output = {}, ['Team'.ljust(31) + '| MP | W | D | L | P']
# Quick lambda that swaps the result for the enemy team
swap = lambda result : 'win' if result == 'loss' else 'loss' if result == 'win' else 'draw'
for row in rows:
team1, team2, result = row.split(';')
process(team1, result); process(team2, swap(result))
# Process all the data with formatting. rjust and ljust add proper spacing for the scoring, so it allows double digit scores
for teamname, data in sorted(teams.items(), key=lambda item : (max([t['P'] for t in teams.values()]) - int(item[1]['P']), item[0])):
output.append('{}| {} | {} | {} | {} | {}'.format(teamname.ljust(31), str(data['MP']).rjust(2), str(data['W']).rjust(2), str(data['D']).rjust(2), str(data['L']).rjust(2), str(data['P']).rjust(2)))
return output |
47fcb516d28fc3f6740d33725d2ee7cefdc64c94 | dnvnxg/cse107-lab4 | /navigate2.py | 1,259 | 4.15625 | 4 | """
A program that takes movement commands and reflects those commands in Turtle
file: navigate2.py
author: Donovan Griego
Date: 9-15-2021
assignment: Lab 4
"""
import turtle
def main():
# grabs commands until "stop" is read
queue = ["start"]
while queue[len(queue) - 1] != "stop":
cmd = input("Please enter a direction: ")
queue.append(cmd)
if cmd == "right" or cmd == "left":
queue.append(float(input("How many degrees? ")))
window = turtle.Screen()
t1 = turtle.Turtle()
i = 0
print("Running...")
# goes through queue and runs the stored commands until "stop" is read
while i < len(queue):
if queue[i] == "start":
t1.pendown()
i += 1
elif queue[i] == "forward":
t1.forward(50)
i += 1
elif queue[i] == "right":
t1.right(float(queue[i + 1]))
i += 2
elif queue[i] == "left":
t1.left(float(queue[i + 1]))
i += 2
elif queue[i] == "stop":
print("Done.")
window.mainloop()
exit(0)
else:
print("Invalid commad '{}'; ignoring".format(queue[i]))
i += 1
if __name__ == "__main__":
main()
|
0e5c47de1bb6fbd156d41d0b3b21b8ef6e32c51a | MuhammadAbbasi/DSA_Semester3 | /Assignments/Assignment 2/All questions/Q1.py | 319 | 4.34375 | 4 | '''Write a short Python function that takes a positive
integer n and returns the sum of the squares of
all the odd positive integers smaller than n.'''
def OddPowerSum(n):
t = 0
for a in range(n):
if a%2 != 0:
t = t + a*a
return t
print(OddPowerSum(12))
print(OddPowerSum(5))
|
9699b838abfa7e868e45cfe8eda441b89e3f90f1 | Famiha/Python-30DaysChallange- | /day2.py | 2,477 | 4.125 | 4 | # ## List #### (Ordered & Changeable )##
# name = ("Arman","John", "Kamal","John","Clair","Karen","Samantha","")
# # # print(f"Here is the list of the name and the position is given below:\n Goalkeeper is {name[0]} \n Wrestler is {name[1]} \n Cricketer is {name[2]}")
# # name.pop()
# # print(name)
# number = [ 10, 30, 50, 60 , 24, 5, 9]
# number.sort()
# print(number)
## Tuples (Ordered & Unchangeable )
## Dictonaries (Unordered & Changeable )##
# car = {
# "brand": "Ford",
# "model": "Mustang",
# "year": 1964
# }
# print(car['year'])
## Conditional Statement ##
# age = 18
# if age==18:
# print('He is eligible for this content')
# else:
# print('He is not eligbe! Turn 18 idiot')
## Write a code where user will give a number(input)
# and you have predefined an another number.
# If it matches with your number then print().
# Else print('You failed')
### Write your code below ###
# num = int(input("Enter a number:"))
# num_2 = 44
# age = 12
# if num == num_2:
# if age>18:
# print("Your guess was right")
# else:
# print('You are under age')
# elif num == 30:
# print("Number was half right")
# else:
# print("you failed")
## MATH, History, Biology , 2 sub( Add them Then take average if average 80 A+, 70 A, 65 A-, 60 B, 50 B- , else F)
# Math = int(input("Enter an number :"))
# History = int(input("Enter an number :"))
# Biology = int(input("Enter an number :"))
# Arts = int(input("Enter an number :"))
# Chemistry = int(input("Enter an number :"))
# avg = (Chemistry + Arts + Biology + History + Math)/5
# print(avg)
# if avg >= 80 :
# print('You got A+')
# elif avg <= 70 :
# print('You got A')
# elif avg <= 65 :
# print('You got A-')
# elif avg <= 60:
# print('You got B ')
# elif avg <= 50 :
# print('You got a B-')
# else :
# print('Sorry Idiot You fail')
# price of house is 1 million dollars. If buyer has good credit , they need to put down 10 %.
#Otherwise they need to put down 20 %. Print the down payment.
# price = 1000000
# has_good_credit = False
# if has_good_credit:
# print(0.1 * price)
# else :
# print(0.2 * price)
# age gender
# age = int(18)
# gender_is_male = True
# gender_is_female = True
# if age >= 18:
# if gender_is_female:
# print("You are eligable")
# else:
# print("Sorry your gender isn't correct")
# else:
# print("You're under age")
import random
x = (1,9)
print(rand.randint(x))
|
6bc8b334d4e1f5b30df281e8bf0e469b85f41337 | daniel-reich/turbo-robot | /tRHaoWNaHBJCYD5Nx_21.py | 721 | 3.96875 | 4 | """
Create a function that returns `True` if two strings share the same letter
pattern, and `False` otherwise.
### Examples
same_letter_pattern("ABAB", "CDCD") ➞ True
same_letter_pattern("ABCBA", "BCDCB") ➞ True
same_letter_pattern("FFGG", "CDCD") ➞ False
same_letter_pattern("FFFF", "ABCD") ➞ False
### Notes
N/A
"""
def same_letter_pattern(txt1, txt2):
l={}
s=[]
d={}
y=[]
c=0
e=0
for t in txt1:
if t in l.keys():
s.append(l[t])
else:
l[t]=c
s.append(c)
c+=1
for p in txt2:
if p in d.keys():
y.append(d[p])
else:
d[p]=e
y.append(e)
e+=1
if s==y:
return True
else:
return False
|
d57d910f9aab6a4df3a529764c57e1627e0f7beb | xiaoqiangcs/LeetCode | /Permutations Sequence.py | 1,303 | 3.578125 | 4 | class Solution(object):
"""
@param n: n
@param k: the k-th permutation
@return: a string, the k-th permutation
"""
def getPermutation(self, n, k):
sequence = [i for i in range(1, n + 1)]
index = 1
for _ in range(1, k):
i = 0
for i in range(n - 2, -1, -1):
if sequence[i] < sequence[i + 1]:
break
index = 0
for index in range(n - 1, i, -1):
if sequence[index] > sequence[i]:
break
sequence[i], sequence[index] = sequence[index], sequence[i]
sequence[i + 1:] = sequence[n - 1:i:-1]
index += 1
result = ""
for j in sequence:
result += str(j)
return result
def getPermutationII(self, n, k):
fact = [1]
for index in range(1, n + 1):
fact.append(fact[-1] * index)
nums = list(range(1, n + 1))
result = []
for i in range(1, n + 1):
number = int((k - 1)/ fact[n - i])
result.append(nums[number])
k = (k - 1) % fact[n - i] + 1
nums.remove(nums[number])
return result
if __name__ == '__main__':
index = Solution().getPermutationII(3, 2)
print(index) |
02d61d8ac5f1ee1187aafafb64d966a6462d81af | AravindVasudev/Machine-Learning-Playground | /DL/ANN/ann.py | 1,736 | 3.671875 | 4 | import numpy as np
class NeuralNetwork():
def __init__(self):
# seeding numpy
np.random.seed(42)
# Init random weights with values in the range -1 to 1 and mean 0
self.synaptic_weights = 2 * np.random.random((3, 1)) - 1
# activation function
def __sigmoid(self, X):
return 1 / (1 + np.exp(-X))
# gradient of the sigmoid curve
def __sigmoid_derivative(self, X):
return X * (1 - X)
def fit(self, X, y, epochs):
for _ in range(epochs):
# pass training data into the network
output = self.__predict(X)
# calculate the error
error = y - output
# calculate adjustment
adjustment = np.dot(X.T, error * self.__sigmoid_derivative(output))
# update the weights
self.synaptic_weights += adjustment
def __predict(self, X):
return self.__sigmoid(np.dot(X, self.synaptic_weights))
def predict(self, X):
return 1 if self.__predict(X) > 0.5 else 0
if __name__ == '__main__':
# init single neuron Neural Network
neural_network = NeuralNetwork()
print('Random Initial Weights:')
print(neural_network.synaptic_weights)
# training set
X = np.array([[0, 0, 1],
[1, 1, 1],
[1, 0, 1],
[0, 1, 1]])
y = np.array([[0, 1, 1, 0]]).T
# train the network
neural_network.fit(X, y, 10000)
print('Weights after training:')
print(neural_network.synaptic_weights)
# test the network
print('Predicting:')
print('[1, 0, 0] =>', neural_network.predict(np.array([1, 0, 0])))
print('[0, 0, 0] =>', neural_network.predict(np.array([0, 0, 0])))
|
5a03db1b796632182238a844f80a8136efe75ad9 | arunmohanan/python | /Practice/tests/TestFibanocciGenerator.py | 1,016 | 3.546875 | 4 | import unittest
from Util import Timer
from Exercise.Practice import FibanocciNumberGenerator
class FibanocciNumberGeneratorTests(unittest.TestCase):
expectedTenFibanocciNumbers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def testFibanocciNumberGenerator(self):
with Timer() as t:
fibanocciNumberGenerator = FibanocciNumberGenerator()
fibanocciNumbers = fibanocciNumberGenerator.getFibanocciUsingForLoop(10)
self.assertEqual(self.expectedTenFibanocciNumbers,fibanocciNumbers)
print (t.interval)
def testFibanocciNumberGeneratorUsingRecursion(self):
fibanocciNumberGenerator = FibanocciNumberGenerator()
fibanocciNumbers = [fibanocciNumberGenerator.getFibanocciNumberUsingRecursion(n) for n in range(10)]
self.assertEqual(self.expectedTenFibanocciNumbers, fibanocciNumbers)
print (fibanocciNumbers)
def main():
unittest.main()
if __name__ == '__main__':
main() |
741c9c48457b97a6438579d91b5a1c92c37be489 | dticed/pythoncoursera | /week6/nim.py | 3,653 | 3.953125 | 4 | import sys
placar_computador = 0
placar_usuario = 0
def main():
partida()
def computador_escolhe_jogada(n,m):
global placar_computador
for i in range(1, m+1):
if ((n - (i + 1)) % (m + 1) == 0):
n = n - 1
if i > 1:
print("O computador tirou " + str(i) + " peças.")
else:
print("O computador tirou uma peça.")
if n > 0:
if n > 1:
print("Agora restam " + str(n) + " peças no tabuleiro.\n")
else:
print("Agora resta apenas uma peça no tabuleiro.\n")
usuario_escolhe_jogada(n,m)
else:
print("Fim do jogo! O computador ganhou!\n")
placar_computador += 1
break
else:
n = n - m
if i > 1:
print("O computador tirou " + str(i) + " peças.")
else:
print("O computador tirou uma peça.")
if n > 0:
if n > 1:
print("Agora restam " + str(n) + " peças no tabuleiro.\n")
else:
print("Agora resta apenas uma peça no tabuleiro.\n")
usuario_escolhe_jogada(n,m)
else:
print("Fim do jogo! O computador ganhou!\n")
placar_computador += 1
break
def usuario_escolhe_jogada(n,m):
global placar_usuario
retirada = int(input("Quantas peças você vai tirar? "))
print()
if retirada > m:
print("Oops! Jogada inválida! Tente de novo.\n")
usuario_escolhe_jogada(n,m)
else:
n = n - retirada
if retirada > 1:
print("Você tirou " + str(retirada) + " peças.")
else:
print("Você tirou uma peça.")
if(n > 0):
if n > 1:
print("Agora restam " + str(n) + " peças no tabuleiro.\n")
else:
print("Agora resta apenas uma peça no tabuleiro.\n")
computador_escolhe_jogada(n,m)
else:
print("Fim do jogo. Você ganhou!\n")
placar_usuario += 1
def partida_isolada():
print("Você escolheu uma partida isolada!")
n = int(input("Quantas peças? "))
m = int(input("Limite de peças por jogada? "))
print()
verifica_inicio(n,m)
return
def campeonato():
print("Você escolheu um campeonato!\n")
rodadas = 1
placar = 0
while rodadas <= 3:
print("**** Rodada", rodadas, "****\n")
rodadas = rodadas + 1
n = int(input("Quantas peças? "))
m = int(input("Limite de peças por jogada? "))
print("")
verifica_inicio(n,m)
return placar
def verifica_inicio(n,m):
if n % (m + 1) == 0:
print("Você começa!\n")
usuario_escolhe_jogada(n,m)
else:
print("Computador começa!\n")
computador_escolhe_jogada(n,m)
def partida():
tipo_partida = input("\nBem-vindo ao jogo do NIM! Escolha:\n\n1 - para jogar uma partida isolada\n2 - para jogar um campeonato ")
print("")
if tipo_partida == "1":
partida_isolada()
sys.exit()
if tipo_partida == "2":
campeonato()
print("**** Final do campeonato! ****\n")
print("Placar: Você " + str(placar_usuario) + " X " + str(placar_computador) + " Computador")
sys.exit()
else:
print("Você digitou o número errado. Encerrando jogo!")
main() |
a211e39468487370a4af797818d362268726b207 | dorisserruto/pythonbasic | /leap_acumulator.py | 392 | 3.59375 | 4 | #!/usr/bin/python
import datetime
def getSumLeap():
sumLeaps = 0
today = datetime.date.today()
proposed_leaps = range(0,today.year,4)
for prop_leap in proposed_leaps:
if isLeap(prop_leap):
sumLeaps+= prop_leap
def isLeap(year):
if (year % 100 > 0): #no divisible
return True
elif (year % 400 > 0):
return True
else:
return False
#def main(argv):
getSumLeap()
raw_input() |
2ffe7136e4bf83b6c62f53614f0967759cb996d9 | josdeivi90/Python_exercise | /fibonacci.py | 459 | 3.640625 | 4 | f_0 = 0
f_1 = 1
f_n = 0
print (f_0)
print (f_1)
while(f_n<50):
f_n = f_0 + f_1
if(f_n >=50):
break
print(f_n)
f_0,f_1 = f_1,f_n
'''def fib(n):
if n < 1:
return None
if n < 3:
return 1
elem1 = elem2 = 1
sum = 0
for i in range(3, n + 1):
sum = elem1 + elem2
elem1, elem2 = elem2, sum
return sum
for n in range(1, 10):
print(n, "->", fib(n))
''' |
857a3949347d405df8897c12a90542aeaae4c0b6 | yzl232/code_training | /mianJing111111/Google/Three coke machines. Each one has two values min & max, which means if you get coke from this machine it will load you a random volume in the range.py | 2,693 | 3.53125 | 4 | # encoding=utf-8
'''
Three coke machines. Each one has two values min & max, which means if you get coke from this machine it will load you a random volume in the range [min, max]. Given a cup size n and minimum soda volume m, show if it's possible to make it from these machines.
'''
# 和另一道coke的题目似乎不大一样。
#应当是用DFS
'''
Assume (x1,y1) , (x2,y2), (x3,y3) are the ranges of the three coke machines.
You have a range (m,n).
As stated before, m < X < Y < n for some (X,Y) to be obtained by a linear combination of the three machines.
Which means K1*x1 + K2*x2 + K3*x3 (= X) > m and K1*y1 + K2*y2 + K3 * y3 (=Y) < n
Take the second equation , we need to find all (K1,K2,K3) < n Start from n-1 (assume everything is an integer here. If not then we can scale the numbers till they become integers).
For every (k1,k2,k3) which satisfies the second equation see if it also satisfies the first equation. If yes , the problem can be solved . If no, decrement Sigma Ki*Xi to n-2 and repeat the algorithm.
It is a brute force approach almost. But it solves definitely.
'''
'''
比如三台machine(50, 100), (100, 200), (500, 1000).
n=110, m=40, yes.
n=90, m=40, no.
n=100, m=60, no
'''
#列出了方程式就清楚了额.
'''
Condition 1 : a1*min1 + a2*min2 + a3*min3 >= l
Condition 2 : a1*max1 + a2*max2 + a3*max3 <= h
'''
#题目是possible。 我觉得如果是某种strategy保证一定实现的话。的话, 才是如下解法
#似乎是机器的范围一定要比杯子小???
class Solution:
def getCoke(self, machines, h, l):
self.machines = machines
return self.dfs(l, h)
def dfs(self, l,h):
if h<0 or l<0: return False
return any((minV <= l and maxV >= h) or self.dfs(l - minV, h - maxV) for minV, maxV in self.machines)
s= Solution()
print s.getCoke([(50, 100), (100, 200), (500, 1000)], 110, 40)
print s.getCoke([(50, 100), (100, 200), (500, 1000)], 90, 40)
print s.getCoke([(50, 100), (100, 200), (500, 1000)], 100, 60)
#喝这道题目一样。
'''
A soda water machine,press button A can generate 300-310ml, button B can generate 400-420ml and button C can generate 500-515ml, then given a number range [min, max], tell if all the numers of water in the range can be generated.
class Solution:
def generate(self, minV, maxV):
dp = [False ] *(maxV+1);
canGen=range(300, 311)+range(400, 421)+range(500, 515)
for x in canGen: dp[x]=True
for i in range(516, maxV+1):
for j in canGen:
if dp[i-j]:
dp[i] = True; break
return False not in dp[minV:maxV+1]
s = Solution()
print s.generate(700, 721)
''' |
75d82d4b9e1f126685e0a62b9e22d4d154d33c89 | adgarciaar/HackerRankInterviewPreparationExercises | /Warm-up Challenges/RepeatedString.py | 965 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 01:00:41 2020
@author: adgar
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
ocurrences_first = 0
for i in range(0, len(s)):
if(s[i] == "a"):
ocurrences_first = ocurrences_first + 1
x = int(n / len(s))
remainder = n % len(s)
ocurrences = ocurrences_first*x
substring = s[0:remainder]
ocurrences_second = 0
for i in range(0, len(substring)):
if(substring[i] == "a"):
ocurrences_second = ocurrences_second + 1
ocurrences = ocurrences + ocurrences_second
return ocurrences
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = "aba"
n = 10
result = repeatedString(s, n)
print(str(result) + '\n')
#fptr.close()
|
e4d61d9987b7381cca5709af3c86ae0cd3cb1f85 | EinarK2/einark2.github.io | /Forritun/Forritun 1/Verkefni 1/Skilaverkefni 1.py | 1,791 | 3.625 | 4 | #Höfundur Einar Karl Pétursson 27/08/2018
#Liður 1
print("#Liður 1")
nafn=input("Hvað heitir notandinn? ") #Forritið spyr notandann um nafn
#Útskrift
print("Velkominn í áfangann FOR1TÖ3AU",nafn+".","Þetta verður skemmtileg önn, ég hlakka til að læra forritun.")
#Liður 2
print("#Liður 2")
tala=float(input("Sláðu inn kommutölu með þrem aukastöfum. ")) #Forritið spyr notandann um einhverja tölu með þrem aukastöfum
#Útskrift
print("Þú hefur valið töluna:",round(tala,1))
#Liður 3
print("#Liður 3")
tala2=int(input("Sláðu inn tölu ")) #Forritið spyr notandann um tvær tölur
tala3=int(input("Sláðu inn aðra tölu "))
#Útskrift
print("Margfeldi talnanna er:",tala2*tala3)
print("Frádráttur talnanna er:",tala2-tala3)
#Liður 4
print("#Liður 4")
haed=int(input("Sláðu inn hæð á kassa ")) #Forritið spyr notandann um hæð, lengd, og breidd á kassa
lengd=int(input("Sláðu inn lengd kassans "))
breidd=int(input("Sláðu inn breidd kassans "))
#Útskrift
print("Rúmmál kassans er:",haed*lengd*breidd)
#Liður 5
print("#Liður 5")
aldur1=int(input("Hver er aldur þinn? ")) #Forritið spyr um aldur notandanns og einnig pabba hans
aldur2=int(input("Hver er aldur pabba þíns? "))
#Útskrift
print("Pabbi þinn var",aldur2-aldur1,"ára þegar þú fæddist")
#Liður 6
print("#Liður 6")
aldur3=int(input("Sláðu inn aldur á einstaklingi ")) #Forritið spyr um aldur á þrem einstaklingum.
aldur4=int(input("Sláðu inn aldur á öðrum einstaklingi "))
aldur5=int(input("Sláðu inn aldur á öðrum einstaklingi "))
medaltala=aldur3+aldur4+aldur5 #Hér er summan á öldrunum
#Útskrift
print("Meðalaldur einstaklingana er",medaltala/3)
#Lok
print("Gaman að geta aðstoðað þig við þessa útreikninga",nafn+".","Hafðu það gott í dag :)")
|
ebf5601f9a3f56a47412797a3608648fdd0f6b18 | gabriellaec/desoft-analise-exercicios | /backup/user_286/ch158_2020_06_09_20_00_21_827161.py | 181 | 3.5 | 4 | contador = 0
with open('texto.txt', 'r') as arquivo:
conteudo = arquivo.read()
lista = conteudo.split()
for a in lista:
if a != ' ':
contador += 1
print(contador) |
d4e9dbba741fa0328b743d3ab15f4b540ca96b1f | yunchan312/assignment_2 | /calculator2.py | 912 | 3.5 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
class Calculator:
def __init__(self):
self.Value = 0
self.memory = 0
def setValue(self, x):
self.Value = x
def getValue(self):
return self.Value
def add(self, x):
self.Value += x
def sub(self, x):
self.Value -= x
def mpy(self, x):
self.Value *= x
def div(self, x):
self.Value //= x
def mod(self, x):
self.Value %= x
def changeSign(self):
self.Value = -self.Value
def clear(self):
self.Value = 0
def memorySave(self):
self.memory = self.Value
def memoryRead(self):
self.Value = self.memory
return self.Value
def memoryClear(self):
self.Value = 0
def memoryAdd(self):
self.memory += self.Value
def memorySub(self):
self.memory -= self.Value
|
b6355c85911eec5e21920d6e9daa8346ab29ef03 | nirajkvinit/python-programming-exercises-1 | /Exercises/Exercise24.py | 353 | 3.78125 | 4 | # Making a game board
not_ok = 1
while not_ok:
try:
x = int(input("What size game board you want to draw: "))
not_ok = 0
except ValueError:
continue
v_cell = " --- "
h_cell = "| |"
b_width = v_cell * x
c_edge = h_cell * x
for i in range(x):
print(b_width)
print(c_edge)
print(b_width) |
dd12fe3362ebf3ac40f24fa6f7cf36c04982750d | aeciovc/sda_python_ee4 | /SDAPythonBasics/strings.py | 893 | 4.15625 | 4 | # Prints the number of characters in the sequence
sentence = "Lorem ipsum dolor sit amet..."
amount = len(sentence)
print(amount) # Prints 29
hello = "Hello, World!"
amount_app = hello.count('o', 0, 8)
print(amount_app) # Prints 4
# List and strings
list_of_letters = ['A', 'E', 'C', 'I', 'O']
string_of_letters = 'AECIO'
name = 'Aecio Costa'
name1 = 'A'
age = 1
print(f" The type for string_of_letters is {type(string_of_letters)}")
print(f" The type for list_of_letters is {type(list_of_letters)}")
index = 0
print(string_of_letters[index], end='!')
print(string_of_letters[1], end='!')
print(string_of_letters[2], end='!')
print(string_of_letters[3], end='')
print(string_of_letters[4])
print(list_of_letters[0])
#
start = 7
stop = 12
step = 2
hello = "Hello, World!"
print(hello[start:len(hello):step])
# Upper
hello = "Hello, World!"
print(hello.upper()) # Prints HELLO, WORLD! |
a8fe8424c4fbdc3c051d9e022daedf318f38cd0b | bgoonz/UsefulResourceRepo2.0 | /_OVERFLOW/Resource-Store/01_Questions/_Python/squarecube.py | 1,285 | 4 | 4 | # pre code
def square():
print(" ")
makeUse = raw_input("Square or Cube : ")
if makeUse.strip() == "Square":
print(" ")
user = int(raw_input("Enter number to get square : "))
square = user ** 2
print(" ")
print("Square of the number " + str(user) + " is " + str(square))
elif makeUse.strip() == "Cube":
print(" ")
userAgain = int(raw_input("Enter number to get square : "))
cube = userAgain ** 3
print(" ")
print("Cube of the number " + str(userAgain) + " is " + str(cube))
# main code
while True:
print("Hello,")
print(" ")
startOrEnd = raw_input("Start or End : ")
print(" ")
if startOrEnd.strip() == "Start":
print(square())
elif startOrEnd.strip() == "End":
print(" ")
print(" ")
print("Program Ended......")
break
else:
print(" ")
print("Try Again")
continue
startagain = "Start again or End : "
print(" ")
if startagain.strip() == "Start again":
print(" ")
print("Starting again.....")
continue
elif startagain == "End":
print(" ")
print(" ")
break
else:
print(" ")
print("Try Again")
continue
|
44fbad1122120bba3783a59e92d01a8329e35fd2 | sharmaatul9654/python-program | /greatest.py | 178 | 4.09375 | 4 | a=int(input('enter the number'))
b=int(input('enter b'))
c=int(input('enter c'))
d= 'a is greater' if a>b and a>c else 'b is greater' if b>a and b>c else 'c is greater'
print(d)
|
179784558ec7b24988745758080d993cedfbbe77 | sgmpy/TIL | /startcamp/day02/for_variable.py | 61 | 3.59375 | 4 | items = ['1','2','3']
for i in items:
print(i)
print(i) |
1fa120effad783358b862faa920ca9a8115a6665 | samzhengkangliu/flask-REST-api | /python-refresher/functions/lamda_functions.py | 433 | 4.03125 | 4 | def add(x, y):
return x + y
# Lambda version: Normally we don't give it a name
# if need a name just name it like: add = lambda
lambda x, y: x + y
def double(x):
return x*2
sequence = [1, 3, 5, 7]
# lambda version
doubled = [(lambda x: x * 2)(x) for x in sequence]
doubled = list(map(lambda x: x * 2, sequence))
# List comprehension version
doubled = [double(x) for x in sequence]
# map
doubled = map(double, sequence) |
2b4d8810a897945cfdd89b30c2e9ce13cb2862be | ANh0r/LeetCode-Daily | /9.8 combine.py | 759 | 3.5625 | 4 | """
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
return list(itertools.combinations(range(1,n+1),k))
"""
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if n < k or n < 1:
return []
if k == 0:
return [[]]
if n == k:
return [[i for i in range(1, n + 1)]]
ans1 = self.combine(n - 1, k - 1)
ans2 = self.combine(n - 1, k)
# printrint(n, k, ans1, ans2)
if ans1:
for i in ans1:
i.append(n)
return ans1 + ans2
t = Solution()
print(t.combine(4,3)) |
3055413e03d6106999afdd6ceb6044a4c6ec52a0 | averycordle/csce204 | /exercises/mar16/smile_click.py | 1,048 | 3.90625 | 4 | #Author: Avery Cordle
import turtle
turtle.bgcolor("skyblue")
turtle.setup(575,575)
pen = turtle.Turtle()
pen.pensize(3)
pen.speed(.5)
pen.color("black")
pen.hideturtle()
smileRadius = 50
def draw_smiley(x,y):
draw_head(x,y)
draw_eye(x-smileRadius/3,y+smileRadius)
draw_eye(x+smileRadius/3,y+smileRadius)
draw_mouth(x-smileRadius/2.5,y+smileRadius/1.5)
def draw_head(x,y):
pen.penup()
pen.setpos(x,y)
pen.pendown()
pen.fillcolor("yellow")
pen.begin_fill()
pen.circle(smileRadius)
pen.end_fill()
def draw_eye(x,y):
pen.penup()
pen.setpos(x,y)
pen.pendown()
pen.fillcolor("black")
pen.begin_fill()
pen.circle(smileRadius/10)
pen.end_fill()
def draw_mouth(x,y):
pen.penup()
pen.setpos(x,y)
pen.pendown()
pen.setheading(-60)
pen.circle(smileRadius/2, 120)
pen.setheading(0)
turtle.onscreenclick(draw_smiley) #on screen click automatically passes in the function so we son't have to add (x,y)
turtle.done() |
be036ffa504d69d0f54f25d31f50cc1bdc56414c | takumiw/AtCoder | /ABC058/B.py | 183 | 3.703125 | 4 | O = input()
E = input()
if len(O) > len(E):
for o, e in zip(O[:-1], E):
print(o + e, end='')
print(O[-1])
else:
for o, e in zip(O, E):
print(o + e, end='') |
c9b51fc98a07f3dac6ef52246f30f1a3b19ceeae | assassint2017/leetcode-algorithm | /Odd Even Linked List/Odd_Even_Linked_List.py | 921 | 4 | 4 | # Runtime: 48 ms, faster than 89.44% of Python3 online submissions for Odd Even Linked List.
# Memory Usage: 15.1 MB, less than 6.02% of Python3 online submissions for Odd Even Linked List.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
oddHead = ListNode(0)
evenHead = ListNode(0)
oddptr = oddHead
evenptr = evenHead
while head:
oddptr.next = head
oddptr = oddptr.next
head = head.next
if head is None:
break
evenptr.next = head
evenptr = evenptr.next
head = head.next
evenptr.next = None
oddptr.next = evenHead.next
return oddHead.next |
b3f373d175a12838a8877b8e1943d09f585f4f27 | minhvip2001/pythonproject | /Week1_PyThonBasic/Beginner/Exercise10.py | 349 | 3.796875 | 4 | def mergeList(lis1, list2):
print("list1 =", list1)
print("list2 =", list2)
list3 = []
for i in list1:
if(i % 2 == 1):
list3.append(i)
for i in list2:
if(i % 2 == 0):
list3.append(i)
return list3
list1 = [10, 20, 23, 11, 17]
list2 = [13, 43, 24, 36, 12]
print("Result List is", mergeList(list1, list2)) |
15a35248faa38de93290f409d188b45e244c6a74 | shiki7/Atcoder | /ABC216/A.py | 133 | 3.671875 | 4 | S = input()
x, y = S.split('.')
if 0 <= int(y) <= 2:
print(x + '-')
elif 3 <= int(y) <= 6:
print(x)
else:
print(x + '+')
|
af7ced082e9912430bdeb0107fba281f0216f52e | dynotw/Leetcode-Lintcode | /LeetCode/28. Implement strStr().py | 942 | 3.96875 | 4 | # Question:
# Implement strStr().
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack, or return 0 when needle is empty.
"""The first of occurrence means the first index when needle occurs in haystack """
# Answer:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
if needle in haystack:
# if needle[0] in haystack:
# return haystack.index(needle[0])
# for i in len(aystack):
# for j in len(needle):
# if haystack[i] == needle[j]:
"""The above are wrong code, which is programmmed when I misunderstand the question"""
return haystack.find(needle)
# defination 'find' return the first index where 'needle' occur
else:
return -1
|
d8d477bd49716f31d30aab52fadbee26578d7bf2 | kapitalistka/GBpythonLessons | /lesson4/ex2.py | 3,488 | 3.703125 | 4 | # Эти задачи необходимо решить используя регулярные выражения!
# Задача - 1
# Запросите у пользователя имя, фамилию, email. Теперь необходимо совершить проверки, имя и фамилия должны иметь заглавные первые буквы.
# email - не должен иметь заглавных букв и должен быть в формате: текст в нижнем регистре, допускается нижнее подчеркивание и цифры,
# потом @, потом текст, допускаются цифры, точка, ru или org или com.
# Например:
# Пупкин василий - неверно указано имя, [email protected] - неверно указан email (спецсимвол, заглавная буква, .net), [email protected] - верно указан.
import re
name = input("Input your name: ")
lastname = input("Input your last name: ")
email = input("Input your email: ")
name_pattern = '[A-ZА-Я][A-ZА-Яa-zа-я]+'
email_pattern = '([a-z_0-9]+)@[a-z-0-9]+\.(ru|com|org)$'
print(f"{name} name is incorrect" if re.match(name_pattern, name) == None else "Name is correct")
print(f"{lastname} last name is incorrect" if re.match(name_pattern, lastname) == None else "Last name is correct")
print(f"{email} email is incorrect" if re.match(email_pattern, email) == None else "Email is correct")
# Задача - 2:
# Вам дан текст:
some_str = '''
Мороз и солнце; день чудесный!
Еще ты дремлешь, друг прелестный —
Пора, красавица, проснись:
Открой сомкнуты негой взоры
Навстречу северной Авроры,
Звездою севера явись!
Вечор, ты помнишь, вьюга злилась,
На мутном небе мгла носилась;
Луна, как бледное пятно,
Сквозь тучи мрачные желтела,
И ты печальная сидела —
А нынче... погляди в окно:
Под голубыми небесами
Великолепными коврами,
Блестя на солнце, снег лежит;
Прозрачный лес один чернеет,
И ель сквозь иней зеленеет,
И речка подо льдом блестит.
Вся комната янтарным блеском
Озарена. Веселым треском
Трещит затопленная печь.
Приятно думать у лежанки.
Но знаешь: не велеть ли в санки
Кобылку бурую запречь?
Скользя по утреннему снегу,
Друг милый, предадимся бегу
Нетерпеливого коня...
И навестим поля пустые,
Леса, недавно столь густые,
И берег, милый для меня.'''
# Необходимо с помощью регулярных выражений определить есть ли в тексте подряд
# более одной точки, при любом исходе сообщите результат пользователю!
pattern='(\.){2,}'
print('Определяем, есть ли в тексте подряд более одной точки:')
print('есть' if re.search(pattern,some_str)!=None else "нет") |
d27df5e4bb337705ebadf2b7623776030ebdeedc | joel-lim/Advent-Of-Code-2020 | /day12/main.py | 615 | 4.03125 | 4 | """
https://adventofcode.com/2020/day/12
"""
from ship import Ship, ShipWithWaypoint
FILE = 'input.txt'
def main():
ship1 = Ship()
ship2 = ShipWithWaypoint()
instructions = parse_input(FILE)
for instruction in instructions:
ship1.read(instruction)
ship2.read(instruction)
print(f'Part 1: {ship1.manhattan_distance()}')
print(f'Part 2: {ship2.manhattan_distance()}')
def parse_input(file):
"""
Parses an input file to obtain a list of instructions
"""
with open(file) as f:
return [line[:-1] for line in f]
if __name__ == '__main__':
main()
|
2aeb6382452f9d617d04330ede244bbd2c50c1cd | Cyber-code/Projet_python | /class/Transaction.py | 4,819 | 3.84375 | 4 | from Interaction import Interaction
from Merchant import Merchant
from Player import Player
class Transaction(Interaction):
""" Transaction class instantiate a transaction object where the player buy or objects with a merchant. """
def __init__(self, player, merchant):
Interaction.__init__(self, player, merchant)
def run(self):
""" This method starts the transaction with the merchant. """
print("You meet a {}.".format(self.mob.name.lower()))
print("You have {} gold.".format(self.player.inventory.gold))
while(True):
if(self.selectAction() in [True, "exit"]):
break
print("\nYou leave the transaction.")
self.player.statistics.merchantsMet += 1
return True
def selectAction(self):
""" This method allows the player to choose an action during a transaction. """
print("\nSelect your action")
print("0 - Leave transaction")
print("1 - Buy an object")
print("2 - Sell an object")
print("3 - Use a consumable")
print("4 - Equip with an object")
print("5 - Take off an object")
print("6 - Show bars (health, shield, mana)")
print("7 - Show infos")
print("8 - Show inventory")
print("9 - Show statistics")
print("10 - Show success")
print("11 - Save and exit")
choice = str()
while(choice not in [str(i) for i in range(12)]):
choice = input("Your action: ")
print("--------------------------------------------------")
choice = int(choice)
# Leave transaction
if(choice == 0):
return True # Leave the loop in the method run
# Buy an object
elif(choice == 1):
choice2 = self.selectObjectToBuy()
if(choice2 > -1):
self.player.buyItem(self.mob.inventory.objects[choice2])
# Sell an object
elif(choice == 2):
choice2 = self.selectObjectTosell()
if(choice2 > -1):
self.player.sellItem(self.player.inventory.objects[choice2])
# Use a consumable
elif(choice == 3):
choice2 = self.selectConsumable()
if(choice2 > -1):
self.player.use(choice2)
# Equip with an object
elif(choice == 4):
(choice2, slot) = self.selectObjectToEquip()
if(choice2 > -1):
self.player.equipItem(self.player.inventory.objects[choice2], slot)
# Take off an object
elif(choice == 5):
choice2 = self.selectObjectToDequip()
if(choice2 != None):
self.player.dequipItem(choice2)
# Show player's bars
elif(choice == 6):
print(self.player.showBars())
# Show player's info
elif(choice == 7):
print(self.player.showInfo())
# Show player's inventory
elif(choice == 8):
print(self.player.showInventory())
# Show player's statistics
elif(choice == 9):
print(self.player.showStatistics())
# Show player's success
elif(choice == 10):
print(self.player.showSuccess())
# Save and exit
elif(choice == 11):
self.player.save()
return "exit" # Leave the loop in the method run
return False
def selectObjectToBuy(self):
""" This method allows the player to choose wich objects on sale from Merchant inventory he could buy. """
print("\nSelect the object to buy: ")
print("-1 - Previous")
objectIndex = ['-1']
for i,objects in enumerate(self.mob.inventory.objects):
print(i, " - ", objects.showInfo())
objectIndex.append(str(i))
choice = str()
while(choice not in objectIndex):
choice = input("Object to buy: ")
print("--------------------------------------------------")
return int(choice)
def selectObjectTosell(self):
""" This method allows the player to choose wich objects he could sell from his inventory. """
print("\nSelect the object to sell: ")
print("-1 - Previous")
objectIndex = ['-1']
for i,objects in enumerate(self.player.inventory.objects):
print(i, " - ", objects.showInfo())
objectIndex.append(str(i))
choice = str()
while(choice not in objectIndex):
choice = input("Object to sell: ")
print("--------------------------------------------------")
return int(choice) |
47501fbfc8ced59d4360f2f8fbf8ae3b536ef1b6 | VamsikrishnaNallabothu/MITx-My-Python-Work | /ps4/ps4-3.py | 467 | 4 | 4 | def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
letters = getFrequencyDict(word)
for c in letters:
if letters[c] > hand.get(c, 0):
return False
return word in wordList |
920e699260f6e2c1b6dd65a0684c25122bd1fd90 | Aasthaengg/IBMdataset | /Python_codes/p02627/s733988493.py | 75 | 3.796875 | 4 | x = input()
if x.islower():
print('a')
elif x.isupper():
print('A') |
b20c123c501c5dd466b69abddeb0329fde7fbc8c | Lightman-EL/Python-by-Example---Nikola-Lacey | /N1_The_Basics/006.py | 194 | 4.09375 | 4 | slides = int(input("With how many slides of pizza you started with? "))
eaten = int(input("\nHow many slides of pizza you have eaten? "))
print("\n", slides - eaten, " slides of pizza remain") |
b5b1eb7994cdbf8e6f4459a18e69e963aed37d09 | Anastasia-Cloud/LearnPython | /task16.py | 632 | 3.71875 | 4 | '''
Даны две строки S1 и S2 . Длины строк не превосходят 1000000. Найдите их наибольшую по длине общую подстроку.
'''
def fixSubstr(l,s1,s2):
m=set()
for i in range(len(s1)-l+1):
m.add(s1[i:i+l])
for i in range(len(s2)-l+1):
if s2[i:i+l] in m:
return s2[i:i+l]
def maxSubstr(s1,s2):
l=min(len(s1),len(s2))
for i in range(l,0,-1):
res=fixSubstr(i,s1,s2)
if res is not None:
return res
print(maxSubstr('aabcdeabcdef','acdeabf'))
print(maxSubstr('aabcdeabcdef','aabcdea def'))
print(maxSubstr('qwerty','123'))
|
d9583966b08b2d65aee5069de21545afc534a3ac | seboldt/ListaDeExercicios | /EstruturaSequencial/03-Soma.py | 155 | 3.890625 | 4 | a = float(input('Informe o primeiro numero da soma \n'))
b = float(input('Informe o segundo nuemro da soma \n'))
soma = a + b
print(f'A soma é {soma}')
|
5a63859a428f009b3c1cd1b3d8676b3b93f7fbfc | sbeleidy/406-AlgoBOWL | /solver.py | 8,487 | 4.125 | 4 | import random, itertools, time
def getManhattan(pOne, pTwo):
"""
Returns the Manhattan Distance between two points
"""
return abs(pOne[0] - pTwo[0]) + abs(pOne[1] - pTwo[1]) + abs(pOne[2] - pTwo[2])
def getMaxManhattan(allPoints, indexes):
"""
Returns the maximum Manhattan Distance between each 2 point combination in a subset of all points
"""
maxManhattan = 0
points = [allPoints[i] for i in indexes]
combs = itertools.combinations(points,2)
for combination in combs:
dist = getManhattan(combination[0], combination[1])
if dist > maxManhattan:
maxManhattan = dist
return maxManhattan
def getSetsScore(points,sets):
"""
Returns the score of sets of point groups
(The maximum Manhattan Distance between each 2 point combination in each subset)
"""
maxDistance = 0
for set in sets:
dist = getMaxManhattan(points, set)
if dist > maxDistance:
maxDistance = dist
return maxDistance
def randomAlg(n,k,points):
"""
A random algorithm for determining the sets of points to give the minMax
Uses the same subset length for all subsets
Returns the sets of points
"""
p = list(range(n))
random.shuffle(p)
sets = []
for i in range(k):
if i == k-1:
sets.append(p[int(i*(n/k)):])
else:
sets.append(p[int(i*(n/k)):int(i*(n/k) + (n/k))])
return sets
def selectRandomStartingPoints(points, k):
return random.sample(range(len(points)), k)
def selectRandomStartingCoords(points, k):
return random.sample(points, k)
def selectGoodStartingCoords(k, r=False):
goodPoints = [
[500, 500, 500],
[-500, -500, -500],
[0, 0, 0],
[500, 0 ,500],
[500, 500, 0],
[0, 500, 500],
[-500, 0 ,-500],
[-500, -500, 0],
[0, -500, -500],
[0, 0, 500],
[0, 500, 0],
[500, 0, 0],
[0, 0, -500],
[0, -500, 0],
[-500, 0, 0],
[750, 750, 750],
[-750, -750, -750],
[750, 0, 750],
[750, 750, 0],
[0, 750, 750],
[750, 0, 0],
[0, 750, 0],
[0, 0, 750],
[-750, 0, -750],
[-750, -750, 0],
[0, -750, -750],
[-750, 0, 0],
[0, -750, 0],
[0, 0, -750],
[250, 250, 250],
[-250, -250, -250],
[250, 0, 250],
[250, 250, 0],
[0, 250, 250],
[250, 0, 0],
[0, 250, 0],
[0, 0, 250],
[-250, 0, -250],
[-250, -250, 0],
[0, -250, -250],
[-250, 0, 0],
[0, -250, 0],
[0, 0, -250]
]
if r:
return random.sample(goodPoints,k)
else:
return goodPoints[0:k]
def getAllDistancesFromPoint(points, pointIndex):
return [getManhattan(points[pointIndex], i) for i in points]
def getAllDistancesFromMultiplePoints(points, indexes):
return [[getManhattan(point, points[index]) for index in indexes ] for point in points]
def getAllDistancesFromCoords(points, coords):
return [[getManhattan(point, coord) for coord in coords ] for point in points]
def getSetsFromStartingPoints(points, startingIndexes):
allDistances = getAllDistancesFromMultiplePoints(points, startingIndexes)
setIndex = [distances.index(min(distances)) for distances in allDistances]
sets = [[] for i in range(len(startingIndexes))]
for i in range(len(points)):
sets[setIndex[i]].append(i)
return sets
def getSetsFromStartingCoords(points, startingCoords):
allDistances = getAllDistancesFromCoords(points, startingCoords)
setIndex = [distances.index(min(distances)) for distances in allDistances]
sets = [[] for i in range(len(startingCoords))]
for i in range(len(points)):
sets[setIndex[i]].append(i)
return sets
def randomStartingPointAlgorithm(n,k,points):
start = selectRandomStartingPoints(points, k)
return getSetsFromStartingPoints(points, start)
def iterateAlgorithm(n,k,points, start, iteratorAlg, iterations):
bestSets = getSetsFromStartingCoords(points,start)
bestScore = getSetsScore(points, bestSets)
newSets = bestSets
for i in range(iterations):
start = getNewStart(points, newSets, iteratorAlg)
newSets = getSetsFromStartingCoords(points, start)
newScore = getSetsScore(points, newSets)
if newScore < bestScore:
bestSets = newSets
bestScore = newScore
return bestScore, bestSets
def getNewStart(points, sets, alg):
start = []
for aSet in sets:
if len(aSet) >=2:
start.append(alg([points[i] for i in aSet]))
return start
def findGeometricCenter(set):
xs = [p[0] for p in set]
ys = [p[1] for p in set]
zs = [p[2] for p in set]
minX = min(xs)
minY = min(ys)
minZ = min(zs)
centerX = abs(max(xs) - minX)/2 + minX
centerY = abs(max(ys) - minY)/2 + minY
centerZ = abs(max(zs) - minZ)/2 + minZ
return [centerX, centerY, centerZ]
def findMean(set):
xs = [p[0] for p in set]
ys = [p[1] for p in set]
zs = [p[2] for p in set]
meanX = sum(xs)/len(xs)
meanY = sum(ys)/len(ys)
meanZ = sum(zs)/len(zs)
return [meanX, meanY, meanZ]
def useAlgorithm(algorithm, n, k, points, runs):
"""
A way to run an algorithm several times and get the best run score and best set
"""
bestScore = 100000000
bestSet = []
for i in range(runs):
thisSet = algorithm(n,k,points)
thisScore = getSetsScore(points, thisSet)
if thisScore < bestScore:
bestScore = thisScore
bestSet = thisSet
return bestScore, bestSet
def solve(n, k, points):
bestScore = 10000000
bestSets = []
winningAlgorithm = "NA"
## General Random Algorithm
start = time.clock()
randomScore, randomSets = useAlgorithm(randomAlg, n, k, points, 1000)
if randomScore < bestScore:
bestScore = randomScore
bestSets = randomSets
winningAlgorithm = "General Random"
print("General Random took {} seconds".format(str(time.clock() - start)))
## Nearest Neighbor Random Start
start = time.clock()
nnRandomScore, nnRandomSets = useAlgorithm(randomStartingPointAlgorithm, n, k, points, 1000)
if nnRandomScore < bestScore:
bestScore = nnRandomScore
bestSets = nnRandomSets
winningAlgorithm = "NN Random Start"
print("NN Random Start took {} seconds".format(str(time.clock() - start)))
iteratorAlgorithms = {
'Mean': findMean,
'Geometric Center': findGeometricCenter
}
for algName in iteratorAlgorithms:
## Iterative Nearest Neighbor Random Start
start = time.clock()
for i in range(50):
iterativeRandomScore, iterativeRandomSets = iterateAlgorithm(n, k, points, selectRandomStartingCoords(points, k), iteratorAlgorithms[algName], 100)
if iterativeRandomScore < bestScore:
bestScore = iterativeRandomScore
bestSets = iterativeRandomSets
winningAlgorithm = "Iterative Random Start - " + algName
print("Iterative Random Start - {} took {} seconds".format(algName, str(time.clock() - start)))
## Iterative Nearest Neighbor Good Start
start = time.clock()
iterativeGoodScore, iterativeGoodSets = iterateAlgorithm(n, k, points, selectGoodStartingCoords(k), iteratorAlgorithms[algName], 100)
if iterativeGoodScore < bestScore:
bestScore = iterativeGoodScore
bestSets = iterativeGoodSets
winningAlgorithm = "Iterative Good Start - " + algName
print("Iterative Good Start - {} took {} seconds".format(algName, str(time.clock() - start)))
## Iterative Nearest Neighbor Random Good Start
start = time.clock()
for i in range(10):
iterativeRandomGoodScore, iterativeRandomGoodSets = iterateAlgorithm(n, k, points, selectGoodStartingCoords(k, True), iteratorAlgorithms[algName], 100)
if iterativeRandomGoodScore < bestScore:
bestScore = iterativeRandomGoodScore
bestSets = iterativeRandomGoodSets
winningAlgorithm = "Iterative Random Good Start - " + algName
print("Iterative Random Good Start - {} took {} seconds".format(algName, str(time.clock() - start)))
return bestScore, bestSets, winningAlgorithm
|
7fc07679580cdd91326abf25cde9078b0b1f0b91 | kakakeven/kaka-python-practice | /Day04/while_loop_guess.py | 453 | 3.625 | 4 | '''
猜数字游戏
@author: kakakeven
'''
import random
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
guess = int(input("请输入: "))
if guess > answer:
print("小一点!")
elif guess < answer:
print("大一点!")
else:
print("恭喜你,猜对了!")
break
print('你一共猜了 %d 次' % counter)
if counter > 7:
print("你的智商余额明显已不足!")
|
1429b157c040800f2045afe903cbe4e7b99c768d | acdlee/Interview-Prep | /ctci/chapters/chpt4/4_2.py | 1,134 | 3.890625 | 4 | #O(nlgn) to create a BST time
#O(n) storage since we're making n nodes
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertBST(node, val):
if not node:
return Node(val)
if val < node.val:
node.left = insertBST(node.left, val)
elif node.val < val:
node.right = insertBST(node.right, val)
else:
#if we repeat a value, dont add another node
return node
return node
def createTree(arr):
#take the middle value and make it the root
# bst = insertBST(None, arr[len(arr)//2])
# for val in arr:
# bst = insertBST(bst, val)
# return bst
return linearSol(arr, 0, len(arr) - 1)
def inOrder(node):
if not node: return
inOrder(node.left)
print(node.val)
inOrder(node.right)
#linear time and space
#we only visit each node once (no extra traversals)
def linearSol(arr, left, right):
if left > right: return None
mid = (left + right) // 2
node = Node(arr[mid])
node.left = linearSol(arr, left, mid - 1)
node.right = linearSol(arr, mid + 1, right)
return node
arr = [3,515,1,23,1,6,10]
arr.sort()
bst = createTree(arr)
inOrder(bst) |
48254bff1432603541f3c397d4861f5833a2e3ad | aojugg/leetcode | /21_MERGE_two_sorted_lists.py | 744 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p1=l1
p2=l2
node=ListNode(0)
q=node
while p1 is not None and p2 is not None:
if p1.val<p2.val:
q.next=p1
p1=p1.next
q=q.next
else:
q.next=p2
p2=p2.next
q=q.next
if not p1:
q.next=p1
if not p2:
q.next=p2
return node.next
|
3bfbd87a83570a274a2facb4a6741514f4e56385 | danielsan98/Curso-de-Python | /Clase python/Caracteres.py | 598 | 3.921875 | 4 | miCadena = input("Dame un a palabra:")
primeraL = miCadena[0]
ultimaL = miCadena[len(miCadena)-1]
print("\n")
print("La primera letra de tu cadena es:", primeraL)
print("\n")
print("La ultima letra de tu cadena es:", ultimaL)
print("\n")
print("La longitud de la cadena es:", len(miCadena))
print("\n")
print("----------------------------------")
var = input("Dame otra palabra: ")
print("Tu palabra es:", var)
var2 = int(input("Escribe el indice del caracter que quieras ver:"))
print("\nEl caracter es:", var[var2])
input("\n Presiona cualquier tecla para continuar")
|
69e9899f189caf9f919fa24bf2ad03c6cdf144c7 | cauegonzalez/exerciciosCursoPythonUsp | /ordemInversa.py | 240 | 3.890625 | 4 |
lista = []
n = int(input('Digite um número (zero para parar): '))
while n != 0:
lista.append(n)
n = int(input('Digite um número (zero para parar): '))
i = len(lista)
while i > 0:
print(lista[i-1], end = ', ')
i = i - 1 |
08e4a844963910ad7f62052c1faf79beffe1d383 | Fjmr18/IPS | /CPeD/Labs/Lab2/fiboSeq.py | 586 | 3.859375 | 4 | # Computação Paralela e Distribuída 2020/2021
# Aluno: Fernando Ramalho 200290040 BS (BrightStart 2ª Edição)
# Aluno: Antonio Costa 200221097 (BrightStart 2ª Edição)
#############################################
import checkSys as check
print(check.get_processsor_info())
import random
def fibonacci(input):
a, b = 0, 1
for item in range(input):
a, b = b, a + b
print(f"F({input}) = {a}")
if __name__ == '__main__':
valores = []
for i in range(50):
number=random.randint(0,100)
valores.append(number)
for val in valores:
fibonacci(val) |
eca86d913763c8acba2df72ce6d6037b10f75fe7 | perjlieb/Freyja | /freyja/fastwalshtransform.py | 968 | 3.78125 | 4 | import numpy as np
def ispoweroftwo(num):
"""
Check if num is power of 2
"""
return num > 0 and ((num & (num - 1)) == 0)
def ceilpoweroftwo(num):
"""
Rounds num up to the next power of 2
"""
x = 1
while(x < num):
x *= 2
return x
def fastwalshtransform(x):
"""
Peforms the fast Walsh transform on the input signal
and returns the Walsh coefficients,
see Beer, Am. J. Phys 49 (1981).
x: input signal
N: fwt size
returns z: Walsh coefficients
"""
N = x.size
# Check if N is a power of 2
if not(ispoweroftwo(N)):
N = ceilpoweroftwo(N)
dN = N - x.size
x = np.append(x,np.zeros(dN))
z = np.zeros(N)
M = 1
while M != N:
points = range(0, N, 2*M)
for i in points:
for j in range(2*M):
z[i+j] = x[i+(j//2)] + ((-1)**(j+(j//2))) * x[i+(j//2)+M]
x[:] = z[:]
M *= 2
return z/np.sqrt(N)
|
826cd2b8df8bcff04ec971f83320805a8bf0b12b | Nora-Wang/Leetcode_python3 | /Hash and Heap/lintcode_0526. Load Balancer.py | 2,922 | 3.5 | 4 | Implement a load balancer for web servers. It provide the following functionality:
Add a new server to the cluster => add(server_id).
Remove a bad server from the cluster => remove(server_id).
Pick a server in the cluster randomly with equal probability => pick().
At beginning, the cluster is empty. When pick() is called you need to randomly return a server_id in the cluster.
Example
Example 1:
Input:
add(1)
add(2)
add(3)
pick()
pick()
pick()
pick()
remove(1)
pick()
pick()
pick()
Output:
1
2
1
3
2
3
3
Explanation: The return value of pick() is random, it can be either 2 3 3 1 3 2 2 or other.
code:
高频班version:直接用set
class LoadBalancer:
def __init__(self):
self.cluster = set()
"""
@param: server_id: add a new server to the cluster
@return: nothing
"""
def add(self, server_id):
self.cluster.add(server_id)
return
"""
@param: server_id: server_id remove a bad server from the cluster
@return: nothing
"""
def remove(self, server_id):
if server_id in self.cluster:
self.cluster.remove(server_id)
return
"""
@return: pick a server in the cluster randomly with equal probability
"""
def pick(self):
import random
#Version 1:
return random.choice(list(self.cluster))
#Version 2
#注意,由于self.cluster是set,最后youge[0]转换一下,因为原方程是random.sample(list,k
#random.sample(序列a,n):从序列a(str/list/set)中随机抽取n个元素,并将n个元素生以list形式返回
#random.sample(序列a,n)[0]返回生成的随机数列表中的第一个值
return random.sample(self.cluster,1)[0]
follow up:如何在不使用set的情况下用O(1)的时间实现?
算法班Version:参考380,使用list+dict的方式,能在不用set的前提下实现O(1)
import random
class LoadBalancer:
def __init__(self):
self.data = []
self.record = {}
"""
@param: server_id: add a new server to the cluster
@return: nothing
"""
def add(self, server_id):
if server_id in self.record:
return
self.data.append(server_id)
self.record[server_id] = len(self.data) - 1
"""
@param: server_id: server_id remove a bad server from the cluster
@return: nothing
"""
def remove(self, server_id):
if server_id not in self.record:
return
index = self.record[server_id]
last = self.data[-1]
self.data[index] = last
self.record[last] = index
self.data.pop()
del self.record[server_id]
"""
@return: pick a server in the cluster randomly with equal probability
"""
def pick(self):
return self.data[random.randint(0, len(self.data) - 1)]
|
57a95e90a119bd0c7b17e3a4518140e16f28db6c | anubhav-shukla/Learnpyhton | /for_loop_string.py | 385 | 3.75 | 4 | # name="Anubhav"
# for i in range (len(name)):
# print(name[i])
# it is an old way you can use in javascript and other
# but in python is special
name='Anubhav'
for i in name:
print(i)
# easy way same output
# 1234 .....>1+2+3+4
num=input("enter any number: ")
total=0
for i in num:
total+=int(i)
print(total)
# python for_loop_string.py |
0ce485f995805891079a654b8e1f8ada29470b5e | procendp/Code_Study | /Programmers/Python/LV1/짝수와 홀수.py | 147 | 3.8125 | 4 | def solution(num):
if num % 2 == 1:
return "Odd"
elif num % 2 == 0:
return "Even"
print(solution(3))
print(solution(4)) |
80c77efa08418414a6cf736146a1ef7c944b01fb | engrjepmanzanillo/hacker_rank_practice | /text_wrap.py | 237 | 3.5 | 4 | import textwrap
def wrap(string, max_width):
return textwrap.fill(string, width=max_width)
if __name__ == '__main__':
string, max_width = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ', int(4)
result = wrap(string, max_width)
print(result) |
5bc17fa9a3faaebfd8a0469d759e7f283ef9db1b | DamianNery/Tecnicas-De-Programacion | /5Mayo/23/err_01.py | 263 | 3.96875 | 4 | #!/usr/bin/env python3
# calcula el cuadrado
# de un nro.
try:
a = float(input("ingrese número: "))
except:
print("ingresá un número")
else:
print("El cuadrado de ",a," es ", a*a)
finally:
print("siempre pase lo que pase")
|
5a99466c375abf84746d37bc7b31094311827095 | ramyasutraye/python_programming-1 | /codekata/natural.py | 126 | 4.09375 | 4 | print("enter the value")
a=int(input())
sum=0
for b in range(a+1):
sum=sum+b
print("the output sum of natural no is",sum)
|
0da6748b43d74d94562e0aba546edc497632cdd1 | Immaannn2222/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 162 | 3.578125 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
tmp = tuple_a + (0, 0)
trd = tuple_b + (0, 0)
return ((tmp[0] + trd[0]), (tmp[1] + trd[1]))
|
fac967877520280a219047ad0d978eff9621619a | kileyneushul/python_stack | /_python/python_fundamentals/Week 1/functions_basic_I.py | 1,698 | 4.0625 | 4 | #1
def a():
return 5
print(a())
#Predictions: 5
#2
def a():
return 5
print(a() + a())
#Predictions: 10
#3
def a():
return 5
return 10
print(a())
#Predictions: 5
#4
def a():
return 5
print(10)
print(a())
#Predictions: 5
#5
def a():
print(5)
x=a()
print(x)
#Predictions: 5, undefined
#6
def a(b,c):
return (b+c)
print(a(1,2)+a(2,3))
#Predictions: 3, 5, undefined
#This code does not allow me to proceed... It informs me that the Types are NoTypes and they cannot be added together. When I change the code to a return statement, it is valid and does not return an undefined value.
#7
def a(b,c):
return str(b)+str(c)
print(a(2,5))
#Predictions: 25
#8
def a():
b = 100
print(b)
if b < 10:
return 5
else:
return 10
return 7
print(a())
#Predictions: 100, 10
#9
def a(b,c):
if b<c:
return 7
else:
return 14
return 3
print(a(2,3))
print(a(5,3))
print(a(2,3) + a(5,3))
#Predictions: 7, 14, 21
#10
def a(b,c):
return b+c
return 10
print(a(3,5))
#Predictions: 8
#11
b = 500
print(b)
def a():
b = 300
print(b)
print(b)
a()
print(b)
#Predictions: 500, 500, 300, 500
#12
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
a()
print(b)
#Predictions: 500, 500, 300, 500
#13
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
b=a()
print(b)
#Predictions: 500, 500, 300, 300
#14
def a():
print(1)
b()
print(2)
def b():
print(3)
a()
#Predictions: 1, 3, 2
#15
def a():
print(1)
x = b()
print(x)
return 10
def b():
print(3)
return 5
y = a()
print(y)
#Predictions: 1, 3, 5, 10
|
3cea76bf17a623c82d4a299902d7b6a47de4ed61 | saotuzi/tensorflow_study | /kerasJianDanXianXing.py | 1,939 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 15:43:11 2019
@author: 64054
"""
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
print('Data -----------')
#构建训练数据和测试数据 (100个点)
number=100
list_x = []
list_y = []
for i in range(number):
#返回[0,1)的随机x,不给维度就是数字,给维度就是返回对应维度的随机值
x = np.random.randn()
#这里构建的数据的分布满足y=2*x+3 增加了一些噪点
y = 2*x+3+np.random.randn()*1
list_x.append(x)
list_y.append(y)
print(list_x)
print('\n')
print(list_y)
plt.scatter(list_x, list_y)
plt.show()
print('Model -----------')
# 把前80个数据放到训练集
X_train, Y_train = list_x[:80], list_y[:80]
# 把后20个点放到测试集
X_test, Y_test = list_x[80:], list_y[80:]
# 定义一个模型
# Keras 单输入单输出的线性序列模型 Sequential,
model = Sequential ()
#设置模型
#通过add()方法一层层添加模型,Dense是全连接层,第一层需要定义输入,
model.add(Dense(output_dim=1, input_dim=1))
#选择损失函数和优化器
model.compile(loss='mse', optimizer='sgd')
# 开始训练
print('Training -----------')
for step in range(200):
cost = model.train_on_batch(X_train, Y_train) # Keras有很多开始训练的函数,这里用train_on_batch()
if step % 20 == 0:
print('train cost: ', cost)
# 查看训练出的网络参数:权重和偏移
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)
# 测试训练好的模型
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=20)
print('test cost:', cost)
#预测值
Y_pred = model.predict(X_test)
#画图(蓝点,红线)
plt.scatter(X_test, Y_test, c='b', marker='o', label='real data')
plt.plot(X_test, Y_pred, c='r', label='predicted data')
plt.show() |
4d2aab22c792495e23e914524efb5b37b871be69 | brandonmburroughs/data_structures_and_algorithms | /1_algorithmic_toolbox/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py | 1,144 | 3.71875 | 4 | # Uses python3
import sys
def optimal_weight(W, w):
n_items = len(w)
optimal_weights = [[0 for _ in range(W + 1)] for _ in range(n_items + 1)]
for item_number in range(1, n_items + 1): # Loop through number of items
for current_weight in range(1, W + 1): # Loop through weights
# Get weight if we didn't add this item
optimal_weights[item_number][current_weight] = optimal_weights[item_number - 1][current_weight]
item_weight = w[item_number - 1]
if item_weight <= current_weight: # If we have the capacity for this weight
# Get the weight for the total minus this item plus the weight of the item
val = optimal_weights[item_number - 1][current_weight - item_weight] + item_weight
# Update it if larger
if val > optimal_weights[item_number][current_weight]:
optimal_weights[item_number][current_weight] = val
return optimal_weights[n_items][W]
if __name__ == '__main__':
input = sys.stdin.read()
W, n, *w = list(map(int, input.split()))
print(optimal_weight(W, w))
|
58b3bea4c52180db9a45a9053cce1a56918857f0 | Nimger/LeetCode | /344.py | 287 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# https://leetcode.com/problems/reverse-string/description/
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
if __name__ == '__main__':
solution = Solution()
print(solution.reverseString('hello')) |
15bdc1260b02f6947bd0290ebe0e9cf67073166e | toanrock/pythonpractice | /Automate The Boring Stuffs with Python/Chapter8/MadLibs.py | 455 | 3.890625 | 4 |
print('enter the adjective:')
adj1 = input()
print('enter the noun:')
noun1= input()
print('enter the verb:')
verb=input()
print('enter the noun:')
noun2 =input()
textfile = open('text.txt')
textcontent = textfile.read()
finalstring=textcontent.replace("ADJECTIVE",adj1).replace("NOUN",noun1,1).replace("VERB",verb).replace("NOUN",noun2,1)
textfile.close()
textfile = open('text.txt','w')
textfile.write(finalstring)
textfile.close()
print(finalstring)
|
15cbbd83293fe583cfa30d0643060469bc07709d | forxhunter/ComputingIntro | /solutions/cs101_openjudge/12065_newton.py | 394 | 3.765625 | 4 | # Newton's method
def solve(function = "x**3-5*x**2+10*x-80", a=4.0):
# a = float(input())
def f(x):
return eval(function)
def df(x, dx):
return (f(x + dx) - f(x)) / dx
while abs(f(a)) > 1e-10:
if df(a, 1e-10) == 0:
a -= 1e-10
else:
a = a - f(a) / df(a, 1e-10)
return a
ans = solve()
print("{:.9f}".format(ans)) |
aa22935540055b6db41e64a2b5856355ad0716ab | namratapadmanabhan/15112termproject | /playerRulesCheck.py | 10,097 | 4.15625 | 4 | #The main purpose of this file and the classes within it is to check each move
#made by the person player with the Scrabble rules. For example, we make sure
#after each move, that the letters are in either the same row or column, that
#they are attached to each other, and that the letters
# actually make a word when put together.
import itertools
import searchingFunctions
import string
class player():
def __init__(self):
self.score = 0
self.hand = ''
def playFromHand(self, letters):
for letter in letters:
letterPosition = self.hand.find(letter)
self.hand = self.hand[:letterPosition] + self.hand[letterPosition+1:]
def changeScore(self, add):
self.score += add
def addLetters(self, char):
self.hand += char
class playerRulesCheck():
def __init__(self):
text = open('scrabbleDictionary.txt', 'r')
finalDoc = text.read().lower()
self.dictionary = set(finalDoc.split('\n'))
def mkAlphabet(self, chars):
allLetters = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0,
'E' : 0, 'F' : 0, 'G' : 0, 'H' : 0,
'I' : 0, 'J' : 0, 'K' : 0, 'L' : 0,
'M' : 0, 'N' : 0, 'O' : 0, 'P' : 0,
'Q' : 0, 'R' : 0, 'S' : 0, 'T' : 0,
'U' : 0, 'V' : 0, 'W' : 0, 'X' : 0,
'Y' : 0, 'Z' : 0, '$' : 0}
for letter in chars:
if letter in """1234567890!@#$%^&*()[]{}:;"'<>,.?/|~`\\ """:
return 'Error: not in alphabet'
else:
allLetters[letter] += 1
return allLetters
def letterCombinationWorks(self, letters, allCells, currBoard, filledCells, charsDict, letterCombinations):
for combination in letterCombinations:
potentialCombination = ''
for cell in combination:
if cell in allCells:
potentialCombination += letters[allCells.index(cell)]
else:
potentialCombination += currBoard[cell]
if potentialCombination.lower() not in charsDict:
printStatement = 'That is not a word!'
return (False, printStatement)
return (True, '')
def updateHand(self, newLetters):
self.newLetters = newLetters
def checkFinalCombination(self, newLetters, allCells, currBoard, filledCells, connected, letters):
if self.checkLetterCount(newLetters):
printStatement = 'All letters are in hand.'
if checkIfFilled(allCells, filledCells):
printStatement = 'Spaces chosen are empty!'
verifyLine = lineConnected(allCells, filledCells, connected)
if verifyLine[0]:
printStatement = 'Letters are connected.'
if connectedToLetters(allCells, filledCells, connected)[0]:
printStatement = 'Letters all attached to board!'
permutations = getAllLetterPermutations(allCells, filledCells, verifyLine[1])
combinationWorks = self.letterCombinationWorks(newLetters, allCells, currBoard, filledCells, letters, permutations)
if combinationWorks[0]:
printStatement = 'Your word follows all the rules!'
return (True, permutations, printStatement)
else:
printStatement = combinationWorks[1]
else:
printStatement = 'Letters are not attached to the board!'
else:
printStatement = verifyLine[1]
else:
printStatement = 'That space is occupied. Try again!'
else:
printStatement = 'Your hand does not have those letters. Try again!'
return (False, [], printStatement)
def checkLetterCount(self, givenWord):
if '$' in givenWord:
return False
alphaLetter = self.mkAlphabet(self.newLetters)
alphaWord = self.mkAlphabet(givenWord)
for char in alphaLetter:
if alphaWord[char] > alphaLetter[char]: return False
else: return True
###############################################################################
def checkIfFilled(currBoard, filled):
for cell in currBoard:
if cell in filled:
return False
else: return True
def checkCurrRow(currBoard):
length = len(currBoard)
row = currBoard[0]//15
for cell in range(length):
currCell = currBoard[cell]
if row != currCell//15:
return (False, 0)
return (True, row)
def checkCurrCol(currBoard):
col = currBoard[0]%15
length = len(currBoard)
for cell in range(1, length):
currCell = currBoard[cell]
if col != currCell%15:
return (False, 0)
return (True, col)
def horizLetters(cell, filledCells):
col = cell % 15
if col != 0:
if (cell - 1) in filledCells:
return True
if col != 14:
if (cell + 1) in filledCells:
return True
else: return False
def vertLetters(cell, filledCells):
row = cell//15
if row != 0:
if (cell - 15) in filledCells:
return True
if row != 14:
if (cell + 15) in filledCells:
return True
return False
def lineConnected(currBoard, filledCells, connectedToLetters):
if len(currBoard) == 0:
return (False, 'These are not letters!')
verifyRow = checkCurrRow(currBoard)
verifyCol = checkCurrCol(currBoard)
if verifyRow[0]:
cols = []
row = currBoard[0]//15
for cell in currBoard:
cols.append(cell % 15)
currCol = 0
while currCol != len(cols)-1:
numOfCurrCol = cols[currCol]
if (((row*15 + numOfCurrCol + 1) in filledCells) and (currCol != 14)):
cols = cols[:currCol+1] + [numOfCurrCol + 1] + cols[currCol+1:]
if numOfCurrCol + 1 != cols[currCol+1]:
return (False, 'Not consecutive columns')
currCol += 1
return (True, True)
elif verifyCol[0]:
rows = []
col = currBoard[0]%15
for cell in currBoard:
rows.append(cell//15)
currRow = 0
while currRow != len(rows)-1:
numOfCurrRow = rows[currRow]
if (((numOfCurrRow*15 + col + 15) in filledCells) and (currRow != 14)):
rows = rows[:currRow+1] + [numOfCurrRow + 1] + rows[currRow+1:]
if numOfCurrRow + 1 != rows[currRow+1]:
return (False, 'Rows not consecutive')
currRow += 1
return (True, False)
else:
return (False, 'Place the letters in the same line!')
def connectedToLetters(currBoard, filledCells, connected):
wordIsConnected = lineConnected(currBoard, filledCells, connected)[1]
for cell in currBoard:
if cell in connected:
return (True, wordIsConnected)
return (False, 'Please connect your letters to current letters on board!')
def getFinalWord(isConnectedToLetters, filledCells, currBoard):
cell = currBoard[0]
boardPositions = [cell]
currPos = cell
if isConnectedToLetters:
newPos = currPos + 1
while (((currPos + 1) in filledCells) or ((currPos + 1) in currBoard)) and (currPos%15 != 14):
currPos += 1
boardPositions.append(currPos)
currPos = cell
prevPos = currPos - 1
while (((currPos - 1) in filledCells) or ((currPos - 1) in currBoard)) and (currPos%15 != 0):
currPos -= 1
boardPositions.append(currPos)
else:
nextRow = currPos + 15
while ((currPos + 15) in filledCells) or ((currPos + 15) in currBoard):
currPos += 15
boardPositions.append(currPos)
currPos = cell
prevRow = currPos - 15
while ((currPos - 15) in filledCells) or ((currPos - 15) in currBoard):
currPos -= 15
boardPositions.append(currPos)
return sorted(boardPositions)
def determineOtherWords(isConnectedToLetters, cell, filledCells):
boardPositions = [cell]
currPos = cell
if isConnectedToLetters:
newRow = currPos + 15
while (currPos + 15) in filledCells:
currPos += 15
boardPositions.append(currPos)
currPos = cell
prevRow = currPos - 15
while (currPos - 15) in filledCells:
currPos -= 15
boardPositions.append(currPos)
else:
newCell = currPos + 1
while ((currPos + 1) in filledCells) and (currPos%15 != 14):
currPos += 1
boardPositions.append(currPos)
currPos = cell
prevCell = currPos - 1
while ((currPos - 1) in filledCells) and (currPos%15 != 0):
currPos -= 1
boardPositions.append(currPos)
return sorted(boardPositions)
def getAllLetterPermutations(currBoard, filledCells, isConnectedToLetters):
currPermutationsList = []
finalWord = getFinalWord(isConnectedToLetters, filledCells, currBoard)
if len(finalWord) != 1:
currPermutationsList.append(finalWord)
for cell in currBoard:
if (isConnectedToLetters) and (vertLetters(cell, filledCells)):
currPermutationsList.append(determineOtherWords(isConnectedToLetters, cell, filledCells))
if (not isConnectedToLetters) and (horizLetters(cell, filledCells)):
currPermutationsList.append(determineOtherWords(isConnectedToLetters, cell, filledCells))
if len(currPermutationsList) == 0:
currPermutationsList.append(finalWord)
return currPermutationsList
|
3d44262bd522debe84d707e139443c893684bfa7 | techlib/kerator | /modules/keywords.py | 5,326 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from modules import utility
import os
def get_keywords(toc_xml_location):
"""
Gets keywords from XML TOC files by calling utility function send_ker_request and returning the responses.
:param toc_xml_location: path to the XML TOC file or ZIP file containing multiple XML TOC files
:return: responses: list of responses returned by send_ker_function
"""
# GETTING KEYWORDS
print("Getting keywords from TOC files...")
# TODO: There will be a function for getting a language from processed document
languages = ['cs', 'en'] # which languages will be requested? # TODO:
responses = utility.send_ker_request(languages=languages, file=toc_xml_location, threshold=0.2, max_words=15)
print("Finished getting keywords from TOC files...")
return responses
def map_keywords_to_scores(lang_response_dict):
"""
Maps keywords returned from KER with their appropriate keywords scores. Scores are also returned from KER,
but in a separate list, hence the need for mapping keywords to scores.
:param lang_response_dict: dictionary containing both list of keywords and list of keyword socres
:return: keyword_map - dict with mapped keywords (keys) and their scores (values)
"""
keyword_map = {}
for lang, response_dict in lang_response_dict.items():
map_lang = {}
for key, value in response_dict.items():
zipped_values = zip(response_dict['keywords'], response_dict['keyword_scores'])
for item in list(zipped_values):
map_lang.update({item[0]: item[1]})
keyword_map[lang] = map_lang
return keyword_map
def get_score_averages(keyword_score_dict):
"""
Gets score averages of all keywords in a given language.
:param keyword_score_dict: dictionary of keywords and scores all languages.
:return: averages - dictionary of score averages of keywords in every language
"""
averages = {}
for language, word_map in keyword_score_dict.items():
keyword_count = 0
total = 0
print("KEYWORD LANGUAGE: ", language)
# print(language, map)
if isinstance(word_map, dict):
for keyword, score in word_map.items():
print("KEYWORD: {}\tSCORE: {}".format(keyword, score))
keyword_count += 1
total = total + score
else:
raise TypeError("Function argument {} is not a dictionary.".format(keyword_score_dict))
try:
average = total / keyword_count
except ZeroDivisionError:
average = 0
averages[language] = average
return averages
def get_highest_average(averages_dict):
"""
Get keywords with highest average score from dictionary of keywords.
:param averages_dict: dictionary of score averages with a given language
:return: chosen_keywords - dict of chosen languages with highest average score
"""
chosen_keywords = {}
highest = 0
highest_lang = ''
for lang, average_score in averages_dict.items():
current_score = average_score
current_lang = lang
if current_score > highest:
highest = current_score
highest_lang = lang
print("CURRENT SCORE:", current_score, "CURRENT LANG:", current_lang)
print("HIGHEST SCORE:", highest, "HIGHEST LANG:", highest_lang)
chosen_keywords[highest_lang] = highest
return chosen_keywords
def get_best_keywords_list(best, keyword_dict):
"""
Gets a list of keywords from the dictionary of keywords identified by the languege of the document.
:param best: language of the best keywords
:param keyword_dict: dictionary of keywords in a different languages
:return: selected_keywords - list of keywords
"""
best_lang = None
selected_keywords = []
for lang in best:
best_lang = lang
for language, keywords in keyword_dict.items():
if language == best_lang:
for keyword, score in keywords.items():
selected_keywords.append(keyword)
return selected_keywords
def select_best_keywords(mapped_keywords, doc_path):
"""
Selects best keywords from KER for each file sent for keyword extraction.
:param mapped_keywords: dictionary of keywords with mapped scores
:param doc_path: path to the current document
:return: final_keywords_list - list of keywords extracted from the TOC files of the document
"""
# GETTING SCORE AVERAGES AND SELECTING THE BEST MATCHING KEYWORDS
print("Getting score averages for keywords...")
averages = get_score_averages(keyword_score_dict=mapped_keywords)
print("Finished getting score averages for keywords...")
# choose only the keywords from the dict that has higher scores overall
print("Selecting best keywords for the document {}...".format(os.path.basename(doc_path)))
best_keywords = get_highest_average(averages_dict=averages)
# TODO: WRITE BEST KEYWORDS TO FILE AND STORE IT IN DOCUMENT ROOT DIR
final_keywords_list = get_best_keywords_list(best=best_keywords, keyword_dict=mapped_keywords)
print("Finished getting best keywords for the document...")
print("BEST KEYWORDS:\n", final_keywords_list)
return final_keywords_list
|
5f93f5b23b3cdc4329d028a307d4b8f1463c3069 | poojaKarande13/ProgramingPractice | /python/LinkedList/reverseLL.py | 467 | 4.21875 | 4 | # Reverse Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(head):
prv = None
curr = head
nxt = None
while curr:
nxt = curr.next
curr.next = prv
prv = curr
curr = nxt
return prv
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(5)
head = reverse(head)
while head:
print(head.data)
head = head.next
|
a6581823a4ba01ea1816994d598c6d47f36b00a1 | kvsaijayanthkrishna/Python_Programming | /15_string_title.py | 435 | 4.1875 | 4 | #15. Write a Python program to capitalize
#first and last letters of each word of a given string.
string=input("enter a string\t:")
string_list=string.split()
length=0
new_string=""
for string in string_list:
length=len(string)
if(length==1):
new_string+=((string[0]).upper()+" ")
else:
new_string+=((string[0]).upper()+string[1:length-1]+(string[-1]).upper()+" ")
print("output:-",new_string)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.