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 |
|---|---|---|---|---|---|---|
35fdd7501a04f8d9c35cb2fa844937e5ed062d7a | divyanshumehta/graph-algo | /bfs.py | 747 | 3.953125 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u, v):
self.graph[u].append(v)
def BFS(self,s):
visited = [False] * len((self.graph))
queue = []
queue.append(s)
visited[s] = True
while queue:
node = queue.pop(0)
print node
##Enqueue adjacent nodes
for child in self.graph[node]:
if visited[child] == False:
queue.append(child)
visited[child] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
s = input("Enter starting edge")
g.BFS(s)
|
214e59ccda73904fc0518a0614631fd996a8d4cc | xulei717/Leetcode | /45. 跳跃游戏II.py | 1,514 | 3.703125 | 4 | # -*- coding:utf-8 -*-
# @time : 2020-01-17 09:52
# @author : xl
# @project: leetcode
"""
标签:困难、贪心算法、数组
题目:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game
"""
# 从0位置开始,看每一步可以达到的最远的位置,看最终包括了最后一个位置就返回当前步数
class Solution1:
def canJump(self, nums: list[int]) -> bool:
if len(nums) == 1:
return 0
last = len(nums) - 1
mm, i, step = 0, 0, 0
while i <= mm:
mm = max(mm, i+nums[i])
if mm >= last:
return step + 1
step += 1
ma = 0
for x in range(i+1, mm+1):
if x + nums[x] >= ma:
i = x
ma = x + nums[i]
# 执行结果:通过
# 执行用时 :56 ms, 在所有 Python3 提交中击败了99.21% 的用户
# 内存消耗 :14.5 MB, 在所有 Python3 提交中击败了100%的用户
|
61ebc71a0a737843a3862835146f28849e68179e | namkiseung/python_BasicProject | /python-package/question_python(resolved)/chapter4_conditional_and_loops(완결)/i_odd_even.py | 539 | 4.21875 | 4 | # -*- coding: utf-8 -*-
def odd_even(x):
""" 정수를 전달받아서 그 수가 짝수면 'even'을, 홀수면 'odd'를 반환하는 함수를 작성하자
sample in/out:
odd_even(2) -> 'even'
odd_even(1000) -> 'even'
odd_even(777) -> 'odd'
"""
# 여기 작성
if x % 2==0:
return 'even'
else:
return 'odd'
if __name__ == "__main__":
print odd_even(2) #-> 'even'
print odd_even(1000) #-> 'even'
print odd_even(777) #-> 'odd'
pass
|
6e1fcb2967c122b1b078d8c3a5c34c15a9c6a25d | Tarun-Sharma9168/Python-Programming-Tutorial | /gfgpart220.py | 1,066 | 3.625 | 4 | ''' ######
# #####
# ### ### ##### #
# # ### # ##### #### #####
###### ### # # #### #
##### #### #
Author name : Tarun Sharma
Problem Statement: use of the exec statement in the python that is to execute the block containing some code
'''
#library section
from collections import Counter
import sys
import numpy as np
from functools import reduce
from time import perf_counter
import math
import re
sys.stdin =open('input.txt','r')
#sys.stdout=open('output.txt','w')
#Code Section
def exec_the_block():
block='''
def add(x,y):
return x+y
print(add(2,3))
'''
exec(block)
#Driver code
#Input Output Section
t1_start=perf_counter()
#n=int(input())
#arr=list(map(int,input().split()))
#element=int(input('enter the element to search'))
#Calling of the functions that are there in the code section
exec_the_block()
t1_end=perf_counter()
print('total elapsed time',t1_start-t1_end) |
0a7cea01a2cedadcf3690b72ffd04380198c20b3 | bio-tarik/PythonUnitTesting | /pytest/Proj02/test_class.py | 530 | 3.578125 | 4 | """
Learning unit testing on Python using py.test.
Tutorial: docs.pytest.org/en/latest/getting-started.html#our-first-test-run
"""
class TestClass(object):
"""
Generic test class
"""
def test_one(self):
"""
Tests if the string 'this' contains 'h'
"""
string = "this"
assert 'h' in string
def test_two(self):
"""
Check if string object has the 'check' attribute
"""
string = "hello"
assert hasattr(string, 'check')
|
80378660ae773aa71593ae59b38372520baf663f | jitudv/python_programs | /prm2.py | 98 | 3.765625 | 4 | var=input("enter the no \t ")
var2=input("enter the 2nd no")
print("addition is= %d"%((var+var2))) |
d54feb625dcdbab60409ced5068ad46d50b004c0 | jackmoody11/project-euler-solutions | /python/p017.py | 1,828 | 3.765625 | 4 | letters = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five",
6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten",
11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen",
16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty",
30: "thirty", 40: "forty", 50: "fifty", 60: "sixty", 70: "seventy", 80: "eighty",
90: "ninety", 100: "onehundred", 1000: "onethousand"}
def count_letters(n):
# Catch 1-20, multiples of 10 up to 100 and 1000
if n in letters.keys():
return letters[n]
# Catch numbers not caught up to 100
elif 20 < n < 100:
tens = n // 10
ones = n - tens * 10
return letters[tens * 10] + letters[ones]
# Catch 200, 300, ..., 900
elif n % 100 == 0:
hundreds = n // 100
return letters[hundreds] + "hundred"
# Catch 110, 120, .., 990
elif n % 10 == 0:
hundreds = n // 100
tens = n // 10 - hundreds * 10
return letters[hundreds] + "hundred" + "and" + letters[tens * 10]
# Catch 111-119, 211-219, ...
elif n % 100 < 20:
hundreds = n // 100
rest = n - hundreds * 100
return letters[hundreds] + "hundred" + "and" + letters[rest]
# Catch 121-129, 131-139, ..., 991-999
else:
hundreds = n // 100
tens = n // 10 - hundreds * 10
ones = n - hundreds * 100 - tens * 10
if tens == 0:
return letters[hundreds] + "hundred" + "and" + letters[ones]
else:
return letters[hundreds] + "hundred" + "and" + letters[tens * 10] + letters[ones]
def compute():
letter_count = 0
for i in range(1, 1001):
letter_count += len(count_letters(i))
return letter_count
if __name__ == "__main__":
print(compute()) |
12cc5ef3a624905bc1aa900526727544e7222539 | amine0909/FunnyReplacer | /change.py | 252 | 3.5 | 4 | # script python, just to rename all images name
# i'm a little bit lazy :p
import glob
import os
list = glob.glob("./pics/*.*")
print(list)
for i,filename in enumerate(list):
#print(filename)
os.rename(filename,"./pics/{0}.jpg".format(i))
|
8bc64bb7045c38ecfd338eb6380863f3b0c07608 | lucasdmazon/CursoVideo_Python | /pacote-download/Exercicios/Aula17.py | 588 | 3.765625 | 4 | num = [2, 5, 9, 1]
num[2] = 3
num.append(7)
sorted(num, reverse=True)
num.insert(2, 2)
if 4 in num:
num.remove(4)
else:
print(f'Não achei o numero 4')
#num.pop(2)
print(num)
print(f'Esta lista tem {len(num)} elementos')
valores = []
valores.append(5)
valores.append(9)
valores.append(4)
for c, v in enumerate(valores):
print(f'Na posição {c} encontrei o valor {v}')
a = [2, 3, 4, 7]
b = a
#b = a[:]
b[2] = 8
print(a)
print(b)
valores = list()
for cont in range(0, 5):
valores.append(int(input('Digite um valor: ')))
for v in valores:
print(f'{v}...', end='')
|
5bb3f01f31167aa154acdfe9dd8483409ffc0e4f | vincenthanguk/TicTacToe-Python | /tictactoemodules.py | 3,855 | 3.90625 | 4 | import random
def display_board(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
def player_input():
# Takes Player input and assigns X or O Marker, returns tuple (player1choice, player2choice)
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = random.randint(0,1)
if marker == 0:
return ('X', 'O')
else:
return ('O','X')
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
return ((board[1] == mark and board[2] == mark and board[3] == mark) or # Hori
(board[4] == mark and board[5] == mark and board[6] == mark) or # zon
(board[7] == mark and board[8] == mark and board[9] == mark) or # tal
(board[1] == mark and board[4] == mark and board[7] == mark) or # Ver
(board[2] == mark and board[5] == mark and board[8] == mark) or # ti
(board[3] == mark and board[6] == mark and board[9] == mark) or # tal
(board[1] == mark and board[5] == mark and board[9] == mark) or # Dia
(board[3] == mark and board[5] == mark and board[7] == mark)) # gonal
def choose_first():
firstplayer = random.randint(1, 2)
if firstplayer == 1:
return 'Player 1'
else:
return 'Player 2'
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
for i in range(1,10):
if space_check(board, i):
return False
return True
def player_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
position = int(input('Choose your next position: (1-9) '))
return position
def random_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
position = random.randint(1,9)
return position
def replay():
return input('Play again? Enter Yes or No: ').lower().startswith('y')
def getduplicateboard(board):
# creates a duplicate board for AI to check win conditions
duplicate_board = []
for i in board:
duplicate_board.append(i)
return duplicate_board
def choose_random_move_from_list(board, moveslist):
# returns valid move from passed list on passed board
# returns None if no valid move
possible_moves = []
for i in moveslist:
if space_check(board, i):
possible_moves.append(i)
if len(possible_moves) != 0:
return random.choice(possible_moves)
else:
return None
def cpu_get_move(board, marker):
if marker == 'X':
playermarker = 'O'
else:
playermarker = 'X'
# check if CPU has a winning move
for i in range(1, 10):
copy = getduplicateboard(board)
if space_check(copy, i):
place_marker(copy, marker, i)
if win_check(copy, marker):
return i
# check if next move of player could be winning move, block
for i in range(1, 10):
copy = getduplicateboard(board)
if space_check(copy,i):
place_marker(copy,playermarker, i)
if win_check(copy,playermarker):
return i
# Try to take corners
move = choose_random_move_from_list(board, [1, 3, 7, 9])
if move != None:
return move
# Try to take center
if space_check(board,5):
return 5
# take a side
return choose_random_move_from_list(board,[2, 4, 6, 8]) |
874e9f13c8a50fbe7f906adbcaaaf3cf81e1454e | yennanliu/CS_basics | /leetcode_python/Array/find-the-celebrity.py | 7,195 | 3.9375 | 4 | """
277. Find the Celebrity
Medium
Suppose you are at a party with n people labeled from 0 to n - 1 and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know the celebrity, but the celebrity does not know any of them.
Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is ask questions like: "Hi, A. Do you know B?" to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
You are given a helper function bool knows(a, b) that tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if they are at the party.
Return the celebrity's label if there is a celebrity at the party. If there is no celebrity, return -1.
Example 1:
Input: graph = [[1,1,0],[0,1,0],[1,1,1]]
Output: 1
Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.
Example 2:
Input: graph = [[1,0,1],[1,1,0],[0,1,1]]
Output: -1
Explanation: There is no celebrity.
Constraints:
n == graph.length
n == graph[i].length
2 <= n <= 100
graph[i][j] is 0 or 1.
graph[i][i] == 1
Follow up: If the maximum number of allowed calls to the API knows is 3 * n, could you find a solution without exceeding the maximum number of calls?
"""
# V0
class Solution:
def findCelebrity(self, n):
self.n = n
for i in range(n):
# NOTE : we return the celebrity directly (if found)
if self.is_celebrity(i):
return i
return -1
# func check if i if celebrity
def is_celebrity(self, i):
for j in range(self.n):
if i == j:
continue # Don't ask if they know themselves.
"""
NOTE : here we check
knows(i, j) or not knows(j, i)
"""
if knows(i, j) or not knows(j, i):
return False
return True
# V0'
class Solution:
# @param {int} n a party with n people
# @return {int} the celebrity's label or -1
def findCelebrity(self, n):
celeb = 0
for i in range(1, n):
if Celebrity.knows(celeb, i): # if celeb knows i, then the given celeb must not a celebrity, so we move to the next possible celeb
celeb = i # move from celeb to i
# Check if the final candicate is the celebrity
for i in range(n):
if celeb != i and Celebrity.knows(celeb, i): # to check if the Celebrity really knows no one
return -1
if celeb != i and not Celebrity.knows(i, celeb): # to check if everyone (except Celebrity) really knows the Celebrity
return -1
return celeb
# V1
# IDEA : BRUTE FORCE
# https://leetcode.com/problems/find-the-celebrity/solution/
class Solution:
def findCelebrity(self, n: int) -> int:
self.n = n
for i in range(n):
if self.is_celebrity(i):
return i
return -1
def is_celebrity(self, i):
for j in range(self.n):
if i == j: continue # Don't ask if they know themselves.
if knows(i, j) or not knows(j, i):
return False
return True
# V1
# IDEA : Logical Deduction
# https://leetcode.com/problems/find-the-celebrity/solution/
class Solution:
def findCelebrity(self, n: int) -> int:
self.n = n
celebrity_candidate = 0
for i in range(1, n):
if knows(celebrity_candidate, i):
celebrity_candidate = i
if self.is_celebrity(celebrity_candidate):
return celebrity_candidate
return -1
def is_celebrity(self, i):
for j in range(self.n):
if i == j: continue
if knows(i, j) or not knows(j, i):
return False
return True
# V1
# IDEA : Logical Deduction with Caching
# https://leetcode.com/problems/find-the-celebrity/solution/
from functools import lru_cache
class Solution:
@lru_cache(maxsize=None)
def cachedKnows(self, a, b):
return knows(a, b)
def findCelebrity(self, n: int) -> int:
self.n = n
celebrity_candidate = 0
for i in range(1, n):
if self.cachedKnows(celebrity_candidate, i):
celebrity_candidate = i
if self.is_celebrity(celebrity_candidate):
return celebrity_candidate
return -1
def is_celebrity(self, i):
for j in range(self.n):
if i == j: continue
if self.cachedKnows(i, j) or not self.cachedKnows(j, i):
return False
return True
# V1
# https://www.jiuzhang.com/solution/find-the-celebrity/#tag-highlight-lang-python
# IDEA :
# AS A CELEBRITY, HE/SHE MOST KNOW NO ONE IN THE GROUP
# AND REST OF PEOPLE (EXCEPT CELEBRITY) MOST ALL KNOW THE CELEBRITY
# SO WE CAN USE THE FACT 1) : AS A CELEBRITY, HE/SHE MOST KNOW NO ONE IN THE GROUP
# -> GO THROUGH ALL PEOPLE IN THE GROUP TO FIND ONE WHO KNOW NO ONE, THEN HE/SHE MAY BE THE CELEBRITY POSSIBILY
# -> THEN GO THROUGH REST OF THE PEOPLE AGAIN TO VALIDATE IF HE/SHE IS THE TRUE CELEBRITY
"""
The knows API is already defined for you.
@param a, person a
@param b, person b
@return a boolean, whether a knows b
you can call Celebrity.knows(a, b)
"""
class Solution:
# @param {int} n a party with n people
# @return {int} the celebrity's label or -1
def findCelebrity(self, n):
celeb = 0
for i in range(1, n):
if Celebrity.knows(celeb, i): # if celeb knows i, then the given celeb must not a celebrity, so we move to the next possible celeb
celeb = i # move from celeb to i
# Check if the final candicate is the celebrity
for i in range(n):
if celeb != i and Celebrity.knows(celeb, i): # to check if the Celebrity really knows no one
return -1
if celeb != i and not Celebrity.knows(i, celeb): # to check if everyone (except Celebrity) really knows the Celebrity
return -1
return celeb
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def findCelebrity(self, n):
"""
:type n: int
:rtype: int
"""
candidate = 0
# Find the candidate.
for i in range(1, n):
if knows(candidate, i): # noqa
candidate = i # All candidates < i are not celebrity candidates.
# Verify the candidate.
for i in range(n):
candidate_knows_i = knows(candidate, i) # noqa
i_knows_candidate = knows(i, candidate) # noqa
if i != candidate and (candidate_knows_i or
not i_knows_candidate):
return -1
return candidate |
29473ad7178fee18cc9fcf8d1492c33dd5613e20 | WuAlin0327/python3-notes | /python基础/day7/购物车作业.py | 1,570 | 3.75 | 4 | goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
shopping_cart = {}
lump = []
sum = 0
shopping = True
user = input("请输入用户名:")
password = input("请输入密码:")
wage = int(input("请输入本月工资:"))
print("-----商品列表-----")
for index,i in enumerate(goods):
print("%s, %s %s"%(index,i['name'], i['price']))
while shopping: #主循环
number = input("请输入需要购买的的商品编号:")
if number.isdigit():
shopping_cart[goods[int(number)]['name']] = goods[int(number)]['price']#将商品名字与商品价格添加到字典中
unit = int(goods[int(number)]['price'])
if unit>wage:
print("余额不足无法添加到购物车")
elif unit<wage:
lump.append(unit)
for x in lump:
sum = sum+x #计算购买物品总额 "\033[43;31mxxxx\033[0m"
banblace = wage - sum # 计算余额
price = int(goods[int(number)]['price'])
if banblace<=0:
print("你的钱不够不能买这个,已结算!")
print('\033[43;31m你本次一共消费:%s,余额是: %s\033[0m'%(sum,banblace))
print("-----购物车中的商品---")
for k,v in shopping_cart:
print(k,v)
shopping = False
if banblace>price:
print("该商品已加入购物车,请问还需要购买什么")
if number == 'q':
print('\033[43;31m你本次一共消费:%s,余额是: \033[0m'%(sum))
print("-----购物车中的商品---")
for commodity in shopping_cart:
print(' '+commodity)
|
edc057d74877ef4c732ed5640193bfb542739981 | MikeDev0X/PythonPracticeEcercises | /convertidor a cm.py | 792 | 3.828125 | 4 | def feet():
feet=int(input('Feet: '))
if feet<=0:
print('Error')
else:
print ('cm: ',feet*30.48)
def inches():
inches=int(input('Inches: '))
if inches<=0:
print('Error')
else:
print ('cm: ',inches*2.54)
def yards():
yards=int(input('Yards: '))
if yards<=0:
print('Error')
else:
print('cm: ',yards*91.44)
def user():
while True:
user=int(input('\nMenu:\n1.Feet\n2.Inches\n3.Yards\n0.Exit\n '))
if user==1:
feet()
elif user==2:
inches()
elif user==3:
yards()
elif user==0:
print('see you later :)')
break
else:
print('Error, try again')
user()
|
941210ba99a6b19b57d90b401cabc1bfff29ba08 | davidmcclure/lint-analysis | /lint_analysis/core/utils.py | 452 | 3.765625 | 4 |
import re
import os
import scandir
def scan_paths(root, pattern=None):
"""Walk a directory and yield file paths that match a pattern.
Args:
root (str)
pattern (str)
Yields: str
"""
for root, dirs, files in scandir.walk(root, followlinks=True):
for name in files:
# Match the extension.
if not pattern or re.search(pattern, name):
yield os.path.join(root, name)
|
1b008231a583dab78b26d94b216ed02483a6c7f7 | xixijiushui/Python_algorithm | /algorithm/14-sortOddAndEvenNum.py | 446 | 3.5 | 4 | def recordOddEven(pData):
if pData == None or len(pData) == 0:
return
start = 0
end = len(pData) - 1
while start < end:
while start < end and pData[start] & 0x1 != 0:
start += 1
while start < end and pData[end] & 0x1 == 0:
end -= 1
if start < end:
pData[start], pData[end] = pData[end], pData[start]
pData = [1, 2, 3, 4, 5]
recordOddEven(pData)
print(pData) |
13c851856e954ed682ae4f12d4b3bc047fe404c7 | ajritch/DoublyLinkedList | /Node.py | 265 | 3.953125 | 4 | class Node(object):
def __init__(self, value, prev = None, next = None):
self.value = value
self.prev = prev
self.next = next
#method to display the node
def printNode(self):
print "Value:", self.value, "|", "Next:", self.next, "|", "Prev:", self.prev |
ee529f30bc053eda2bf2a980743a088f269251e2 | ankitkumarr/AdventOfCodeSolutions | /Day5/solution2.py | 609 | 3.515625 | 4 | def rule1(st):
for x in range ((len(st)-1)):
if rule1test (st[x:x+2], st, x)==True:
return True
return False
def rule1test(st1, st2, y):
for x in range (len(st2)):
if (x< ((len(st2))-1)) and x!= y and x!=y-1 and x!=y+1 :
if st2[x:x+2]==st1:
return True
return False
def rule2(st):
for x in range (len(st)):
if x < ((len(st))-2):
if st[x]==st[x+2]:
return True
return False
with open("input.txt") as f:
count = 0
while(True):
line = f.readline()
if not line:
break
if (rule2(line) and rule1(line)):
count+=1
print "Total nice strings are: ", count
|
d2d5c415bdb478397756373992c417d1bd17c1c0 | BossDing/Interview-example | /其他/字符串的排列/Permutation.py | 547 | 3.734375 | 4 | # -*- coding:utf-8 -*-
#输入一个字符串,按字典序打印出该字符串中字符的所有排列。
#例如输入字符串abc,则打印出由字符a,b,c
#所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if(ss==''):
return []
li=list(itertools.permutations(list(ss),len(ss)))
for i in range(len(li)):
li[i]=''.join(li[i])
l=list(set(li))
return (sorted(l))
|
05ade5232e2b47fcdaa2956056c1917f16fd1d5e | BirAnmol14/My-Python-Learning | /Automation Codes/Regex/RegExAdv.py | 2,213 | 3.53125 | 4 | #Regex advanced
# ? character -> optional my appear once or never
import re
batreg=re.compile(r'bat(wo)?man') #this means the wo group can apperaer 0 or one times in the pattern
mo=batreg.search('Adventures of batman')
print(mo.group())
mo=batreg.search('Adventures of batwoman')
print(mo.group())
mo=batreg.search('Adventures of batwowoman')
if not mo==None:
print(mo.group())
else: print('None')
mo=batreg.search('Adventures of batwo')
if not mo==None:
print(mo.group())
else: print('None')
print('***************************************')
preg=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo=preg.search('My number is 111-222-3333')
if not mo==None:
print(mo.group())
preg=re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo=preg.search('My number is 222-3333')
if not mo==None:
print(mo.group())
def aQuestion(str):
print('***********************************')
a=re.compile(r'\?')
mo=a.search(str)
if mo ==None:
print('No an interrogative sentence')
print('***********************************')
return
print('How dare you ask me a question')
print('***********************************')
aQuestion('How are you?')
aQuestion('bye!')
#Like ? (0 or 1) characters
# * matches 0 or more times
batreg=re.compile(r'bat(wo)*man') #this means the wo group can apperaer 0 or one times in the pattern
mo=batreg.search('Adventures of batman')
print(mo.group())
mo=batreg.search('Adventures of batwoman')
print(mo.group())
mo=batreg.search('Adventures of batwowoman')
print(mo.group())
# to match * use \*
#+ matches one or more times
#use \+ to match a plus in the string
msg='does 2+3-4*8=23? 123+*?'
t=re.compile(r'\+\*\?')
mo=t.findall(msg)
print(mo)
#Exact number of repetitions
laugh=re.compile(r'(ha){3}')#must be consecutive repititions
mo=laugh.search('hahaha he said')
print(mo.group())
pno=re.compile(r'((\d\d\d-)?\d\d\d-\d\d\d\d(,)?){3}')
mo=pno.search('my numbers are 999-888-7777,887-7654,123-234-3456')
print(mo.group())
#range of reps
# (){min,max}
#(){min,}->till infy
#(){,max}->0 to max
# by default greedy match, tries to match as many as possible
#to mke non-greedy match, (){}? write this, it will try to match the minimum number of times
|
c31350118e9a2a900b8a48623f0753c954a18c5c | karolwk/tictactoe | /tictactoe.py | 9,959 | 3.640625 | 4 | import random
import copy
class StaticMethods:
@staticmethod
def check_field(cords, board) -> bool:
# Check for "X" or "O" in specified field
if board[cords[0]][cords[1]] in ("X", "O"):
return True
else:
return False
@staticmethod
def avail_spots(board) -> []:
return [x for x in board if isinstance(x, int)]
@staticmethod
def change_sign(sign):
if sign == "O":
return "X"
else:
return "O"
@staticmethod
def check_draw(board: []) -> bool:
if all([x.count("_") == 0 for x in board]):
print("Draw")
return True
return False
@staticmethod
def check_win(board: [], sign) -> bool:
# Checking win or draw condition for hard coded situations
# Return 'True' in case of win
is_matrix = all(isinstance(ele, list) for ele in board)
if not is_matrix:
# Making matrix
board = [[board[i + x] for x in range(3)] for i in range(0, 8, 3)]
if (board[0][0] == sign) and (board[1][1] == sign) and (board[2][2] == sign):
return True
if (board[0][2] == sign) and (board[1][1] == sign) and (board[2][0] == sign):
return True
for i in range(3):
if (board[i][0] == sign) and (board[i][1] == sign) and (board[i][2] == sign):
return True
if (board[0][i] == sign) and (board[1][i] == sign) and (board[2][i] == sign):
return True
return False
@staticmethod
def print_board(board: []):
# Print board accordly to instructions
print(f"""{9 * "-"}
| {board[0][2]} {board[1][2]} {board[2][2]} |
| {board[0][1]} {board[1][1]} {board[2][1]} |
| {board[0][0]} {board[1][0]} {board[2][0]} |
{9 * "-"}""")
class Player:
def __init__(self):
self.player = ""
self.board = []
self.sign = ""
self.first_player = ""
self.second_player = ""
def _easy_ai_move(self) -> []:
# Returns random cords
while True:
move = [random.randrange(0, 3), random.randrange(0, 3)]
if not StaticMethods.check_field(move, self.board):
return move
def _medium_ai_move(self, sign) -> []:
# Creating temporary board and checking for win in specified cords for two different signs.
# First it returns cords for wining condition, secondly for blocking opponent wining move
# If it fails it behave as Easy AI
temp_board = copy.deepcopy(self.board)
for _ in range(2):
for i in range(3):
for n in range(3):
if self.board[i][n] == "_":
temp_board[i][n] = sign
if StaticMethods.check_win(temp_board, sign):
return [i, n]
else:
temp_board[i][n] = "_"
sign = StaticMethods.change_sign(sign)
return self._easy_ai_move()
def _hard_ai_move(self, sign) -> []:
# Finds the best move based on MiniMax Algorithm in Game Theory
self.first_player = sign
self.second_player = StaticMethods.change_sign(sign)
# Cords that we return up accordingly with number/key we get from min_max
cords = {0: [0, 2], 1: [1, 2], 2: [2, 2], 3: [0, 1], 4: [1, 1], 5: [2, 1], 6: [0, 0], 7: [1, 0], 8: [2, 0]}
# Creating new board for AI
new_board = [["_" for x in range(3)] for i in range(3)]
# Filling new board with data from original board in correct order for algorithm
for x in range(3):
for y in range(3):
new_board[2 - y][x] = self.board[x][y]
# Creating one dimension board
new_board = [new_board[n][i] for n in range(3) for i in range(3)]
# Changing "_" to index numbers
new_board = [num if value == "_" else value for num, value in enumerate(new_board)]
results = self._min_max(new_board, sign)[0]
return cords[results]
def make_move(self, player, board, sign) -> None:
self.board = board[:]
self.player = player
self.sign = sign
if player == "easy":
# Making move for "Easy" AI - AI makes only random decisions
move = self._easy_ai_move()
self.board[int(move[0])][int(move[1])] = sign
print(f'Making move level {player}')
StaticMethods.print_board(self.board)
if player == "medium":
# Making move for "Medium" AI
move = self._medium_ai_move(sign)
self.board[int(move[0])][int(move[1])] = sign
print(f'Making move level {player}')
StaticMethods.print_board(self.board)
if player == "hard":
move = self._hard_ai_move(sign)
self.board[move[0]][move[1]] = sign
print(f'Making move level {player}')
StaticMethods.print_board(self.board)
if player == "user":
# Human player logic
while True:
cords = input("Enter the coordinates: >").split()
if len(cords) == 2 and cords[0].isdigit() and cords[1].isdigit():
if (int(cords[0]) > 3) or (int(cords[1]) > 3):
print("Coordinates should be from 1 to 3!")
elif not StaticMethods.check_field([int(cords[0]) - 1, int(cords[1]) - 1], self.board):
self.board[int(cords[0]) - 1][int(cords[1]) - 1] = sign
StaticMethods.print_board(self.board)
break
else:
print("This cell is occupied! Choose another one!")
else:
print("You should enter numbers from 1 to 3 separated with space for example: '1 2'!")
def _min_max(self, board: [], player: str) -> ():
# Making list of available spots (index numbers)
spots = StaticMethods.avail_spots(board)
if StaticMethods.check_win(board, self.first_player):
return 0, 10
if StaticMethods.check_win(board, self.second_player):
return 0, -10
if len(spots) == 0:
return 0, 0
# dictionary that contains each move and values {board_index: value}
moves = {}
for value in spots:
# loop through available spots and fill 'moves' dict with indexes and values
moves[value] = value
board[value] = player
if player == self.first_player:
result = self._min_max(board, self.second_player)
moves[value] = result[-1]
else:
result = self._min_max(board, self.first_player)
moves[value] = result[-1]
# reset board to original value
board[value] = value
# tuple to return with best position and value
best_value = ()
# searching for best value depending on player that is playing
if player == self.first_player:
temp = -1000
for index, value in moves.items():
if value > temp:
temp = value
best_value = (index, value)
if player == self.second_player:
temp = 1000
for index, value in moves.items():
if value < temp:
temp = value
best_value = (index, value)
return best_value
def return_board(self) -> []:
return self.board
class TicTacToe:
def __init__(self):
self.board = []
self._parameters = ('user', 'easy', 'medium', 'hard', 'exit', 'start')
self._quit = False
self._reset_board()
def _check_parameters(self, *args) -> bool:
# Checking parameters if they are in tuple "_parameters"
for n in args:
if n not in self._parameters:
print('Bed parameters')
return True
if n == "exit":
self._quit = True
return True
if 3 != len(args) != 1:
print('Bed parameters')
return True
return False
def _reset_board(self) -> None:
self.board = [["_" for x in range(3)] for i in range(3)]
def play_game(self):
# Main game method
player1 = Player()
player2 = Player()
while True:
user_input = input("Input command: ").split()
if not self._check_parameters(*user_input):
StaticMethods.print_board(self.board)
while not self._quit:
if not StaticMethods.check_win(self.board, "O"):
if not StaticMethods.check_draw(self.board):
player1.make_move(user_input[1], self.board, "X")
self.board = player1.return_board()
if not StaticMethods.check_win(self.board, "X"):
if not StaticMethods.check_draw(self.board):
player2.make_move(user_input[2], self.board, "O")
self.board = player1.return_board()
else:
self._reset_board()
break
else:
print("X wins")
self._reset_board()
break
else:
self._reset_board()
break
else:
print("O wins")
self._reset_board()
break
if self._quit:
break
game = TicTacToe()
game.play_game()
|
d261169c5ecdecc6eccbdf3bbd95f7846954e1b8 | kojicovski/python | /exercises/ex018.py | 245 | 4.15625 | 4 | from math import sin, cos, radians, tan
degree = int(input('Type a value in degree :'))
print('Value of sin {:.4f}, cos {:.4f} and tg {:.4f} of {} degree'.format(sin(radians(degree)), \
cos(radians(degree)), tan(radians(degree)), degree))
|
6e4c1d8f83d99baf4c030cea3f9bdb29b062c00f | KangKyungJin/Poker_hackathon | /cards.py | 1,452 | 3.75 | 4 | import random
#class card to create card objects
class card:
def __init__(self,suit, val, numericVal):
self.suit=suit
self.val= val
self.numericVal=numericVal
def displaycardinfo(self):
return(f"{self.val}{self.suit}")
def returnVal(self):
if self.val == "Ace":
self.numericVal = 11
elif self.numericVal > 10:
self.numericVal = 10
return(self.numericVal)
# class hand:
# def __init__(self,numofcards=0):
# self.totalval=0
# self.numofcards=numofcards
# def addcard(self):
# self.numofcards+=1
# def handtotal(self):
# self.totalval+=self.numofcards.numericval
suitdict={ '0': '♥', '1':'♦', '2':'♠', '3': '♣'}
carddict={'1':'2','2':'3','3':'4','4':'5','5':'6','6':'7','7':'8','8':'9', '9':'10', '10':'Jack', '11':'Queen','12':'King','13':'Ace'}
#deck class for building a deck
class Deck:
def __init__(self,deckAmmount=1):
self.deck = []
for d in range(deckAmmount):
for x in range(4):
for y in range(13):
self.deck.append(card(x,y+1,y+2))
def shuffles(self):
length=len(self.deck)
for i in range(length):
r = random.randint(0,length-1)
self.deck[i], self.deck[r] = self.deck[r], self.deck[i]
return self
def draw(self):
card = self.deck.pop()
return card
|
23f1a63c1c676e67efbc0cba54116de481cd0fd5 | benjaminrall/uno | /display.py | 24,268 | 3.671875 | 4 | import turtle
def update():
turtle.update()
def resetFirst():
turtle.tracer(0,0)
turtle.speed(0)
turtle.ht()
turtle.pu()
def reset():
turtle.clear()
def write(x, y, size, text):
turtle.color("white")
turtle.fillcolor("white")
turtle.pu()
turtle.goto(x,y)
turtle.write(text,False,align="center",font=("Helvetica 97 Cond Black Oblique",size))
def draw(x, y, size, card):
if card[0] == 0:
colour = "red"
elif card[0] == 1:
colour = "#ffd633" #yellow
elif card[0] == 2:
colour = "#0099ff" #blue
elif card[0] == 3:
colour = "#008000" #green
else:
colour = "white"
try:
card[1] = int(card[1])
numberCard(x, y, size, colour, card[1])
except:
if card[1] == "d":
draw2Card(x, y, size, colour)
elif card[1] == "s":
skipCard(x, y, size, colour)
elif card[1] == "r":
reverseCard(x, y, size, colour)
elif card[1] == "w":
wildCard(x, y, size, colour)
elif card[1] == "f":
draw4Card(x, y, size, colour)
else:
unoCard(x, y, size)
def outline(x, y, size, colour):
global defaultSize
turtle.fillcolor(colour)
turtle.goto(x,y)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.left(90)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(0)
turtle.fd((defaultSize[0] * size) / 8)
turtle.pd()
turtle.begin_fill()
for i in range(2):
for i in range(6):
turtle.fd((defaultSize[0] * size) / 8)
turtle.circle(-((defaultSize[0] * size) / 8),90)
for i in range(10):
turtle.fd((defaultSize[1] * size) / 12)
turtle.circle(-((defaultSize[0] * size) / 8),90)
turtle.end_fill()
turtle.seth(180)
turtle.pu()
turtle.fd((defaultSize[0] * size) / 8)
turtle.seth(0)
def createCard(x, y, size, colour, colour2):
global defaultSize
turtle.color("white")
outline(x, y, size, "white")
size = size * 0.9
outline(x, y, size, colour)
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/4)
turtle.pd()
turtle.fillcolor(colour2)
turtle.color(colour2)
turtle.begin_fill()
turtle.fd((defaultSize[1] * size)/16)
turtle.circle(-80 * size,45)
turtle.circle(-60 * size,45)
turtle.circle(-14.2 * size,90)
turtle.fd((defaultSize[1] * size)/8)
turtle.circle(-80 * size,45)
turtle.circle(-60 * size,45)
turtle.circle(-14.2 * size,90)
turtle.end_fill()
turtle.pu()
def numberCard(x, y, size, colour, number):
global defaultSize
createCard(x,y,size,colour,"white")
turtle.goto(x,y)
turtle.seth(270)
turtle.fd(39 * size)
turtle.right(90)
turtle.fd(3 * size)
turtle.fillcolor("black")
turtle.color("black")
fontSize = round(48 * size)
turtle.write(str(number),False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize + (2*size)),"italic","bold"))
turtle.fillcolor(colour)
turtle.fd(size)
turtle.seth(90)
turtle.fd(2 * size)
turtle.color(colour)
turtle.write(str(number),False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.color("white")
turtle.fillcolor("white")
turtle.goto(x,y)
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) + (8 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
fontSize = round(12 * size)
turtle.write(str(number),False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) - (11 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.write(str(number),False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.pu()
def draw2Card(x, y, size, colour):
global defaultSize
createCard(x, y, size, colour,"white")
turtle.color("black")
size = size * 0.9
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/5)
turtle.seth(180)
size = size / 0.9
turtle.fd(size*9)
for i in range(2):
turtle.pd()
turtle.fillcolor("black")
turtle.begin_fill()
for i in range(2):
turtle.fd(size*20)
turtle.left(66)
turtle.fd(size*41)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.fd(size)
turtle.pd()
turtle.fillcolor("white")
turtle.begin_fill()
for i in range(2):
turtle.fd(size*20)
turtle.left(66)
turtle.fd(size*40)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.fd(size * 2)
turtle.left(66)
turtle.fd(size * 2)
turtle.left(294)
turtle.pd()
turtle.fillcolor(colour)
turtle.begin_fill()
for i in range(2):
turtle.fd(size*16)
turtle.left(66)
turtle.fd(size*36)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.left(66)
turtle.fd(size*20)
turtle.right(66)
turtle.fd(size*7)
turtle.goto(x,y)
turtle.color("white")
turtle.fillcolor("white")
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) + (5 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
fontSize = round(10 * size)
turtle.write("+2",False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) - (10 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.write("+2",False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.pu()
def skipCard(x, y, size, colour):
global defaultSize
createCard(x, y, size, colour,"white")
turtle.color("black")
size = size * 0.9
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/4)
turtle.seth(180)
size = size / 0.9
turtle.fd(size*37)
turtle.left(90)
turtle.fd(size*5.5)
turtle.seth(0)
turtle.pd()
turtle.begin_fill()
turtle.circle(-19.5*size)
turtle.end_fill()
turtle.pu()
turtle.seth(90)
turtle.fd(0.5*size)
turtle.seth(0)
turtle.fd(1*size)
turtle.seth(270)
turtle.color(colour)
turtle.fillcolor(colour)
turtle.fd(size)
turtle.right(90)
turtle.fd(size)
turtle.pd()
turtle.begin_fill()
turtle.circle(19*size,360)
turtle.end_fill()
turtle.pu()
turtle.seth(270)
turtle.color("black")
turtle.fillcolor("white")
turtle.fd(size*5)
turtle.seth(180)
turtle.pd()
turtle.begin_fill()
turtle.circle(13.5*size,360)
turtle.end_fill()
turtle.pu()
turtle.circle(13.5*size,125)
turtle.fd(3*size)
turtle.left(90)
turtle.pd()
turtle.fillcolor(colour)
turtle.begin_fill()
for i in range(2):
turtle.fd(size*27)
turtle.left(90)
turtle.fd(size*6)
turtle.left(90)
turtle.end_fill()
turtle.left(90)
turtle.color(colour)
for i in range(2):
turtle.fd(size*6)
turtle.pu()
turtle.right(90)
turtle.fd(size*27)
turtle.right(90)
turtle.pd()
turtle.pu()
turtle.goto(x,y)
turtle.color("black")
turtle.fillcolor("white")
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) + (3 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.pd()
turtle.begin_fill()
turtle.circle(5*size,360)
turtle.end_fill()
turtle.pu()
turtle.left(90)
turtle.fd(size*2)
turtle.right(90)
turtle.fillcolor(colour)
turtle.pd()
turtle.begin_fill()
turtle.circle(3*size,360)
turtle.end_fill()
turtle.pu()
turtle.circle(3*size,125)
turtle.fillcolor("white")
turtle.fd((2/3)*size)
turtle.left(90)
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*6)
turtle.left(90)
turtle.fd(size*(4/3))
turtle.left(90)
turtle.end_fill()
turtle.left(90)
turtle.color("white")
for i in range(2):
turtle.fd(size*(4/3))
turtle.pu()
turtle.right(90)
turtle.fd(size*6)
turtle.right(90)
turtle.pd()
turtle.pu()
turtle.color("black")
turtle.fillcolor("white")
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) + (2 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.pd()
turtle.begin_fill()
turtle.circle(5*size,360)
turtle.end_fill()
turtle.pu()
turtle.left(90)
turtle.fd(size*2)
turtle.right(90)
turtle.fillcolor(colour)
turtle.pd()
turtle.begin_fill()
turtle.circle(3*size,360)
turtle.end_fill()
turtle.pu()
turtle.circle(3*size,125)
turtle.fillcolor("white")
turtle.fd((2/3)*size)
turtle.left(90)
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*6)
turtle.left(90)
turtle.fd(size*(4/3))
turtle.left(90)
turtle.end_fill()
turtle.left(90)
turtle.color("white")
for i in range(2):
turtle.fd(size*(4/3))
turtle.pu()
turtle.right(90)
turtle.fd(size*6)
turtle.right(90)
turtle.pd()
turtle.pu()
turtle.color("black")
def reverseCard(x, y, size, colour):
global defaultSize
createCard(x, y, size, colour,"white")
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x,y)
for i in range(2):
turtle.seth(220)
turtle.fd(size*8)
turtle.seth(40)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.color(colour)
turtle.fillcolor(colour)
turtle.goto(x - 1.5*size,y + 1.5*size)
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x+(1.5*size),y-(1.5*size))
for i in range(2):
turtle.seth(40)
turtle.fd(size*8)
turtle.seth(220)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.color(colour)
turtle.fillcolor(colour)
turtle.goto(x+0.5*size,y+0.5*size)
turtle.goto(x,y)
turtle.color("black")
turtle.fillcolor("white")
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (8 * size))
size = size / 5
x2,y2 = turtle.xcor(),turtle.ycor()
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x2,y2)
for i in range(2):
turtle.seth(220)
turtle.fd(size*8)
turtle.seth(40)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.fillcolor("white")
turtle.goto(x2 - 1.5*size,y2 + 1.5*size)
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x2+(1.5*size),y2-(1.5*size))
for i in range(2):
turtle.seth(40)
turtle.fd(size*8)
turtle.seth(220)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.fillcolor("white")
turtle.goto(x2+0.5*size,y2+0.5*size)
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) - (185 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (118 * size))
x2,y2 = turtle.xcor(),turtle.ycor()
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x2,y2)
for i in range(2):
turtle.seth(220)
turtle.fd(size*8)
turtle.seth(40)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.fillcolor("white")
turtle.goto(x2 - 1.5*size,y2 + 1.5*size)
turtle.color("black")
turtle.fillcolor("black")
turtle.goto(x2+(1.5*size),y2-(1.5*size))
for i in range(2):
turtle.seth(40)
turtle.fd(size*8)
turtle.seth(220)
turtle.pd()
turtle.begin_fill()
turtle.fd(size*24)
turtle.right(90)
turtle.fd(7*size)
turtle.left(135)
turtle.fd(18*size)
turtle.left(90)
turtle.fd(18*size)
turtle.left(135)
turtle.fd(7*size)
turtle.right(90)
turtle.fd(size*12)
turtle.circle(12*size,90)
turtle.end_fill()
turtle.pu()
turtle.fillcolor("white")
turtle.goto(x2+0.5*size,y2+0.5*size)
turtle.pu()
def wildCard(x, y, size, colour):
global defaultSize
createCard(x, y, size, "black","white")
size = size*0.8
turtle.color("black")
turtle.goto(x,y)
turtle.seth(0)
turtle.fd(40*size)
turtle.seth(90)
turtle.fd(size*30)
turtle.seth(270)
turtle.pd()
turtle.fillcolor("red")
turtle.color("red")
turtle.begin_fill()
turtle.fd((defaultSize[1] * size)/16)
turtle.circle(-80 * size,45)
turtle.circle(-60 * size,45)
turtle.circle(-14.2 * size,90)
turtle.fd((defaultSize[1] * size)/8)
turtle.circle(-80 * size,45)
turtle.circle(-60 * size,45)
turtle.circle(-14.2 * size,90)
turtle.end_fill()
turtle.pu()
turtle.goto(x,y)
turtle.color("#ffd633")
turtle.fillcolor("#ffd633")
turtle.seth(90)
turtle.right(20)
turtle.begin_fill()
turtle.pd()
turtle.fd(size*55)
turtle.goto(x,y)
turtle.seth(0)
turtle.fd(size*36.7)
turtle.left(70)
turtle.circle(90*size,20)
turtle.circle(30*size,30)
turtle.circle(15*size,70)
turtle.fd(10*size)
turtle.end_fill()
turtle.color("#008000")
turtle.fillcolor("#008000")
turtle.begin_fill()
turtle.circle(56*size,50)
turtle.circle(180*size,8.55)
turtle.left(111)
turtle.fd(size*37.8)
turtle.end_fill()
turtle.seth(0)
turtle.right(105)
turtle.color("#0099ff")
turtle.fillcolor("#0099ff")
turtle.begin_fill()
turtle.fd(51.8*size)
turtle.right(67)
turtle.fd(10*size)
turtle.circle(-17*size,100)
turtle.fd(10*size)
turtle.right(5)
turtle.fd(size*10)
turtle.right(6)
turtle.fd(size*2)
turtle.fd(size*12.5)
turtle.seth(0)
turtle.fd(size*38)
turtle.end_fill()
turtle.pu()
turtle.goto(x,y)
turtle.color("black")
turtle.fillcolor(colour)
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) - (10 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (13 * size))
turtle.pd()
turtle.begin_fill()
turtle.circle(5*size,360)
turtle.end_fill()
turtle.pu()
turtle.color("black")
turtle.fillcolor(colour)
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) - (10 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (13 * size))
turtle.pd()
turtle.begin_fill()
turtle.circle(5*size,360)
turtle.end_fill()
turtle.pu()
def draw4Card(x, y, size, colour):
global defaultSize
createCard(x, y, size, "black","white")
size = size*0.8
turtle.color("black")
turtle.goto(x,y)
turtle.seth(0)
turtle.fd(37*size)
turtle.seth(90)
turtle.fd(size*30.5)
turtle.seth(270)
turtle.fd(size*5)
turtle.seth(180)
size = (size/0.8) * 0.85
turtle.pd()
turtle.fillcolor("black")
for i in range(2):
xg,yg = turtle.xcor(),turtle.ycor()
turtle.begin_fill()
turtle.left(66)
turtle.fd(size*41)
turtle.right(66)
turtle.fd(size*10)
xy,yy = turtle.xcor(),turtle.ycor()
turtle.left(66)
turtle.fd((4/6) * size*41)
turtle.right(66)
turtle.fd(size*20)
turtle.right(114)
turtle.fd((2/6) * size*41)
turtle.seth(180)
turtle.fd((4/5) * size*20)
turtle.right(114)
turtle.fd(size*41)
turtle.right(66)
xr,yr = turtle.xcor(),turtle.ycor()
turtle.fd(10*size)
turtle.left(66)
turtle.fd((4/6) * size*41)
turtle.right(66)
turtle.fd(size*20)
xb,yb = turtle.xcor(),turtle.ycor()
turtle.right(114)
turtle.fd((2/6) * size*41)
turtle.seth(0)
turtle.fd((4/5) * size*20)
turtle.pu()
turtle.end_fill()
turtle.seth(90)
turtle.fd(0.5*size)
turtle.seth(180)
turtle.fd(0.5*size)
turtle.pd()
turtle.fillcolor("white")
turtle.pu()
turtle.goto(xy,yy)
turtle.color("#ffd633")
turtle.fillcolor("#ffd633")
turtle.seth(66)
turtle.fd((2/6) * size*41)
turtle.seth(270)
turtle.fd(size * 1.5)
turtle.seth(180)
turtle.fd(size*2)
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*17)
turtle.left(66)
turtle.fd(size*38)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.goto(xg,yg)
turtle.seth(246)
turtle.color("black")
turtle.fillcolor("white")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*41)
turtle.right(66)
turtle.fd(size*20)
turtle.right(114)
turtle.pu()
turtle.end_fill()
turtle.seth(270)
turtle.fd(size * 1.5)
turtle.seth(180)
turtle.fd(size*2)
turtle.color("#008000")
turtle.fillcolor("#008000")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*17)
turtle.left(66)
turtle.fd(size*38)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.goto(xb,yb)
turtle.seth(246)
turtle.color("black")
turtle.fillcolor("white")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*41)
turtle.right(66)
turtle.fd(size*20)
turtle.right(114)
turtle.pu()
turtle.end_fill()
turtle.seth(270)
turtle.fd(size * 1.5)
turtle.seth(180)
turtle.fd(size*2)
turtle.color("#0099ff")
turtle.fillcolor("#0099ff")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*17)
turtle.left(66)
turtle.fd(size*38)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.goto(xr + (size*20),yr)
turtle.seth(246)
turtle.color("black")
turtle.fillcolor("white")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*41)
turtle.right(66)
turtle.fd(size*20)
turtle.right(114)
turtle.pu()
turtle.end_fill()
turtle.seth(270)
turtle.fd(size * 1.5)
turtle.seth(180)
turtle.fd(size*2)
turtle.color("red")
turtle.fillcolor("red")
turtle.pd()
turtle.begin_fill()
for i in range(2):
turtle.fd(size*17)
turtle.left(66)
turtle.fd(size*38)
turtle.left(114)
turtle.end_fill()
turtle.pu()
turtle.goto(x,y)
turtle.color(colour)
turtle.fillcolor(colour)
turtle.seth(180)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(90)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(270)
turtle.fd(((defaultSize[0] * size)/4) - (5 * size))
turtle.seth(0)
turtle.fd(((defaultSize[0] * size)/4) - (10 * size))
fontSize = round(10 * size)
turtle.write("+4",False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.goto(x,y)
turtle.seth(0)
turtle.fd((defaultSize[0] * size)/2)
turtle.seth(270)
turtle.fd((defaultSize[1] * size)/2)
turtle.seth(90)
turtle.fd(((defaultSize[0] * size)/4) - (20 * size))
turtle.seth(180)
turtle.fd(((defaultSize[0] * size)/4) - (8 * size))
turtle.write("+4",False,align="center",font=("Helvetica 97 Cond Black Oblique",int(fontSize),"italic","bold"))
turtle.pu()
def unoCard(x, y, size):
global defaultSize
createCard(x, y, size, "black","red")
turtle.color("black")
turtle.fillcolor("blue")
turtle.goto(x,y)
turtle.fd(size*20)
turtle.right(90)
turtle.fd(size*25)
turtle.right(110)
turtle.fd(size*7)
turtle.seth(180)
turtle.fd(size*5.5)
fontSize = round(size*18)
turtle.write("UNO",False,align="left",font=("Ariel Bold",int(fontSize),"bold"))
turtle.seth(270)
turtle.fd(size*1)
turtle.left(90)
turtle.fd(1*size)
turtle.color("skyblue")
turtle.write("UNO",False,align="left",font=("Ariel Bold",int(fontSize),"bold"))
turtle.seth(270)
turtle.fd(size*1)
turtle.left(90)
turtle.fd(1*size)
turtle.color("yellow")
turtle.write("UNO",False,align="left",font=("Ariel Bold",int(fontSize),"bold"))
turtle.pu()
defaultSize = [80,120]
resetFirst()
turtle.bgcolor("grey")
|
a7e1384c179cd458abef9eb9eb42ea9a0a2d4793 | GianlucaTravasci/Coding-Challenges | /Advent of Code/2020/Day 3/solution3.py | 613 | 3.5 | 4 | with open('input.txt', 'r') as file:
map_lines = file.read().splitlines()
line_length = len(map_lines[0])
def way_tree_counter(right, down):
tree_counter = 0
for i in range(0, int(len(map_lines) / down)):
step = i * right
if map_lines[i * down][step % line_length] == '#':
tree_counter += 1
return tree_counter
# Part 1
print(f"Part one (right 3, down 1): {way_tree_counter(3, 1)}")
# Part 2
ways = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
multiply_all = 1
for way in ways:
multiply_all *= way_tree_counter(way[0], way[1])
print(f"Part two: {multiply_all}")
|
4ba42df9e051ece562b5d6f9d4b537ad8da1bb28 | vineetpathak/Python-Project2 | /reverse_alternate_k_nodes.py | 965 | 4.21875 | 4 | # -*- coding: UTF-8 -*-
# Program to reverse alternate k nodes in a linked list
import initialize
def reverse_alternate_k_nodes(head, k):
count = 0
prev = None
curr = head
# reverse first k nodes in link list
while count < k and curr:
next = curr.nextnode
curr.nextnode = prev
prev = curr
curr = next
count += 1
# head will point to k node. So next of it will point to the k+1 node
if head:
head.nextnode = curr
# don't want to reverse next k nodes.
count = 0
while count < k-1 and curr:
curr = curr.nextnode
count += 1
# Recursively call the same method if there are more elements in the link list
if curr:
curr.nextnode = reverse_alternate_k_nodes(curr.nextnode, k)
return prev
head = initialize.initialize_linked_list()
head = reverse_alternate_k_nodes(head, 2)
print "After reversing the alternate k nodes in linked list"
while head:
print head.data
head = head.nextnode
|
6cd26e15abb228d8ae218504dcd89472ebff7401 | AdrienCeschin/sauvegarde-formation | /python_training/vagrant/sapin.py | 514 | 4 | 4 | nb_lines = int(input('Please enter the height of the tree, int and positive values only: '))
distance = ' '
branch = '^'
if nb_lines>0:
n=0
while n != nb_lines:
tmp_line = ''
tmp_distance = distance*(nb_lines-1-n)
tmp_branch = branch*(2*n+1)
tmp_line = tmp_distance + tmp_branch + tmp_distance
print(tmp_line)
n=n+1
else:
print('Please follow the instructions and enter a proper (integer and positive) value next time, else you will not get any tree.') |
b463750c73e5cdd0586379a091a84c977182a2d9 | Rushikesh8421/Python-projects-2 | /Grocery Billing application.py | 894 | 3.953125 | 4 | """
Project By: Rushikesh Patil;
Description: A grocery billing application to display and sum total bill using Python;
"""
def sum_single(quantity, price):
return price*quantity;
mylist = [];
suma = 0;
new_item = "y"
while new_item == "y":
print("...Guruprasad Grocery...")
item = input("Enter the name of item: ");
quantity = int(input(f"Enter the Quantity of {item}: "));
price = int(input(f"Enter the prince per unit item of {item}: "));
total = sum_single(price, quantity);
suma = suma+total;
mylist.append(f"{item} of quantity {quantity} so {price}*{quantity} = {total}")
new_item = str(input("Want to add new item y/n: "));
print(".....🛍️WELCOME TO GURUPRASAD GROCERIES🛍️.....")
for i in mylist:
print(i);
print(f"THE TOTAL BILL IS ₹ {suma}/-only.\nThanks for shopping with us 🙏🙏, have a nice day! 😊😊")
|
8fe42c20049a4d1590f99ecec25de72cb5a95f62 | IronE-G-G/algorithm | /leetcode/101-200题/139wordBreak.py | 2,029 | 3.828125 | 4 | """
139 单词拆分
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
dpi 前i个元素为结尾的子串是否能拆分
"""
if not wordDict:
return False
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
wordDict = set(wordDict)
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[-1]
class Solution1(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
回溯 dfs
复杂度为n**n
最大的例子时会超时
"""
if not wordDict:
return False
self.size = set([len(item) for item in wordDict])
self.min_size = min(self.size)
self.res = False
wordDict = set(wordDict)
def backtrack(s):
if not s:
self.res = True
return
if len(s) < self.min_size:
return
for i in [item for item in self.size if item <= len(s)]:
if s[:i] in wordDict:
backtrack(s[i:])
backtrack(s)
return self.res
|
477a1f977f2f2225622e4c0f1c1e492fc59bde49 | himangi6550/student-data | /test2.py | 421 | 3.75 | 4 | import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
for i in range(1,5):
mysid=int(input("enter id:"))
myname=input("enter name:")
myage=int(input("enter age:"))
mymarks=float(input("enter marks:"))
curschool.execute("insert into student(StudentID,name,age,marks) values (?,?,?,?);",(mysid,myname,myage,mymarks))
MySchool.commit()
|
dd1ecb055c5c4234ae5c1766efb4315afa9db215 | Zorro30/Udemy-Complete_Python_Masterclass | /Using Tkinter/tkinter_button_command.py | 225 | 3.828125 | 4 | #On Click listener
from tkinter import *
root = Tk()
def doSomething():
print ("Button is been clicked!")
button1 = Button(root, text = "Click here!", command = doSomething)
button1.pack()
root.mainloop() |
5f256b2646576b1f8c3a49c07e498305b0fd6f59 | JOHNTESFU/python | /exercice 8.py | 867 | 4.09375 | 4 | def say_hi(name, age):
print("hello " + name, "you are " + str(age))
say_hi("john" , 33)
say_hi("mike" , 23)
print("--------------------------")
def cube(num):
return num*num*num
result= cube(10*10)
print(result)
print("----------------------------")
is_male = True
is_tall = True
if is_male and is_tall:
print("you are a tall male")
elif is_male and not(is_tall):
print("you are a short male")
elif not (is_male) and is_tall:
print("you are a not a male but are tall")
else:
print("you are not a male and not tall")
print("---------------------")
def max_num(num1, num2,num3) :
if num1 >= num2 and num1>=num3:
return num1
elif num2>= num1 and num2 >=num3:
return num2
else:
return num3
print(max_num(3,3,5))
print("---------------")
|
7e9138ddef64d39a390cc480b0e2bf4cbc2cc2be | AileenXie/leetcode | /written-examination/0823iqiyi_wsf/01.py | 1,394 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/23 4:06 PM
# @Author : aileen
# @File : 01.py
# @Software: PyCharm
class Solution:
def func(self,string,words):
if not words: return string
dic = {}
dic_len = {}
for word in words:
dic.setdefault(word[0],[]).append(word)
dic_len.setdefault(word[0],set()).add(len(word))
ans = ""
i=0
while i<len(string):
s=string[i]
if s not in dic:
ans+=s
else:
for word_len in dic_len[s]:
j,l=i+1,1
cur=s
while l<word_len and j<len(string):
if string[j]!=" ":
cur+=string[j]
l+=1
j+=1
if l<word_len: # 长度不够
continue
if cur in dic[s]: # 匹配
ans+=" "+cur+" "
i = j-1 # 处理下一个字符
break
i+=1
return " ".join(list(ans.split()))
print(Solution().func("可 今日小 主要 参加殿 选",["小主","殿选"]))
print(Solution().func("aa bcd edf deda",["ded"]))
print(Solution().func("娘娘 谬赞,臣妾愧 不敢 当",["愧不敢当"]))
|
472f41f9d8b86bd1f3d74e40df84cbe780063a56 | yaolizheng/leetcode | /166/fraction.py | 545 | 3.578125 | 4 | def fraction(n, d):
res = ''
if n / d < 0:
res += '-'
if n % d == 0:
return str(n / d)
table = {}
res += str(n / d)
res += '.'
n = n % d
i = len(res)
while n != 0:
if n not in table:
table[n] = i
else:
i = table[n]
res = res[:i] + '(' + res[i:] + ')'
return res
n = n * 10
res += str(n / d)
n = n % d
i += 1
return res
if __name__ == '__main__':
n = 1
d = 8
print fraction(n, d)
|
700b79e970f6dbc27004911bb7b8b2ed1537c9ee | hemal507/python | /reverseOnDiagonals.py | 715 | 3.578125 | 4 | def reverseOnDiagonals(matrix):
l=len(matrix)/2
pos=len(matrix)-1
for x in range(l) :
matrix[x][x] , matrix[pos][pos] = matrix[pos][pos] , matrix[x][x]
pos -= 1
pos=len(matrix)-1
for x in range(l) :
matrix[pos][x] , matrix[x][pos] = matrix[x][pos] , matrix[pos][x]
pos -= 1
return matrix
#print(reverseOnDiagonals([[1,2,3], [4,5,6], [7,8,9]]))
print(reverseOnDiagonals( [ [1,2,3,4] , [5,6,7,8] , [9,10,11,12] , [13,14,15,16] ] ) )
print(reverseOnDiagonals( [[43,455,32,103], [102,988,298,981], [309,21,53,64], [2,22,35,291]] ) )
#[[34,1000,139,248,972,584], [98,1,398,128,762,654], [33,498,132,543,764,43], [329,12,54,764,666,213], [928,109,489,71,837,332], [93,298,42,53,76,43]] ) )
|
1451daf71d99d11b76b8d2581e80e7bcff6cb36f | irtefa/skoop | /classifiers/wordcountclassifier.py | 803 | 3.78125 | 4 | """
WordCount classifier -- scores a doc based on word count
"""
from classifier import Classifier
import string
class WordCountClassifier(Classifier):
# constructs a word count classifier based a given input word
def __init__(self, options):
keyword = options['keyword-word']
self.keyword = keyword
# scores the document based on word count
def score_document(self, title, content, rank):
words = content.lower().split()
punc = set(string.punctuation)
words = [''.join(ch for ch in word if ch not in punc) for word in words]
count = words.count(self.keyword)
return float(count)/float(len(words))
def get_labels(self):
word = '"' + self.keyword + '"'
return ["Proportion of word " + word, "Low", "High"]
|
124eb9acffee943f3d0a93042373b475cbf2837d | thegapro/CSPC4810-Assigments | /pythonquestion.sh | 435 | 3.703125 | 4 | #!/usr/bin/env python3
import pandas as pd
df = pd.read_csv('2007.csv')
delay = df[['ArrDelay']][df['Origin'] == 'SFO'].head(3)
print("a, The first 3 of the arrival delay for the flights that depart from SFO are: \n",delay)
top = pd.DataFrame(df['Dest'].value_counts().head(3))
top = top.reset_index()
top.columns = ['Dest','Counts']
print("b, The top 3 destination airports are: \n",top)
print('\n')
print('Tuan Anh Nguyen - 100348136')
|
b9ff5b4754da25a26d736cb5dda5361ac1e85cfe | muhammadqasim3/Python-Programming-Exercises | /2_Odd_Even.py | 200 | 4.15625 | 4 | number = int(input("Enter the number you want to check: "))
if number % 2 == 0 and number % 4 == 0:
print("Even and Divisible by 4")
elif number % 2 == 0:
print("Even")
else:
print("odd")
|
291e6cc0b65e5c66b5aebcb471519cb7247fdb02 | Lekanda/master-python | /07-Ejercicios/ejercicio8.py | 276 | 3.828125 | 4 | """
TANTO POR CIENTO: Con dos numeros dados. El total y el % a sacar
"""
num=int(input("Dame el numero total: "))
tanto=int(input("Dame el %: "))
resultado=0
cienparte=0
cienparte=num/100
resultado=cienparte*tanto
print(f"El {tanto}% de {num} es: {resultado}")
print("\n\n")
|
971c3ad295e7a85387538cfd412e05f21ed13594 | kasthuri2698/python | /naturalnumber.py | 154 | 3.609375 | 4 | number=input()
number=number.split()
num1=int(number[0])
num2=int(number[1])
sum=0
z=input().split()
for i in range(num2):
sum=sum+int(z[i])
print(sum)
|
61fba2eb691dbcc608145126470647c50a3a3b2f | python-cmd2/cmd2 | /examples/decorator_example.py | 4,375 | 3.515625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""A sample application showing how to use cmd2's argparse decorators to
process command line arguments for your application.
Thanks to cmd2's built-in transcript testing capability, it also
serves as a test suite when used with the exampleSession.txt transcript.
Running `python decorator_example.py -t exampleSession.txt` will run
all the commands in the transcript against decorator_example.py,
verifying that the output produced matches the transcript.
"""
import argparse
from typing import (
List,
)
import cmd2
class CmdLineApp(cmd2.Cmd):
"""Example cmd2 application."""
def __init__(self, ip_addr=None, port=None, transcript_files=None):
shortcuts = dict(cmd2.DEFAULT_SHORTCUTS)
shortcuts.update({'&': 'speak'})
super().__init__(transcript_files=transcript_files, multiline_commands=['orate'], shortcuts=shortcuts)
self.maxrepeats = 3
# Make maxrepeats settable at runtime
self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self))
# Example of args set from the command-line (but they aren't being used here)
self._ip = ip_addr
self._port = port
# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
# self.default_to_shell = True
speak_parser = cmd2.Cmd2ArgumentParser()
speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
speak_parser.add_argument('words', nargs='+', help='words to say')
@cmd2.with_argparser(speak_parser)
def do_speak(self, args: argparse.Namespace):
"""Repeats what you tell me to."""
words = []
for word in args.words:
if args.piglatin:
word = '%s%say' % (word[1:], word[0])
if args.shout:
word = word.upper()
words.append(word)
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
self.poutput(' '.join(words))
do_say = do_speak # now "say" is a synonym for "speak"
do_orate = do_speak # another synonym, but this one takes multi-line input
tag_parser = cmd2.Cmd2ArgumentParser()
tag_parser.add_argument('tag', help='tag')
tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
@cmd2.with_argparser(tag_parser)
def do_tag(self, args: argparse.Namespace):
"""create an html tag"""
# The Namespace always includes the Statement object created when parsing the command line
statement = args.cmd2_statement.get()
self.poutput("The command line you ran was: {}".format(statement.command_and_args))
self.poutput("It generated this tag:")
self.poutput('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
@cmd2.with_argument_list
def do_tagg(self, arglist: List[str]):
"""version of creating an html tag using arglist instead of argparser"""
if len(arglist) >= 2:
tag = arglist[0]
content = arglist[1:]
self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content)))
else:
self.perror("tagg requires at least 2 arguments")
if __name__ == '__main__':
import sys
# You can do your custom Argparse parsing here to meet your application's needs
parser = cmd2.Cmd2ArgumentParser(description='Process the arguments however you like.')
# Add a few arguments which aren't really used, but just to get the gist
parser.add_argument('-p', '--port', type=int, help='TCP port')
parser.add_argument('-i', '--ip', type=str, help='IPv4 address')
# Add an argument which enables transcript testing
args, unknown_args = parser.parse_known_args()
port = None
if args.port:
port = args.port
ip_addr = None
if args.ip:
ip_addr = args.ip
# Perform surgery on sys.argv to remove the arguments which have already been processed by argparse
sys.argv = sys.argv[:1] + unknown_args
# Instantiate your cmd2 application
c = CmdLineApp()
# And run your cmd2 application
sys.exit(c.cmdloop())
|
86a576383c9febd6a8b5a47e5c9889b54b24f5ec | zhanghuaisheng/mylearn | /Python基础/day002/06 运算符.py | 1,316 | 3.640625 | 4 | # 1.比较运算符
"""
> <
>= <=
==
!=
"""
# 2.算术运算符
"""
+ - * /
// 整除,向下取整(地板除)
** 幂
% 取余,取模
"""
# print(5 / 2) #2.5
# print(5 // 2) #2
# print(5 ** 2) #25
# print(5 % 2) #1
# 3.赋值运算符
"""
=
+=
-=
*=
/=
//=
**=
%=
"""
# a = 10
# b = 2
# b += 1 #b = b + 1
# a -= 1 #a = a -1
# a *= 2 #a = a *2
# a /= 2 #a = a / 2
# a //= 2 #a = a // 2
# a **= 2 #a = a ** 2
# a %= 2 #a = a % 2
# 4.逻辑运算符
# True 和 False 逻辑运算时
"""
与(and):同真为真,有假为假
或(or):有真为真,同假为假
非(not):取反
优先级:() > not > and > or
查找顺序:从左向右
"""
# 数字逻辑运算时(面试用):
# and数字不为0时和不为False:and运算选择and后面的内容
# and两边都为假时选择and左边
# 一真一假选假
# print(1 and 3)
# print(0 and 8)
# print(9 and 0)
# print(9 and True)
# print(True and 9)
# print(9 and False)
# print(2 or -2)
# or数字不为0时和不为False:or算选择or前面的内容
# or两边都为假时选择or左边
# 一真一假选真
# print(1 or 2)
# print(1 or 0)
# print(-2 or 0)
# 5.成员运算符
"""
in:在
not in:不在
"""
# name = 'name'
# msg = input('输入内容')
# if name in msg:
# print("在")
# else:
# print("不在") |
e3c584f5a4fd3a22abe27ceb800ce311c8d29c82 | adamlwgriffiths/PyMesh | /pymesh/md5/common.py | 2,357 | 3.609375 | 4 | import math
def process_md5_buffer( buffer ):
"""Generator that processes a buffer and returns
complete OBJ statements.
Empty lines will be ignored.
Comments will be ignored.
Multi-line statements will be concatenated to a single line.
Start and end whitespace will be stripped.
"""
def md5_line( buffer ):
"""Generator that returns valid OBJ statements.
Removes comments, whitespace and concatenates multi-line
statements.
"""
while True:
line = buffer.next()
# check if we've hit the end
# EOF is signified by ''
# whereas an empty line is '\n'
if line == '':
break
# remove any whitespace
line = line.strip()
# remove any comments
line = line.split( '//' )[ 0 ]
# don't return empty lines
if len( line ) <= 0:
continue
yield line
# use our generator to remove comments and empty lines
gen = md5_line( buffer )
# iterate through each valid line of the OBJ file
# and yield full statements
for line in gen:
yield line
def parse_to( buffer, keyword ):
"""Continues through the buffer until a line with a
first token that matches the specified keyword.
"""
while True:
line = buffer.next()
if line == '':
return None
values = line.split( None )
if values[ 0 ] == keyword:
return line
def compute_quaternion_w( x, y, z ):
"""Computes the Quaternion W component from the
Quaternion X, Y and Z components.
"""
# extract our W quaternion component
w = 1.0 - (x ** 2) - (y ** 2) - (z ** 2)
if w < 0.0:
w = 0.0
else:
w = math.sqrt( w )
return w
class MD5( object ):
md5_version = 10
def __init__( self ):
super( MD5, self ).__init__()
self.md5_version = None
def load( self, filename ):
"""
Reads the MD2 data from the existing
specified filename.
@param filename: the filename of the md2 file
to load.
"""
with open( filename, 'r' ) as f:
self.load_from_buffer( f )
def load_from_buffer( self, buffer ):
raise NotImplementedError
|
725f84647af17d9c670ab18011ff2a4f8dac09f9 | gabealvarez11/BrownianMassMeasurement | /Gabe/expectedMass.py | 274 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 23 14:44:22 2018
@author: alvar
"""
import numpy as np
def expectedMass(diameter):
density = 2000 #kg / m^3
return density* 4./3*np.pi*np.power(diameter / 2, 3)
diam = 2.01*10**(-6) #m
print expectedMass(diam), "kg" |
f2ff9d4871f43e99d46ae73f9d74fd836bb715ed | PauloAlexSilva/Python | /Sec_14_iteradores_geradores/a_iterators_iterables.py | 666 | 4.71875 | 5 | """
Iterators e Iterables
Iterator:
- É um objeto que pode ser iterado;
- Um objeto que retorna um dado, sendo um elemento por vez quando uma função next() é chamada.
Iterable:
- Um objeto que irá retornar um iterator quando a função iter() for chamada.
nome = 'Paulo' # É um iterable mas não é um iterator
numeros = [1, 2, 3, 4, 5] # É um iterable mas não é um iterator
it_1 = iter(nome)
it_2 = iter(numeros)
print(next(it_1)) # P
print(next(it_1)) # A
print(next(it_1)) # U
print(next(it_1)) # L
print(next(it_1)) # O
"""
nome = 'Paulo'
for letra in nome: # transforma o nome que é iterable num iterator
print(f'{letra}')
|
071d438f2e8c0e9dd2b239f13b52d86073c7e7ab | clintKunz/Data-Structures | /binary_search_tree/binary_search_tree.py | 1,563 | 4.03125 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return f'value: {self.value}'
def insert(self, value):
# check if the new node's value is less than our current node's value
if value < self.value:
# check if no left child
if not self.left:
# park the new node here
self.left = BinarySearchTree(value)
# otherwise keep traversing further down
else:
self.left.insert(value)
#check the right side
else:
# check if no right child
if not self.right:
self.right = BinarySearchTree(value)
else:
# keep recursing down to the right since there is a right child
self.right.insert(value)
def contains(self, target):
if self.value == None:
return False
elif target == self.value:
return True
elif target < self.value and self.left:
return self.left.contains(target)
elif target > self.value and self.right:
return self.right.contains(target)
else:
return False
def get_max(self):
max = 0
current = self
while current:
if current.value > max:
max = current.value
current = current.right
return max
def for_each(self, cb):
self.value = cb(self.value)
if self.left:
self.left.for_each(cb)
if self.right:
self.right.for_each(cb)
a = BinarySearchTree(11)
a.insert(5)
a.insert(15)
a.insert(3)
a.insert(6)
a.insert(20)
print(a.value)
print(a.get_max()) |
2127aeaa1ef3c8fa4c82f20c11353e6578fbe040 | wusanshou2017/Leetcode | /using_python/154_findmin.py | 278 | 3.5625 | 4 | from typing import List
import random
# [2,2,2,0,1]
class Solution:
def findMin (self,nums:List[int])-> int:
l =0
r = len (nums)-1
while l<r:
mid =(l+r)//2
if nums[mid]<nums[r]:
r=mid
elif nums[mid]>nums[r]:
l=mid+1
else:
r-=1
return nums[l]
|
4202367baaac485691b433056e60821abe12279b | Tanjim-js-933/python-practice | /odd_even.py | 147 | 4.21875 | 4 | string = input("please give a number: ")
num = int(string)
if num % 2 == 0:
print("it is a even number")
else:
print("it is a odd number")
|
de25eefc225ba5a51098c5a7a8b765ce9243d826 | bschs1/IBM_data_science | /Scripts/numpy_aprendendo_01/numpy02_arrays_2D.py | 3,713 | 4.65625 | 5 | import numpy as np
import matplotlib.pyplot as plt
#O que vou ver nessa aula?
#Criação de arrays 2D
#Indexing e Slicing de Arrrays 2D
#Operações básicas em Arrays 2D
#[start:end:step] -> ARRAY SLICING
# Slicing in python means taking elements from one given index to another given index.
#
# We pass slice instead of index like this: [start:end].
#
# We can also define the step, like this: [start:end:step].
#
# If we don't pass start its considered 0
#
# If we don't pass end its considered length of array in that dimension
#
# If we don't pass step its considered 1
def separador():
print('************************************************************************\n' )
#arrays 2D
print('abaixo uma lista contendo outras listas aka nested lists todas com o mesmo tamanho:')
a = [[11,12,13], [21,22,23], [31,32,33]]
print(a)
separador()
print('transformando uma lista em um array: ')
a = np.array(a)
print(type(a))
separador()
print('Número de nested lists:')
print(f'O Número de Dimensões do array: {np.ndim(a)}')
print(f'O Shape {np.shape(a)}, E Retorna uma tupla dizendo que nesse caso é 3 por 3')
print(f'O Tamanho do array: {np.size(a)}')
print(f'Shape: {a.shape}') # shape
print(f'Size: {a.size}')
print(f'Numero de Dimensões: {a.ndim}')
separador()
print('Acessando elementos do array: ')
print(f'segunda linha, segunda coluna temos o elemento:\n {a[1,2]}') # segunda linha, 2 coluna
print(f'Segunda Linha e Terceira Coluna temos o elemento:\n {a[1][2]}') # mesma coisa da linha 36, mas da p ser desse jeito
print(f'Acessando Linha 0 e Coluna 0 temos o elemento:\n {a[0,0]}' )
separador()
print('Slicing de Arrays 2D')
# print('we can also use slicing in numpy arrays. Consider the following figure. We would like to obtain the first two columns in the first row')
print(f'Acessando os elementos da primeira Linha e Primeira e Segunda Coluna: {a[0][0:2]}') # o [0:2] SIGNIFICA ACESAR AS PRIMEIRAS 2 COLUNAS
print(f'Acessando as Duas Primeiras Linhas da Terceira Coluna: {a[0:2, 2]}') # o [0:2] CORRESPONDE AS DUAS PRIMEIRAS LINHAS E O ,2 É A COLUNA
print(np.array(a))
print(f'{a[0,1:3]}')
separador()
print('Operações Básicas')
print('Soma de Arrays:')
x = np.array([[1,0], [0,1]])
print(f'Array X: \n{x}')
y = np.array([[2,1], [1,2]])
print(f'Array Y: \n{y}')
print(f'Somando os Arrays X e Y:')
z = x +y
print(f'O valor de Z é: \n{z}')
separador()
print('Multiplicação de Arrays')
Y = np.array([[2,1], [1,2]])
print(f'O Array Y: \n {Y}')
print(f'Multiplicando o Array Y por 2 Temos: \n{y * 2}')
print('Voltando O Array Y para seu valor normal: ')
Y = np.array([[2,1], [1,2]])
print(Y)
X = np.array([[1,0], [0,1]])
print(f'O Valor do Array X é: \n{x}')
Z = x * y
print(f'Multiplicando o ARRAY X POR Y TEMOS: \n{z}')
separador()
print('Criando uma Matriz')
A = np.array([[0,1,1], [1,0,1]])
print(f'Matriz A = \n {A}')
B = np.array([[1,1], [1,1], [-1,1]])
print(f'Matriz B= \n {B}')
Z = np.dot(A,B)
print(f'A Multiplicação DOT das Matrizes A e B Resultam em: \n {Z}')
print('A DOT funciona assim: ')
k, l = np.arange(3), np.arange(3, 6)
print(k)
print(l)
print(np.dot(k,l))
print('retorna 14')
print('Retorna 14 pq multiplicando as duas matrizes vc vai ter 14 -> a conta: ')
print('3x0 + 1x4 + 2x5 = 14')
separador()
print(f'Seno de Z {np.sin(z) }')
print('Criando a Matriz C: ')
C = np.array([[1,1], [2,2], [3,3]])
print(f' A Matriz C = \n {C}')
#print(f'Matriz transposta de C : {C.transpose()}')
separador()
q = np.array([[1,0],[0,1]])
print(q)
separador()
w = np.array([[0,1],[1,0]])
print(w)
separador()
print(q + w)
separador()
o = np.array([[1,0],[0,1]])
print(o)
separador()
p = np.array([[2,2],[2,2]])
print(p)
separador()
print(np.dot(o, p)) |
98f95eb588c72a99ec6605fd2bdea716d8c2fc73 | Rohan2596/Mytest | /FunctionalPrograms/eucldist.py | 583 | 4.09375 | 4 | import math
import random
# a= int(input("enter the a "))
# b= int(input("enter the b "))
# z=a*a + b*b
# print(z)
# sq=math.sqrt(z)
# print("Distance is ",sq)
# output:
###################
# enter the a 89
# enter the b 8
# 7985
# enter the a 4
# enter the b -4
# 32
# Distance is 5.656854249492381
x=random.randint(-100,100)
print(x)
y=random.randint(-100,100)
print(y)
z1=x*x + y*y
print(z1)
s1 =math.sqrt(z1)
print("Distance is sq ",s1)
# ############
# output:
# -100
# 69
# 14761
# Distance is sq 121.49485585818027
# y
# 8
# 34
# 1220
# Distance is sq 34.92849839314596
|
3b3465e8390d8a611ead939e0fb02ad9650496cc | ryanatgz/data_structure_and_algorithm | /jianzhi_offer/09_旋转数组的最小数字.py | 1,312 | 3.75 | 4 | # encoding: utf-8
"""
@project:Data_Structure&&Algorithm
@author: Jiang Hui
@language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux
@time: 4/2/19 9:34 PM
@desc: 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
"""
class Solution:
def minNumberInRotateArray(self, rotateArray):
if not rotateArray:
return -1
n = len(rotateArray) - 1
# 去重
while rotateArray[n] == rotateArray[0]:
n -= 1
# 如果剩下数组为递增序列,直接返回首元素
if rotateArray[n] >= rotateArray[0]:
return rotateArray[0]
# 否则使用二分查找法
l = 0
r = n
while l < r:
mid = (l + r) // 2
if rotateArray[mid] < rotateArray[0]:
r = mid
else:
l = mid + 1
return rotateArray[l]
if __name__ == '__main__':
sol = Solution()
print(sol.minNumberInRotateArray([4, 5, 6, 7, 8, 0, 1, 2]))
|
9e0fa3e63448b8ea0938d82b24498b93513ce4a2 | KanagatS/PP2 | /TSIS5/Part 1/10.py | 119 | 3.546875 | 4 | #count of each word in file
from collections import Counter
f = open('test.txt', 'r')
print(Counter(f.read().split())) |
00bbe2b68ea1165995e35b099ffdd1623899b2be | ZekeMiller/euler-solutions | /solutions/026_decimal_repititions/fraction_repititions.py | 652 | 3.546875 | 4 |
def genPrimes( max ):
primes = [2]
for i in range( 3, max, 2 ):
for k in primes:
if i % k == 0:
break
primes += [ i ]
return primes
def multOrder( g, n ):
i = 1
while g ** i % n != 1:
i += 1
return i
def calcPeriod( val ):
if val % 2 == 0 or val % 5 == 0: # rel prime to 10
return 0
return multOrder( 10, val )
def periodMax( bound ):
n = 0
val = 0
for i in genPrimes( bound ):
p = calcPeriod( i )
if p > n:
val = i
n = p
return val
def main():
print( periodMax( 1000 ) )
main()
|
922a500936f04c63242f8e083d4202de5fe7ccf2 | Jayesh598007/Python_tutorial | /Chap3_strings/10_prac5.py | 204 | 3.5 | 4 | # practise for escape sequence
letter = "Dear Jayesh, this python course is nice!, Thanks!"
print(letter)
formatted_letter = "Dear Jayesh,\nThis python course is nice!,\nThanks!"
print(formatted_letter) |
f6d4ae478877058cf938677b2596e29b8ac626a7 | NataFediy/MyPythonProject | /hackerrank/math_find_angle.py | 662 | 4.40625 | 4 | #! Find the value of angle in degrees
# Input Format:
# The first line contains the length of side AB.
# The second line contains the length of side BC.
#
# Output Format:
# Output the value of angle in degrees.
#
# Note: Round the angle to the nearest integer.
#
# Examples:
# If angle is 56.5000001°, then output 57°.
# If angle is 56.5000000°, then output 57°.
# If angle is 56.4999999°, then output 56°.
#
# Sample Input:
# 10
# 10
# Sample Output:
# 45°
import math
AB, BC = int(input()),int(input())
hypotenuse = math.hypot(AB, BC)
angle = round(math.degrees(math.acos(BC/hypotenuse)))
degree_symbol = chr(176)
print(angle, degree_symbol, sep='') |
977b2b396f19bd0b61ca5b13d334c7796d66c73c | Yogesh6790/PythonBasic | /com/test/final/testclassfile.py | 523 | 3.546875 | 4 | class TestClass:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
@property
def x(self):
return self._x
@x.setter
def x(self, val):
self._x = val
@property
def y(self):
return self._y
@y.setter
def y(self, val):
self._y = val
@property
def z(self):
return self._z
@z.setter
def z(self, val):
self._z = val
def print_vals(self):
print(self._x,self._y, self._z)
|
4f3f8f7bd519d2ff47babcc67f414415cf6568b7 | gurram444/narendr | /hareesh.py | 844 | 4 | 4 | n=int(input("enter number:")) #find powers of number
i=int(input("power of number:"))
j=n**i
print(j)
sentense='narendrabsccomputers' #find all vowels and their count in sentense
vowel=['a','e','i','o','u']
for i in vowel:
if i in sentense:
print(i,sentense.count(i))
list=[2,3,4,1,4,6,9,12,23,56,76,97] #remove every third element from list and display number
for i in range(len(list)-1):
if i in[2,4,6,8]:
print(list[i],list.remove(list[i]))
print(list)
def count_currency(amount): #find currency count
notes=[2000,500,200,100,50,20,10,5,1]
count=[0,0,0,0,0,0,0,0,0]
print('count currency---->')
for i,j in zip(notes,count):
if amount>=i:
j=amount//i
amount=amount-j*i
print(i,':',j)
amount=868
count_currency(amount) |
21c6f0e5ee45ea0f36a5db0623d3b59e352c3950 | vvweilong/OpenCVproj | /getSetPixel.py | 865 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
import cv2
import numpy as np
# 读取图像
oImg = cv2.imread("pic.jpg")
# 方法一:
# # 为了看效果 采用 for 修改了一条线
# for i in range(100, 200,1):
# # 获取某个像素点
# for j in range(100,200,1):
# # 这里进行的是值拷贝 修改 px 对象 对 oimg 没有影响……
# px = oImg[i, j]
# # 修改该像素的 rgb 值 [B,G,R]
# oImg[i,j] = [255,0 , 0]
# 方法二:
# 使用 item
# 0 - B 1-G 2-R
print oImg.item(10, 10, 0)
# 使用循环 修改一个矩形
for i in range(100, 200, 1):
# 获取某个像素点
for j in range(100, 200, 1):
# 修改该像素的 rgb 值 [B,G,R]
oImg.itemset(( i, j, 0), 255)
oImg.itemset(( i, j, 1), 255)
oImg.itemset(( i, j, 2), 0)
cv2.imwrite("pixel.jpg", oImg)
|
3cdb6a30c5859af87dfdc63887c3b64765e59965 | ChristinaEricka/LaunchCode | /unit1/Chapter 08 - More About Iteration/Chaapter 08 - Exercise 01.py | 602 | 4.21875 | 4 | # Write a function print_triangular_numbers(n) that prints out the first n
# triangular numbers. A call to print_triangular_numbers(5) would produce
# the following output:
#
# 1
# 3
# 6
# 10
# 15
def print_triangular_numbers(n):
"""Print out the first <n> triangular numbers"""
sum = 0
for i in range(1, n + 1):
sum += i
print(sum)
def main():
"""Perform a cursory test to validate print_triangular_numbers(n)"""
print("The first 5 trianglular numbers are:")
print_triangular_numbers(5)
if __name__ == '__main__':
main()
|
5927eb63d34ae2aa4199fc71324c4f6d44030472 | rajrahul1997/Code-Practice | /pattern/pattern3.py | 543 | 3.6875 | 4 | '''Program to print pattern below
0
101
21012
3210123
432101234
if (N=4) is given by user
here three loop of j is running 1st one is printing space
2nd loop is ruuning from j(i,0,-1) and printing value of left side to zero
3rd loop is ruuning from j(0,i+1) an dprinting value of right side to zero'''
N= int(input("input:"))
for i in range(0,N+1):
for j in range(0,N-i-1):
print(end ="")
for j in range(i,0,-1):
print(j,end = "")
for j in range(0,i+1):
print(j,end = "")
print()
|
9615920dca520c085b93739cc2a1fe54d305ad19 | varun1414/Xformations | /Scrappers/to_csv.py | 467 | 3.625 | 4 | import csv
def convert(data,name):
csv_columns = ['comp','date','result','teams','score','formation']
dict_data = data
csv_file = name
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data:
writer.writerow(data)
except IOError:
print("I/O error")
|
126f60d2d6f41a89012223cc1ff1875fa1bdef63 | dyrroth-11/Information-Technology-Workshop-I | /Python Programming Assignments/Assignemt2/3.py | 1,024 | 3.84375 | 4 | #!/usr/bin/env python3
"""
Created on Thu Apr 2 07:38:27 2020
@author: Ashish Patel
"""
"""
Write a Python program to replace dictionary values with their sum.
Example: Input: {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI': 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
Output: [{'subject': 'math', 'id': 1, 'V+VI': 76.0},
{'subject': 'math', 'id': 2, 'V+VI': 73.5}
{'subject': 'math', 'id': 3, 'V+VI': 80.5}]
LOGIC: We iterate through the list of dictionaries and store the value of
elements with key 'V' and 'VI' and then add an element with key 'V + VI'
and value as sum of previous stored values.
"""
list= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
]
for i in list:
x = i.pop('V')
y = i.pop('VI')
i['V+VI'] = (x+y)/2
print(list)
|
35377ec521580c40343d95eaad24a78e801b3bd0 | alegde/data_structures_and_algorithms | /cs_algorithms/stack.py | 503 | 3.703125 | 4 |
class Stack:
def __init__(self):
self.my_stack = []
def _is_empty(self):
if len(self.my_stack) == 0:
return True
else:
return False
def push(self, value):
self.my_stack.append(value)
def pop(self):
if self._is_empty():
return "Underflow"
else:
a = self.my_stack[-1]
del(self.my_stack[-1])
return a
def __repr__(self):
return self.my_stack.__str__()
|
c524dfb4f742a99dad781be013df79d3e58694c7 | stephalexandra/u3l5 | /u3l5/problem6.py | 168 | 3.546875 | 4 | firstname = "Albus"
lastname = "Dumbledore"
fullname = firstname + " " + lastname
print(firstname + " " + firstname)
print(lastname + " " + lastname)
print(fullname) |
8f0c78bdb2b1dc230dec9be38e5f45199b5293b9 | csJd/oj-codes | /leetcode/179.largest-number.py | 1,268 | 3.734375 | 4 | #
# @lc app=leetcode id=179 lang=python3
#
# [179] Largest Number
#
# https://leetcode.com/problems/largest-number/description/
#
# algorithms
# Medium (26.29%)
# Likes: 1138
# Dislikes: 147
# Total Accepted: 138.4K
# Total Submissions: 525.7K
# Testcase Example: '[10,2]'
#
# Given a list of non negative integers, arrange them such that they form the
# largest number.
#
# Example 1:
#
#
# Input: [10,2]
# Output: "210"
#
# Example 2:
#
#
# Input: [3,30,34,5,9]
# Output: "9534330"
#
#
# Note: The result may be very large, so you need to return a string instead of
# an integer.
#
#
from functools import cmp_to_key
from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def mycmp(a, b):
if a + b > b + a:
return -1
elif a + b < b + a:
return 1
return 0
nums = [str(num) for num in nums]
nums.sort(key=cmp_to_key(mycmp))
if nums and nums[0] == nums[-1] == '0':
return "0"
return "".join(nums)
def main():
solu = Solution()
print(solu.largestNumber([10, 2]))
print(solu.largestNumber([0, 0]))
print(solu.largestNumber([3, 30, 34, 5, 9]))
if __name__ == "__main__":
main()
|
8ef9db967e753b1641ab78da6a010bb4e7b16960 | nathanielb91/SeleniumPractice | /SearchAmazonForBattletoads.py | 856 | 3.6875 | 4 | """ This code loads Chrome, searches amazon.com for a video game,
and prints out the product names along with their price """
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.get('https://www.amazon.com')
# get the search textbox
search_field = driver.find_element_by_id('twotabsearchtextbox')
search_field.clear()
# enter search keyword and submit
search_field.send_keys('battletoads')
search_field.submit()
# assign elements to variables
prices = driver.find_elements_by_xpath("//div/div/div/div[2]/div[2]/div[1]/div[2]/div/a/span[2]")
names = driver.find_elements_by_xpath("//div/div/div/div[2]/div[1]/div[1]/a/h2")
# iterate through each element and print the product name and it's price
for i in range(len(prices)):
print names[i].text + " : " + prices[i].text
# exit Chrome
driver.close()
|
f186a4634f4f7c10416619491a4252cddd3f3fae | krocki/ADS | /leetcode/007_reverse_int.py | 585 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Author: Kamil Rocki
# @Date: 2017-01-31 15:39:44
# @Last Modified by: Kamil Rocki
# @Last Modified time: 2017-01-31 15:39:46
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
res = 0
if x < 0:
s = -1
x = -x
else: s = 1
while (x != 0):
print x, res, x % 10
res = res * 10
res += x % 10
x = x/10
if (res > 1 << 31): return 0
return res * s
|
12bcadc8452d3f237b5bd1200f0b0f9734fe06db | hzhnb/python2 | /037-算数运算1.py | 182 | 3.734375 | 4 | print(type(len))
a = int(123)
b = int(456)
print(a+b)
#
class New_int(int):
def __add__(self, other):
return int(self)+int(other)
n = New_int(2)
m = New_int(3)
print(m+n) |
ffa6eba669d02fee03c0ca5f22578141c30ab698 | Nathalia1234/Python | /Python_7_PontoFlutuante/ponto_flutuante.py | 518 | 4.1875 | 4 | num = 10
dec = 10.5
texto = "ola"
print()
print("Concatenação de inteiros")
print("O valor é:", num)
print("O valor é: %i" %num)
print("O valor é: " + str(num))
print()
print("Concatenação de números float")
print("Concatenação de decimal: ", dec)
print("Concatenação de decimal: %.2f" %dec)
print("Concatenação de decimal:" + str(dec))
print()
print("Concatenando String")
print("Concatenação de String: ", texto)
print("Concatenação de String: %s" %texto)
print("Concatenação de String: "+ texto) |
c60d9965fa077ea029a11f992eef6d238132ab8e | Shikhar99-lab/Python-CDLine-Database-Apps | /ProjYou.py | 2,961 | 3.78125 | 4 | import sqlite3 as lite
# functionality goes here
class DatabaseManage(object):
def __init__(self):
global con
try:
con = lite.connect('videos.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS video(Id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT,tags TEXT)")
except Exception:
print("Unable to create a DB !")
# TODO: create data
def insert_data(self, data):
try:
with con:
cur = con.cursor()
cur.execute(
"INSERT INTO video(name, description, tags) VALUES (?,?,?)", data
)
return True
except Exception:
return False
# TODO: read data
def fetch_data(self):
try:
with con:
cur = con.cursor()
cur.execute("SELECT * FROM video")
return cur.fetchall()
except Exception:
return False
# TODO: delete data
def delete_data(self, id):
try:
with con:
cur = con.cursor()
sql = "DELETE FROM video WHERE id = ?"
cur.execute(sql, [id])
return True
except Exception:
return False
# TODO: provide interface to user
def main():
print("*"*40)
print("\n:: YOUTUBE VIDEO IDEAS :: \n")
print("*"*40)
print("\n")
db = DatabaseManage()
print("#"*40)
print("\n :: User Manual :: \n")
print("#"*40)
print('\nPress 1. Insert a new Youtube video idea\n')
print('Press 2. Show all video ideas\n')
print('Press 3. Delete a video idea (NEED ID OF VIDEO)\n')
print("#"*40)
print("\n")
choice = input("\n Enter a choice: ")
if choice == "1":
name = input("\n Enter video name: ")
description = input("\n Enter video description: ")
tags = input("\n Enter tags for video: ")
if db.insert_data([name, description, tags]):
print("Video Idea was inserted successfully")
else:
print("OOPS SOMETHING WENT WRONG")
elif choice == "2":
print("\n:: Youtube Video Ideas List ::")
for index, item in enumerate(db.fetch_data()):
print("\n Sl no : " + str(index + 1))
print("Video ID : " + str(item[0]))
print("Video Name : " + str(item[1]))
print("Video Description : " + str(item[2]))
print("Tags for video : " + str(item[3].split(',')))
print("\n")
elif choice == "3":
record_id = input("Enter the video ID: ")
if db.delete_data(record_id):
print("Course was deleted with a success")
else:
print("OOPS SOMETHING WENT WRONG")
else:
print("\n BAD CHOICE")
if __name__ == '__main__':
main() |
aa96840769442733fb84b5b06d602b981fa0f948 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/Lab2/4.py | 380 | 4.15625 | 4 | # Lab Project by Sarang Dev Saha
# LAB_02 QUE_04
# Take a list of 10 nos. and remove 3rd to 6th elements and change the value of last element with a number taken from the user.
list=[0, 1,2,3,4,5,6,7,8,9]
#Deleting 3,4,5 and 6 from the list
del list[3:7]
#printing the omitted list
print(list)
# Entering input at the last position
list[5]=float(input("Enter new number:"))
print(list) |
670597fd7ac549513473899a7a56f4c03ca86d0b | juliagolder/project-2 | /Yahtzee.py | 4,404 | 3.515625 | 4 | #juliagolder
#5/23/18
#Yahtzee.py
from random import randint
def printRoll(dice): #prints out list of dice
print(dice)
def printCard(scoreL): #prints out scorecard
print('1: Aces -', scoreL[0])
print('2: Twos -', scoreL[1])
print('3: Threes -', scoreL[2])
print('4: Fours -', scoreL[3])
print('5: Fives -', scoreL[4])
print('6: Sixes -', scoreL[5])
print('7: Three of a Kind -', scoreL[6])
print('8: Four of a Kind', scoreL[7])
print('9: Full House -', scoreL[8])
print('10: Small Straight -', scoreL[9])
print('11: Large Straight -', scoreL[10])
print('12: YAHTZEE! -', scoreL[11])
def enterScore(num, dice, scoreL): #tallies up score of the roll
score = 0
if num == 1:
score = L.count(1)
if num == 2:
score = L.count(2)*2
if num == 3:
score = L.count(3)*3
if num == 4:
score = L.count(4)*4
if num == 5:
score = L.count(5)*5
if num == 6:
score = L.count(6)*6
if num == 7:
if is3ofakind(L):
score = sum(L)
else:
score = 0
if num == 8:
if is4ofakind(L):
score = sum(L)
else:
score = 0
if num == 9:
if isfullhouse(L):
score = 25
else:
score = 0
if num == 10:
if isSmallStraight(L):
score = 30
else:
score = 0
if num == 11:
if isLargeStraight(L):
score = 40
else:
score = 0
if num == 12:
if isYahtzee(L):
score = 50
else:
score = 0
scoreL[num-1] = score
def is3ofakind(L): #function for determining rolls with three of a kind
for i in range(1,7):
if L.count(i) >= 3:
return True
return False
def is4ofakind(L): #function for determining rolls with four of a kind
for i in range(1,7):
if L.count(i) >= 4:
return True
return False
def isfullhouse(L): #function for determining rolls with a full house
L.sort()
if L[0] == L[1] and L[0] == L[2] and L[3] == L[4]:
return True
if L[0] == L[1] and L[2] == L[3] and L[2] == L[4]:
return True
else:
return False
def isSmallStraight(L): #function for determining rolls with a small straight
for i in L:
if (1 in L and 2 in L and 3 in L and 4 in L) or (2 in L and 3 in L and 4 in L and 5 in L or 3 in L and 4 in L and 5 in L and 6 in L):
return True
return False
def isLargeStraight(L): #function for determining rolls with a large straight
for i in L:
if (1 in L and 2 in L and 3 in L and 4 in L and 5 in L) or (2 in L and 3 in L and 4 in L and 5 in L and 6 in L):
return True
return False
def isYahtzee(L): #function for determining rolls with a Yahtzee
for i in range(1,7):
if L.count(i) == 5:
return True
return False
def rollDice(L,pick): #function that allows the user to pick which die they want to reroll
for i in range(5):
if i in pick:
L[i] = (randint(1,6))
if __name__ == '__main__': #sets up and runs the game
L = [0,0,0,0,0] # a blank list with placeholders for dice
scoreL = [' ']*12 #list for score card
for i in range(12):
#allows the user to roll and reroll specific dice
rollDice(L,[0,1,2,3,4]) #gives numbers to each die
printRoll(L)
again = input('Do you want to roll again?')
if again == 'y' or again == 'yes':
which = input('Which dice do you want to roll?').split(' ')
toRoll = []
for die in which:
toRoll.append(int(die)-1)
rollDice(L,toRoll)
printRoll(L)
again = input('Do you want to roll again?')
if again == 'y' or again == 'yes':
which = input('Which dice do you want to roll?').split(' ')
toRoll = []
for die in which:
toRoll.append(int(die)-1)
rollDice(L,toRoll)
printRoll(L)
#allows user to pick catagory and display score card
printCard(scoreL)
chose = int(input('What number do you want to choose?'))
enterScore(chose,L,scoreL)
printCard(scoreL)
print('Your final score is', sum(scoreL), '!') |
64ecb937173646821e241e4d79d7ca3c585552a1 | anya92/learning-python | /2.Lists/nested_lists.py | 613 | 4.1875 | 4 | nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# accessing items
print(nested_list[0]) # [1, 2, 3]
print(nested_list[-1]) # [7, 8, 9]
print(nested_list[1][1]) # 5
# looping through a nested list
for i in nested_list:
for j in i:
print(j)
# nested list comprehensions
print([[num for num in range(1, 4)]
for val in range(3)]) # [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print([['X' if x % 2 == 0 else 'O' for x in range(3)] for val in range(3)])
# [['X', 'O', 'X'], ['X', 'O', 'X'], ['X', 'O', 'X']]
print([[a, b, c] for a in range(1, 4)
for b in range(1, 4) for c in range(1, 4)])
|
32ff106056221e63c1d89f2d88f6af10658fa2a4 | r25ta/USP_python_1 | /semana4/fatorial.py | 181 | 3.96875 | 4 | def main():
print("Fatorial")
n = int(input("Digite o valor de n:"))
fat=1
while (n > 0):
fat = fat * n
n = n - 1
print(fat)
main() |
3aceca8ec2a3d395ef3f166a44d08a004ec2f7f9 | justinnnlo/leetcode-python | /290 Word Pattern.py | 1,322 | 4.1875 | 4 | '''
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
Runtime: 44 ms
'''
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_list = str.split(" ");
if(len(pattern) != len(str_list)):
return False;
patdic , strdic = {},{};
for pat,st in zip(pattern,str_list) :
if(pat not in patdic):
patdic[pat] = st;
if(st not in strdic):
strdic[st] = pat;
if(patdic[pat]!=st or strdic[st]!=pat):
return False;
return True;
if __name__=="__main__":
pattern, str = "abba","dog cat cat dog"
print Solution().wordPattern(pattern, str)
|
c22c629fbfc70ae7db320660770c26a50be36fb7 | lixiaoya0313/pythonbox | /execise_004.py | 902 | 4.03125 | 4 | #import turtle
#t = turtle.Turtle()
#t.speed(0)
#t.color("pink")
#for x in range(100):
# t.circle(x)
# t.left(93)
#input("Press <enter>")
# coding: utf-8
print('我是能减乘除的计算器~')
while True:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
num=input('请输入运算符号:')
a=int(input('请输入第一个数:'))
b=int(input('请输入第二个数:'))
if num =='+':
print(a,'+',b,'=',add(a,b))
if num =='-':
print(a,'-',b,'=',subtract(a,b))
if num =='*':
print(a,'*',b,'=',multiply(a,b))
if num =='/':
print(a,'/',b,'=',divide(a,b))
no =input('您还要做其他运算吗?')
i = input("您还要做其他运算吗? ")
if i =='no':
break
|
1dc15c12d2ad74c01ad8827f162f24620383efdf | ebunsoft/pythontask | /loop.py | 84 | 3.78125 | 4 | #Loopingin Python
sum = 0
for i in range (1, 11, 3):
sum = sum + i
print(sum)
|
f4ccc900d319f6ea65acd48dd4d8a50bc8f5b265 | Tomgauld/python-year11 | /YorN.py | 202 | 3.859375 | 4 | def answer (Y,N):
input("Y or N?")
if answer == ("Y"):
print("Valid entry")
if answer == ("N"):
print("Valid entry")
else if
print("Invalid entry")
|
2629e5db23acc2a7c1ad73a340bb320740c9765e | datAnir/GeekForGeeks-Problems | /Greedy/activity_selection.py | 1,176 | 3.96875 | 4 | '''
https://practice.geeksforgeeks.org/problems/n-meetings-in-one-room/0
There is one meeting room in a firm. There are N meetings in the form of (S[i], F[i]) where S[i] is start time of meeting i and F[i] is finish time of meeting i.
What is the maximum number of meetings that can be accommodated in the meeting room?
Input:
2
6
1 3 0 5 8 5
2 4 6 7 9 9
8
75250 50074 43659 8931 11273 27545 50879 77924
112960 114515 81825 93424 54316 35533 73383 160252
Output:
1 2 4 5
6 7 1
'''
# since we need to find max rooms, means meeting should end early
# sort by finish time, check finish <= start, then count++ and update finish
def find_max_meeting(start, finish, n):
pair = []
for i in range(n):
pair.append([start[i], finish[i], i+1])
pair.sort(key = lambda x: x[1])
fin = pair[0][1]
ind = pair[0][2]
for s, e, i in pair:
if s >= fin:
print(ind, end = ' ')
fin = e
ind = i
print(ind)
t = int(input())
while t:
n = int(input())
start = list(map(int, input().split()))
finish = list(map(int, input().split()))
find_max_meeting(start, finish, n)
t -= 1 |
14e466e7c55721e1d47f54fe7aa58af61c014e9a | DwyaneTalk/ProgrammingLanguage | /PythonCookbook/Chapter1/Chapter1_3.py | 708 | 3.546875 | 4 | # FileName : Chapter1_3.py
'''
保留最后优先个历史记录
关键点:
collections.deque
with *A as *B:将*A赋值给*B,并在前后会执行*B对象的__enter__()和__exit()__
yield: 指定函数为生成器函数,作用是将序列的结果依次返回节省空间
'''
from collections import deque
def search(lines, pattern, history = 5):
previous_lines = deque(maxlen = history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
if __name__ == '__main__':
with open(r'..\work\text.txt') as f:
for line, prelines in search(f, 'Python', 5):
for plines in prelines:
print(plines, end='')
print(line, end='')
print('-' * 20) |
5816597123107c61466f3ed205e612815e55e909 | preetsimer/assignment-6 | /assignment-6.py | 673 | 3.859375 | 4 | #question 1
def area(r):
a=4*r*r*3.14
print("The area of sphere is ",a)
n=int(input("Enter radius of sphere: "))
area(n)
#question 2
s=0
for num in range(1,1001):
for i in range(1,num):
if num%i==0:
s=s+i
if s==num:
print(num)
s=0
#question 3
n=int(input("Enter a number: "))
print("The multiplication table of %d is:"%n)
for i in range(1,11):
m=i*n
print("%d * %d = %d"%(n,i,m))
#question 4
def power(a,b):
if(b==1):
return(a)
if(b!=1):
return(a*power(a,b-1))
a=int(input("Enter number: "))
b=int(input("Enter exponential value: "))
p=power(a,b)
print("%d^%d=%d"%(a,b,p))
|
5d29193af663c95bc73bc1c23159e68e18dae2b4 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Basic - Part-II/program-50.py | 1,680 | 4.28125 | 4 | #!/usr/bin/env python3
##################################################################################
# #
# Program purpose: Finds a replace the string "Python" with "Java" and the #
# string "Java" with "Python". #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : September 22, 2019 #
# #
##################################################################################
def read_string(mess: str):
valid = False
user_str = ""
while not valid:
try:
user_str = input(mess).strip()
valid = True
except ValueError as ve:
print(f"[ERROR]: {ve}")
return user_str
def swap_substr(main_str: str, sub_a: str, sub_b: str):
if main_str.index(sub_a) >= 0 and main_str.index(sub_b) >= 0:
i = 0
while i < len(main_str):
temp_str = main_str[i:i + len(sub_a)]
if temp_str == sub_a:
main_str = main_str[0:i] + sub_b + main_str[i+len(sub_a):]
else:
temp_str = main_str[i:i + len(sub_b)]
if temp_str == sub_b:
main_str = main_str[0:i] + sub_a + main_str[i+len(sub_b):]
i += 1
return main_str
if __name__ == "__main__":
data = read_string(mess="Enter some string with 'Python' and 'Java': ")
print(f"Processed string is: {swap_substr(main_str=data, sub_a='Python', sub_b='Java')}")
|
97073c12cf795d02974022556cb0109c97239542 | clacroi/MTH6412B | /queue.py | 1,379 | 3.96875 | 4 | class Queue(object):
"""Une implementation de la structure de donnees << file >>."""
def __init__(self):
self._items = []
@property
def items(self):
return self._items
def enqueue(self, item):
"Ajoute `item` a la fin de la file."
self.items.append(item)
def dequeue(self):
"Retire l'objet du debut de la file."
return self.items.pop(0)
def is_empty(self):
"Verifie si la file est vide."
return (len(self.items) == 0)
def __contains__(self, item):
return (item in self.items)
def __repr__(self):
return repr(self.items)
class PriorityQueue(Queue):
def dequeue(self):
"Retire l'objet ayant la plus haute priorite."
highest = self.items[0]
for item in self.items[1:]:
if item > highest:
highest = item
idx = self.items.index(highest)
return self.items.pop(idx)
# Les items de priorite nous permettent d'utiliser min() et max().
class PriorityMinQueue(Queue):
def dequeue(self):
"Retire l'objet ayant la plus petite priorite."
return self.items.pop(self.items.index(min(self.items)))
class PriorityMaxQueue(Queue):
def dequeue(self):
"Retire l'objet ayant la plus haute priorite."
return self.items.pop(self.items.index(max(self.items)))
|
25f6c8157a790a0e74b75e7dff2acb722223c7b6 | Nanutu/python-poczatek | /module_4/zad_130/homework_1/main.py | 623 | 4.28125 | 4 | # Stwórz odpowiednik klasy Apple jako named tuple.
#
# Stwórz instancję takiej krotki, a następnie wypisz zawarte w niej dane na trzy sposoby:
#
# a) korzystając z nazw
# b) odwołując się do kolejnych indeksów
# c) za pomocą pętli
from collections import namedtuple
Apple = namedtuple("Apple", ["species_name", "size", "price"])
def run_homework():
apple = Apple(species_name="Ligol", size=4, price=5)
print(apple.species_name, apple.size, apple.price)
print(apple[0], apple[1], apple[2])
for param in apple:
print(param)
if __name__ == '__main__':
run_homework()
|
54d9d1e8db127cf8e082e1f8decb34e16146ff5c | jeon-jeong-yong/pre-education | /quiz/pre_python_11.py | 254 | 3.71875 | 4 | """11. 최대공약수를 구하는 함수를 구현하시오
예시
<입력>
print(gcd(12,6))
<출력>
6
"""
def gcd(a, b):
i = min(a, b)
while True:
if a % i == 0 and b % i == 0:
return i
i -= 1
print(gcd(12, 6)) |
3b9d8fa76bdfb51811a9c3d1da11d70c914f85cb | Takemelady/CP3-Pattarasri-Piti | /Excercise21_Pattarasri_P.py | 1,248 | 3.53125 | 4 | from tkinter import *
import math
def leftClickButton(event):
bmiResult = float(textBoxWeight.get())/math.pow(float(textBoxHeight.get())/100,2)
if bmiResult <= 18.5:
a = "ผอมเกิน"
elif bmiResult <= 22.9:
a = "ปกติ"
elif bmiResult <= 24.9:
a = "น้ำหนักเกิน"
elif bmiResult <= 29.9:
a = "อ้วน"
elif bmiResult >= 30:
a = "อ้วนเกินไป"
labelResult.configure(text="ค่า BMI ของคุณคือ :" + str(bmiResult) + " ผลการประเมินคือ : "+ a)
MainWindow = Tk()
labelHeight = Label(MainWindow, text="ส่วนสูง (cm.)")
labelHeight.grid(row=0,column=0)
textBoxHeight = Entry(MainWindow)
textBoxHeight.grid(row=0,column=1)
labelWeigth = Label(MainWindow, text="น้ำหนัก (Kg.)")
labelWeigth.grid(row=1,column=0)
textBoxWeight = Entry(MainWindow)
textBoxWeight.grid(row=1,column=1)
calculateButton = Button(MainWindow,text = "คำนวน")
calculateButton.bind('<Button-1>', leftClickButton)
calculateButton.grid(row=2,column=0)
labelResult = Label(MainWindow,text="ผลลัพธ์")
labelResult.grid(row=2,column=1)
MainWindow.mainloop() |
b98261817f3d2962cf0fba64a03b40f0879823e5 | mateusisrael/Estudo-Python | /Assuntos Diversos/Testando Funções/5 - Retorno de Valores.py | 315 | 3.921875 | 4 | # Retorno de Valores
# Toda função é capaz de retornar valor.
'''def soma():
return 10
print(soma())'''
'''def soma(x, y):
return x*y
print(soma(10, 20))'''
def soma(x, y):
num = x * y
return num # return faz com que a função pare após o valor ser retornado
print(soma(10, 20)) |
b429a209b02a82aa7e58e5e4bfc8e53cf3a3f759 | hnz71211/Python-Basis | /com.lxh/exercises/37_difference_set/__init__.py | 279 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 返回集合 {‘A’,‘D’,‘B’} 中未出现在集合 {‘D’,‘E’,‘C’} 中的元素(差集)
set1 = {'A', 'D', 'B'}
set2 = {'D', 'E', 'C'}
set3 = set1.difference(set2)
set4 = set1 - set2
print(set3)
print(set4) |
113a4543d90c66dac33bb1a1b8dcc2a576501568 | yongtao-wang/leetcodes | /algorithms/lists.py | 96,692 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Lists(object):
def twoSum(self, nums, target):
"""
# 1
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
:param nums:
:param target:
:return:
"""
'''
此类题目用#15那样的左右逼近是最好解法,但必须是sorted list
又由于此处求的是下标,所以若遇到重复数字比如nums=[3, 3], target=6就很混乱
'''
rev = {}
for index, n in enumerate(nums, 0):
minus = target - n
if n not in rev:
rev[minus] = index
else:
return [rev[n], index]
def findMedianSortedArrays(self, nums1, nums2):
"""
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
l = len(nums1) + len(nums2)
if l % 2 == 1:
return self._find_kth(nums1, nums2, l / 2)
else:
return (self._find_kth(nums1, nums2, l / 2 - 1) + self._find_kth(nums1, nums2, l / 2)) / 2.0
def _find_kth(self, a, b, k):
"""
:type a: List[int]
:type b: List[int]
:type k: int
"""
if len(a) > len(b):
a, b = b, a
if not a:
return b[k]
if k == len(a) + len(b) - 1:
return max(a[-1], b[-1])
i = min(len(a) - 1, k / 2)
j = min(len(b) - 1, k - i)
if a[i] > b[j]:
return self._find_kth(a[:i], b[j:], i)
else:
return self._find_kth(a[i:], b[:j], j)
def threeSum(self, nums):
"""
# 15 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
:type nums: List[int]
:rtype: List[List[int]]
"""
'''使用左右逼近能达到logN。总效率N * logN'''
'''优化后的速度能达到98.04%,未优化时为68.44%'''
res = []
nums.sort() # 如果不想改变list顺序,可以使用sorted(nums)
for i in xrange(len(nums) - 2):
# some optimization
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
l = i + 1
r = len(nums) - 1
# some optimization, too
if nums[l] > -nums[i] / 2.0:
continue
if nums[r] < -nums[i] / 2.0:
continue
while l < r:
s = nums[i] + nums[l] + nums[r]
if s > 0:
l += 1
elif s < 0:
r -= 1
else:
res.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
return res
def threeSumClosest(self, nums, target):
"""
# 16 3-Sum Closest
Given an array S of n integers, find three integers in S
such that the sum is closest to a given number, target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
:type nums: List[int]
:type target: int
:rtype: int
"""
'''此题只能做到N^2。比较大小时注意需要使用abs()'''
ss = sorted(nums)
closest_sum = ss[0] + ss[1] + ss[2]
for i in xrange(len(ss) - 2):
l = i + 1
r = len(ss) - 1
while l < r:
sum3 = ss[l] + ss[i] + ss[r]
if sum3 == target:
return sum3
elif abs(sum3 - target) < abs(closest_sum - target):
closest_sum = sum3
if sum3 < target:
l += 1
else:
r -= 1
return closest_sum
def letterCombinations(self, digits):
"""
# 17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
import itertools
pad = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
res = []
out = []
for d in digits:
if d not in pad:
return None
res.append(pad[d])
cartesian = list(itertools.product(*res))
for c in cartesian:
out.append(''.join(c))
return out
def fourSum(self, nums, target):
"""
# 18 4-Sum
Given an array S of n integers, are there elements a, b, c, and d in S
such that a + b + c + d = target? Find all unique quadruplets in the array
which gives the sum of target.
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
'''
这是一个较为优化的算法,将4-sum转变成两个2-sum。精益求精。
def fourSum(self, nums, target):
def findNsum(nums, target, N, result, results):
if len(nums) < N or N < 2 or target < nums[0]*N or target > nums[-1]*N: # early termination
return
if N == 2: # two pointers solve sorted 2-sum problem
l,r = 0,len(nums)-1
while l < r:
s = nums[l] + nums[r]
if s == target:
results.append(result + [nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
elif s < target:
l += 1
else:
r -= 1
else: # recursively reduce N
for i in range(len(nums)-N+1):
if i == 0 or (i > 0 and nums[i-1] != nums[i]):
findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)
results = []
findNsum(sorted(nums), target, 4, [], results)
return results
'''
nums.sort()
result = []
for i in xrange(len(nums) - 3):
if nums[i] > target / 4.0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
target2 = target - nums[i]
for j in xrange(i + 1, len(nums) - 2):
if nums[j] > target2 / 3.0:
break
if j > i + 1 and nums[j] == nums[j - 1]:
continue
l = j + 1
r = len(nums) - 1
target3 = target2 - nums[j]
if nums[l] > target3 / 2.0:
continue
if nums[r] < target3 / 2.0:
continue
while l < r:
sum_lr = nums[l] + nums[r]
if sum_lr == target3:
result.append([nums[i], nums[j], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif sum_lr < target3:
l += 1
else:
r -= 1
return result
def removeDuplicates(self, nums):
"""
# 26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place
such that each element appear only once and return the new length.
Do not allocate extra space for another array,
you must do this in place with constant memory.
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
p = 0
q = 0
while q < len(nums):
if nums[p] == nums[q]:
q += 1
continue
p += 1
# or simply nums[p] = nums[q]. speed up from 58% to 83%
nums[p], nums[q] = nums[q], nums[p]
q += 1
return p + 1
def removeElement(self, nums, val):
"""
27. Remove Element
Given an array and a value, remove all instances of that value in place
and return the new length.
Do not allocate extra space for another array,
you must do this in place with constant memory.
The order of elements can be changed.
It doesn't matter what you leave beyond the new length.
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums:
return 0
p = 0
q = len(nums) - 1
while p < q:
if nums[q] == val:
q -= 1
continue
if nums[p] == val:
nums[p], nums[q] = nums[q], nums[p]
q -= 1
p += 1
if nums[p] is not val:
p += 1
return p
def searchInsert(self, nums, target):
"""
35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
:type nums: List[int]
:type target: int
:rtype: int
"""
def search(list_num, start, end):
if not nums:
return start
mid = (start + end) / 2
if start == end:
return start + 1 if nums[start] < target else start
if start + 1 == end:
if target <= nums[start]:
return start
elif target > nums[end]:
return end + 1
else:
return end
if nums[mid] == target:
return mid
if nums[mid] < target:
return search(list_num[mid + 1:end + 1], mid, end)
if nums[mid] > target:
return search(list_num[start:mid], start, mid)
return search(nums, 0, len(nums) - 1)
def nextPermutation(self, nums):
"""
#31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically
next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest
possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(len(nums) - 1, -1, -1):
if i == 0: # meaning the list is at maximum permutation
nums[:] = nums[::-1]
return
if nums[i - 1] < nums[i]:
# search from rightmost to find the first one larger than nums[i-1]
for k in xrange(len(nums) - 1, i - 1, -1):
if nums[k] > nums[i - 1]:
nums[i - 1], nums[k] = nums[k], nums[i - 1]
break
# reverse from i
nums[i:] = nums[i:][::-1]
return
def longestValidParentheses(self, s):
"""
32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')',
find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()",
which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()",
which has length = 4.
:type s: str
:rtype: int
"""
stack = []
matched = [0] * len(s)
longest = 0
for i in xrange(len(s)):
if s[i] == '(':
stack.append(i)
elif stack:
j = stack.pop(-1)
matched[i], matched[j] = 1, 1
count = 0
for k in xrange(len(matched)):
if matched[k] == 1:
count += 1
else:
longest = max(longest, count)
count = 0
longest = max(longest, count)
return longest
def search(self, nums, target):
"""
33. Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated
at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search.
If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target <= nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] <= target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
def searchRange(self, nums, target):
"""
# 34. Search for a Range
Given an array of integers sorted in ascending order,
find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
'''
另一个concise solution. 分开算左边和右边。效率略高一些。
---------------------------------------
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left, right = self.search_left(nums, target), self.search_right(nums, target)
return [left, right] if left <= right else [-1, -1]
def search_left(self, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
def search_right(self, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid - 1
return right
'''
i = 0
j = len(nums) - 1
ans = [-1, -1]
if not nums:
return ans
while i < j:
mid = (i + j) / 2
if nums[mid] < target:
i = mid + 1
else:
j = mid
if nums[i] != target:
return ans
else:
ans[0] = i
j = len(nums) - 1
while i < j:
mid = (i + j) / 2 + 1
if nums[mid] > target:
j = mid - 1
else:
i = mid
ans[1] = j
return ans
def isValidSudoku(self, board):
"""
# 36. Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled,
where empty cells are filled with the character '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells need to be validated.
:type board: List[List[str]]
:rtype: bool
"""
row_dict = {}
col_dict = {}
cube_dict = {}
if len(board) != 9:
return False
for i in xrange(len(board)):
if len(board[i]) != 9:
return False
for i in xrange(len(board)):
if i not in row_dict:
row_dict[i] = set()
for j in xrange(len(board[0])):
if j not in col_dict:
col_dict[j] = set()
if (i / 3, j / 3) not in cube_dict:
cube_dict[(i / 3, j / 3)] = set()
if board[i][j] == '.':
continue
if board[i][j] in row_dict[i] or board[i][j] in col_dict[j] \
or board[i][j] in cube_dict[(i / 3, j / 3)]:
return False
row_dict[i].add(board[i][j])
col_dict[j].add(board[i][j])
cube_dict[(i / 3, j / 3)].add(board[i][j])
return True
def solveSudoku(self, board):
"""
37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
self._solve_sudoku(board)
def _solve_sudoku(self, board):
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if board[i][j] == '.':
for num in xrange(1, 10):
if self._is_valid_input(board, i, j, num):
row = board[i]
board[i] = board[i][:j] + str(num) + board[j + 1:]
if self.solveSudoku(board):
return True
else:
board[i] = row
return False
return True
def _is_valid_input(self, board, row, col, n):
for i in xrange(9):
if board[i][col] != '.' and board[i][col] == str(n):
return False
if board[row][i] != '.' and board[row][i] == str(n):
return False
if board[(row + i) / 3, (col + i) / 3] != '.' and board[(row + i) / 3, (col + i) / 3] == str(n):
return False
return True
def combinationSum(self, candidates, target):
"""
# 39. Combination Sum
Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(nums, target, index, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
dfs(nums, target - nums[i], i, path + [nums[i]], res)
res = []
candidates.sort()
dfs(candidates, target, 0, [], res)
return res
def combinationSum2(self, candidates, target):
"""
# 40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(nums, target, index, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
if i != index and nums[i] == nums[i - 1]:
continue
dfs(nums, target - nums[i], i + 1, path + [nums[i]], res)
res = []
candidates.sort()
dfs(candidates, target, 0, [], res)
return res
def trap(self, height):
"""
42. Trapping Rain Water
Given n non-negative integers representing an elevation map
where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
:type height: List[int]
:rtype: int
"""
h = 0
d = {}
water = 0
for i in xrange(len(height)):
h = max(h, height[i])
d[i] = h
h = 0
for i in xrange(len(height) - 1, -1, -1):
h = max(h, height[i])
water += min(d[i], h) - height[i]
return water
def jump(self, nums):
"""
45. Jump Game II
Given an array of non-negative integers,
you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2.
(Jump 1 step from index 0 to 1, then 3 steps to the last index.)
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) == 1:
return 0
step = 1
start = 0
end = nums[start]
max_pos = start + nums[start]
while end < len(nums) - 1:
for i in xrange(start + 1, end + 1):
max_pos = max(max_pos, nums[i] + i)
step += 1
start = end
end = max_pos
return step
def permute(self, nums):
"""
# 46. Permutations
Given a collection of distinct numbers, return all possible permutations.
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(n, path, ans):
if not n:
ans.append(path)
return
for i in xrange(len(n)):
dfs(n[:i] + n[i + 1:], path + [n[i]], ans)
res = []
dfs(nums, [], res)
return res
def permuteUnique(self, nums):
"""
# 47. Permutations II
Given a collection of numbers that might contain duplicates,
return all possible unique permutations.
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(n, path, ans):
if not n:
ans.append(path)
return
for i in xrange(len(n)):
if i != 0 and n[i] == n[i - 1]:
continue
dfs(n[:i] + n[i + 1:], path + [n[i]], ans)
nums.sort()
res = []
dfs(nums, [], res)
return res
def rotate(self, matrix):
"""
# 48. Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
'''
取巧的方法是:
matrix[::] = zip(*matrix[::-1])
1-line solution
'''
if not matrix:
return matrix
if len(matrix) != len(matrix[0]):
return None
n = len(matrix)
matrix.reverse()
for i in xrange(n):
for j in xrange(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return matrix
def groupAnagrams(self, strs):
"""
# 49. Group Anagrams
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
:type strs: List[str]
:rtype: List[List[str]]
"""
dictionary = {}
for s in strs:
key = ''.join(sorted(s))
if key in dictionary:
dictionary[key].append(s)
else:
dictionary[key] = [s]
return [i for i in dictionary.itervalues()]
def solveNQueens(self, n):
"""
51. N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard
such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement,
where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
:type n: int
:rtype: List[List[str]]
"""
res = []
self._dfs_leet51([], n, [], [], res)
return [['.' * i + 'Q' + '.' * (n - i - 1) for i in r] for r in res]
def _dfs_leet51(self, queens, n, xy_diff, xy_sum, res):
p = len(queens)
if p == n: # check width
res.append(queens)
return None
for q in xrange(n): # loop through all heights
if q not in queens and p - q not in xy_diff and p + q not in xy_sum:
self._dfs_leet51(queens + [q], n, xy_diff + [p - q], xy_sum + [p + q], res)
def totalNQueens(self, n):
"""
52. N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations,
return the total number of distinct solutions
:type n: int
:rtype: int
"""
self.res = 0
self._dfs_leet52([], n, [], [])
return self.res
def _dfs_leet52(self, queens, n, xy_diff, xy_sum):
p = len(queens)
if p == n:
self.res += 1
return None
for q in xrange(n):
if q not in queens and p - q not in xy_diff and p + q not in xy_sum:
self._dfs_leet52(queens + [q], n, xy_diff + [p - q], xy_sum + [p + q])
def maxSubArray(self, nums):
"""
# 53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
:type nums: List[int]
:rtype: int
"""
for i in xrange(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nums)
def spiralOrder(self, matrix):
"""
# 54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
:type matrix: List[List[int]]
:rtype: List[int]
"""
'''处理graph的要诀就是颠倒变换至便于操作的位置。参考#48的"取巧"解法'''
return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])
def merge(self, intervals):
"""
56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
:type intervals: List[Interval]
:rtype: List[Interval]
"""
'''对于sorted有了新的认识'''
merged = []
for i in sorted(intervals, key=lambda k: k.start):
if merged and i.start <= merged[-1].end:
merged[-1].end = max(merged[-1].end, i.end)
else:
merged.append(i)
return merged
def insert(self, intervals, newInterval):
"""
57. Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
'''
OR we can make a little use of # 56
------------------------------------------------------
def insert(self, intervals, newInterval):
intervals += [newInterval]
res = []
for i in sorted(intervals, key=lambda k: k.start):
if res and i.start <= res[-1].end:
res[-1].end = max(res[-1].end, i.end)
else:
res.append(i)
return res
------------------------------------------------------
'''
start = newInterval.start
end = newInterval.end
i = 0
res = []
while i < len(intervals):
if start <= intervals[i].end:
if end < intervals[i].start:
break
start = min(start, intervals[i].start)
end = max(end, intervals[i].end)
else:
res.append(intervals[i])
i += 1
res.append(Interval(start, end))
res += intervals[i:]
return res
# noinspection PyTypeChecker
def generateMatrix(self, n):
"""
59. Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
:type n: int
:rtype: List[List[int]]
"""
'''
临场能写出
def generateMatrix(self, n):
A = [[n*n]]
while A[0][0] > 1:
A = [range(A[0][0] - len(A), A[0][0])] + zip(*A[::-1])
return A * (n>0)
就相当了不起了
'''
matrix = []
s = n * n + 1 # make it starting from 1 rather than 0
while s > 1:
s, e = s - len(matrix), s
matrix = [range(s, e)] + zip(*matrix[::-1])
return matrix # spiral counter clockwise return zip(*matrix)
def getPermutation(self, n, k):
"""
60. Permutation Sequence
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
:type n: int
:type k: int
:rtype: str
"""
'''注意,以下解法是在一定有解的前提下。
如果不可解(比如n=1, k=2)则在判断nums[c]时加入些条件即可'''
res = []
nums = [i for i in xrange(1, n + 1)]
f = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
while n > 0:
c, k = k / f[n - 1], k % f[n - 1]
if k > 0:
res.append(str(nums[c]))
nums.remove(nums[c])
else:
res.append(str(nums[c - 1]))
nums.remove(nums[c - 1])
n -= 1
return ''.join(res)
def uniquePaths(self, m, n):
"""
62. Unique Paths
A robot is located at the top-left corner of a m x n grid
(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
(marked 'Finish' in the diagram below).
How many possible unique paths are there?
:type m: int
:type n: int
:rtype: int
"""
matrix = [[0] * m for _ in xrange(n)]
for i in xrange(n):
for j in xrange(m):
if j == 0 or i == 0:
matrix[i][j] = 1
else:
matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1]
return matrix[n - 1][m - 1]
def uniquePathsWithObstacles(self, obstacleGrid):
"""
63. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = 0
if m > 0:
n = len(obstacleGrid[0])
matrix = [[0] * n for _ in range(m)]
for i in xrange(m):
for j in xrange(n):
if i == 0 and j == 0:
matrix[i][j] = 1 if obstacleGrid[i][j] == 0 else 0
if obstacleGrid[i][j] == 1:
continue
if i == 0 and j > 0 and obstacleGrid[i][j - 1] == 0:
matrix[i][j] = matrix[i][j - 1]
continue
elif j == 0 and i > 0 and obstacleGrid[i - 1][j] == 0:
matrix[i][j] = matrix[i - 1][j]
continue
if i > 0 and j > 0 and obstacleGrid[i - 1][j] == 0:
matrix[i][j] += matrix[i - 1][j]
if i > 0 and j > 0 and obstacleGrid[i][j - 1] == 0:
matrix[i][j] += matrix[i][j - 1]
return matrix[m - 1][n - 1]
def minPathSum(self, grid):
"""
64. Minimum Path Sum
Given a m x n grid filled with non-negative numbers,
find a path from top left to bottom right which minimizes
the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = 0
if m > 0:
n = len(grid[0])
matrix = [[0] * n for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
if i == j == 0:
matrix[i][j] = grid[i][j]
continue
if i == 0 and j > 0:
matrix[i][j] = grid[i][j] + matrix[i][j - 1]
continue
elif j == 0 and i > 0:
matrix[i][j] = grid[i][j] + matrix[i - 1][j]
continue
matrix[i][j] = grid[i][j] + min(matrix[i - 1][j], matrix[i][j - 1])
return matrix[m - 1][n - 1]
def plusOne(self, digits):
"""
66. Plus One
Given a non-negative integer represented as a non-empty array of digits,
plus one to the integer.
You may assume the integer do not contain any leading zero,
except the number 0 itself.
The digits are stored such that the most significant digit is
at the head of the list.
:type digits: List[int]
:rtype: List[int]
"""
'''没有转换为integer是为避免溢出'''
reverse_digits = digits[::-1]
reverse_digits[0] += 1
for i in xrange(len(digits) - 1):
if reverse_digits[i] > 9:
reverse_digits[i] -= 10
reverse_digits[i + 1] += 1
if reverse_digits[-1] > 9:
reverse_digits[-1] -= 10
reverse_digits.append(1)
return reverse_digits[::-1]
def fullJustify(self, words, maxWidth):
"""
68. Text Justification
Given an array of words and a length L, format the text such that
each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is,
pack as many words as you can in each line. Pad extra spaces ' ' when necessary
so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible.
If the number of spaces on a line do not divide evenly between words,
the empty slots on the left will be assigned more spaces than the slots
on the right.
For the last line of text, it should be left justified and no extra space
is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
Note: Each word is guaranteed not to exceed L in length.
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
text = ' '.join(words) + ' '
if text == ' ':
return [' ' * maxWidth]
res = []
while text:
index = text.rfind(' ', 0, maxWidth + 1)
line = text[:index].split()
c_length = sum([len(w) for w in line])
word_count = len(line)
if word_count == 1:
res.append(line[0] + ' ' * (maxWidth - c_length))
else:
space_each = (maxWidth - c_length) / (word_count - 1)
space_remain = (maxWidth - c_length) % (word_count - 1)
line[:-1] = [w + ' ' * space_each for w in line[:-1]]
line[:space_remain] = [w + ' ' for w in line[:space_remain]]
res.append(''.join(line))
text = text[index + 1:]
res[-1] = ' '.join(res[-1].split()).ljust(maxWidth)
return res
def climbStairs(self, n):
"""
70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
:type n: int
:rtype: int
"""
climb = {}
climb[1] = 1
climb[2] = 2
for i in xrange(3, n + 1):
climb[i] = climb[i - 1] + climb[i - 2]
return climb[n]
def setZeroes(self, matrix):
"""
73. Set Matrix Zeroes
Given a m x n matrix, if an element is 0,
set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
if m == 0:
return
n = len(matrix[0])
n_zero = False
m_zero = False
if 0 in matrix[0]:
n_zero = True
for line in matrix:
if line[0] == 0:
m_zero = True
break
for i in xrange(1, m):
for j in xrange(1, n):
if matrix[i][j] == 0:
matrix[0][j] = 0
matrix[i][0] = 0
for i in xrange(1, m):
if matrix[i][0] == 0:
matrix[i] = [0] * n
for j in xrange(1, n):
if matrix[0][j] == 0:
for k in xrange(m):
matrix[k][j] = 0
if n_zero:
matrix[0] = [0] * n
if m_zero:
for line in matrix:
line[0] = 0
def sortColors(self, nums):
"""
75. Sort Colors
Given an array with n objects colored red, white or blue,
sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red,
white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
p1, p2 = 0, 0
for i in xrange(len(nums)):
if nums[i] == 0:
nums[i], nums[p2] = nums[p2], nums[p1]
nums[p1] = 0
p1 += 1
p2 += 1
elif nums[i] == 1:
nums[i], nums[p2] = nums[p2], nums[i]
p2 += 1
def combine(self, n, k):
"""
77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
:type n: int
:type k: int
:rtype: List[List[int]]
"""
'''
THERE IS A FORMULA OF
C(n, k) = C(n - 1, k - 1) + C(n - 1, k)
the following solution takes its idea.
time for some high school maths
-------------------------------------------
if k == 1:
return [[i] for i in range(1, n + 1)]
elif k == n:
return [[i for i in range(1, n + 1)]]
else:
rs = []
rs += self.combine(n - 1, k)
part = self.combine(n - 1, k - 1)
for ls in part:
ls.append(n)
rs += part
return rs
------------------------------------------
DFS itself is a little bit slow for this question
'''
def dfs(nums, c, index, path, res):
if c == 0:
res.append(path)
return
if len(nums[index:]) < c:
return
for i in xrange(index, len(nums)):
dfs(nums, c - 1, i + 1, path + [nums[i]], res)
result = []
dfs(list(xrange(1, n + 1)), k, 0, [], result)
return result
def subsets(self, nums):
"""
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
:type nums: List[int]
:rtype: List[List[int]]
"""
'''
def dfs(numbers, start, path, res):
res.append(path)
for i in xrange(start, len(numbers)):
dfs(numbers, i + 1, path + [numbers[i]], res)
result = []
dfs(sorted(nums), 0, [], result)
return result
'''
res = [[]]
for n in sorted(nums):
res += [r + [n] for r in res]
return res
def exist(self, board, word):
"""
79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell,
where "adjacent" cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board:
return False
visited = {}
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self._dfs_leet79(board, i, j, visited, word):
return True
return False
def _dfs_leet79(self, board, i, j, visited, word):
if len(word) == 0:
return True
if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or visited.get((i, j)):
return False
if board[i][j] != word[0]:
return False
visited[(i, j)] = True
# DO NOT RUN SEPARATELY AS WE DON'T NEED TO CALCULATE ALL OF FOUR
res = self._dfs_leet79(board, i - 1, j, visited, word[1:]) or \
self._dfs_leet79(board, i + 1, j, visited, word[1:]) or \
self._dfs_leet79(board, i, j - 1, visited, word[1:]) or \
self._dfs_leet79(board, i, j + 1, visited, word[1:])
visited[(i, j)] = False
return res
def largestRectangleArea(self, height):
"""
84. Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height
where the width of each bar is 1, find the area of largest rectangle in the histogram.
:type heights: List[int]
:rtype: int
"""
n = len(height)
if n < 2:
return height[0] if n else 0
height.append(0) # guard
max_area = 0
for i in xrange(0, n):
if height[i] > height[i + 1]:
bar = height[i]
k = i
while k >= 0 and height[k] > height[i + 1]:
bar = min(bar, height[k])
max_area = max(max_area, bar * (i - k + 1))
k -= 1
return max_area
def maximalRectangle(self, matrix):
"""
85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's,
find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix:
return 0
w = len(matrix[0])
max_area = 0
height = [0] * (w + 1)
for row in matrix:
for i in xrange(w):
height[i] = height[i] + 1 if row[i] == '1' else 0
for i in xrange(w):
if height[i] > height[i + 1]:
bar = height[i]
j = i
while j >= 0 and height[j] > height[i + 1]:
bar = min(bar, height[j])
max_area = max((i - j + 1) * bar, max_area)
j -= 1
return max_area
def numDecodings(self, s):
"""
91. Decode Ways
:type s: str
:rtype: int
A message containing letters from A-Z is being encoded to numbers
using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine
the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
"""
if not s:
return 0
d = [0] * (len(s) + 1)
d[0] = 1
d[1] = 1 if s[0] != '0' else 0
for i in xrange(2, len(s) + 1):
if 0 < int(s[i - 1:i]) <= 9:
d[i] += d[i - 1]
if s[i - 2:i][0] != '0' and int(s[i - 2:i]) < 27:
d[i] += d[i - 2]
return d[len(s)]
def maxProfit(self, prices):
"""
121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction
(ie, buy one and sell one share of the stock), design an algorithm to find
the maximum profit.
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for i in xrange(1, len(prices)):
current_profit = prices[i] - min_price
max_profit = max(current_profit, max_profit)
if prices[i] < min_price:
min_price = prices[i]
return max_profit
def findLadders(self, beginWord, endWord, wordList):
"""
126. Word Ladder II
(same as 127, return a list or visited words rather than the count of steps)
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
if endWord not in wordList:
return []
res = []
wordList = set(wordList)
queue = {beginWord: [[beginWord]]}
# 将当前queue全部取出,全部处理完成后再放进queue
# 考虑做为BFS求全部解的模板
# 127不需要全部取出是因为只需要找到一任意一个解即可结束
while queue:
build_dict = {}
for word in queue:
if word == endWord:
res.extend([k for k in queue[word]])
else:
for i in xrange(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
build = word[:i] + c + word[i + 1:]
if build in wordList:
if build in build_dict:
build_dict[build] += [seq + [build] for seq in queue[word]]
else:
build_dict[build] = [seq + [build] for seq in queue[word]]
wordList -= set(build_dict.keys())
queue = build_dict
return res
def ladderLength(self, beginWord, endWord, wordList):
"""
127. Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list,
find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list.
Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList:
return 0
queue = [(beginWord, 1)]
wordList = set(wordList)
visited = set()
while queue:
word, index = queue.pop(0)
for i in xrange(len(word)):
for j in 'abcdefghijklmnopqrstuvwxyz':
build = word[:i] + j + word[i + 1:]
if build == endWord:
return index + 1
if build not in visited and build in wordList:
visited.add(build)
queue.append((build, index + 1))
return 0
def longestConsecutive(self, nums):
"""
128. Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
:type nums: List[int]
:rtype: int
"""
s = set(nums)
longest = 0
for n in nums:
if n - 1 not in s:
end = n + 1
while end in s:
end += 1
longest = max(longest, end - n)
return longest
def wordBreak(self, s, wordDict):
"""
139. Word Break
Given a non-empty string s and a dictionary wordDict containing
a list of non-empty words, determine if s can be segmented into
a space-separated sequence of one or more dictionary words.
You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
wordDict = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in xrange(0, len(s)):
for j in xrange(i, len(s)):
if dp[i] and s[i:j + 1] in wordDict:
dp[j + 1] = True
return dp[len(s)]
def wordBreakII(self, s, wordDict):
"""
140. Word Break II
Given a non-empty string s and a dictionary wordDict containing
a list of non-empty words, add spaces in s to construct a sentence
where each word is a valid dictionary word. You may assume
the dictionary does not contain duplicate words.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
'''DP + DFS'''
d = {}
return self._dfs_leet140(s, d, wordDict)
def _dfs_leet140(self, s, d, wordDict):
if not s:
return [None]
if s in d:
return d[s]
res = []
for word in wordDict:
n = len(word)
if word == s[:n]:
for each in self._dfs_leet140(s[n:], d, wordDict):
if each:
res.append(word + ' ' + each)
else:
res.append(word)
d[s] = res
return res
def maxPoints(self, points):
"""
149. Max Points on a Line
Given n points on a 2D plane, find the maximum number
of points that lie on the same straight line.
:type points: List[Point]
:rtype: int
"""
l = len(points)
max_count = 0
for i in xrange(l):
d = {'vertical': 1}
count_lines = 0
ix, iy = points[i].x, points[i].y
for j in xrange(i + 1, l):
px, py = points[j].x, points[j].y
if px == ix and py == iy:
count_lines += 1
continue
if px == ix:
slope = 'vertical'
else:
slope = (py - iy) / (px - ix) # numpy.longfloat(1) * (py - iy) / (px - ix)
if slope not in d:
d[slope] = 1
d[slope] += 1
max_count = max(max_count, max(d.values()) + count_lines)
return max_count
def rob(self, nums):
"""
198. House Robber
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint
stopping you from robbing each of them is that adjacent houses have security
system connected and it will automatically contact the police if two adjacent
houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house,
determine the maximum amount of money you can rob tonight without alerting the police.
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
pre, now = 0, 0
for i in nums:
pre, now = now, max(pre + i, now)
return now
def numIslands(self, grid):
"""
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water),
count the number of islands. An island is surrounded by
water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
:type grid: List[List[str]]
:rtype: int
"""
if not grid:
return 0
count = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j] == '1':
self._dfs_leet200(grid, i, j)
count += 1
return count
def _dfs_leet200(self, grid, m, n):
if m < 0 or n < 0 or m >= len(grid) or n >= len(grid[0]) or grid[m][n] != '1':
return
grid[m] = grid[m][:n] + '$' + grid[m][n + 1:]
self._dfs_leet200(grid, m + 1, n)
self._dfs_leet200(grid, m - 1, n)
self._dfs_leet200(grid, m, n + 1)
self._dfs_leet200(grid, m, n - 1)
def rob_2(self, nums):
"""
213. House Robber II
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself
a new place for his thievery so that he will not get too much attention.
This time, all houses at this place are arranged in a circle. That means
the first house is the neighbor of the last one. Meanwhile, the security
system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house,
determine the maximum amount of money you can rob tonight without alerting the police.
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
pre, now = 0, 0
if len(nums) == 1:
return nums[0]
for i in nums[:-1]:
pre, now = now, max(pre + i, now)
highest = now
pre, now = 0, 0
for i in nums[1:]:
pre, now = now, max(pre + i, now)
return max(highest, now)
def findKthLargest(self, nums, k):
"""
215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ? k ? array's length.
:type nums: List[int]
:type k: int
:rtype: int
"""
def partition(numbers, low, high):
check, pivot = low, numbers[high]
for i in xrange(low, high):
if numbers[i] <= pivot:
numbers[check], numbers[i] = numbers[i], numbers[check]
check += 1
numbers[check], numbers[high] = numbers[high], numbers[check]
return check
l, h = 0, len(nums) - 1
k = len(nums) - k
while True:
index = partition(nums, l, h)
if index == k:
return nums[index]
elif index > k:
h = index - 1
else:
l = index + 1
def getSkyline(self, buildings):
"""
218. The Skyline Problem
(see description: https://leetcode.com/problems/the-skyline-problem/description/ )
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
import heapq
h = []
heights = [0]
max_height = 0
heapq.heapify(h)
skylines = []
for b in buildings:
heapq.heappush(h, (b[0], -b[2]))
heapq.heappush(h, (b[1], b[2]))
while h:
index, height = heapq.heappop(h)
if height < 0:
# found a starting point
height *= -1
if height > max_height:
max_height = height
heights.append(height)
skylines.append([index, height])
else:
heights.append(height)
else:
# found an ending point
if height < max_height or heights.count(max_height) > 1:
heights.remove(height)
else:
heights.remove(max_height)
max_height = sorted(list(heights))[-1]
skylines.append([index, max_height])
return skylines
def summaryRanges(self, nums):
"""
228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
:type nums: List[int]
:rtype: List[str]
"""
if not nums:
return []
nums.append(nums[0] - 1)
res = []
i = 0
while i < len(nums) - 1:
j = i
while j < len(nums) - 1:
if nums[j] + 1 == nums[j + 1]:
j += 1
else:
if i == j:
s = str(nums[i])
else:
s = str(nums[i]) + '->' + str(nums[j])
res.append(s)
j += 1
i = j
break
return res
def productExceptSelf(self, nums):
"""
238. Product of Array Except Self
Given an array of n integers where n > 1, nums,
return an array output such that output[i] is equal to
the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return 0
left = [1]
right = [1]
res = []
for i in xrange(len(nums) - 1, -1, -1):
right.append(nums[i] * right[-1])
for i in xrange(len(nums)):
left.append(nums[i] * left[-1])
res.append(left[i] * right[len(nums) - i - 1])
return res
def maxSlidingWindow(self, nums, k):
"""
239. Sliding Window Maximum
Given an array nums, there is a sliding window of size k which is moving
from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7].
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
import collections
d = collections.deque()
res = []
for i, n in enumerate(nums):
while d and nums[d[i]] < n:
d.pop()
d.append(i)
if d[0] == i - k:
d.popleft()
if i >= k - 1:
res.append(nums[d[0]])
return res
def shortestDistance(self, words, word1, word2):
"""
243. Shortest Word Distance
Given a list of words and two words word1 and word2,
return the shortest distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
l = len(words)
m, n = l, l
res = l
for i, w in enumerate(words):
if w == word1:
m = i
res = min(res, abs(m - n))
elif w == word2:
n = i
res = min(res, abs(m - n))
return res
def shortestWordDistance(self, words, word1, word2):
"""
245. Shortest Word Distance III
This is a follow up of Shortest Word Distance.
The only difference is now word1 could be the same as word2.
Given a list of words and two words word1 and word2,
return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = "makes", word2 = "makes", return 3.
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
if word1 == word2:
d = [i for i, w in enumerate(words) if w == word1]
res = len(words)
for n in xrange(1, len(d)):
res = min(res, d[n] - d[n - 1])
return res
res, d = len(words), {}
for i, w in enumerate(words):
if w == word1 and word2 in d:
res = min(res, i - d[word2])
if w == word2 and word1 in d:
res = min(res, i - d[word1])
if w == word1 or w == word2:
d[w] = i
return res
def getFactors(self, n):
"""
254. Factor Combinations
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
:type n: int
:rtype: List[List[int]]
"""
queue = [(n, 2, [])]
res = []
while queue:
cur, i, ans = queue.pop()
while i * i <= cur:
if cur % i == 0:
res.append(ans + [i, cur / i])
queue.append((cur / i, i, ans + [i]))
i += 1
return res
def minCost(self, costs):
"""
256. Paint House
There are a row of n houses, each house can be painted
with one of the three colors: red, blue or green.
The cost of painting each house with a certain color is different.
You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented
by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting
house 0 with color red; costs[1][2] is the cost of painting house 1 with color green,
and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
:type costs: List[List[int]]
:rtype: int
"""
if len(costs) == 0:
return 0
dp = costs[0]
for i in xrange(1, len(costs)):
cur = dp[:]
dp[0] = costs[i][0] + min(cur[1:3])
dp[1] = costs[i][1] + min(cur[0], dp[2])
dp[2] = costs[i][2] + min(cur[:2])
return min(dp)
def binaryTreePaths(self, root):
"""
257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
res = []
paths = []
self._dfs_leet257(root, [], res)
for r in res:
paths.append('->'.join(r))
return paths
def _dfs_leet257(self, node, path, res):
if not node.left and not node.right:
res.append(path + [str(node.val)])
return
if node.left:
self._dfs_leet257(node.left, path + [str(node.val)], res)
if node.right:
self._dfs_leet257(node.right, path + [str(node.val)], res)
def alienOrder(self, words):
"""
269. Alien Dictionary
There is a new alien language which uses the latin alphabet.
However, the order among letters are unknown to you.
You receive a list of non-empty words from the dictionary,
where words are sorted lexicographically by the rules of this new language.
Derive the order of letters in this language.
:type words: List[str]
:rtype: str
"""
def addOperators(self, num, target):
"""
282. Expression Add Operators
Given a string that contains only digits 0-9 and a target value,
return all possibilities to add binary operators (not unary) +, -, or *
between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
:type num: str
:type target: int
:rtype: List[str]
"""
res = []
for i in range(1, len(num) + 1):
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
self._dfs_leet282(num[i:], num[:i], int(num[:i]), int(num[:i]), target,
res) # this step put first number in the string
return res
def _dfs_leet282(self, num, temp, cur, last, target, res):
if not num:
if cur == target:
res.append(temp)
return
for i in range(1, len(num) + 1):
val = num[:i]
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
self._dfs_leet282(num[i:], temp + "+" + val, cur + int(val), int(val), target, res)
self._dfs_leet282(num[i:], temp + "-" + val, cur - int(val), -int(val), target, res)
self._dfs_leet282(num[i:], temp + "*" + val, cur - last + last * int(val), last * int(val), target, res)
def moveZeroes(self, nums):
"""
283. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function,
nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
p, q = 0, 0
while q < len(nums):
if nums[q] != 0:
nums[p], nums[q] = nums[q], nums[p]
p += 1
q += 1
def multiply(self, a, b):
"""
311. Sparse Matrix Multiplication
Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
if not a or not b:
return []
matrix = [[0 for _ in xrange(len(b[0]))] for _ in xrange(len(a))]
dict_a = {i: n for i, n in enumerate(a) if any(n)}
dict_b = {i: n for i, n in enumerate(zip(*b)) if any(n)}
for i in xrange(len(a)):
for j in xrange(len(b[0])):
if i in dict_a and j in dict_b:
for k in xrange(len(a[0])):
matrix[i][j] += a[i][k] * b[k][j]
return matrix
def maxCoins(self, nums):
"""
312. Burst Balloons
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it
represented by array nums. You are asked to burst all the balloons.
If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:
Given [3, 1, 5, 8]
Return 167
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
:type nums: List[int]
:rtype: int
"""
nums = [1] + nums + [1]
n = len(nums)
matrix = [[0 for _ in xrange(n)] for _ in xrange(n)]
k = 0
while k + 2 < n:
left, right = k, k + 2
matrix[left][right] = nums[k] * nums[k + 1] * nums[k + 2]
k += 1
for i in xrange(3, n):
k = 0
while k + i < n:
left, right = k, k + i
solutions = []
for j in xrange(left + 1, right):
ans = matrix[left][j] + nums[left] * nums[j] * nums[right] + matrix[j][right]
solutions.append(ans)
sol = max(solutions)
matrix[left][right] = sol
k += 1
i += 1
return matrix[0][-1]
def countSmaller(self, nums):
"""
315. Count of Smaller Numbers After Self
You are given an integer array nums and you have to return a new counts array.
The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
:type nums: List[int]
:rtype: List[int]
"""
rank = {val: i + 1 for i, val in enumerate(sorted(nums))}
N, res = len(nums), []
BITree = [0] * (N + 1)
def update(i):
while i <= N:
BITree[i] += 1
i += (i & -i)
def getSum(i):
s = 0
while i:
s += BITree[i]
i -= (i & -i)
return s
for x in reversed(nums):
res += getSum(rank[x] - 1),
update(rank[x])
return res[::-1]
def findItinerary(self, tickets):
"""
332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and
arrival airports [from, to], reconstruct the itinerary in order.
All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary
that has the smallest lexical order when read as a single string.
For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.
:type tickets: List[List[str]]
:rtype: List[str]
"""
d = {}
for start, end in tickets:
d[start] = d.get(start, []) + [end]
def dfs(dic, loc):
path.append(loc)
if len(path) == route_length:
return True
if loc in dic:
i, n = 0, len(dic[loc])
while i < n:
next_loc = dic[loc].pop()
if dfs(dic, next_loc):
return True
else:
dic[loc] = [next_loc] + dic[loc]
i += 1
path.pop()
return False
path = []
route_length = len(tickets) + 1
return dfs(d, 'JFK')
def palindromePairs(self, words):
"""
336. Palindrome Pairs
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list,
so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
:type words: List[str]
:rtype: List[List[int]]
"""
d = {w[::-1]: i for i, w in enumerate(words)}
res = []
for i, w in enumerate(words):
for j in xrange(len(w) + 1):
pre, post = w[:j], w[j:]
if pre in d and i != d[pre] and post == post[::-1]:
res.append([i, d[pre]])
# check j > 0 to avoid calculating itself twice
if j > 0 and post in d and i != d[post] and pre == pre[::-1]:
res.append([d[post], i])
return res
def rob_3(self, root):
"""
337. House Robber III
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root." Besides the root,
each house has one and only one parent house. After a tour, the smart thief
realized that "all houses in this place forms a binary tree". It will automatically
contact the police if two directly-linked houses were broken into on the same night.
:type root: TreeNode
:rtype: int
"""
return max(self._dfs_leet337(root))
def _dfs_leet337(self, root):
if not root:
return (0, 0)
left, right = self._dfs_leet337(root.left), self._dfs_leet337(root.right)
return (root.val + left[1] + right[1]), max(left) + max(right)
def reverseVowels(self, s):
"""
345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
:type s: str
:rtype: str
"""
d = 'aeiouAEIOU'
l, r = 0, len(s) - 1
s = list(s)
while l <= r:
if s[l] in d and s[r] in d:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
elif s[l] not in d:
l += 1
elif s[r] not in d:
r -= 1
else:
l += 1
r -= 1
return ''.join(s)
def numberOfPatterns(self, m, n):
"""
351. Android Unlock Patterns
Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9,
count the total number of unlock patterns of the Android lock screen,
which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
Each pattern must connect at least m keys and at most n keys.
All the keys must be distinct.
If the line connecting two consecutive keys in the pattern passes through any other keys,
the other keys must have previously selected in the pattern. No jumps through non selected
key is allowed.
The order of keys used matters.
:type m: int
:type n: int
:rtype: int
"""
skip = [[0 for _ in xrange(10)] for _ in xrange(10)]
skip[1][3] = skip[3][1] = 2
skip[1][7] = skip[7][1] = 4
skip[3][9] = skip[9][3] = 6
skip[7][9] = skip[9][7] = 8
skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5
visited = [False for _ in xrange(10)]
res = 0
for i in xrange(m, n):
res += self._dfs_leet351(1, visited, skip, i - 1) * 4
res += self._dfs_leet351(2, visited, skip, i - 1) * 4
res += self._dfs_leet351(5, visited, skip, i - 1)
return res
def _dfs_leet351(self, cur, visited, skip, remain):
if remain < 0:
return 0
if remain == 0:
return 1
visited[cur] = True
res = 0
for i in xrange(10):
if not visited[i] and (skip[cur][i] == 0 or visited(skip[cur][i])):
res += self._dfs_leet351(i, visited, skip, remain - 1)
visited[cur] = False
return res
def sortTransformedArray(self, nums, a, b, c):
"""
360. Sort Transformed Array
Given a sorted array of integers nums and integer values a, b and c.
Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
Result: [3, 9, 15, 33]
nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5
Result: [-23, -5, 1, 7]
:type nums: List[int]
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
res = []
if not nums:
return res
def f(x):
return a * x * x + b * x + c
l, r = 0, len(nums) - 1
while l <= r:
l_cal, r_cal = f(nums[l]), f(nums[r])
if (a > 0 and l_cal <= r_cal) or (a <= 0 and l_cal >= r_cal):
res.append(r_cal)
r -= 1
else:
res.append(l_cal)
l += 1
return res if a <= 0 else res[::-1]
def canCross(self, stones):
"""
403. Frog Jump
A frog is crossing a river. The river is divided into x units and at
each unit there may or may not exist a stone. The frog can jump on a stone,
but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order,
determine if the frog is able to cross the river by landing on the last stone.
Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1,
k, or k + 1 units. Note that the frog can only jump in the forward direction.
Note:
The number of stones is ≥ 2 and is < 1,100.
Each stone's position will be a non-negative integer < 231.
The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]
There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.
Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
[0,1,2,3,4,8,9,11]
Return false. There is no way to jump to the last stone as
the gap between the 5th and 6th stone is too large.
:type stones: List[int]
:rtype: bool
"""
d = {n: set() for n in stones}
d[1].add(1)
for i in xrange(len(stones[1:])):
for j in d[stones[i]]:
for k in xrange(j - 1, j + 2):
if k > 0 and stones[i] + k in d:
d[stones[i] + k].add(k)
return d[stones[-1]] != set()
def canPartition(self, nums):
"""
416. Partition Equal Subset Sum
Given a non-empty array containing only positive integers,
find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
:type nums: List[int]
:rtype: bool
"""
s = sum(nums)
if s % 2 != 0:
return False
return self._dfs_leet416(nums, s / 2, 0, len(nums) - 1, {})
def _dfs_leet416(self, nums, target, index, end, d):
if target == 0:
return True
elif target in d:
return d[target]
else:
d[target] = False
if target > 0:
for i in xrange(index, end):
if self._dfs_leet416(nums, target - nums[i], i + 1, end, d):
d[target] = True
break
return d[target]
def pacificAtlantic(self, matrix):
"""
417. Pacific Atlantic Water Flow
Given an m x n matrix of non-negative integers representing the
height of each unit cell in a continent, the "Pacific ocean" touches the left and
top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to
another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
pacific = [[False for _ in xrange(n)] for _ in xrange(m)]
atlantic = [[False for _ in xrange(n)] for _ in xrange(m)]
res = []
for i in xrange(m):
self._dfs_leet417(matrix, i, 0, pacific, m, n)
self._dfs_leet417(matrix, i, n - 1, atlantic, m, n)
for j in xrange(n):
self._dfs_leet417(matrix, 0, j, pacific, m, n)
self._dfs_leet417(matrix, m - 1, j, atlantic, m, n)
for i in xrange(m):
for j in xrange(n):
if pacific[i][j] and atlantic[i][j]:
res.append((i, j))
return res
def _dfs_leet417(self, matrix, i, j, visited, m, n):
visited[i][j] = True
directions = [(1, 0), (-1, 0), (0, -1), (0, 1)]
for d in directions:
x, y = i + d[0], j + d[1]
if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:
continue
self._dfs_leet417(matrix, x, y, visited, m, n)
def validWordSquare(self, words):
"""
422. Valid Word Square
Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid word square if the kth row and column
read the exact same string, where 0 ≤ k < max(numRows, numColumns).
Note:
The number of words given is at least 1 and does not exceed 500.
Word length will be at least 1 and does not exceed 500.
Each word contains only lowercase English alphabet a-z.
Example 1:
Input:
[
"abcd",
"bnrt",
"crmy",
"dtye"
]
Output:
true
Example 2:
Input:
[
"abcd",
"bnrt",
"crm",
"dt"
]
Output:
true
:type words: List[str]
:rtype: bool
"""
n = max(len(w) for w in words)
words = [w.ljust(n, '#') for w in words]
rotated = [''.join(z) for z in zip(*words)]
if len(rotated) != len(words):
return False
for i, r in enumerate(rotated):
if r != words[i]:
return False
return True
def numberOfBoomerangs(self, points):
"""
447. Number of Boomerangs
Given n points in the plane that are all pairwise distinct,
a "boomerang" is a tuple of points (i, j, k) such that
the distance between i and j equals the distance between i and k
(the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be
at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
:type points: List[List[int]]
:rtype: int
"""
res = 0
for p in points:
h = {}
for q in points:
if p != q:
dis = (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
h[dis] = 1 + h.get(dis, 0)
for k in h:
res += h[k] * (h[k] - 1)
return res
def findDisappearedNumbers(self, nums):
"""
448. Find All Numbers Disappeared in an Array
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume
the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
:type nums: List[int]
:rtype: List[int]
"""
return list(set(i for i in xrange(1, len(nums) + 1)) - set(nums))
def findLongestWord(self, s, d):
"""
524. Longest Word in Dictionary through Deleting
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]
Output:
"a"
:type s: str
:type d: List[str]
:rtype: str
"""
res = ''
for word in d:
k = 0
for char in s:
if k < len(word) and word[k] == char:
k += 1
if k < len(word):
continue
if len(word) > len(res) or (len(word) == len(res) and word < res):
res = word
return res
def checkRecord(self, s):
"""
551. Student Attendance Record I
You are given a string representing an attendance record for a student.
The record only contains the following three characters:
'A' : Absent.
'L' : Late.
'P' : Present.
A student could be rewarded if his attendance record doesn't contain more than
one 'A' (absent) or more than two continuous 'L' (late).
You need to return whether the student could be rewarded according to his attendance record.
Example 1:
Input: "PPALLP"
Output: True
Example 2:
Input: "PPALLL"
Output: False
:type s: str
:rtype: bool
"""
absence = 0
late = 0
for c in s:
if c == 'A':
absence += 1
late = 0
if absence >= 2:
return False
elif c == 'L':
late += 1
if late >= 3:
return False
else:
late = 0
return True
if __name__ == '__main__':
# debug template
l = Lists()
print l.findItinerary([["JFK", "SFO"], ["JFK", "ATL"], ["SFO", "ATL"], ["ATL", "JFK"], ["ATL", "SFO"]])
|
058d5277dcc28c95054d6ffe25e42f40b5ec8dbd | MistaRae/week_02_day_03_pub_lab | /tests/food_test.py | 396 | 3.59375 | 4 | import unittest
from src.food import Food
class TestFood(unittest.TestCase):
def setUp(self):
self.food_1 = Food("Pie", 2.50, 10, 10)
def test_food_setup(self):
self.assertEqual("Pie", self.food_1.name)
self.assertEqual(2.50, self.food_1.price)
self.assertEqual(10, self.food_1.rejuvenation_level)
self.assertEqual(10, self.food_1.quantity) |
acb4ea2a050f484cf9dd12e6459e66f6e2e59325 | jamanddounts/Python-answers | /4-8.py | 97 | 3.578125 | 4 | a = input("Input First Name:")
b = input("Input Last Name:")
print(a+b)
#any letter works btw :)
|
02dc3a901c01b82a690e0a2e7c637ba99d65e844 | haerba/SAD | /HangMan/Hangman_Visualizer.py | 2,834 | 3.71875 | 4 | '''
Created on 9 Mar 2019
@author: haerba
'''
class Hangman_Visualizer(object):
def __init__(self, name):
self.name = name
self.wrong_letter_strings = []
self.correct_letter_strings = []
self.hanged_man = []
self.charge_HangedMan()
def print_currentStatus(self, lifes, l_u, hidden_word):
print("------------------ HANGED MAN GAME ------------------","\nPlayer: "+self.name , "\nCurrent Lives: "+ str(lifes),
"\nUsed Letters: "+ ', '.join(l_u), "\nYour word is: "+ hidden_word, "\nHANGED MAN:\n\n", self.hanged_man[10-lifes])
def print_usedLetters(self, l_u):
print("""Letter already used, please insert another one.
Your used letters are:""")
print(', '.join(l_u))
def print_wrongLetter(self, letter):
print("Your letter was wrong.")
def charge_HangedMan(self):
self.hanged_man.append("")
self.hanged_man.append("______________")
self.hanged_man.append("""
|
|
|
|
|
|
|
|_____________
FFS pls.""")
self.hanged_man.append("""
––––––––––––––
|
|
|
|
|
|
|
|_____________
Just surrender pls.""")
self.hanged_man.append("""
––––––––––––––
| /
|/
|
|
|
|
|
|_____________
It looks exactly like the ETSETB exam rooms 10 min before...""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
|
|
|
|
|
|_____________
Just pray my boy.""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
| |
|
|
|
|
|_____________
Shit happens.""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
| -|
|
|
|
|
|_____________
It does not look very good man...""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
| -|-
|
|
|
|
|_____________
I can feel your death...""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
| -|-
| /
|
|
|
|_____________
It's getting closer!!!!!!!!""")
self.hanged_man.append("""
––––––––––––––
| / |
|/ O
| -|-
| / \
|
|
|
|_____________
You lost...""")
def print_GameOver(self, word):
print("\n\nYOU LOST! LOOOOOOOOOOOOOOOOOOOOOOOSER!!!!!", "\nThe word was "+word)
def print_Winner(self, word):
print("\n\n Beh, okay, you won. Wtf do you want? GET LOST.", "\nYour word was "+word)
def askForHint(self):
print("""Do you want a Hint?
Yes: y No: n""")
|
63f33acfd4983a8d927424754bb2a458e728a787 | quangnhan/PYT2106 | /Day10/fuc/bai2/shop.py | 2,172 | 3.5625 | 4 | from products import Product
from database import Database
class Shop:
def __init__(self, name, products, money):
self.products = products
self.name = name
self.money = money
def show_all_product(self):
for item in self.products:
print(f"amount: {item['amount']}\t amount sold: {item['amount_sold']}", end='\t')
item['product'].show()
def sell(self, product, amount):
item = None
#tìm product trong list
for item_name in self.products:
if item_name['product'].name == product:
item = item_name
if item == None: #nếu không có product-> return
print(f'No product such as {product}')
return
#nếu số lượng lớn hơn số lượng hiện có -> return
if amount > item['amount']:
print('Not enough quantity')
return
else:
item['amount'] -= amount
item['amount_sold'] += amount
self.money += amount*item['product'].price
print(f"Sold!! {item['product'].name} price: {item['product'].price}")
print(f'thanh tien: {item["product"].price*amount}')
return {'shop name': self.name, 'product': product, 'amount': amount, 'price': amount*item['product'].price}
# tạo ra một vài cái shop để order gọi
Db = Database()
list_product = []
list_shop = {}
count = 0
for item in Db.list_database:
product =Product(item['id'], item['name'], int(item['price']))
list_product.append({'amount':10, 'product':product, 'amount_sold': 0})
list_shop.update({f'shop{count}':Shop(f'shop{count}', list_product, 0)})
count +=1
print(list_shop)
if __name__ == '__main__':
'''Db = Database()
list_product = []
list_shop = []
count = 0
for item in Db.list_database:
product =Product(item['id'], item['name'], item['price'])
list_product.append({'amount':10, 'product':product, 'amount_sold': 0})
list_shop.append({f'shop{count}':Shop(f'shop{count}', list_product, 0)})
count +=1
print(list_shop)'''
pass |
a0d4a8084a84705a4a8151e568e040528c5c3987 | pyh3887/Tensorflow | /py_tensorflow/pack/tf3/케라스20_이미지분류.py | 3,093 | 3.515625 | 4 | # CNN(Convoluation)
# convolution : feature extraction 역할
import tensorflow as tf
from tensorflow.keras import datasets,layers,models
import sys
(x_train,y_train),(x_test,y_test) = tf.keras.datasets.fashion_mnist.load_data()
print(x_train.shape, ' ', y_train.shape) # (60000, 28, 28) (60000,)
print(x_test.shape, ' ', y_test.shape) #(10000, 28, 28) (10000,)
print(x_train[0])
# import matplotlib.pyplot as plt
# plt.imshow(x_train[0].reshape(28,28), cmap = 'Greys')
# plt.show()
# 3차원을 4차원으로 구조 변경 . (흑백(1), 칼라(3) 여부 확인용 채널 추가 )
x_train = x_train.reshape((60000,28,28,1))
print(x_train.ndim)
train_images = x_train / 255.0 # 정규화
print(train_images[:1])
x_test = x_test.reshape((10000,28,28,1)) # 구글 이외의 제품일 경우 채널의 위치가 다를수 있다.
print(x_test.ndim)
test_test = x_test /255.0
print(test_test[:1])
# model
model = models.Sequential()
#CNN
model.add(layers.Conv2D(64, kernel_size=(3,3),padding='valid',
activation='relu',input_shape=(28,28,1)))
#valid는 패딩을 두지 않겠다는 의미.
model.add(layers.MaxPool2D(pool_size=(2,2),strides=None)) #strides=(2,2)
model.add(layers.Dropout(0.2))
model.add(layers.Flatten()) #fully connected layer :이미지의 주요 특징만 추출한 CNN 결과를 1차원으로 변경
#분류기로 분류 작업
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(32,activation='relu'))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(10,activation='softmax'))
model.summary() # 설정된 구조 화깅ㄴ
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',metrics=['accuracy']) #sparse_categorical > onehot encoding 내부적으로가능
from tensorflow.keras.callbacks import EarlyStopping
early_stop = EarlyStopping(monitor='loss',patience='5')
history = model.fit(x_train,y_train,batch_size=128,verbose=2,validation_split=0.2,epochs=100,callbacks = [early_stop])
history = history.history
print(history)
#evaluate
train_loss, train_acc = model.evaluate(x_test,y_test,batch_size=128,verbose=2)
test_loss, test_acc = model.evaluate(x_test,y_test,batch_size=128,verbose=2)
print('train_loss, train_acc : ',train_loss, train_acc)
print('test_loss, test_acc : ',test_loss,test_acc)
#모델 저장 후 읽기
model.save('fashion.hdf5')
del model
model = tf.keras.models.load_model('fashion.hdf5')
#predict
import numpy as np
print('예측값 :',np.argmax(model.predict(x_test[:1])))
print('예측값 :',np.argmax(model.predict(x_test[[0]])))
print('실제값 : ',y_test[0])
print('예측값 :',np.argmax(model.predict(x_test[[1]])))
print('실제값 : ',y_test[1])
import matplotlib.pyplot as plt
def plot_acc(title=None):
plt.plot(history['accuracy'])
plt.plot(history['val_accuracy'])
if title is not None:
plt.title(title)
plt.xlabel('epchos')
plt.xlabel('acc')
plt.legend(['train data', 'validation data'],loc =4)
plot_acc('accuracy')
plt.show()
plt.show()
|
bc11cec9c380b4f15ccd108ea244ab415f8abbfc | titf512/FPRO---Python-exercises | /overlap_segments.py | 531 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 09:14:10 2021
@author: teresaferreira
"""
def overlaps(segments):
lst=[]
sett=set()
for i in range(len(segments)):
a=[x for x in range(segments[i][0],segments[i][1]+1)]
lst+=[a]
for k in range(len(lst)):
for m in range(k+1,len(lst)):
for element in lst[k]:
if element in lst[m]:
comum=element
b=(k,m)
sett.add(b)
return sett |
37599fcdc322912d59d16638459d3e7637c04dbd | Sharan1425/pythonProject1 | /venv/Palindrome.py | 126 | 4.0625 | 4 | n = input("Please enter the input: ")
if n == n[::-1]:
print(n,"is a palindrome")
else:
print(n,"is not a palindrome") |
4541b293c58dbd978594a745b239a0b16e98a87e | scls19fr/openphysic | /python/oreilly/cours_python/solutions/exercice_12_04.py | 731 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding: Latin-1 -*-
class Satellite:
def __init__(self, nom, masse =100, vitesse =0):
self.nom, self.masse, self.vitesse = nom, masse, vitesse
def impulsion(self, force, duree):
self.vitesse = self.vitesse + force * duree / self.masse
def energie(self):
return self.masse * self.vitesse**2 / 2
def affiche_vitesse(self):
print "Vitesse du satellite %s = %s m/s" \
% (self.nom, self.vitesse)
# Programme de test :
s1 = Satellite('Zo', masse =250, vitesse =10)
s1.impulsion(500, 15)
s1.affiche_vitesse()
print s1.energie()
s1.impulsion(500, 15)
s1.affiche_vitesse()
print s1.energie() |
488693d68288ed23463eb962318831c356bc6e17 | leehm00/pyexamples | /Python概述/面向对象/创建类的实例成员(方法).py | 680 | 3.828125 | 4 | # _*_ coding.utf-8 _*_
# 开发人员 : leehm
# 开发时间 : 2020/6/22 10:15
# 文件名称 : 创建类的实例成员(方法).py
# 开发工具 : PyCharm
# 与函数类似,第一个参数必须是self且必须是包含此参数
class Geese:
"""大雁类"""
def __init__(self, beak, wing, claw): # 构造方法只能有一个
print('大雁类') # 判断init是否执行了
print(beak, wing, claw)
def fly(self, state='可以飞'): # 飞行方法,制定了默认值
print(state)
beak1 = 'beak1'
wing1 = 'wing1'
claw1 = 'claw1'
WildGoose = Geese(beak1, wing1, claw1) # 传入init的三个参数,self自动传入
WildGoose.fly('fly1')
|
a09c6287e6141315348816462ff6fdc63097b4e6 | Zgurskaya/geekbrains_python | /lesson_3/homework_3/home_7.py | 907 | 4.34375 | 4 | """
Продолжить работу над заданием. В программу должна попадать строка из слов,
разделённых пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Нужно
сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
Используйте написанную ранее функцию int_func().
"""
def int_func(string):
# функция возвращает каждое слово строчки с первой прописной буквой, остальные буквы строчные
print(string.lower())
return string.title()
print(int_func(input("Введите строку из слов, разделенных пробелами")))
|
d79844e0d0df3392592a6d500296b6ffcf73cba8 | greatteacher/lesson2part1 | /not4u/pincode.py | 363 | 3.734375 | 4 | line=input('введите свой пинкодище ')
a=type(line)
if a !=str:
print('O no no no')
t1=input('введите свой пинкод ')
t1=str(t1)
t2=input(' повторишь свой пинкод? ')
t2=str(t2)
if t1 == t2:
print('попал')
else:
print('попробуй в другой раз, у тебя получится') |
73a6a886e5c0d9ccc1d5e8e4a4621c7ae5239f81 | avadhootkulkarni/learn_python_hard_way_exercises | /ex14.py | 712 | 3.703125 | 4 | from sys import argv
script, user_name, age = argv
prompt = 'Answer - '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'm gonna ask you a few questions"
print "Do you like me, %s" % user_name
likes = raw_input(prompt)
print "Where do you live, %s" % user_name
lives = raw_input(prompt)
print "What computer do you have?"
computer = raw_input(prompt)
print "Do you play super mario? Difficult question for a %s years old ;)" % age
mario = raw_input(prompt)
print """
Okay %s, so you said %r about liking me.
You live in %r. Cool place!
And you have %r computer. Nice.
Playing mario is good. You said %r, It's a game for kids to be honest :D
""" % (user_name, likes, lives, computer, mario)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.