blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
007bfa506f9040b3fffef57be4cacfa9c749ac87 | sofiatti/exercism | /pangram/pangram.py | 234 | 3.75 | 4 | import string
def is_pangram(sentence):
alphabet = list(string.ascii_lowercase)
for letter in alphabet:
if letter in list(sentence.lower()):
continue
else:
return False
return True |
58a149e5362358bd04e0e25d4e4f207e3cb4bf42 | babiswas/Graph-Theory | /topsort_kans.py | 1,182 | 3.984375 | 4 | from collections import defaultdict
class Graph:
def __init__(self,V):
self.vertex=V
self.graph=defaultdict(list)
def add_edges(self,u,v):
self.graph[u].append(v)
def topsort(self):
visited=[False]*self.vertex
queue=[]
count=0
indegree=[0]*self.vertex
for i in range(self.vertex):
for j in self.graph[i]:
indegree[j]=indegree[j]+1
for i in range(self.vertex):
if indegree[i]==0:
queue.append(i)
while queue:
m=queue.pop(0)
print(m)
for i in self.graph[m]:
indegree[i]=indegree[i]-1
if indegree[i]==0:
queue.append(i)
count=count+1
if count==self.vertex:
print("Topological sort is possible")
else:
print("The graph has a cycle")
if __name__=="__main__":
graph=Graph(6)
graph.add_edges(4,0)
graph.add_edges(5,0)
graph.add_edges(4,1)
graph.add_edges(3,1)
graph.add_edges(5,2)
graph.add_edges(2,3)
graph.topsort()
|
e190cef802f2e613fa1f43e9d9e17fe421e70202 | jklemm/curso-python | /pythonbrasil/lista_1_estrutura_sequencial/ex_05_converte_metros_para_centimetros.py | 250 | 3.890625 | 4 | print('Conversor de metros para centímetros')
medida_em_metros = float(input('Informe uma medida em metros: '))
medida_em_centimetros = medida_em_metros * 100
print('Esta medida convertida fica {:.0f} centímetros'.format(medida_em_centimetros))
|
b5837c0feaeca8d25cacf463ea26abb9ebeddd47 | Ozcry/PythonCEV | /ex/ex063.py | 496 | 4.09375 | 4 | '''Escreva um programa que leia um número 'n' inteiro qualquer e mostre na tela os 'n'
primeiros elementos de uma Sequência de Fibonacci.
Ex:. 0 - 1 - 1 - 2 - 3 - 5 - 8'''
print('\033[1;33m-=\033[m' * 20)
n1 = int(input('\033[34mDigite um número:\033[m '))
t1 = 0
t2 = 1
cont = 3
print('{} - {}'.format(t1, t2), end='')
while cont <= n1:
t3 = t1 + t2
print(' - {}'.format(t3), end='')
t1 = t2
t2 = t3
cont += 1
print(' -\033[35m FIM\033[m')
print('\033[1;33m-=\033[m' * 20) |
9d4bccaea59e53a0f700c9c6d1da2e7661abbb7e | Aizen741/PythonBasic | /lat_lang.py | 931 | 4.375 | 4 | from math import *
#You need Radius of earth to find the distance between two points
radius_of_earth = 6373.0
# You can use the simple .split(" ") with float to get input but this is fast trick called 'List Comprehension'
my_long, my_lat = [float(my_long) for my_long in input('Enter you location longitude and latitude with space between them: ').split()]
desired_long, desired_lat = [float(desired_long) for desired_long in input('Enter you location longitude and latitude with space between them: ').split()]
# Radians are used because the points are in float value
longitude = radians(desired_long) - radians(my_long)
latitude = radians(desired_lat) - radians(my_lat)
#Net se mila tha ye formula
formula = sin(latitude/ 2)**2 + cos(my_lat) * cos(desired_lat) * sin(longitude/ 2)**2
another_formula = 2 * atan2(sqrt(formula), sqrt(1 - formula))
distance = radius_of_earth * another_formula
# ta- da !!
print(distance)
|
3234edaab8c87f286fce21f3e8b5386cbb9b2b89 | Fabien-Vauclin/BachelorDIM-Lectures-Algorithms-2020 | /assignements/S3_imgproc_tools.py | 1,426 | 3.5 | 4 | import cv2
import numpy as np
img = cv2.imread('/home/fabien/Pictures/algo_img.jpg')
print("input image shape", img.shape)
cv2.imshow('input', img)
cv2.waitKey()
img_out = np.zeros(img.shape, dtype=np.uint8)
for row in range(img.shape[0]):
for col in range(img.shape[1]):
for channel in range (img.shape[2]):
img_out[row, col, channel] = 255-img[row, col, channel]
cv2.imshow("output", img_out)
cv2.waitKey()
def invert_colors_numpy(input_img):
'''
This function reverse the color of an image
Parameters:
input_img: an image
Returns: a reversed image. It's the optimal solution.
'''
return 255 - input_img
img_gray = cv2.imread("/home/fabien/Pictures/algo_img.jpg", 0)
img_bgr = cv2.imread("/home/fabien/Pictures/algo_img.jpg", 1)
img_bgr_reversed = invert_colors_numpy(cv2.imread("/home/fabien/Pictures/algo_img.jpg", 1))
cv2.imshow("Gray levels image", img_gray)
cv2.imshow("BGR image", img_bgr)
cv2.imshow("BGR image inverted", img_bgr_reversed)
cv2.waitKey()
img = cv2.imread("/home/fabien/Pictures/algo_img.jpg")
def inv_gray_levels(img):
if img is None:
raise ValueError("expected an uint8 and array")
if not (isinstance(img, np.ndarray)):
raise TypeError("expected and nd array")
if img.dtype!=np.dtype(np.uint8):
raise TypeError("expected uint8 typed nd array")
return 255-img
print(inv_gray_levels(img))
|
8ed99e8ed166c0be93d09bdf9c1b5f26728482fb | jnlycklama/DataStructures | /binarySearchTree.py | 4,459 | 3.796875 | 4 | import random
import time
#Experiment One
def inList():
bin_count = 0
bin_total = 0
tri_count = 0
tri_total = 0
for j in range (250, 80000, 3000): #number of values in the list, changes by 3000
lis = []
k = []
for i in range (0, j):
num = random.randint(0, 1000000)
lis.append(num)#adds random nums between 0-1,000,000
if i%10 == 0: #searches for every 10th element
k.append(num)
lis = qsort(lis, 0, len(lis)-1)
print "Experiment #1"
start = time.time()
for q in k: #searches for every element in k
bin_search(lis, 0, len(lis)-1, q)
fin = time.time()
print "Binary Search took ", (fin-start), " time with ", j, "elements in the list, searching for ", len(k)
bin_total += fin-start
start_two = time.time()
for w in k: #searches for every element in k
trin_search(lis, 0, len(lis)-1, w)
fin_two = time.time()
print "Trinary Search took ", (fin_two-start_two), " time with ", j, "elements in the list, searching for ", len(k)
tri_total += fin_two-start_two
if ((fin-start) > (fin_two-start_two)):
print "Trinary search was faster"
tri_count += 1
else:
print "Binary search was faster"
bin_count += 1
print ""
print "Trinary was faster ", tri_count, " times"
print "Binary was faster ", bin_count, " times"
print "Binary Total: ", bin_total
print "Trinary Total: ", tri_total
#Experiment Two
def notInList():
bin_count = 0
tri_count = 0
for j in range (250, 80000, 3000):#number of values in the list, changes by 3000
lis = []
k = []
for i in range (0, j):
num = random.randrange(0, 2000000, 2)
lis.append(num)#adds random even numbers up to 2 million
if i%10 == 0: #adds number to k after every 10 numbers
k.append(num-1) #searches for the number below the even num in list
lis = qsort(lis, 0, len(lis)-1)
print "Experiment #2"
start = time.time()
for q in k:
bin_search(lis, 0, len(lis)-1, q)
fin = time.time()
print "Binary Search took ", (fin-start), " time with ", j, "elements in the list, searching for ", len(k)
start_two = time.time()
for w in k:
trin_search(lis, 0, len(lis)-1, w)
fin_two = time.time()
print "Trinary Search took ", (fin_two-start_two), " time with ", j, "elements in the list, searching for ", len(k)
if ((fin-start) > (fin_two-start_two)):
print "Trinary search was faster"
tri_count += 1
else:
print "Binary search was faster"
bin_count += 1
print ""
print "Trinary was faster ", tri_count, " times"
print "Binary was faster ", bin_count, " times"
def qsort(lis, l, r):
i = l
j = r
p = lis[l + (r - l) / 2]
while i <= j:
while lis[i] < p: i += 1
while lis[j] > p: j -= 1
if i <= j:
lis[i], lis[j] = lis[j], lis[i]
i += 1
j -= 1
if l < j:
qsort(lis, l, j)
if i < r:
qsort(lis, i, r)
return lis
def bin_search(lis,first,last,target):
if first > last:
return -1
else:
mid = (first+last)/2
if mid >= len(lis):
return -1
if lis[mid] == target:
return mid
elif lis[mid] > target:
return bin_search(lis,first,mid-1,target)
else:
return bin_search(lis,mid+1,last,target)
def trin_search(lis,first,last,target):
if first > last:
return -1
else:
one_third = first + (last-first)/3
if one_third >= len(lis):
return -1
two_thirds = first + 2*(last-first)/3
if two_thirds >= len(lis):
return -1
if lis[one_third] == target:
return one_third
elif lis[one_third] > target:
return trin_search(lis,first,one_third-1,target)
elif lis[two_thirds] == target:
return two_thirds
elif lis[two_thirds] > target:
return trin_search(lis,one_third+1,two_thirds-1,target)
else:
return trin_search(lis,two_thirds+1,last,target)
|
473b823d8cf8c386fa54b4b407a2336204ff8b00 | bssrdf/pyleet | /F/FindMinimumRotatedSortedArrayII.py | 1,064 | 3.96875 | 4 | """
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
"""
import sys
__author__ = 'Danyang'
class Solution(object):
def findMin(self, nums):
"""
similar to find target in rotated sorted array
:type A: list
:param A: a list of integer
:return: an integer
"""
if not nums:
return None
l,r=0,len(nums)-1
while r-l > 1:
m = l+(r-l)/2
if nums[m] < nums[r]:
r = m
elif nums[m] > nums[r]:
l = m+1
else:
r -= 1
return min(nums[l], nums[r])
if __name__ == "__main__":
num = [7, 1, 2, 2, 3, 4, 5, 6]
#num = [10, 1, 10, 10, 10]
#num = [3,3,1,3]
assert Solution().findMin(num) == 1
|
5f0b2f85bd4015416a59474f96bdc47bad63b466 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/chelsea_nayan/lesson08/circle.py | 4,066 | 4.46875 | 4 | # Lesson08: Circle Class Exercise
"""
Create a class that represents a simple circle
"""
import math
class Circle(object):
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
# diameter = radius*2
@property
def diameter(self):
return self._radius * 2
# User able to set the radius or diameter of a circle
@radius.setter
def radius(self, value):
self._radius = value
@diameter.setter
def diameter(self, value):
self._radius = value / 2
# Area = pi*radius^2
@property
def area(self):
return math.pi * (self._radius ** 2)
# Let user create a circle directly with the diameter
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
# Print out the radius of the circle in informal and formal string representation
def __str__(self):
return f'Circle with a radius of {self.radius}'
def __repr__(self):
return f'Circle({self._radius})'
# Add circles
def __add__(self, other):
if isinstance(other, int):
return Circle(self.radius + other)
elif isinstance(other, Circle):
return Circle(self.radius + other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported.')
# Substract circles
def __sub__(self, other):
if isinstance(other, int):
result = self.radius - other
if result <= 0:
raise ValueError('Circle radius must be a positive value.')
return Circle(result)
elif isinstance(other, Circle):
result = self.radius - other.radius
if result <= 0:
raise ValueError('Circle radius must be a positive value.')
return Circle(result)
else:
raise TypeError('Whoops, sorry! Unsupported.')
# Multiply circles
def __mul__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported feature.')
# Compare circles
def __lt__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported feature.')
def __le__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported feature.')
def __gt__(self, other):
#return self.radius > other.radius
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported feature.')
def __eq__(self, other):
if isinstance(other, int):
return Circle(self.radius * other)
elif isinstance(other, Circle):
return Circle(self.radius * other.radius)
else:
raise TypeError('Whoops, sorry! Unsupported feature.')
"""
Create a class that represents a simple sphere using the circle class
"""
# Sphere class that subclassing the Circle class
class Sphere(Circle):
@property
# Volume = (4/3)*pi*radius^3
def volume(self):
return (4/3) * math.pi * ((self.radius) ** 3)
@property
# Surface area = 4*pi*radius^2
def area(self):
return 4 * math.pi * ((self._radius) ** 2)
# Print out the radius of the sphere in informal and formal string representation
def __str__(self):
return f'Sphere with a radius of {self._radius}'
def __repr__(self):
return f'Sphere({self._radius})'
|
0b4542d44b8502fd31d42087246796cc9583b963 | ChristianVasq/Classes | /Final Project/Final Project.py | 1,579 | 4.1875 | 4 | def main():
import random
import calendar
# import graphics as g
#Store the month selection with days included
MonthWdays = {"1":31, "2":29, "3":31, "4":30, "5":31, "6":30, "7":31,
"8":31, "9":30, "10":31, "11":30,"12":31}
#Statement declaring fruit types
FruitTypes = {"cherry":1200 , "orange": 400, "peach": 300}
FruitChoice = input("Which fruit do you prefer cherry, orange, or peach?: ")
if FruitChoice not in FruitTypes:
print("Oops,", FruitChoice , "not a choice, try again")
main()
MonthChoice = input("Select a month from the following list; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12: ")
if MonthChoice not in MonthWdays:
print("Oops,", MonthChoice , "not a choice, try again")
main()
FruitChoices=[]
while(len(FruitChoices) < MonthWdays[MonthChoice]):
Fruits = random.randrange(1,FruitTypes[FruitChoice])
if Fruits not in FruitChoices :
FruitChoices.append(Fruits)
# def splitseq(seq, size):
# newseq = []
# splitsize = 1.0/30*len(seq)
# for i in range(i):
# newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
# return newseq
print("The following is a list of", FruitChoice ,"for the whole month of", MonthChoice,"for you.")
for mon in range(0,len(FruitChoices)):
print(MonthChoice+"",mon+1,",","-",FruitChoices[mon])
year = int(input("Type any year: " ))
print (calendar.calendar(year))
main() |
cbe28f0bb4f96f2b5396f14b48445fbe652c2716 | HyungilNam/IntroductionToSoftwareDesign | /170320_Ex2.py | 1,251 | 4 | 4 | #170320_Exercise2
#Summation/Average/Max/Min
def Totaltotal(a,NumNum):
Total = a + NumNum
return Total
def Max(NowMax,A):
if(NowMax < A):
NowMax = A
return NowMax
def Min(NowMin, A):
if(NowMin > A):
NowMin = A
return NowMin
Count = -1
A = ''
Sum = 0
Ave = 0
NowMax = ''
NowMin = ''
print 'Select the Function'
print '1.Summation, 2.Average, 3.Max, 4.Min'
Select = ''
Select = raw_input()
Select = int(Select)
if(Select == 1):
print 'Input numbers'
while(A != 0):
A = raw_input()
A = int(A)
Sum = Totaltotal(Sum, A)
print 'The total is '+ str(Sum)
if(Select == 2):
print 'Input numbers'
while(A != 0):
A = raw_input()
A = int(A)
Sum = Totaltotal(Sum, A)
Count = Count + 1
Ave = float(Sum/Count)
print 'The average is '+ str(Ave)
if(Select == 3):
print 'Input numbers'
while(A != 0):
A = raw_input()
A = int(A)
NowMax = Max(NowMax, A)
print 'The max number is ' + str(NowMax)
if(Select == 4):
print 'Input numbers'
while(A!=0):
A = raw_input()
A = int(A)
if(A != 0):
NowMin = Min(NowMin, A)
print 'The min number is ' + str(NowMin)
|
7d6d3180d77b867fe194a0eb5a8469c6e9eb8c9b | lmregus/Portfolio | /python/exercism/word-count/wordcount.py | 682 | 4.125 | 4 | #########################
# #
# Developer: Luis Regus #
# Date: 12/11/2015 #
# #
#########################
def word_count(string):
""" Returns the word count in a string
This functions gets a string and counts the
words in it
Args:
string (int): String to be processed
Returns:
dict: dictionary with word count
"""
word_list = string.lower().split()
word_list.sort()
word_count = {x: 1 for x in (word_list)}
for x in range(len(word_list) - 1):
if word_list[x] == word_list[x+1]:
word_count[word_list[x]] += 1
return word_count
|
73403646eddec60575cbf7b8c055ac153ba8df70 | JuliaPanova/Otus_T | /Task_2/truck.py | 2,325 | 4.1875 | 4 | from Task_2.vehicle import Vehicle
class Truck(Vehicle):
"""
Truck is a subclass of Vehicle
"""
def __init__(self, weight, fuel, engine, tank_volume, number_of_wheels, capacity, cargo):
super().__init__(weight, fuel, engine, tank_volume, number_of_wheels)
self.capacity = capacity
self.cargo = cargo
def __repr__(self):
return """This {} has {} wheels and weighs {} tons. The engine volume is {} litres and max rpm is {}. The tank volume is {} litres.
The load capacity is {} tons, and the current cargo weighs {} tons.""" \
.format(self.__class__.__name__.lower(), self.number_of_wheels, self.weight, self.engine.volume,
self.engine.rpm, self.tank_volume, self.capacity, self.cargo)
def load(self, new_cargo):
"""
This function adds new cargo to the truck
:param new_cargo: weight of cargo to be loaded
"""
if new_cargo < 0:
raise NegCargoError(new_cargo)
if self.cargo + new_cargo > self.capacity:
raise LoadError(self.capacity, self.cargo, new_cargo)
self.cargo += new_cargo
print("{} tons has been loaded. Now the total weight of cargo is {} tons.".format(new_cargo, self.cargo))
def drop_off(self, cargo_to_remove):
"""
This function adds new cargo to the truck
:param new_cargo: weight of cargo to be loaded
"""
if self.cargo == 0:
print("The truck has no cargo.")
else:
self.cargo -= cargo_to_remove
print("Now the truck has {} tons of cargo.".format(self.cargo))
class LoadError(ValueError):
"""
Error in case the load capacity of the truck is not enough to load the cargo
"""
def __init__(self, capacity, cargo, new_cargo):
super().__init__("The load capacity of {} tons exceeded. Current cargo weight is {} tons. It's not possible to load {} more tons."\
.format(capacity, cargo, new_cargo))
class NegCargoError(ValueError):
"""
Error in case the weight of cargo to pick up is negative
"""
def __init__(self, new_cargo):
super().__init__("Cargo weight cannot be less that zero ({} tons).".format(new_cargo))
|
5295d787e56b91cf2c0da9cfc0ebb630fadba1c4 | ROF618/Think_Python | /CS9.8.py | 324 | 3.75 | 4 |
def check_palindrome(numbers):
num_list = []
i = 0
for digit in str(numbers):
num_list.append(int(digit))
num_list_reversed = list(reversed(num_list))
while i < len(num_list):
if num_list[i] == num_list_reversed[i]:
print(num_list[i])
i += 1
check_palindrome(5445) |
518168201f5e9904de47dfc08fd775ffdd1924ba | KerouacAutumn/PyCode | /day01/ForDemo.py | 1,022 | 3.859375 | 4 | # str01 = "安河桥"
# for item in str01:
# print(item)
# # range整数生成器 range(开始值,结束值,间隔)
# for item in range(1, 5, 2):
# print(item)
# # for + range执行预定次数
# thickness = 0.0001
# for item in range(30):
# thickness *= 2
# print(thickness)
# str = ","
# for i in range(1, 10):
# for j in range(1, i + 1):
# if j != i:
# print(j, "x", i, "=", "%d" % (i * j), str, end="\t")
# elif j == i & i == 9:
# print(j, "x", i, "=", "%d" % (i * j), "。", end="\t")
# print()
for i in range(1, 10):
for j in range(1, i + 1):
if j == i & i == 9:
print(j, "x", i, "=", "%d" % (i * j), "。", end="\t")
else:
print(j, "x", i, "=", "%d" % (i * j), ",", end="\t")
print()
# for i in range(1,10):
# for j in range(1,i+1):
# if j!=i:
# print(j,'*',i,'=','%d,'%(i*j),end='\t')
# else:
# print(j,'*',i,'=','%d'%(i*j),end='\t')
# print() |
4e3dee470e9cef576508a8085b716571308bce90 | Yunyi111/git_test | /week 9/plotting_matplotlib.py | 574 | 3.625 | 4 | import matplotlib.pyplot as p
my_list=[2, 5.5, 6, 8.9] # x-values by default: 0, 1, 2, 3
my_list_xvalues=[2, 4, 6, 8] # define x-values
my_list_xvalues2=[1, 3, 5, 7]
# Trend plotting
#p.plot(my_list, linewidth=5)
#p.title("Square Numbers", fontsize=24)
#p.xlabel("Value", fontsize=14)
#p.ylabel("Square of values", fontsize=14)
# scatter plotting
p.scatter(my_list_xvalues, my_list, 100, c="red")
p.scatter(my_list_xvalues2, my_list, 100, c="blue")
p.title("Square Numbers", fontsize=24)
p.xlabel("Value", fontsize=14)
p.ylabel("Square of values", fontsize=14)
p.show() |
4bbbfdb6d658bcf27f9b0edc9278829734cf0805 | prudhvireddym/CS5590-Python | /Source/Python/ICP 1/Reverse.py | 120 | 4.34375 | 4 |
name = input("enter a string:")
rname=""
for i in name:
rname = i + rname
print("The reverse string is %s"%(rname)) |
92e60e7470577a6e2c55d29272c64d397ce67676 | UmasouTTT/leetcode | /reshapeMatrix566.py | 819 | 3.640625 | 4 | class Solution(object):
def isReshapeLegal(self, nums, r, c):
if len(nums) * len(nums[0]) == r*c:
return True
return False
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if not self.isReshapeLegal(nums, r, c):
return nums
result = []
temp = []
index = 0
for row in nums:
for item in row:
temp.append(item)
index += 1
if c == index:
result.append(temp.copy())
temp.clear()
index = 0
return result
sol = Solution()
print(sol.matrixReshape(nums =
[[1,2],
[3,4]],
r = 1, c = 4))
|
f50e9d0654075f764e7ad892becd1e05451648f4 | bhoomit93/Data-Structures-and-Algorithm-in-Python | /Rotate_LinkedList.py | 1,052 | 3.984375 | 4 | # Node Class
class Node:
def __init__(self,data):
self.data = data
self.next = None
#LinkedList
# functions included:
# push, printList, rotate the list
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next=self.head
self.head = new_node
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp=temp.next
def rotate(self,k):
if k ==0:
return
curr = self.head
count = 1
while (count <k and curr is not None):
curr = curr.next
count = count +1
# if k is greater than the size of list return
if curr is None:
return
kthNode = curr
while (curr.next is not None):
curr = curr.next
curr.next = self.head
self.head = kthNode.next
kthNode.next = None
"""
Input :
[1,2,3,4,5]
2
output:
[3,4,5,1,2]
""" |
0fc7c901114011fb240adea8b3a2d8f5eea027f3 | CXuTao/Python_source | /python_grammar/时间操作/time.py | 1,665 | 3.765625 | 4 | import time
"""
UTC(世界协调时间):格林尼治时间,世界标准时间
在中国来说是UTC+8
DST(夏令时):是一种节约能源而人为规定时间制度,
在夏季调快1个小时
事件表现形式:
1、时间戳
以整形或浮点型表示时间的一个以秒为时间间隔,这个时间间隔的基础值
是从1970年1月1日凌晨开始算起的
2、元组
一种python的数据结构表示,这个元祖有9个模型内容
year
day
hours
minutes
seconds
weekday
Julia day
flag (1 或 -1 或 0)
3、格式化字符串
"""
#返回当前时间的时间戳,浮点数形式,不需要参数
c = time.time()
print(c)
#将时间戳转为UTC时间元组
t = time.gmtime(c)
print(t)
#将时间戳转为本地时间元组
b = time.localtime(c)
print(b)
#将本地时间元组转化为时间戳
m = time.mktime(b)
print(m)
#将时间元组转成字符串
s = time.asctime()
print(s)
#将时间戳转为字符串
p = time.ctime(c)
print(p)
#将时间元组转换成给定格式的字符串,参数二维时间元组,参数二不存在,认为转化当前时间
q = time.strftime("%Y-%m-%d %H:%M:%S",b)
print(q)
print(type(q))
#将时间字符串转为时间元组
w = time.strptime(q,"%Y-%m-%d %H:%M:%S")
print(w)
#延迟时间
time.sleep(1)
#返回当前程序的cpu执行时间
#UNIX系统始终返回全部的运行时间
#windows从第二次开始,都是以第一个调用此函数的
#开始时间戳作为基数
y1 = time.clock()
print("%d" % y1)
time.sleep(1)
y2 = time.clock()
print("%d" % y2)
time.sleep(2)
y3 = time.clock()
print("%d" % y3) |
9ea079f4dcc7dde2ce97a78b7ec93f416d0bee3b | pchen12567/Triangle567 | /TestTriangle.py | 3,602 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Feb 27 17:50:00 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: Pan Chen
"""
import unittest
from Triangle import classify_triangle
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
def test001(self):
self.assertNotEqual(classify_triangle(1.1, 1.2, 1.3), 'InvalidInput')
def test002(self):
self.assertEqual(classify_triangle('x', 1, 1), 'InvalidInput')
def test003(self):
self.assertEqual(classify_triangle(None, 1, 1), 'InvalidInput')
def test004(self):
self.assertNotEqual(classify_triangle(198, 199, 200), 'InvalidInput')
def test005(self):
self.assertEqual(classify_triangle(-1, 1, 1), 'InvalidInput')
def test006(self):
self.assertEqual(classify_triangle(0, 1, 1), 'InvalidInput')
def test007(self):
self.assertEqual(classify_triangle(199, 199, 201), 'InvalidInput')
def test008(self):
self.assertNotEqual(classify_triangle(2, 3, 4), 'NotATriangle')
def test009(self):
self.assertNotEqual(classify_triangle(3, 4, 2), 'NotATriangle')
def test010(self):
self.assertNotEqual(classify_triangle(4, 2, 3), 'NotATriangle')
def test011(self):
self.assertEqual(classify_triangle(1, 2, 3), 'NotATriangle')
def test012(self):
self.assertEqual(classify_triangle(2, 3, 1), 'NotATriangle')
def test013(self):
self.assertEqual(classify_triangle(3, 1, 2), 'NotATriangle')
def test014(self):
self.assertEqual(classify_triangle(3, 4, 5), 'Right Scalene')
def test015(self):
self.assertEqual(classify_triangle(4, 5, 3), 'Right Scalene')
def test016(self):
self.assertEqual(classify_triangle(5, 3, 4), 'Right Scalene')
def test017(self):
self.assertNotEqual(classify_triangle(2, 3, 4), 'Right Scalene')
def test018(self):
self.assertEqual(classify_triangle(1, 1, 1), 'Equilateral')
def test019(self):
self.assertEqual(classify_triangle(1, 2, 2), 'Isosceles')
def test020(self):
self.assertEqual(classify_triangle(2, 1, 2), 'Isosceles')
def test021(self):
self.assertEqual(classify_triangle(2, 2, 1), 'Isosceles')
def test022(self):
self.assertEqual(classify_triangle(2, 3, 4), 'Scalene')
def test023(self):
self.assertEqual(classify_triangle(3, 4, 2), 'Scalene')
def test024(self):
self.assertEqual(classify_triangle(4, 2, 3), 'Scalene')
def test025(self):
self.assertEqual(classify_triangle(1, 1, 2 ** 0.5), 'Right Isosceles')
# def test026(self):
# self.assertEqual(classify_triangle(3, 4, 5), 'Right Scalene')
# print('3,4,5 is a Right Scalene Triangle')
#
# def test027(self):
# self.assertEqual(classify_triangle(3, 3, 3), 'Equilateral')
# print('3,3,3 is an Equilateral Triangle')
#
# def test028(self):
# self.assertEqual(classify_triangle(1, 2, 2), 'Isosceles')
# print('1,2,2 is an Isosceles Triangle')
#
# def test029(self):
# self.assertEqual(classify_triangle(2, 3, 4), 'Scalene')
# print('2,3,4 is a Scalene Triangle')
#
# def test030(self):
# self.assertEqual(classify_triangle(1, 2, 3), 'NotATriangle')
# print('1,2,3 is not a Triangle')
def test031(self):
self.assertEqual(classify_triangle('hello', 1, 1), 'InvalidInput')
if __name__ == '__main__':
unittest.main(exit=False, verbosity=2)
|
9e81cd211d950aff5bb4f58135a2d82609f0df62 | Priyansu-Prit-Maharana/School | /School11/practice and extra.py | 4,263 | 3.953125 | 4 | """
Q1 write a program to calculate the total expense, quantity , price per unit are input by the user & a discount is given
"""
A = int(input("enter the quantity"))
B = int(input("price per item"))
C = A * B
if C > 5000:
print(C - (C / 10))
else:
print(C)
# question 2
S = int(input("enter the selling price:"))
C = int(input("enter the cost of the item:"))
if S > C:
print("owner is in profit")
print("the owner is in profit of ", (S - C))
else:
print("owner is in loss")
print("the owner is in loss of ", (C - S))
# question 3
A = int(input("enter your age"))
B = int(input("enter your age"))
C = int(input("enter your age"))
if (A > B) and (A > C):
print(A, "is the eldest")
elif (B > A) and (B > C):
print(B, "is the eldest ")
else:
print(C, "is the eldest")
# question 4
# COMPLEX CAL CALCULATOR
N = 1
print("the type of operators available in the calculator +,-,*,**,/,//,%")
while N <= 5:
operator = input("Enter operator:")
A = float(input("Enter first number:"))
B = float(input("Enter second number:"))
if operator == "+":
print("the addition of two numbers is", A + B)
elif operator == "-":
print("the subtraction of two numbers is", A - B)
elif operator == "*":
print("the multiplication of two numbers is", A * B)
elif operator == "**":
print("the power of two numbers is", A ** B)
elif operator == "/":
print("the division of two numbers is", A / B)
elif operator == "%":
print("the remainder of two numbers is", A % B)
elif operator == "//":
print("the integral quotient of two numbers is", A // B)
else:
print("Invalid operator")
continue
N += 1
# question 5
S1 = float(input('enter side 1'))
S2 = float(input('enter side 2'))
S3 = float(input('enter side 3'))
A1 = float(input('enter angle 1'))
A2 = float(input('enter angle 2'))
A3 = float(input('enter angle 3'))
if A1 + A2 + A3 == 180:
R1 = 'true'
else:
R1 = 'false'
if (S1 + S2) > S3:
R2 = 'true'
else:
R2 = 'false'
if (S1 + S3) > S2:
R3 = 'true'
else:
R3 = 'false'
if (S3 + S2) > S1:
R4 = 'true'
else:
R4 = 'false'
if (R1 == 'true') and (R2 == 'true') and (R3 == 'true') and (R4 == 'true'):
print("It can form a triangle")
else:
print('It cannot form a triangle')
# QUESTION 6
t1 = 0
t2 = 0
bill = float(input("enter the number of call"))
if bill < 101:
print("your total amount is 200 ")
elif (bill > 100) and (bill < 151):
a1 = (bill - 100) * 0.6
t1 = 200 + a1
print("your total amount is", t1)
elif (bill > 150) and (bill < 151):
a2 = (bill - 150) * 0.50
t2 = (t1 + a2)
print("your total amount is", t2)
elif bill > 200:
a3 = (bill - 200) * 0.4
t3 = (t2 + a3)
print("the total amount is", t3)
# QUESTION 7
a = float(input('enter your salary'))
if a < 1500:
Hra = a * 0.1
Da = a * 0.9
print('your hra=', Hra, 'your da=', Da)
elif a >= 1500:
Hra = 500
Da = a * 0.98
print('your hra=', Hra, 'your da=', Da)
# QUESTION 8
x2 = int(input("enter the term x^2"))
x1 = int(input("enter the term X"))
x0 = int(input("enter the term without x"))
root1 = x1 + ((x1 ^ 2)-(4 * x2 * x0))
root2 = x1 - ((x1 ^ 2)-(4 * x2 * x0))
print("the two roots of your equation are", root1, root2)
coordinates = [(4, 100), (88, 1000)]
print(coordinates[0])
# QUESTION 9
info = (input("enter your subject (sci or commerce)"))
if info == "science":
info2 = (input("enter your subjects(comp or bio)"))
personal1, personal2, personal3 = map(str, input("enter your name mobile no. and 10th percentage separated by SPACE").split())
print("your group is", info, "your subjects are", info2)
print("your name is", personal1)
print("your mobile is", personal2)
print("and your 10th percentage is", personal3)
elif info == "commerce":
info2 = (input("enter your subjects (pure maths or maths with comp)"))
personal1, personal2, personal3 = map(str, input("enter your name mobile no. and 10th percentage separated by SPACE").split())
print("your group is", info, "your subjects are", info2)
print("your name is", personal1)
print("your mobile is", personal2)
print("and your 10th percentage is", personal3)
|
9a7a0cb55d1215149b3f078671f06ed4318bbc9b | sourav98/Python-For-Coding-Interviews | /HackerRank/repeatedStrings.py | 289 | 3.890625 | 4 | def repeatedString(s, n):
n1=n//len(s)
x1=s.count('a')
c1=x1*n1
c2=s[:n%len(s)].count('a')
return c1+c2
s=input()
n=int(input())
result = repeatedString(s,n)
print(result)
"""
Warm Up HackerRank Challenges
https://www.hackerrank.com/challenges/repeated-string
""" |
8bcb676c5d17e2b73b7aa903a791e0062400eb8d | NathanJesudason/TicTacToe | /TicTacToe.py | 4,222 | 3.53125 | 4 | import pygame
import random
from time import sleep
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREY = (200, 200, 200)
BLACK = (0, 0, 0)
B = 0
X = 1
O = 2
tilemap = [
[B,B,B],
[B,B,B],
[B,B,B]
]
rectangle = [
[None, None, None],
[None, None, None],
[None, None, None]
]
def init():
for row in range(3):
for column in range(3):
tilemap[row][column] = B
main()
def main():
"""
for each row in range(3):
if ((tilemap[row][0] == O OR X) AND (tilemap[row][1] == O) AND (tilemap[row][2] == O))
"""
compMove = False
screen = pygame.display.set_mode((643, 643))
pygame.display.set_caption('Divine Intellect')
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
for row in range(3):
for column in range(3):
if rectangle[row][column].collidepoint(event.pos):
if tilemap[row][column] == B:
tilemap[row][column] = O
compMove = True
while compMove == True:
compMove2 = False
for row in range(3):
for column in range(3):
if tilemap[row][column] == B:
compMove2 = True
if compMove2:
while compMove:
ax = random.randint(0,2)
ay = random.randint(0,2)
if tilemap[ax][ay] == B:
tilemap[ax][ay] = X
compMove = False
compMove = False
#432
screen.fill(RED)
pygame.draw.rect(screen, BLACK, pygame.Rect(211,0,5,640))
pygame.draw.rect(screen, BLACK, pygame.Rect(427,0,5,640))
pygame.draw.rect(screen, BLACK, pygame.Rect(0,211,640,5))
pygame.draw.rect(screen, BLACK, pygame.Rect(0,427,640,5))
for row in range(3):
for column in range(3):
if tilemap[row][column] == B:
rectangle[row][column] = pygame.draw.rect(screen, WHITE, (216*row, 216*column, 211, 211))
#elif tilemap[row][column] == X:
#draw an X
#pass
elif tilemap[row][column] == O:
rectangle[row][column] = pygame.draw.rect(screen, WHITE, (216*row, 216*column, 211, 211))
pygame.draw.circle(screen, BLACK, (((216*row)+108),((216*column)+108)), 100)
elif tilemap[row][column] == X:
rectangle[row][column] = pygame.draw.rect(screen, WHITE, (216*row, 216*column, 211, 211))
pygame.draw.circle(screen, RED, (((216*row)+108),((216*column)+108)), 100)
pygame.display.update()
clock.tick(30)
endGame = True
for row in range(3):
for column in range(3):
if tilemap[row][column] == B:
endGame = False
for row in range(3):
if (((tilemap[row][0] == O) and (tilemap[row][1] == O) and (tilemap[row][2] == O)) or ((tilemap[row][0] == X) and (tilemap[row][1] == X) and (tilemap[row][2] == X))):
endGame = True
for column in range (3):
if (((tilemap[0][column] == O) and (tilemap[1][column] == O) and (tilemap[2][column] == O)) or ((tilemap[0][column] == X) and (tilemap[1][column] == X) and (tilemap[2][column] == X))):
endGame = True
if (((tilemap[0][0] == O) and (tilemap[1][1] == O) and (tilemap[2][2] == O)) or ((tilemap[0][0] == X) and (tilemap[1][1] == X) and (tilemap[2][2] == X))):
endGame = True
if (((tilemap[2][0] == O) and (tilemap[1][1] == O) and (tilemap[0][2] == O)) or ((tilemap[2][0] == X) and (tilemap[1][1] == X) and (tilemap[0][2] == X))):
endGame = True
if endGame:
sleep(1)
init()
init()
pygame.quit()
|
a61ed72ea905bc9882fa77915f2d66aaea7685cc | newderezzed/Library-Student | /utils/mypage.py | 3,260 | 3.90625 | 4 | """
自定义分页组件
"""
class Pagenation(object):
def __init__(self, data_num, current_page, url_prefix, per_page=10, max_show=11):
"""
进行初始化.
:param data_num: 数据总数
:param current_page: 当前页
:param url_prefix: 生成的页码的链接前缀
:param per_page: 每页显示多少条数据
:param max_show: 页面最多显示多少个页码
"""
self.data_num = data_num
self.per_page = per_page
self.max_show = max_show
self.url_prefix = url_prefix
# 把页码数算出来
self.page_num, more = divmod(data_num, per_page)
if more:
self.page_num += 1
try:
self.current_page = int(current_page)
except Exception as e:
self.current_page = 1
# 如果URL传过来的页码数是负数
if self.current_page <= 0:
self.current_page = 1
# 如果URL传过来的页码数超过了最大页码数
elif self.current_page > self.page_num:
self.current_page = self.page_num # 默认展示最后一页
# 页码数的一半 算出来
self.half_show = max_show // 2
# 页码最左边显示多少
if self.current_page - self.half_show <= 1:
self.page_start = 1
self.page_end = self.max_show
elif self.current_page + self.half_show >= self.page_num: # 如果右边越界
self.page_end = self.page_num
self.page_start = self.page_num - self.max_show
else:
self.page_start = self.current_page - self.half_show
# 页码最右边显示
self.page_end = self.current_page + self.half_show
@property
def start(self):
# 数据从哪儿开始切
return (self.current_page - 1) * self.per_page
@property
def end(self):
# 数据切片切到哪儿
return self.current_page * self.per_page
def page_html(self):
# 生成页码
l = []
# 加一个首页
l.append('<li><a href="{}?page=1">首页</a></li>'.format(self.url_prefix))
# 加一个上一页
if self.current_page == 1:
l.append('<li class="disabled" ><a href="#">«</a></li>'.format(self.current_page))
else:
l.append('<li><a href="{}?page={}">«</a></li>'.format(self.url_prefix, self.current_page - 1))
for i in range(self.page_start, self.page_end + 1):
if i == self.current_page:
tmp = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(self.url_prefix, i)
else:
tmp = '<li><a href="{0}?page={1}">{1}</a></li>'.format(self.url_prefix, i)
l.append(tmp)
# 加一个下一页
if self.current_page == self.page_num:
l.append('<li class="disabled"><a href="#">»</a></li>'.format(self.current_page))
else:
l.append('<li><a href="{}?page={}">»</a></li>'.format(self.url_prefix, self.current_page + 1))
# 加一个尾页
l.append('<li><a href="{}?page={}">尾页</a></li>'.format(self.url_prefix, self.page_num))
return "".join(l)
|
27b32c3f0ff2ae7d2086574127135b3708e1409a | ProgFuncionalReactivaoct19-feb20/clase02-Jdesparza | /Practica/Practica1.py | 329 | 4 | 4 | """
Jdesparza
"""
# se pide una valor por teclado
n = input("Ingrese un numero: \n")
# se transforma el valor en entero
n = int(n)
# se hace la operacion para determinar si es par
valor_par = lambda x: x%2 == 0
# se guarda en una variable la operacion realizada
valor = valor_par(n)
# se imprime si el valor es par
print(valor)
|
504e6f8b4ac20790a26e6ddc3acb7e52ae329b35 | natebellanger10/EulerProject | /Problem2.py | 335 | 3.6875 | 4 | """Add all even Fib numbers below 4,000,000"""
def fib(n):
if n==1:
return 1
if n==2:
return 2
else:
return fib(n-1)+fib(n-2)
n=1
countList = []
while fib(n) < 4000000:
j=fib(n)
if j%2==0:
countList.append(j)
n+=1
counter=0
for i in countList:
counter+=i
print(counter) |
29f7237b4c39f3a6e12e422dd99fba63dedc17a1 | toddbryant/leetcode | /060_permutation_sequence.py | 640 | 3.90625 | 4 | """
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
"""
class Solution:
def getPermutation(self, n: int, k: int) -> str:
k=k-1 # make k 0-based
result = []
digits = list(range(1,n+1))
total = math.factorial(n)
while n:
i, k = k // (total//n), k % (total//n)
total, n = total//n, n-1
result.append(str(digits.pop(i)))
return ''.join(result)
|
e8fcbb80cdee81ffb44915207d926ae9994d7b7d | shivani12032002/OMNEHA | /swap.py | 242 | 3.953125 | 4 | x=int(input("enter first number"))
y=int(input("enter second number"))
print("before swapping")
print("the value of x",x)
print("the value of y",y)
temp=x
x=y
y=temp
print("after swapping")
print("the value of x",x)
print("the value of y",y)
|
624c906ab8b04a6529a44975ed9028fc2439954a | Sonmone/Approximate-matching-algorithms | /ged.py | 4,238 | 3.625 | 4 | '''This project adopts global edit distance method to predict possible correct spelling posWords
in the dictionary of given misspelled words.
Besides, it also calculates the precision and recall to evaluate this method.
'''
import numpy #a package used in list[]
misfile = open("data\misspell.txt") #open the misspelled text
corfile = open("data\correct.txt") #open the correct spelling text
dicfile = open("data\dictionary.txt") #open the dictionary text
mislist = [] #array to storage misspelled words
corlist = [] #array to storage correct spelling words
diclist = [] #array to storage dictionary words
for word in misfile.readlines():
mislist.append(word.replace("\n", "")) #add each word into mislist[]
for word in corfile.readlines():
corlist.append(word.replace("\n", "")) #add each word into corlist[]
for word in dicfile.readlines():
diclist.append(word.replace("\n", "")) #add each word into diclist[]
def ifEqual(misChar, corChar): #judge if the character in misword equals the character in corword
if misChar == corChar:
return matVal
else:
return repVal
def getGedaList(scoreList): #get the highest socre possible correct spelling words
maxScoreList = []
posWords = []
temp = scoreList[0]
for score in scoreList:
if (score > temp).any():
temp = score
for index in range(len(scoreList)):
if scoreList[index] == temp:
maxScoreList.append(index)
for val in maxScoreList:
if diclist[val] not in posWords:
posWords.append(diclist[val])
return posWords
def getGedaPoint(posResult): #get the point of GED algorithm of each result
result = [] #storage the correctness in first unit, the length of predicted words in second unit
for posword in posResult:
for corword in corlist:
if posword == corword:
result = [1, len(posResult)]
if not result:
result = [0, len(posResult)]
return result
class GEDA(object): #the class of Global Edit Distance Algorithm
global insVal #cost of insert
global delVal #cost of delete
global repVal #cost of replace
global matVal #cost of match
insVal = -1
delVal = -1
repVal = -1
matVal = 1
def minDistance(self, misword, corword):
lenOfMword = len(misword) #length of misspelled word
lenOfCword = len(corword) #length of correct spelling word
arrTemp = numpy.zeros([lenOfCword, lenOfMword]) #the array storages GED
for i in range(lenOfCword):
arrTemp[i][0] = insVal * i #initialize GED array
for j in range(lenOfMword):
arrTemp[0][j] = delVal * j #initialize GED array
for i in range(1, lenOfCword): #adjust GED array
for j in range(1, lenOfMword):
arrTemp[i][j] = max((arrTemp[i][j - 1] + delVal), (arrTemp[i - 1][j] + insVal), (arrTemp[i - 1][j - 1] + ifEqual(misword[j - 1], corword[i - 1])))
return arrTemp[lenOfCword - 1][lenOfMword - 1] #return the score
if __name__ == '__main__': #main function access
# find possible correct spelling words in dictionary
prepoint = 0
prelen = 0
for misword in mislist: #traverse all the misspelled text
gedaScore = [] #store the distance(score) of each dictionary entry
gedaResult = [] #store the results of each misspelled word
gedaPoint = [] #store the points when predicting correctly
for dicword in diclist:
geda = GEDA()
gedaScore.append(geda.minDistance(misword, dicword))
gedaResult = getGedaList(gedaScore)
gedaPoint = getGedaPoint(gedaResult)
prepoint += gedaPoint[0]
prelen += gedaPoint[1]
print("Misspelled Word:" + misword)
print("Correct Word: " + corlist[mislist.index(misword)])
print("Predicted Word:", end = " ")
print(gedaResult)
print("Score:", end = " ")
print(str(gedaPoint[0]) + " of " + str(gedaPoint[1]))
print("********************************************")
print("Precision:", end = " ")
print("%.2f%%" % ((prepoint / prelen) * 100))
print("Recall:", end = " ")
print("%.2f%%" % ((prepoint / len(mislist)) * 100))
|
530ddac0b6c81a0265b60974108e681264a6fcb4 | HuzaifaSaifuddin/python-is-easy | /homework-8/notes.py | 1,894 | 4.15625 | 4 | import os
FileName = input("Please provide filename : ")
def PlayFile(FileName, option):
if option == "A":
ReadFile = open(FileName, "r") # Open File
print(ReadFile.read()) # read File
ReadFile.close() # Close it back
elif option == "B":
open(FileName, 'w').close() # Open and Close to empty File
elif option == "C":
Note = input("Add your Note?\n") # Input From User
AppendFile = open(FileName, "a") # Open File using a(append)
AppendFile.write(str(Note) + "\n") # Write in new Line
AppendFile.close() # Close File
elif option == "D":
LineNumber = input("Line No. to be replaced? ")
NewText = input("New Text ")
# Code to Replace Line
with open(FileName, 'r+') as file:
# Read Lines
lines = file.readlines()
# Set Position
position = int(LineNumber)
# Insert a position 1 above
lines.insert(position - 1, str(NewText) + "\n")
# Remove existing Line at Position
RemoveLine = lines[position]
lines.remove(RemoveLine)
# Open/Close file to empty it
open(FileName, 'w').close()
# Seek The cursor to bring on First Line
file.seek(0)
# Write each line in File again
for i in lines:
i.strip()
file.write(str(i))
else:
print("Invalid Option")
while(True):
if(os.path.exists(FileName)): # Check if File Exists
print("A) Read the file")
print("B) Delete the file and start over")
print("C) Append the file")
print("D) Replace a Line")
print("E) Exit")
userInput = input("Please choose A, B, C, D or E : ")
if userInput == "E":
break
else:
PlayFile(FileName, userInput)
else:
NewFile = open(FileName, "w") # Open with W, creates new file
NewNote = input("Add your Note?\n")
NewFile.write(str(NewNote) + "\n") # Write on File
NewFile.close() # Close File
|
e929b2188b3a1241f5a6b3dfe1d4120141854668 | Pradeep1321/PythonNotesForProfessionals | /Chapter-2-3-4.py | 4,036 | 3.90625 | 4 | """
Chapter 2: Python Data Types
Section 2.1: String Data Type
Python allows for either pairs of single or double quotes. Strings are immutable sequence data type, i.e each time one
makes any changes to a string, completely new string object is created.
Section 2.2: Set Data Types
Sets are unordered collections of unique objects, there are two types of set:
1. Sets - They are mutable and new elements can be added once sets are defined
2. Frozen Sets - They are immutable and new elements cannot added after its defined.
Section 2.3: Numbers data type
Numbers have four types in Python. Int, float, complex, and long.
int_num = 10 #int value
float_num = 10.2 #float value
complex_num = 3.14j #complex value
long_num = 1234567L #long value
Section 2.4: List Data Type
lists are almost similar to arrays in C. One difference is that all the items belonging to a list can be of different
data type.
Section 2.5: Dictionary Data Type
Dictionary consists of key-value pairs. It is enclosed by curly braces {} and values can be assigned and accessed
using square brackets[].
Section 2.6: Tuple Data Type
Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are enclosed in
parentheses ( ) and cannot be updated. Tuples are immutable.
Chapter 3: Indentation
Section 3.1: Simple example
#If a function is not indented to the same level it will not be considers as part of the parent class
Spaces or Tabs?
The recommended indentation is 4 spaces but tabs or spaces can be used so long as they are consistent. Do not
mix tabs and spaces in Python as this will cause an error in Python 3 and can causes errors in Python 2.
Section 3.2: How Indentation is Parsed
Whitespace is handled by the lexical analyzer before being parsed.
Section 3.3: Indentation Errors
The spacing should be even and uniform throughout. Improper indentation can cause an IndentationError or
cause the program to do something unexpected
Chapter 4: Comments and Documentation
Section 4.1: Single line, inline and multiline comments
Single-line comments begin with the hash character (#) and are terminated by the end of line.
Single line comment:
# This is a single line comment in Python
Inline comment:
print("Hello World") # This line prints "Hello World"
Comments spanning multiple lines have \""" or ''' on either end. This is the same as a multiline string, but
they can be used as comments:
Section 4.2: Programmatically accessing docstrings
Docstrings are - unlike regular comments - stored as an attribute of the function they document, meaning that you
can access them programmatically.
An example function
def func():
"""This is a function that does nothing at all"""
return
The docstring can be accessed using the __doc__ attribute:
print(func.__doc__)
Advantages of docstrings over regular comments
Just putting no docstring or a regular comment in a function makes it a lot less helpful.
def greet(name, greeting="Hello"):
# Print a greeting to the user `name`
# Optional parameter `greeting` can change what they're greeted with.
print("{} {}".format(greeting, name))
print(greet.__doc__)
None
Section 4.3: Write documentation using docstrings
A docstring is a multi-line comment used to document modules, classes, functions and methods. It has to be the
first statement of the component it describes.
Syntax conventions:
PEP 257:
PEP 257 defines a syntax standard for docstring comments
Sphinx:
Sphinx is a tool to generate HTML based documentation for Python projects based on docstrings. Its markup
language used is reStructuredText. They define their own standards for documentation, pythonhosted.org hosts a
very good description of them. The Sphinx format is for example used by the pyCharm IDE.
Google Python Style Guide:
Google has published Google Python Style Guide which defines coding conventions for Python, including
documentation comments.
Using the Napoleon plugin, Sphinx can also parse documentation in the Google Style Guide-compliant format.
""" |
58c7a0db0af5b0e7a04572dd014c2df419d8d6af | akjayant/Data-Structures-Algorithms | /ds_algo_practice/arrays/day1/day1_4singlenumber.py | 1,745 | 3.671875 | 4 | #https://leetcode.com/problems/single-number/submissions/
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = nums[0]
for i in range(1,len(nums)):
s=s^nums[i]
return s
#---advanced version
#https://leetcode.com/problems/single-number-ii/
#Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
#
# You must implement a solution with a linear runtime complexity and use only constant extra space.
def getSingle(arr, n):
ones = 0
twos = 0
for i in range(n):
# one & arr[i]" gives the bits that
# are there in both 'ones' and new
# element from arr[]. We add these
# bits to 'twos' using bitwise OR
twos = twos | (ones & arr[i])
# one & arr[i]" gives the bits that
# are there in both 'ones' and new
# element from arr[]. We add these
# bits to 'twos' using bitwise OR
ones = ones ^ arr[i]
# The common bits are those bits
# which appear third time. So these
# bits should not be there in both
# 'ones' and 'twos'. common_bit_mask
# contains all these bits as 0, so
# that the bits can be removed from
# 'ones' and 'twos'
common_bit_mask = ~(ones & twos)
# Remove common bits (the bits that
# appear third time) from 'ones'
ones &= common_bit_mask
# Remove common bits (the bits that
# appear third time) from 'twos'
twos &= common_bit_mask
return ones
# driver code
arr = [3, 3, 2, 3]
n = len(arr)
print("The element with single occurrence is ",
getSingle(arr, n))
|
fb862a912767ff215dcf7e67662a16fd43bb40d2 | Onyiee/python_practice_exercises | /Strings/Palindromes.py | 845 | 4.125 | 4 | # 3.12 (Palindromes) A palindrome is a number, word or text phrase that reads the same
# backwards or forwards. For example, each of the following five-digit integers is a
# palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five-digit integer
# and determines whether it’s a palindrome. [Hint: Use the // and % operators to separate
# the number into its digits.]
number = int(input("Enter a five-digit number: "))
fifth_number = number % 10
number = number // 10
fourth_number = number % 10
number = number // 10
third_number = number % 10
number = number // 10
second_number = number % 10
number = number // 10
first_number = number % 10
number = number // 10
if first_number == fifth_number and fourth_number == second_number:
print("Number is a palindrome")
else:
print("Number is not a palindrome")
|
ae19291954ec188e0d634431407fc2d66a32a0ad | NBaiel81/Classes | /21.01.21.ex.classes.py | 1,400 | 3.8125 | 4 | class Beaver:
finished_bridges = 0
def __init__(self, name, age, weight, power):
self.name = name
self.age = age
self.weight = weight
self.power = power
if self.age>=11:
self.power-=5
def __str__(self):
return "{} {}".format(self.name, self.age)
class Bridge:
def __init__(self, legth, weight):
self.length = legth
self.weight = weight
self.material = 'tree'
def building(self, team:list):
group_power=0
for beaver in team:
group_power+=(beaver.weight+beaver.power)
print("power of beavers:",group_power,"needed power to create bridge:",bridge.weight+bridge.length)
if group_power> self.weight + self.length:
print("Мост успешно создан")
Beaver.finished_bridges+=1
else:
print("Команда слишком слабая")
beaver1 = Beaver(name='Bobrik', age=5, weight=9, power=10)
beaver2 = Beaver(name='Musya', age=7, weight=20, power=15)
beaver3 = Beaver(name='Aktan', age=8, weight=23, power=18)
beaver4 = Beaver(name='Maksim', age=12, weight=43, power=20)
beaver5 = Beaver(name='Trump', age=9, weight=23, power=20)
bridge = Bridge(legth=10, weight=100)
beaver_team=[beaver1, beaver2, beaver3, beaver4, beaver5]
bridge.building(beaver_team)
print(beaver1)
print(bridge.building) |
55a49cd00ca66117378afaabd60afe6cfcc307cc | DmOfff/praktika | /1/t49.py | 377 | 3.875 | 4 | # Пользователь вводит четыре числа.
# Найдите наибольшее четное число среди них. Если оно не существует, выведите фразу "not found"
nums = []
for i in range(4):
n = int(input(""))
if n % 2 == 0:
nums.append(n)
print(max(nums) if len(nums) > 0 else "not found")
|
255c126c0848721e06cbeae62320f865e847c9c8 | pittDeng/MACHINE | /machineLearning/AndFunc.py | 391 | 3.5625 | 4 | from Perceptron import Perceptron
def myfunc(x):
return 1 if x>0 else 0
def get_training_dataset():
dataset=[[1,1,1],[1,1,0],[1,0,1],[1,0,0],[0,1,1],[0,1,0],[0,0,1],[0,0,0]]
labels=[1,0,0,0,0,0,0,0];
return dataset,labels
if __name__=='__main__':
percep=Perceptron(3,myfunc,0.1)
dataset,labels=get_training_dataset()
percep.train_and_iterate(20,dataset,labels)
|
b2eec627c9c5c33e1fffcd3faf91b7ba42bd1984 | xin-liqihua/PythonLearn | /Chapter_1/test2.py | 576 | 3.6875 | 4 | '''
获得用户输入的一个正整数输入,输出该数字对应的中文字符表示。
0到9对应的中文字符分别是:零一二三四五六七八九
'''
Str = "零一二三四五六七八九"
Num = input()
StrNum = str(Num)
for num in StrNum:
print(Str[int(num)], end="") |
a4490e34f74e9f168f2d75765157d506f3097571 | GaoYu/zeroPython | /15_filter.py | 700 | 3.6875 | 4 | def isodd(x):
return x % 2 == 1
for x in filter(isodd, range(10)):
print(x)
even = [x for x in filter(lambda x: x%2 ==0, range(10))]
#练习:
# 1. 将 1 ~20 内的偶数用filter筛选出来,形成列表
even = [x for x in
filter(lambda x : x%2==0, range(1,20))]
print(even)
even = list(filter(lambda x:x%2==0,range(1,20)))
print(even)
# 2. 用filter函数将1~100之间的所有素数(prime) 放入到列表中
def isprime(i):#素数从2开始向后遍历
if i <= 1:
return False
for x in range(2, i):
#判断能否被2整除的数
if i % x == 0:
return False
return True
L = list(filter(isprime,range(100)))
print(L) |
63d630f4c251a361a788d527db247a8dacb1297f | jschnab/leetcode | /arrays/subarray_sum_equals.py | 1,395 | 3.78125 | 4 | # leetcode challenge 560: subarray sum equals k
# given an array of integers and an integer k, we need to find the total
# number of continuous subarrays whose sum equals k
# input: [1,1,1], k = 2
# output: 2
def subarray_sum_brute(nums, k):
"""
Brute force solution, check every subarray and make its sum.
Time complexity: O(n^2)
Space complexity: O(n)
:param list[int] nums:
:params int k:
:return int:
"""
answer = 0
length = len(nums)
for i in range(length):
sum_ = 0
for j in range(i, length):
sum_ += nums[j]
if sum_ == k:
answer += 1
return answer
def subarray_sum_linear(nums, k):
"""
More scalable solution, make the cumulative sum of the array
and check how many values in the cumulative sum are separated by k.
Time complexity: O(n)
Space complexity: O(n)
:param list[int] nums:
:params int k:
:return int:
"""
answer = 0
sum_ = 0
count = {0: 1}
for n in nums:
sum_ += n
answer += count.get(sum_ - k, 0)
count[sum_] = count.get(sum_, 0) + 1
return answer
def test1():
assert subarray_sum_linear([1,1,1], 2) == 2
print("test 1 successful")
def test2():
assert subarray_sum_brute([1,1,1], 2) == 2
print("test 2 successful")
if __name__ == "__main__":
test1()
test2()
|
3f0ee2826011e17572e2ccef08f3ea01220d6ba3 | heysushil/full-python-course-2020 | /13.class.py | 2,632 | 4.34375 | 4 | # class: varibale + method : object
# hamesa class neame wo capital letter
class Myclass:
name = 'Python'
# create class object
obj = Myclass()
print(obj.name)
# creat a cons. in class
class User:
# createing construcre: it helps to pass values to each methods
# self: it's a current instance which holds current value and byt htee helpf of self we will pass values to any emthod
def __init__(self, name, course):
self.name = name
self.c = course
self.address = 'India'
def userDetails(self):
print('hello userdtails your name is: ',self.name,' your course name is: ',self.c,' your address is: ',self.address)
# only create obje of class
userobj = User('Mr. Ram','Python')
userobj.userDetails()
# other object
newuser = User('Ravi','PHP')
# del newuser.name
newuser.userDetails()
# print(userobj.name)
class NewUserREgistration:
pass
# new class
class HelloUser:
def __init__(self, users):
self.u = users
def users(self):
print('Hell all users: ',self.u)
# obj of HelloUser
# userslist = ['Ravi','Hemma','Pushpa','Neelam']
username = input('Enter your name: ')
user = HelloUser(username)
user.users()
# proper class
class UserDetilas:
def __init__(self, name, course, addr):
self.n = name
self.c = course
self.a = addr
# method to show user detials
def showUserDetails(self):
print('''
Hello {}, how are you.
Your course is {},
and your finall address is {}
'''.format(self.n,self.c,self.a))
def welcomeMessage(self):
# chekc conditon
if self.n == 'Ayman' or self.n == 'ayman':
print('Welcome ',self.n)
else:
print('Welcome new user ',self.n)
# create obj of UserDetilas
name = input('Enter your name: ')
course = input('Enter your course name: ')
addr = input('Enter your address: ')
mydetails = UserDetilas(name, course, addr)
mydetails.showUserDetails()
# mydetails.welcomeMessage()
'''
Programs:
1. create class in which you have 2 mthods and first one use to get the user details like name, mobile, email etc and on oher method you will show the detials. Remmber input work done into first method and you will pass it to another mthod.
2. creat a class in which you will recive dict data and which you show using multip line sting in method and also your dict data is someting like : studetn anem, father name, mother name, class. on mehtod also check if class is 2nd then show wlecome2nd class message with studetn name or if class is 3rd then show the same fo 3rd or 4th or 5th.
''' |
9c42ab072586874e5711476ec90637d04357dcae | stephenboothuk/a | /demo_dictionary.py | 220 | 3.671875 | 4 | a = dict(A=1, Z=-1)
print(a)
b = {'A': 1, 'Z': -1}
print(b)
c = dict(zip(['A', 'Z'], [1, -1]))
print(c)
d = dict([('A', 1), ('Z', -1)])
print(d)
e = dict({'Z': -1, 'A': 1})
print(e)
print(a == b == c == d == e) |
ffddb6adc1ef21f81a116723d7ad1635d58f4f96 | Aman-dev271/PythonProjects | /4thexc.py | 425 | 3.8125 | 4 | s= [2,3,4,5,'amandeep',333,444,55,666,77788,77,80,12,1,23]
list1 = []
for item in s:
if type(item) == int and item > 6:
print("your add the" ,',', item ,',',"value in the list")
list1.append(item)
else:
print("not can't be add")
print("your new list is :" ,list1)
for i in list1:
if i > 333:
print(i)
else:
print("it is not possible")
|
b8c81d302a4b70ec5ac355b73fac7e25880fe08a | siddiqum/Project2 | /Matplotlib_2.3.py | 681 | 4 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = [0,1,2,3,4]
y = [0,2,4,6,8]
plt.figure(figsize=(8,5), dpi=100)
plt.plot(x,y, 'g--', label='2x')
# select interval we want to plot points at
x2 = np.arange(0,4.5,0.5)
# Plot part of the graph as line
plt.plot(x2[:6], x2[:6]**2, 'b', label='X^2')
# Plot remainder of graph as a dot
plt.plot(x2[5:], x2[5:]**2, 'b--')
plt.title('Our First Graph!', fontdict={'fontname': 'Comic Sans MS', 'fontsize': 20})
# X and Y labels
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
# X, Y axis Tickmarks (scale of your graph)
plt.xticks([0,1,2,3,4,])
plt.legend()
plt.savefig('mygraph.png', dpi=300)
plt.show() |
6eb43172bf8e5c4701885531c6c39eae7e4e01e7 | KeleiAzz/LeetCode | /Google/Jump.py | 517 | 3.75 | 4 | def JumpArray(arr):
count = 0
visited = [0] * len(arr)
index = 0
while count < len(arr):
if visited[index] == 1 and index != 0:
return False
elif visited[index] >= 1:
break
visited[index] += 1
index = (index + arr[index]) % len(arr)
count += 1
print count
if index == 0 and count == len(arr):
return True
else:
return False
print JumpArray([1,1,1,1,1,1])
print JumpArray([2,2,3,1])
print JumpArray([7,5,2,3]) |
de45e28079a431009a68cb3d4fbce61da35c4a35 | LucasBarbosaRocha/URI | /Strings/1248_v2.py | 740 | 3.5625 | 4 | N = int(input())
for i in range(N):
dieta = input()
cafe = input()
almoco = input()
janta = ""
refeicao = cafe + almoco
dietaOrdenada = sorted(dieta)
refeicaoOrdenada = sorted(refeicao)
#print(dietaOrdenada, refeicaoOrdenada)
if (len(refeicaoOrdenada) > len(dietaOrdenada)):
print("CHEATER")
else:
aux = 1
j = 0
for i in range(len(refeicaoOrdenada)):
if (refeicaoOrdenada[i] not in dietaOrdenada):
aux = 0
break
if (aux == 1):
for i in range(len(dietaOrdenada)):
if (refeicaoOrdenada.count(dietaOrdenada[i]) == 0):
janta = janta + dietaOrdenada[i]
elif ((refeicaoOrdenada.count(dietaOrdenada[i]) > 1)):
aux = 0
break
if (aux == 1):
print (janta)
else:
print ("CHEATER")
|
7963927e5e78a670856a798f68c6328f825bdf7d | st4rk95/pruebasPython | /pruebasPython/aprendeconalf.es/tuplas_y_diccionarios/ejercicio13.py | 522 | 3.859375 | 4 | #Escribir un programa que pregunte por una muestra de numeros, separados por comas, los guarde en una lista y muestre por pantalla su media
numeros_introducidos = str(input("Introduce una serie de numeros separados por comas: "))
lista_numeros = numeros_introducidos.split(",")
suma_total = 0
for i in lista_numeros:
suma_total += int(i)
print ("En la lista hay "+str(len(lista_numeros))+" numeros, que suman un total de "+str(suma_total)+", por lo que la media aritmetica es "+str(suma_total/len(lista_numeros)))
|
f9cf783acce2309eb190bc8d638d2fee205f16ef | TingliangZhang/VR_Robot | /Python/Pythonpa/ch09/TemperatureConverter.py | 880 | 3.5625 | 4 | class TemperatureConverter:
@staticmethod
def c2f(t_c): #摄氏温度到华氏温度的转换
t_c = float(t_c)
t_f = (t_c * 9/5) + 32
return t_f
@staticmethod
def f2c(t_f): #华氏温度到摄氏温度的转换
t_f = float(t_f)
t_c = (t_f - 32) * 5 /9
return t_c
#测试代码
print("1. 从摄氏温度到华氏温度.")
print("2. 从华氏温度到摄氏温度.")
choice = int(input("请选择转换方向:"))
if choice == 1:
t_c = float(input("请输入摄氏温度: "))
t_f = TemperatureConverter.c2f(t_c)
print("华氏温度为: {0:.2f}".format(t_f))
elif choice == 2:
t_f = float(input("请输入华氏温度: "))
t_c = TemperatureConverter.f2c(t_f)
print("摄氏温度为: {0:.2f}".format(t_c))
else:
print("无此选项,只能选择1或2!")
|
a33faae818694f698b521fd060033e6973ce47af | Sudheer-Movva/Python_Assignment01 | /Assignment-1/Chap12/ChapTwelve3.py | 1,708 | 3.859375 | 4 |
class Account:
def __init__(self,id,balance=100):
self.__id = int(id)
self.__balance = float(balance)
def getID(self):
return self.__id
def getBalance(self):
return self.__balance
def withdraw(self,amount):
self.__balance -= float(amount)
def deposit(self,amount):
self.__balance += float(amount)
account_list = []
for i in range(10):
account = Account(i)
account_list.append(account)
#account_list.append(account.getID(),account.getInitialBalance())
while 1<2 :
account_id = eval(input("Enter an Account ID: "))
found = False
selected_account=[]
for idx in range(len(account_list)):
if account_list[idx].getID() == account_id:
found = True
selected_account.append(account_list[idx])
break
#print(selected_account[0].getID())
if not found:
print("Enter a correct ID")
continue
if found:
print("Main Menu")
print("1: check balance")
print("2: withdraw")
print("3: deposit")
print("4: exit")
choice = eval(input("Enter a choice: "))
if (choice == 1):
print("The balance is ",selected_account[0].getBalance())
elif (choice == 2):
amount = eval(input("Enter an amount to withdraw:"))
selected_account[0].withdraw(amount)
print("The balance is ",selected_account[0].getBalance())
elif (choice == 3):
amount = eval(input("Enter an amount to deposit:"))
selected_account[0].deposit(amount)
print("The balance is ",selected_account[0].getBalance())
elif (choice == 4):
continue
|
d75a943e08c427460ddfeba9629e6bef0d656b04 | sasazlat/UdacitySolution-ITSDC | /computer_vision/visualizing_the_data.py | 2,478 | 3.703125 | 4 |
# coding: utf-8
# # Day and Night Image Classifier
# ---
#
# The day/night image dataset consists of 200 RGB color images in two
# categories: day and night. There are equal numbers of each example: 100 day
# images and 100 night images.
#
# We'd like to build a classifier that can accurately label these images as day
# or night, and that relies on finding distinguishing features between the two
# types of images!
#
# *Note: All images come from the [AMOS
# dataset](http://cs.uky.edu/~jacobs/datasets/amos/) (Archive of Many Outdoor
# Scenes).*
#
# ### Import resources
#
# Before you get started on the project code, import the libraries and
# resources that you'll need.
# In[ ]:
import cv2 # computer vision library
import helpers
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
get_ipython().run_line_magic('matplotlib', 'inline')
# ## Training and Testing Data
# The 200 day/night images are separated into training and testing datasets.
#
# * 60% of these images are training images, for you to use as you create a
# classifier.
# * 40% are test images, which will be used to test the accuracy of your
# classifier.
#
# First, we set some variables to keep track of some where our images are
# stored:
#
# image_dir_training: the directory where our training image data is stored
# image_dir_test: the directory where our test image data is stored
# In[ ]:
# Image data directories
image_dir_training = "day_night_images/training/"
image_dir_test = "day_night_images/test/"
# ## Load the datasets
#
# These first few lines of code will load the training day/night images and
# store all of them in a variable, `IMAGE_LIST`. This list contains the images
# and their associated label ("day" or "night").
#
# For example, the first image-label pair in `IMAGE_LIST` can be accessed by
# index:
# ``` IMAGE_LIST[0][:]```.
#
# In[ ]:
# Using the load_dataset function in helpers.py
# Load training data
IMAGE_LIST = helpers.load_dataset(image_dir_training)
# ---
# # 1. Visualize the input images
#
# In[ ]:
# Select an image and its label by list index
image_index = 0
selected_image = IMAGE_LIST[image_index][0]
selected_label = IMAGE_LIST[image_index][1]
## TODO: Print out 1. The shape of the image and 2. The image's label `selected_label`
## TODO: Display a night image
# Note the differences between the day and night images
# Any measurable differences can be used to classify these images
|
2e4450a8c46670f23efce414fdec009cead76aed | yunusgok/Naive-Bayes-and-Hidden-Markov-Models | /nb.py | 5,424 | 4.03125 | 4 | from math import log as ln
import os
import re
import numpy as np
def vocabulary(data):
"""
Creates the vocabulary from the data.
:param data: List of lists, every list inside it contains words in that sentence.
len(data) is the number of examples in the data.
:return: Set of words in the data
"""
vocab = []
for lst in data:
for word in lst:
vocab.append(word)
return set(vocab)
def estimate_pi(train_labels):
"""
Estimates the probability of every class label that occurs in train_labels.
:param train_labels: List of class names. len(train_labels) is the number of examples in the training data.
:return: pi. pi is a dictionary. Its keys are class names and values are their probabilities.
"""
pi = {}
n = len(train_labels)
for label in train_labels:
if label in pi:
pi[label] += 1/n
else:
pi[label] = 1/n
return pi
def estimate_theta(train_data, train_labels, vocab):
"""
Estimates the probability of a specific word given class label using additive smoothing with smoothing constant 1.
:param train_data: List of lists, every list inside it contains words in that sentence.
len(train_data) is the number of examples in the training data.
:param train_labels: List of class names. len(train_labels) is the number of examples in the training data.
:param vocab: Set of words in the training set.
:return: theta. theta is a dictionary of dictionaries. At the first level, the keys are the class names. At the
second level, the keys are all the words in vocab and the values are their estimated probabilities given
the first level class name.
"""
theta = {}
n_vocab = len(vocab)
classes = set(train_labels)
for c in classes:
v = {}
for word in vocab:
v[word] = 0
theta[c] = v
for i in range(len(train_data)):
for word in train_data[i]:
theta[train_labels[i]][word] += 1
for label in theta:
count = 0
missing = 0
for word in theta[label]:
count += theta[label][word]
for word in theta[label]:
theta[label][word] = (theta[label][word]+1)/(count+n_vocab)
return theta
def test(theta, pi, vocab, test_data):
"""
Calculates the scores of a test data given a class for each class. Skips the words that are not occurring in the
vocabulary.
:param theta: A dictionary of dictionaries. At the first level, the keys are the class names. At the second level,
the keys are all of the words in vocab and the values are their estimated probabilities.
:param pi: A dictionary. Its keys are class names and values are their probabilities.
:param vocab: Set of words in the training set.
:param test_data: List of lists, every list inside it contains words in that sentence.
len(test_data) is the number of examples in the test data.
:return: scores, list of lists. len(scores) is the number of examples in the test set. Every inner list contains
tuples where the first element is the score and the second element is the class name.
"""
scores = []
for words in test_data:
sub = []
for label in pi:
result = ln(pi[label])
for word in words:
if word in theta[label]:
result += ln(theta[label][word])
sub.append((result,label))
scores.append(sub)
return scores
def read_data(folder, filename):
train_data_path = os.path.join(folder,filename)
train_data = []
with open(train_data_path, "r",encoding="utf-8") as train_data_file:
lines = train_data_file.readlines()
for line in lines:
raw = line.lower()
wordList = re.sub("[^\w]", " ", raw).split()
train_data.append(wordList[1:])
return train_data
def read_labels(folder, filename):
train_labels_path = os.path.join(folder,filename)
train_labels = []
with open(train_labels_path, "r",encoding="utf-8") as train_labels_file:
labels = train_labels_file.read().splitlines()
return labels
def compare_labels(estimated_labels, train_labels):
count = 0
n = len(estimated_labels)
for i in range(n):
if estimated_labels[i] == test_labels[i]:
count += 1
return count/n
def find_labels(scores):
estimated_labels = []
for i in range(len(scores)):
maximum = scores[i][0]
for label in scores[i]:
if label[0]> maximum[0]:
maximum = label
estimated_labels.append(maximum[1])
return estimated_labels
if __name__ == "__main__":
folder = os.path.join('hw4_data', 'sentiment')
train_data = read_data(folder, "train_data.txt")
train_labels = read_labels(folder, "train_labels.txt")
test_data = read_data(folder, "test_data.txt")
test_labels = read_labels(folder, "test_labels.txt")
vocab = vocabulary(train_data)
pi = estimate_pi(train_labels)
theta = estimate_theta(train_data, train_labels, vocab)
scores = test(theta, pi, vocab, test_data)
estimated_labels = find_labels(scores)
accuracy = compare_labels(estimated_labels, train_labels)
print("Accuracy:" ,accuracy) |
971315675af2175540d8bbf088a75e14f45b2fff | brunops/algorithms | /misc/python/maximum-subarray.py | 315 | 3.609375 | 4 | # Kadane's algorithm
# Return maximum continuos sum in an array
# Complexity O(n)
def maximum_subarray(A):
max_so_far = max_ending_here = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
print maximum_subarray([1,11,-10,20])
|
aab522dbe4b5af63d7f8a01e12febcc2c7767e82 | TimLeeTY/compPhyEx | /ex2/ODE.py | 8,581 | 3.875 | 4 | """
=========================================
Ex.2 Solving the ODE of a simple pendulum
=========================================
Solve equation: θ''=-(g/l)*sin(θ)-q*θ'+F*sin(Ω*t)
Define: θ=θ, ⍵=θ'
The coupled first order ODES are:
⍵=θ'
⍵'=-(g/l)*sin(θ)-q*⍵+F*sin(Ω*t)
Apply 4th order Runge-Kutta
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
# returns the derivatives of θ and ⍵, F and q referenced from global scope (bad practice but neater code)
def dy(y, t): return(np.array([y[1], -1*np.sin(y[0])-q*y[1]+F*np.sin(Omg*t)]))
def RK4step(dy, t, y, dt): # More 'standard' implementation of 4th order Runge-Kuta method
k1 = dt*dy(y, t)
k2 = dt*dy(y+k1/2, t+dt/2)
k3 = dt*dy(y+k2/2, t+dt/2)
k4 = dt*dy(y+k3, t+dt)
return(k1/6+k2/3+k3/3+k4/6)
def RK4(dy): # Implementation of 4th order Runge-Kuta method using Lambda notation
return(lambda t, y, dt: ( # takes arguments of t (time), y (the current [θ,⍵]) and dt (the timestep)
lambda k1: (
lambda k2: (
lambda k3: (
# returns the vector [Δθ(t),Δ⍵(t)]
lambda k4: k1/6+k2/3+k3/3+k4/6
)(dt*dy(y+k3, t+dt))
)(dt*dy(y+k2/2, t+dt/2))
)(dt*dy(y+k1/2, t+dt/2))
)(dt*dy(y, t))
)
# performs integration given dy (the derivatives), dt (the timestep), Tf (the final time) and y0,y1 (the initial conditions)
def solveRK(RK4, dy, dt, Tf, y0, y1=0):
t, y = 0., np.array([y0, y1]) # initial conditions
# initialises array, final holds results as a list of [θ(t),⍵(t)] values
finalRK = np.zeros((int(Tf/dt), 2))
for i in range(len(finalRK)):
finalRK[i] = y
# t,y=t+dt,y+RK4step(dy,t,y,dt)
t, y = t+dt, y+RK4(dy)(t, y, dt)
# returns an 2D array with rows of [θ(t),⍵(t)] at each timestep
return(finalRK)
#%%
q, Omg, F = 0, 2/3, 0 # setting parameters
dt = 0.05
"""
------------------------
§1. Period vs. amplitude
------------------------
Investigating how the period, T, is affected by θ_0
"""
def period(tarr, y): # finds the avearge time between when y changes sign
return(lambda sgn: (
# returns time period and associated error
lambda T: np.array([np.mean(T[1:]-T[:-1]), np.std(T[1:]-T[:-1])])
)((tarr[:-1])[(sgn[1:]-sgn[:-1]) != 0]*2) # time stamps for when y changes sign (*2 for actual period)
)(sgn=np.sign(y)) # sign of y
Tf = 600 # average time period over ~100 oscillations
tarr = np.arange(0.0, Tf, dt)
y0 = np.linspace(0.01, np.pi-0.01, 100)
parr = np.array([period(tarr, integrate.odeint(dy, [i, 0], tarr)[:, 1])
for i in y0]) # more efficient LSODA method used here
# plotting results
fig, ax = plt.subplots()
plt.xlabel(r"$\theta_0$")
plt.ylabel(r"$T$/s")
plt.xlim([0, np.pi])
plt.ylim([5, 30])
ax.plot(y0, parr[:, 0])
fig.savefig("TvsAmp.pdf", format="pdf")
#%%
"""
-------------------
§2. Varying q and F
-------------------
Investigating how θ and ⍵ vary with different values of q and F
(θ_0 kept at 0.2 throughout)
"""
tD = np.pi*3
Tf = 100
tarr = np.arange(0.0, Tf, dt)
F, qarr = 0, [5, 2, 0.5] # keeping F at 0, varying q
# plotting θ in for loop on one figure
fig, ax = plt.subplots()
plt.xlabel(r'$t/T_\mathrm{0}$')
plt.ylabel(r'$\theta (t)$/rad')
plt.xlim([0, 6])
for i in qarr:
q = i
ax.plot(tarr/2/np.pi, solveRK(RK4, dy, dt, Tf, 0.2)
[:, 0], label=r'$q={:.1f}$'.format(q), lw=0.8)
ax.legend()
fig.savefig('q_theta.pdf', format="pdf")
# plotting ⍵ in for loop on one figure
fig, ax = plt.subplots()
plt.xlabel(r'$t/T_\mathrm{0}$')
plt.ylabel(r'$\omega (t)$/rad s$^{-1}$')
plt.xlim([0, 6])
for i in qarr:
q = i
ax.plot(tarr/2/np.pi, solveRK(RK4, dy, dt, Tf, 0.2)
[:, 1], label=r'$q={:.1f}$'.format(q), lw=0.8)
ax.legend()
plt.gcf()
fig.savefig('q_omega.pdf', format="pdf")
# keeping q fixed at 0.5 while varying F
q, Farr = 0.5, [0.5, 1.2, 1.44, 1.465]
# plotting θ in for loop on one figure
fig, ax = plt.subplots()
plt.xlabel(r'$t/T_\mathrm{D}$')
plt.ylabel(r'$\theta (t)$/rad')
plt.xlim([0, 8])
for i in Farr:
F = i
ax.plot(tarr/tD, solveRK(RK4, dy, dt, Tf, 0.2)
[:, 0], label=r'$F={:.3f}$'.format(F), lw=0.8)
ax.legend()
fig.savefig('F_theta.pdf', format="pdf")
# plotting ⍵ in for loop on one figure
fig, ax = plt.subplots()
plt.xlabel(r'$t/T_\mathrm{D}$')
plt.ylabel(r'$\omega (t)$/rad s$^{-1}$')
plt.xlim([0, 8])
plt.ylim([-3, 3])
for i in Farr:
F = i
ax.plot(tarr/tD, solveRK(RK4, dy, dt, Tf, 0.2)
[:, 1], label=r'$F={:.3f}$'.format(F), lw=0.8)
ax.legend(fontsize=8)
fig.savefig('F_omega.pdf', format="pdf")
#%%
"""
-----------
§3. θ vs. ⍵
-----------
Investigating the form of θ vs. ⍵ with different values of F
Shows example of period doubling and quadrupling
"""
Tf = 50*tD
tarr = np.arange(0.0, Tf, dt)
# keeping q fixed at 0.5 while varying F
q, Farr = 0.5, [0.5, 1.2, 1.44, 1.465]
title = dict(zip(Farr, ['Small angle', 'Chaotic',
'Period doubling', 'Period quadrupling']))
# plotting different F values on separate figures
for i in Farr:
F = i
plt.figure()
plt.xlabel(r'$\theta (t)$/rad')
plt.xlim([-np.pi, np.pi])
plt.ylabel(r'$\omega (t)$/rad s$^{-1}$')
y = integrate.odeint(dy, [0.2, 0], tarr)
plt.plot((y[:, 0]+np.pi) % (2*np.pi)-np.pi, y[:, 1], '.', markersize=1)
# centring θ around 0 and in the range [-π,π]
plt.title('{}'.format(title[F]))
plt.gcf()
plt.savefig('y0vy1_F{:.0f}.pdf'.format(F*1000), format="pdf")
#%%
"""
--------------------
§4. 'Chaotic motion'
--------------------
Investigating the sensitivity of motion to initial conditions for F=1.2
"""
F, q = 1.2, 0.5
Tf = 500
tarr = np.arange(0.0, Tf, dt)
y0 = [0.2, 0.20001, 0.20000001] # initial θ_0 vary by only 1/20000
# plotting both graphs on the same axis
fig, ax = plt.subplots()
plt.xlim(0, Tf/tD)
plt.xlabel(r'$t/T_\mathrm{D}$')
plt.ylabel(r'$\theta (t)$/rad')
for i in y0:
ax.plot(tarr/tD, solveRK(RK4, dy, dt, Tf, i)
[:, 0], label=r"$\theta_0={}$".format(i))
ax.legend()
fig.savefig('chaotic.pdf', format="pdf")
#%%
"""
-------------------
§5. Plotting Energy
-------------------
Comparing 4th order Runge-Kuta method implemented above with the standard scipy
LSODA implementation
Computing time is substantial (the R-K implementation in particular, to save on
time, results are plotted separately by 'energyPlot.py' as to avoid reevaluating
the integral every time I wish to change the plot.
"""
q, Omg, F = 0, 2/3, 0 # setting parameters
dt = 0.05 # step size
Tf = int(np.pi*2*10000) # final time (10000 natural oscilaltions)
tarr = np.arange(0.0, Tf, dt)
y0 = 0.01 # initial displacement
t, y = 0., np.array([y0, 0.]) # initial conditions
# my implementation of 4th order R-K, slower by factor of ~10
finalRK = solveRK(RK4, dy, dt, Tf, y0)
# default integrate.odeint implementation of LSODA
finalLSODA = integrate.odeint(dy, y, tarr)
# keeping every 256 entries to decrease file size
trunc = np.arange(len(tarr)) % (2**8) == 0
tarr, finalRK, finalLSODA = tarr[trunc], finalRK[trunc], finalLSODA[trunc]
np.savetxt('energyDiffOut.csv', np.stack(
(tarr, finalRK.T[0], finalRK.T[1], finalLSODA.T[0], finalLSODA.T[1])).T, delimiter=',')
#%%
"""
===================================
Appendix - Animating chaotic motion
===================================
Commented out as it does not directly relate to the task and provides no
particular insight into the physics.
import matplotlib.animation as animation
F,q=1.2,0.5
Tf=300
tarr=np.arange(0.0, Tf, dt)
finalRK1=solveRK(RK4,dy,dt,Tf,0.2)
finalRK2=solveRK(RK4,dy,dt,Tf,0.20001)
def init():
line1.set_data([], [])
line2.set_data([], [])
return(line1,line2)
def animate(i):
tempx=[0,np.sin(finalRK1[3*i][1])]
tempy=[0,-np.cos(finalRK1[3*i][1])]
tempx1=[0,np.sin(finalRK2[3*i][1])]
tempy1=[0,-np.cos(finalRK2[3*i][1])]
line1.set_data(tempx,tempy)
line2.set_data(tempx1,tempy1)
return (line1,line2)
fig = plt.figure()
ax = plt.axes(xlim=(-1.2,1.2), ylim=(-1.2,1.2),yticks=[],xticks=[] ,autoscale_on=False)
ax.set_aspect('equal')
line1, = ax.plot([], [], 'o-', lw=2)
line2, =ax.plot([], [], 'o-', lw=2)
ani = animation.FuncAnimation(fig, animate, frames=np.arange(1, int(len(finalRK1)/3)), interval=20, init_func=init)
Writer = animation.writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='tyl35'), bitrate=1800)
ani.save('pendulum.mp4', writer=writer)
plt.show()
"""
|
c624064df0b4cac02bddc33a2aa1d71ca93c9104 | GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I | /exercicios_strings/exe2.py | 243 | 4.0625 | 4 |
'''. Escreva um programa que leia uma palavra qualquer e veri que se esta palavra é um
palíndromo.'''
string = input('Informe uma palavra: ')
if string == string[::-1]:
print("É palindromo!")
else:
print("Não é palindromo!") |
a25941bf290bd30bc3330d63704be7a212c82f37 | ninux1/Python | /decorators/timedeco.py | 500 | 3.625 | 4 | #!/usr/bin/env python
from datetime import datetime
import time
def timedeco(func):
def action(num):
start = datetime.now()
res = func(num)
print(res)
return datetime.now() - start
return action
@timedeco
def factorial(num):
result = num
while(num != 1):
result = result * (num-1)
num = num-1
return result
if __name__ == '__main__':
print("The time required to execute 6 factorial is {} microseconds".format(factorial(6))) |
12dc6c29533b9fd51fde9bc4927934550f904fac | anthonyraj/py | /interviews/dailycoding/amazon-steps.py | 1,288 | 4.53125 | 5 | """
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time,
you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5},
you could climb 1, 3, or 5 steps at a time.
"""
def climb(n):
if (n == 0 or n == 1): return 1
if (n == 2): return 2
count = 0
if (n > 2):
count = climb(n-1) + climb(n-2)
return count
def climb_x(n,x):
if (n == 0): return 1
total = {}
total[0] = 1
#print "n=",n
for step in range(1,n):
#print "step=",step
count = 0
for i in x:
if step-i >= 0:
count += total[step-i]
total[step]= count
print total
return total[n-1]
def run(n):
print "n = ",n," count = ",climb(n)
def run1(n,x):
print "n = ",n, "x = ",x," count = ",climb_x(n,x)
run(2)
run(3)
run(4)
run(5)
run(6)
run(7)
x=[1,3,5]
run1(3,x)
run1(5,x)
x = [5,10,15]
run1(100,x) # wrong result
|
67785b581ac29d74c123c5a986f872cc1e67164a | PriteshKiri/Basic-Pyhon-Projects | /rolling the dice/dicee.py | 862 | 3.640625 | 4 | from PIL import Image
from random import randint
randomm = randint(1,6)
im = Image.open('dice.jpg')
while True :
inp = input("Please type 'ROLL' to roll the dice : ")
if inp == 'ROLL':
def roll(value):
if value==1:
box = (0,0,333,342)
portion1 = im.crop(box)
portion1.show()
if value==2:
box = (333,0,666,342)
portion2 = im.crop(box)
portion2.show()
if value==3:
box = (666,0,999,342)
portion3 = im.crop(box)
portion3.show()
if value==4:
box = (0,342,333,685)
portion4 = im.crop(box)
portion4.show()
if value==5:
box = (333,342,666,685)
portion5 = im.crop(box)
portion5.show()
if value==6:
box = (666,342,1000,680)
portion6 = im.crop(box)
portion6.show()
roll(randomm)
break
else:
print(f"WRONG INPUT ! you have entered '{inp}'")
|
dfa4be1c2fd32777a3ce4855107ecda5226f073a | vksmgr/DA-Py | /src/test.py | 2,451 | 3.796875 | 4 | import bisect
c = [1,2,2,4,9]
pos = bisect.bisect(c, 10)
print("position : {}".format(pos))
bisect.insort(c,10)
print(c)
for (i, value) in enumerate(c):
print(" I : {0} , value : {1}".format(i,value))
itme = 'i love you'
print(sorted(itme))
print(list(zip(c,itme)))
for (i, v) in enumerate(zip(c,itme)):
print("i : {0}, value: {1}".format(i,v))
# the cleaver way to unzip is
first_value, last_value = zip(*zip(c,itme))
print(first_value)
print(last_value)
# dictionary (hashmaps)
dics = {1: 'one', 2: 'two', 3: 'three'}
print(dics[1])
dics[4] = 'four'
print(dics[4])
#dict function will accept a list of 2- tuples
ld = dict(zip(c,itme))
print(ld)
#arranging words by there first letter
words = ['apple', 'bar', 'boom']
by_first_letter = {}
for word in words:
letter = word[0]
if letter not in by_first_letter:
by_first_letter[letter] = [word]
else:
by_first_letter[letter].append(word)
print(by_first_letter)
#you can do same thing in set default
by_first_letter_new = {}
for word in words:
letter = word[0]
by_first_letter_new.setdefault(letter, []).append(word)
print(by_first_letter_new)
#you can also use default dict
from collections import defaultdict
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(by_letter)
#python comprehension feature
strings = [ 'a' , 'as' , 'bat' , 'car' , 'dove' , 'python' ]
val = [x.upper() for x in strings if len(x) > 2]
print(val)
#dict comprehensions
dict_comp = { index: val for index, val in enumerate(dics)}
print(dict_comp)
#dict comprehensions with strings
local_mapping = {idx: val.upper() for idx, val in enumerate(strings)}
print(local_mapping)
#nested comprehension
all_data = [[ 'John' , 'Emily' , 'Michael' , 'Mary' , 'Steven' ],
[ 'Maria' , 'Juan' , 'Javier' , 'Natalia' , 'Pilar' ]]
#get a single list containing all names with two or more e’s in them
result = [name for names in all_data for name in names if name.count('e') > 1]
print(result)
#“flatten” a list of tuples of integers into a simple list of integers
some_tuples = [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )]
simple_list = [x for tuple in some_tuples for x in tuple]
print(simple_list)
#produce list of list insted of just list
list_list = [[x for x in tuple]for tuple in some_tuples]
print(list_list) |
64ab408d192d3d38ebf9be70772c6373fe1a3ecb | tabletenniser/leetcode | /5442_avoid_flood.py | 5,227 | 3.984375 | 4 | '''
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Given an integer array rains where:
rains[i] > 0 means there will be rains over the rains[i] lake.
rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
Return an array ans where:
ans.length == rains.length
ans[i] == -1 if rains[i] > 0.
ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)
Example 1:
Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.
Example 2:
Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
Example 3:
Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
Example 4:
Input: rains = [69,0,0,0,69]
Output: [-1,69,1,1,-1]
Explanation: Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1] is acceptable where 1 <= x,y <= 10^9
Example 5:
Input: rains = [10,20,20]
Output: []
Explanation: It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
Constraints:
1 <= rains.length <= 10^5
0 <= rains[i] <= 10^9
'''
class Solution:
def sub(self, rains):
res = []
hs = dict()
slow, fast = 0, 0
while fast < len(rains):
r = rains[fast]
if r != 0:
if r in hs:
while True:
if slow >= fast:
return []
r2 = rains[slow]
print(r,slow,r2)
if r2 == 0:
if slow > hs[r]:
res.append(r)
slow += 1
break
else:
res.append(1)
else:
res.append(-1)
slow += 1
hs[r] = fast
fast += 1
# print(slow,res)
while slow < len(rains):
r = rains[slow]
num = 1 if r == 0 else -1
res.append(num)
slow += 1
return res
def avoidFloodOLD(self, rains):
res = self.sub(rains)
if len(res) > 0:
return res
# res = self.sub(rains[::-1])
# if len(res) > 0:
# return res[::-1]
return []
def avoidFlood(self, rains):
dry_lands = []
last_flood = dict()
res = []
for i,r in enumerate(rains):
if r == 0:
dry_lands.append(i)
res.append(1)
else:
if r in last_flood:
print(i,r,dry_lands,last_flood,res)
dried = False
for j,dl in enumerate(dry_lands):
if dl > last_flood[r]:
res[dl] = r
last_flood[r] = i
del dry_lands[j]
dried = True
break
if not dried:
return []
else:
last_flood[r] = i
res.append(-1)
return res
s = Solution()
# rains = [1,2,3,4]
# assert s.avoidFlood(rains) == [-1,-1,-1,-1]
# rains = [1,2,0,0,2,1]
# print(s.avoidFlood(rains))
# assert s.avoidFlood(rains) == [-1,-1,2,1,-1,-1]
# rains = [1,2,0,1,2]
# assert s.avoidFlood(rains) == []
# # rains = [69,0,0,0,69]
# # assert s.avoidFlood(rains) == []
# rains = [10,20,20]
# assert s.avoidFlood(rains) == []
# rains = [0,1,1]
# assert s.avoidFlood(rains) == []
# rains = [1,0,2,0,2,1]
# rains = [1,0,2,0,1,2]
# rains = [1,2,0,2,3,0,1]
# assert s.avoidFlood(rains) == [-1,-1,2,-1,-1,1,-1]
# rains = [1,2,0,2,3,0,1][::-1]
# assert s.avoidFlood(rains) == [-1,-1,2,-1,-1,1,-1][::-1]
# rains = [1,1,0,0]
# assert s.avoidFlood(rains) == []
rains = [2,3,0,0,3,1,0,1,0,2,2]
print(s.avoidFlood(rains))
|
d1c34cf7c505b25a714238ffda640cf391132db8 | dongsik93/HomeStudy | /Question/sw_expert/D2/1983.py | 867 | 3.640625 | 4 | def grade(num, rank):
import math
n = math.ceil(rank / (num / 10))
if(n == 1):
return "A+"
elif(n == 2):
return "A0"
elif(n == 3):
return "A-"
elif(n == 4):
return "B+"
elif(n == 5):
return "B0"
elif(n == 6):
return "B-"
elif(n == 7):
return "C+"
elif(n == 8):
return "C0"
elif(n == 9):
return "C-"
else:
return "D0"
T = int(input())
for i in range(T):
N, K = map(int, input().split())
score = []
for idx, j in enumerate(range(N),1):
mid, fin, proj = map(int, input().split())
total = mid * 0.35 + fin * 0.45 + proj * 0.2
score.append([total,idx])
score.sort(reverse=True)
for j in range(len(score)):
if(score[j][1] == K):
print(f"#{i+1} {grade(N,j+1)}")
|
dae238ed82e3ba001f9213f6190829b8e9b32bfa | monicador/Python | /Else_Numero_romano.py | 1,049 | 4 | 4 | '''
Elabora un algoritmo que permita ingresar un numero entero,
de 1 a 10, y muestre su equivalente escrito en romano.
'''
numero = int(input("Escribe un numero> "))
if numero == 1:
print("I")
else:
if numero == 2:
print("II")
else:
if numero == 3:
print("III")
else:
if numero == 4:
print("IV")
else:
if numero == 5:
print("V")
else:
if numero == 6:
print("VI")
else:
if numero == 7:
print("VII")
else:
if numero == 8:
print("VIII")
else:
if numero == 9:
print("IX")
else:
if numero == 10:
print("X")
|
970ea9d184376b89e739f89985844cfd1e25afcc | shixinyang666/pyworkspace | /day03/demodef.py | 729 | 4 | 4 | #定义九九乘法表函数
def nine() :
for i in range(1,10) :
for j in range(1,i+1) :
print("{0} * {1} = {2}".format(i,j,i*j),end=" ")
print()
#定义1-100对齐
def num() :
for i in range(1,101) :
num = str(i).rjust(3," ")
print(num,end="")
if i % 10 ==0 :
print()
#定义菱形函数
def rhombus(row) :
b=row
c=row
for i in range(1,row+1) :
print(" "*(c-1),"*"*(2*i-1))
c-=1
if i == row :
for j in range(1,row) :
print(" "*j,"*"*(2*b-3))
b-=1
#定义等边三角形函数
def triangle(row) :
for i in range(row+1):
print(" " * (row - i), end="")
print(" *" * i)
|
705018ff1ff100306f2070607e62d9849015ce69 | nahaza/pythonTraining | /ua/univer/lesson02/__init__.py | 511 | 3.9375 | 4 | def task05_print_season(month_number):
if month_number == 1 or month_number == 2 or month_number == 12:
season = 'Winter'
elif month_number == 3 or month_number == 4 or month_number == 5:
season = 'Spring'
elif month_number == 6 or month_number == 7 or month_number == 8:
season = 'Summer'
elif month_number == 9 or month_number == 10 or month_number == 11:
season = 'Autumn'
print(season)
month_number = input("Enter month_number: ")
task05_print_season()
|
35507f01c5093c7c8fd9e7796eaee73b24a1f235 | ScITS-Bern/ddip | /hints/fib.py | 1,229 | 3.578125 | 4 | from functools import wraps
def debug(f):
@wraps(f)
def debug_wrapper(*args, **kwargs):
print(f"{f.__name__} called with arguments:", *args, **kwargs)
return f(*args, **kwargs)
return debug_wrapper
def memoize(f):
cache = {} # Some sort of data structure to store cached results.
# A dict works well, mapping { n: f(n) }
@wraps(f)
def memoize_wrapper(n):
# Should check if result of f(n) is already computed
# If not, compute, store and return
# If yes, return stored
# if n is in cache's keys:
# return cache[n]
# else:
# compute f(n)
# store in cache[n]
# return it
return f(n)
return memoize_wrapper
@debug
def fib(n):
if n in [0, 1]:
return 1
else:
return fib(n - 2) + fib(n - 1)
@memoize
@debug
def memo_fib(n):
if n in [0, 1]:
return 1
else:
return memo_fib(n - 2) + memo_fib(n - 1)
print(f"f(6) is {fib(6)}") # Logs 25 calls
print(f"f(6) is {memo_fib(6)}") # Should log only 7 calls
print(f"f(5) is {memo_fib(5)}") # Should log no calls: already calculated
|
bb657dbc42cdb36af3ed3cb13523c44c1ab27b8a | zhaochl/python-utils | /utils/sort_util_me.py | 4,582 | 3.9375 | 4 | #!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
# 各种排序算法
# author zcl
# date:2016/1/11
#选择排序
def select_sort(sort_array,asc=True):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[i:len(sort_array)]):
if asc:
if sort_array[i] > sort_array[j + i]:
#交换
sort_array[i], sort_array[j + i] = sort_array[j + i], sort_array[i]
else:
if sort_array[i] < sort_array[j + i]:
#交换
sort_array[i], sort_array[j + i] = sort_array[j + i], sort_array[i]
return sort_array
#冒泡排序
def bubble_sort(sort_array):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[:len(sort_array) - i - 1]):
if sort_array[j] > sort_array[j + 1]:
sort_array[j], sort_array[j + 1] = sort_array[j + 1], sort_array[j]
#插入排序
def insert_sort(sort_array):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[:i]):
if sort_array[j] > sort_array[i]:
sort_array.insert(j, sort_array[i])
del sort_array[i + 1]
#归并排序
def merge_sort_wrapper(sort_array):
merge_sort(sort_array, 0, len(sort_array) - 1)
def merge_sort(sort_array, left = 0, right = 0):
if left < right:
center = (left + right) / 2
merge_sort(sort_array, left, center)
merge_sort(sort_array, center + 1, right)
merge(sort_array, left, right, center)
def merge(sort_array, left, right, center):
result = []
arrayA = sort_array[left:center + 1]
arrayB = sort_array[center + 1:right + 1]
while((len(arrayA) > 0) and (len(arrayB) > 0)):
if(arrayA[0] > arrayB[0]):
result.append(arrayB.pop(0))
else:
result.append(arrayA.pop(0))
if(len(arrayA) > 0):
result.extend(arrayA)
if(len(arrayB) > 0):
result.extend(arrayB)
sort_array[left:right + 1] = result
#快排
def quick_sort(sort_array):
if(len(sort_array) < 2):
return
left = [x for x in sort_array[1:] if x < sort_array[0]]
right = [x for x in sort_array[1:] if x >= sort_array[0]]
quick_sort(left)
quick_sort(right)
sort_array[:] = left + [sort_array[0]] + right
#shell排序
def shell_sort(sort_array):
dist=len(sort_array)/2
while dist > 0:
for i in range(dist,len(sort_array)):
tmp=sort_array[i]
j = i
while j >= dist and tmp < sort_array[j - dist]:
sort_array[j] = sort_array[j - dist]
j -= dist
sort_array[j] = tmp
dist /= 2
#基数排序,均为整数,不支持负数和重复
def radix_sort(sort_array):
max_elem = max(sort_array)
bucket_list = []
for i in range(max_elem):
bucket_list.insert(i, 0)
for x in sort_array:
bucket_list[x - 1] = -1
sort_array[:] = [x + 1 for x in range(len(bucket_list)) if bucket_list[x] == -1]
#堆排序
def heap_sort(sort_array):
#没有写出来,再想想
pass
#测试例子
def algo_sort_test(sort_array, sort_method):
sort_method(sort_array)
if __name__ == '__main__':
print '---------select_sort-asc----'
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
select_sort(sort_array,True)
print sort_array
print '---------select_sort-desc----'
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
select_sort(sort_array,False)
print sort_array
print '---------bubble_sort-desc----'
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, bubble_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, insert_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, merge_sort_wrapper)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 300, 19, 13, 16, 18, 500, 190, 456, 23]
algo_sort_test(sort_array, quick_sort)
print sort_array
sort_array = [1, 2, 3, 5, -4, 4, 10, 3, 19, 13, 16, 18, 5, 190, 456, 23]
algo_sort_test(sort_array, shell_sort)
print sort_array
sort_array = [1, 2, 3, 5, 4, 10, 19, 13, 16, 18, 190, 456, 23]
algo_sort_test(sort_array, radix_sort)
print sort_array
print 'OK'
|
99d44b2b2a2d1cc03c95820a75c31fc72da95695 | codeblaster7/TypingSpeedGame | /TypingSpeedGame.py | 3,731 | 3.625 | 4 | from tkinter import *
import random
from tkinter import messagebox
def wordTyper():
global count, typing_words
text = "Welcome to Typing Test Game"
if count >= len(text):
count = 0
typing_words = ""
typing_words += text[count]
count += 1
font_label.configure(text=typing_words)
font_label.after(150, wordTyper)
def start_timer():
global time_left, score, miss
if time_left >= 11:
pass
else:
time_label_count.configure(fg="red")
if time_left > 0:
time_left -= 1
time_label_count.configure(text=time_left)
time_label_count.after(1000, start_timer)
else:
gameplay_label.configure(text="Hit = {} | Missed = {} | Total score = {}".format(score, miss, score-miss))
ss = messagebox.askretrycancel('Time Up!', 'To play the game again hit retry button')
if ss == True:
score = 0
time_left = 60
miss = 0
time_label_count.configure(text=time_left)
word_label.configure(text=words[0])
score_label_count.configure(text=score)
def startGame(event):
global score, miss
if time_left == 60:
start_timer()
gameplay_label.configure(text="")
if word_entry.get() == word_label['text']:
score += 1
score_label_count.configure(text=score)
else:
miss += 1
print("Miss:", miss)
random.shuffle(words)
word_label.configure(text=words[0])
word_entry.delete(0, END)
# Created Root
root = Tk()
root.geometry('800x600+400+100')
root.configure(bg="peach puff")
root.title("Typing Test Game")
root.iconbitmap("icon.ico")
# Created Variables
score = 0
time_left = 60
count = 0
miss = 0
typing_words = ""
words = ['leave', 'bullet', 'coding', 'programmer', 'two', 'move', 'been',
'song', 'children', 'way', 'too', 'over', 'good', 'turn', 'even',
'stop', 'will', 'head', 'call', 'spell', 'city', 'life', 'that',
'saw', 'too', 'back', 'land', 'see', 'high', 'men', 'father']
# Created Label
font_label = Label(root, text="",
font=("AppleSystemUIFont", 25, "italic"),
bg="peach puff", fg="gray11", width=40)
font_label.place(x=10, y=10)
wordTyper()
random.shuffle(words)
word_label = Label(root, text=words[0],
font=("AppleSystemUIFont", 40),
bg="peach puff", fg="MediumPurple4")
word_label.place(x=350, y=200)
score_label = Label(root, text="Your Score : ",
font=("AppleSystemUIFont", 25),
bg="peach puff", fg="dark slate blue")
score_label.place(x=10, y=100)
score_label_count = Label(root, text=score,
font=("AppleSystemUIFont", 25),
bg="peach puff", fg="dark slate blue")
score_label_count.place(x=80, y=160)
timer_label = Label(root, text="Time Left : ",
font=("AppleSystemUIFont", 25),
bg="peach puff", fg="dark slate blue")
timer_label.place(x=610, y=100)
time_label_count = Label(root, text=time_left,
font=("AppleSystemUIFont", 25),
bg="peach puff", fg="dark slate blue")
time_label_count.place(x=680, y=160)
gameplay_label = Label(root, text="Type the given word and hit enter",
font=("AppleSystemUIFont", 30), bg="peach puff", fg="gray43")
gameplay_label.place(x=120, y=450)
# Created Entry
word_entry = Entry(root, font=("AppleSystemUIFont", 25), bd=5, justify="center")
word_entry.place(x=250, y=300)
word_entry.focus_set()
root.bind('<Return>', startGame)
root.mainloop() |
bedd856ad1b846504e70083507a8ae31180dff4b | LiamAlexis/programacion-en-python | /clase 3/practica2/funciones.py | 586 | 3.5625 | 4 | from random import random
import random
def login():
usuario = "usuario123"
password = "1234"
nombre = input("Ingrese su Nick : ")
clave = input("ingrese su clave : ")
if usuario == nombre and password == clave :
print("logeado con exito")
else :
print("Nombre incorrecto")
def saludoUsuario(un_nombre):
print("Hola", un_nombre, "como estas?")
def numeroAleatorio():
print("el numero aleatorio es: ", random.randrange(5,21))
def opcionElegida(opcion):
print("opcion seleccionada: ", opcion)
|
3b514fdf6f5e8fc84da44807bbd6627e453d894b | mvanswol/leetCodeSols | /sols/python/6 - zigzag.py | 794 | 3.796875 | 4 | #
#
# Created By : Mitchell Van Swol
# Date : 2/6/2018
#
import sys
# convert the given string to a zigzag pattern
# basic idea is that we map out the string in a zig zag
# pattern and then join the strings together
# O(n) solution
class Solution(object):
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s):
return s
idx, step = 0, 1
end = numRows - 1
ans = [""] * numRows
for char in s:
ans[idx] += char
if not idx:
step = 1
elif idx == end:
step = -1
idx += step
return "".join(ans)
input_file = open(sys.argv[1])
input_line = input_file.readline()
string = input_line.strip("\n")
num_rows = int(input_file.readline().strip("\n"))
print(string)
print(Solution().convert(string, num_rows))
|
013e49e277d669dedfb3455080756edff51efa03 | fingerman/python_fundamentals | /intro/2_9_celsius.py | 74 | 3.640625 | 4 |
a = float(input())
a = a * 1.8 + 32
print(float("{0:.2f}".format(a)))
|
dc30aba7ef2f24014fe1aecfbd7eb7226f272e4a | Tavares-NT/Curso_NExT | /MóduloPython/Extras04.py | 803 | 4.1875 | 4 | '''Faça um programa, com uma função que necessite de uma quantidade de argumentos indefinida, e um argumento de operação dos valores. Esta função deverá returnar o resultado da operação destes valores.'''
def soma(valores):
resultado = 0
for x in valores:
resultado += x
return resultado
def calculadora(*valores, operacao='soma'):
if (operacao=='soma'):
return soma(valores)
elif (operacao=='multiplicacao'):
resultado = 1
for x in valores:
resultado *= x
return resultado
elif (operacao=='divisao'):
resultado = 1
for x in valores:
resultado /= x
return resultado
elif (operacao=='subtracao'):
resultado = 0
for x in valores:
resultado -= x
return resultado
print(calculadora(1,1,1,4,72,6,operacao='soma')) |
c20ccd58bf0b3aa60838c55010d72f55d8776107 | sannicko/Python | /Python/Scores and Grades.py | 753 | 4.03125 | 4 | import random
# testing the random module
# value = random.randint(1, 6)
# print(value)
# greetings = ['Hello', 'Hi', 'Hola', 'Ciao', 'Howdy']
# value = random.choice(greetings)
# print(value + ', Nick!')
def grade(scores):
print "Scores and Grades"
for i in range (0, scores):
score = random.randint(60, 101)
if score >= 60 and score <=69:
print "score:", score, "; Your grade is D"
elif score >= 70 and score <=79:
print "score:", score, "; Your grade is C"
elif score >= 80 and score <=89:
print "score:", score, "; Your grade is B"
elif score >= 90 and score <=100:
print "score:", score, "; Your grade is A"
print "END of the program. Bye!"
grade(15) |
1abc4b98c3ba3828d275cf663501fe43a4597ab0 | adit-negi/LeetcodePython | /tree/Btree_zig_zag.py | 1,058 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
def height(root):
if root is None:
return 0
ld = height(root.left)
rd = height(root.right)
return max(ld+1, rd+1)
def levelorder(root, level, l):
if not root:
return
if level == 1:
l.append(root.val)
elif level > 1:
levelorder(root.left, level-1, l)
levelorder(root.right, level-1, l)
return l
h = height(root)
l = []
for i in range(1, h+1):
if i % 2 == 0:
temp = levelorder(root, i, [])
temp = temp[::-1]
l.append(temp)
else:
l.append(levelorder(root, i, []))
return l
|
74f7ba4b795981263fe765dca51e92bf0882e5ff | cmanallen/csv-manager | /csv_manager/parser.py | 1,310 | 3.609375 | 4 | class Parser(object):
def __init__(self, csv, heading):
self.csv = csv
self.heading = heading
def parse(self):
loaded_file = open(self.csv).read()
return self._file_to_object(loaded_file)
def _file_to_object(self, csv):
rows = csv.split('\n')
row_object = {}
if self.heading:
head = rows[0].split(',')
del[rows[0]]
else:
head = None
i = 0
for row in rows:
row_object[i] = self._string_to_object(row, head)
i += 1
return row_object
def _string_to_object(self, string, head):
column_object = {}
character_list = []
escaped = False
j = 0
for character in string:
if not escaped and character == '"':
escaped = True
character_list.append(character)
elif escaped and character == '"':
escaped = False
character_list.append(character)
elif not escaped and character == ',':
column = ''.join(character_list)
character_list = []
if head is not None:
column_object[head[j]] = column
else:
column_object[j] = column
j += 1
elif escaped and character == ',':
character_list.append(character)
else:
character_list.append(character)
column = ''.join(character_list)
if head is not None:
column_object[head[j]] = column
else:
column_object[j] = column
return column_object |
9f20e220171d0a81dee3e827264b8560a62b6404 | Davidhfw/algorithms | /python/offer/56_num_two_counts.py | 473 | 3.53125 | 4 | import functools
def singleNumbers(nums):
ret = functools.reduce(lambda x, y: x ^ y, nums)
div = 1
while div & ret == 0:
div <<= 1
a, b = 0, 0
for n in nums:
if n & div:
a ^= n
print(f'first group nums is {n}')
else:
b ^= n
print(f'second group nums is {n}')
return [a, b]
if __name__ == '__main__':
nums = [4, 4, 5, 6, 8, 8, 9, 9, 0, 0]
print(singleNumbers(nums))
|
1fad2a4b2ca9231fc7c9167345f589dcaf5de227 | dansmyers/Baby-Name-Popularity | /app.py | 2,168 | 3.5 | 4 | from flask import Flask, request, Response, render_template
import json
import pandas as pd
app = Flask(__name__, static_url_path='', static_folder='./static')
### Constants
MIN_YEAR = 1910
MAX_YEAR = 2019
### Flask routes
@app.route('/')
def root():
return app.send_static_file('index.html')
@app.route('/submit')
def get_name_popularity():
"""
Return the year-by-year popularity rankings for a given baby name
and sex combination.
Parameters
----------
name: the baby name, passed as HTTP GET parameter in the URL
sex: 'F' or 'M', passed as HTTP GET parmatere in the URL
Returns
-------
JSON-formatted list containing the year-by-year popularity rankings
for the given name-sex combination.
"""
# Parse HTTP GET parameters
name = request.args.get('name')
sex = request.args.get('sex')
# Extract year and rank in year for the given name-sex combination
name_subset = babynames[(babynames['name'] == name) & (babynames['sex'] == sex)]
name_years = name_subset['year'].tolist()
name_ranks = name_subset['rank_in_year'].tolist()
# Some names do not appear in all years
#
# Build the return list with a value of None for the years where
# the given name does not appear
result = []
for year in range(MIN_YEAR, MAX_YEAR + 1):
if year not in name_years:
result.append(None);
else:
result.append(name_ranks.pop(0))
# Return as JSON
# Python None values are automatically parsed to JavaScript null
return_object = {'data': result}
return Response(json.dumps(return_object), mimetype='application/json')
### Main -- runs when the app starts
# Load babynames.csv into a pandas dataframe
babynames = pd.read_csv('./data/babynames.csv', names=['sex', 'year', 'name', 'count'])
# Construct a column giving the rank within each year and sex for each name
#
# e.g. Mary is the #1 ranking name for girls in 1910
# John is the #1 ranking name for boys in 1910
babynames['rank_in_year'] = babynames.groupby(['year', 'sex'])['count'].rank(ascending=False)
|
ab1b6f516912afd51b886ac577738fb2293ae1bb | ahtornado/study-python | /day6/test.py | 1,032 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2017/10/27 22:35
# @File :test.py
f = open("aa", 'r')
# read是逐字符地读取,是read可以指定参数,设定需要读取多少字符,无论一个英文字母还是一个汉字都是一个字符
f_read = f.read()
print (f_read)
f.close()
f1 = open("aa", 'r')
# readline只能读取第一行代码,原理是读取到第一个换行符就停止。
f1_read = f1.readline()
print (f1_read)
f1.close()
f2 = open("aa", 'r')
# readlines会把内容以列表的形式输出。
f2_read = f2.readlines()
print (f2_read)
f2.close()
# 使用for循环可以把内容按字符串输出。
# 输出一行内容输出一个空行,一行内容一行空格... 因为文件中每行内容后面都有
# 一个换行符,而且print()语句本身就可以换行,如果不想输出空行,就需要使用下面的语句::print(line.strip())
f3 = open('aa','r')
for line in f3.readlines():
# print(line)
print(line.strip())
f3.close()
|
54a7d6ac2c561d8d3518c53f617f4e18a478aa50 | jackcarter/MIT-ocw-hangman | /hangman.py | 3,574 | 3.84375 | 4 | # Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
import string
import os
clear = lambda: os.system('cls')
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
UNGUESSED_LETTER = "_"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
for secret_letter in secret_word:
if secret_letter not in letters_guessed:
return False
else:
return True
def print_alphabet():
global letters_guessed
output = []
for letter in string.ascii_lowercase:
if letter in letters_guessed:
output.append('*')
else:
output.append(letter)
return ''.join(output)
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
output = []
for secret_letter in secret_word:
if secret_letter in letters_guessed:
output.append(secret_letter)
else:
output.append(UNGUESSED_LETTER)
return ''.join(output)
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
letters_guessed = []
secret_word = get_word()
while True:
print (MAX_GUESSES - mistakes_made), 'incorrect guesses left.'
print print_alphabet()
print print_guessed()
guessed_letter = string.lower(raw_input("Your guess: "))
clear()
if guessed_letter in letters_guessed:
print "You already guessed that!"
else:
letters_guessed.append(guessed_letter)
if guessed_letter in secret_word:
if word_guessed():
print "You win!"
break
else:
print "Yep!"
else:
print "Nope!"
mistakes_made += 1
if mistakes_made == MAX_GUESSES:
print "You lose! The word was", secret_word
break
return None
play_hangman() |
7d1378c3f16d76dd4ba06d6a6233daea00ec5cb3 | SethHWeidman/algorithms_python | /problem_solving_miller_ranum/05_search_and_sort/05_shell_sort.py | 932 | 4.03125 | 4 | from typing import Any, List
def shell_sort(a_list: List[Any]) -> None:
def gap_insertion_sort(a_list: List[Any], start: int, gap: int) -> None:
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while position >= gap and a_list[position - gap] > current_value:
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_position in range(sublist_count):
gap_insertion_sort(a_list, start_position, sublist_count)
print("After increments of size", sublist_count, "The list is", a_list)
sublist_count = sublist_count // 2
if __name__ == "__main__":
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shell_sort(a_list)
print(a_list)
|
36e365dbe265cf257524b4d232ca87efd93eacef | amit-raut/Project-Euler-Python | /pr37/pr37.py | 1,145 | 4.125 | 4 | #!/usr/bin/env python
"""
The number 3797 has an interesting property. Being prime itself it is possible to continuously remove digits from left to right and remain prime at each stage: 3797 797 97 and 7. Similarly we can work from right to left: 3797 379 37 and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""
import math
count = finalSum = 0
def is_prime(n):
i = 3
if n == 1:
return False
elif n == 2:
return True
elif n % 2:
while i < math.sqrt(n) + 1:
if not n % i:
return False
i += 2
return True
else:
return False
def is_truncatable_prime(n):
returnFlag = False
for index in xrange(1, len(str(n))):
if is_prime(int(str(n)[:index])) and is_prime(int(str(n)[index:])):
returnFlag = True
else:
returnFlag = False
break
return returnFlag
for num in xrange(10, 1000000):
if is_prime(num) and is_truncatable_prime(num):
count += 1
finalSum += num
if count == 11:
print "The sum of the only 11 truncatable prime is %d" % finalSum #748317
break
|
b0826bcc7dd69c1a178060b564e58bd214168cfc | love-adela/algorithm-ps | /acmicpc/1247/1247.py | 213 | 3.71875 | 4 | for _ in range(3):
n = int(input())
test_list = [int(input()) for _ in range(n)]
if sum(test_list) == 0:
print('0')
elif sum(test_list) > 0:
print('+')
else:
print('-')
|
13927366798d51dfe47c977d29d5359be18be3d2 | Chehlarov/Python-Advanced | /D04_Fast_Food.py | 496 | 3.890625 | 4 | from collections import deque
existing_food = int(input())
line = map(int, input().split())
customers = deque(line)
print(max(customers))
is_complete = True
while len(customers) > 0:
order = customers[0]
if order <= existing_food and is_complete:
existing_food -= order
customers.popleft()
else:
print(f"Orders left: {order}", end=" ")
customers.popleft()
is_complete = False
if is_complete:
print("Orders complete")
|
9de2d7796b52a9ebc8ac6e1e489ece8976ba1314 | Ana-geek/Incapsulyaciya | /lib.py | 1,190 | 4.25 | 4 | """
Разработайте ĸласс Book (Книга) и реализуйте в нем
-ĸонструĸтор объеĸтов,
-набор атрибутов,
-набор аĸсессоров,
-и метод __str__().
Для тестирования данного ĸласса создайте списоĸ из
5 ĸниг различных авторов, выведите на эĸран ĸонсоли
"""
# Создаем клас с инкапсуляцией
class Books:
def __init__(self, name: str, author: str, year: int, price: str, comment: str, rating: str):
self.__name = name
self.__author = author
self.__year = year
self.__price = price + 'грн'
self.__review = comment
self.__rating = rating + ' из 10'
# Делаем метод __str__()
def __str__(self):
return f'{self.__name}. Автор {self.__author}, издана в {self.__year} году, цена {self.__price}. ' \
f'Рецензия: {self.__review} {self.__rating}'
# Аксессоры
def get_name(self) -> str:
return self.__name
def get_review(self) -> str:
return self.__review
|
097ece95985da8fe86e46c4360549073bde20696 | guohaoyuan/algorithms-for-work | /python/进程/消息队列Queue.py | 1,033 | 3.953125 | 4 | """
Queue 为了实现进程间的通信
创建队列,指定长度
.put() 表示插值
.get() 表示取值
"""
import multiprocessing
# 1. 创建队列
queue = multiprocessing.Queue(5)
# 2. 插值
queue.put(1)
queue.put("hello")
queue.put([1, 2, 3])
queue.put((1, 2, 3))
queue.put({"a": 1, "b": 2})
# .put()如果超过长度,会进入阻塞状态, 且程序不会结束, 默认等待队列先取出值,再放入新的值
# queue.put("ghy")
# .put_nowait() 不进入阻塞状态的差值,如果队列已经满了,报错
# queue.put_nowait("ghy")
# 3. 取值
value = queue.get()
print(value)
print("--"*20)
value = queue.get()
print(value)
print("--"*20)
value = queue.get()
print(value)
print("--"*20)
value = queue.get()
print(value)
print("--"*20)
value = queue.get()
print(value)
print("--"*20)
# 当队列已经为空,再次get()进入阻塞状态,等待放入新值到队列中, 然后取出
# get_nowait() 当队列已经空,不再等待,直接报错
# value = queue.get_nowait()
# print(value)
# print("--"*20) |
1f512ae623ce2084392b6e6b4aa8043e418d9bcc | ieee-saocarlos/ia-2019 | /exercicios-membros/Marco/Lista 2 - IA/E3L2.py | 807 | 3.828125 | 4 | # Faça um programa que a partir da lista [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] imprima:
# a) Uma lista com somente números pares.
# b) Uma lista com somente números ímpares.
# c) Uma lista inversa a lista inicial (sem uso de comandos prontos como reverse).
# d) Uma lista com somente números primos.
m=[1,2,3,4,5,6,7,8,9,10]
pares=[]
impares=[]
inversa=[]
primos=[]
#pares e impares
for i in m:
if i%2==0:
pares.append(i)
else:
impares.append(i)
#inversa
n=9
while n!=-1:
inversa.append(m[n])
n=n-1
#primos
for i in m:
mult=0
for count in range (2,i):
if(i%count==0):
mult=1
if mult==0 and i!=1:
primos.append(i)
print("Lista original:",m)
print("As listas pares, impares, inversa e de primos formadas, foram, respectivamemte:\n",pares,impares,inversa,primos)
|
077f39ab0d1d67cd18c4d63424a017dfee64e3ed | bohdan-holodiuk/python_core | /lesson5/hw5/Is_this_my_tail.py | 1,062 | 4.09375 | 4 | """
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails.
To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit!
If the tail is right return true, else return false.
The arguments will always be strings, and normal letters.
For Haskell, body has the type of String and tail has the type of Char. For Go, body has type string and tail has type rune.
"""
def correct_tail(body, tail):
"""
:param body:
:param tail:
:return:
"""
sub = body[len(body) - len(tail)]
if sub == tail:
return True
else:
return False
if __name__ == '__main__':
print(correct_tail("Fox", "x"), True)
print(correct_tail("Rhino", "o"), True)
print(correct_tail("Meerkat", "t"), True)
print(correct_tail("Emu", "t"), False)
print(correct_tail("Badger", "s"), False)
print(correct_tail("Giraffe", "d"), False) |
6483264d9da9caeb4085e3ee7a4ffc5124f3c9a0 | jdtully/coursera-python | /ishot.py | 173 | 3.984375 | 4 | tmp = input("what is the temp?")
temp = int(tmp)
def is_hot(tmp):
if temp > 70:
return(" its hot")
else:
return("its not")
print(is_hot(input))
|
074b877b4e4ba99d6a626b533416a15a63bfa3a0 | MattAllen92/Data-Science-Basics | /Practice and Notes/Code Wars/MTV Cribs.py | 837 | 3.546875 | 4 | def my_crib(n):
width = (n * 2) + 2
roof = []
house = []
for i in range(1, n+1):
roof_length = i*2 + 2
house_length = n*2 + 2
roof_buff = " " * int(buffer(width, roof_length))
house_buff = " " * int(buffer(width, house_length))
if roof == []:
roof.append(roof_buff + " /\\ " + roof_buff)
if i != n:
roof.append(roof_buff + "/" + (" " * (i*2)) + "\\" + roof_buff)
house.append(house_buff + "|" + (" " * (n*2)) + "|" + house_buff)
elif i == n:
roof.append(roof_buff + "/" + ("_" * (i*2)) + "\\" + roof_buff)
house.append(house_buff + "|" + ("_" * (n*2)) + "|" + house_buff)
crib = roof + house
return '\n'.join(crib)
def buffer(w, l):
return (w-l) / 2
print my_crib(1) |
9f37209e3563b2d61f1d85b1d59a633cdf6c27e5 | namanshah01/mini-projects | /Text Encrypt-Decrypt/encrypt.py | 965 | 3.5625 | 4 | import sys
import os
import random
# switching to current running python files directory
os.chdir('\\'.join(__file__.split('/')[:-1]))
# handling possible errors
fname = input('Enter name of text file: ')
if fname.split('.')[-1] != 'txt':
print('Please enter the name of a text file')
sys.exit()
if not os.path.isfile(fname):
print('File does not exist')
sys.exit()
fh = open(fname, 'r')
lines = fh.readlines()
fh.close()
enc_key = random.randint(1, 1000)
final = []
for line in lines:
line = line.strip()
new = []
for letter in line:
new.append(str(ord(letter)*enc_key))
final.append('@#'.join(new))
print(f'The key to decrypt encoded file is: {enc_key}')
desc = input('Do you wish to save the key(y/n)')
if desc == 'y':
fh = open('key_' + fname, 'w')
fh.write(str(enc_key))
print('Key saved in current directory')
# fname = 'encoded_' + fname
fh = open(fname, 'w')
fh.write('&%&%'.join(final))
fh.close() |
ea468d381a28e97b5a5706d60e6419aa50772fee | vitroid/PythonTutorials | /PythonSamples/NodeBox/sympl.py | 1,259 | 4.03125 | 4 | from math import * #sqrt()関数のために必要。
speed(30)
size(400,400)
def circle(x,y,r):
oval(x-r,y-r,r*2,r*2)
def setup():
#力学変数はみんなsetup()で初期化し、
#draw()関数と共通に使えるようにする。
global x,y,vx,vy,Dt,k,m,fx,fy
x = 0.0
y = 0.0
vx = 0.0
vy = 0.0
Dt = 0.1
k = 1.0
m = 1.0
fx = 0.0
fy = 0.0
def draw():
global x,y,vx,vy,Dt,k,m,fx,fy
#速度を成分ごとに積分する
vx = vx + fx / m * Dt * 0.5
vy = vy + fy / m * Dt * 0.5
#位置を成分ごとに積分する
x = x + vx * Dt
y = y + vy * Dt
#相対位置の計算
dx = x - MOUSEX
dy = y - MOUSEY
#距離の計算
r = sqrt(dx**2+dy**2)
#バネの力は距離に比例
f = -k * r
#力ベクトルを求める。
fx = f * dx / r
fy = f * dy / r
#速度を成分ごとに積分する
vx = vx + fx / m * Dt * 0.5
vy = vy + fy / m * Dt * 0.5
#ポテンシャルエネルギー
Epot=k*r**2 / 2.0
#運動エネルギー
Ekin=m*(vx**2+vy**2) / 2.0
#円を描く
circle(x,y,10)
#ポテンシャルと運動エネルギーの和を表示する。
fontsize(14)
text("%s" % (Epot+Ekin),0,10) |
171ec03333c9ab4ad43cdd57d59b2a65f5802364 | keinam53/Zrozumiec_Programowanie | /If_else.py | 3,119 | 4 | 4 | # name = input("Jak masz na imię? ")
# print("Miło mi Cię poznać", name)
# if len(name) >= 7:
# print(f"{name} to całkiem długie imię")
# if len(name) < 7:
# print(f"{name} to krótkie imię")
# age = int(input("Ile masz lat? "))
# if age < 18:
# print("Nie możesz jeszcze głosować")
# if age >= 18:
# print("Możesz już głosować")
# if age >= 35:
# print("Możesz kandydować na prezydenta")
# name = input("Jak masz na imię? ")
# if len(name) >= 7:
# print(name,"To całkiem długie imię")
# else:
# print(name,"To krótkie imię")
#zad1
# ceny = []
# price = float(input("Podaj cenę pierwszego produktu "))
# ceny.append(price)
# price = float(input("Podaj cenę drugiego produktu "))
# ceny.append(price)
# price = float(input("Podaj cenę trzeciego produktu "))
# ceny.append(price)
# if ceny[0]>ceny[1]:
# print("Cena pierwsza jest wyższa od drugiej")
# else:
# print("Cena pierwsza jest niższa od drugiej")
# if ceny[1]>ceny[2]:
# print("Cena druga jest wyższa od trzeciej")
# else:
# print("Cena druga jest niższa od trzeciej")
# if ceny[2]>ceny[0]:
# print("Cena trzecia jest wyższa od drugiej")
# else:
# print("Cena trzecia jest niższa od drugiej")
# shopping_list = input("Podaj listę zakupów rozdzielając przecinkiem ")
# shopping_elements = shopping_list.split(",")
# if len(shopping_elements) >= 4:
# print("Lista zakupów jest długa")
# else:
# print("Lista zakupów jest krótka")
#zad 2
# jedzenie = float(input("Ile wydajesz na jedzenie? "))
# rozrywka = float(input("Ile wydajesz na rozrywkę? "))
# oplaty = float(input("Ile wydajesz na opłaty? "))
# inne = float(input("Ile wydajesz na inne? "))
#
# suma= jedzenie+rozrywka+oplaty+inne
# procent = {
# "jedzenie": jedzenie*100/suma,
# "rozrywka": rozrywka*100/suma,
# "opłaty": oplaty*100/suma,
# "inne": inne*100/suma
# }
# most_important = "jedzenie"
# if procent["rozrywka"] > procent[most_important]:
# most_important = "rozrywka"
# if procent["opłaty"] > procent[most_important]:
# most_important = "opłaty"
# if procent["inne"] > procent[most_important]:
# most_important = "inne"
# print(f"Najwięcej wydajesz na {most_important} czyli {procent[most_important]:.2f}%")
#zad3
# matematyka = int(input("Podaj ocenę z matematyki "))
# fizyka = int(input("Podaj ocenę z fizyki "))
# chemia = int(input("Podaj ocenę z chemii "))
# biologia = int(input("Podaj ocenę z biologii "))
# jedynki = 0
# if matematyka < 2:
# jedynki = jedynki +1
# if fizyka < 2:
# jedynki = jedynki +1
# if chemia < 2:
# jedynki = jedynki +1
# if biologia < 2:
# jedynki = jedynki +1
# if jedynki == 0:
# print("Zdajesz do kolejnej klasy")
# else:
# if jedynki == 1:
# srednia = ((matematyka + fizyka + chemia + biologia) / 4)
# if srednia >= 3.5:
# print("Zdajesz warunkowo")
# else:
# print("Nie zdajesz")
# else:
# print("Nie zdajesz")
#zad4
name = input("Podaj imię ")
if name[-1] == "a":
print("Imię żeńskie")
else:
print("Imię męskie")
|
06821247b1de68ca4532de747f74c7fff087edab | rafaelperazzo/programacao-web | /moodledata/vpl_data/330/usersdata/303/93582/submittedfiles/lista1.py | 431 | 3.671875 | 4 | # -*- coding: utf-8 -*-
valores=(int(input('Digite a quatidade de valores:')))
a= []
contpar=0
contimpar=0
somapar=0
somaimpar=0
for i in range (0,valores,1):
a.append(int(input('DIGITE UM NUMERO:')))
for i in range (0,valores,1):
if a[i]%2==0:
contpar+=1
somapar+=a[i]
else:
contimpar+=1
somaimpar+=a[i]
print(somaimpar)
print(somapar)
print(contimpar)
print(contpar)
print(a)
|
fa5357d2a443d88dbb33e2574ed9f27963149bab | followfellow/GS1 | /aa.py | 1,228 | 3.53125 | 4 | from random import randint
from ctypes import *
import time
import os,sys
user32 = windll.LoadLibrary('user32.dll')
def check():
t = 0
while True:
try:
str_num = input("guess number(0~100)")
num = int(str_num)
break
except:
t += 1
if t > 2:
print("好玩不")
time.sleep(1)
user32.LockWorkStation()
sys.exit(0)
print("瞎啊, try again")
return num
def play():
random_int = randint(0, 100)
while True:
# user_guess = int(input("guess number(0~100)"))
user_guess = check()
if user_guess == random_int:
print(f"congratulations! ({random_int})")
break
if user_guess < random_int:
print("less")
continue
if user_guess > random_int:
print("more")
continue
print("try again?")
user_guess = str(input("y?n"))
if user_guess == "y":
play()
elif user_guess == "n":
print("bye")
else:
print("瞎啊,锁锁")
time.sleep(1)
user32.LockWorkStation()
if __name__ == '__main__':
play()
|
e155eba699cefa0d39f21a9011668a20f2387f3d | Techne3/Intro-Python-II | /examples/rps.py | 1,471 | 4.21875 | 4 | import random
# Create a rock paper scissors game in Python
# Player should be able to type r, p, or s
# Computer will pick r, p or s
# Game will print out the results and keep track of wins, losses and ties
# Type q to quit
# Build a REPL
choices = ["r", "p", "s"]
wins = 0
losses = 0
ties = 0
# Define a function that
def eval_moves(player_move, cpu_move):
'''
Evaluates player move and cpu move, returns results
Player move and cpu move must be r/p/s
'''
winning_moves = {"r": "s", "s": "p", "p": "r"}
if player_move == cpu_move:
print("You tie")
return 0
elif winning_moves[player_move] == cpu_move:
print("You win!")
return 1
else:
print("You came close, try again!")
return -1
# LOOP
while True:
# READ
# PRINT results and score
print(f"\nWins: {wins}, Losses: {losses}, Ties: {ties}")
cmd = input("~~> ")
# EVAL
# Computer picks r/p/s
cpu_move = random.choice(choices)
print(f"CPU picks {cpu_move}")
# Compare player command to cpu command
if cmd in choices:
results = eval_moves(cmd, cpu_move)
if results == 0:
ties += 1
elif results == 1:
wins += 1
else:
losses += 1
elif cmd == "q":
print("Goodbye!")
break
else:
print("I did not understand that command. Please pick r, p, s, or q.")
# Update results based on win/loss/tie
|
9962cceb0a6790113028b80be28940540f6acf37 | alamathe1/Algorithms | /python/mergeSort.py | 937 | 4.34375 | 4 | def mergeMain(left, right, arr):
i = 0
j = 0
k = 0
# when i and k both have elements in them
while (i < len(left) and j < len(right)):
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# when i has elements
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
# when j has elements
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
# print("The arr value is {}".format(arr))
return arr
def mergeSort(arr):
if len(arr) < 2:
return "Array size is less than 2"
mid = int(len(arr) / 2)
left = arr[0:mid]
right = arr[mid:len(arr)]
mergeSort(left)
mergeSort(right)
return mergeMain(left, right, arr)
arr_to_sort = [6, 8, -3, 6, 5, 9, 20, -75]
out = mergeSort(arr_to_sort)
print(out)
|
d4a10914aa8db838b9880e03bca58aa91192ba91 | amath0312/py100 | /day17/sample.py | 3,068 | 3.578125 | 4 |
import time
from functools import wraps
from threading import Lock
# 装饰器
def record_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('in wrapper record_time')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'{func.__name__} => {result} (time={end-start:.8f})')
print('out wrapper record_time')
return result
return wrapper
@record_time
def f1(*args):
return sum(args)
def test_decorate1():
print(f1(1, 2, 3, 4, 5))
# 自定义参数的装饰器
def record(output):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
output('in wrapper record')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
output(f'{func.__name__} => {result} (time={end-start:.8f})')
output('out wrapper record')
return result
return wrapper
return decorate
@record(print)
def f2(*args):
return sum(args)
def test_decorate2():
print(f2(1, 2, 3, 4, 5))
# 装饰器类
class Record(object):
def __init__(self, output):
self._output = output
def __call__(self, func):
print(func)
@wraps(func)
def wrapper(*args, **kwargs):
self._output('in wrapper Record')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
self._output(f'{func.__name__} => {result} (time={end-start:.8f})')
self._output('exit wrapper Record')
return result
return wrapper
@Record(print)
def f3(*args):
return sum(args)
def test_decorate3():
print(f3(1, 2, 3, 4, 5))
# 类装饰器2
class Record2(object):
def __init__(self, func):
self._func = func
def __call__(self, *args, **kwargs):
print('in wrapper Record2', *args)
result = self._func(*args, **kwargs)
print(f'{self._func.__name__}')
print('exit wrapper Record2')
return result
@Record2
def f4(*args):
return sum(args)
def test_decorate4():
print(f4(1, 2, 3, 4, 5))
# 单例模式
def singleton(cls):
locker = Lock()
instances = {}
@wraps(cls)
def wrapper(*args, **kwargs):
if cls not in instances:
with locker:
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class President(object):
def __init__(self, name):
self.name = name
@record(print)
@Record(print)
@record_time
def say(self, word):
print('%s says %s' % (self.name, word))
def test_singleton():
p1 = President('emmm')
p2 = President('ahahahaha')
print(p1.name)
print(p2.name)
print(p1 == p2)
p1.say('im here')
def main():
test_decorate1()
test_decorate2()
test_decorate3()
test_decorate4()
test_singleton()
if __name__ == '__main__':
main()
|
6856abdb3e57c0d3d9adc6a1d078e7c8a25b8a4d | DollaR84/spider | /checker.py | 1,517 | 3.703125 | 4 | """
Module contain functions with check rules for playing cards.
Created on 26.10.2018
@author: Ruslan Dolovanyuk
"""
from constants import Cards
def change_color_suit(card1, card2):
"""Check change suit two cards."""
if card1.suit in Cards.black_suits:
return True if card2.suit in Cards.red_suits else False
else:
return True if card2.suit in Cards.black_suits else False
def equal_suit(card1, card2):
"""Check equal suit two cards."""
return True if card1.suit == card2.suit else False
def change_color_suits(cards):
"""Check change suits cards."""
for index, card in enumerate(cards):
if (len(cards) - 1) > index:
if not change_color_suit(card, cards[index + 1]):
return False
return True
def equal_suits(cards):
"""Check equal suits cards."""
for index, card in enumerate(cards):
if (len(cards) - 1) > index:
if not equal_suit(card, cards[index + 1]):
return False
return True
def rate_down(cards):
"""Check down rate index cards."""
for index, card in enumerate(cards):
if (len(cards) - 1) > index:
if cards[index + 1].rate_index != card.rate_index - 1:
return False
return True
def rate_up(cards):
"""Check up rate index cards."""
for index, card in enumerate(cards):
if (len(cards) - 1) > index:
if cards[index + 1].rate_index != card.rate_index + 1:
return False
return True
|
defaf77399fe5eca330e20c23e7e928dcd6b23d0 | Neural-network-assignement/Problem-solving-curve-fitting | /2) XOR/sanstitre0.py | 4,088 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 16:39:49 2019
@author: Tim
"""
import numpy as np
# This implementation of a standard feed forward network (FFN) is short and efficient,
# using numpy's array multiplications for fast forward and backward passes. The source
# code comes with a little example, where the network learns the XOR problem.
#
# Copyright 2008 - Thomas Rueckstiess
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def derivative(x):
return x*(1-x)
###################################################################################################
def get_data():
global width
data=np.genfromtxt("2in_xor.txt",delimiter="")
shape = np.shape(data)
width = shape[0]
inputs = np.zeros((width,2))
outputs = np.zeros((width,1))
for i in range(width):
inputs[i][0] = data[i][0]
inputs[i][1] = data[i][1]
outputs[i] = data[i][1]
return width,inputs,outputs
###################################################################################################
def feedforward(nIn, nHidden, nOut, inputs, teach):
# learning rate
alpha = 0.1
global hWeights,oWeights,hActivation,oActivation,iOutput,oOutput,hOutput
# initialize weights randomly (+1 for bias)
hWeights = np.random.random((nHidden, nIn+1))
oWeights = np.random.random((nOut, nHidden+1))
#○print(oWeights.shape)
#print(" ")
#print(hWeights.shape)
# activations of neurons (sum of inputs)
hActivation = np.zeros((nHidden, 1), dtype=float)
oActivation = np.zeros((nOut, 1), dtype=float)
# outputs of neurons (after sigmoid function)
iOutput = np.zeros((nIn+1, 1), dtype=float) # +1 for bias
hOutput = np.zeros((nHidden+1, 1), dtype=float) # +1 for bias
oOutput = np.zeros((nOut), dtype=float)
# deltas for hidden and output layer
hDelta = np.zeros((nHidden), dtype=float)
oDelta = np.zeros((nOut), dtype=float)
# set input as output of first layer (bias neuron = 1.0)
iOutput[:-1, 0] = inputs
iOutput[-1:, 0] = 0
# hidden layer
hActivation = np.dot(hWeights, iOutput)
hOutput[:-1, :] = sigmoid(hActivation)
#○print(self.hOutput)
# set bias neuron in hidden layer to 1.0
hOutput[-1:, :] = 0
# output layer
oActivation = np.dot(oWeights, hOutput)
oOutput = sigmoid(oActivation)
error = oOutput - teach
#error_total = 0.5*(oOutput - teach)**2
#print(error_total)
# deltas of output neurons
oDelta = derivative(oActivation) * error
# deltas of hidden neurons
hDelta = derivative(hActivation) * np.dot(oWeights[:,:-1].transpose(), oDelta)
# apply weight changes
hWeights = hWeights - alpha * np.dot(hDelta, iOutput.transpose())
oWeights = oWeights - alpha * np.dot(oDelta, hOutput.transpose())
#################################################################################################
def test(var):
# set input as output of first layer (bias neuron = 1.0)
iOutput[:-1, 0] = var
iOutput[-1:, 0] = 0
#print(var)
# hidden layer
hActivation = np.dot(hWeights, iOutput)
hOutput[:-1, :] = sigmoid(hActivation)
#print(hActivation)
#○print(self.hOutput)
# set bias neuron in hidden layer to 1.0
hOutput[-1:, :] = 0
# output layer
oActivation = np.dot(oWeights, hOutput)
oOutput = sigmoid(oActivation)
print(oOutput[0][0])
if __name__ == '__main__':
'''
XOR test example for usage of ffn
'''
width,inputs,output = get_data()
# define training set
# create network
for a in range(2000):
for i in range(width):
feedforward(2,9,1,inputs[i],output[i])
test([0,0])
|
625fb4f68e015e8658402f51a40afa6376aa8686 | elruizz/AdvPy-eRuiz | /Assignmnents/Project_1/OneChickenPerPerson/onechicken.py | 921 | 3.828125 | 4 | #! /usr/bin/env python3
import sys
def answer(a, b):
ans = ''
if a > b:
x = a - b
if x == 1:
ans = 'Dr. Chaz needs 1 more piece of chicken!'
return ans
else:
ans = 'Dr. Chaz needs '+ str(x) + ' more pieces of chicken!'
return ans
else:
x = b - a
if x == 1:
ans = 'Dr. Chaz will have 1 piece of chicken left over!'
return ans
else:
ans = 'Dr. Chaz will have '+ str(x) + ' pieces of chicken left over!'
return ans
def solve():
a, b = map(int, input().split())
print(answer(a, b))
def test():
assert answer(20, 100) == 'Dr. Chaz will have 80 pieces of chicken left over!'
assert answer(2, 3) == 'Dr. Chaz will have 1 piece of chicken left over!'
assert answer(10, 1) == 'Dr. Chaz needs 9 more pieces of chicken!'
print('All Cases Passed')
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == 'test':
test()
else:
solve()
|
3666997fa6a38d2fcbacd3a6b2db9c4485f77d24 | carlos2020Lp/progra-utfsm | /certamenes/2012-1-certamen-1/edad/solucion.py | 550 | 3.796875 | 4 | ano = int(raw_input('Ano: '))
mes = int(raw_input('Mes: '))
dia = int(raw_input('Dia: '))
if mes < 5 or (mes == 5 and dia < 10):
edad_anos = 2012 - ano
else:
edad_anos = 2011 - ano
if dia <= 10:
edad_dias = 10 - dia
if mes <= 5:
edad_meses = 5 - mes
else:
edad_meses = (12 + 5) - mes
else:
edad_dias = (30 + 10) - dia
if mes < 5:
edad_meses = 4 - mes
else:
edad_meses = (12 + 4) - mes
print 'Edad:',
print edad_anos, 'anos,',
print edad_meses, 'meses,',
print edad_dias, 'dias.'
|
d793d8585b0375efa6a2326914b24b2851c5ac37 | DL2021Spring/CourseProject | /data_files/814 Binary Tree Pruning.py | 621 | 3.5625 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from typing import Tuple
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
root, _ = self.prune(root)
return root
def prune(self, node) -> Tuple[TreeNode, bool]:
if not node:
return None, False
node.left, contain_left = self.prune(node.left)
node.right, contain_right = self.prune(node.right)
if not contain_left and not contain_right and node.val == 0:
return None, False
return node, True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.