blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a048a2ad1041929246faca56575e18dc838d75d5 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/bhrjam001/question3.py | 608 | 4.09375 | 4 | # James Behr
# 2014-04-23
# Assignment 6 Question 3
parties = {} # dictionary to hold names
print('Independent Electoral Commission')
print('--------------------------------')
print('Enter the names of parties (terminated by DONE):')
# Loop until sentinel is reached
while True:
s = input()
if s == 'DONE':
break
if s in parties.keys():
parties[s] += 1
else:
parties[s] = 1
print() # Blank line
print('Vote counts:')
# Output by looping through sorted keys
for key in sorted(parties):
print('{:10} - {}'.format(key, parties[key]))
|
260de9addf92fc27a7b97be2a782b6007d21f692 | cudjoeab/python_fundamentals3 | /collections-iterations-1.py | 3,406 | 3.734375 | 4 | #LISTS
fav_colours = ['black', 'turqouise', 'yellow']
family_ages = [25, 46, 34, 40, 41, 27]
coin_flip = ['tails', 'heads', 'tails', 'tails','tails']
fav_artists = ['Janelle Monae', 'Tush', 'Lizzo']
#DICTIONARIES
dictionary = {
'burgeon': 'to sprout, bloom, or flourish',
'lionize': 'to treat with great importance',
'flair': 'a natural talent or unique style'
}
fav_movies = {
'The Lion King': 1994,
'Akira': 1988,
'The Shining': 1980,
'Us': 2019,
'Paprika': 2006
}
cities = {
'Toronto': 2930000,
'Orleans': 116668,
'Kingston': 666041
}
siblings = {
'Andrew': 46,
'Shawn': 41,
'Jason': 40,
'Dustin': 34,
'Ekua': 25
}
#Exercise 1
print(coin_flip)
print(fav_colours[0])
print(sorted(family_ages))
family_ages.append(0)
print(family_ages)
print(fav_movies['Akira'])
#Exercise 2
print(fav_colours[-1])
cities.update({'Fort Erie': 30710 })
print(cities)
coin_flip.reverse()
print(coin_flip)
print(cities['Toronto'])
for artist in fav_artists:
print("I think {} is great.".format(artist))
#Exercise 3
#1
print(fav_artists[0:2])
#2
for movie, year in fav_movies.items():
print("{} came out in {}.".format(movie, year))
#3
family_ages.sort()
family_ages.reverse()
print(family_ages)
#4
fav_movies.update({'Beauty and the Beast': '1991 & 2017'})
print(fav_movies)
#Exercise 4
#1
for member in family_ages:
if member <=30:
print(member)
#2
family_ages.sort()
print(family_ages[-1])
#3
print(coin_flip.count('heads'))
#4
fav_artists.pop(2)
print(fav_artists)
#5
print(cities['Toronto'])
cities['Toronto'] = 2930001
print(cities['Toronto'])
#Exercise 5
#1
total = 0
for population in cities:
total
#2
for sibling, age in siblings.items():
if age <= 30:
age = 'young'
else:
age = 'old'
print("{} is {}.".format(sibling,age))
#3
print(fav_colours[1:2+1])
#4 increase everyones' age
for index, age in enumerate(family_ages):
family_ages[index] = age + 1
print(family_ages)
#5 adding two new colours
print(fav_colours)
fav_colours.append('pink')
fav_colours.append('lavender')
print(fav_colours)
#Exercise 6
#1
movie_archive = {
1999: ['The Matrix', 'Star Wars: Episode 1', 'The Mummy'],
2009: ['Avatar', 'Star Trek', 'District 9'],
2019: ['How to Train Your Dragon 3', 'Toy Story 4', 'Star Wars: Episode 9']
}
#2
phone_buttons = [
[1,2,3],
[4,5,6],
[7,8,9],
['*',0, '#']
]
#3
# countries = {
# 'Canada': ['N_America', False],
# 'Ghana': ['Africa', False],
# 'Australia': ['Australia', True]
# }
#Exercise 7
#1
message = 'I will not skateboard in the halls.'
print (message * 20)
#2 list with message
detention = [message * 20]
print(detention)
#3
numbers_list= []
for number in range(1,51):
numbers_list.append(number)
print(numbers_list)
#4
total = 0
for number in numbers_list:
total = total + number
print(total)
#5
new_numbers_list= []
for number in range(1,51):
for triple_number in range(1,4):
new_numbers_list.append(number)
print(new_numbers_list)
#6
countries = {
'Canada': ['N_America', False],
'Ghana': ['Africa', False],
'Australia': ['Australia', True]
}
country_islands = []
for country in countries:
print(countries[country][1])
if countries[country][1] == True:
country_islands.append(country)
print(country_islands) |
33ed90643046a0a7aa2cc4f6b6f542bf4d682a86 | z-waterking/ClassicAlgorighthms | /LeetCode/1110.删点成林.py | 967 | 3.515625 | 4 | #
# @lc app=LeetCode.cn id=1110 lang=python3
#
# [1110] 删点成林
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
self.res = []
self.to_delete = to_delete
root = self.helper(root)
if root:
self.res.append(root)
return self.res
def helper(self, root):
if not root:
return root
root.left = self.helper(root.left)
root.right = self.helper(root.right)
if root.val in self.to_delete:
if root.left:
self.res.append(root.left)
if root.right:
self.res.append(root.right)
root = None
return root
# @lc code=end
|
038ae8b6217b720f546edf2af295ab2be753acad | ParulProgrammingHub/assignment-1-DPexotic | /program 8.py | 125 | 3.671875 | 4 | print("enter parameters:")
b = float(input("base:"))
h = float(input("height:"))
area = 0.5 * b * h
print("area:",area)
|
cd518ee3aff65ee9fd14c88451e1fb55a4a2fc1d | MaximZolotukhin/erik_metiz | /chapter_8/exercise_8.6.py | 716 | 4.125 | 4 | """
Названия городов:
напишите функцию city_country(), которая получает название города и страну.
Функция должна возвращать строку в формате "Santiago, Chile". Вызовите
свою функцию по карйне мере для трех пар "город - страна" и выведите
возвращенное значение.
"""
def city_country(city, country):
return f"{city} - {country}"
print(city_country("Курск", "Россия"))
cityContry = city_country("Токио", "Япония")
print(cityContry)
cityContry = city_country("Париж", "Франция")
print(cityContry)
|
0c20855cfbdf23b6ad4e4b3978c3443401fcc31f | chulsea/TIL | /datascience/pandas_practice/selection_drop.py | 882 | 4.03125 | 4 | import pandas as pd, numpy as np
# pandas data frame selection
raw_data = {
'first_name': ['gyeongcheol', 'wooje', 'hohyun'],
'last_name': ['park', 'noh', 'kim'],
'age': [27, 27, 28]
}
df = pd.DataFrame(raw_data)
print(df)
# 한개의 column 선택
print(df['first_name'])
# print(df['first']) 만약 없는 값인 경우 오류
# 한개 이상의 column 선택
print(df[['first_name', 'last_name']])
# column의 이름 없이 index number를 사용하는 경우 row를 기준으로 표시한다.
print(df[:2])
# column이름과 함께 row index를 사용하면 해당 column만 indexing할 수 있다.
print(df['last_name'][:2])
# 1개 이상의 index를 가져올때 list에 가져오고자 하는 index를 담아서 가져올 수 있다. (Series)
print(df['first_name'][[0, 2]])
# numpy의 boolean index도 활용가능하다.
print(df['age'][df['age'] == 27])
|
dd544253f222a8362c85a35ee750ce84aabcb767 | Nehagarde/etl | /control_flows_percentage.py | 350 | 3.75 | 4 | if __name__ == '__main__':
percentage = int(input("Enter percentage: "))
if 100 >= percentage >= 80:
print("Distinction")
elif 79 >= percentage >= 70:
print("First class")
elif 69 >= percentage >= 60:
print("Second class")
elif 59 >= percentage >= 50:
print("Pass")
else:
print("Fail") |
143f8028856e5dfa0e3f2e41ef1d1c77039fa6ea | Silverchiffa/python | /sockscounter.py | 828 | 3.78125 | 4 | ar.sort()
socksCounter = 0
while len(ar) > 1:
if ar[0] == ar[1]:
socksCounter += 1
ar.pop(0)
ar.pop(0)
else:
ar.pop(0)
return socksCounter
def countingValleys(steps, path):
# Write your code here
# O(n + (n-1)) --> O(n)
# O(n + n)
currentLevel = 0
stepsList = []
valleysCount = 0
for i in range(steps):
currentLevel += 1 if path[i] == "U" else -1
stepsList.append(currentLevel)
for i in range(1, len(stepsList)):
if stepsList[i - 1] == -1 and stepsList[i] == 0:
valleysCount += 1
return valleysCount |
3089839bedb9a595d186dae7d438976071e4a223 | tmajest/project-euler | /python/p11/p11.py | 1,320 | 3.609375 | 4 | from operator import mul
import sys
# In the 2020 grid below, four numbers along a diagonal line have
# been marked in red.
#
# (see input file in this directory)
#
# The product of these numbers is 26 63 78 14 = 1788696.
#
# What is the greatest product of four adjacent numbers in any
# direction (up, down, left, right, or diagonally) in the 2020 grid?
#
grid = [map(int, line.split()) for line in sys.stdin]
maxProduct = 0
# Check horizontal products
for i in range(len(grid)):
for j in range(len(grid) - 3):
horizontalProduct = reduce(mul, grid[i][j:j+4], 1)
maxProduct = max(horizontalProduct, maxProduct)
# Check vertical products
for i in range(len(grid)):
for j in range(len(grid) - 3):
verticalProduct = reduce(mul, [x[i] for x in grid[j:j+4]], 1)
maxProduct = max(verticalProduct, maxProduct)
# Check diagonal (\) products
for i in range(len(grid) - 3):
for j in range(len(grid) - 3):
diagProduct = reduce(mul, [grid[i+x][j+x] for x in range(4)], 1)
maxProduct = max(diagProduct, maxProduct)
# Check other diagonal (/) products
for i in range(len(grid) - 3):
for j in range(len(grid) - 3):
diagProduct = reduce(mul, [grid[i+3-x][j+x] for x in range(4)], 1)
maxProduct = max(diagProduct, maxProduct)
print maxProduct
|
1976ba5518c9f20202b6fe8d5ba135b0f9e41b95 | LaurelKuang/2017A2CS | /Ch23/stack.py | 1,172 | 3.703125 | 4 | # S3C2 Laurel Kuang
NullPointer=-1
class StackNode:
def __init__(self):
self.value=""
self.nextP=NullPointer
class Stack:
def __init__(self,length):
self.tp=NullPointer
self.fp=0
self.records=[]
for i in range(length):
NewNode=StackNode()
NewNode.nextpointer=i+1
self.records.append(NewNode)
NewNode.nextpointer=-1
def push(self,Item):
if self.fp!=NullPointer:
self.newnullpointer=self.fp
self.records[self.newnullpointer].value=Item
self.fp=self.records[self.fp].nextpointer
self.records[self.newnullpointer].nextpointer=self.tp
self.tp=self.newnullpointer
else:
print("No space available.")
def pop(self):
if self.tp==NullPointer:
print("No data.")
return("")
else:
value=self.records[self.tp].value
self.cNodeP=self.tp
self.tp=self.records[self.tp].nextpointer
self.records[self.cNodeP].nextpointer=self.fp
self.fp=self.cNodeP
return(value)
|
d4cdf6b52fe8ccfbe3eacc3df4e4640043677e80 | connectlym/graph-search-dijkstra | /main.py | 3,724 | 3.640625 | 4 | # ***********************************************************************************************************
# Graph Search - Shortest Path - Single Source Shortest Path
# (Reference: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_A)
# ***********************************************************************************************************
# Solution: This python program is a solution,
# written by YM Li, in Fall 2018.
# ***********************************************************************************************************
import heapq, sys
class PriorityQueue:
"""
Applies the priority queue data structure.
Items inserted is in the order of values related to them.
"""
def __init__(self):
self.heap = []
def push(self, item, priority):
entry = (priority, item)
heapq.heappush(self.heap, entry)
def pop(self):
priority, item = heapq.heappop(self.heap)
return (item, priority)
def isEmpty(self):
return len(self.heap) == 0
class Graph:
"""
Creates a graph object.
"""
def __init__(self, vertex_num, edge_num, root):
"""
Initializes the graph.
:param (int) vertex_num - number of vertices
:param (int) edge_num - number of edges
:param (int) root - the number representing root node
"""
self.vertex_num = vertex_num
self.root = root
# creates an array of tuples s.t. at vertices[vertex], all [another vertex attached, edge cost] are include.
self.vertices = []
# creates an array of ints including the shortest path
self.path = []
for i in range(0, vertex_num):
self.vertices.append([])
#print(self.vertices)
self.path.append(100000) # inf = 100000 for this specific question
#print(self.path)
def addEdge(self, s, t, d):
"""
Adds edge reading from user input into the array vertices.
:param (int) s - source vertices of i-th edge
:param (int) t - target vertices of i-th edge
:param (int) d - the cost of the i-th edge
"""
self.vertices[s].append((t, d))
def dijkstra(self):
"""
Applies and modifies Dijkstra algorithm to find the shortest path.
"""
# initializes current queue and path
q = PriorityQueue()
q.push(self.root, 0)
self.path[self.root] = 0
# updates queues and path
while not q.isEmpty():
u, u_cost = q.pop()
#print(u)
#print(u_cost)
for info in self.vertices[u]:
t = info[0] # target vertex attached to vertex u
d = info[1] # cost of edge of (u,t)
if self.path[t] > u_cost + d:
self.path[t] = u_cost + d
q.push(t, self.path[t])
if __name__ == "__main__":
# gets the 1st line of user input and initializes the graph
print("Enter your inputs here:")
input_graph = sys.stdin.readline()
input_graph = input_graph.split(" ")
V = int(input_graph[0])
E = int(input_graph[1])
r = int(input_graph[2])
problem = Graph(V, E, r)
# get lines of input and initializes the edges of graph
for i in range(0, E):
input_edges = sys.stdin.readline()
input_edges = input_edges.split(" ")
s = int(input_edges[0])
t = int(input_edges[1])
d = int(input_edges[2])
problem.addEdge(s, t, d)
# solves the problem
problem.dijkstra()
# print out the result
for v in problem.path:
if v == 100000:
print("INF")
else:
print(v)
|
b6830dd085a7b3136c24a04eda602fbd1cd41d9f | zyhsna/Leetcode_practice | /problems/island-perimeter.py | 659 | 3.578125 | 4 | # _*_ coding:UTF-8 _*_
# 开发人员:zyh
# 开发时间:2020/9/4 10:04
# 文件名:island-perimeter.py
# 开发工具:PyCharm
class Solution:
def islandPerimeter(self, grid: list[list[int]]) -> int:
c = 0
m, n = len(grid), len(grid[0])
for i in range(m):
grid[i].insert(n, 0)
grid[i].insert(0, 0)
grid.insert(m, [0] * (n + 2))
grid.insert(0, [0] * (n + 2))
for i in range(1, m + 1):
for j in range(1, n + 1):
if grid[i][j] == 1:
c += [grid[i - 1][j], grid[i + 1][j], grid[i][j - 1], grid[i][j + 1]].count(0)
return c
|
40c6af945dee55671cda3203d343d7e4d621288a | movjc/pythontest | /13.py | 897 | 3.59375 | 4 | #coding=utf-8
"""
date:2017-08-17
@author: ray
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
"""
"""
for n in range(100,1000):
i = n/100 #百位上的数
j = n/10%10 #十位上的数
k = n%10 #各位上的数
if n == i**3 + j**3 + k**3:
print n
for x in range(1,10):
for y in range(0,10):
for z in range(0,10):
s1 = x*100 + y*10 +z
s2 = pow(x,3) + pow(y,3) + pow(z,3)
if s1 == s2:
print s1
"""
for i in range(100,1000):
s = str(i)
if int(s[0])**3 + int(s[1])**3 + int(s[2])**3 == i:
print i |
56fe3dc9082a9b3c41a714316678475d7c334407 | lcxidian/soga | /leetcode/90.py | 76,333 | 4.03125 | 4 |
LeetCode题解整理版(二)
Leetcode开始支持Python了,本篇题解中的题目都是用Python写的。(更新中..)
已更新完,本篇题解中共96题,按照Leetcode上的顺序从上向下。可以用CTRL+F查找,如果没有的话就是在前一篇题解中了。
因为时间原因,题解写的并不是很详细,大多数题目都只给出了关键思路。
Reverse Words in a String
将abc def形式的字符串翻转成def abc,并且去掉多余的空格。
先将这个字符串翻转过来,再逐次翻转每个词。(当然不是效率最高的办法,只是为了好写。)
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
return ' '.join([word[::-1] for word in s[::-1].split()])
Recover Binary Search Tree
一棵二叉搜索树中两个节点错误,修正这棵树。
正确二叉树中序遍历应该是递增,而交换了两个节点后会导致有一处或者两处某节点值小于前一个节点,记录,最后交换即可。
class Solution:
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
self.pre = None
self.n1 = self.n2 = None
self.dfs(root)
self.n1.val, self.n2.val = self.n2.val, self.n1.val
return root
def dfs(self, root):
if not root:
return
self.dfs(root.left)
if self.pre and root.val < self.pre.val:
if not self.n1:
self.n1, self.n2 = self.pre, root
else:
self.n2 = root
self.pre = root
self.dfs(root.right)
Validate Binary Search Tree
判断是否是BST
中序遍历,比较当前点的值是否大于前一点的值即可
class Solution:
# @param root, a tree node
# @return a boolean
val = None
def isValidBST(self, root):
if root is None:
return True
res = self.isValidBST(root.left)
if self.val is None:
self.val = root.val
else:
res = res and (root.val > self.val)
self.val = root.val
res = res and self.isValidBST(root.right)
return res
Interleaving String
判断C串是否有A串和B串组成(就是说C中提取出A之后剩下B)
简单DP,dp[i][j]表示A[1..i]和B[1..j]是否可以组成C[1..i+j]
class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
if len(s3) != len(s1) + len(s2):
return False
dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)]
for i in range(len(s1) + 1):
for j in range(len(s2) + 1):
if i == 0 and j == 0:
dp[i][j] = True
elif i > 0 and dp[i-1][j] and s3[i+j-1] == s1[i-1]:
dp[i][j] = True
elif j > 0 and dp[i][j-1] and s3[i+j-1] == s2[j-1]:
dp[i][j] = True
else:
dp[i][j] = False
return dp[len(s1)][len(s2)]
Unique Binary Search Trees II
给出N个节点二叉搜索树的所有形态。
要生成所有形态,也只有暴力枚举了。
class Solution:
# @return a list of tree node
treelist = None
def generateTrees(self, n):
return self.dfs(0, n)
def dfs(self, l, r):
ans = []
if l == r:
ans.append(None)
return ans
for i in range(l, r):
lb, rb = self.dfs(l, i), self.dfs(i + 1, r)
for lc in lb:
for rc in rb:
node = TreeNode(i + 1)
node.left = lc
node.right = rc
ans.append(node)
return ans
Reverse Linked List II
翻转链表的中间一段,要求常数空间,只遍历一遍
记录下第m个节点和它的前一个节点,中间直接翻,到第n个节点再进行一些处理。思想简单但很容易写错。
class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverseBetween(self, head, m, n):
prem, pre, next, now, nowm = None, None, None, head, None;
ind = 1;
while now is not None:
next = now.next
if ind >= m and ind <= n:
now.next = pre
if ind == m:
prem, nowm = pre, now
if ind == n:
nowm.next = next
if prem is None:
head = now
else:
prem.next = now
pre, now, ind = now, next, ind + 1
return head
Subsets II
枚举一个集合中的不重复子集
既然枚举子集,想必题目中的集合不会有多少数,可以用二进制数来表示某个数选了没有,因为要保证不重复,所以对集合排序后,连续相同的数不能选相同数目,我们可以规定对于相同数,如果前面一个没选,后面一个就不能选来保证这一点。
class Solution:
# @param num, a list of integer
# @return a list of lists of integer
def subsetsWithDup(self, S):
S.sort()
bset = []
for x in range(2**len(S)):
for i in range(1, len(S)):
if (S[i] == S[i-1] and (x>>(i-1)&0x03 == 0x01)): break
else:
bset.append(x)
return [[S[x] for x in range(len(S)) if i>>x&1] for i in bset]
Decode Ways
1->A..26->Z一一对应,给一个数字串,问有多少种解码方式。
动态规划,S[i]表示到i位有多少种组合方式,其值决定与S[i-1]与S[i-2]。
S[i] = if(S[i] ok) S[i-1] + if (S[i-1..i] ok) S[i-2]
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if len(s) == 0:
return 0
dp = [1] + [0] * len(s)
ok = lambda x: x[0] != '0' and int(x) >= 1 and int(x) <= 26;
for i in range(1, len(s) + 1):
dp[i] = dp[i-1] if ok(s[i-1:i]) else 0
if i >= 2:
dp[i]+= dp[i-2] if ok(s[i-2:i]) else 0
return dp[len(s)]
GrayCode
排列0~2^N-1个二进制串,相邻串之间只有一位不同。
可以这样考虑,假设N-1的问题已经解决,已经有2^(N-1)个串符合条件,现在解决N的问题,那么还要再生成2^(N-1)个串,很显然,这后2^(N-1)个的最高位都为1,所以只要考虑其余N-1位即可。第2^(N-1)+1个串只能在第2^(N-1)个串的最高位加个1,然后我们又知道第2^(N-1)-1和第2^(N-1)个只差一位,所以第2^(N-1)+2个串只要在第2^(N-1)-1个串的第N位加个1,以此类推。
下面给个例子,很容易看懂
000 0
001 1
011 3
010 2
----后两位以此为对称轴
110 6
111 7
101 5
100 4
class Solution:
# @return a list of integers
def grayCode(self, n):
self.res = [0]
for i in [2**x for x in range(0, n)]:
self.res.append(self.res[-1] + i)
self.res.extend([i + v for v in self.res[-3:None:-1]])
return self.res;
Merge Sorted Array
合并A、B两个有序数组到A中。
从前向后放不行,那就从后向前放吧
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
for i in range(m + n - 1, -1, -1):
if m == 0 or (n > 0 and B[n-1] > A[m-1]):
A[i] = B[n-1]
n -= 1
else:
A[i] = A[m-1]
m -= 1
return A
Scramble String
http://oj.leetcode.com/problems/scramble-string/
动态规划,用dp[lp][rp][len]表示s1[lp:lp+len]和s2[rp:lp+len]是Scramble String。
class Solution:
# @return a boolean
def isScramble(self, s1, s2):
if len(s1) != len(s2):
return False
if len(s1) == 0:
return True
self.s1, self.s2 = s1, s2
lens = len(s1)
self.dp = [[[-1] * lens for i in range(lens)] * lens for i in range(lens)]
return self.dfs(0, 0, len(s1))
def dfs(self, lp, rp, len):
if self.dp[lp][rp][len - 1] >= 0:
return True if self.dp[lp][rp][len - 1] == 1 else False
if len == 1:
return self.s1[lp] == self.s2[rp]
for i in range(1, len):
if self.dfs(lp, rp, i) and self.dfs(lp + i, rp + i, len - i) \
or self.dfs(lp, rp + i, len - i) and self.dfs(lp + len - i, rp, i):
self.dp[lp][rp][len - 1] = 1
return True
self.dp[lp][rp][len - 1] = 0
return False
Partition List
给定一个值,将链表中按该值分为前后两部分,要求保持原序。
拖两条链,一条大值链一条小值链,最后连起来即可。
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
if head is None:
return head
sHead, bHead = ListNode(0), ListNode(0)
sTail, bTail = sHead, bHead
while head is not None:
if head.val < x:
sTail.next = head
sTail = sTail.next
else:
bTail.next = head
bTail = bTail.next
head = head.next
bTail.next = None
sTail.next = bHead.next
return sHead.next
Maximal Rectangle
给出0、1矩阵,找出最大的由1构成的矩阵。
就是对每一行依次用单调栈求以这行为底的最大矩形,最后取最大的就可以了,单调栈的解释见下一题。
class Solution:
# @param matrix, a list of lists of 1 length string
# @return an integer
def maximalRectangle(self, matrix):
if len(matrix) == 0:
return 0
ans = 0;
for i in range(len(matrix)):
stk = []
for j in range(len(matrix[0]) + 1):
if j < len(matrix[0]): matrix[i][j] = int(matrix[i][j])
if i > 0 and j < len(matrix[0]) and matrix[i][j]:
matrix[i][j] += matrix[i-1][j]
while len(stk) and (j == len(matrix[0]) or matrix[i][stk[-1]] >= matrix[i][j]):
top = stk.pop()
if len(stk) == 0:
ans = max(ans, matrix[i][top]*j)
else:
ans = max(ans, matrix[i][top]*(j-stk[-1]-1))
stk.append(j)
return ans
Largest Rectangle in Histogram
N块宽度相同,高度不同的木板连在一起,求最大矩形。
首先,我们知道暴力的方法,就是枚举每个木板作为它所在矩形最大高度,然后看最左和最右分别能延伸多长,复杂度O(N^2)。
基于暴力方法可以用单调栈优化,从左向右扫,同时入栈,入栈前将栈顶比它短的木板全部出栈,每个木板在出栈时计算以它为所在矩形最大高度的矩形的最大面积。每个木板入栈出栈各一次,复杂度O(n)。
其实不难理解,每个木板出栈时它(栈的)下面那块木板就是左边第一块比它短的,而使它出栈的那块木板则是右边第一块比它短的,也就很快找到了上面暴力方法中最左和最右能延伸的距离。
代码要注意细节处理。
class Solution:
# @param height, a list of integer
# @return an integer
def largestRectangleArea(self, height):
ans, lenh, stk = 0, len(height), []
for i in range(lenh + 1):
while len(stk) and (i == lenh or height[stk[-1]] >= height[i]):
top = stk.pop()
if len(stk) == 0:
ans = max(ans, height[top] * i)
else:
ans = max(ans, height[top] * (i - stk[-1] - 1))
stk.append(i)
return ans
Remove Duplicates from Sorted List II
删除有序链表中的重复元素。
注意处理细节,首先,当一个元素的后两个连续节点值相同时删除下一个,其次,当后两个连续节点不同但上一次是删除操作时也要删除下一个,然后更改标记不继续删后面的。
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head:
return head
nHead, flag = ListNode(0), False
nHead.next, head = head, nHead
while head:
if (head.next and head.next.next and head.next.next.val == head.next.val):
head.next = head.next.next
flag = True
elif flag == True and head.next:
head.next = head.next.next
flag = False
else:
head = head.next
return nHead.next
Remove Duplicates from Sorted List
有序链表中若有多个元素重复,只保持一个。
比上题简单,标记都省了。
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head:
return head
nHead = ListNode(0)
nHead.next, head = head, nHead
while head:
if (head.next and head.next.next and head.next.next.val == head.next.val):
head.next = head.next.next
else:
head = head.next
return nHead.next
Search in Rotated Sorted Array II
一个有序数组循环右移若干后位之后,在之中搜索一个值。
在普通二分上做修改,需要注意的是A[l]=A[m]=A[n]时,无法知道往那边搜索,最坏复杂度可能有O(N)。
class Solution:
# @param A a list of integers
# @param target an integer
# @return a boolean
def search(self, A, target):
l, h = 0, len(A) - 1
while (l <= h):
m = l + ((h - l) >> 1)
if A[m] == target:
return True
if A[m] == A[l] and A[m] == A[h]:
l, h = l + 1, h - 1
elif (A[m] > A[l] and target < A[m] and target >= A[l]) or (A[m] < A[l] and not (target <= A[h] and target > A[m])):
h = m - 1
else:
l = m + 1
return False
Remove Duplicates from Sorted Array II
有序数组中的若有多个元素重复,只保持两个。
没做I的时候我用的是POP元素。。和I一样,往数组前段放就可以了,保证已放的重复元素不超过两个
class Solution:
# @param A a list of integers
# @return an integer
def removeDuplicates(self, A):
sz = 0
for i in range(len(A)):
if sz < 2 or A[sz - 2] != A[i]:
A[sz] = A[i]
sz = sz + 1
return sz
Word Search
在一个矩阵中找一个单词。
暴力DFS。(我能说我一个暴力DFS写了半天么(┬_┬))
class Solution:
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
self.h = len(board)
self.w = len(board[0])
for i in range(self.h):
for j in range(self.w):
if board[i][j] == word[0]:
t, board[i][j] = board[i][j], ' '
if self.dfs(board, word, i, j, 1):
return True
board[i][j] = t
return False
def dfs(self, board, word, x, y, p):
dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
if (p == len(word)):
return True
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx and nx < self.h and 0 <= ny and ny < self.w and board[nx][ny] == word[p]:
t, board[nx][ny] = board[nx][ny], ' '
if self.dfs(board, word, nx, ny, p + 1):
return True
board[nx][ny] = t
return False
Subsets
枚举所有子集。
二进制表示选了哪些数。
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
S.sort()
return [[S[x] for x in range(len(S)) if i>>x&1] for i in range(2**len(S))]
Combinations
枚举C(n, k)
暴力DFS枚举。
class Solution:
# @return a list of lists of integers
def combine(self, n, k):
self.res = []
tmp = []
self.dfs(n, k, 1, 0, tmp)
return self.res
def dfs(self, n, k, m, p, tmp):
if k == p:
self.res.append(tmp[:])
return
for i in range(m, n+1):
tmp.append(i)
self.dfs(n, k, i+1, p+1, tmp)
tmp.pop()
Minimum Window Substring
找出串S中最短的串,包含了串T中出现的每个字符。
思路是左右各一个指针,分别是pl、pr,pr先移动直到包含T中所有字符,然后pl尽量右移直到S[pl:pr]刚刚不能保证包含所有T中字符,那么S[pl-1:pr]就是一个可行的最短串。之后重复以上过程直到串尾,记下中间找到的最短段即可。
class Solution:
# @return a string
def minWindow(self, S, T):
d, dt = {}, dict.fromkeys(T, 0)
for c in T: d[c] = d.get(c, 0) + 1
pi, pj, cont = 0, 0, 0
ans = ""
while pj < len(S):
if S[pj] in dt:
if dt[S[pj]] < d[S[pj]]:
cont += 1
dt[S[pj]] += 1;
if cont == len(T):
while pi < pj:
if S[pi] in dt:
if dt[S[pi]] == d[S[pi]]:
break;
dt[S[pi]] -= 1;
pi+= 1
if ans == '' or pj - pi < len(ans):
ans = S[pi:pj+1]
dt[S[pi]] -= 1
pi += 1
cont -= 1
pj += 1
return ans
Sort Colors
给一个只有0,1,2的数组排序,要求only one pass。
貌似是USACO上的题,已经忘记当时怎么做的了。
一共三个指针,头指针、尾指针、”壹”指针(一开始和头指针都在开始)。从前向后,如果当前位置是1,头指针后移,而壹指针停在原地,如果是2,和尾指针指向的数交换,并且尾指针前移,如果是0,则交换0和壹指针上的数,并且头指针和壹指针都后移。
这里头尾指针都很容易理解,关键是对壹指针的理解,它总是在一串连续的一的开头,并且这串1的结尾就是头指针!每次头指针遇到一个0,都会将0交换到壹指针所在的位置,再将壹指针后移到下一个1。
class Solution:
# @param A a list of integers
# @return nothing, sort in place
def sortColors(self, A):
s, t, e = 0, 0, len(A) - 1
while s <= e:
if A[s] == 0:
if s != t:
A[s], A[t] = A[t], A[s]
s, t = s + 1, t + 1
elif A[s] == 1:
s = s + 1
elif A[s] == 2:
if s != e:
A[s], A[e] = A[e], A[s]
e = e - 1
return A
Search a 2D Matrix
把N*M个有序数按顺序排成矩阵,然后判断一个数是否在矩阵内。
变成矩阵难道就不是二分查找了?
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
l, h = 0, len(matrix) * len(matrix[0]) - 1
while (l <= h):
m = l + ((h-l) >> 2)
v = matrix[m/len(matrix[0])][m%len(matrix[0])]
if v < target:
l = m + 1
elif v > target:
h = m - 1
else:
return True
return False
Set Matrix Zeroes
给一个矩阵,若某格为0,该格所在行及所在列全部改为0,要求常数空间复杂度。
显然先扫一遍Mark的话空间复杂度是O(M+N),这个Mark是必不可少的,不能用额外空间的话,就只能用原数组的某一行及某一列来记录了。最后再扫一遍数组,根据标记行及标记列的值来判断某格是否要置0。需要注意的是,该行及该列其它的格子要最后再置0。
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
if len(matrix) == 0:
return
lenn, lenm = len(matrix), len(matrix[0])
x, y = None, None
for i in range(lenn):
for j in range(lenm):
if matrix[i][j] != 0:
continue
if x is not None:
matrix[x][j] = matrix[i][y] = 0
else:
x, y = i, j
if x is None:
return
for i in range(lenn):
for j in range(lenm):
if i == x or j == y:
continue
if matrix[x][j] == 0 or matrix[i][y] == 0:
matrix[i][j] = 0
for i in range(lenn):
matrix[i][y] = 0
for i in range(lenm):
matrix[x][i] = 0
Edit Distance
两个字符串的最短编辑距离,可以增删改。
经典DP,d[i][j]表示s1[1:i]和s2[1:j]的最短编辑距离,它可以由d[i-1][j]、d[i][j-1]、d[i-1][j-1]这三个状态转化而来,取最小的即可。
class Solution:
# @return an integer
def minDistance(self, word1, word2):
dp = [[0] * (len(word2) + 1) for i in range(len(word1) + 1)]
for i in range(1, len(word1) + 1):
dp[i][0] = i
for i in range(1, len(word2) + 1):
dp[0][i] = i
for i in range(1, len(word1) + 1):
for j in range(1, len(word2) + 1):
dp[i][j] = dp[i - 1][j - 1] + 1
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1)
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
return dp[len(word1)][len(word2)]
Climbing Stairs
爬楼梯,每次一步或两步,求爬法有多少种
菲波拉契数列,f[n] = f[n-1] + f[n-2]
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
f = [1, 1]
while len(f) <= n:
f.append(f[-1] + f[-2])
return f[n]
Sqrt(x)
实现Sqrt(x)。
科普题,牛顿迭代,y = 1/2 * (y + x / y)。
class Solution:
# @param x, an integer
# @return an integer
def sqrt(self, x):
y0, y1 = 0, 1
while int(y0) != int(y1):
y0 = y1
y1 = 1.0/2.0 * (y0 + x / y0)
return int(y0)
Text Justification
数字排版,将一个字符串排列成每行N个字母。
恶心题,坑一堆。首先最后一行特判,单词间只有一个空格,其次关于空格均分的规则,假如8个空格3个空,就是(3,3,2)。
'''
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
'''
class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def fullJustify(self, words, L):
ans, p, plen = [], 0, 0
for i in range(len(words)):
if plen + len(words[i]) + i - p - 1 >= L:
spc = (L - plen) // (i - p - 1) if i - p > 1 else 0
sps = (L - plen - spc * (i - p - 1))
str = words[p]
for j in range(p + 1, i):
if sps > 0:
str += ' '
sps -= 1
str += ' ' * spc + words[j]
ans.append(str + ' ' * (L - plen))
plen, p = 0, i
if i < len(words):
plen += len(words[i])
str = ''
while p < len(words):
str += words[p]
if len(str) < L:
str += ' '
p = p + 1
ans.append(str + ' ' * (L - len(str)))
return ans
Plus One
讲一个大数加1
加到不进位位置,注意头部有可能要加1
class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
for i in range(len(digits)-1, -1, -1):
digits[i] = (digits[i] + 1) % 10
if digits[i]:
break;
else:
digits.insert(0, 1)
return digits
Valid Number
判断一个数字是否合法
很麻烦的DFA,这里的合数字状况比较多,小数点前有没有数字要区别对待,WA了很多次,还参考了CSGrandeur的题解才过。
class Solution:
# @param s, a string
# @return a boolean
def isNumber(self, s):
s = s.strip();
# dfa status
err = -1 # error
srt = 0 # start
sgd = 1 # integer part sign
did = 2 # integer part number
ddp = 3 # xx. (there are some numbers before '.')
dnp = 3 # .
dii = 5 # decimal part number
exe = 6 # e
sge = 7 # exp part sign
die = 8 # exp part number
end = 9 # end
# construct a dfa
dfa = [[err] * 128 for i in range(9)]
dfa[srt][ord('+')] = dfa[srt][ord('-')] = sgd
dfa[srt][ord('.')] = dfa[sgd][ord('.')] = dnp
dfa[did][ord('.')] = ddp
dfa[did][ord('e')] = dfa[ddp][ord('e')] = dfa[dii][ord('e')] = exe
dfa[exe][ord('+')] = dfa[exe][ord('-')] = sge
dfa[dii][0] = dfa[ddp][0] = dfa[did][0] = dfa[die][0] = end
for i in range(10):
t = ord('0') + i
dfa[srt][t] = dfa[sgd][t] = dfa[did][t] = did
dfa[ddp][t] = dfa[dnp][t] = dfa[dii][t] = dii
dfa[exe][t] = dfa[sge][t] = dfa[die][t] = die
# run dfa with s
s = s.strip()
status = srt
for c in s:
status = dfa[status][ord(c)]
#print status
if (status == err):
return False
return True if dfa[status][0] == end else False
Add Binary
大数加法,只是换成了二进制而已
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
a = [ord(c) - ord('0') for c in a][::-1]
b = [ord(c) - ord('0') for c in b][::-1]
if (len(a) < len(b)):
a, b = b, a
flag = 0
for i in range(len(a)):
if (i < len(b)):
a[i] += b[i]
a[i] += flag
flag = a[i] // 2
a[i] %= 2
if flag:
a.append(1)
return ''.join([chr(c + ord('0')) for c in a][::-1])
Merge Two Sorted Lists
合并两个有序列表
归并排序了,加个临时头节点好写一些
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
nHead = ListNode(0)
lt, rt, backHead = l1, l2, nHead
while lt or rt:
if lt is None:
nHead.next, rt = rt, rt.next
elif rt is None:
nHead.next, lt = lt, lt.next
elif lt.val < rt.val:
nHead.next, lt = lt, lt.next
else:
nHead.next, rt = rt, rt.next
nHead = nHead.next
return backHead.next
Minimum Path Sum
从矩形格子的左上走到右下,经过的点和加起来最小
不是从上面过来就是从左边过来,DP。
class Solution:
# @param grid, a list of lists of integers
# @return an integer
def minPathSum(self, grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if i == 0 and j > 0:
grid[i][j] += grid[i][j-1]
elif j == 0 and i > 0:
grid[i][j] += grid[i-1][j]
elif i > 0 and j > 0:
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[len(grid) - 1][len(grid[0]) - 1]
Unique Paths II
从矩形格子的左上走到右下,有些格子不能走,求路径数
只能从左边过来或者上边过来,加起来就是到这个格子的路径数,不能走的话该点就是0
class Solution:
# @param obstacleGrid, a list of lists of integers
# @return an integer
def uniquePathsWithObstacles(self, obstacleGrid):
ans = [[0] * len(obstacleGrid[0]) for i in range(len(obstacleGrid))]
for i in range(len(obstacleGrid)):
if obstacleGrid[i][0] == 1: break
else: ans[i][0] = 1
for i in range(len(obstacleGrid[0])):
if obstacleGrid[0][i] == 1: break
else: ans[0][i] = 1
for i in range(1, len(obstacleGrid)):
for j in range(1, len(obstacleGrid[0])):
if obstacleGrid[i][j] == 1:
ans[i][j] = 0
else:
ans[i][j] = ans[i][j-1] + ans[i-1][j]
return ans[len(ans)-1][len(ans[0])-1]
Unique Paths
从矩形格子的左上走到右下,有些格子不能走,求路径数
比上面一题还简单了,不用考虑不能走的格子
class Solution:
# @return an integer
def uniquePaths(self, m, n):
g = [[0] * n for i in range(m)]
for i in range(m): g[i][0] = 1
for j in range(n): g[0][j] = 1
for i in range(1, m):
for j in range(1, n):
g[i][j] = g[i][j-1] + g[i-1][j]
return g[m-1][n-1]
Rotate List
链表循环右移K个元素(即后k个元素放到链表头)
注意K要模N,然后走len-K步,再将前半部链表接到后面即可。
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def rotateRight(self, head, k):
if not head:
return head
p, len = head, 1
while p.next:
p, len = p.next, len + 1
k = len - k % len
if k == len:
return head
pp, len = head, 1
while len < k:
pp, len = pp.next, len + 1
p.next, head, pp.next = head, pp.next, None
return head
Permutation Sequence
对于集合[1,2..n],给出它字典序第K大的排列
注意到[1,2..n]有n个排列,从第一位开始枚举没用过的数字,每枚举一个,剩下的m个位置就有m!种排序方法,K不断减去m!直到K<m!,然后继续枚举下一位。
class Solution:
# @return a string
def getPermutation(self, n, k):
d, ans, use = [0, 1], [], ['0'] * n
for i in range(2, 10) : d.append( i * d[-1])
for i in range(n):
ans.append(0)
for j in range(n):
if use[j] == 1:
continue;
ans[i] = chr(ord('0') + j + 1)
if k <= d[n-i-1]:
use[j] = 1
break
k -= d[n-i-1]
return ''.join(ans)
Spiral Matrix II
将1~n^n个数以如下方式填充到矩阵中
一直向某个方向走,走到不能走顺时针旋转90度继续走
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
a = [[0] * n for i in range(n)]
sx, sy = 0, 0
dx, dy, dn = [0, 1, 0, -1], [1, 0, -1, 0], 0
for i in range(n * n):
a[sx][sy] = i + 1
nx, ny = sx + dx[dn], sy + dy[dn]
if nx < 0 or nx < 0 or nx >= n or ny >= n or a[nx][ny]:
dn = (dn + 1) % 4
nx, ny = sx + dx[dn], sy + dy[dn]
sx, sy = nx, ny
return a
Length of Last Word
求最后一个单词的长度
从后向前找,先找到第一个非空格,再从该位置向前找到第一个空格
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
i = len(s) - 1
while i >= 0 and s[i] == ' ': i -= 1
j = i - 1
while j >= 0 and s[j] != ' ': j -= 1
return 0 if i < 0 else i - j
Insert Interval
将一个区间合并到一个连续不重叠区间集合,要求返回的区间也是连续不重叠的。
将和新区间有重叠的区间合并为一个大区间即可,其它区间不变。
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert(self, intervals, newInterval):
ans, inserted = [], False
for i in range(len(intervals)):
if intervals[i].end < newInterval.start:
ans.append(intervals[i])
elif intervals[i].start > newInterval.end:
if not inserted:
inserted = True
ans.append(newInterval)
ans.append(intervals[i])
else:
newInterval.start = min(newInterval.start, intervals[i].start)
newInterval.end = max(newInterval.end, intervals[i].end)
if len(ans) == 0 or newInterval.start > ans[-1].end:
ans.append(newInterval)
return ans
Merge Intervals
合并若个个区间。
先按左端点排序,合并时直到当前区间左端点比之前所有区间最右的端点还要靠右的时候将之前的区间合并。
class Solution:
# @param intervals, a list of Interval
# @return a list of Interval
def merge(self, intervals):
intervals.sort(cmp = lambda x, y: cmp(x.start, y.start) or (x.start == y.start and cmp(x.end,y.end)))
ans, p, maxr = [], 0, 0
for i in range(len(intervals) + 1):
if i > 0 and (i == len(intervals) or intervals[i].start > maxr):
ans.append(Interval(intervals[p].start, maxr))
p = i
if i < len(intervals):
maxr = max(maxr, intervals[i].end)
return ans
Jump Game
每个格子上的数字N表示从这个格子可以到后面的N格,问是否能从头走到尾。
x表示从当前位置最多还能走几步, 每走一步都将x-1和当前格子的值的较大值作为x的值。
class Solution:
# @param A, a list of integers
# @return a boolean
def canJump(self, A):
if len(A) == 0:
return False
maxj = A[0]
for i in range(1, len(A)):
maxj -= 1
if (maxj < 0):
return False
maxj = max(maxj, A[i])
return True
Spiral Matrix
和上面的Spiral Matrix II差不多,就是从填数变成了取数。
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
return [1,2,3,6,9,8,7,4,5]
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
if len(matrix) == 0:
return []
a, ans, m, n = matrix, [], len(matrix), len(matrix[0])
x = [[0] * n for i in range(m)]
sx, sy = 0, 0
dx, dy, dn = [0, 1, 0, -1], [1, 0, -1, 0], 0
for i in range(m * n):
ans.append(a[sx][sy])
x[sx][sy] = 1
nx, ny = sx + dx[dn], sy + dy[dn]
if nx < 0 or nx < 0 or nx >= m or ny >= n or x[nx][ny]:
dn = (dn + 1) % 4
nx, ny = sx + dx[dn], sy + dy[dn]
sx, sy = nx, ny
return ans
Maximum Subarray
求子区间最大值
前缀和加到负数就重新累加,因为前面的数加进来只会减小总和。
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):
ans, sum = A[0], A[0]
for i in range(1, len(A)):
if (sum < 0):
sum = A[i]
else:
sum += A[i]
ans = max(ans, sum)
return ans
N-Queens II
八(N)皇后问题求解数
位压缩DFS
class Solution:
# @return an integer
def totalNQueens(self, n):
self.ans = 0
self.full = ((1 << n) - 1)
self.dfs(n, 0, 0, 0, 0)
return self.ans
def dfs(self, n, p, lt, rt, nt):
if n == p:
self.ans += 1
return
can = (~(lt | rt | nt) & self.full)
while can:
now = can&-can
self.dfs(n, p+1, (lt|now)>>1, (rt|now)<<1, nt|now)
can -= now
N-Queens
还是N皇后问题,只是要给出具体解
一样是未压缩DFS,py的字符串和list总要转来转去真是不怎么方便。
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
self.ans, self.dt = [], {}
self.full = ((1 << n) - 1)
for i in range(n): self.dt[1<<i] = i
tmp = [['.'] * n for i in range(n)]
self.dfs(n, 0, 0, 0, 0, tmp)
return self.ans
def dfs(self, n, p, lt, rt, nt, tmp):
if n == p:
self.ans.append([''.join(s) for s in tmp])
return
can = (~(lt | rt | nt) & self.full)
while can:
now = can&-can
tmp[p][self.dt[now]] = 'Q'
self.dfs(n, p+1, (lt|now)>>1, (rt|now)<<1, nt|now, tmp)
tmp[p][self.dt[now]] = '.'
can -= now
Pow(x, n)
快速幂,二分
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):
if n == 0:
return 1
xx = pow(x, n >> 1)
xx *= xx
if n & 1: xx *= x
return xx
Anagrams
真不知道题目这单词是什么意思。。其实就是列表里如果有多个单词由相同字母组成就加到结果里,比如cat,tac。
排序后map一下就OK了,注意处理重复问题,Map中添加新元素时记录该元素的下标,遇到Anagrams后将对应单词加进结果集并将下标改为-1,下次就不再添加该单词。
class Solution:
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
ans, dt = [], {}
for i in range(len(strs)):
lt = list(strs[i])
lt.sort()
s = ''.join(lt)
d = dt.get(s, -2)
if d == -2:
dt[s] = i
elif d == -1:
ans.append(strs[i])
else:
ans.append(strs[i])
ans.append(strs[d])
dt[s] = -1
return ans
Rotate Image
将一个二维数组90度旋转,要求原地工作。
数学学的差,半天才把源坐标和目的坐标的对应关系算出来。四个一组进行旋转。
class Solution:
# @param matrix, a list of lists of integers
# @return a list of lists of integers
def rotate(self, matrix):
L = len(matrix)
R = (L + 1) // 2
for x in range(0, R):
for y in range(0, L - R):
#(x,y)->(y,l-1-x)->(l-1-x,l-1-y)->(l-1-y,x)
matrix[x][y], matrix[y][L-1-x], matrix[L-1-x][L-1-y], matrix[L-1-y][x] \
= matrix[L-1-y][x], matrix[x][y], matrix[y][L-1-x], matrix[L-1-x][L-1-y]
return matrix
Permutations II
Permutations
这两题一样,都是给出一个集合,得到它的所有排列。只是一个有重复,一个没重复。按下面这种解法有没有重复都是一样的。
这里实现了一下STL里的next_permutation函数,用于得到当前排列的下一个排列(按字典序)。
next_permutation先从后向前找到第一个d[i]d[i]的数,最后swap(d[i],d[j])并且reverse(d[i+1…n])就得到了下一个排列。
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(self, num):
num.sort()
ans = [num[:]]
while self.next_permutation(num):
ans.append(num[:])
return ans
def next_permutation(self, num):
for i in range(len(num)-2, -1, -1):
if num[i] < num[i+1]:
break
else:
return False
for j in range(len(num)-1, i, -1):
if num[j] > num[i]:
num[i], num[j] = num[j], num[i]
break
for j in range(0, (len(num) - i)//2):
num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1]
return True
Jump Game II
每个格子上的数字N表示从这个格子可以跳到后面的1~N格,问从头到尾至少要跳几步。
一边遍历一边记录从前面的格子最远能够跳到的格子,假设前一步最远可以跳到第x格,那么遍历到第x格的时候,下一步的最远距离也已经知道了。
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
maxj, maxn, tms = 0, 0, 0
for i in range(len(A) - 1):
maxn = max(maxn, A[i] + i)
if i == maxj:
maxj, tms = maxn, tms + 1
return tms
Wildcard Matching
实现带?和*的模糊匹配,其中?匹配单字符,*匹配任意长度字符串
先写了个DP,超时了,模式串和匹配串都有可能非常长。对于这题的数据,搜索还快一些,对于号使用非贪婪匹配,优先匹配尽量少的字符。记录最后一次匹配到的时p和s扫描到的位置,失配时回溯(其实就是枚举*匹配的长度)。
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
ps, pp, lastp, lasts = 0, 0, -1, -1
while ps < len(s):
if pp < len(p) and (s[ps] == p[pp] or p[pp] == '?'):
ps, pp = ps + 1, pp + 1
elif pp < len(p) and p[pp] == '*':
pp = pp + 1
lastp, lasts = pp, ps
elif lastp != -1:
lasts = lasts + 1
pp, ps = lastp, lasts
else:
return False
while pp < len(p) and p[pp] == '*':
pp = pp + 1
return ps == len(s) and pp == len(p)
Multiply Strings
字符串模拟大数乘法
虽然py支持大数,但还是手写一下吧,再次觉得py处理字符串转来转去的不方便,也许是我太菜了吧。。
class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
def multiply(self, num1, num2):
num1 = [ord(i) - ord('0') for i in num1][::-1]
num2 = [ord(i) - ord('0') for i in num2][::-1]
ans = [0] * (len(num1) + len(num2) + 1)
for i in range(len(num1)):
for j in range(len(num2)):
ans[i + j] += num1[i] * num2[j]
ans[i + j + 1] += ans[i + j]
#ans[i + j]
while len(ans) > 1 and ans[len(ans) - 1] == 0:
ans.pop()
return ''.join([chr(i + ord('0')) for i in ans][::-1])
Trapping Rain Water
每个木板有高度,求最多能蓄多少水
分别求出每块木板左边最高的和右边最高的,然后取较小的就是该块木板的最高蓄水位。
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
maxl, maxr, maxv, ans = [], [], 0, 0
for i in range(len(A)):
if A[i] > maxv: maxv = A[i]
maxl.append(maxv)
maxv = 0
for i in range(len(A)-1, -1, -1):
if A[i] > maxv: maxv = A[i]
maxr.append(maxv)
for i in range(len(A)):
minh = min(maxl[i], maxr[len(A) - i - 1]) - A[i]
ans += minh if minh > 0 else 0
return ans
First Missing Positive
找第一个少了的正数。
如果1~N都有,N正好就是数组长度,所以用原数组做Hash就可以了,Hash的范围是1~N。具体实现是不断swap当前数和它应该在的位置上的数,直到当前数不能换了为止(每个数最多只会帮换一次,所以复杂度还是O(N))。
class Solution:
# @param A, a list of integers
# @return an integer
def firstMissingPositive(self, A):
L = len(A)
for i in range(L):
while A[i] > 0 and A[i] <= L and A[i] != A[A[i] - 1] and i != A[i] - 1:
A[A[i] - 1], A[i] = A[i], A[A[i] - 1]
#A[i], A[A[i] - 1] = A[A[i] - 1], A[i] dosen't work
for i in range(L):
if i != A[i] - 1:
return i + 1
return L + 1
Combination Sum II
在集合中选几个数和为N,每个数只能用一次,问有多少种解法。
这种有重复数字需要避免重复解的DFS,处理方法基本都一样,就是DFS的时候如果前一个数是相同的并且没用,那么这个数也不能用。
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum2(self, candidates, target):
candidates.sort()
self.ans, tmp, use = [], [], [0] * len(candidates)
self.dfs(candidates, target, 0, 0, tmp, use)
return self.ans
def dfs(self, can, target, p, now, tmp, use):
if now == target:
self.ans.append(tmp[:])
return
for i in range(p, len(can)):
if now + can[i] <= target and (i == 0 or can[i] != can[i-1] or use[i-1] == 1):
tmp.append(can[i]);
use[i] = 1
self.dfs(can, target, i+1, now + can[i], tmp, use)
tmp.pop()
use[i] = 0
Combination Sum
上一题的简化版,而且每个数可以用多次,直接DFS就可以了
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
candidates.sort()
self.ans, tmp = [], []
self.dfs(candidates, target, 0, 0, tmp)
return self.ans
def dfs(self, candidates, target, p, now, tmp):
if now == target:
self.ans.append(tmp[:])
return
for i in range(p, len(candidates)):
if now + candidates[i] <= target:
tmp.append(candidates[i])
self.dfs(candidates, target, i, now+candidates[i], tmp)
tmp.pop()
Count and Say
求以下序列的第N项,模拟即可。
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
class Solution:
# @return a string
def countAndSay(self, n):
s, now = [str(1), ''], 0
for i in range(1, n):
now, pre, tot = now^1, now, 0
s[now], p = "", 0
while p < len(s[pre]):
tot, v, p = 1, s[pre][p], p + 1
while p < len(s[pre]) and v == s[pre][p]:
p += 1
tot += 1
s[now] += str(tot) + v
return s[now]
Sudoku Solver
求数独的解,dancing links不会,只能写个位压缩版了。。
class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
def solveSudoku(self, board):
lt, rt, bt = [0] * 9, [0] * 9, [0] * 9
self.dt = {}
for i in range(9): self.dt[1<<i] = chr(ord('1')+i)
for i in range(9):
board[i] = list(board[i])
for j in range(9):
if (board[i][j] == '.'):
continue;
num = ord(board[i][j]) - ord('1')
lt[i] |= 1 << num
rt[j] |= 1 << num
bt[j//3*3+i//3] |= 1 << num
self.dfs(board, 0, lt, rt, bt)
board = [''.join(s) for s in board]
def dfs(self, board, p, lt, rt, bt):
while p < 81 and board[p/9][p%9] != '.':
p += 1
if p == 81:
return True
i, j, k = p//9, p%9, p%9//3*3+p//9//3
if board[i][j] != '.':
self.dfs(board, p + 1, lt, rt, bt)
return True
can = (~(lt[i]|rt[j]|bt[k])) & (0x1ff)
pre = board[i]
while can:
num = can&-can
board[i][j] = self.dt[num]
lt[i] |= num
rt[j] |= num
bt[k] |= num
if self.dfs(board, p + 1, lt, rt , bt):
return True
board[i][j] = '.'
lt[i] &= ~num
rt[j] &= ~num
bt[k] &= ~num
can -= num
return False
Valid Sudoku
判断数独初始局面是否合法,就是在上题初始化的过程中加上了判断。
class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
lt, rt, bt = [0] * 9, [0] * 9, [0] * 9
for i in range(9):
for j in range(9):
print i, j
if (board[i][j] == '.'):
continue;
num = ord(board[i][j]) - ord('1')
if 0 == (~(lt[i]|rt[j]|bt[j/3*3+i/3]) & (1<<num)):
return False
lt[i] |= 1 << num
rt[j] |= 1 << num
bt[j/3*3+i/3] |= 1 << num
return True
Search Insert Position
给一个排序数组和一个数,找出这个数应该插在哪个位置。
二分稍加变形,保证l最后停在第一个比它大的数的位置上。
class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
l, h = 0, len(A)
while l < h:
m = (l + h) // 2
if A[m] < target:
l = m + 1
else:
h = m
return l
Search for a Range
找出排序数组中一个数第一次出现的位置和最后一次出现的位置。
也是二分变形,写对真不容易。。
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
return [self.lower_bound(A, target), self.upper_bound(A, target)]
def lower_bound(self, A, target):
l, h, m = 0, len(A), 0
while l < h:
m = (l + h) >> 1
if A[m] < target:
l = m + 1
else:
h = m
return l if l < len(A) and A[l] == target else -1
def upper_bound(self, A, target):
l, h, m = 0, len(A), 0
while l < h:
m = (l + h) >> 1
if A[m] <= target:
l = m + 1
else:
h = m
return l-1 if l-1 < len(A) and A[l-1] == target else -1
Search in Rotated Sorted Array
把一个有序数组循环右移若干位之后,查找某个数是否在这个数组中。
还是二分,只是到底是向左还是向右的时候判断要复杂一些。
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
l, h = 0, len(A) - 1
while (l <= h):
m = l + ((h - l) >> 1)
if A[m] == target:
return m
elif (A[m] > A[l] and target < A[m] and target >= A[l]) or (A[m] < A[l] and not (target <= A[h] and target > A[m])):
h = m - 1
else:
l = m + 1
return -1
Longest Valid Parentheses
最长的合法括号序列。
写了好久,首先用栈可以找到每个右括号对应的左括号,如果它对应的左括号前面也是一个独立的合法括号序列,要累加起来。
class Solution:
# @param s, a string
# @return an integer
def longestValidParentheses(self, s):
stk, p ,ans = [], [0] * len(s), 0
for i in range(len(s)):
if s[i] == '(':
stk.append(i)
elif s[i] == ')':
if len(stk) > 0:
p[i] = i - stk[-1] + 1
if i >= p[i] and p[i - p[i]]:
p[i] += p[i-p[i]]
ans = max(ans, p[i])
stk.pop()
return ans
Next Permutation
求下一个序列,前面的Permutations题中已经用到了。(CTRL+F向上找。。)
class Solution:
# @param num, a list of integer
# @return a list of integer
def nextPermutation(self, num):
for i in range(len(num)-2, -1, -1):
if num[i] < num[i+1]:
break
else:
num.reverse()
return num
for j in range(len(num)-1, i, -1):
if num[j] > num[i]:
num[i], num[j] = num[j], num[i]
break
for j in range(0, (len(num) - i)//2):
num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1]
return num
Substring with Concatenation of All Words
给出一个字符串集合L和字符串S,找出S从哪些位置开始恰好包含每个字符串各一次。
这类判断某一段包含了哪些内容的题做法都差不多,一个pre指针,一个last指针,用一个集合记录这之间出现的值,last指针不断往后扫直到扫到多余的元素,然后pre指针再从之前的位置扫到第一个有这个元素的位置之后,这时候last指针就可以继续后移了。
这个题就是要做一些变形,将S分成len(L(0))段,每段分别使用以上算法。比如len(L(0))=3,len(S)=10时,就分成S[0,3,6,9],S[1,4,7],S[2,5,8]三段。
class Solution:
# @param S, a string
# @param L, a list of string
# @return a list of integer
def findSubstring(self, S, L):
LS, LL, LL0 = len(S), len(L), len(L[0])
did, ids, dl = {}, 0, {}
for s in L:
id = did.get(s, -1)
if id == -1:
ids = ids + 1
id = ids
did[s] = id
dl[id] = dl.get(id, 0) + 1
pos, ans = [0] * LS, []
for k, v in did.items():
f = S.find(k)
while f != -1:
pos[f] = v
f = S.find(k, f + 1)
for sp in range(LL0):
np, pp, tot, dt = sp, sp, 0, {}
while np < LS:
t = pos[np]
if t == 0:
tot, dt = 0, {}
pp, np = np + LL0, np + LL0
elif dt.get(t, 0) < dl[t]:
dt[t] = dt.get(t, 0) + 1
tot = tot + 1
if tot == LL:
ans.append(pp)
np = np + LL0
else:
while pos[pp] != t:
tot = tot - 1
dt[pos[pp]] -= 1
pp = pp + LL0
pp = pp + LL0
dt[t] -= 1
tot = tot - 1
return ans
Divide Two Integers
不使用乘除法实现加法。
二进制思想,用二进制去凑答案。
class Solution:
# @return an integer
def divide(self, dividend, divisor):
flag, ans = 0, 0
if dividend < 0:
flag, dividend = flag^1, -dividend
if divisor < 0:
flag, divisor = flag^1, -divisor
while dividend >= divisor:
count, newDivisor = 1, divisor
while newDivisor + newDivisor <= dividend:
newDivisor = newDivisor + newDivisor
count = count + count
dividend -= newDivisor
ans += count
return ans if flag == 0 else -ans
Implement strStr()
实现strStr()函数
KMP了,好久不写真的写不出来了。。。
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
lenh, lenn = len(haystack), len(needle)
if lenn == 0:
return haystack
next, p = [-1] * (lenn), -1
for i in range(1, lenn):
while p >= 0 and needle[i] != needle[p + 1]:
p = next[p]
if needle[i] == needle[p + 1]:
p = p + 1
next[i] = p
p = -1
for i in range(lenh):
while p >= 0 and haystack[i] != needle[p + 1]:
p = next[p]
if haystack[i] == needle[p + 1]:
p = p + 1
if p + 1 == lenn:
return haystack[i - p:]
return None
Remove Element
在数组中移除指定元素
不是指定的元素就往前面放就行了
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
sz = 0
for i in range(0, len(A)):
if A[i] != elem:
A[sz] = A[i]
sz += 1
return sz
Remove Duplicates from Sorted Array
有序数组删除重复元素到只留一个
往数组前部放,放之前保证和已放的最后一个不一样即可
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0
sz = 1
for i in range(1, len(A)):
if A[i] != A[i-1]:
A[sz] = A[i]
sz += 1
return sz
Reverse Nodes in k-Group
链表,每K个一段进行reverse。
到每第K个元素的时候掉个头就行,中间就是正常的链表逆置,注意最后几个不要处理。
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def reverseKGroup(self, head, k):
nHead = ListNode(0)
nHead.next = head
p2, lenl = head, 0
while p2: p2, lenl = p2.next, lenl + 1
now, pre, ind = head, nHead, 1
preHead, preHeadNext = nHead, head
while now:
if lenl - ind < lenl % k:
break
next = now.next
now.next = pre
if ind % k == 0:
preHead.next = now
preHeadNext.next = next
preHead = preHeadNext
pre = preHead
preHeadNext = next
else:
pre = now
now, ind = next, ind + 1
return nHead.next
Swap Nodes in Pairs
上一题的简化版,相当于 K=2
代码写的相当暴力,反正两个元素最多也就3个NEXT就能访问到下一段。。
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
if head is None or head.next is None:
return head
nHead = ListNode(0)
nHead.next = head
p1, p2 = nHead, head
while p2 and p2.next:
p2 = p2.next.next
p1.next.next.next = p1.next
p1.next = p1.next.next
p1.next.next.next = p2
p1 = p1.next.next
return nHead.next
Merge k Sorted Lists
合并K个有序链表。
和归并一样,每次选K个链表头部最小的元素。这里的优化就是用一个堆来维护这K个元素的最小值,复杂度O(sum(len(Ki)) * logK)
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
self.heap = [[i, lists[i].val] for i in range(len(lists)) if lists[i] != None]
self.hsize = len(self.heap)
for i in range(self.hsize - 1, -1, -1):
self.adjustdown(i)
nHead = ListNode(0)
head = nHead
while self.hsize > 0:
ind, val = self.heap[0][0], self.heap[0][1]
head.next = lists[ind]
head = head.next
lists[ind] = lists[ind].next
if lists[ind] is None:
self.heap[0] = self.heap[self.hsize-1]
self.hsize = self.hsize - 1
else:
self.heap[0] = [ind, lists[ind].val]
self.adjustdown(0)
return nHead.next
def adjustdown(self, p):
lc = lambda x: (x + 1) * 2 - 1
rc = lambda x: (x + 1) * 2
while True:
np, pv = p, self.heap[p][1]
if lc(p) < self.hsize and self.heap[lc(p)][1] < pv:
np, pv = lc(p), self.heap[lc(p)][1]
if rc(p) < self.hsize and self.heap[rc(p)][1] < pv:
np = rc(p)
if np == p:
break
else:
self.heap[np], self.heap[p] = self.heap[p], self.heap[np]
p = np
Generate Parentheses
生成所有可能的括号序列
DFS搜索了,注意右括号不能比左括号多即可
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
self.ans, tmp = [], []
lb = 0
self.dfs(lb, 0, n, tmp)
return self.ans
def dfs(self, lb, p, n, tmp):
if p == n * 2:
self.ans.append(''.join(tmp))
return
if lb < n:
tmp.append('(')
self.dfs(lb + 1, p + 1, n, tmp)
tmp.pop()
if p - lb < lb:
tmp.append(')')
self.dfs(lb, p + 1, n, tmp)
tmp.pop()
Valid Parentheses
判断括号序列是否合法,共有三种括号
用栈,遇到右括号时左括号必须和当前括号是一对,然后出栈
class Solution:
# @return a boolean
def isValid(self, s):
dct = {'(':')', '[':']', '{':'}'}
stk = []
for c in s:
if dct.get(c, None):
stk.append(c)
elif len(stk) == 0 or dct[stk[-1]] != c:
return False
else:
stk.pop()
return True if len(stk) == 0 else False
Remove Nth Node From End of List
删除链表的第N个元素,只能扫一遍
一个指针先走N-K步,然后另一个指针在开头,一起走直到先走的指针到达末尾,删除后走的指针
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
nHead = ListNode(0)
nHead.next = head
p, t = 0, head
while p < n:
t = t.next
p += 1
pre = nHead
while t:
t, pre = t.next, pre.next
pre.next = pre.next.next
return nHead.next
Letter Combinations of a Phone Number
按一串电话按键,求所有可能的字母组合
DFS
class Solution:
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
if len(digits) == 0:
return [""]
self.dglist = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
self.ans, tmp = [], []
self.dfs(digits, 0, tmp)
return self.ans
def dfs(self, digits, p, tmp):
if (p == len(digits)):
self.ans.append(''.join(tmp))
return
for c in self.dglist[ord(digits[p]) - ord('0')]:
tmp.append(c)
self.dfs(digits, p + 1, tmp)
tmp.pop()
4Sum
求集合中4个数的和为0的所有解。
做法和3sum一样,py超时,用c++写的,复杂度O(N^3)。
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > ans;
sort(num.begin(), num.end());
for (int i = 0; i < num.size(); i++) {
if (i > 0 && num[i] == num[i-1]) continue;
for (int j = i + 1; j < num.size(); j++) {
if (j > i + 1 && num[j] == num[j - 1]) continue;
int l = j + 1, r = num.size() - 1;
while (l < r) {
int sum = num[i] + num[j] + num[l] + num[r];
if (sum == target) {
ans.push_back({num[i], num[j], num[l], num[r]});
while (l < r && num[l] == num[l + 1]) l++; l++;
while (l < r && num[r] == num[r - 1]) r--; r--;
} else if (sum < target) {
l++;
} else {
r--;
}
}
}
}
return ans;
}
};
3Sum Closest
求集合中3个数能够得到的距离target最近的和
和3Sum一样,而且不用处理重复解问题了。
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
num.sort()
ans = None
for i in range(len(num)):
l, r = i + 1, len(num) - 1
while (l < r):
sum = num[l] + num[r] + num[i]
if ans is None or abs(sum- target) < abs(ans - target):
ans = sum
if sum <= target:
l = l + 1
else:
r = r - 1
return ans
3Sum
求3个数的和为target的所有解。
枚举第一个数,然后第二个数为这个数的后一个数,第三个数为最后一个数,如果和小于0,第二个数后移,如大于0第三个数前移,等于0的话记录结果并且都向中间移。注意处理重复解。
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
num.sort()
dct, ans = {}, []
for i in range(0, len(num)):
if (i > 0 and num[i] == num[i-1]):
continue
l, r = i + 1, len(num) - 1
while l < r:
sum = num[l] + num[r] + num[i]
if sum == 0:
ans.append([num[i], num[l], num[r]])
while l < r and num[l] == num[l + 1]: l = l + 1
while l < r and num[r] == num[r - 1]: r = r - 1
l, r = l + 1, r - 1
elif sum < 0:
l = l + 1
else:
r = r - 1
return ans
Longest Common Prefix
求所有的字符串的最长公共前缀
暴力直接一位位扫,直到遇到某位有不同的字符或者某个字符串结尾
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) <= 1:
return strs[0] if len(strs) == 1 else ""
end, minl = 0, min([len(s) for s in strs])
while end < minl:
for i in range(1, len(strs)):
if strs[i][end] != strs[i-1][end]:
return strs[0][:end]
end = end + 1
return strs[0][:end]
Roman to Integer
罗马数字转阿拉伯数字。
右边比左边大就减对应值,否则就加对应值。
class Solution:
# @return an integer
def romanToInt(self, s):
roval = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
ans = 0
for i in range(len(s)):
if i + 1 < len(s) and roval[s[i]] < roval[s[i+1]]:
ans -= roval[s[i]]
else:
ans += roval[s[i]]
return ans
Integer to Roman
阿拉伯数字转罗马数字。
打表。
class Solution:
# @return a string
def intToRoman(self, num):
ronum = [['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
['', 'M', 'MM', 'MMM', ' ', ' ', ' ', ' ', ' ', ' ']]
ans, ind = '', 0
while num:
ans = ronum[ind][num%10] + ans
num, ind = num / 10, ind + 1
return ans
Container With Most Water
给出N个高度不同的挡板y,每个柱子距离1,找出两个挡板,使这两个挡板之间盛水最多
一开始题目理解错了,以为挡板都先放好了,其实是选两个挡板出来,其它挡板不用。。
从两边向中间枚举,假设两块挡板满足height[x]<height[y],那么把y向中间移动肯定得不到更优的解,所以每次选较矮的一块往中间移
class Solution:
# @return an integer
def maxArea(self, height):
l, r, ans = 0, len(height) - 1, 0
while l <= r:
ans = max(ans, (r - l) * min(height[r], height[l]))
if height[l] < height[r]:
l = l + 1
else:
r = r - 1
return ans
Regular Expression Matching
实现带.和*的正则表达式匹配,其中.匹配任一字符,*表示重复之前内容0次以上。
DP做的,dp[i][j]表示s[1..i]和p[1..j]匹配,需要考虑的情况还是比较复杂的,搜索应该也可行。
class Solution:
# @return a boolean
def isMatch(self, s, p):
s, p = ' ' + s, ' ' + p
dp = [[False] * (len(p)) for i in range(len(s))]
dp[0][0] = True
ind = 2
while ind < len(p) and p[ind] == '*':
dp[0][ind], ind = True, ind + 2
for i in range(1, len(s)):
for j in range(1, len(p)):
if (s[i] == p[j] or p[j] == '.') and dp[i-1][j-1]:
dp[i][j] = True
if p[j] == '*' and (dp[i][j-2] or ((p[j-1] == '.' or p[j-1] == s[i]) and (dp[i-1][j-2] or dp[i-1][j]))):
dp[i][j] = True
return dp[len(s) - 1][len(p) - 1]
s = Solution()
print s.isMatch("aa", "a") # False
print s.isMatch("aa", "aa") # True
print s.isMatch("aaa","aa") # False
print s.isMatch("aa", "a*") # True
print s.isMatch("aa", ".*") # True
print s.isMatch("ab", ".*") # True
print s.isMatch("aab", "c*a*b") # True
print s.isMatch("aaa", "ab*a") # Fasle
print s.isMatch("aaba", "ab*a*c*a") # False
print s.isMatch("", ".*") # True
print s.isMatch("bbab", "b*a*") # False
print s.isMatch("aab", "b.*") # False
Palindrome Number
判断一个数字是否是回文串
判断翻转后的数字和原数字是否相同即可。虽然翻转后可能溢出。。但是。。这种东西py没有。。
一开始还写了个数组存,其实不需要,一开始使a=x,然后不断b=b*10+a%10,b就是a翻转的结果了
class Solution:
# @return a boolean
def isPalindrome(self, x):
if x <= 0:
return False if x < 0 else True
a, b = x, 0
while a:
b, a = b * 10 + a % 10, a / 10
return b == x
String to Integer (atoi)
实现atoi
坑略多,主要是以下几个:
1.前面有空格;
2.遇到非法字符就不再分析后面的;
3.有可能越界。
class Solution:
# @return an integer
def atoi(self, str):
if len(str) == 0:
return 0
sgn, num, p = 0, 0, 0
imin, imax = -1<<31, (1<<31)-1
while str[p] == ' ':
p = p + 1
if str[p] == '-' or str[p] == '+':
sgn = 1 if str[p] == '-' else 0
p = p + 1
while p < len(str) and str[p] >= '0' and str[p] <= '9':
num = num * 10 + ord(str[p]) - ord('0')
x = -num if sgn else num
if x < imin: return imin
if x > imax: return imax
p = p + 1
return -num if sgn else num
Reverse Integer
翻转一个数字
注意可能会溢出,py就不用管了,但是c的话记得用long long
class Solution:
# @return an integer
def reverse(self, x):
a = 0
b = x if x > 0 else -x
while b:
a, b = a * 10 + b % 10, b / 10
return a if x > 0 else -a
ZigZag Conversion
将一个字符串的字符Z形排列,然后按行顺序输出所有字母,下面有样例
找到规律,然后模拟
'''
P A H N 1 5 ...
A P L S I I G 2 4 6 8 ...
Y I R 3 7 ...
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
'''
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1 or len(s) == 0:
return s
res, lens = [], len(s)
add, now = [nRows * 2 - 2, 0], 0
for i in range(nRows):
if i < lens:
res.append(i)
while res[-1] + add[now] < lens:
if add[now] > 0:
res.append(res[-1] + add[now])
now ^= 1
add, now = [add[0] - 2, add[1] + 2], 0
return ''.join([s[i] for i in res])
s = Solution()
print s.convert("A", 2)
Longest Palindromic Substring
求最大回文子串长度
这个O(n)算法看了不亚于三遍了,每次写都会忘。。可能是因为没理解透彻,然后也没怎么用吧。
核心思想就是利用了回文串的对称性质。
class Solution:
# @return a string
def longestPalindrome(self, s):
arr = ['$', '#']
for i in range(len(s)):
arr.append(s[i])
arr.append('#')
p = [0] * len(arr)
mx, pos, ansp = 0, 0, 0
for i in range(1, len(arr)):
p[i] = min(mx - i, p[2 * pos - i]) if mx > i else 1
while p[i] + i < len(arr) and arr[i + p[i]] == arr[i - p[i]]:
p[i] += 1
if p[i] + i > mx:
mx, pos = p[i] + i, i
if p[i] > p[ansp]:
ansp = i
st = (ansp - p[ansp] + 1) // 2
return s[st:st + p[ansp] - 1]
Add Two Numbers
链表版大数加法
和数组没什么区别吧。。?翻转都不用了。。
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
nHead, flag = ListNode(0), 0
head = nHead
while flag or l1 or l2:
node = ListNode(flag)
if l1:
node.val += l1.val
l1 = l1.next
if l2:
node.val += l2.val
l2 = l2.next
flag = node.val // 10
node.val %= 10
head.next, head = node, node
return nHead.next
Longest Substring Without Repeating Characters
求最长的没有重复字符的子串
维护两个指针,保证两个指针之间的串没有重复字符,后指针扫到某个字符重复时就将前指针向后移到第一个和当前字符相同的字符之后
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
dict, ans, p1, p2 = {}, 0, 0, 0
while p2 < len(s):
p = dict.get(s[p2], None)
if p == None:
dict[s[p2]] = p2
p2 += 1
ans = max(ans, p2 - p1)
else:
while p1 <= p:
dict.pop(s[p1])
p1 += 1
p1 = p + 1
return ans
Median of Two Sorted Arrays
求两个有序数组的中位数。
我是用求两个有序数组的第K大数方法做的,复杂度没有细算。
假设A数组中取第x个数,Y数组取第y个数,并且满足x+y=K,若A[x] < B[y],则比A[x]小的数必然小于K个,也就是说A[1]~A[x]都比第K小的数要小,可以舍弃掉然后求第K-x小的数;若A[x] > B[y]也是一样的道理。
class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
totlen = len(A) + len(B)
if (1 & totlen):
return self.findK(A, B, (totlen + 1) / 2)
else:
return (self.findK(A, B, totlen / 2) + self.findK(A, B, totlen / 2 + 1)) / 2.0
def findK(self, A, B, K):
la, lb, pa, pb = len(A), len(B), min(K/2, len(A)), K - min(K/2, len(A))
if (la > lb):
return self.findK(B, A, K)
if (la == 0):
return B[K-1]
if (K == 1):
return min(A[0], B[0])
if A[pa - 1] < B[pb - 1]:
return self.findK(A[pa:], B, K - pa)
elif A[pa - 1] > B[pb - 1]:
return self.findK(A, B[pb:], K- pb)
else:
return A[pa - 1]
Two Sum
找出数组中的两个数,这两个数和为target
扫到x时看前面Hash的数里有没有target-x,然后将x也放进Hash表。
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict = {}
for i in range(len(num)):
if dict.get(target-num[i], None) == None:
dict[num[i]] = i
else:
return (dict[target-num[i]] + 1, i + 1) |
a48468e70c0f7d95bc005bf1bb89c690e22a9000 | Keilo104/faculdade-solucoes | /Semestre 1/AP1/exerciciosextra/atividadepratica01.py | 2,874 | 3.6875 | 4 | i = 0
prataCaro = 0
prataCaroNome = ""
mais60k = 0
amarelo2010 = 0
amarelo2010media = 0
branco30k = 0
while True:
i += 1
modelo = input("Digite o modelo do {}º carro: ".format(i)) # Faça um programa para informatizar o
ano = int(input("Digite o ano de fabricação do {}º carro: ".format(i))) # cadastro de carros em um estacionamento.
valor = float(input("Digite o valor do {}º carro: ".format(i))) # Você deve cadastrar os carros com as seguintes
cor = input("Digite a cor do {}º carro: ".format(i)) # informações: modelo, ano de fabricação, valor e cor.
print("---------------------------------------------")
if valor > prataCaro and cor == "prata": # - o modelo do carro mais caro e da cor prata.
prataCaro = valor
prataCaroNome = modelo
if cor == "preto" and (valor > 60000 or ano < 2017): # - a quantidade de carros pretos com valor maior que
mais60k += 1 # R$ 60.000,00 ou ano de fabricação menor que 2017
if cor == "amarelo" and ano > 2010: # - média de valores dos carros amarelos com ano de
amarelo2010 += 1 # fabricação maior que 2010.
amarelo2010media += valor
if cor == "branco" and valor > 30000: # - o percentual de carros que custam mais que
branco30k += 1 # R$ 30.000,00 e que são da cor branca.
if ano < 2000: # Devem ser cadastrados carros até algum veículo com ano
break # de fabricação inferior a 2000 ser cadastrado.
# Quando isso ocorrer informar:
# - o modelo do carro mais caro e da cor prata.
if prataCaro == 0:
print("Nenhum carro prata foi cadastrado.")
else:
print("O carro prata mais caro cadastrado era modelo \"{}\", valendo R${}.".format(prataCaroNome, prataCaro))
# - a quantidade de carros pretos com valor maior que R$ 60.000,00 ou ano de fabricação menor que 2017
print("Foram cadastrados {} carros pretos com valor maior que R$60.000,00 ou com ano de fabricação menor que 2017.".format(mais60k))
# - média de valores dos carros amarelos com ano de fabricação maior que 2010.
if amarelo2010 == 0:
print("Não foram cadastrados carros amarelos com ano de fabricação maior que 2010.")
else:
amarelo2010media = amarelo2010media / amarelo2010
print("A média de valor entre os carros amarelos com ano de fabricação maior que 2010 é R${}.".format(amarelo2010media))
# - o percentual de carros que custam mais que R$ 30.000,00 e que são da cor branca.
mediaBranco30k = (branco30k / i) * 100
print("{}% dos carros cadastrados custam mais de R$30.000,00 e são da cor branca.".format(mediaBranco30k))
|
60dec79e0b77b77a66f0711db817e1b5faf901ff | MuniraLinda/Python-Class | /numbers.py | 208 | 4.3125 | 4 | #Asignment : numeric datatypes
'''
1. Using the random library,
Print out random numbers range from 10-100
2. Convert float to int
'''
import random
print(random.randrange(10,100))
#x = 35.3
#print(int(x)) |
9673fa64db4c85fd993a205190c199e0c86cbb2b | chandra10207/Python-tkinter-workouts | /Python Testing and Quality Assurance/Task1/count.py | 308 | 3.625 | 4 | def countNum(start, end, num):
count = 0
for i in range(start, end):
if str(num) in str(i):
count = count + 1
return count
print(countNum(1,5,8))
print(countNum(1,500,2))
print(countNum(-50,-5,6))
print(countNum(100,1000,42))
print(countNum(1,12,1))
print(countNum(5,5,5))
|
2519356335743ebefac9939d9798b1203c63beb1 | dsurraobhcc/CSC-225-T1 | /classes/class4/meetings.py | 1,813 | 4.15625 | 4 | # 1. Complete the code below:
# a. Create a 'Meeting' class that stores the following information
# about an event in your calendar: title, location, start time, end time
# b. Instantiate the following events using this class and add them to a list
# Doctor appointment, MGH, 10/18/2020 9-10 am
# Soccer practice, BU athletic field, 9/1/2020 5-7pm
# Foliage trip, Berkhires, 11/24/2020 - 11/25/2020
# c. Implement the special method __lt__ that compares start times of two
# Meeting objects (this should be only one line of code!).
# d. Sort the above meeting list to check if this method works.
# Hint: datetime(2019, 5, 18, 15, 17) represent a time '2019-05-18T15:17:00'
from datetime import datetime
class Meeting(object):
#TODO: implement the constructor
def __init__(self, title, location, start_time, end_time):
self.title = title
self.location = location
self.start_time = start_time
self.end_time = end_time
#TODO: implement this method
def __lt__(self, other):
return self.start_time < other.start_time
def __str__(self):
return self.title + ', ' + self.location + ', ' \
+ datetime.__str__(self.start_time) + ', ' \
+ datetime.__str__(self.end_time)
#TODO: instantiate three instances of the above class using data in b.
m1 = Meeting('Doctor appointment', 'MGH', \
datetime(2020, 10, 18, 9), datetime(2020, 10, 18, 10))
m2 = Meeting('Soccer practice', 'BU athletic field', \
datetime(2020, 9, 1, 17), datetime(2020, 9, 1, 17))
m3 = Meeting('Foliage trip', 'Berkshires', \
datetime(2020, 11, 24), datetime(2020, 11, 25))
#TODO: create a list, sort it using list.sort(), and print meetings in the list
meetings = [m1, m2, m3]
meetings.sort()
for meeting in meetings:
print(meeting) |
b9a52ccf1606f3031e663199d08138d2fde3a6c2 | sfadiga/Hashsort | /hash_sort.py | 1,011 | 4.53125 | 5 | def hash_sort(arr):
'''
this code will only work in python 2
A very simple and naive sort algorithm that uses a hash table as auxiliary structure
A good use case for this algorithm is a list of numbers distributed randomly
but with range approximate of the size of the list.
:param arr: a list of numbers to be sorted, the list will be sorted in place
'''
# creates the aux hash
# add a counter as a value to this hash so it could handle duplicate values
# uses the values from the arr as key to the hash, this is where sorting gets place
hash = {}
for a in arr:
if a not in hash:
hash[a] = 0
hash[a] += 1
# traverses the hash extracting the count values from it and set back to the
# original arr structure, the inner for handles the counter for 1 or more duplicates
index = 0
for k in hash:
v = hash[k]
for n in range(0, v):
arr[index] = k
index += 1
|
3a7aa11faef6c93d247032a8a146015e49ea8fdc | LXSkyhawk/ProjectEuler | /Sum_Square_Difference.py | 198 | 3.671875 | 4 | sum_of_squares = 0
square_of_sum = 0
for x in range(1, 101):
sum_of_squares += x ** 2
square_of_sum += x
square_of_sum **= 2
difference = square_of_sum - sum_of_squares
print(difference)
|
d389ccdb165affecc327bf645a179037622889aa | vijayxtreme/ctci-challenge | /LinkedLists/removeDups.py | 3,152 | 3.84375 | 4 | #RemoveDups
'''
Remove dups from an unsorted linked list.
How would you solve this problem if a temporary buffer is not allowed?
Questions:
- Can I assume that 2 is different from "2"?
- Are we allowing any types to be in LinkedList or is it strict?
- Is this a doubly linked list or singly linked list?
My Idea:
Fill up this linkedlist with different values
Go through each node. If we can use a buffer we can store each node visited. If the node matches what's already in our buffer, we can remove it.
To remove a node, simply just set its current data (value) to the next node, and its next pointer to the next node's pointer.
If it's a doubly linked list then we just want to also update the prev's node's next to be the current node's next, as well as make the curr node's next's prev be the prev node. A little confusing but that's the gist. Same with setting the values.
If we don't have a buffer, then we may need to run a double while loop, one that looks at every node then a second loop that runs ahead and looks at every other node; compares it. This would be O(N^2).
'''
from collections import defaultdict
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class LinkedList:
def __init__(self, node):
self.head = node
self.tail = node
#O(1)
def add(self, node):
tail = self.tail
tail.next = node
self.tail = node
#O(1) helper method
def remove(self, node):
if node.next is not None:
node.data = node.next.data
node.next = node.next.next
else:
node.data = None
node.next = None
# O(N)
def removeNode(self, node):
current = self.head
while current is not None:
#it might be smarter to have a node id
if current.data == node.data:
self.remove(current)
break;
current = current.next
#O(1)
def getHeadValue(self):
print(self.head.data)
#Answer with a buffer
def removeDups(self):
d = defaultdict(lambda : 0)
current = self.head
while current is not None:
if d[current.data] == current.data:
self.remove(current)
d[current.data] = current.data
current = current.next
#Answer without a buffer O(N^2)
def removeDupsNoBuffer(self):
i = self.head
while i is not None:
j = i.next
while j is not None:
if i.data == j.data:
self.remove(j)
j = j.next
i = i.next
#O(N)
def print(self):
next = self.head
out = ""
while next is not None:
if next.data is not None:
out += (str(next.data) + "->")
next = next.next
out += "%"
print(out)
n = Node(1)
ll = LinkedList(n)
ll.add(Node(2))
ll.add(Node(2))
ll.add(Node(3))
ll.add(Node(1))
ll.add(Node(0))
ll.add(Node(4))
ll.add(Node(3))
ll.print()
ll.removeDupsNoBuffer()
ll.print()
|
a7efe663b57f1b7397f6a43aeb12103dacf560ce | ryanlsmith4/space_man | /spaceman1.py | 2,757 | 4 | 4 | import random
letters_guessed = []
correct_guesses = []
my_list = []
low_dash = []
def dictionary_list():
'''
This function reads the entire content of a file and puts
them into a list then splits the dictionary with commas by the /n chars
'''
f = open('dictionary.txt', 'r')
dict_list = f.readlines()
f.close()
dict_list = dict_list[0].split(' ')
return dict_list
# END dictionary_list
def gen_secret_word(list):
'''
This function takes in a sequence || (list) and return one element
in it Using random.choice which becomes the secret_word
'''
secret_word = random.choice(list)
return secret_word
# END gen_secret_word
def guess_letter():
'''
Function to take in user input and verify its valid to be
returned in lowercase form
'''
letter = input("Guess a Letter: ")
if letter == None:
print("can't be null")
elif len(letter) > 1:
print("only one letter please")
letter = letter.lower()
return letter
#END guess letter()
def check_matching(secret_word, guess):
'''
function takes in the user guess and the
secret word and returns true or
false whether the guess matched
'''
match = True
if guess in secret_word:
correct_guesses.append(guess)
else:
match = False
letters_guessed.append(guess)
print("not in secret word")
return match
#END check_matching
def print_game():
'''
Function that draws the game board the length of the secret_word
'''
load_word = "Secret Word: "
for i in low_dash:
load_word = load_word + i + " "
print(load_word)
#END print_game()
def replace_dash(guess, secret_word):
'''Function that replaces the dashes with the corresponding
letters'''
secret_word = list(secret_word)
for i in range(len(secret_word)) :
if guess == secret_word[i]:
low_dash[i] = guess
#END replace_dash
def gen_dash_word() :
'''
Function that turns secret_word into dashes
'''
for i in secret_word:
low_dash.append("_")
# print(low_dash)
# Game loop (Work in progress)
def play_space():
turns = 0
print(secret_word)
while turns < 7:
print_game()
guess = guess_letter()
replace_dash(guess, secret_word)
if check_matching(secret_word, guess) == False:
turns += 1
elif "".join(correct_guesses) == secret_word:
print("You WIN")
return
print(turns)
#END play space
#assign secret_word using gen_secret_word()
secret_word = gen_secret_word(dictionary_list())
gen_dash_word()
# print(secret_word)
play_space()
#shout out to Alex Bogert for unblocking me on this project
|
85d432cbce0229ce4cc63caf853a7063dc37d3fd | PrinceGumede20/100daycodechallenge | /myrnn.py | 2,963 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 18 18:13:23 2019
@author: Prince
"""
#data preprocessing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset_train =pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:, 1:2].values
#Feature Scalling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(0,1))
training_set_scaled = sc.fit_transform(training_set)
#creating a data structure with timesteps and 1 output
#we going to look at 3 months worth of data before making a prediction
X_train =[]
y_train =[]
for i in range(60,1258):
X_train.append(training_set_scaled[i-60:i, 0])
y_train.append(training_set_scaled[i, 0])
X_train,y_train = np.array(X_train) , np.array(y_train)
#Add new dimension in a numpy array using reshape
X_train = np.reshape(X_train, (X_train.shape[0],X_train.shape[1],1))
#RNN CODE
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
#inititialising the RNN
regressor = Sequential()
#Adding the first LSTM layer and Dropout regularisation to prevent overfitting
regressor.add(LSTM(units = 50, return_sequences =True , input_shape =(X_train.shape[1],1)))
regressor.add(Dropout(0.2))
#second LSTM layer
regressor.add(LSTM(units = 50, return_sequences =True ))
regressor.add(Dropout(0.2))
#third LSTM layer
regressor.add(LSTM(units = 50, return_sequences =True ))
regressor.add(Dropout(0.2))
#fourth LSTM layer
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))
#Adding the output layer
regressor.add(Dense(units = 1))
#Compling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
#Fitting the RNN TO THE trainingset
regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)
#making the predictions and visualising the results
#Getting the real stock price
dataset_test =pd.read_csv('Google_Stock_Price_Test.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values
#Getting the predicted Stock price
dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)
inputs = dataset_total[len(dataset_total)-len(dataset_test) - 60 :].values
inputs = inputs.reshape(-1, 1)
inputs =sc.transform(inputs)
X_test =[]
for i in range(60,80):
X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
predicted_stock_price =regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)
#Visualising the results
plt.plot(real_stock_price, color ='red', label = 'Real Google Stock Price')
plt.plot(predicted_stock_price, color ='blue', label = 'Predicted Google Stock Price')
plt.title('Google Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
|
76a54be82c232ed4329609118e76666847a9f6b8 | RAmruthaVignesh/PythonHacks | /FileOperations/stream_textfile.py | 658 | 3.84375 | 4 | def stream_textfile_1(path):
'''This function takes in the path input.
It reads the entire file and returns each line in a list'''
file_x = open(path,'rw+')
lines = file_x.readlines()
lines = [line.strip('\n') for line in lines]
return lines
textfile_1=stream_textfile_1("../FileOperations/sampletext.txt")
def stream_textfile_2(path):
'''This function takes in the path of the file.
It reads the entire file and
returns the generator object of all the lines of the file.'''
lines =open(path, 'rw')
for line in lines:
yield line
text_file_2 = stream_textfile_2("../FileOperations/sampletext.txt")
|
d6e47eca3162c3ac9f953d6e67c467e273e202fb | mi-kei-la/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 364 | 3.890625 | 4 | #!/usr/bin/python3
"""This is a single class module.
MyList is a subclass of the class List.
"""
class MyList(list):
"""This class is inherited from the class list.
Methods:
print_sorted: prints the list items in ascending order.
"""
def print_sorted(self):
"""Print int list in ascending order."""
print(sorted(self))
|
ffa458f2dd6d1327b0514ee0b70bb4fbc4cafcde | raushancena/Leetcode_April | /Search_in_rotated_sorted_array.py | 834 | 3.90625 | 4 | #Function to finding minimum element in nums:-
def f(nums,left,right):
print(nums)
while(left<right):
mid=left+(right-left)//2
if(nums[mid]>nums[right]):
left=mid+1
else:
right=mid
return left
#Function to find target in nums:-
def bs(nums,left,right,target):
while(left<=right):
t,t1=left,right
mid=left+(right-left)//2
if(nums[mid]==target):
return mid
elif(nums[mid]<target):
left=mid+1
else:
right=mid-1
return -1
class Solution:
def search(self, nums: List[int], target: int) -> int:
if(len(nums)==0):
return -1
a=f(nums,0,len(nums)-1)
if(target>=nums[a] and target<=nums[-1]):
x=bs(nums,a,len(nums)-1,target)
else:
x=bs(nums,0,a,target)
return x
|
a1ce476ad12f5b6c729a25d224844db2f4ecce14 | DeadCereal/HackerRankCode | /Python3/WarmUps/ManasaAndStones.py | 430 | 3.59375 | 4 | numcases = int(input())
for _ in range(numcases):
numstones = int(input())-1
one = int(input())
two = int(input())
b = max(one,two)
a = min(one,two)
difference = b-a
maxval = b*numstones
current = a*numstones
if(a==b):
print(str(current))
else:
while(current <= maxval):
print(str(current) + " ", end="")
current += difference
print("")
|
c6823778f5f24194b0de575adf44630c93b78bf3 | EnthusiasticTeslim/MIT6.00.1x | /other/HanoiTowers.py | 416 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 04:30:29 2019
@author: olayi
"""
def printMove(fro,to):
print('move from' + str(fro) + " to " + str(to))
def Towers(n, fro, to, spare):
if n == 1:
printMove(fro, to)
else:
Towers(n-1, fro, spare, to)
Towers(1, fro, to, spare)
Towers(n-1, spare, to, fro)
print(Towers(4, 'P1', 'P2', 'P3')) |
b2ea73a1b6a04800d2e27c7c950d805f69c8e809 | SUTDNLP/ZPar | /scripts/ccg/evaluate/filterdeplen.py | 723 | 3.671875 | 4 | import sys
def filterdeplen(path, lower, upper):
file = open(path)
for line in file:
line = line[:-1]
if line.startswith('#') or line.startswith('<c>') or not line:
print line
continue
words = line.split()
#assert len(words)==5
words[0] = words[0].split('_')
assert len(words[0]) == 2
pos1 = int(words[0][1])
words[3] = words[3].split('_')
assert len(words[3]) == 2
pos2 = int(words[3][1])
size = abs(pos2 - pos1)
if size >= lower and size<=upper:
print line
file.close()
if __name__ == '__main__':
path = sys.argv[1]
lower = int(sys.argv[2])
upper = int(sys.argv[3])
filterdeplen(path, lower, upper)
|
ac471c8fc3c189131417b9e6aef5acf87d9eae74 | IslamAyesha/Assignments | /OTP GENERATOR.py | 189 | 3.546875 | 4 | import random as r
import string
length = 6
OTP = ' '
characters = string.ascii_letters + string.digits
for i in range(length):
OTP = OTP + r.choice(characters)
print('OTP:',OTP) |
0b89a776ed59d3b23aac2dede7f13c52e63ef436 | gnavink/Python | /3_OOP/oop6.py | 1,101 | 4.0625 | 4 | #oop6.py
#Illustrates:
# i) Dunder Methods: __repr__, __str__
# ii) __add__, __len__
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
def __repr__(self):
return f'Employee({self.first},{self.last},{self.pay})'
def __str__(self):
return f'{self.fullname()} - {self.email}'
def __add__(self,other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
if __name__ == '__main__':
emp_1 = Employee('Navin','Kumar',50000)
#1) repr, str
# print(emp_1)
# print(str(emp_1))
# print(repr(emp_1))
#2) Add two employee instances
#emp_2 = Employee('Gnana','Prakash',80000)
#print(emp_1 + emp_2)
#3) __len__
print(emp_1.fullname(), len(emp_1))
|
0408fb192baec6ff32c7d03f1fb9fb2ee763c2d8 | AnoopMasterCoder/python-course-docs | /6. Chapter 6/09_pr_07.py | 138 | 4.09375 | 4 | text = input("Enter your text: ")
if 'harry' in text.lower():
print("Yes harry is present")
else:
print("No harry is not present") |
5f1fd007a134244189f0ef127687858aedc0823a | Prashant-Bharaj/A-December-of-Algorithms | /December-27/python_crytotech.py | 532 | 3.796875 | 4 | def VowelSquare(a):
for i in range(len(a)):
for l in range(len(a[i])):
if a[i][l] in 'aeiou' and a[i][l+1] in 'aeiou' and a[i+1][l] in 'aeiou' and a[i+1][l+1] in 'aeiou':
return 'Top left Position of vowel square:' + str(i) + '-' + str(l)
return 'Unavailable'
lis=input("Enter 2Dmatrix (seperated by commas )")
c=lis.split(",")
print(c)
print("The Matrix should be: ")
for i in c:
for j in range(len(i)):
print(i[j],end=" ")
print(sep="\n")
print(VowelSquare(c))
|
4e02e01ecf358c5b8dfa3d5a4be95468c0fb61e4 | gh4masha/dive_into_python | /dive_into_python/week4/week04_01.py | 1,478 | 3.5625 | 4 | import os
import tempfile
class File:
file_name=''
def __init__(self, file_name):
self.file_name=file_name
def __add__(self, other):
with open(os.path.join(tempfile.gettempdir(), 'storage.data'),"w") as resfile:
with open(self.file_name,'r') as f1:
resfile.write(f1.read())
with open(other.file_name) as f2:
resfile.write(f2.read())
return File(os.path.join(tempfile.gettempdir(), 'storage.data'))
# tempfile.gettempdir
def __str__(self):
return self.file_name
def write(self, text):
with open(self.file_name,'a+') as f:
f.write(text)
lines=[]
cur_ind=-1;
def __iter__(self):
self.cur_ind=-1
with open(self.file_name,'r') as f:
self.lines = f.readlines()
return self
def __next__(self):
self.cur_ind+=1
if self.cur_ind <len(self.lines):
return self.lines[self.cur_ind]
raise StopIteration
# obj = File('/home/masha/dive_into_python/dive_into_python/week3/coursera_week3_cars.csv')
#
# obj.write('line')
#
# first = File('/home/masha/dive_into_python/dive_into_python/week3/coursera_week3_cars.csv')
# second = File('/home/masha/dive_into_python/dive_into_python/week3/week03_02.py')
#
# new_obj = first + second
#
#
# for line in File('/home/masha/dive_into_python/dive_into_python/week3/coursera_week3_cars.csv'):
# print(line)
#
#
# print(obj) |
b737f9fdf7d83168cfa873ed2c39029c682ff75d | neba9/data-structures-and-algorithms | /python/array_shift/array_shift.py | 99 | 3.828125 | 4 | my_list = [1,2,4,5] # Insert the number 3 between the 2 and the 4
my_list[2:1] = [3]
print(my_list) |
f31412d63b03737056ab84c4af30308bf984e4ca | parulmehtaa/new_rep | /08_07_print_armstrong_numbers_till_n.py | 614 | 4.125 | 4 | def count_the_digits(n):
j=1
i=0
while (n//j)>=1:
i=i+1
j=j*10
return i
def power_num(n,num_digits):
sum=0
sum=n**num_digits
return sum
def is_strong(n):
i=n
rem=0
sum=0
fac=0
num_digits=count_the_digits(n)
while i>0:
rem=i%10
fac=power_num(rem,num_digits)
sum=sum+fac
i=i//10
if sum==n:
return 1
else:
return 0
def main():
n=int(input("Enter the value of n"))
for num in range(1,n+1,1):
if is_strong(num):
print(num)
main() |
d7e6bfc489782f1789c0fdb1389958224e83414e | loisaidasam/adventofcode | /2015/day05/solution1.py | 1,110 | 3.828125 | 4 |
import sys
def _num_vowels(input_str):
vowels = set(['a', 'e', 'i', 'o', 'u'])
vowels_found = [char for char in input_str if char in vowels]
return len(vowels_found)
def _has_repeating_char(input_str):
last_char = None
for char in input_str:
if char == last_char:
return True
last_char = char
return False
def _has_forbidden_strings(input_str):
FORBIDDEN_STRS = ('ab', 'cd', 'pq', 'xy')
for forbidden_str in FORBIDDEN_STRS:
if forbidden_str in input_str:
return True
return False
def _is_nice(input_str):
return (_num_vowels(input_str) >= 3 and
_has_repeating_char(input_str) and
not _has_forbidden_strings(input_str))
def num_nice(input_strs):
result = 0
for input_str in input_strs:
if _is_nice(input_str):
result += 1
return result
if __name__ == '__main__':
"""
$ python solution1.py input.txt
Found 238 nice strings
"""
with open(sys.argv[1], 'r') as fp:
result = num_nice(fp)
print "Found %s nice strings" % result
|
f6cbc82ac8e769cc3269d21f5a40dd5229074a68 | DreamDZhu/python | /week-3/day22_面向对象/人狗大战.py | 1,753 | 3.78125 | 4 | import random
import time
class Dog:
def __init__(self, name, blood, ad, kind):
self.dog_name = name
self.hp = blood
self.ad = ad
self.kind = kind
self.random = 10
# 舔舔攻击
def lick(self, person): # 方法,拥有一个必须传的参数 --> self
hit = random.randint(1, self.random)
person.hp -= hit
print(self.lick_format(self.dog_name, person.person_name, hit))
def lick_format(self, dog_name, person_name, hit):
return f"{dog_name}舔了一口{person_name},对其造成了{hit}点伤害"
class Person:
def __init__(self, name, blood, ad, kind):
self.person_name = name
self.hp = blood
self.ad = ad
self.kind = kind
self.random = 20
# 普通攻击
def fight(self, dog):
hit = random.randint(1, self.random)
dog.hp -= hit
print(self.fight_format(self.person_name, dog.dog_name, hit))
def fight_format(self, person_name, dog_name, hit):
return f"{person_name} 打了{dog_name}一拳,对其造成了{hit}点伤害"
alex = Person('alex', 1000, 10, "未知")
dog = Dog('小黑', 5000, 50, "泰迪")
print("人狗大战开始!")
flag = True
while True:
time.sleep(1)
if flag:
alex.fight(dog)
print(f"{alex.person_name}剩余{alex.hp}血量")
print("==================================")
flag = False
if alex.hp <= 0:
print("over ,alex die")
break
else:
dog.lick(alex)
print(f"{dog.dog_name}剩余{dog.hp}血量")
print("==================================")
flag = True
if dog.hp <= 0:
print("over, dog die")
break
|
0fa615a791e1fe97ddc7ca8bf9f73393235bbb74 | WalczRobert/Module10 | /invoice_class/__init__.py | 2,067 | 4.09375 | 4 | """
Robert Walczak"""
#Write an Invoice class with the following data members, which are identified as required or optional in the constructor.
# invoice_id - required
# customer_id - required
# last_name - required
# first_name - required
# phone_number - required
# address - required
# items_with_price - dictionary, optional
class Invoice:
def __init__(self, invoice_id, customer_id, last_name, first_name, phone_number, address,
items_with_price={}):
self.__invoice_id = invoice_id
self.__customer_id = customer_id
self.__last_name = last_name
self.__first_name = first_name
self.__phone_number = phone_number
self.__address = address
self.items_with_price = items_with_price
def __str__(self):
return 'Invoice ID: ' + str(self.__invoice_id) + 'Customer ID: ' + str(self.__customer_id) + 'Name' + \
self.__first_name + " " + self.__last_name + 'Phone Number: ' + self.__phone_number + 'Address: ' + \
self.__address + "Price List" + str(self.items_with_price)
def __repr__(self):
return 'Invoice ID: ' + str(self.__invoice_id) + 'Customer ID: ' + str(self.__customer_id) + 'Name' + \
self.__first_name + " " + self.__last_name + 'Phone Number: ' + self.__phone_number + 'Address: ' + \
self.__address + "Price List" + str(self.items_with_price)
def add_item(self, new_item):
self.items_with_price.update(new_item)
def create_invoice(self):
prdict = self.items_with_price
tax = round(sum(prdict.values()) * .06, 2)
total = sum(prdict.values()) + tax
for key in prdict:
print(key + "..... $" + str(pdict[key]))
print("Tax......... " + "{0:.2f}".format(tax))
print("Total....... " + "{0:.2f}".format(total))
# Driver code
invoice = Invoice(1, 123, '1313 Disneyland Dr, Anaheim, CA 92802' ,'Mouse', 'Minnie', '555-867-5309')
invoice.add_item({'iPad': 799.99})
invoice.add_item({'Surface': 999.99})
invoice.create_invoice()
|
f49a136c237cb9dfa6b250a2ced776131672fc39 | julianalvarezcaro/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 418 | 3.6875 | 4 | #!/usr/bin/python3
"""Finds the minimun operations needed to have a given amount of H characters
"""
from math import sqrt
def minOperations(n):
min_ops = 0
if n <= 1:
return 0
for i in range(2, int(sqrt(n) + 1)):
while n % i == 0:
min_ops += i
n = n / i
if n <= 1:
break
if n > 1:
min_ops += int(n)
return min_ops
|
cfa1d8b38e5835b0884e2f34f411e97e3044bead | vipulsingh24/Python | /File_Handling.py | 4,847 | 4.03125 | 4 | # fp = open('test.txt')
# print(fp.read())
# fp.close()
# ------------------------------------
# with open('test.txt') as fp:
# buffer = fp.read()
# print(buffer)
# ---------------------------------------
# fp = open("test.txt")
# while True:
# buffer = fp.readline()
# if buffer == '':
# break
# print(buffer)
# fp.close()
# --------------readline()---------------------------
# Displays only those lines that contain the word
# fp = open("test.txt")
# while True:
# buffer = fp.readline()
# if 'methods' in buffer:
# print(buffer)
# if buffer == '':
# break
# fp.close()
# --------------readlines()-----------------------------
# fp = open('test.txt')
# buffer = fp.readlines() # Create a list of strings including \n at the end of each string
# print(buffer)
# for line in buffer:
# print(line, end='') # end ='', tells print that don't go to next line after each print.
# fp.close()
# ---------------------------------------------------------
# For large file you shoudn't use read() or readlines() methods,
# it may lead to memory problem. You should read a file line
# by line with the readline() method.
# fp = open('test.txt')
# count = 0
# while count < 2:
# buffer = fp.readline()
# if buffer == '':
# break
# print(buffer, end='')
# count += 1
# fp.close()
# ---------------------------------------------------
# Count the occurence of word in a file
# fp = open('test.txt')
# word = 0
# while True:
# buffer = fp.readline()
# if 'methods' in buffer:
# word += 1
# if buffer == '':
# break
# print(word)
# fp.close()
# -----------------writing a file--------------------------------
# fp = open('test_write.txt', 'w')
# while True:
# text = input('Enter a line of text: ')
# if text == '':
# break
# fp.write(text+'\n')
# fp.close()
#
# fp = open('test_write.txt')
# buffer = fp.read()
# fp.close()
# print(buffer)
# ------------------------------------------------------
# Copying one file contents to another
# fp = open('test.txt')
# fp_new = open('test_copy.txt', 'w')
# while True:
# buffer = fp.readline()
# fp_new.write(buffer)
# if buffer == '':
# break
# fp_new.close()
# fp.close()
# with open('test_copy.txt') as fp:
# buffer = fp.read()
# print(buffer)
# --------------------------------------------------
# Copy the contents of file and reverse it and store the
# the new reverse text to new file
# fp = open('test.txt')
# fp_new = open('test_reverse.txt', 'w')
# while True:
# buffer = fp.readline()
# if buffer == '':
# break
# fp_new.write(buffer[::-1]) # [start:end:step]
# fp_new.close()
# fp.close()
# with open('test_reverse.txt') as fp:
# buffer = fp.read()
# print(buffer)
# -----------------Appending a file-----------------------------------
# filename = 'test.txt'
#
# def displayContents(f):
# fp = open(f)
# print(fp.read())
# fp.close()
#
# displayContents(filename)
#
# fp = open('test.txt', 'a')
# while True:
# text = input('Enter a line of text: ')
# if text == '':
# break
# fp.write(text + '\n')
# fp.close()
#
# displayContents(filename)
# -----------------os.path module----------------------------------
# exists() - gets a path as argument and return True if that path exists, otherwise False
# from os.path import exists
#
# if exists('test.txt'):
# print('test text file exists')
# else:
# print('test text file doesn\'t exist')
# -----------------listdir() and join()---------------------------
# from os import listdir, getcwd
# from os.path import join
#
# filelist = listdir('.')
# for name in filelist:
# pathname = join(getcwd(), name)
# print(pathname)
# -----------------basename()-------------------------------
# basename extracts the filename from path
# from os.path import basename
# print(basename('/home/vipu/Projects/Git/Python/test.txt'))
# -----------------dirname()-------------------------------------
# dirname, extracts the directory name from a path
# from os . path import dirname
# print ( dirname ( "/System/Home/readme .txt" ))
# -----------------getsize()------------------------------------
# getsize, gets the size of the file that is passed
# from os.path import getsize
#
# num_bytes = getsize('/home/vipul/Projects/Git/Python/test.txt')
# print(str(num_bytes)+'bytes')
# ----------------------------------------------------
# Adds up the sizes of all the files in the current directory
# from os import listdir
# from os.path import getsize
#
# filelist = listdir('.')
# totalSize = 0
# for i in filelist:
# totalSize += getsize(i)
# print(totalSize)
# -----------------File Encoding----------------------------
# from sys import getfilesystemencoding
#
# print(getfilesystemencoding())
|
e5da29e5e28e58d13105585dd1b552bdf822a628 | Alexkaer/dailyleetecode | /day003.py | 1,654 | 3.921875 | 4 | """
地址:https://leetcode.com/problems/merge-sorted-array/description/
描述:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
思路:
这道题目其实和基本排序算法中的merge sort非常像,但是 merge sort 很多时候,合并的时候我们通常是 新建一个数组,这样就很简单。 但是这道题目要求的是原地修改.
这就和 merge sort 的 merge 过程有点不同,我们先来回顾一下 merge sort 的 merge 过程。
merge 的过程可以是先比较两个数组的头元素,然后将较小的推到最终的数组中,并将其从原数组中出队列。 循环直到两个数组都为空。
"""
class Solution:
@staticmethod
def merge(nums1, m, nums2, n):
nums1_copy = nums1[:m]
nums1[:] = []
p1 = p2 = 0
while p1 < m and p2 < n:
if nums1_copy[p1] < nums2[p2]:
nums1.append(nums1_copy[p1])
p1 += 1
else:
nums1.append(nums2[p2])
p2 += 1
if p1 < m:
nums1[p1 + p2:] = nums1_copy[p1:]
if p2 < n:
nums1[p1 + p2:] = nums2[p2:]
return nums1
print(Solution.merge([1, 3, 5, 7], 4, [2, 4, 6, 8, 10, 12], 6))
print(Solution.merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3))
|
7a011dc1d165b1950a20fc5b95980e305bc4e9f0 | seanxu229/LeetCodeSummary | /数据结构实现/BinarySearch.py | 543 | 3.796875 | 4 | '''前提是排好序了,有序的顺序表,必须相邻,即顺序表,不能是链条'''
def binary_search(alist,item):
n=len(alist)
if n>0:
mid=n/2
if alist[mid]==item:
return True
elif item<alist[mid]:
binary_search(alist[:mid],item)
else:
binary_search(alist[mid+1:],item)
return False
def binary_search1():
#not recursion
n=len(alist)
first=0
last=n-1
while first<=last:
mid=(first+last)//2
if alist[mid]==item:
return True
elif alist[mid]<item:
first=mid+1
else:
last=mid-1
return False |
1c4318dd68fbeba4831586cd344ac09a7bf81d1f | ChupaChupaChups/Automatic-marking-system | /Documents/문제종류/sorting_answer.py | 3,214 | 3.859375 | 4 |
## ===================== Binary Search ==========================
def bSearch(L, e, low ,high):
if high - low < 2:
return L[low] == e or L[high] == e
mid = low + int((high - low)/2)
if L[mid] == e:
return True
if L[mid] > e:
return bSearch(L, e, low, mid-1)
else:
return bSearch(L, e, mid+1, high)
## ====================== Selection Sorting ======================
def selSort(L):
"""Assume that L is a list of elements that can using >. Sorts L in ascending order"""
for i in range(len(L)-1):
#Invariant: the list L[:i] is sorted
minIndex = i
minVal = L[i]
j = i + 1
while j < len(L):
if minVal > L[j]:
minIndex = j
minVal = L[j]
j += 1
#change position L[minIndex] -> L[i], L[i] -> L[minIndex]
temp = L[i]
L[i] = L[minIndex]
L[minIndex] = temp
print ("Partially sorted list = ", L)
##L = [35, 4, 5, 29, 17, 58, 0]
##selSort(L)
##print ("Sorted List= ",L)
## ========== Binary Search =====================
##findValue=int(input("Enter Value: "))
##print ("Binary Search= ", bSearch(L, findValue, 0, len(L)))
## ======================== Merge Sorting ===========================
def merge(left, right, lt):
"""Assume left and right are sorted lists.
lt defines an ordering on the elements of the lists.
Returns a new sorted(by lt) list containing the same elements
as (left+right) would contain."""
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if lt(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
def sort ( L , lt = lambda x, y: x < y):
"""Returns a new sorted list containing the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = int(len(L)/2)
left = sort(L[:middle], lt)
right = sort(L[middle:], lt)
print ("About to merge ", left, "and ", right)
return merge(left, right, lt)
##L = [35, 4, 5, 29, 17, 58, 0]
##newL = sort(L)
##print ("Sorted List= ", newL)
##L = [1.0, 2.25, 24.5, 12.0, 2.0, 23.0, 19.125, 1.0]
##newL = sort(L, float.__lt__)
##print ("Sorted List= ", newL)
# python 2.7
# import string
# string.split( Str, ' ')
# python 3.4
# Str.split(' ')
def lastName_FirstName(name1, name2):
name1 = name1.split(' ')
name2 = name2.split(' ')
if name1[1] != name2[1]:
return name1[1] < name2[1]
else:
return name1[0] < name2[0]
def firstName_LastName(name1, name2):
name1 = name1.split(' ')
name2 = name2.split(' ')
if name1[0] != name2[0]:
return name1[0] < name2[0]
else:
return name1[1] < name2[1]
##L = ["John Guttang", "Tom Brady", "Chancellor Grimson", "Gisele Brady", "Big Julie"]
##newL = sort(L, lastName_FirstName)
##print ("Sorted List= ",newL)
##newL = sort(L, firstName_LastName)
##print ("Sorted List= ",newL)
|
ad0452ce1add3e006c9c45d9ba5a71c87f9d72ca | sanchitahuja/CodingPractice | /leetcode/left_right_target.py | 616 | 3.5625 | 4 | import bisect
from typing import *
class Solution:
def find_left_most_value(self, arr, x):
i = bisect.bisect_left(arr, x)
if i < len(arr) and i != -1 and arr[i] == x:
return i
else:
return -1
def find_right_most_value(self, arr, x):
i = bisect.bisect_right(arr, x)
if len(arr) + 1 > i > 0 and arr[i - 1] == x:
return i - 1
else:
return -1
def searchRange(self, nums: List[int], target: int) -> List[int]:
return [self.find_left_most_value(nums, target), self.find_right_most_value(nums, target)]
|
f0bf8d62d136e561536e27456024c81a9dbd7faf | PQCuongCA18A1A/Ph-m-Qu-c-C-ng_CA18A1A | /PhamQuocCuong_44728_CH03/Exercise/page_72_exercise_04.py | 312 | 3.8125 | 4 | """
Author: Phạm Quốc Cường
Date: 8/9/2021
Problem:
Write a loop that outputs the numbers in a list named salaries. The outputs should be formatted in a column that is right-justified,
with a field width of 12 and a precision of 2.
Solution:
"""
a = 10000
b = 20000
print("%12.2f$ %12.2f$" % (a, b)) |
6931feec4e641ddd9ffe73db230833ff47a3a1d7 | maxwagner440/python_patterns | /Singleton.py | 687 | 3.765625 | 4 | class B:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(B):
"""This class inherits from the B class every time its instantiated which allows access to the _shared_state object that is global"""
def __init__(self, **kwargs):
B.__init__(self)
self._shared_state.update(kwargs)
def __str__(self):
return str(self._shared_state)
sing1 = Singleton(HTTP = "Hyper Text Transfer Protocol")
print(sing1)
sing2 = Singleton(TEST = "TEST")
# Every Singleton object will have access to the updated _shared_state so sing1 and sing2 will have two key-value pairs here
print(sing1)
print(sing2)
|
977e98db9bc822e2c09627d93289be47a54b2d3f | py2k5/PyGeneralPurposeFunctions | /linkedList_newway.py | 2,142 | 4.0625 | 4 | class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def insert(self, newNode ):
temp = newNode
temp.next = self.head
self.head = temp
def delete(self,data):
if self.head is None:
print("Nothing to delete")
return
current = self.head
previous = self.head
while True:
if current is None:
break
if current.data == data:
previous.next = current.next
previous = current
current = current.next
def printList(self):
if self.head is None:
print("List is empty")
return
current = self.head
while True:
if current is None:
break
print(current.data)
current = current.next
# Returns data at given index in linked list
def getNth(self, index):
current = self.head # Initialise temp
count = 0 # Index of current node
# Loop while end of linked list is not reached
while (current):
if (count == index):
return current.data
count += 1
current = current.next
# if we get to this line, the caller was asking
# for a non-existent element so we assert fail
assert(false)
return 0;
n1 = Node(10)
ll = LinkedList()
ll.delete(90)
ll.insert(n1)
n2 = Node(20)
ll.insert(n2)
n2 = Node(30)
ll.insert(n2)
n2 = Node(30)
ll.insert(n2)
n2 = Node(50)
ll.insert(n2)
print("Before delete")
ll.printList()
ll.delete(90)
print("after delete")
ll.printList()
|
c3dec6c1bc32c1277aa21ee8984b1e4745e9d7ce | trace7729/Intermediate-Python | /Lab 6 Multiprocessing/Lab06.py | 3,881 | 4 | 4 | from threading import Semaphore, Thread, Lock
from queue import Queue, Empty
from random import randint
from time import sleep
from os import system, name
# Python II - Lab 6 - Annie Yen
max_customers_in_bank = 10 # maximum number of customers that can be in the bank at one time
max_customers = 30 # number of customers that will go to the bank today
max_tellers = 3 # number of tellers working today
teller_timeout = 10 # longest time that a teller will wait for new customers
class Customer():
''' Customer objects that each has name attribute'''
def __init__(self, name):
self.name = name
def __str__(self):
return f"{self.name}"
class Teller():
''' Teller objects that each has name attribute'''
def __init__(self, name):
self.name = name
def __str__(self):
return f"{self.name}"
def bankprint(lock, msg):
'''
Print commands
Args:
lock: Lock()
msg: string
Returns:
None
'''
lock.acquire()
try:
print(msg)
finally:
lock.release()
def wait_outside_bank(customer, guard, teller_line, printlock):
'''
Thread function for Customer object
Args:
customer: Customer object
guard: Semaphore
teller_line: Queue
printlock: Lock()
Returns:
None
'''
bankprint(printlock,f"{customer} is waiting outside the bank")
try:
bankprint(printlock,f"<G> Security guard letting {customer} into the bank")
guard.acquire()
bankprint(printlock, f"(C) {customer} is trying to get into line")
teller_line.put(customer)
#guard.release()
except Exception as Error:
print("Cannot put {customer} into line " +str(Error))
def teller_job(teller, guard, teller_line, printlock):
'''
Thread method for Teller object
Args:
teller: Teller object
guard: Semaphore
teller_line: Queue
printlock: Lock()
Returns:
None
'''
bankprint(printlock, f"[T] {teller} has started working")
while True:
try:
#guard.acquire()
customer = teller_line.get(timeout=teller_timeout)
bankprint(printlock, f"[T] {teller} is now helping {customer}")
sleep(randint(1,4))
bankprint(printlock, f"[T] {teller} is done helping {customer}")
bankprint(printlock, f"<G> Security is letting {customer} out of the bank")
guard.release()
except Empty:
bankprint(printlock, f"[T] No one is in line, {teller} is going on a break")
break
if __name__ == '__main__':
printlock = Lock()
teller_line = Queue(maxsize=max_customers_in_bank)
guard = Semaphore(max_customers_in_bank)
bankprint(printlock, "<G> Security guard starting their shift")
bankprint(printlock, "*B* Bank open")
# create list of Customer objects and pass to thread method
customers = [Customer("Customer " +str(i)) for i in range(1, max_customers+1)]
for i in range(0, len(customers)):
customer_thread = Thread(name=f"customers[i]", target = wait_outside_bank, args =(customers[i],guard, teller_line, printlock))
customer_thread.start()
sleep(5)
bankprint(printlock, "*B* Tellers started working")
# create a list of Teller objects and pass to thread method in another list
tellers = [Teller("Teller "+str(i)) for i in range(1,max_tellers+1)]
tellers_list = [Thread(name=f"tellers[i]", target = teller_job, args = (tellers[i], guard, teller_line, printlock)) for i in range(0,len(tellers))]
for teller in tellers_list:
teller.start()
for teller in tellers_list:
teller.join()
bankprint(printlock, "*B* Bank closed")
|
2c35834075de8091faa64f823df594a350698fd7 | shiningPanther/Project-Euler | /Problem28.py | 679 | 3.71875 | 4 | '''
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
'''
if __name__ == '__main__':
total = 0
counter = 0
skipSize = 1
skip = 1
for n in range(1,1001*1001+1):
if n == 1:
total+=1
continue
if skip >= 1:
skip-=1
continue
total += n
counter += 1
if counter == 4:
counter = 0
skipSize += 2
skip = skipSize
print(total)
|
8b2866b8788fdd01a495c264a5dc54ff2d554f51 | xixijiushui/Python_algorithm | /algorithm/20-printMatrixInCircle.py | 1,091 | 4.3125 | 4 |
def printMatrixClockwisely(numbers, columns, rows):
if numbers == None or columns <= 0 or rows <= 0:
return
start = 0
while columns > start * 2 and rows > start * 2:
printMatrixInCircle(numbers, columns, rows, start)
start += 1
def printMatrixInCircle(numbers, columns, rows, start):
endX = columns - start - 1
endY = rows - start - 1
# 从左到右打印一行
for i in range(start, endX + 1):
print(numbers[start][i])
# 从上到下打印一列
if start < endY:
for i in range(start+1, endY + 1):
print(numbers[i][endX])
# 从右到左打印一行
if start < endX and start < endY:
for i in range(endX-1, start-1, -1):
print(numbers[endY][i])
# 从下到上打印一列
if start < endX and start < endY:
for i in range(endY - 1, start, -1):
print(numbers[i][start])
# printMatrixClockwisely([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4, 4)
printMatrixClockwisely([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], 4, 3) |
8b4228c7351e3c22e3949813e844ad7f42a58d57 | rupaliwaghmare/python_list | /logicque.py | 326 | 3.640625 | 4 | name=["sharadda","rupali","anita"]
i=0
while i<len(name):
a=len(name[i])
print(name[i],a)
i=i+1
# name=["Sakshi","Rupali","Anita"]
# i=0
# while i<len(name):
# a=len(name[i])
# if a%2==0:
# print(name[i],a,"even number")
# else:
# print(name[i],a,"odd number")
# i=i+1
|
1f48c55eaaad7ff0a7fc4bdb26ebe2f75c0e1869 | livochka/programming-project-semestr2 | /nby_api.py | 1,080 | 3.703125 | 4 | # Module created to get information from National Bank of Ukraine
import urllib.request, urllib.parse, urllib.error
import json
url = 'https://bank.gov.ua/NBUStatService/v1/statdirectory/inflation?period=m' \
'&date='
# Getting consumer price index (CPI) for 2013 and 2015 years in Lvivska obl
date_1 = '201201&json'
date_2 = '201501&json'
ex_1 = urllib.request.urlopen(url + date_1)
ex_2 = urllib.request.urlopen(url + date_2)
data_1 = ex_1.read().decode()
data_2 = ex_2.read().decode()
Lvivska_obl = []
year_1 = json.loads(data_1)
year_2 = json.loads(data_2)
# Adding of info with value 'Total' on key 'mcrd081'
# what means that this is CPI and value '13' on key 'ku'
# what means that this is about Lvivska oblast
for x in year_1:
if x['mcrd081'] == 'Total' and x['ku'] == '13' and x['tzep'] == 'DTPY_':
Lvivska_obl.append([x['dt'], x['value']])
for x in year_2:
if x['mcrd081'] == 'Total' and x['ku'] == '13' and x['tzep'] == 'DTPY_':
Lvivska_obl.append([x['dt'], x['value']])
print(Lvivska_obl) |
e03fce5d01f4a5d5be18bfb7c01d0d9489d457b8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4163/codes/1800_2571.py | 118 | 3.765625 | 4 | a = input("digite")
saida = ""
for i in range(len(a)):
if a[i].lower() != 'a' :
saida = saida + a[i]
print(saida) |
3a54f084e5fe36e69e530afc74d44dcfb8ae4ee6 | SaiKrishnaBV/python-basics | /userDefinedExceptions.py | 691 | 3.859375 | 4 | '''
User defined Exceptions
'''
class Error(Exception):
''' Base class for other exceptions'''
pass
class ValueTooSmallError(Error):
'''Raised when input value is too small'''
pass
class ValueTooLargeError(Error):
'''Raised when input value is too large'''
pass
number = 10
while True:
try:
guess = int(input("Enter a number: "))
if(guess < number):
raise ValueTooSmallError
elif(guess > number):
raise ValueTooLargeError
else:
print("your guess is correct")
break
except ValueTooSmallError:
print("Entered value is smaller than actual number, try again.!!")
except ValueTooLargeError:
print("Entered value is larger than actual number, try again.!!")
|
ce77149ff19356fccbbea7e1ebf57d92cf36a7df | Ankur-singh/computer_vision_book | /_build/jupyter_execute/course_material/02_drawing.py | 7,276 | 4.65625 | 5 | #!/usr/bin/env python
# coding: utf-8
# # More on pixels
#
# In the first part of the notebook, we will learn about accessing and manipulating pixel values. In the second part, we will learn to draw different shapes on an image, using opencv.
# In[1]:
import cv2
import numpy as np
# ## Accessing pixel values
# In[2]:
img = cv2.imread('images/yoda.jpeg')
# Whenever we read an image using `cv2.imread()`, it returns a numpy array. Access values from numpy array is super easy. You can access a single pixel by simply passing its cordinates.
# In[3]:
pixel_00 = img[0, 0]
pixel_00
# To access a region of an image, we can use slicing. For example, this is how we can access the upper-left region of the image
# In[4]:
upper_left_5 = img[:5, :5]
upper_left_5
# to select the lower-right region you can do `img[-5:0, -5:0]`. If you are new to numpy, we would recommend you to checkout [indexing documentation](https://numpy.org/doc/stable/reference/arrays.indexing.html).
#
# 5 x 5 is a very small region to display, so lets select a bigger region.
# In[5]:
upper_left_150 = img[:150, :150]
upper_left_150.shape
# You can think of this as a 150 x 150 image with 3 channels. Lets display it now.
# In[6]:
cv2.imshow('Upper Left corner', upper_left_150)
cv2.waitKey(0)
cv2.destroyAllWindows()
# This process of selecting a small part of an images is also know as **cropping**. It is one of the easiest transformation that you can apply to your images.
# ## Manipulating images
#
# Again, since its just a numpy array, we can simply assign a new value to the pixels. Lets select the upper-left corner and make it blue.
# In[7]:
img[:150, :150] = (255, 0, 0)
# **Note:** OpenCV by default stores pixels in BGR format, not RGB format. So, (255, 0, 0) is blue not red.
#
# when we assign a tuple (of 3 values, representing a color) to the selected region, it is automatically broadcasted to all the pixel in the selected region. This concept is called broadcasting and if you are listening it for the first time, then we recommend you to check [the docs](https://numpy.org/doc/stable/user/basics.broadcasting.html).
#
# Lets have a look at our image after manipulation.
# In[8]:
cv2.imshow('Colored corner', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# We have called these 3 lines multiple times. Lets put them inside a function for future use.
# In[10]:
def imshow(title, img):
cv2.imshow(title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# **Exercise:**
#
# - Try selecting all the 4 corner and color them with different colours.
# - Also, select a 100 x 100 region, in the center of the image and make it white.
# ## Drawing
#
# Using NumPy array slices, we were able to draw a square on our image. But what if we wanted to draw a single line? Or a circle? NumPy does not provide that type of functionality – it’s only a numerical processing library after all!
#
# Luckily, OpenCV provides convenient, easy-to-use methods to draw shapes on an image. We’ll review the three most basic methods to draw shapes: `cv2.line`, `cv2.rectangle`, and `cv2.circle`.
#
# Lets start by defining our canvas. Since images is nothing but a numpy arrays, we can manually define a numpy array with all zeros, and use it as our canvas.
# In[11]:
canvas = np.zeros((500, 500, 3))
# to see how our canvas looks we will use the `show()` function we defined above.
# In[12]:
imshow('canvas',canvas)
# why is our canvas **black**? Think for a second. What are the pixel values?
#
# Lets draw some shapes . . .
# ### Lines
#
# In order to draw a line, we make use of the `cv2.line` method. The first argument to this method is the image we are going to draw on. In this case, it’s our canvas. The second argument is the starting point of the line. We will start our line, at point (0, 10). We also need to supply an ending point for the line (the third argument). We will define our ending point to be (500, 10). The last argument is the color of our line, we will use blue color.
#
# Lets see `cv2.line` in action
# In[13]:
blue = (255, 0, 0)
canvas = cv2.line(canvas, (0, 10), (500, 10), blue)
# Here, we drew a blue line from point (0, 10) to point (500, 10). Lets draw another line with thickness of 2px
# In[14]:
green = (0, 255, 0)
canvas = cv2.line(canvas, (0, 30), (500, 30), green, 2)
# time to look at our image . . .
# In[15]:
imshow('canvas', canvas)
# As you can see, drawing a line is pretty easy. Specify the canvas, start & end point, color, and thickness (optional).
#
# **Note:** Whenever using `cv2.line`, `cv2.rectangle` and `cv2.circle` make sure you use the **OpenCV cordinate system**, not numpy system. Because, [5, 10] in numpy system means 5th row, 10th column. Where as in opencv system, it means 5th column (x-axis) and 10th row (y-axis).
# ### Rectangle
#
# To draw a rectangle, we make use of the `cv2.rectangle` method. `cv2.rectangle` is very similar to `cv2.line`. The only difference is, instead of passing start and end points of the line, we will pass upper-left and lower-right corner of the rectangle.
# In[16]:
red = (0, 0, 255)
canvas = cv2.rectangle(canvas, (0, 50), (300, 100), red, 2)
# In[17]:
imshow('canvas', canvas)
# we have only drawn the outline of a rectangle. To draw a rectangle that is “filled in”, like when using NumPy array slices, we can pass negative thickness.
# In[18]:
red = (0, 0, 255)
canvas = cv2.rectangle(canvas, (10, 70), (310, 120), red, -1)
# In[19]:
imshow('canvas', canvas)
# ### Circles
#
# Drawing circles is just as simple as drawing rectangles, but the function arguments are a little different. To draw a circle, we need two things: center and radius.
# In[20]:
center = (300, 300)
radius = 20
canvas = cv2.circle(canvas, center, radius, blue, 2)
# In[21]:
imshow('canvas', canvas)
# To draw a fill-in circle, just change the thickness from 2 to -1.
#
# Lets make some concentric circles.
# In[22]:
canvas = np.zeros((500, 500, 3))
(centerX, centerY) = (canvas.shape[1] // 2, canvas.shape[0] // 2)
red = (0, 0, 255)
for r in range(0, 175, 25):
canvas = cv2.circle(canvas, (centerX, centerY), r, red)
# In[23]:
imshow('canvas', canvas)
# This is great, we have learned how to draw lines, rectangles and circles in OpenCV. Lets do some fun projects based on this newly acquired skill.
#
# **Exercise:**
# - Make 640 x 640 canvas and make it look like a chess board with alternate white and black squares.
# - Create a canvas, randomly select a point (`center`), randomly select a color (`c`), and finally, randomly select a radius (`r`). Now, make a circle center at `center`, of radius `r` and fill-in color `c`. Repeat it 25 times. Now, does it look **psychedelic**?
# ## Questionaire
#
# - Numpy indexing
# - Broadcasting
# - OpenCV uses which format BGR or RGB? What difference does it make?
# - Which cordinate system is used by `cv2.line`, `cv2.rectangle` and `cv2.circle`; Numpy or OpenCV?
# - How to drawing a line, rectangle and circle?
#
# Make sure you know answers to all these questions before you move ahead in the course.
#
# Its time, we should now start building some useful applications. In the next notebook, we will build a face detector.
|
b70d83b68789fcb0395165b8132717dd93f4bf21 | davelive/Homework | /hw5_David.py | 2,522 | 4.15625 | 4 | """
Problem 1
You have a list, you want to iterate over it and return the numbers that are divisible by 5.
If you iterate over a number larger than 500, stop the loop.
"""
list = [5, 11, 30, 45, 175, 99, 106, 300, 490, 512, 890, 1000]
N = 5
for num in list:
if(num%N==0 and num <= 500):
print (num)
"""
Problem 2
Create a loop to print the reverse of a list.
"""
list1 = [1, 2, 3, 4, 5]
for i in range(len(list1) // 2):
list1[i], list1[-1 - i] = list1[-1 - i], list1[i]
print(list1)
"""
Problem 3
Write a function to get a number and return the factorial of the number. Use loops.
ex. factorial of 5 is 1*2*3*4*5
You can't count factorial of negative numbers, and the factorial of 0 is 1.
"""
def fac(n):
if n == 0:
return 1
else:
return n * fac(n-1)
n = int(input("Enter a number: "))
"""
Problem 4
Write a code that would print list items that are at even positions.
ex. in list = [10, 11, 12], 10 is at index 0, 11 - index 1 (odd), 12 - index 2 (even)
Use loops.
"""
test_list = [10, 11, 12, 13, 14, 15, 16]
odd = []
even = []
for i in range(0, len(test_list)):
if i % 2:
even.append(test_list[i])
else:
odd.append(test_list[i])
res1 = odd
res2 = even
print("Odd numbers list: " + str(res1))
print("Even numbers list: " + str(res2))
"""
Problem 5
Write a function that gets a list of names and returns the ones that start with A.
Notice that some list items begin and end with spaces, or start with @. Get rid of space and @ before printing the name.
"""
def problem5(names):
for x in names:
num1 = (x.replace("@"," "))
num2 = (num1.strip())
for y in num2:
if y[0] == "A":
print(num2)
names = [' Anna', "Lily", " Anahit ", "@Bob", "@Ani@", " Luiza@", "@@Armen"]
problem5(names)
"""
Problem 6
Write a program that checks if a number is prime (պարզ) or not. Try not to google. :)
"""
num = int(input("Enter the number to checks if it's prime or not: "))
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
"""
Problem 7 (OPTIONAL)
Write a loop that will print this pattern.
*
* *
* * *
* * * *
* * * * *
Hint: print("\r") -> for printing on a new line,
print('*', end=' ') -> for printing on the same line
"""
tox = 5
for i in range(0, tox):
for j in range(0, i + 1):
print("*", end=' ')
print("\r") |
84fc179f24bc8f2811b45e36f0cc89fc731e945f | IAmAbszol/DailyProgrammingChallenges | /Problem_102/problem.py | 604 | 3.78125 | 4 | '''
1,2,3,4,5 sum = 9
^
^
9
'''
# Bounding problem when right += 1 occurs, then accesses list.
def problem(arr, k):
if arr is None:
return arr
if k < arr[0]:
return None
left = 0
right = 0
# Since 1,1 is not in the array, only a single.
total_sum = arr[left]
while left < len(arr) and right < len(arr):
if total_sum == k:
return arr[left:right + 1]
# Move right up & add value.
elif total_sum < k:
right += 1
total_sum += arr[right]
# Decrement value && move left up.
elif total_sum > k:
total_sum -= arr[left]
left += 1
print(problem([1,2,3,4,5],9))
|
33b665b0e6bce8e6e6e1f41600f3955c7ddce26b | spearfish/python-crash-course | /practice/04.11_pizzas.py | 326 | 4.0625 | 4 | #!/usr/bin/env python3
my_pizzas = ['pepperoni', 'cheeze', 'beef']
friend_pizzas = my_pizzas[:]
my_pizzas.append('chilli')
friend_pizzas.append('hawai')
print("My favorite pizzas are : ")
for pizza in my_pizzas :
print(pizza)
print("My friend's favorite pizzas are : ")
for pizza in friend_pizzas :
print(pizza)
|
97be8e76b19c8b4db66c09bc554ad790b168e364 | mzhao15/mylearning | /algorithms/Sort/insertion_sort.py | 867 | 4.15625 | 4 | """
Insertion Sort
"""
def sort_insertion(array):
for i in range(len(array)):
for j in range(i, 0, -1):
if type(array[j]) != int and type(array[j] != float):
return j
if array[j] > array[j-1]:
t = array[j]
array[j] = array[j-1]
array[j-1] = t
return array
def insertion_sort(arr):
if len(arr) < 2:
return arr
for i in range(1, len(arr)):
for j in range(i, 0, -1):
if arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
return arr
def binary_insertion_sort(arr):
if len(arr) < 2:
return arr
# replace the comparison by a binary search then swap. Can increase the efficiency
return arr
a = [3, 2, 4, 1]
# a = [1] # edge case 1
# a = [] # edge case 2
print(insertion_sort(a))
|
e0e3617dc599778aab76c14fa0fd131fab2fee24 | defins/eksamens_a_roznieks | /4uzdevums.py | 271 | 3.90625 | 4 | def split(word):
return [char for char in word]
def listToString(s):
str1 = ""
c =len(s)
for num in range(c,0,-1) :
str1 += l[num-1]
return str1
print("Ievadi Vārdu:")
word = input()
l = split(word)
rinda= listToString(l)
print(rinda)
|
11d3fd49014d6bf6a8fa3476dba733dec478e0ce | scifinet/Network_Automation | /DEVCOR/DEVASC/Birthday_JSON_p1.py | 582 | 4.5 | 4 | #### Creat Dictionary of people's birthdays and write a program that asks a user who's birthday they would like to look up ###
### CREATE DICTIONARY ###
birthday_dict = {
"Taylor":"04/15/1987",
"Justin":"04/13/1990",
"Ryan":"04/07/1990",
"Nathan":"11/06/1991"
}
def main():
print("Welcome to the birthday dictionary. We know the birthdays of:")
for name in birthday_dict:
print(name)
bday = input("Who's birthday would you like to look up?\n")
print(bday +"'s birthday is " + birthday_dict.get(bday))
if __name__ == '__main__':
main()
|
0c0f7ff5185a37d2d9c9d3ce49a68064c48341da | FatmanaK/leetcode-python | /solutions/reverse_nodes_in_k_group.py | 2,166 | 3.84375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not k:
return head
def reverse_node_order(head):
tail = head
new_head = head
current_node = head.next
while current_node:
next_node = current_node.next
current_node.next = new_head
new_head = current_node
current_node = next_node
return new_head, tail
if not head or not head.next:
return head
current_node = head
for _ in range(k - 1):
if not current_node.next:
return head
current_node = current_node.next
reversed_remaining = self.reverseKGroup(current_node.next, k)
current_node.next = None
new_head, tail = reverse_node_order(head)
tail.next = reversed_remaining
return new_head
def main():
def get_nodes(values):
next_node = None
for value in values[::-1]:
node = ListNode(value)
node.next = next_node
next_node = node
return next_node
def get_list(head):
node = head
nodes = list()
while node:
nodes.append(node.val)
node = node.next
return nodes
solution = Solution()
assert get_list(solution.reverseKGroup(get_nodes([]), 2)) == []
assert get_list(solution.reverseKGroup(get_nodes([1]), 2)) == [1]
assert get_list(solution.reverseKGroup(
get_nodes([1, 2, 3, 4]), 2)) == [2, 1, 4, 3]
assert get_list(solution.reverseKGroup(
get_nodes([1, 2, 3, 4, 5]), 2)) == [2, 1, 4, 3, 5]
assert get_list(solution.reverseKGroup(
get_nodes([1, 2, 3, 4, 5]), 3)) == [3, 2, 1, 4, 5]
assert get_list(solution.reverseKGroup(
get_nodes([1, 2, 3, 4, 5]), 1)) == [1, 2, 3, 4, 5]
if __name__ == '__main__':
main()
|
eaaa5ae5e2ed33f7a34c5e78a3019bcbd6900b26 | snowsmile1211/Be_A_Data_Scientist | /CSE 5526 Introduction to Neural Network/Programming Assignments/PA2/PA2 RBF online.py | 7,214 | 3.890625 | 4 |
##### CSE 5526 Introduction to Neural Networks #####
##### Programming Assignment 2 RBF #####
##### Online Learning #####
import numpy as np
import matplotlib.pyplot as plt
class Cluster:
def __init__(self,data,num_elements):
self.data=data
self.num_elements=num_elements
def __getdata__(self): # get the input data of this input node
return self.data
def find_cluster(x,center_list,num_cluster):
# Find the index of cluster in which x is
# Besides the index of cluster, also return the distance list to each of the centers
dist_list=[]
for i in range(num_cluster):
dist=abs(x-center_list[i])
dist_list.append(dist)
min_dist=min(dist_list)
index_cluster=dist_list.index(min_dist)
return (index_cluster,dist_list)
def Kmeans(k,input_x,sample_size):
# function for K-means #
# input parameter: k number of cluster centers
# input_x input patterns for K-means
# output: a list of cluster centers
#Initialize centers randomly
# index_center_list=np.random.randint(sample_size,size=k)
a = np.arange(75)
np.random.shuffle(a)
index_center_list=a[0:k]
center_list=np.array([input_x[index_center] for index_center in index_center_list]).reshape(k,)
index_cluster_sample=np.ones(sample_size)*(-1)
while True:
# calculate the index of cluster for each of the input patterns
for i in range(sample_size):
(index_cluster_sample[i],dist_test)=find_cluster(input_x[i],center_list,k)
pass
center_list_new=np.ones(k,)*(-99)
# Update cluster centers
for j in range(k):
sum_x=0
count_j=0
for i in range(sample_size):
if index_cluster_sample[i]==j:
sum_x=sum_x+input_x[i]
count_j=count_j+1
center_list_new[j]=sum_x/count_j
dif0=abs(center_list_new[0]-center_list[0])
dif1=abs(center_list_new[1]-center_list[1])
print('dif0 %s, dif1 %s\n '%(dif0, dif1))
if np.array_equal(center_list_new,center_list):
break
center_list=center_list_new
return center_list_new
def max_distance(center_list,k):
dmax=0
for i in range(k):
for j in range(k):
if i!=j:
d=abs(center_list[i]-center_list[j])
if d>dmax:
dmax=d
pass
pass
pass
pass
return dmax
# Activation functions
def gaussian(x,xj,delta):
dif_2=(x-xj)**2
phi=np.exp(-dif_2/(2*delta**2))
return phi
# Derivative of activation function
def gaussianDer(x,xj,delta):
coef=-abs(x-xj)/(delta**2)
dif_2=(x-xj)**2
expv=-dif_2/(2*delta**2)
phi_prime=coef*np.exp(expv)
return phi_prime
# Forward Process between input and hidden layer
def Forward_in2hi(input_x, xj_list,delta,k):
result = [gaussian(input_x,xj_list[i],delta) for i in range(k)]
result = np.array(result).reshape(k,1)
return result
# Forward Process between hidden and output layer
def Forward_hi2op(w_hi2op, b_op, yj,k):
yj=yj.reshape(k,1)
w_hi2op = w_hi2op.reshape(k,)
yj = yj.reshape(k,)
tmp = np.sum(w_hi2op * yj) + b_op
return (tmp)
# The whole forward process
def Forward(input_x, xj_list,delta, w_hi2op, b_op,k):
yj = Forward_in2hi(input_x, xj_list,delta,k)
act_output = Forward_hi2op(w_hi2op, b_op, yj,k)
return act_output
# BackPropogation between output layer and hidden layer
def BackProp_op2hi(input_x, xj_list,w_hi2op, b_op, exp_output, act_output,k):
yj= Forward_in2hi(input_x,xj_list,delta, k)
act_output = Forward_hi2op(w_hi2op, b_op, yj,k)
# vk = sum(np.multiply(w_hi2op.reshape(k,), yj.reshape(k,)))
dw_hi2op = -(exp_output-act_output) * yj
dw_hi2op=np.array(dw_hi2op).reshape(k,1)
db_op = -(exp_output-act_output) * 1
return (dw_hi2op, db_op)
# Update the weights based on several parameters
def Weight_update( w_hi2op, b_op , dw_hi2op, db_op, gama=0.02):
dw_hi2op = gama * dw_hi2op
db_op = gama * db_op
return (w_hi2op-dw_hi2op,b_op- db_op,dw_hi2op, db_op)
# Cost/loss function
def CostFunction(act_output,exp_output):
ESquare=((act_output-exp_output)**2)*0.5
return ESquare
# Initialize the input and output data for training samples
sample_size=75
np.random.seed(42)
noise=np.random.uniform(-0.1,0.1,sample_size).reshape(sample_size,1)
input_x=np.random.uniform(0,1,sample_size).reshape(sample_size,1)
output_h=0.4*np.sin(2*np.pi*input_x)+0.5+noise
# print(output_h.reshape(1,sample_size))
# ax = plt.gca()
# ax.scatter([input_x[i] for i in range(sample_size)], [1 for i in range(sample_size)], color='red', marker='.', alpha=0.8)
# ax.set_aspect(1)
K=[2,4,7,11,16]
lr=[0.01,0.02]
k=K[0]
center_list=Kmeans(k,input_x,sample_size)
# ax.scatter([center_list[i] for i in range(k)], [1 for i in range(k)], color='black', marker='o', alpha=0.8)
# ax.set_ylim([0, 2])
# plt.show()
# Calculate Gaussian Widths (different clusters assume same Gaussian width)
dmax=max_distance(center_list,k)
delta=dmax/(np.sqrt(2*k))
print(delta)
# w_hi2op=np.array([1 for i in range(k)]).reshape(k,1)
# b_op=1
np.random.seed(42)
w_hi2op = np.random.rand(k,1)*2-1
b_op = np.random.rand()*2-1
for index_epoch in range(100):
cost_total = 0
dw_hi2op = np.array([0.0 for i in range(k)]).reshape(k,1)
db_op=0
for index_sample in range(sample_size):
x=input_x[index_sample]
exp_output=output_h[index_sample]
# def BackProp_op2hi(input_x, xj_list,w_hi2op, b_op, exp_output, act_output,k):
act_output = Forward(x, center_list,delta, w_hi2op, b_op,k)
(dw_hi2op,db_op)=BackProp_op2hi(x,center_list,w_hi2op,b_op,exp_output,act_output,k)
(w_hi2op, b_op, dw_hi2op, db_op) = Weight_update(w_hi2op, b_op, dw_hi2op, db_op,gama=0.01)
for index_sample in range(sample_size):
x=input_x[index_sample]
exp_output=output_h[index_sample]
act_output = Forward(x, center_list,delta, w_hi2op, b_op,k)
cost_total += CostFunction(act_output, exp_output)
if index_epoch % 10 == 0:
print('Iteration %s: Total Loss is %s' % (iter, cost_total))
print(w_hi2op)
print(b_op)
# Plot t
input_x_final=np.arange(0.0,1 ,0.00001)
final_output=[]
for index_sample in range(100000):
x=input_x_final[index_sample]
act_output = Forward(x, center_list,delta, w_hi2op, b_op,k)
final_output.append(act_output)
ax = plt.gca()
ax.scatter(list(input_x_final),final_output , color='red', marker='.', alpha=0.8)
ax.scatter(list(input_x),list(output_h) , color='blue', marker='.', alpha=0.8)
x_list=np.arange(0.0,1 ,0.0001)
y_list=0.4*np.sin(2*np.pi*x_list)+0.5
ax.scatter(list(x_list),list(y_list) , color='black', marker='o', alpha=0.8)
# ax.set_aspect(1)
ax.set_ylim([0, 1])
plt.show() |
ec4bdd6c199cd240049a6c91d6fafc82f8ae9d90 | pythonzhangfeilong/Python_WorkSpace | /9_Demo_数据分析常用模块/1_Matplotlib/2_NumPy Matplotlib/2_简单的绘图实例.py | 503 | 3.578125 | 4 | """
@File : 2_简单的绘图实例.py
@Time : 2020/4/15 3:31 下午
@Author : FeiLong
@Software: PyCharm
"""
import numpy
from matplotlib import pyplot
# 定义x轴的坐标
x=numpy.arange(1,11)
# 定义y轴的坐标
y=2*x+5
# 坐标图的标题
pyplot.title('Matplotlib Demo')
# x轴的名称
pyplot.xlabel('x axes')
# y轴的名称
pyplot.ylabel('y axes')
# 设置坐标参数
xp=[1,2,3,4]
yp=[7,6,5,4]
# 根据坐标参数绘制
pyplot.plot(xp,yp)
# 展示
pyplot.show()
|
252a97565b1f601b2b06c58081d0d18be726e7a2 | Ritvik19/CodeBook | /data/Algorithms/Kth Smallest Element in BST.py | 1,187 | 3.796875 | 4 | class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __str__(self):
return f"{self.data}"
count = 0
def kthSmallestInBST(root, k):
global count
if root is None:
return None
left = kthSmallestInBST(root.left, k)
if left:
return left
count += 1
if(count == k):
return root
return kthSmallestInBST(root.right, k)
def insert(node, key):
if node is None:
return Node(key)
if key < node.data:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
def inorderTraversal(node):
res = []
if node:
res = inorderTraversal(node.left)
res.append(node.data)
res = res + inorderTraversal(node.right)
return res
if __name__ == "__main__":
root = Node(10)
root = insert(root, 50)
root = insert(root, 30)
root = insert(root, 20)
root = insert(root, 40)
root = insert(root, 70)
root = insert(root, 60)
root = insert(root, 80)
print(*inorderTraversal(root))
print(f"3th Smallest: {kthSmallestInBST(root, 3)}")
|
f8aba774f544c38fdd093a036d09cdcd589dfd20 | Dieye-code/td_1 | /python/exo26.py | 602 | 3.53125 | 4 | import array as ar
n = 10
tab = ar.array('i', [])
for i in range(n):
print("entrer l'element à l'indice ", i+1)
x = input()
while x.isdigit == False or int(x) < 1 or int(x) > 100:
x = input("Vous devez saisir un entier compris entre 1 et 100")
tab.append(int(x))
dc = 1
c = 1
m = 1
for i in range(n-1):
if tab[i] < tab[i+1]:
dc = 0
elif tab[i] > tab[i+1]:
c = 0
if c == 1:
print("Les nombres sont dans l'ordre croissant")
elif dc == 1:
print("les nombres sont dans l'ordre decroissant")
else:
print("les nombres sont dant l'ordre quelconque") |
b527e0dc149e1c769f394ceaa9f9ae332c0fecfa | phaustin/ocgy-dataviewer | /station.py | 473 | 3.53125 | 4 | class Station:
def __init__(self, type, lat, lon, name, colour):
self.type = type
self.lat = lat
self.lon = lon
self.name = name
self.colour = colour
def in_list(lat, lon, list):
for s in list:
if (s.lat == lat) & (s.lon == lon):
return True
return False
def remove_from_list(lat, lon, list):
for s in list:
if (s.lat == lat) & (s.lon == lon):
list.remove(s)
return list |
e48aab14e9da972c252381366ac83b7042c42c01 | zhangyan0814/python-homework | /python/sum-of-multiples/sum_of_multiples.py | 200 | 3.65625 | 4 | def sum_of_multiples(limit, multiples):
count = 0
for i in range(limit):
for x in multiples:
if i%x == 0:
count += i
break
return count
|
d030ac95158c21820c97764932f8605dbebdf953 | phillybenh/Intro-Python-II | /src/player.py | 2,068 | 3.765625 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
# * Put the Player class in `player.py`.
# * Players should have a `name` and `current_room` attributes
class Player:
def __init__(self, name, current_room, victory=False):
self.name = name
self.current_room = current_room
self.victory = victory
self.player_items = []
def __str__(self):
# return f"{self.name} you are in the {self.current_room}"
return f"{self.name}"
# def get_name(self):
# return self.name
# don't need after refactor?
def set_location(self, room):
if room != None:
self.current_room = room
return self.current_room
else:
return -1
def set_victory(self, victory):
self.victory = victory
return self.victory
def player_room(self):
if self.current_room.room_items == []:
return f" {self.current_room.name}. {self.current_room.description}.\n"
else:
items = ""
for item in self.current_room.room_items:
items += item.name + " - " + item.description + ", \n"
return f" {self.current_room.name}. {self.current_room.description}. \n Look, there are some old things on the ground: {items}\n"
def get_item(self, picked_item):
for item in self.current_room.room_items:
if item.name == picked_item:
self.player_items.append(item)
self.current_room.room_items.remove(item)
return f"\n You have picked up {item.name} \n"
return f"\n {picked_item} not found"
#self.current_room.room_items
def drop_item(self, picked_item):
for item in self.player_items:
if item.name == picked_item:
self.current_room.room_items.append(item)
self.player_items.remove(item)
return f"\n You have dropped up {item.name} \n"
return f"\n {picked_item} not found"
|
bc6576d411f6b09e0bf38568568e16fc283dfd70 | miketwo/euler | /p3.py | 1,077 | 3.796875 | 4 | #!/usr/bin/env python
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
from itertools import count
from time import time
# Prints all primes for a given number.
# Uses recursion
def factor(number):
# Divide the number by every prime lower than it.
# it it divides evenly, do it again with the remainder.
# if not, move on to the next prime.
# if no division is found, it's a prime number.
for i in count(start=2, step=1):
division, remainder = divmod(number, i)
# print "{}/{} = {} R{}".format(number, i, division, remainder)
if not remainder:
yield i
# Wacky recursive yield
for r in factor(division):
yield r
raise StopIteration
if i >= number:
raise StopIteration
yield number
def main():
num = 600851475143
print "--- FACTORING {} ---".format(num)
for prime in factor(num):
print "PRIME: {}".format(prime)
if __name__ == '__main__':
main()
|
4dd2bf14a759e7fd7a3dd9e4488c0cd7c300713c | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_53.py | 331 | 3.96875 | 4 | """
escreva um programa que leia um número inteiro positivo N e em seguida imprima N
linhas do chamado Triangulo de Floyd.
"""
n = int(input("Digite o valor para o Triângulo de Floyd: "))
linhas = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
print(linhas, end=" ")
linhas = linhas + 1
print()
|
4371970da7d26c53e0900014804c0525cbc01b86 | olgaloboda/Python-MIT | /Week2/Week2_task1.py | 514 | 4.15625 | 4 | # Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
year = 12
while year >= 1:
monthlyInterestRate = annualInterestRate / 12.0
minMonthlyPaymentRate = monthlyPaymentRate * balance
monthlyUnpaidBalance = balance - minMonthlyPaymentRate
balance = monthlyUnpaidBalance + monthlyInterestRate * monthlyUnpaidBalance
year -= 1
print("Remaining balance: {}".format(round(balance, 2))) |
a0a3ada9fd70ffaeacd75b8ee9c6944a243e620b | deep1409/Computer-Vision-Practicals | /practical2B.py | 328 | 3.765625 | 4 | # Python program to explain cv2.imread() method
# importing cv2
import cv2
# path
path = r'C:\\Users\\Deep\\Downloads\\\product-sans\\photo.jpg'
# Using cv2.imread() method
# Using 0 to read image in grayscale mode
img = cv2.imread(path, 0)
# Displaying the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
9bc412b4791b001234141b5ad332fe989de0ee10 | funnyuser97/HT_1 | /task4.py | 232 | 4.1875 | 4 | # 4. Write a script to concatenate N strings.
number=int(input('Input number of string: '))
list_string=[]
for i in range(number):
list_string.append(input())
all_string = ' '.join(list_string)
print('All strings: ' ,all_string) |
9597367f88e7e374c9513a665c61b482a91ab317 | opentechschool-zurich/resources | /15-min-projects/ale/camel-case/main.py | 356 | 4.21875 | 4 | def dash_to_camel_case(text):
result = ''
nextUpper = False
for c in text:
if c == '_':
nextUpper = True
else:
if nextUpper:
result += c.upper()
nextUpper = False
else:
result += c
return result
print(dash_to_camel_case('sum_of_digits'))
|
bd8b7bc23b750074ff86be61c30e343ccd6803b4 | msmr1109/Python | /area/fourbox_area.py | 609 | 3.625 | 4 | def area(boxes):
s = []
for box in boxes:
x1, y1, x2, y2 = box
for x in xrange(x1, x2):
for y in xrange(y1, y2):
if contains(s, x, y): continue
s.append((x,y))
return len(s)
def contains(l, xpos, ypos):
for t in l:
x, y = t
if x == xpos and y == ypos:
return True
return False
if __name__ == "__main__":
boxes = [[1, 2, 4, 4], [2, 3, 5, 7], [3, 1, 6, 5], [7, 3, 8, 6]]
print(area(boxes))
#boxes = [[1, 1, 2, 6], [3, 3, 5, 6], [1, 4, 2, 7], [3, 4, 8, 8]]
#print(area(boxes))
|
1fd19d3051f81c7afe624225eabf8f5248f9af82 | b0hd4n/multitarget_mt | /scripts/ignore_lines.py | 1,069 | 3.625 | 4 | #!/usr/bin/env python3
# filter out lines specified in another file
import sys
import argparse
def main():
args = parse_args()
skipped_lines_generator = get_skipped_line_generator(args.lines)
with open(args.source, encoding='utf-8') as f_data:
skip_line = next(skipped_lines_generator)
for i, data_line in enumerate(f_data, 1):
if i == skip_line:
skip_line = next(skipped_lines_generator)
else:
print(data_line.strip())
def parse_args():
parser = argparse.ArgumentParser(description='Filter out lines specified in another file.')
parser.add_argument('--lines', '-l', type=str,
help='File contains lines to skip')
parser.add_argument('--source', '-s', type=str,
help='Source file to be filtered')
args = parser.parse_args()
return args
def get_skipped_line_generator(lines_file):
with open(lines_file) as f:
for line in f:
yield int(line)
yield -1
if __name__=='__main__':
main()
|
916870799b9513e59d72c8eee773b140e84a67f0 | ReWKing/StarttoPython | /if语句/5.4 使用if语句处理列表/voting.py | 223 | 3.953125 | 4 | age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you register to vote yet?")
else:
print("Sorry,you are to young to vote.")
print("Please register to vote as soon as you turn to 18!")
|
12a2fc8796eb31a84a4d3f830739101321a68cdd | mohitraj/mohitcs | /Learntek_code/10_july_18/file1.py | 136 | 3.5 | 4 | file_txt = open("sample1.txt", 'r')
i = 0
for line in file_txt:
print line
if 'is' in line:
i = i+1
print i
file_txt.close()
|
7be42beca9ceebe90fd285ce02a3c575fe8ca11f | rsairam34/sample | /range.py | 251 | 4.1875 | 4 | #range function
print (range(10))
print (range(5,10))
print (range(0,10,3))
print (range(-10,-100,-30)
list = ["mary","had","a","little","lamb"]
for i in range(len(list)):
print i,list[i]
print "third edit locally"
print "fifth change locally" |
317061c9a2b60a7e897d0c054683f8fe67c22856 | JKelle/ProjectEuler | /Euler060.py | 1,244 | 3.515625 | 4 | from math import sqrt
import EulerUtils, sortedList
maxSize = 1000000
sieve = EulerUtils.sieve(maxSize)
primes = [i for i in xrange(len(sieve)) if sieve[i]]
pairs = []
def isPrime(num):
if num >= len(sieve):
for n in xrange(2, int(sqrt(num))):
if num % n == 0:
return False
return not num % int(sqrt(num)) == 0
else:
return sieve[num]
def can_split_into_primes(num):
digits = EulerUtils.getDigits(num)
for i in xrange(1, len(digits)):
a = EulerUtils.getNumFromDigits(digits[:i])
b = EulerUtils.getNumFromDigits(digits[i:])
# print "%s:" % num
if isPrime(a) and isPrime(b):
if isPrime( EulerUtils.concat(b,a) ):
# print "\t%s, %s" % (a,b)
pair = tuple(sorted((a,b)))
if not pair in pairs:
#sortedList.sorted_add(pairs, pair)
pairs.append(pair)
#print
"""
num = 7109
can_split_into_primes(num)
"""
def main():
for num in primes:
can_split_into_primes(num)
print len(pairs)
if __name__ == '__main__':
print EulerUtils.timeit(main)
"""
for a in xrange(len(primes)):
for b in xrange(a+1, len(primes)):
for c in xrange(b+1, len(primes)):
for d in xrange(c+1, len(primes)):
print primes[a], primes[b], primes[c], primes[d]
"""
|
3d90761237e0030c401f5b0f5711d18d4d82bb84 | ErrorCode51/ProjectEuler | /Euler_06.py | 346 | 3.71875 | 4 | import math
sumSquares = 0 #de som van de kwadraten
squareSum = 0 #het kwadraad van de som
for i in range(100):
sumSquares += math.pow(i+1, 2)
for i in range(100):
squareSum += (i + 1)
squareSum = pow(squareSum, 2)
print("sumSquares: ", sumSquares)
print("squareSum: ", squareSum)
print("Difference: ", abs(squareSum - sumSquares)) |
b968535ae828d7df3dbc5c6789f6ac09c0b74310 | ChengYaoYan/python-crash-course | /chapter2/name_cases.py | 407 | 3.921875 | 4 | name = "franklin liu"
message = f"Hello, {name}. Would you like to learn Python today."
print(message)
name = "franklin liu"
print(name.title())
print(name.lower())
print(name.upper())
person = "Albert Einstein"
quote = "A person who never made a mistake never tried anything new"
print(f'{person} once said, "{quote}".')
string = " some thing\n\t ... "
print(string.rstrip())
print(string.lstrip())
print(string.strip())
|
76cc72534bb68364221b5ff84077e781c953764f | thecodearrow/100-Days-Of-Code | /Primality Test.py | 666 | 4.0625 | 4 | t=int(input())
while(t!=0):
t=t-1
#Fermat's theorem for primality
#Remember Carmichael numbers fail this test
n=int(input())
a=2 #test for a=3,4,5....n
ferm=a**n-a
if(ferm%n==0):
print("yes")
else:
print("no")
#OR
n=int(input())
small_primes=[2,3,5,7,11,13,17,23,29,31,37]
if(n in small_primes):
print("PRIME")
elif(pow(2,n-1,n)==1): #561 is composite but goes through!
composite=False
for i in small_primes:
if(n%i==0):
print("COMPOSITE")
composite=True
break
if(not composite):
print("PRIME")
else:
print("COMPOSITE") |
2b490e27d1c3ef1d4175925360cad86098d6e3b9 | ccdunn/euler | /e029.py | 1,788 | 3.5625 | 4 | """
Project Euler Problem 29
========================
Consider all integer combinations of a^b for 2 a 5 and 2 b 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we
get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by a^b for
2 <= a <= 100 and 2 <= b <= 100?
"""
import utils
import numpy as np
# def solve_0(N):
# a = np.arange(2, N + 1, dtype=int)
# b = a[:, np.newaxis]
# a = a[np.newaxis, :]
#
# print(np.power(a, b))
#
# return np.sum(np.logical_not(np.isclose(b - a, loga_b)))
# def solve(N):
# a = np.arange(2, N + 1, dtype=int)
# b = a[:, np.newaxis]
# a = a[np.newaxis, :]
#
# pow(a, b)
# logb = np.log(b)
# loga = np.log(a)
#
# loga_b = logb/loga
#
# return np.sum(np.logical_not(np.isclose(b - a, loga_b)))
#
#
# def solve_1(N):
# factors = [utils.factorize_and_count(n) for n in np.arange(2, N+1, dtype=int)]
#
# mult = np.math.factorial(int(np.log2(N)))
#
# maxs = [np.max(fs[1]) for fs in factors]
# dists = [(fs[1]*mult)//np.max(fs[1]) for fs in factors]
#
# return (N - 1)**2 - n_dubs
# this is dumb. should be a more elegant way than just always relying on python's amazing int class
# other solution would involve looking at factorization of bases and looking for integer multiples of the counts of the prime factors
def solve_2(N):
return np.unique([[base**power for base in range(2, N + 1)] for power in range(2, N + 1)]).size
# print(solve_2(5))
# assert(solve_2(5) == 15)
print(solve_2(100))
|
a769f45b464fd82dad453d697d3d7728dc0becce | museHD/NCSS-Int-2020 | /Cheer Squad/cheer_squad.py | 598 | 4.3125 | 4 | '''
Write a program to cheer for your favourite sports teams!
Your program should ask the user to input their team name and then print out a cheer like this:
Team: Dolphins
Give me a D!
Give me a O!
Give me a L!
Give me a P!
Give me a H!
Give me a I!
Give me a N!
Give me a S!
What does that spell? DOLPHINS!
Here's another example:
Team: Tigers
Give me a T!
Give me a I!
Give me a G!
Give me a E!
Give me a R!
Give me a S!
What does that spell? TIGERS!
'''
team = input('Team: ')
for letter in team:
print(f'Give me a {letter.upper()}!')
print(f'What does that spell? {team.upper()}!') |
bfa93e154cbe98ecb35f3915c505aba5c26ab406 | Dreskiii1/CSE-231 | /Exercises/Exercises Chapter 07/7.2.py | 470 | 4.0625 | 4 | ##function 'return_list' goes here
def return_list(the_string):
new_list = []
the_string = the_string.replace(" ",",")
the_string = the_string.split(",")
if len(the_string) == 1:
return the_string[0]
else:
for x in range(len(the_string)):
new_list.append(the_string[x])
return new_list
def main():
the_string = input("Enter the string: ")
result = return_list(the_string)
print(result)
main() |
37083c7567c16e3feb4326f57e5657551549216b | imn00133/algorithm | /BaekJoonOnlineJudge/SolvedACClass/Class1/baekjoon_1330.py | 182 | 3.78125 | 4 | # https://www.acmicpc.net/problem/1330
# Solving Date: 20.03.27.
a, b = (int(x) for x in input().split())
if a > b:
print('>')
elif a < b:
print('<')
else:
print('==')
|
c24901df9f22915d7b0bb776ac5ff6630004da55 | PrintTeamX/eBoys | /1D-2B.py | 642 | 3.984375 | 4 | a = float(input('Введіть магнітуду: '))
if a <= 2.0 and a >= 0:
print('Мікро')
elif a >= 2.0 and a <= 3.0 :
print('Дуже слабкий')
elif a >= 3.0 and a <= 4.0 :
print('Слабкий')
elif a >= 4.0 and a <= 5.0 :
print('Легкий')
elif a >= 5.0 and a <= 6.0 :
print('Помірний')
elif a >= 6.0 and a <= 7.0 :
print('Сильний')
elif a >= 7.0 and a <= 8.0 :
print('Дуже сильний')
elif a >= 8.0 and a <= 10.0 :
print('Великий')
elif a >= 10.0 :
print('Рідкісно великий')
else:
print("Введіть коректне число")
|
40aca622b511e099e3f3ac8a37685bf8ec05d5b2 | Adasumizox/ProgrammingChallenges | /codewars/Python/7 kyu/OddOrEven/oddOrEven_test.py | 554 | 3.609375 | 4 | from oddOrEven import oddOrEven
import unittest
from random import randint
class TestOddOrEven(unittest.TestCase):
def test(self):
self.assertEqual(oddOrEven([0, 1, 2]), 'odd')
self.assertEqual(oddOrEven([0, 1, 3]), 'even')
self.assertEqual(oddOrEven([1023, 1, 2]), 'even')
def test_rand(self):
for _ in range(100):
lst = [randint(-100,100) for _ in range(randint(1,20))]
self.assertEqual(oddOrEven(lst), ["even", "odd"][sum(lst) & 1])
if __name__ == '__main__':
unittest.main() |
728d67e559a99e78def4760679df473674c9a728 | IvanIsCoding/OlympiadSolutions | /beecrowd/1165.py | 547 | 3.59375 | 4 | # Ivan Carvalho
# Solution to https://www.beecrowd.com.br/judge/problems/view/1165
# -*- coding: utf-8 -*-
"""
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
"""
ordem = int(input())
array = []
for i in range(ordem):
array.append(int(input()))
def primo(x):
return (
x == 2
or x > 1
and x % 2 == 1
and all([x % i for i in range(3, int(x**0.5) + 1, 2)])
)
for k in array:
if primo(k):
print("%d eh primo" % (k))
else:
print("%d nao eh primo" % (k))
|
34e2e98b13cba6da6061d34ea85c3154549e0901 | loc-dev/CursoEmVideo-Python | /Fase09/03_Transformacao_02.py | 869 | 4.125 | 4 | # Fase 09 - Manipulando Texto
# Teoria
# Técnica de Transformação
# Iremos alterar o valor da variável 'frase'
frase = ' Aprenda Python '
print('É comum na área de tecnologia, pessoas incluir espaços na caixa de texto')
print(frase)
# As linguagens de Programação apresenta funcionalidades internas para remoção desses espaços
# Vejamos o método .strip()
print('')
print('O método .strip() pode ajudar no momento de remover todos os caracteres \n'
'iniciais e finais:')
print(frase.strip())
# Continuação com o método .strip()
print('')
print('O método .rstrip() pode fazer a mesma ajuda, porém, remove somente os caracteres da direita:')
print(frase.rstrip())
print('')
print('De forma análoga, não podemos esquecer o left (esquerda) \n'
'O método .lstrip(), remove todos os caracteres da esquerda:')
print(frase.lstrip())
|
44dd3947ee1d77b13b833c33bbdb53ebe5464ad2 | globocom/dojo | /2021_03_31/dojo.py | 1,498 | 3.6875 | 4 | def append_string_value(c, value):
if len(value) == 0:
return c
return (int(value)*c)
def main(input_string, max_length):
value = ""
decoded_string = ""
for c in input_string:
if c.isdigit():
value = value + c
else:
decoded_string += append_string_value(c,value)
if len(decoded_string) > max_length:
return "unfeasible"
value = ""
return decoded_string
def encode_value(value, previous_letter):
if value == 1:
return previous_letter
return str(value) + previous_letter
def encode_string(decoded_string):
previous_letter = decoded_string[0]
value = 0
encoded_string = ""
for c in decoded_string:
if c == previous_letter:
value += 1
else:
encoded_string += encode_value(value, previous_letter)
value = 1
previous_letter = c
encoded_string += encode_value(value, previous_letter)
return encoded_string
# if decoded_string == "abcd":
# return "abcd"
# if decoded_string == "aaaaabbc":
# return "5a2bc"
# else:
# return "asdf4x"
# Celso - Ingrid - Lara - Tiago - Juan
#input
#5a2bc 8
#output
#aaaaabbc
#input
#5a2bc 7 => aaaaabbc (length: 8)
#output
#unfeasible
#input
#asdf4x 50
#output
#asdfxxxx
#input
#asjkdf10000000000kz 1000000
#output
#unfeasible
#func com o objetivo de formar o numero |
aa6ff500dee33136a90c2b8a73889a062b6b65ce | DavidMFreeman34/NoahDavidCollab | /pinwheel_color_winter.py | 2,834 | 3.53125 | 4 | #-----------------------------------------
# Python + matplotlib + numpy + mpmath
# Created by David Freeman (2016) with consultation from Noah Weaver
# Modified from http://www.bubuko.com/infodetail-911894.html
#-----------------------------------------
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from mpmath import *
plt.figure(figsize=(2,1.4),dpi=500)
plt.subplot(aspect='equal')
plt.axis([0,24,0,24])
plt.xticks([])
plt.yticks([])
plt.axis('off')
print "Pinwheel(p,q) Tiling"
p = input('Enter the value of p: ')
q = input('Enter the value of q: ')
m = input('Enter number of divisions: ')
r = max(p,q)
filename = 'pinwheel(%s,%s,%s)_winter.eps' %(p,q,m)
# Now we calculate the proportions of the triangles based on (p,q). The number b provides
# the base of a triangle, and the number a provides the height. The hypotenuse equals 1.
mp.dps = 10
mp.pretty = True
f = lambda x: (0.5**p)*(1-x**2)**(0.5*p)-x**q
a=findroot(f,0.5)
b=(1-a**2)**(0.5)
c=b/2
# Now we insert the starting triangle into the list 'triangles'
A=np.array([0,0])
B=np.array([24*b,0])
C=np.array([24*b,24*a])
D=np.array([0,24*a])
triangles = [(1,A,B,C),(1,C,D,A)]
# Now we insert the size of the hypotenuse of the starting triangle into the list 'sizes'
sizes = [1]
# Now we define the subdivision rule.
def subdivide(largest):
result = []
for size,A,B,C in largest:
P = A + (C-A)*(0.5*b**2)
Q = A + (C-A)*(b**2)
S = A + (B-A)*(0.5)
R = A + (B-A)*(0.5) + (C-A)*(0.5*b**2)
result += [(size*c,A,P,S),(size*c,Q,P,S),(size*c,S,R,Q),(size*c,S,R,B),(size*a,B,Q,C)]
return result
# Now we apply the subdivision rule. Note the need for a bit of rounding!
for i in xrange(m):
n = max(sizes)
for size,A,B,C in triangles:
if round(size,5) == round(n,5):
largest = [(size,A,B,C)]
triangles += subdivide(largest)
sizes += [size*c,size*a]
sizes = list(set(sizes))
sizes = [x for x in sizes if round(x,5) != round(n,5)]
# Now we clean up the sizes list in order to color the tiling
sizes.sort()
final_sizes = []
for i in xrange(r):
if sizes:
final_sizes += [sizes[0]]
sizes = [x for x in sizes if round(x,5) != round(sizes[0],5)]
# Now we set the color scheme and draw the triangles
cmap = mpl.cm.winter
def DrawFigure(triangles):
for size,A,B,C in triangles:
vertices = [C,A,B,C]
codes = [Path.MOVETO]+[Path.LINETO]*3
tri = Path(vertices,codes)
for i in xrange(len(final_sizes)):
if round(size,5) == round(final_sizes[i],5):
tri_patch=PathPatch(tri,facecolor=cmap(0.4*(float(r)-i)/float(r)+i/float(r)),edgecolor='#000000',joinstyle='round',linewidth=0)
plt.gca().add_patch(tri_patch)
plt.savefig(filename, format='eps')
plt.show()
DrawFigure(triangles)
|
2c7bf82d0805dfbf4801c74fdb856e1de0de138c | prabhu30/coding | /Hackerrank/19 _ Capitalize!/solution.py | 141 | 3.703125 | 4 | # Complete the solve function below.
def solve(s):
a_string = s.split(' ')
return ' '.join((word.capitalize() for word in a_string))
|
76a428d76b75b5aba3211ac7f1cbb67a88463186 | HishamKhalil1990/data-structures-and-algorithms | /python/code_challenges/fifo_animal_shelter/fifo_animal_shelter/fifo_animal_shelter.py | 2,641 | 4.03125 | 4 | class Cat:
def __init__(self,value = "cat"):
self.value = value
self.next = None
def __str__(self):
return f"{self.value}"
class Dog:
def __init__(self,value = "dog"):
self.value = value
self.next = None
def __str__(self):
return f"{self.value}"
class Animal_Shelter:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self,animal):
if animal == "cat":
new_animal = Cat()
elif animal == "dog":
new_animal = Dog()
else:
new_animal = None
if not self.front and new_animal:
self.front = new_animal
self.rear = self.front
elif new_animal:
self.rear.next = new_animal
self.rear = new_animal
def dequeue(self,pref):
value = None
if pref == "cat" or pref == "dog":
current = self.front
if str(current) == pref:
value = str(current)
self.front = self.front.next
else:
previous = self.front
current = previous
while current:
if str(current) == pref:
dequeued = current
value = str(dequeued)
previous.next = dequeued.next
break
previous = current
current = current.next
return value
else:
return value
def __str__(self):
string = ""
current = self.front
if not current:
string = 'empty'
while current:
string += f"{str(current)}"
current = current.next
if current:
string += " -> "
return string
if __name__ == "__main__":
shelter = Animal_Shelter()
shelter.enqueue("bird")
print(shelter)
shelter.enqueue("cat")
print(shelter)
shelter.enqueue("horse")
print(shelter)
shelter.enqueue("cat")
print(shelter)
shelter.enqueue("dog")
print(shelter)
shelter.enqueue("dog")
print(shelter)
shelter.enqueue("cat")
print(shelter)
shelter.enqueue("dog")
print(shelter)
shelter.enqueue("cat")
print(shelter)
shelter.enqueue("dog")
print(shelter)
print(shelter.dequeue("bird"))
print(shelter)
print(shelter.dequeue("cat"))
print(shelter)
print(shelter.dequeue("dog"))
print(shelter)
print(shelter.dequeue("dog"))
print(shelter)
print(shelter.dequeue("cat"))
print(shelter)
|
9b65ccc0564ef8ccafb36fb63cb6086619cde85a | scottberke/algorithms | /test/practice_problems/search/rotated_array_test.py | 875 | 3.75 | 4 | import unittest
import random
from collections import *
from practice_problems.search.rotated_array import *
class RotatedArrayTest(unittest.TestCase):
def create_rotated_array(self, skip=1, high=100):
arr = deque(list(range(1, high, skip)))
rotate_by = random.randint(1, high//2)
arr.rotate(rotate_by)
return list(arr)
def test_rotated_array_found(self):
arr = self.create_rotated_array()
for i in arr:
res = search_rotated_array(arr, 0, len(arr) - 1, i)
self.assertEqual(
res, i
)
def test_rotated_array_not_found(self):
arr = self.create_rotated_array(skip=2) # only odd numbers
even_num = 40
res = search_rotated_array(arr, 0, len(arr) - 1, even_num )
self.assertFalse(res)
if __name__ == '__main__':
unittest.main()
|
18820dbc56bdc76c3a400faadd34eab849fb63f3 | adonismendozaperez/codewars-algorithm | /Algorithm/ConvertStringToCamelCase.py | 501 | 4.4375 | 4 | #Convert string to camel case
# Complete the method/function so that it converts
# dash/underscore delimited words into camel casing.
# The first word within the output should be capitalized
# only if the original word was capitalized.
def to_camel_case(text):
result = ""
count = 0
for val in text.replace("-","_").split("_"):
count += 1
if count != 1:
result += "".join(val.capitalize())
else:
result += "".join(val)
return result |
df19960b30479be8642f9f63908b65ffb85002ad | dinhthi1102/pam | /btth5.1.py | 224 | 3.65625 | 4 | ## file : mymarth.py ##
def square(n):
return n*n
def cube(n):
return n*n*n
def average(values):
nvals = len(values)
sum = 0.0
for v in values:
sum += V
return float(sum)/nvals
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.