text
stringlengths 37
1.41M
|
---|
class Solution:
def rotate(self, nums, k):
copy_nums = nums.copy()
for i in range(len(nums)):
nums[(i + k) % len(nums)] = copy_nums[i]
class Solution:
def rotate(self, nums, k):
n = len(nums)
k %= n
# reverse all numbers
for i in range(n // 2):
nums[i], nums[n - i - 1] = nums[n - i - 1], nums[i]
# reverse first k numbers
for i in range(k // 2):
nums[i], nums[k - i - 1] = nums[k - i - 1], nums[i]
# reverse last n-k numbers
for i in range(k, n - (n - k) // 2):
nums[i], nums[n - i - 1 + k] = nums[n - i - 1 + k], nums[i]
class Solution:
def rotate(self, nums, k):
n = len(nums)
k %= n
start = count = 0
while count < n:
current, prev = start, nums[start]
while True:
next_idx = (current + k) % n
nums[next_idx], prev = prev, nums[next_idx]
current = next_idx
count += 1
if start == current:
break
start += 1
|
# Approach 1 using sorting
# Time-complexity: O(N log N)
class Solution:
def carPooling(self, trips, capacity):
timestamp = []
for trip in trips:
timestamp.append([trip[1], -trip[0]])
timestamp.append([trip[2], trip[0]])
timestamp.sort(key=lambda x: (x[0], -x[1]))
for el in timestamp:
capacity += el[1]
if capacity < 0:
return False
return True
# Approach 2 using Bucket Sort
# Time-complexity: O(N)
class Solution2:
def carPooling(self, trips, capacity):
timestamp = [0] * 1001
for trip in trips:
timestamp[trip[1]] -= trip[0]
timestamp[trip[2]] += trip[0]
for i in range(1001):
capacity += timestamp[i]
if capacity < 0:
return False
return True
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
first = TreeNode()
second = TreeNode()
prev = TreeNode(-(2**31))
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.traverse(root)
self.first.val = self.second.val
def traverse(self, root: TreeNode):
if not root:
return
self.traverse(root.left)
if not self.first and self.prev.val >= root.val:
self.first = self.prev
if self.first and self.prev.val >= root.val:
self.second = root
self.prev = root
self.traverse(root.right)
|
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
sorted_nodes = []
stack1 = []
stack2 = []
while stack1 or root1 or stack2 or root2:
while root1:
stack1.append(root1)
root1 = root1.left
while root2:
stack2.append(root2)
root2 = root2.left
if not stack2 or (stack1 and stack1[-1].val <= stack2[-1].val):
root1 = stack1.pop()
sorted_nodes.append(root1.val)
root1 = root1.right
else:
root2 = stack2.pop()
sorted_nodes.append(root2.val)
root2 = root2.right
return sorted_nodes
|
# Brute-Force: O(N ^ 3) where N - length of s
class Solution:
def longestNiceSubstring(self, s: str) -> str:
n = len(s)
max_length = 0
ans = ""
for i in range(n - 1):
for j in range(i + 1, n):
good = True
substring = s[i:j + 1]
set_ch = set()
for ch in substring:
if ch not in set_ch:
set_ch.add(ch)
for ch in set_ch:
if 'a' <= ch <= 'z':
other_ch = chr(ord(ch) - 32)
else:
other_ch = chr(ord(ch) + 32)
if other_ch not in set_ch:
good = False
break
if good:
if j - i > max_length:
max_length = j - i
ans = s[i:j + 1]
return ans
# Optimized: O(N ^ 2)
class Solution:
def longestNiceSubstring(self, s: str) -> str:
n = len(s)
start = end = 0
for i in range(n - 1):
set_ch = {s[i]}
deleted = set()
for j in range(i + 1, n):
ch = s[j]
if 'a' <= ch <= 'z':
other_ch = chr(ord(ch) - 32)
else:
other_ch = chr(ord(ch) + 32)
if other_ch in deleted or ch in deleted:
if not set_ch and j - i > end - start:
end = j
start = i
continue
if ch not in set_ch:
if other_ch in set_ch:
set_ch.remove(other_ch)
if not set_ch and j - i > end - start:
end = j
start = i
deleted.add(ch)
else:
set_ch.add(ch)
if start == end:
return ""
return s[start:end + 1]
|
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
largest_sum = -float("inf")
curr_sum = 0
for num in nums:
curr_sum += num
largest_sum = max(largest_sum, curr_sum)
curr_sum = max(0, curr_sum)
return largest_sum
|
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
n = len(board)
m = len(board[0])
rows, cols, squares = {}, {}, {}
for i in range(9):
rows[i] = set()
cols[i] = set()
for i in range(3):
for j in range(3):
squares[(i, j)] = set()
for i in range(n):
for j in range(m):
if board[i][j] != '.':
square_x, square_y = i // 3, j // 3
if board[i][j] in rows[i] or board[i][j] in cols[j] or board[i][j] in squares[(square_x, square_y)]:
return False
rows[i].add(board[i][j])
cols[j].add(board[i][j])
squares[(square_x, square_y)].add(board[i][j])
return True
|
# Recursive
class Solution:
def postorderTraversal(self, root):
ans = []
self.helper(root, ans)
return ans
def helper(self, root, ans):
if root:
self.helper(root.left, ans)
self.helper(root.right, ans)
ans.append(root.val)
# Iterative 1
# The first is by postorder using a flag to indicate whether the node has been visited or not.
class Solution2:
def postorderTraversal(self, root):
ans = []
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if node:
if visited:
# add to result if visited
ans.append(node.val)
else:
# post-order
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
return ans
# Iterative 2
# The second uses modified preorder(right subtree first).Then reverse the result
class Solution3:
def postorderTraversal(self, root):
ans = []
stack = [root]
while stack:
node = stack[-1]
stack.pop()
if node:
# pre-order, right first
ans.append(node.val)
stack.append(node.left)
stack.append(node.right)
# reverse result
return ans[::-1]
|
# Recursive
class Solution:
def inorderTraversal(self, root):
ans = []
self.solve(root, ans)
return ans
def solve(self, root, ans):
if root:
self.solve(root.left, ans)
ans.append(root.val)
self.solve(root.right, ans)
return ans
# Iterative
class Solution2:
def inorderTraversal(self, root):
stack = []
ans = []
while root or len(stack) > 0:
while root:
stack.append(root)
root = root.left
root = stack[-1]
stack.pop()
ans.append(root.val)
root = root.right
return ans
# Morris Method
class Solution3:
def inorderTraversal(self, root):
ans = []
curr = root
while curr:
if not curr.left:
ans.append(curr.val)
curr = curr.right
else:
pre = curr.left
while pre.right:
pre = pre.right
pre.right = curr
temp = curr
curr = curr.left
temp.left = None
return ans
|
from typing import List
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
duplicates = {}
for path in paths:
directory, *files = path.split(" ")
for file in files:
idx = file.index('(')
content = file[idx + 1: -1]
directory_path = directory + '/' + file[:idx]
if content in duplicates:
duplicates[content].append(directory_path)
else:
duplicates[content] = [directory_path]
duplicates = duplicates.values()
ans = []
for duplicate in duplicates:
if len(duplicate) > 1:
ans.append(duplicate)
return ans
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
dq = deque()
dq.append(root)
level = 0
while dq:
level += 1
for _ in range(len(dq)):
curr = dq.popleft()
if curr.left:
dq.append(curr.left)
if curr.right:
dq.append(curr.right)
return level
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head):
if not head:
return
if head.next:
h = head.next
else:
return head
curr = head
first = True
while True:
nxt = curr.next
third = curr.next.next
if not first:
prev.next = nxt
else:
first = False
nxt.next = curr
curr.next = third
prev = curr
if curr.next:
if curr.next.next:
curr = curr.next
else:
break
else:
break
return h
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
cur_root = root
while cur_root:
last_root = cur_root
if val < cur_root.val:
cur_root = cur_root.left
position = 0
else:
cur_root = cur_root.right
position = 1
if position == 0:
last_root.left = TreeNode(val)
else:
last_root.right = TreeNode(val)
return root
|
def hIndex(citations):
if len(citations) == 0 or (len(citations) == 1 and citations[0] == 0):
return 0
l = 0
r = len(citations) - 1
ans = 0
while l <= r:
mid = l + (r - l) // 2
if citations[mid] == len(citations) - mid:
return citations[mid]
elif citations[mid] > len(citations) - mid:
ans = len(citations) - mid
r = mid - 1
else:
l = mid + 1
return ans
|
from typing import List
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
nums_sum = sum(nums)
n = len(nums)
left_sum, right_sum = 0, nums_sum
for i in range(n):
right_sum -= nums[i]
if left_sum == right_sum:
return i
left_sum += nums[i]
return -1
|
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for row in matrix:
start = 0
end = n - 1
while start < end:
row[start], row[end] = row[end], row[start]
start += 1
end -= 1
i = n - 1
j = 0
while True:
start_x = i
start_y = j
sum_idx = n - (start_x + start_y) - 1
end_x = start_x + sum_idx
end_y = start_y + sum_idx
while start_x < end_x:
matrix[start_x][start_y], matrix[end_x][end_y] = matrix[end_x][end_y], matrix[start_x][start_y]
start_x += 1
start_y += 1
end_x -= 1
end_y -= 1
if i == 0:
j += 1
else:
i -= 1
if i == 0 and j == n:
break
|
def validIPAddress(ip):
number = 0
word = 0
ok = 1
zero = 0
if ip.count(':') == 7 and len(ip) <= 39:
for ch in ip:
if ('a' <= ch <= 'f') or ('A' <= ch <= 'F') or ch.isdecimal():
word += 1
elif ch == ':':
if word > 4 or word == 0:
return "Neither"
word = 0
else:
return "Neither"
if word == 0 or word > 4:
return "Neither"
else:
return "IPv6"
elif ip.count('.') == 3 and len(ip) <= 15:
for ch in ip:
if '0' <= ch <= '9':
if zero == 1:
return "Neither"
if ch == '0':
zero = 1
else:
zero = 0
number = number * 10 + int(ch)
ok = 0
elif ch == '.':
if number >= 256 or ok == 1:
return "Neither"
number = 0
ok = 1
zero = 0
else:
return "Neither"
if number >= 256 or ok == 1:
return "Neither"
else:
return "IPv4"
else:
return "Neither"
|
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
merged_start, merged_end = intervals[0]
merged_intervals = []
for start, end in intervals:
if start <= merged_end:
merged_end = max(merged_end, end)
else:
merged_intervals.append([merged_start, merged_end])
merged_start, merged_end = start, end
merged_intervals.append([merged_start, merged_end])
return merged_intervals
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
add = 0
dummy = l3 = ListNode(0)
while l1 and l2:
sum_digits = l1.val + l2.val + add
add = sum_digits // 10
l3.next = ListNode(sum_digits % 10)
l3 = l3.next
l1 = l1.next
l2 = l2.next
while l1:
add_digit = l1.val + add
add = add_digit // 10
l3.next = ListNode(add_digit % 10)
l3 = l3.next
l1 = l1.next
while l2:
add_digit = l2.val + add
add = add_digit // 10
l3.next = ListNode(add_digit % 10)
l3 = l3.next
l2 = l2.next
if add == 1:
l3.next = ListNode(1)
return dummy.next
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
first_greater = prev = None
curr = head
while curr:
changed_curr = False
if curr.val < x:
if first_greater:
changed = curr
curr = curr.next
prev.next = curr
if before_first_greater:
before_first_greater.next = changed
else:
head = changed
changed.next = first_greater
before_first_greater = changed
changed_curr = True
else:
if not first_greater:
first_greater = curr
before_first_greater = prev
if not changed_curr:
if not prev:
prev = curr
else:
prev = prev.next
curr = curr.next
return head
|
# Approach 1 using hashing
# Time-complexity: O(N)
class Solution:
def findJudge(self, N, trust):
people = [0] * N
for pair in trust:
people[pair[1]-1] += 1
trust_judge = max(people)
if trust_judge == N - 1:
judge = people.index(trust_judge)
for pair in trust:
if pair[0] == judge+1:
return -1
return judge+1
return -1
# Approach 2 using matrix
# Time-complexity: O(N ^ 2)
class Solution:
def findJudge(self, N, trust) -> int:
possible_town_judge = -1
matrix = [[0] * N for _ in range(N)]
for pair in trust:
matrix[pair[0] - 1][pair[1] - 1] = 1
# Check possible town judge by searching a line with all zeroes
for i in range(N):
zero = True
for j in range(N):
if matrix[i][j] == 1:
zero = False
break
if zero:
possible_town_judge = i
if possible_town_judge == -1:
return -1
# Check if possible town judge is the actual town judge by searching for a column with only one zero
cnt = 0
for i in range(N):
if matrix[i][possible_town_judge] == 1:
cnt += 1
if cnt == N - 1:
return possible_town_judge + 1
else:
return -1
|
def rangeBitwiseAnd(x, y):
while x < y:
y -= (y & -y)
return y
print(rangeBitwiseAnd(12, 15))
|
def trace(matrix):
r = 0
trace = 0
index = 0
for row in matrix:
if len(row) != len(set(row)):
r += 1
trace += row[index]
index += 1
return [r, trace]
t = int(input())
for i in range(1, t + 1):
n = int(input())
matrix = []
matrix_reversed = []
for j in range(n):
matrix.append([int(s) for s in input().split(" ")])
for col in range(len(matrix)):
column = []
for row in range(len(matrix)):
column.append(matrix[row][col])
matrix_reversed.append(column)
trace(matrix_reversed)
print("Case #{}: {} {} {}".format(i, trace(matrix)[1], trace(matrix)[0], trace(matrix_reversed)[0]))
|
from collections import deque
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
dq = deque()
dq.append(["(", 1, 0])
ans = []
while dq:
combination, left, right = dq.popleft()
if left == n and right == n:
ans.append(combination)
continue
if left == right:
dq.append([combination + "(", left + 1, right])
elif left == n:
dq.append([combination + ")", left, right + 1])
else:
dq.append([combination + "(", left + 1, right])
dq.append([combination + ")", left, right + 1])
return ans
|
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
stack = [root]
range_sum = 0
while stack:
curr_node = stack.pop()
if low <= curr_node.val <= high:
if low != curr_node.val and curr_node.left:
stack.append(curr_node.left)
if high != curr_node.val and curr_node.right:
stack.append(curr_node.right)
range_sum += curr_node.val
elif low > curr_node.val:
if curr_node.right:
stack.append(curr_node.right)
else:
if curr_node.left:
stack.append(curr_node.left)
return range_sum
|
# Approach 1 (BRUTE-FORCE)
# TC: O(2^N)
class Solution:
def fib(self, n: int) -> int:
if n < 2:
return n
return self.fib(n-1)+self.fib(n-2)
# Approach 2 (MEMOIZATION)
# TC: O(N)
class Solution:
def fib(self, n: int) -> int:
cache = {0: 0, 1: 1}
def recur_fib(n):
if n in cache:
return cache[n]
else:
result = recur_fib(n-1)+recur_fib(n-2)
cache[n] = result
return result
return recur_fib(n)
|
from math import sqrt
t = int(input())
for test in range(1, t + 1):
z = int(input())
target = int(sqrt(z))
first = second = third = -1
for i in range(target, target - 565, -1):
prime = True
for d in range(2, int(sqrt(i) + 1)):
if i % d == 0:
prime = False
break
if prime:
if second == -1:
second = i
else:
first = i
break
for i in range(target + 1, target + 283):
prime = True
for d in range(2, int(sqrt(i)) + 1):
if i % d == 0:
prime = False
break
if prime:
third = i
break
if second * third <= z:
print("Case #{}: {}".format(test, second * third))
else:
print("Case #{}: {}".format(test, first * second))
|
#!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program calculates the square of all positive integers
# between 0 and a user input
def main():
# this function will calculate the square of all positive
# integers between 0 and a user input
print("This program calculates the square of all positive integers"
" between 0 and a user input.")
# loop counter variable
loop_counter = 0
# square of positive integers variable
square_num = 0
# input
user_input = input("Enter a positive integer: ")
print("")
# process
try:
user_input_int = int(user_input)
if user_input_int >= 0:
# loop statement
for loop_counter in range(user_input_int + 1):
square_num = loop_counter**2
print("{0}² = {1}".format(loop_counter, square_num))
else:
# output
print("{} is not a positive integer!"
.format(user_input_int))
except Exception:
# output
print("That's not a number! Try again.")
finally:
print("")
print("Thanks for playing!")
if __name__ == "__main__":
main()
|
'''The function filter(function, list) offers an elegant way to filter out all the elements of a list,
for which the function function returns True.
The function filter(f,l) needs a function f as its first argument.
f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l.
Only if f returns True will the element of the list be included in the result list. '''
fib=[0,1,1,2,3,5,8,13,21,34,55]
output=filter(lambda x:x%2==0,fib)
print output
pentaho_acl_authorize_list=("GrantedAuthorityEffectiveAclsResolver",
"GrantedAuthority", "AclEntry", "IPentahoSession", "WebPentahoObjectFactory")
def stringwithg(st):
return st.()
pentaho_acl_authorize_uppercase_list=map(uppercase,pentaho_acl_authorize_list)
print pentaho_acl_authorize_uppercase_list
|
_MAX_SPLITS_ALLOWED = 1
class Hand(object):
"""A representation of a blackjack hand."""
def __init__(self, split=False, split_card=None, split_count=0):
"""Deals a new blackjack hand and stores it as a tuple.
Args:
shoe: A blackjack shoe interface.
split: A boolean indicating whether the hand is a result of a split
split_card: The card that was in the split hand that will now make
up the new hand.
"""
self.split_count = split_count
self.split_aces = False
self._ace_count = 0
self._doubled_down = False
self._cards = ()
if split:
self._cards = split_card,
if self._cards[0].rank == 'A':
self._ace_count += 1
self.split_aces = True
self.split_count += 1
def deal_hand(self, shoe):
"""Deals a new 2 card blackjack hand.
Args:
shoe: Blackjack shoe that cards are dealt from.
"""
self._cards = (shoe.deal_card(), shoe.deal_card())
for card in self._cards:
if card.rank == 'A':
self._ace_count += 1
def hit(self, shoe):
"""Adds a card to the hand when the player or dealer hits.
Args:
shoe: Blackjack shoe that cards are dealt from.
"""
self._cards += shoe.deal_card(),
if self._cards[-1].rank == 'A':
self._ace_count += 1
def hand_value(self):
"""Returns the blackjack hand value."""
hand_value = 0
for card in self._cards:
hand_value += card.value()
if hand_value > 21 and self._ace_count > 0:
aces_left = self._ace_count
while aces_left > 0:
hand_value -= 10
if hand_value <= 21:
break
aces_left -= 1
return hand_value
def display_hand(self):
"""Returns the cards in the hand in the form of 'RsRs...'."""
cards = ""
for card in self._cards:
cards += card.rank + card.suit
return cards
def display_one_dealer_card(self):
"""Returns the first card as a string in the form 'Rs'"""
return self._cards[0].rank + self._cards[0].suit
def split(self):
"""Splits a two card hand and returns two one card hands."""
card_one = self._cards[0]
card_two = self._cards[1]
hand_one = Hand(True, card_one, self.split_count)
hand_two = Hand(True, card_two, self.split_count)
return hand_one, hand_two
def split_allowed(self):
"""Returns True if split is allowed, otherwise False."""
if len(self._cards) == 2 and (
self.split_count < _MAX_SPLITS_ALLOWED) and (
self._cards[0].rank == self._cards[1].rank):
return True
else:
return False
def double_down_allowed(self):
"""Returns True if double down is allowed, False otherwise."""
if len(self._cards) == 2 and self.split_count == 0 and (
self._doubled_down is False):
return True
else:
return False
|
import bankroll
class PlayerInput(object):
"""Container for player input functions."""
def __init__(self, time):
"""Creates a new player input container.
Args:
time: A time interface.
"""
self._time = time
def welcome_and_get_buyin(self, input_func=raw_input):
"""Welcomes the player to the game and returns buy-in amount.
Args:
input_func: Function to receive input from the user.
"""
print ("\nWelcome to Shetty Casino blackjack! We're thrilled to take "
"your mon...I mean...we're thrilled to have you here playing "
"with us!\n")
print ("The rules of blackjack can be found here: \n\n"
"http://www.bicyclecards.com/how-to-play/blackjack/ \n\nIn "
"addition, we have some house rules: We don't offer insurance, "
"we only allow one split per hand, and we don't allow doubling "
"down after a split.")
while True:
try:
buy_in = int(input_func("\nHow much would you like to buy in "
"for? Please choose a whole dollar amount between "
"$500 and $50000: $"))
break
except ValueError:
print "\nIntegers only, please!\n"
self._time.sleep(2)
while not 500 <= buy_in <= 50000:
while True:
try:
buy_in = int(input_func("Please enter a buy-in amount "
"between $500 and $50,000 only, please: $"))
break
except ValueError:
print "\nIntegers, only, please.\n"
self._time.sleep(2)
return buy_in
def bet(self, input_func=raw_input):
"""Acquires and returns bet size from the user.
Args:
input_func: Function to receive input from the user.
"""
while True:
try:
bet = int(input_func("\nHow much would you like to wager? Whole"
" dollar amounts between %s and %s only, "
"please: " % (
bankroll.MIN_BET, bankroll.MAX_BET)))
break
except ValueError:
print "\nInteger values only, please!\n"
self._time.sleep(2)
while not (bankroll.MIN_BET <= bet <= bankroll.MAX_BET):
while True:
try:
bet = int(input_func("Please enter your wager again. Only "
"whole dollar amounts between %s and "
"%s: " % (
bankroll.MIN_BET, bankroll.MAX_BET)))
break
except ValueError:
print "\n Integer values only, please!\n"
self._time.sleep(2)
return bet
def action(self, hand, input_func=raw_input):
"""Acquires and returns desired player action.
Args:
hand: The hand for which the action is being requested.
input_func: Function to receive input from the user.
"""
if hand.double_down_allowed() and hand.split_allowed():
allowed_actions = ['h', 'st', 'sp', 'd']
action = input_func("Would you like to [h]it, [st]and, [sp]lit, or "
"[d]ouble down? ")
while action not in allowed_actions:
action = input_func("Please choose your action from the "
"following options: 'h' to hit, 'st' to "
"stand, 'sp' to split, or 'd' to double "
": ")
if hand.double_down_allowed() and not hand.split_allowed():
allowed_actions = ['h', 'st', 'd']
action = input_func("Would you like to [h]it, [st]and, or [d]ouble "
"down? ")
while action not in allowed_actions:
action = input_func("Please choose your action from the "
"following options: 'h' to hit, 'st' to "
"stand, or 'd' to double down: ")
if not hand.double_down_allowed() and not hand.split_allowed():
allowed_actions = ['h', 'st']
action = input_func("Would you like to [h]it or [st]and? ")
while action not in allowed_actions:
action = input_func("Please choose your action from the "
"following options: 'h' to hit or 'st' to "
"stand. ")
return action
def play_another_round(self, bankroll_balance, input_func=raw_input):
"""Returns True if the player would like to continue playing.
Args:
bankroll_balance: Current bankroll balance.
input_func: Function to receive input from the user.
"""
print "\nAfter the last round, your current bankroll is $%s." % (
bankroll_balance)
keep_playing = input_func("\nWould you like to continue playing ([y]es "
"or [n]o)? ")
while keep_playing != 'y' and keep_playing != 'n':
keep_playing = input_func("\nPlease enter 'y' to continue playing, "
"or 'n' to quit: ")
if keep_playing == 'y':
return True
elif keep_playing == 'n':
return False
def rebuy(self, bankroll_balance, input_func=raw_input):
"""Returns True if player wants to rebuy, false otherwise.
Args:
bankroll_balance: Current bankroll balance.
input_func: Function to receive input from the user.
"""
rebuy = input_func("\nYour current bankroll is $%s. Would you like to "
"rebuy ([y]es or [n]o)? " % (bankroll_balance))
while rebuy != 'y' and rebuy != 'n':
rebuy = input_func("\nPlease enter 'y' if you would like to rebuy, "
"or 'n' if you would not: ")
if rebuy == 'y':
return True
elif rebuy == 'n':
return False
def rebuy_amount(self, input_func=raw_input):
"""Returns user-entered rebuy amount.
Args:
input_func: Function to receive input from the user.
"""
while True:
try:
rebuy_amount = int(input_func("\nHow much would you like to "
"rebuy for? Please enter a whole "
"dollar amount between $500 and "
" $50000: "))
break
except ValueError:
print "\nIntegers only, please."
while not 500 <= rebuy_amount <= 50000:
while True:
try:
rebuy_amount = int(input_func("\nPlease enter a rebuy amount "
"between $500 and $50,000 only, please: $"))
break
except ValueError:
print "\nIntegers, only, please."
self._time.sleep(2)
return rebuy_amount
def wait_for_enter(self, input_func=raw_input):
"""Prompts the player to hit Enter before the game continues.
Args:
input_func: Function to receive input from the user.
"""
input_func("\nPress Enter to continue.")
|
def find_swap(next, sorted_tail):
"""
return negative int index in sorted tail of thing to swap
"""
if len(sorted_tail) == 1:
return -1
i = -2
while abs(i) <= len(sorted_tail):
if next > sorted_tail[i]:
return i+1
i -= 1
def do_swap(head, sorted_tail, swap_neg_index):
"""return list final answer"""
assert(len(sorted_tail) >= abs(swap_neg_index))
temp = head[-1]
head[-1] = sorted_tail[swap_neg_index]
sorted_tail[swap_neg_index] = temp
assert(len(head)>0)
assert(len(sorted_tail)>0)
return head + sorted_tail
def bigger_is_greater(word):
sorted_tail = [word[-1]]
for i in range(len(word)-2,-1,-1):
next = word[i]
if next < sorted_tail[-1]:
swap_neg_index = find_swap(next, sorted_tail)
return ''.join(do_swap(word[:i+1], sorted_tail, swap_neg_index))
sorted_tail.append(next)
return "no answer"
num_lines = int(input().strip())
for l in range(num_lines):
word_as_list = list(input().strip())
print(bigger_is_greater(word_as_list))
|
def is_even(num):
if num % 2 == 0:
return True
else:
return False
def only_evens(lst):
new_lst = []
for n in lst:
if is_even(n):
new_lst.append(n)
return new_lst
print(only_evens([11, 20, 42, 97, 23, 10]))
|
# ---------------------------------------------------------------------------------------------
# Name: main.py
# Purpose: Uses the Nearest Neighbour class and read_write_TSP to find the tour and plots
# the tour using GraphWorld
# Programmers: Ishwar Agarwal(Driver) & Xhafer Rama(Navigator)
# Acknowledgement: Dr. Jan Pearce for the two opt pseudocode
# Created: 10/13/15
# ---------------------------------------------------------------------------------------------
from two_opt import TwoOpt
from GraphWorld import *
from read_write_TSP import TspRW
import time
def main():
time.clock()
object = TwoOpt() # create a two-opt object
read_write = TspRW() # create a read_write object
read_write.read_file(raw_input('Enter file to read from: ')) # reads all the coordinates of citties from an ASCII file
object.labels = read_write.labels # store the labels in a list
object.coordinates = read_write.coordinates # store the coordinates in this list
numRound = int(raw_input('Enter the number of random graphs you want to generate: '))
roundTimes = int(raw_input('Enter the number of times you want to swap edges: '))
for i in range(numRound):
object.generate_rand_graph() # generate a random graph
for i in range(roundTimes):
object.generate_rand_vertices() # randomly generate two indices which have no common connection
object.find_random_edge() # generate two random edges from the given indices
object.find_new_edge() # find the new edge if swap were to happen.
dx_oldtour = object.cal_distance_of_edge(object.edge1) + object.cal_distance_of_edge(object.edge2) # difference in cost before swapping using two-opt
dx_newtour = object.cal_distance_of_edge(object.new_edge1) + object.cal_distance_of_edge(object.new_edge2) # difference in cost after adding two edges.
if dx_newtour < dx_oldtour:
object.remove_edges()
object.add_edge_reversely()
if object.costOfBestTour > object.costOfTour:
bestTour = object.tour
bestTour_vertices = object.tour_vertices
object.costOfBestTour = object.costOfTour
# write the tour in .tour ASCII file
read_write.coordinates = []
read_write.labels = []
for i in bestTour_vertices:
read_write.coordinates.append(i.pos)
for i in bestTour_vertices:
read_write.labels.append(i.label)
read_write.write_file()
print 'Run time: ', time.clock()
# The following two lines allows to switch the layout of the graph displayed
# layout = CartesianLayout(bestTour)
layout = RandomLayout(bestTour)
# layout = CircleLayout(bestTour)
# draw the graph
gw = GraphWorld()
gw.show_graph(bestTour, layout)
gw.mainloop()
main()
|
class Entries:
"""Class for creating an entries dictonary"""
# Class initializer. It has 5 custom parameters, with the
# special `self` parameter that every method on a class
# needs as the first parameter.
def __init__(self, id, time, concept, entry, mood_id):
self.id = id
self.time = time
self.concept = concept
self.entry = entry
self.mood_id = mood_id
self.mood = None
|
'''
Title: 819. Most Common Word (Easy) https://leetcode.com/problems/most-common-word/
Runtime: 52 ms, faster than 8.96% of Python online submissions for Most Common Word.
Memory Usage: 11.9 MB, less than 5.05% of Python online submissions for Most Common Word.
Description:
Given a paragraph and a list of banned words,
return the most frequent word that is not in the list of banned words.
It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation.
Words in the paragraph are not case sensitive. The answer is in lowercase.
Example:
Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
'''
class Solution(object):
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
parse = ""
for index,i in enumerate(paragraph):
if ord(i) >= 65 and ord(i) <= 91:
parse += chr(ord(i) + 32)
if index < len(paragraph) - 1:
if not ((ord(paragraph[index+1]) >= 65 and ord(paragraph[index+1]) <= 91) or (ord(paragraph[index+1]) >= 97 and \
ord(paragraph[index+1]) <= 123)):
key = 1
elif ord(i) >= 97 and ord(i) <= 123:
parse += i
if index < len(paragraph) - 1:
if not ((ord(paragraph[index+1]) >= 65 and ord(paragraph[index+1]) <= 91) or (ord(paragraph[index+1]) >= 97 and \
ord(paragraph[index+1]) <= 123)):
key = 1
else:
if key:
parse += ' '
key = 0
dict = {}
for i in parse.split(' '):
if i in dict and i not in banned:
dict[i] += 1
elif i not in dict and i not in banned:
dict[i] = 1
m = max(dict.values())
for i in dict:
if dict[i] == m and len(i) > 0:
return i
|
'''
Title: 496. Next Greater Element I (Easy) https://leetcode.com/problems/next-greater-element-i/
Runtime: 80 ms, faster than 21.69% of Python online submissions for Next Greater Element I.
Memory Usage: 11.7 MB, less than 5.94% of Python online submissions for Next Greater Element I.
Description:
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2.
Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
Next Greater Number of a number x in nums1 is the first greater number to its right in nums2.
If it does not exist, output -1 for this number.
Example:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
'''
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
for index,i in enumerate(nums1):
flag = 0
for j in range(nums2.index(i),len(nums2)):
if nums2[j] > i:
flag = 1
nums1[index] = nums2[j]
break
if flag == 0:
nums1[index] = -1
return nums1
|
'''
Title: 292. Nim Game (Easy) https://leetcode.com/problems/nim-game/
Runtime: 20 ms, faster than 69.91% of Python online submissions for Nim Game.
Memory Usage: 11.7 MB, less than 5.36% of Python online submissions for Nim Game.
Description:
You are playing the following Nim Game with your friend: There is a heap of stones on the table,
each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner.
You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game.
Write a function to determine whether you can win the game given the number of stones in the heap.
Example:
Input: 4
Output: false
Explanation: If there are 4 stones in the heap, then you will never win the game;
No matter 1, 2, or 3 stones you remove, the last stone will always be
removed by your friend.
'''
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return not n % 4 == 0
|
'''
Title: 35. Search Insert Position (Easy) https://leetcode.com/problems/search-insert-position/
Runtime: 36 ms, faster than 93.09% of Python3 online submissions for Search Insert Position.
Memory Usage: 13.6 MB, less than 5.11% of Python3 online submissions for Search Insert Position.
Description:
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.
You may assume no duplicates in the array.
Example:
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for index,i in enumerate(nums):
if target - i in dict:
return [dict[target-i], index]
else:
dict[i] = index
|
'''
Title: 905. Sort Array By Parity (Easy) https://leetcode.com/problems/sort-array-by-parity/
Runtime: 68 ms, faster than 49.45% of Python online submissions for Sort Array By Parity.
Memory Usage: 12.5 MB, less than 5.22% of Python online submissions for Sort Array By Parity.
Description:
Given an array A of non-negative integers, return an array consisting of all the even elements of A,
followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
'''
class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
even = []
odd = []
for i in A:
if i%2 == 0:
even.append(i)
else:
odd.append(i)
return even+odd
|
'''
Title: 104. Maximum Depth of Binary Tree (Easy) https://leetcode.com/problems/maximum-depth-of-binary-tree/
Runtime: 48 ms, faster than 87.33% of Python3 online submissions for Maximum Depth of Binary Tree.
Memory Usage: 14.5 MB, less than 82.20% of Python3 online submissions for Maximum Depth of Binary Tree.
Description:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
depth = 0
if root:
thislevel = [root]
while thislevel:
depth += 1
nextlevel = []
for i in thislevel:
if i.left:
nextlevel.append(i.left)
if i.right:
nextlevel.append(i.right)
thislevel = nextlevel
return depth
|
'''
Title: 7. Reverse Integer (Easy) https://leetcode.com/problems/reverse-integer/
Runtime: 40 ms, faster than 99.91% of Python3 online submissions for Reverse Integer.
Memory Usage: 13.1 MB, less than 5.71% of Python3 online submissions for Reverse Integer.
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Example:
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
'''
class Solution:
def reverse(self, x: int) -> int:
output = ""
tmp = str(x)
if x < 0:
output += '-'
if tmp[len(tmp)-1] != 0:
for i in range(len(tmp)-1,0,-1):
output+=tmp[i]
if int(output) < pow(-2,31):
return 0
return int(output)
else:
output = tmp[::-1]
if int(output) > pow(2,31):
return 0
return int(output)
|
'''
Title: 217. Contains Duplicate (Easy) https://leetcode.com/problems/contains-duplicate/
Runtime: 108 ms, faster than 42.07% of Python online submissions for Contains Duplicate.
Memory Usage: 17.1 MB, less than 5.24% of Python online submissions for Contains Duplicate.
Description:
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Example:
Input: [1,2,3,1]
Output: true
Input: [1,2,3,4]
Output: false
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
'''
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return not len(nums) == len(list(set(nums)))
|
'''
Title: 283. Move Zeroes (Easy) https://leetcode.com/problems/move-zeroes/
Runtime: 40 ms, faster than 56.79% of Python online submissions for Move Zeroes.
Memory Usage: 12.8 MB, less than 5.06% of Python online submissions for Move Zeroes.
Description:
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.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
'''
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
output = [0 for i in range(len(nums))]
pos = 0
for i in range(len(nums)):
if nums[i] != 0:
output[pos] = nums[i]
pos += 1
for i in range(len(nums)):
nums[i] = output[i]
|
'''
Title: 671. Second Minimum Node In a Binary Tree (Easy) https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/
Runtime: 20 ms, faster than 74.81% of Python online submissions for Second Minimum Node In a Binary Tree.
Memory Usage: 11.5 MB, less than 6.06% of Python online submissions for Second Minimum Node In a Binary Tree.
Description:
Given a non-empty special binary tree consisting of nodes with the non-negative value,
where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes,
then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes'
value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def DFS(self, root, arr):
arr.append(root.val)
if root.left:
self.DFS(root.left, arr)
if root.right:
self.DFS(root.right, arr)
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
arr = []
if root:
self.DFS(root, arr)
arr.sort()
first = arr[0]
if len(arr) == 1:
return -1
for i in range(1,len(arr)):
if arr[i] > first:
return arr[i]
break
if i == len(arr) - 1:
return -1
|
'''
Title: 509. Fibonacci Number (Easy) https://leetcode.com/problems/fibonacci-number/
Runtime: 20 ms, faster than 78.99% of Python online submissions for Fibonacci Number.
Memory Usage: 11.8 MB, less than 5.25% of Python online submissions for Fibonacci Number.
Description:
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence,
such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
Example:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
'''
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
fib = {}
fib[0] = 0
fib[1] = 1
output = 0
for i in range(2,31):
fib[i] = fib[i-1] + fib[i-2]
return fib[N]
|
'''
Title: 637. Average of Levels in Binary Tree (Easy) https://leetcode.com/problems/average-of-levels-in-binary-tree/
Runtime: 60 ms, faster than 21.54% of Python online submissions for Average of Levels in Binary Tree.
Memory Usage: 16.5 MB, less than 5.81% of Python online submissions for Average of Levels in Binary Tree.
Description:
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
output = []
if root:
thislevel = [root]
while thislevel:
nextlevel = []
values = []
for i in thislevel:
values.append(i.val)
if i.left:
nextlevel.append(i.left)
if i.right:
nextlevel.append(i.right)
output.append(float(sum(values)) / len(values))
thislevel = nextlevel
return output
|
# a부터 b까지 정수의 합을 구하기(for문)위해 값 정렬
# print('a부터 b까지 정수의 합을 구합니다.')
# a = int(input('정수 a를 입력하세요.: '))
# b = int(input('정수 b를 입력하세요.: '))
# if a > b:
# a, b = b, a
# sum = 0
# for i in range(a, b + 1):
# sum += i
# print(f'{a}부터 {b}까지 정수의 합은 {sum}입니다.')
# +와 -를 번갈아가며 출력하기(내 코드)
# print('+와 -를 번갈아 출력합니다.')
# n = int(input('몇 개를 출력할까요? : '))
# for i in range(1,n + 1):
# if i % 2:
# print('+',end='')
# else:
# print('-',end='')
# print()
# +와 -를 번갈아가며 출력하기(교재 코드)
# print('+와 -를 번갈아 출력합니다.')
# n = int(input('몇 개를 출력할까요? : '))
# for _ in range(n // 2):
# print('+-',end='')
# if n % 2:
# print('+', end='')
# print()
# *를 n개 출력하되, w개마다 줄바꿈 하기
print('*를 출력합니다.')
n = int(input('몇 개를 출력할까요?: '))
w = int(input('몇 개마다 줄바꿈을 할까요?: '))
etc = 0
for _ in range(n // w):
print('*' * w)
if n % w:
etc = (n % w)
print('*' * etc)
print()
|
def selection_sort(arr):
smallest = arr[0]
smallest_pos = 0
for i in range(len(arr)):
for j in range(i, len(arr)):
if arr[j] < smallest:
smallest = arr[j]
smallest_pos = j
arr[i], arr[smallest_pos] = arr[smallest_pos], arr[i]
smallest = arr[i+1]
smallest_pos = i + 1
return arr
|
# from random import randrange
# class Pet():
# sounds="Meow"
# def __init__(self, name="kitty"):
# self.name=name
# self.hunger=randrange(10)
# self.boredom=randrange(10)
# self.sounds=self.sounds[]
# def clock_tick(self):
# self.boredom+=1
# self.hunger+=1
# def mood(self):
# if self.hunger<=5 and self.boredom<=6:
# return "happy"
# elif self.hunger>5 :
# return "hungry"
# else:
# return "bored"
# def __str__(self):
# state =" I am "+self.name+ "."
# state+="I am "+self.mood() + " ."
# return state
# def teach(self,word):
# self.sounds.append(word)
# self.boredom -=1
# def hi(self):
# print(self.sounds[])
# print("------------WELCOME TO TAMGOTCHI GAME------------")
# print("1. Adopt a pet [adopt <name>] \n 2. Feed the pet [feed name] \n 3.Teach the pet \n 4.Quit")
# x= int(input())
# if x==1:
# print("Enter the name of the pet ")
# name=input()
#
import sys
sys.setExecutionLimit(60000)
def whichone(petlist, name):
for pet in petlist:
if pet.name == name:
return pet
return None # no pet matched
def play():
animals = []
option = ""
base_prompt = """
Quit
Adopt <petname_with_no_spaces_please>
Greet <petname>
Teach <petname> <word>
Feed <petname>
Choice: """
feedback = ""
while True:
action = input(feedback + "\n" + base_prompt)
feedback = ""
words = action.split()
if len(words) > 0:
command = words[0]
else:
command = None
if command == "Quit":
print("Exiting...")
return
elif command == "Adopt" and len(words) > 1:
if whichone(animals, words[1]):
feedback += "You already have a pet with that name\n"
else:
animals.append(Pet(words[1]))
elif command == "Greet" and len(words) > 1:
pet = whichone(animals, words[1])
if not pet:
feedback += "I didn't recognize that pet name. Please try again.\n"
print()
else:
pet.hi()
elif command == "Teach" and len(words) > 2:
pet = whichone(animals, words[1])
if not pet:
feedback += "I didn't recognize that pet name. Please try again."
else:
pet.teach(words[2])
elif command == "Feed" and len(words) > 1:
pet = whichone(animals, words[1])
if not pet:
feedback += "I didn't recognize that pet name. Please try again."
else:
pet.feed()
else:
feedback+= "I didn't understand that. Please try again."
for pet in animals:
pet.clock_tick()
feedback += "\n" + pet.__str__()
play()
|
import pyglet
class Tag(object):
def __init__(self, text, font, color=(1,1,1,1)):
self.text=pyglet.font.Text(font, text, color=color,
halign="left", valign="bottom")
@property
def left(self):
return self.text.x
@property
def right(self):
return self.text.x+self.text.width
@property
def top(self):
return self.text.y+self.text.height
@property
def bottom(self):
return self.text.y
def setPos(self,position):
self.text.x=position[0]
self.text.y=position[1]
def collidesWith(self,tag):
if self.left < tag.right and self.right > tag.left and \
self.top > tag.bottom and self.bottom < tag.top:
return True
else:
return False
def draw(self):
self.text.draw()
|
# coding: utf-8
def find_min_index(number_list):
min_index = 0
min_value = number_list[min_index]
for i in range(1, len(number_list)):
if(number_list[i] < min_value):
min_index = i
min_value = number_list[min_index]
return min_index
question = [5, 3, 2, 8, 9, 0, 4, 1, 6, 7]
# sorting
for i in range(len(question)):
min_index = find_min_index(question[i:])
min_value = question[min_index + i]
question[min_index + i] = question[i]
question[i] = min_value
print(question)
|
import os.path
import fileinput
import sys
print("""
Divide Large CSV File in Python
- Pass # Of Rows per file
- Pass Main File Name
- Ctr+C to interrupt at anytime
""")
filesize = int(input("Enter # of Rows for each file (e.g. 150000):"))
if filesize > 150000 or filesize == 0 or filesize < 0:
sys.exit(f"\nError: Incorrect Filesize {filesize} entered.\n")
filename = str(input("Enter Filename (e.g. juldec2016.csv): "))
if os.path.isfile(filename) == False:
sys.exit(f"\nError: File {filename} Not Exist.\n")
fout = None
num_lines = sum(1 for line in open(filename))
print(f"Total # of Rows in {filename} = {num_lines}")
for (i, line) in enumerate(fileinput.FileInput(filename)):
if i % filesize == 0:
if fout: fout.close()
fout = open('output/output%d.csv' % (i/filesize), 'w')
num_lines = num_lines - filesize
print(f"Current Filesize = {num_lines} --> Writing {filesize} rows to output{int(i/filesize)}.csv")
fout.write(line)
fout.close()
|
def one (name):
return "Menin atym "+ name
def two (name):
return "my name is " + name
def caller (assign):
a= "Mirlan"
b= "Nurken"
c= "Suiun"
d = "Ainash"
return assign( a)
print ( caller(two) )
|
from function_save import save
def keluar(user,gadget,consumable,consumable_history,gadget_borrow_history,gadget_return_history): #exit() command. Menggunakan fungsi save().
print("Apakah Anda mau melakukan penyimpanan pada file yang sudah diubah? (y/n): ",end="")
choice=str(input())
if choice=="y" or choice=="Y":
save(user,gadget,consumable,consumable_history,gadget_borrow_history,gadget_return_history)
elif choice!="n" and choice!="N":
print("Masukan tidak valid")
keluar(user,gadget,consumable,consumable_history,gadget_borrow_history,gadget_return_history)
|
a = int(input("Students in Class1:"))
b = int(input("Students in Class2:"))
c = int(input("Students in Class3:"))
# Desks = x1,x2,x3
x1 = a / 2
if x1 % 2 == 0:
print(x1)
else:
print(round(x1))
x2 = b / 2
if x2 % 2 == 0:
print(x2)
else:
print(round(x2))
x3 = c / 2
if x3 % 2 == 0:
print(x3)
else:
print(round(x3))
result = x1 + x2 + x3
print(round(result))
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author: MSJ
# date: 2021/3/11
# desc:计算字符串或列表中每个字符出现的次数,并打印出现次数最多的字符
def calc_max_string(str):
# 将字符串转化成列表
str_list = list(str)
# 定义一个空字典,用来存储 字符: 出现次数
str_dict = {}
# 遍历列表(字符串)
for x in str_list:
# 如果该字符没有在字典中出现过,则赋值为1,否则在原来基础上+1
if str_dict.get(x) is None:
str_dict[x] = 1
else:
str_dict[x] = str_dict[x] + 1
# 输出 { 字符:出现次数 }
print(str_dict)
# 找出字典中的 max(values)
max_str = max(str_dict.values())
# 遍历字典
for k,v in str_dict.items():
# 如果 values = max,打印该字符及出现次数
if v == max_str:
print('出现次数最多的字符是:', k, ',一共出现了', v, '次')
else:
continue
if __name__ == '__main__':
calc_max_string('asdfghjkliiuytreqasdccvv')
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author: MSJ
# date: 2021/4/14
# desc:
#
# 影响因素:
# 1.
# 2.
# 检查点:
# 1.
# 测试用例:
# 0.
class Solution(object):
def minArray(self, s):
"""
:type numbers: List[int]
:rtype: int
"""
#numbers.sort()
dic = {}
for i in s:
if dic.get(i) is None:
dic[i] = 1
else:
dic[i] = dic[i] + 1
for k, v in dic.items():
if v == 1:
return k
return ' '
s = Solution()
r = s.minArray('leetcode')
print(r)
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author: MSJ
# date: 2021/3/11
# desc:给定一个字符串,判断字符串中的括号是否成对
def is_valid(str):
# 新建括号匹配字典
brackets = { ')': '(', ']': '[', '}': '{' }
# 左/右括号
left_brackets = brackets.values()
right_brackets = brackets.keys()
# 空数组(模拟空栈)
stack = []
# 遍历字符串
for x in str:
# 如果是左括号,进栈
if x in left_brackets:
stack.append(x)
# 如果是右括号,判断栈是否为空&&栈顶元素和右括号是否匹配,匹配左括号出栈,否则括号不匹配,直接 return
elif x in right_brackets:
if stack and (stack[-1] == brackets[x]):
stack.pop(-1)
else:
return False
# 右括号遍历完,判断左括号是否为空,如果不为空则证明括号匹配
if not stack:
return True
else:
return False
if __name__ == '__main__':
r1 = is_valid('{ccc[dddkkkk(ook)]}')
print(r1)
r2 = is_valid('}hhgj{(hhgj)[hhgj]')
print(r2)
r3 = is_valid('{anh[ddd](djjjjkkk)}}')
print(r3)
r4 = is_valid('{anh[ddd]((djjjjkkk)}')
print(r4)
r5 = is_valid('[')
print(r5)
|
def is_unique_string(str):
dict = {}
for s in str:
if s not in dict.keys():
dict[s] = True
else:
return False
return True
print(is_unique_string("say"))
def sort_string(s):
return ''.join(sorted(s))
def check_permutation(x, y):
if len(x) != len(y):
return False
return sort_string(x).upper() == sort_string(y).upper()
print(check_permutation('as', 'sA'))
def change_space(str):
result = ""
for s in str:
if s == ' ':
result += '%20'
else:
result += s
return result
print(change_space("s s"))
def check_palindrom(str):
j = len(str) - 1
for s in str:
if s != str[j]:
return False
j -= 1
return True
print(check_palindrom("anna"))
def check_replacement(str1, str2):
if len(str1) != len(str2):
return False
j = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
j += 1
if j > 1:
return False
return True
def check_insert_removed(str1, str2):
if len(str1) == len(str2):
return False
if len(str1) < len(str2):
long = str2
short = str1
else:
long = str1
short = str2
idx_long = 0
idx_short = 0
j = 0
while idx_long < len(long) and idx_short < len(short):
if short[idx_short] != long[idx_long]:
j += 1
else:
idx_short += 1
idx_long += 1
if j > 1:
return False
return True
def check_oneway(str1, str2):
if check_replacement(str1, str2):
return True
elif check_insert_removed(str1, str2):
return True
return False
print(check_oneway("pale", "bales"))
def compress_string(string):
i = 0
result = ""
is_comppresed = False
while i < len(string):
result += string[i]
k = 1
while len(string) - 1 > i and string[i + 1] == string[i]:
k += 1
i += 1
is_comppresed = True
result += str(k)
i += 1
if not is_comppresed:
return string
return result
print(compress_string("aabcd"))
def matrix_zero(data):
dict_zero = {}
for i in range(len(data)):
for j in range(len(data[i])):
if data[i][j] == 0:
dict_zero[i] = j
""""
for y, x in dict_zero.items():
for i in data[y]:
data[y][i] = 0
"""""
cache = {}
for i in range(len(data)):
for j in range(len(data[i])):
if (i, j) in cache.keys():
break
if i in dict_zero.keys():
data[i][j] = 0
cache[(i, j)] = True
if j in dict_zero.values():
data[i][j]= 0
cache[(i, j)] = True
data = [
[1,0,2],
[1,2,3],
[1,3,2,5],
[4,2,1,4,0]
]
for i in range(len(data)):
for j in range(len(data[i])):
print(data[i][j], end=" ")
print()
def is_palindrome_permutation(string):
char_count = {}
valid = True
for s in string:
if s in char_count.keys():
char_count[s] =+ 1
else:
char_count[s] = 1
if char_count[s] % 2 == 1:
valid = False
else:
valid = True
return valid
print(is_palindrome_permutation("TactCoa"))
def rotate(matrix):
if len(matrix) == 0 or len(matrix) != len(matrix[0]):
return False
n = len(matrix)
length = n - 1
for layer in range(n // 2):
last = length - layer
for i in range(layer, last):
top = matrix[layer][i]
matrix[layer][i] = matrix[last - i][layer]
matrix[last - i][layer] = matrix[last][last - i]
matrix[last][last - i] = matrix[layer + i][last]
matrix[layer + i][last] = top
data = [
[1,4,5,34],
[10,2,7,42],
[11,3,4,31],
[10,5,12,43]
]
rotate(data)
for i in range(len(data)):
for j in range(len(data[i])):
print(data[i][j], end=" ")
print()
|
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
map = {}
res = []
for i in range(len(strs)):
if map.get(i, False): continue
temp = [strs[i]]
map[i] = True
for j in range(i + 1, len(strs)):
if not map.get(j, False) and self.is_valid(strs[i], strs[j]):
map[j] = True
temp.append(strs[j])
res.append(temp)
return res
def is_valid(self, str1, str2):
if len(str1) != len(str2):
return False
map = {}
for s in str1: map[s] = map.get(s, 0) + 1
for s in str2:
if map.get(s, 0) == 0:
return False
else:
map[s] -= 1
for v in map.values():
if v != 0: return False
return True
print(Solution().groupAnagrams(["", ""]))
|
def lengthOfLongestSubstring(s):
has = ""
result = 0
temp = 0
i = 0
j = 1
while i < len(s):
if s[i] in has:
has = s[j:i]
temp = len(has)
j += 1
else:
temp += 1
has += s[i]
if temp > result:
result = temp
i += 1
return result
print(lengthOfLongestSubstring("abcabcbb"))
|
# A version of linear regression using tensorflow.
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
# We emphasize that this is the stupidest possible neural network-- 1 input, 1 output, with 2 weights.
# I mean, this is linear regression after all...
# First, we need a function to generate a dataset to play with.
def generate_data(m, b, noise, num_data, seed=0):
"""
INPUT
m = slope of data
b = bias of data
noise = variance of Gaussian error terms
num_data = number of data points
seed = random seed
OUTPUT
X = list of input data values
y = list of output data values
"""
np.random.seed(seed)
X = np.random.uniform(0, 1, num_data)
gaussian_noise = np.random.randn(num_data) * noise
y = m * X + b + gaussian_noise
return X, y
## Now we set up our data
num_data = 30
noise = 0.3
X_data, y_data = generate_data(3, 2, noise, num_data)
# Hyperparameters
learning_rate = 0.5
num_episodes = 100
# We create a basic computational graph for our linear regression.
X = tf.placeholder("float")
W = tf.get_variable(name="weight", initializer=tf.constant(np.random.randn()))
b = tf.get_variable(name="bias", initializer=tf.constant(np.random.randn()))
y_guess = X * W + b
y = tf.placeholder("float")
# Loss
loss = tf.reduce_mean(tf.pow(y_guess - y, 2))
# Optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# Initialize variables
init = tf.global_variables_initializer()
## Run model
sess = tf.Session()
sess.run(init)
for i in range(num_episodes):
sess.run(optimizer, feed_dict={X: X_data, y: y_data})
if i % 10 == 0:
episode_loss = sess.run(loss, feed_dict={X: X_data, y: y_data})
print("Episode ", i, " ==> Loss: ", episode_loss,
" w: ", sess.run(W), " b: ", sess.run(b))
final_w = sess.run(W)
final_b = sess.run(b)
plt.scatter(X_data, y_data)
x_plot = np.linspace(0,1,30)
plt.plot(x_plot, 3*x_plot+2, '-g', label="real line")
plt.plot(x_plot, final_w*x_plot+final_b, '-r', label="predicted line")
plt.legend()
plt.show()
|
'''
6. Implement a function to determine if a string has all unique characters.
What if you cannot use additional structures?
'''
# HAHAHA! This one was too easy.
def hasAllUniqueCharacters(s):
return ''.join(sorted(set(s))) == ''.join(sorted(s))
print(hasAllUniqueCharacters('Computer Programmer Numerical Control'))
print(hasAllUniqueCharacters('Film Or Tape Librarian'))
print(hasAllUniqueCharacters('Hotel Food Counter Worker'))
print(hasAllUniqueCharacters('ZYXWVUTSRQPONMLKJIHGFEDCBA'))
print(hasAllUniqueCharacters('zyxwvutsrqponmlkjihgfedcbaA'))
|
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
def locally_weighted(x, y):
neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(x, y)
print("Enter X value : ")
x_i = int(input())
print("Enter Y value : ")
y_i = int(input())
predict = [x_i, y_i]
if neigh.predict([predict]) == 0:
print("The sample "+str(predict)+" is of negative class")
else:
print("The sample "+str(predict)+" is of positive class")
def distance_weighted(x, y):
neigh = KNeighborsClassifier(n_neighbors=3, weights = 'distance')
neigh.fit(x, y)
print("Enter new sample to predict : ")
print("Enter X value : ")
x_i = int(input())
print("Enter Y value : ")
y_i = int(input())
predict = [x_i, y_i]
if neigh.predict([predict]) == 0:
print("The sample "+str(predict)+" is of negative class")
else:
print("The sample "+str(predict)+" is of positive class")
data = pd.read_csv('knngraph.csv')
x = data.values[:,0:2]
y = data.values[:,2]
print(x)
print(y)
print("----MENU-----")
print("1 - Locally weighted ")
print("2 - Distance weighted ")
print("Enter your choice : ")
user_input = int(input())
if user_input == 1:
locally_weighted(x, y)
else:
distance_weighted(x, y)
|
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
df = pd.read_csv('salaries.csv')
company_le = LabelEncoder()
job_le = LabelEncoder()
degree_le = LabelEncoder()
df['company'] = company_le.fit_transform(df['company'])
df['job'] = job_le.fit_transform(df['job'])
df['degree'] = degree_le.fit_transform(df['degree'])
x = df.drop('salary_more_then_100k', 1).values
y = df['salary_more_then_100k'].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
model = DecisionTreeClassifier()
model.fit(x_train, y_train)
print('Accuracy : ', model.score(x_test, y_test))
|
# Example 1, do not modify!
import pandas as pd
import matplotlib.pyplot as plt
netflix=pd.read_csv("netflix_titles.csv")
netflix_by_year=netflix.sort_values("release_year")
print(netflix_by_year.isnull().sum())
M_night=netflix[netflix["director"]== "M. Night Shyamalan"]
print(M_night)
movies=netflix[netflix["type"]=="Movie"]
print(movies.isnull().sum())
Full_movies=movies.fillna("unknown")
print(Full_movies.info())
Full_movies.to_csv("Full_netflix-movies.csv")
|
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
# 遍历全部可能,把有重复的剃掉
total = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if (i!=j)and(j!=k)and(k!=i):
print(i,j,k)
total +=1
print(total)
# 简便方法 用itertools中的permutations即可
import itertools
sum_3 = 0
a = [1,2,3,4]
for i in itertools.permutations(a,3):
a =list(i)
b = [str(i) for i in a]
c = ''.join(b)
print(c)
sum_3 +=1
print(sum_3)
|
import argparse
import sys
import itertools
import pprint
def read_points(filename):
"""
The read_points method reads opens the file with the points and returns them in a
list filled with lists of couples with coordinates.
input: -filename: string name of the file with the points
output: -points: list with couples of coordinates [[X1,Y1],...,[Xn,Yn]]
"""
points = []
with open(filename) as points_file:
for line in points_file:
content = line.split(" ")
point = [int(content[0]), int(content[1].rstrip())]
points.append(point)
return points
parser = argparse.ArgumentParser()
parser.add_argument(
"points_file", help="Name of the file which contains the crossword")
parser.add_argument("-f", "--setCovering", action="store_true",
help="Use -f if you want to utilise the set covering method")
parser.add_argument("-g", "--parallel", action="store_true",
help="Use -g if you want the lines to be parallel with the x & y axis")
args = parser.parse_args()
# Saving names in variables so args.filename is not executed many times in case needed
points_file = args.points_file
set_covering = args.setCovering
parallel = args.parallel
points = read_points(points_file)
# Global list with all the possible lines
S = []
def line_exists(point1, point2):
"""
The line_exists method checks if two points are already being used in a line,
in the set S. If those two points exist in a line, this means that a line with
those points already appears in S. This happens because two points can adress one
and only one line.
input: -point1: list with the coordinates of point1
-point2: list with the coordinates of point2
output: -exists: boolean True --> line exists | False --> line does not exists
"""
exists = False
for line in S:
count = 0
for point in line:
if point == point1 or point == point2:
count += 1
if count == 2:
exists = True
break
return exists
def find_S():
"""
The find_S method calculates all the possible lines that can pass through all
the given points. It is used for the set covering method and it inputs all these
lines in a global list called S.
In order to check for all possible lines find_s:
1. takes two different points
2. adds them in a line (finding the line with a (slope), b(intercept), or x = b)
3. checks if other points match the line
4. adds the possible lines on the S list
"""
for point1 in points:
second_starting_point = points.index(point1) + 1
for point2_index in range(second_starting_point, len(points)):
point2 = points[point2_index]
if not line_exists(point1, point2):
line = [point1, point2]
third_starting_point = point2_index + 1
if point1 != point2:
"""
The following lines check wether a can be calculate and it does not
involve division with zero. If x1 and x2 match that means that the
line follows the x = x1 = x2 pattern
"""
if point1[0] != point2[0]:
a = (point2[1] - point1[1])/(point2[0] - point1[0])
b = point1[1] - a * point1[0]
for point3_index in range(third_starting_point, len(points)):
point3 = points[point3_index]
fits = point3[1] == a*point3[0] + b
if point3 != point1 and point3 != point2 and fits:
line.append(point3)
S.append(line)
else:
x = point1[0]
for point3_index in range(third_starting_point, len(points)):
point3 = points[point3_index]
fits = point3[0] == x
if point3 != point1 and point3 != point2 and fits:
line.append(points[point3_index])
S.append(line)
def find_parallel_S():
"""
The find_parallel_S function retrieves all the lines that cover the points. If a point (X, Y)
not have a match to define a line, then the point (X+1, Y) is used as its match. The method simply
checks for each point if it has a match with same x or y coordinates and adds them to the listx or listy
accordingly.
"""
for point1 in points:
x = point1[0]
y = point1[1]
listx = [point1]
listy = [point1]
for point2 in points:
if point1 != point2:
if point2[0] == x:
listx.append(point2)
elif point2[1] == y:
listy.append(point2)
if len(listx) != 1:
S.append(listx)
if len(listy) != 1:
S.append(listy)
if len(listx) == 1 and len(listy) == 1:
S.append([point1, [point1[0] + 1, point1[1]]])
def set_covering_method(is_parallel):
"""
The set_covering function calculates the solution for the set covering method
for all types of lines. It uses an algorithm with the following steps:
Until no solution is found
1. Find all possible subsets of S for every possible number of lines
2. For every possible subset check if:
a. solution covers number of points (makes less loops)
b. solution covers all points
3. If solution is found end the process
input: -is_parallel: boolean True --> S contains parallel points | False --> otherwise
output: -solution: list with the solution of the problem
"""
found = False
i = 1
while not found:
solution = []
all_solutions = itertools.combinations(S, i)
for possible_solution in all_solutions:
used = [False] * len(points)
sum_of_points = 0
"""
If the sum of points is les than 18 this means the solution is not found
for sure, so move on (break).
"""
for lines in possible_solution:
sum_of_points += len(lines)
if sum_of_points >= len(points):
for line in possible_solution:
for point in line:
if point in points:
used[points.index(point)] = True
if used.count(True) == len(used):
solution = possible_solution
found = True
else:
if not is_parallel:
break
i += 1
return solution
def greedy_method():
"""
The greedy_method function implements the greedy algorithm. In more depth,
the algorithm finds every time the line that covers the most uncovered points
and adds it to the solution. This loop ends when all the points are covered.
output: -solution: list with the solution of the greedy algorithm
"""
used = [False] * len(points)
solution = [S[0]]
for point in S[0]:
used[points.index(point)] = True
while used.count(True) != len(used):
max_covered = 0
i = 0
max_index = -1
for line in S:
covered = 0
for point in line:
if point in points:
if not used[points.index(point)]:
covered += 1
if covered > max_covered:
max_covered = covered
max_index = i
i += 1
solution.append(S[max_index])
for point in S[max_index]:
if point in points:
used[points.index(point)] = True
return solution
def final_sort(unsorted_list):
"""
The final_sort method sorts the solution appropriately just for the case
of -g. In order to sort first by reverse length and then by the first element
we input the unsorted solution (unsorted list) and for every group of lines
with the same list, we sort them and then append them to the sorted list.
input: -unsorted_lsit: list with the unsorted solution
output: -sorted_list: list with the sorted solution
"""
line_length = len(unsorted_list)
lines_by_length = []
sorted_list = []
while line_length > 0:
for line in unsorted_list:
if len(line) == line_length:
lines_by_length.append(
sorted(line, key=lambda solution: solution[1]))
line_length -= 1
if lines_by_length:
lines_by_length = sorted(lines_by_length)
for line in lines_by_length:
sorted_list.append(line)
lines_by_length.clear()
return sorted_list
solution = []
if set_covering:
if parallel:
#
# Set covering with parallel lines solution
#
find_parallel_S()
S = sorted(S, key=len)
S.reverse()
i = 0
for line in S:
S[i] = sorted(S[i])
i += 1
unique_S = []
for line in S:
if not line in unique_S:
unique_S.append(line)
S = unique_S
solution = set_covering_method(parallel)
solution = final_sort(solution)
else:
#
# Set covering withOUT parallel lines solution
#
find_S()
# sort S from largest covering lines to smaller for faster results
S = sorted(S, key=len)
S.reverse()
solution = set_covering_method(parallel)
solution = sorted(solution, key=len)
solution.reverse()
else:
if parallel:
#
# greedy with parallel lines solution
#
find_parallel_S()
S = sorted(S, key=len)
S.reverse()
i = 0
for line in S:
S[i] = sorted(S[i])
i += 1
unique_S = []
for line in S:
if not line in unique_S:
unique_S.append(line)
S = unique_S
solution = greedy_method()
solution = final_sort(solution)
else:
#
# greedy withOUT parallel lines solution
#
find_S()
# sort S from largest covering lines to smaller for faster results
S = sorted(S, key=len)
S.reverse()
solution = greedy_method()
solution = sorted(solution, key=len)
solution.reverse()
print()
for line in solution:
for point in line:
print('(' + str(point[0]) + ',', str(point[1]) + ')', end=' ')
print()
|
class Inventory(object):
"""
Representation of a inventory
"""
def __init__(self):
"""
Initialize inventory
"""
self.inventory = {}
def add(self, item):
"""
Adds an item to the inventory, and checks
that we do not ecounter any KeyErrors
"""
try:
self.inventory.update(item)
except KeyError:
print("Invalid command")
def remove(self, item_name):
"""
Removes an item form the inventory, and checks
that we do not ecounter any KeyErrors
"""
try:
self.inventory.pop(item_name)
except KeyError:
print("Invalid command")
def __str__(self):
for key, value in self.inventory.items():
return(f"{key}:{value}")
|
"""Stores details of movies and displays them on a website"""
import fresh_tomatoes
import media
def main():
"""Creates six Movie objects, initialises the objects alongside the title,
storyline, poster image, video trailer """
shock_treatment = media.Movie("Shock Treatment",
"80's game show goes off the rails",
"http://bit.ly/2xjpDUR",
"https://www.youtube.com/watch?v=z-xRAvVWp5w",
)
rocky = media.Movie("Rocky",
"The classic movie about an underdog boxer",
"http://bit.ly/2jIdIuA",
"https://www.youtube.com/watch?v=Wif1EzGQ9Fk",
)
hercules = media.Movie("Hercules",
"Son of Zeus becomes a god",
"http://bit.ly/2xk6L7R",
"https://www.youtube.com/watch?v=yIAvF8hFEYM",
)
arrival = media.Movie("Arrival",
"Aliens show up on earth on strange ships",
"http://bit.ly/2wEAcOp",
"https://www.youtube.com/watch?v=tFMo3UJ4B4g",
)
hocus_pocus = media.Movie("Hocus Pocus",
"Witches wake up after thousands of years in salem",
"http://bit.ly/2eVrLrA",
"https://www.youtube.com/watch?v=2UUMsInka2s",
)
space_jam = media.Movie("Space Jam",
"Aliens show up to ball against Michael Jordan",
"http://bit.ly/2xk18X3",
"https://www.youtube.com/watch?v=oKNy-MWjkcU",
)
"""Stores movie objects in a list"""
movies = [shock_treatment, rocky, hercules, arrival, hocus_pocus, space_jam]
"""Opens the movie website in the browser"""
fresh_tomatoes.open_movies_page(movies)
main()
|
# ------------------------------------------------------------------
# QuadrupleList object
#
# Manages the quadruple list.
# ------------------------------------------------------------------
class QuadrupleList:
def __init__(self):
self.list = []
def add(self, quadruple):
self.list.append(quadruple)
def lookup(self, index):
return self.list[index]
def clear(self):
self.list.clear()
def size(self):
return len(self.list)
def __str__(self):
description = ''
for i, val in enumerate(self.list):
number = ("%-2d" % (i))
description = description + number + ". " + str(val)
if i != len(self.list) - 1:
description = description + '\n'
return description
|
# ------------------------------------------------------------------
# Stack object
# ------------------------------------------------------------------
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
if len(self.items) > 0:
return self.items[len(self.items)-1]
else:
return None
def size(self):
return len(self.items)
def __str__(self):
description = ''
for i, val in enumerate(self.items):
description = description + str(val) + ' '
return description
|
def area(base, height):
'''Compute he are of a triangle with the given base and height'''
'''Raises value error if base or height or both are negative'''
if base < 0 or height < 0:
raise ValueError('Base and height must be positive. \ Was given base: {}, height {}'.format(base, height))
area = base * height / 2
return area
|
def get_count(word):
lower = word.lower()
final = ""
vowel_counts = {}
for vowel in "aeiou":
count = lower.count(vowel)
vowel_counts[vowel]=count
for key in vowel_counts:
if vowel_counts[key]:
result = ''.join(str(vowel_counts[key])+str(key))
final = final+result
if final:
return final
else:
pass
def main():
result = get_count("qwtyp")
print(result)
if result == "3e1i2o":
print("Correct")
main()
|
# read and prepare n, m, and p
n = int(input("Number of jobs: "))
m = int(input("Number of machines: "))
pStr = input("Processing times ")
p = pStr.split(" ")
for i in range(n):
p[i] = int(p[i])
# machine loads and job assignment
loads = [0]*m
assignment = [0]*n
# in iteration j, assign job j to the least loaded machine
for j in range(n):
# find the least loaded nachine
leastLoadMachine = 0
leastLoad = loads[0]
for i in range(1, m):
if loads[i] < leastLoad:
leastLoadMachine = i
leastLoad = loads[i]
# schedule a job
loads[leastLoadMachine] += p[j]
assignment[j] = leastLoadMachine + 1
# to check the process
print(str(p[j]) + ": " + str(loads))
# the result
print("Job assignment: " + str(assignment))
print("machine loads: " + str(loads))
|
#https://www.w3resource.com/python-exercises/python-basic-exercises.php
#RM 03/22/2018 2022 create a basics.py non Python os, file programs.
#1. Write a Python program to print the following string in a specific format: Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output :
"""
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
"""
print("""
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
""")
#3. Write a Python program to display the current date and time.
from datetime import datetime
print(datetime.now()) #print 2017-11-10 20:12:11.688408
currentdate = datetime.now()
print(currentdate.month) #print 11
print(currentdate.year) #print 2017
print(currentdate.day) #print 20
print(currentdate.month,"/",currentdate.day,"/",currentdate.year)
print(currentdate.strftime("%m/%d/%Y")) #print 11/20/2017
#4. Write a Python program which accepts the radius of a circle from the user and compute the area.
from math import pi
def areacircle(radius):
return pi*(radius**2)
print(areacircle(1.1)) #print 3.8013271108436504
#5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. RM: skip input().
firstname = "Raymond"
lastname = "Mar"
name = firstname+" "+lastname
print(name[::-1]) #print raM dnomyaR
#6. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
sampledata = 3, 5, 7, 23
print(sampledata) #print (3, 5, 7, 23)
# sampledatalist = []
# for eachsampledata in sampledata:
# sampledatalist.append(str(eachsampledata))
# print(sampledatalist) #print ['3', '5', '7', '23']
print(tuple(map(str,sampledata))) #print ('3', '5', '7', '23')
print(list(map(str,sampledata))) #print ['3', '5', '7', '23']
#8. Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
print(color_list[0]) #print Red
print(color_list[-1]) #print Black
#9. Write a Python program to display the examination schedule. (extract the date from exam_st_date exam_st_date = (11, 12, 2014) Sample Output : The examination will start from : 11 / 12 / 2014
examstartdate = (11, 12, 2014)
print(type(examstartdate)) #print <class 'tuple'>
print(type(examstartdate[0])) #print <class 'int'>
print("The examination will start from:", examstartdate[0],"/",examstartdate[1],"/",examstartdate[2]) #print The examination will start from: 11 / 12 / 2014
# printexamestartdate = datetime.strptime(examstartdate,"%m/%d/%Y")
# print(printexamestartdate) #error TypeError: strptime() argument 1 must be str, not tuple
#10. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. Sample value of n is 5. Expected Result : 615.
n = 5
print(n+(n**2)+(n**3)) #print 155
a = 5
n1 = int( "%s" % a )
print(n1) #print 5
n2 = int( "%s%s" % (a,a) )
print(n2) #print 55
n3 = int( "%s%s%s" % (a,a,a) )
print(n3) #print 555
print(n1+n2+n3) #print 615
#12. Write a Python program to print the calendar of a given month and year. Note: Use 'calendar' module.
import calendar
c = calendar.TextCalendar(calendar.SUNDAY) #The example configures TextCalendar to start weeks on Sunday, following the American convention. The default is to use the European convention of starting a week on Monday.
c.prmonth(2017, 11) #print the Nov 2017 calendar
#13. Write a Python program to print the following here document. Go to the editor Sample string :
"""
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
"""
print("""
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
""")
#14. Write a Python program to calculate number of days between two dates. Sample dates : (2014, 7, 2), (2014, 7, 11) Expected output : 9 days
import datetime
firstdate = datetime.date(2014, 7, 2)
secondate = datetime.date(2014, 7, 11)
print((secondate - firstdate).days) #print 9
#15. Write a Python program to get the volume of a sphere with radius 6.
from math import pi
def volumesphere(radius):
return (4/3)*pi*(radius**3)
print(volumesphere(6)) #print 904.7786842338603
#16. Write a Python program to get the difference between a given number and 17, if the [given] number is greater than 17 return double the absolute difference.
givennumber = 14
constant = 17
if givennumber <= constant:
print(constant - givennumber) #print 3
else:
print((givennumber - constant)*2)
#17. Write a Python program to test whether a number is within 100 of 1000 or 2000.
givennumber = 999
if givennumber >=900 or givennumber <=1100:
print(givennumber,"Given number is within 1000 +/- 100") #print 999 Given number is within 1000 +/- 100
elif givennumber >=1900 or givennumber <=2100:
print(givennumber,"Given number is within 2000 +/- 100")
else:
print("Given number is not within 1000 +/100 or 2000 +/-100")
#18. Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
def sumthreenumbers(a, b, c):
if a == b and b ==c:
return(3*(a+b+c))
else:
return a + b + c
print(sumthreenumbers(5, 10, 15)) #print 30
print(sumthreenumbers(50, 50, 50)) #print 450
#19. Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
def newstring(newstring):
if newstring[0] == "I" and newstring[1] == "s":
print(newstring)
else:
print("Is"+newstring)
newstring("Isokay") #retrn Isokay
newstring("okayis") #retrn Isokayis
#20. Write a Python program to get a string which is n (non-negative integer) copies of a given string.
n = 5
givenstring = "The quick brown fox jumped over the lazy dog"
print(givenstring*5) #print The quick brown fox jumped over the lazy dogThe quick brown fox jumped over the lazy dogThe quick brown fox jumped over the lazy dogThe quick brown fox jumped over the lazy dogThe quick brown fox jumped over the lazy dog
#21. Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
def evenorodd(n):
if n % 2 == 0:
print(n,"is even")
else:
print(n,"is odd")
evenorodd(10) #return 10 is even
evenorodd(17) #return 17 is odd
#22. Write a Python program to count the number 4 in a given list.
import random
numberlist = []
count = 1
while count < 11:
numberlist.append(random.randint(1,5))
count +=1
print(numberlist)
count = 0
for eachnumberlist in numberlist:
if eachnumberlist == 4:
count += 1
print("There are",count,"four's in the list.")
#23. Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2
def copy2characters(string,n):
if len(string) < 2:
return string*n
else:
return (string[0]+string[1])*n
print(copy2characters("Parker Brothers",5)) #print PaPaPaPaPa
print(copy2characters("S",15)) #print SSSSSSSSSSSSSSS
#24. Write a Python program to test whether a passed letter is a vowel or not.
vowel = ["a","e","i","o","u"]
def lettercheck(letter):
if letter in vowel:
print(letter+" is a vowel")
else:
print(letter+" is a consonant")
lettercheck("e") #return e is a vowel
lettercheck("t") #return t is a consonant
#25. Write a Python program to check whether a specified value is contained in a group of values. Test Data : 3 -> [1, 5, 8, 3] : True -1 -> [1, 5, 8, 3] : False
def valuecheck(n):
testdata = [1, 5, 8, 3]
if n in testdata:
return True
else:
return False
print(valuecheck(3)) #print True
print(valuecheck(-1)) #print False
#26. Write a Python program to create a histogram from a given list of integers.
import matplotlib.pyplot as plt
xpopulationages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
ybins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
plt.hist(xpopulationages,ybins, label="labelhistogram", histtype="bar", rwidth=1.0)
plt.xlabel("xlabel")
plt.ylabel("ylabel")
plt.title("Title")
plt.legend()
#plt.show() #comment out plt.show() to avoid displaying histogram
#27. Write a Python program to concatenate all elements in a list into a string and return it.
def liststring(liststring):
print(" ".join(liststring))
print(", ".join(liststring))
wordlist = ["Let","It","Snow","Jingle","Bells","Silver","Spirit","Christmas"]
liststring(wordlist) #print Let It Snow Jingle Bells Silver Spirit Christmas\n Let, It, Snow, Jingle, Bells, Silver, Spirit, Christmas
#28. Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
def evennumber237(listnumber):
numbersfinal = []
for eachlistnumber in listnumber:
if eachlistnumber == 237:
break
elif eachlistnumber % 2 == 0:
numbersfinal.append(eachlistnumber)
print(numbersfinal)
numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 100000, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 743, 527]
evennumber237(numbers) #return [386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918, 100000]
#29. Write a Python program to print out a set containing all the colors from colorlist1 which are not present in colorlist2.
"""
Test Data :
colorlist1 = set(["White", "Black", "Red"])
colorlist2 = set(["Red", "Green"])
Expected Output : {'Black', 'White'}
"""
colorlist1 = set(["White", "Black", "Red"])
colorlist2 = set(["Red", "Green"])
print(colorlist1.union(colorlist2)) #print {'Green', 'Red', 'White', 'Black'}
print(colorlist1.intersection(colorlist2)) #print {'Red'}
print(colorlist1.difference(colorlist2)) #print {'Black', 'White'}
print(colorlist2.difference(colorlist1)) #print {'Green'}
#source: https://www.python-course.eu/sets_frozensets.php
"""
RM: long way
colorlist1 = list(colorlist1)
colorlist2 = list(colorlist2)
print(colorlist1) #print ['Red', 'Black', 'White']
print(colorlist2) #print ['Green', 'Red']
colorlist3 = []
for eachcolorlist1 in colorlist1:
if eachcolorlist1 not in colorlist2:
colorlist3.append(eachcolorlist1)
print(set(colorlist3)) #print {'Black', 'White'}
"""
#30. Write a Python program that will accept the base and height of a triangle and compute the area
def areatriangle(base, height):
return base*height*0.5
# baseheight = input("Enter the base and height of a triangle separated by a space ")
# baseheight = baseheight.split(" ")
# print(areatriangle(float(baseheight[0]),float(baseheight[1])))
print(areatriangle(5,4.5)) #print 11.25
#31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers. RM: function from Barry Brown
def gcd(a, b):
"""Return the greatest common divisor of a and b. gcd(10, 5) is 5, (14, 21) is 7, (80, 30) is 10, (7, 15) is 1, (9, 0) is 9 """
if b == 0:
return a
else:
return gcd(b, a % b) #recursion
print(gcd(20,10)) #return 10
#32. Write a Python program to get the least common multiple (LCM) of two positive integers. Official solution: https://www.w3resource.com/python-exercises/python-basic-exercise-32.php
def isprime(n):
if n == 1:
return False #1 is not a prime number
for d in range(2, n):
if n % d == 0:
return False
return True
#number1 and number2 are the two positive integers
number1 = 3000
number2 = 45550
prime1 = isprime(number1)
prime2 = isprime(number2)
#a pair of prime numbers the LCM is their product
if prime1 == True and prime2 == True:
print(number1*number2,"is the lowest common multiple")
else:
set1 = set()
set2 = set()
eachnumber = 1
while True:
try:
#create two sets of number1 multiples and number2 multiples
set1.add(eachnumber*number1)
set2.add(eachnumber*number2)
min(set1.intersection(set2))
#no value for min(set1.intersection(set2)) add 1 to eachnumber and continue addting multiples to the two sets
except ValueError:
eachnumber +=1
continue
else:
print(min(set1.intersection(set2)),"is the lowest common multiple",number1,"and",number2)
break
#33. Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
def sumthreeintegers(x,y,z):
"""Returns the sum of three different integers. Press q to exit."""
if x<0 or y<0 or z<0:
positivenumbers = abs(x)+abs(y)+abs(z)
print("I converted all numbers to positive:",positivenumbers)
elif (x==y) or (y==z) or (x==z):
print(0)
else:
print(x+y+z)
def sumthreeintegers2(x,y,z):
"""Returns the sum of three different integers. Press q to exit."""
if x<0 or y<0 or z<0:
positivenumbers = abs(x)+abs(y)+abs(z)
convert = "I converted all numbers to positive:",str(positivenumbers)
return " ".join(convert)
elif (x==y) or (y==z) or (x==z):
return 0
else:
return x+y+z
#three given integers. I modified problem to positive integers only.
x=10
y=-15
z=100
sumthreeintegers(x,y,z)
print(sumthreeintegers2(x,y,z))
#RM: reminder help for a function.
#print(help(sumthreeintegers)) #print Help on function sumthreeintegers in module __main__: sumthreeintegers(x, y, z) Returns the sum of three different integers. Press q to exit.
#34. Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
def sumtwointegers(x,y):
if ((x+y) >=15) and ((x+y) <=20):
return 20
else:
return x+y
#two given integers
print(sumtwointegers(20,12))
print(sumtwointegers(4,12))
print(sumtwointegers(12,4))
print(sumtwointegers(20,-3))
#35. Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5.
def givenintegers(a,b):
if (a == b) or (abs(a)-abs(b)==5) or (abs(b)-abs(a)==5):
return True
else:
return False
print(givenintegers(505,-500))
print(givenintegers(1000,1000))
print(givenintegers(-33,10))
#36. Write a Python program to add two objects if both objects are an integer type.
object1 = 5
object2 = 6
if isinstance(object1, int) is True and isinstance(object2, int) is True:
print(object1 + object2)
if type(object1) is int and type(object2) is int:
print(object1 + object2)
#37. Write a Python program to display your details like name, age, address in three different lines.
description = ["Name","Age","Address"]
yourdetails = input("Enter your first name, age, address separated by a ! ")
yourdetails = yourdetails.split("!")
n=0
for eachyourdetails in yourdetails:
print(description[n]+": "+eachyourdetails)
n+=1
#38. Write a Python program to solve (x + y) * (x + y). Test Data : x = 4, y = 3 Expected Output : (4 + 3) ^ 2) = 49
def xy(x,y,power):
print(pow((x+y),power))
xy(4,3,2)
#39. Write a Python program to compute the future value of a specified principal amount, rate of interest, and a number of years. Test Data : amt = 10000, int = 3.5, years = 7 Expected Output : 12722.79
#RM: Compounded Annual Interest. Interest rate applied to each year's cumulative account balance. FV=I*((1+R)^T) or future value = principal*((1+interest rate per year)^number of years)) #https://www.investopedia.com/terms/f/futurevalue.asp
def futurevalue(principal, interestrate, years):
return (principal*((1+interestrate)**years))
print(round(futurevalue(10000,.035,7),2))
#40. Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
#We use the Pythagoras Theorem to derive a formula for finding the distance between two points in 2- and 3- dimensional space. Let P = (x1,y1) and Q = (x2,y2) be two points on the Cartesian plane. Then from the Pythagoras Theorem we find that the distance between P and Q is PQ = (((x2-x1)**2)+((y2-y1)**2))**.5
#http://mathsfirst.massey.ac.nz/Al gebra/PythagorasTheorem/pythapp.htm
import matplotlib.pyplot as plt
from math import sqrt
def distance(x1,y1,x2,y2):
return sqrt(((x2-x1)**2)+((y2-y1)**2))
firstpoint = input("Enter x and y for first point separated by a space ")
secondpoint = input("Enter x and y for second point separated by a space ")
firstpoint = firstpoint.split(" ")
secondpoint = secondpoint.split(" ")
x1=float(firstpoint[0])
y1=float(firstpoint[1])
x2=float(secondpoint[0])
y2=float(secondpoint[1])
p=[x1,y1]
q=[x2,y2]
plt.plot(p,q, label="firstlineforlegend")
plt.xlabel("xlabel")
plt.ylabel("ylabel")
plt.title("title\ntitlenewline")
plt.legend()
plt.show()
print(distance(x1,y1,x2,y2))
#48. Write a Python program to parse a string to Float or Integer.
word = "255"
print(int(word)) #print 255
print(float(word)) #print 255.0
#50. Write a Python program to print without newline or space.
wordlist = "abcdef"
for eachwordlist in wordlist:
print(eachwordlist, end="") #print abcdef in one line
print("\n")
#57. Write a program to get execution time for a Python method.
import time
print(time.time()) #prints number of seconds since Jan 1, 1970
startime = time.time() #prints number of seconds since Jan 1, 1970
#python code
endtime = time.time()
print((endtime-startime),"seconds")
print((round(endtime-startime)),"seconds")
import time
startime = time.clock()
#python code
endtime = time.clock()
print((endtime-startime),"seconds")
print((round(endtime-startime)),"seconds")
import time
startime = time.time()
#python code
endtime = time.time()
timetaken = endtime - startime # time_taken is in seconds
hours, rest = divmod(timetaken,3600)
minutes, seconds = divmod(rest, 60)
print(timetaken)
print(hours, rest, minutes, seconds)
#58. Write a python program to sum of the first n positive integers.
n = 100
sumn = 0
for eachnumber in range(1,n+1):
sumn = sumn + eachnumber
print(sumn)
#59. Write a Python program to convert height (in feet and inches) to centimeters.
height = input("Enter height in feet and inches separate feet and inches with a space. I convert to centimeters. ")
heightsplit = height.split()
print(int(heightsplit[0])*30.48+(int(heightsplit[1])*2.54))
#60. Write a Python program to calculate the hypotenuse of a right angled triangle.
legs = input("Enter the two legs of the right triangle separate the two lengths with a space. I calculate the hypotenuse. ")
legssplit = legs.split()
print(legssplit)
print(int(legssplit[0])**2+(int(legssplit[1])**2))
#61. Write a Python program to convert the distance (in feet) to inches, yards, and miles.
import math
feettomiles = 0.0001894
feettoinches = 12
feettoyards = 0.333
milestoinches = 63360
milestofeet = 5280.0
distancefeet = float(input("Enter the distance in feet "))
print(distancefeet*feettoyards,"yards")
print(distancefeet*feettoinches,"inches")
print(distancefeet*feettomiles,"miles")
#Bonus answer. Convert decimal miles to feet.
miles = distancefeet * feettomiles
math.modf(miles)
print(math.modf(miles))
decimalmiles, integermiles = math.modf(miles)
print(integermiles,"miles")
if 0 < decimalmiles < 1.0000:
print(round(decimalmiles*milestofeet,4),"feet")
else:
pass
#Another way separate math.modf() tuple
# modftuple = math.modf(miles)
# print(modftuple[0])
# print(modftuple[1])
#62. Write a Python program to convert all units of time into seconds.
inputtime = input("Enter the hours and minutes separated by a space ")
inputtimelist = inputtime.split()
print(int(inputtimelist[0])*60*60+int(inputtimelist[1])*60,"seconds")
#65. Write a Python program to convert seconds to day, hour, minutes and seconds. RM: used sample solution
time = float(input("Input time in seconds: "))
day = time // (24 * 3600)
time = time % (24 * 3600)
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
print("d:h:m:s-> %d:%d:%d:%d" % (day, hour, minutes, seconds))
#66. Write a Python program to calculate body mass index.
weight = int(input("Enter weight in pounds "))
height = input("Enter height in feet and inches separated by a space ")
height = height.split(" ")
height = (int(height[0])*12)+(int(height[1]))
bodymassindex = (weight/height**2)*703
print("Your body mass index is",round(bodymassindex,2))
#67. Write a Python program to convert pressure in kilopascals to pounds per square inch, a millimeter of mercury (mmHg) and atmosphere pressure.
#68. Write a Python program to calculate the sum of the digits in an integer.
integerinput = 123456789
integerinputsum = 0
for eachintegerinput in str(integerinput):
integerinputsum = integerinputsum + int(eachintegerinput)
print(integerinputsum)
#69. Write a Python program to sort three integers without using conditional statements and loops.
threeintegers = input("Enter three integers separated by a space ")
threeintegers = threeintegers.split(" ")
threeintegers = list(map(int,threeintegers)) #convert list string to list integers
threeintegers.sort()
print(str(threeintegers).strip("[]")) #extract integers out of list to string with commas
#72. Write a Python program to get the details of math module.
import math
print(dir(math))
#73. Write a Python program to calculate midpoints of a line.
def midpoint(x1,y1,x2,y2):
answer = (round(((x1+x2)/2),2),round(((y1+y2)/2),2))
print(answer)
firstpoint = input("Enter x and y for first point separated by a space ")
secondpoint = input("Enter x and y for second point separated by a space ")
firstpoint = firstpoint.split(" ")
secondpoint = secondpoint.split(" ")
x1=float(firstpoint[0])
y1=float(firstpoint[1])
x2=float(secondpoint[0])
y2=float(secondpoint[1])
midpoint(x1,y1,x2,y2)
#74. Write a Python program to hash a word.
#first python code is sample solution
soundex=[0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2]
print(len(soundex))
word=input("Input the word be hashed: ")
word=word.upper()
coded=word[0]
for a in word[1:len(word)]:
i=65-ord(a)
coded=coded+str(soundex[i])
print("The coded word is: "+coded)
#Source: https://www.pythoncentral.io/hashing-strings-with-python/
import hashlib
print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)
hash_object = hashlib.sha1(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig) #print 0a4d55a8d778e5022fab701977c5d840bbc486d0
hash_object = hashlib.sha224(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig) #print c4890faffdb0105d991a461e668e276685401b02eab1ef4372795047
#78. Write a Python program to find the available built-in modules.
#RM: used sample solution.
import sys
print(sys.builtin_module_names) #print ('_ast', '_bisect', '_codecs', '_collections', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha512', '_signal', '_socket', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zipimport', 'zlib')
import math
print(dir(math))
import select
print(dir(select))
import pwd
print(dir(pwd))
#81. Write a Python program to concatenate N strings.
def liststring(liststring):
print(" ".join(liststring))
userinput = ""
stringconcatenate = []
while userinput != "q":
userinput = str(input("Enter a string to concatenate. Type q to quit. "))
if userinput == "q":
break
stringconcatenate.append(userinput)
liststring(stringconcatenate)
#82. Write a Python program to calculate the sum over a container.
import random
numberslist = []
count = random.randint(1,101)
for i in range(1,count):
addnumber = random.randint(1,101)
numberslist.append(addnumber)
print(numberslist)
print(sum(numberslist))
#83. Write a Python program to test if a certain number is greater than all numbers of a list.
import random
def greaterallinlist(testcertainnumber):
#create number list
numberslist = []
count = random.randint(5,11)
for i in range(1,count):
addnumber = random.randint(1,51)
numberslist.append(addnumber)
numberslist.sort()
print(numberslist)
#check testcertainnumber greater than all numbers in number list
for j in range(len(numberslist)-1,-1,-1):
print(numberslist[j])
if testcertainnumber > numberslist[j]:
print("testcertainnumber "+str(testcertainnumber)+" is greater than all numbers in list")
break
else:
print("testcertainnumber "+str(testcertainnumber)+" is not greater than all numbers in list")
break
greaterallinlist(40)
#84. Write a Python program to count the number occurrence of a specific character in a string.
stringinput = "The quick brown fox jumped over the lazy dog"
characterinput = "e"
counter = 0
for eachstringinput in stringinput:
if eachstringinput == characterinput:
counter += 1
print(counter) #print 4 RM: yes there are four e's
#86. Write a Python program to get the ASCII value of a character.
character = "A"
print(ord(character)) #print 65
asciinumber = 65
print(chr(asciinumber)) #print A
character = "@"
print(ord(character)) #print 65
asciinumber = 64
print(chr(asciinumber)) #print @
#88. Given variables x=30 and y=20, write a Python program to print t "30+20=50".
x = 30
y = 20
print("%s+%s=50"%(x,y)) #print 30+20=50
#89. Write a Python program to perform an action if a condition is true. Given a variable name, if the value is 1, display the string "First day of a Month!" and do nothing if the value is not equal.
variablename = 1
if variablename == 1:
print("First day of a Month!")
else:
pass
#91. Write a Python program to swap two variables.
variable1 = "abc"
variable2 = "def"
print(variable1) #print abc
print(variable2) #print def
variable3 = variable2
variable2 = variable1
variable1 = variable3
print(variable1) #print def
print(variable2) #print abc
#92. Write a Python program to define a string containing special characters in various forms. RM: copied solution. I didn't understand the question.
print("\#{'}${\"}@/")
print("\#{'}${"'"'"}@/")
print(r"""\#{'}${"}@/""")
print('\#{\'}${"}@/')
print('\#{'"'"'}${"}@/')
print(r'''\#{'}${"}@/''')
#95. Write a Python program to check if a string is numeric.
stringcheck = 55
print(type(stringcheck))
if type(stringcheck) is str:
print("String is string")
elif type(stringcheck) is int:
print("String is integer")
else:
print("String is something else. Float?")
#solution
#stringcheck2 = 55
stringcheck2 = "a55"
try:
i = float(stringcheck2)
except (ValueError, TypeError):
print("Not a number")
#98. Write a Python program to get the system time.
import datetime
print(datetime.datetime.now().time()) #print 19:55:29.995253
print(datetime.datetime.today()) #print 2018-03-02 19:55:29.995320
#109. Write a Python program to check if a number is positive, negative or zero.
def check(n):
if n == 0:
print("zero")
elif n > 0:
print("positive")
else:
print("negative")
check(0) #print zero
check(0.000001) #print positive
check(-0.000001) #print negative
#110. Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.
listnumbers = [15,30,100,151,5000,4500,79,81,697,1236879]
list15 = []
def divisible15(n):
for eachn in n:
if eachn % 15 == 0:
list15.append(eachn)
divisible15(listnumbers)
print(list15) #print [15, 30, 4500]
#112. Write a Python program to remove the first item from a specified list.
thelist = ["apple","orange","grape","tangerine"]
thelist.pop(0)
print(thelist)
#113. Write a Python program to input a number, if it is not a number generate an error message.
#RM: solution is integers
#Source: https://www.tutorialspoint.com/python/python_strings.htm
pretenduserinput = "5000000"
if pretenduserinput.isdigit() == True:
print("It's a number")
try:
#userinput = int(input("Enter a number "))
userinput = int("a$")
except ValueError:
print("You didn't enter a number")
else:
print(userinput,"is a number")
#114. Write a Python program to filter the positive numbers from a list.
wantpositivenumbers = [-987,-963,992,545,82,-556,649,-342,402,-606,-762,-59,-401,-297]
gotpositivenumbers = []
for eachwantpositivenumbers in wantpositivenumbers:
if eachwantpositivenumbers > 0:
gotpositivenumbers.append(eachwantpositivenumbers)
print(gotpositivenumbers) #print [992, 545, 82, 649, 402]
print(list(map(lambda x: x>0,wantpositivenumbers))) #print [False, False, True, True, True, False, True, False, True, False, False, False, False, False]
print(list(filter(lambda x: x>0,wantpositivenumbers))) #print [992, 545, 82, 649, 402]
#115. Write a Python program to compute the product of a list of integers (without using for loop).
from functools import reduce
productlist = [9,6,10,5,10,4,1,8,1,6,1,8,2,1]
print(reduce(lambda x,y: x*y,productlist)) #print 82944000
#import numpy as np
#print(np.prod(np.array(productlist))) #takes longer
#118. Write a Python program to create a bytearray from a list. RM: I don'tunderstand. Copied solution.
nums = [10, 20, 56, 35, 17, 99]
# Create bytearray from list of integers.
values = bytearray(nums)
for x in values: print(x)
#119. Write a Python program to display a floating number in specified numbers.
floatingnumber = 1123.5678
specifieddigits = 2
print(round(floatingnumber,specifieddigits)) #print 1123.57
print("{0:.2f}".format(floatingnumber)) #print 1123.57
stringfloatingnumber = str(floatingnumber)
decimalindex = stringfloatingnumber.find(".")
print(stringfloatingnumber[0:decimalindex+specifieddigits+1]) #print 1123.56
#120. Write a Python program to format a specified string to limit the number of characters to 6.
formatstring = "the quickbrown fox jumped over the lazy dog"
print(formatstring[0:6]) #print the qu
#121. Write a Python program to determine if variable is defined or not.
#error message below SyntaxError: invalid syntax
# try:
# definedvariable = ""
# except SyntaxError:
# print("definedvariable is not defined")
# else:
# print(definedvariable)
#RM: solution
try:
definedvariable
except NameError:
print("definedvariable is not defined") #print the except
else:
print("definedvariable is defined"+definedvariable)
#122. Write a Python program to empty a variable without destroying it. RM: copied solution
n = 20
d = {"x":200}
l = [1,3,5]
t= (5,7,8)
print(type(n)()) #print 0
print(type(d)()) #print {}
print(type(l)()) #print []
print(type(t)()) #print ()
#123. Write a Python program to determine the largest and smallest integers, longs, floats. RM: Python 3x use integers for longs.
def maxmin(inputlist):
print(max(inputlist))
print(min(inputlist))
integerslist = [1,2,3,4,5,6,7,8,9,10]
maxmin(integerslist) #return 10\n 1
floatslist = [1.2,5.5,6.7,6.9,5.75]
maxmin(floatslist) #return 6.9\n 1.2
#124. Write a Python program to check if multiple variables have the same value.
x=1
y=1
z=1
if x==y==z:
print("x y z multiple variables have the same value.")
#125. Write a Python program to sum of all counts in a collections? RM: What are collections? Answer is a module import collections. https://pymotw.com/3/collections/counter.html I used collections for Project Euler #39 Integer Right Triangles
import collections
numberlist = [2,2,4,6,6,8,6,10,4]
print(sum(numberlist)) #print 48
print(collections.Counter(numberlist)) #print Counter({6: 3, 2: 2, 4: 2, 8: 1, 10: 1})
print(sum(collections.Counter(numberlist).values())) #print 9. 9 is correct. We want the sum of the counts, not sum of the numbers in numberlist.
#126. Write a Python program to get the actual module object for a given object. RM: copied solution
from inspect import getmodule
from math import sqrt
print(getmodule(sqrt)) #print <module 'math' (built-in)>
#127. Write a Python program to check if an integer fits in 64 bits. RM: copied solution
int_val = 30
if int_val.bit_length() <= 63:
print((-2 ** 63).bit_length()) #print 64
print((2 ** 63).bit_length()) #print 64
#128. Write a Python program to check if lowercase letters exist in a string.
astring = "THE QUICK BROWN FOX JUMPEd OVeR THE LAZY DOG"
for eachastring in astring:
if eachastring == " ":
continue
lowercase = eachastring.lower()
if eachastring == lowercase:
print("There is a lowercase letter "+eachastring) #print There is a lowercase letter d\n There is a lowercase letter e
#129. Write a Python program to add leading zeroes to a string.
astring = "THE QUICK BROWN FOX JUMPEd OVeR THE LAZY DOG"
azero = "0"
numberofzeros = 5
print((azero*numberofzeros)+astring) #print 00000THE QUICK BROWN FOX JUMPEd OVeR THE LAZY DOG
#130. Write a Python program to use double quotes to display strings.
astring = "THE QUICK BROWN FOX JUMPEd OVeR THE LAZY DOG"
doublequotes = "\""
print(doublequotes+astring+doublequotes) #print "THE QUICK BROWN FOX JUMPEd OVeR THE LAZY DOG"
#131. Write a Python program to split a variable length string into variables. RM: https://stackoverflow.com/questions/19300174/python-assign-each-element-of-a-list-to-a-separate-variable says not a good idea. In other words, don't create dynamic variables. Another opinion https://stackoverflow.com/questions/20688324/python-assign-values-to-list-elements-in-loop
var_list = ['a', 'b', 'c']
x, y, z = (var_list + [None] * 3)[:3]
print(x, y, z) #print a b c
print(x) #print a
print(y) #print b
print(z) #print c
var_list2 = [100, 20.25]
x, y = (var_list2 + [None] * 2)[:2]
print(x, y) #print 100 20.25
print(x) #print 100
print(y) #print 20.25
#133. Write a Python program to calculate the time runs (difference between start and current time) of a program.
import time
startime = time.time()
endtime = time.time()
print((endtime-startime),"seconds")
print((round(endtime-startime)),"seconds")
#also
from timeit import default_timer
start = default_timer()
print(default_timer()-start)
print(round(default_timer()-start),"seconds")
#134. Write a Python program to input two integers in a single line.
twointegers = input("Enter two integers ")
print(twointegers,end="")
#RM: official solution doesn't work on 3.5; however, user input correct
x, y = [int(x) for x in input("numbers: ").split()]
print("The value of x & y are: ",x,y)
#135. Write a Python program to print a variable without spaces between values. Sample value: x=30 Expected output: Value of x is "30"
x=30
print("Value of x is \""+str(x)+"\"") #print Value of x is "30"
print("Value of x is ""\""+str(x)+"\"") #print Value of x is "30"
#RM: Official solution
x = 30
print('Value of x is "{}"'.format(x))
#137. Write a Python program to extract single key-value pair of a dictionary in variables.
stocks = {"GOOG": 434,"AAPL": 325,"FB": 54,"AMZN": 623,"F": 32,"MSFT": 549,}
for key, value in stocks.items():
print(key, value) #print AMZN 623\n FB 54\n GOOG 434\n MSFT 549\n AAPL 325\n F 32
#138. Write a Python program to convert true to 1 and false to 0.
#RM: Official solution
numbertrue = True
numberfalse = False
print(int(numbertrue))
print(int(numberfalse))
#140. Write a Python program to convert an integer to binary keep leading zeros. Sample data : 50. Expected output : 00001100, 0000001100
integerconvert = 50
print(bin(integerconvert)) #print 0b110011
print("{0:b}".format(integerconvert)) #print 110010
print("{0:010b}".format(integerconvert)) #print 0000110010
print("{0:012b}".format(integerconvert)) #print 000000110010
#141. Write a python program to convert decimal to hexadecimal. Go to the editor Sample decimal number: 30, 4. Expected output: 1e, 04.
print(hex(30)) #print 0x1e
print("{0:x}".format(30)) #print 1e
print(hex(4)) #print 0x4
print("{0:x}".format(4)) #print 4
print(hex(15)) #print 0xf
print("{0:x}".format(15)) #print f
#144. Write a Python program to check if variable is of integer or string.
stringvariable = "paper"
print(type(stringvariable)) #print class 'str'>
integervariable = 55
print(type(integervariable)) #print class 'int'>
#147. Write a Python function to check whether a number is divisible by another number. Accept two integers values form the user.
def quotientzero(dividend, divisor):
if dividend % divisor == 0:
print(dividend,"is divisible by",divisor)
else:
print(dividend,"is not divisible by",str(divisor)+". The quotent is %.2f." % (dividend/divisor))
division = input("Enter the dividend and the divisor separated by a space. Dividend is the number to be divided. Divisor is the number by. e.g. 20/5 20 is the dividend and 5 is the divisor to get the quotient 4. ")
divisionnumbers = division.split()
quotientzero(int(divisionnumbers[0]),int(divisionnumbers[1]))
#148. Write a Python function to find the maximum and minimum numbers from a sequence of numbers. Note: Do not use built-in functions.
inputsequence = input("Enter integers separated by a space ")
inputsequencelist = inputsequence.split()
resultsinteger = list(map(int,inputsequencelist))
print(resultsinteger)
maximum = 0
minimum = 0
for eachnumber in resultsinteger:
if eachnumber > 0:
maximum = eachnumber
if eachnumber < 0:
minimum = eachnumber
print(maximum)
print(minimum)
#149. Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number.
def sumcube(positiveinteger):
sumcube = 0
for eachnumber in range(1,positiveinteger):
sumcube = sumcube + pow(eachnumber,3)
print(sumcube)
sumcube(12)
#150. Write a Python function to find a distinct pair of numbers whose product is odd from a sequence of integer values.
from random import randint
from itertools import combinations
start = randint(1,50)
sequencelength = randint(5,25)
sequencelist = list(range(start,start+sequencelength))
print(sequencelist)
for combopairs in combinations(sequencelist, 2):
if combopairs[0]*combopairs[1] % 2 != 0:
print((combopairs[0]*combopairs[1]),(combopairs))
|
help()
#help() #1. run help(). See help> 2. Type a python command; e.g. print. Information displayed. Press page up and page down. 3. Type q to quit. 4. Type ctrl+c to quit. Perhaps create a help.py file to run help() only?
# Welcome to Python 3.5's help utility!
# If this is your first time using Python, you should definitely check out
# the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
# Enter the name of any module, keyword, or topic to get help on writing
# Python programs and using Python modules. To quit this help utility and
# return to the interpreter, just type "quit".
# To get a list of available modules, keywords, symbols, or topics, type
# "modules", "keywords", "symbols", or "topics". Each module also comes
# with a one-line summary of what it does; to list the modules whose name
# or summary contain a given string such as "spam", type "modules spam".
#72. Write a Python program to get the details of math module.
# import math
# print(dir(math))
#78. Write a Python program to find the available built-in modules.
#RM: used sample solution.
#import sys
#print(sys.builtin_module_names) #print ('_ast', '_bisect', '_codecs', '_collections', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha512', '_signal', '_socket', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zipimport', 'zlib')
# import math
# print(dir(math))
# import select
# print(dir(select))
# import pwd
# print(dir(pwd))
|
import os
import re
import sys
import pprint
search = raw_input("Enter FileName to search: ")
List = []
fcount=0
var = re.compile(search,re.IGNORECASE)
rootdir = raw_input("Enter where to search: (To search in present directory leave as it is)")
if(rootdir==""):
rootdir='.'
for root, dirs, files in os.walk(rootdir, topdown=True):
for name in files:
count=0
m = var.search(name)
if m:
dest=os.path.join(root,name)
count=1
print('Found at : '+dest[1:])
fcount+=1
if count==0:
for name in dirs:
m = var.search(name)
if m:
dest=os.path.join(root,name)
count=1
print('Found at : '+dest[1:])
fcount+=1
print('Total Number of Files found : '+str(fcount))
|
def twoNumberSum(array, targetSum):
for i in range(len(array) - 1):
firstNumber = array[i]
for j in range(i + 1,len(array)):
secondNumber = array[j]
if firstNumber + secondNumber == targetSum:
return [firstNumber,secondNumber]
return []
|
var1 = 1+1*2
var2 = (1+1)*2
print(str(var1) + ' ' + str(var2))
#Isso ocorre porque o parenteses muda a ordem que as contas são realizadas, iniciando para o grau mais adentro para mais para fora,
# enquanto a outra segue a ordem de preferencia matemática padrão
|
def work(a,b,c):
su = a + b + c
pr = a * b * c
return su, pr
a = int(input("Введите число a: "))
b = int(input("Введите число b: "))
c = int(input("Введите число c: "))
su, pr = work(a,b,c)
print("Сумма введенных чисел: ", su)
print("Произведение введеных чисел: ", pr)
|
class demoClass:
"""demo class"""
name = "lance"
age = 0
def __init__(self, name):
self.name = name
age = 10
def demo(self):
print "demo" + self.name + str(self.age)
|
class Time(object):
"""this will tell the time"""
t=Time()
t.hour=10
t.minutes=20
t.seconds=30
def print_time(t):
print("%.2d:%.2d:%.2d" % (t.hour,t.minutes,t.seconds))
print_time(t)
|
import math
class Point(object):
"""this is class for point"""
point_a = Point()
point_b = Point()
point_a.x, point_a.y = 2.0, 2.0
point_b.x, point_b.y = 5.0, 3.0
def distance(point_a, point_b):
axisx = point_b.x - point_a.x
axisy = point_b.y - point_a.y
return math.sqrt(axisx ** 2 + axisy ** 2)
print(distance(point_a,point_b))
|
# -*- coding: utf-8 -*-
# IF/ELSE: TREE WITH TRUE/FALSE BRANCHES
age = 20
if age >= 18:
print('Your age is {0}'.format(age))
print('You are an adult!')
age = 3
if age >= 18:
print('Your age is {0}.'.format(age))
print('You are an adult.')
elif age >= 10:
print('Your age is {0}.'.format(age))
print('You are a teenager.')
else:
print('Your age is {0}.'.format(age))
print('You are a child.')
# if x: pass
# When x is neither void, nor have the value of FALSE/0, then it's true.
x = ''
if x:
print('There\'s a normal value stored in \'x\'.')
else:
print('The value stored in \'x\' is abnormal.')
# INPUT: the value picked by input() method will be stored as a string.
# You need to force covert the string to a target type accordingly.
# yob = input('You birth in:\n')
# # if yob <2000:
# # print('You are younger than 18 yrs old.\n')
# # else:
# # print('You are elder than 18 yrs old.\n')
# #
# # Traceback (most recent call last):
# # File "C:/Users/Kevin-Office/IdeaProjects/Python101/04_basicPython/conditionJudgement.py", line 32, in <module>
# # if yob <2000:
# # TypeError: '<' not supported between instances of 'str' and 'int'
yob = input('You birth in:\n')
if int(yob) <2000:
print('You are elder than 18 yrs old.\n')
else:
print('You are younger than 18 yrs old.\n')
# 练习
# 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
#
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
# 用if-elif判断并打印结果:
#
# # -*- coding: utf-8 -*-
#
# height = 1.75
# weight = 80.5
# bmi = ???
# if ???:
# pass
# -*- coding: utf-8 -*-
height = 1.75
weight = 80.5
bmi = weight / (height * height)
if bmi < 18.5:
print('Your BMI is {0}. You are too skinny.\n'.format(bmi))
elif bmi <= 25:
print('Your BMI is {0}. Your weight is normal.\n'.format(bmi))
elif bmi <= 28:
print('Your BMI is {0}. You are overweight.\n'.format(bmi))
elif bmi <= 32:
print('Your BMI is {0}. You are fat.\n'.format(bmi))
elif bmi > 32:
print('Your BMI is {0}. You are too fat.\n'.format(bmi))
|
### https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import cmath
import time
# From stokes parameters, looking to create the ellipse and then animate it on a raspPi
#to then be used for the GUI once we start getting real time # data.
# start = time.time()
def polarization_ellipse(S):
#set individual stokes parameters from stokes vector
S0,S1,S2,S3 = S[0],S[1],S[2],S[3]
#solve for psi, the angle from the x axis of the ellipse
if S1 == 0:
psi = np.pi/4
else:
psi = 0.5*np.arctan(S2/S1)
#define ellipse parameters from stokes vectors
a=np.sqrt(0.5*(S0+np.sqrt(S1**2+S2**2)))
b=np.sqrt(0.5*(S0-np.sqrt(S1**2+S2**2)))
ba = b/a
rot = np.matrix([[np.cos(psi),-1*np.sin(psi)],
[np.sin(psi),np.cos(psi)]])
x1,x2,y1,y2 = [],[],[],[]
#create an x array for plotting ellipse y values
x = np.linspace(-a, a, 200)
# print(a)
for x in x:
Y1 = ba*np.sqrt(a**2-x**2)
#relection about the x-axis
Y2 = -Y1
# Y2 = -ba*np.sqrt(a**2-x**2)
#rotate the ellipse by psi
XY1 = np.matrix([[x],
[Y1]])
XY2 = np.matrix([[x],
[Y2]])
y1.append(float((rot*XY1)[1]))
x1.append(float((rot*XY1)[0]))
y2.append(float((rot*XY2)[1]))
x2.append(float((rot*XY2)[0]))
#x2,y2 reversed in order so that there is continuity in the ellipse (no line through the middle)
x=x1+x2[::-1]
y=y1+y2[::-1]
return x,y
fig = plt.figure(figsize = (10,10))
ax = plt.axes(xlim=(-1.0, 1.0), ylim=(-1.0, 1.0))
ax.set_xlabel('Ex')
ax.set_ylabel('Ey')
ax.set_title('Polarization Ellipse')
plt.grid()
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
#later, iterate through S instead of phi
def animate(phi):
xanim = []
yanim = []
S = [1,0,np.cos(phi),np.sin(phi)]
xanim,yanim = polarization_ellipse(S)
line.set_data(xanim,yanim)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=np.linspace(1, 2*np.pi, 800), interval=1, blit=True)
plt.show()
|
def setbits(n):
count=0
while(n>0):
n=n&(n-1)
count+=1
return count
for _ in range(int(input())):
n = int(input())
res=0
for i in range(n+1):
res+=setbits(i)
print(res)
|
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 44
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, whose sum and difference are
pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
"""
# Imports
import time
# Global variables
# Lamda functions
pent = lambda n: (n*(3*n-1))/2
# Functions
# Main functions
def main():
for i in range(1,10):
print(i, pent(i))
print('Output')
# Execute code
start = time.time()
if __name__ == "__main__":
main()
end = time.time()
print('Run time: {}'.format(end - start))
|
# -*- coding: utf-8 -*-
'''
Project Euler - Problem 25
Calculate first number in Fibonacci sequence to contain 1000 digits
F(n) = F(n-1) + F(n-2)
F(0) = 0, F(1) = 1, F(2) = 1
'''
# Imports
import time
# To calculate prorgram run time
start = time.time()
# Initialise variables
num_digits = 1000
a = 1
b = 0
n = 1
# Loop until desired digit length is achieved
while len(str(a)) < num_digits:
a, b = a+b, a
n += 1
end = time.time()
print('Run time: {}'.format(end - start))
print('Number: {} \nLength: {} \nTerm in sequence: {}'.format(a, len(str(a)), n))
|
"""
File Name: growth.py
Author's Name: Tejaswini Jagtap
"""
from utils import *
def sorted_growth_data(data,year1,year2):
"""
sorts from higher to lower the countries according to the growth in life expectancies from year1 to year2
:param data: data dictionary containing country name as key
:param year1: starting year
:param year2: ending year
:return: sorted list with country name and its growth in life expectancies from year1 to year2
"""
CountryValueTemp={}
CountryValue=[]
for k,v in data.items():
if v[3][year1]!='' and v[3][year2]!='':
CountryValueTemp[abs(v[3][year1]-v[3][year2])]=k
#print(CountryValueTemp)
a=list(CountryValueTemp.keys())
a.sort(reverse=True)
for i in a:
CountryValue.append([CountryValueTemp[i],i])
return CountryValue
def main():
"""
prints top and bottom 10 growth in life expectancies from year1 to year2 as sorted
:return:
"""
(entries, larger, meta, data, reg, inc) = read_data('worldbank_life_expectancy')
year1=int(input('Enter starting year of interest (-1 to quit): '))
year2 = int(input('Enter ending year of interest (-1 to quit): '))
while year1!=-1 and year2!=-1:
if year1>1959 and year1<2016 and year2>1959 and year2<2016:
reg=input("Enter region (type 'all' to consider all): ")
reg_data=filter_region(data,reg)
#print(reg_data)
if reg_data:
inc = input("Enter income category (type 'all' to consider all): ")
inc_data=filter_income(reg_data,inc)
if inc_data:
cv_data=sorted_growth_data(inc_data,year1,year2)
i=0
print("")
print("Top 10 Life Expectancy Growth:", year1, " to", year2)
while i!=10 and i!=len(cv_data):
print(cv_data[i])
i+=1
i=len(cv_data)-1
print("")
print("Bottom 10 Life Expectancy Growth:", year1, " to", year2)
while i != len(cv_data)-11 and i != -1:
print(cv_data[i])
i-=1
else:
print(inc+' not a valid income')
else:
print(reg+' not a valid region')
else:
print('Valid years are 1960-2015')
print("")
year1 = int(input('Enter starting year of interest (-1 to quit): '))
if year1==-1:
break
year2 = int(input('Enter ending year of interest (-1 to quit): '))
if __name__=='__main__':
main()
|
class Node:
def __init__(self, item, left=None, right=None):
"""(Node, object, Node, Node) -> NoneType"""
self.item = item
self.left = left
self.right = right
def depth(self):
left_depth = self.left.depth() if self.left else 0
right_depth = self.right.depth() if self.right else 0
return max(left_depth, right_depth) + 1
tree = Node(1, Node(2), Node(3))
print(tree.depth())
|
# Python code to listen and send the mail to receiver
import speech_recognition as sr
import pyttsx3
from pyttsx3 import voice
import time
import smtplib
import getpass as gp
# Initialize the recognizer
r = sr.Recognizer()
# Function to convert text to speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
# Function to send the mail
def Sendmail(server, port, xsender, xpassword, xreceiver, xmessage):
# Sending mail
# Creates SMTP session
s = smtplib.SMTP(server, port)
s.ehlo()
# start TLS for security
s.starttls()
# Authentication
s.login(str(xsender), str(xpassword))
# sending the mail
s.sendmail(str(xsender), str(xreceiver), str(xmessage))
# terminating the session
s.quit()
# Prompt to the user
print("\nThe mail was sent successfully...")
SpeakText("Mail Sent successfully, Thank You for using this program")
# Function to display an error message when the mail is not sent
def ShowError():
print("\nWe are having problem sending your mail.");
SpeakText("We are having problem sending your mail.")
time.sleep(1)
print("\nPlease check your mail and authenticate the program and enable less secure apps for your account.")
SpeakText("Please check your mail and authenticate the program and enable less secure apps for your account.")
time.sleep(1)
print("\nHope it helps, Thank You")
SpeakText("Hope it helps, Thank You")
# Taking information from the user about the mail
print("\n\nHello! Welcome to Voice Based Mailing Service")
SpeakText("Hello! Welcome to Voice Based Mailing Service")
time.sleep(0.5)
print("You need to login first, so we need your Email and Password...")
SpeakText("You need to login first, so we need your email and password")
time.sleep(1)
# Enter the credentials
SpeakText("\nPlease Enter your Email")
sender = input("\nEmail : ")
SpeakText("\nAlright! Now enter your password")
password = gp.getpass()
time.sleep(1)
# Initialize subject and body, helpful if any error pop from speech recognizer
subject = 'no'
body = 'no'
# Get the message from the user
# Exception handling to handle
# exceptions at the runtime
try:
# use the microphone as source for input.
with sr.Microphone() as source2:
# wait for a second to let the recognizer
# adjust the energy threshold based on
# the surrounding noise level
r.adjust_for_ambient_noise(source2, duration=0.2)
#listens for the user's input
SpeakText("You are good to go.");
time.sleep(1)
SpeakText("Tell me the subject.")
print("\nSubject : Listening...")
audio2 = r.listen(source2)
# Using google to recognize audio
subject = r.recognize_google(audio2)
subject = subject.lower()
print("\nYour Subject: " + subject)
SpeakText("Tell me the message body.")
print("\nBody : Listening...")
audio2 = r.listen(source2)
# Using google to recognize audio
body = r.recognize_google(audio2)
body = body.lower()
print("Your Body: \n" + body)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
if subject == 'no':
subject = "Ignore this mail..."
if body == 'no':
body = "Sorry :( Sent by-mistake..."
except sr.UnknownValueError:
print("unknown error occured")
if subject == 'no':
subject = "Ignore this mail..."
if body == 'no':
body = "Sorry :( Sent by-mistake..."
# Get the sender details
SpeakText("Well Done! Please enter receiver EMail Address.")
receiver = input("\nReceiver's Email: ")
# Add the subject and body to complete the message
message = 'Subject: ' + subject + "\nDear " + receiver + ', \n\n' + body + '\nSent from: https://github.com/subhamsagar524/Voice-Based-Mailing-from-Terminal'
# Prompt the user to choose the service
SpeakText("Now Please choose your mailing service.")
choose = int(input("\n\n1. Gmail\n2. Yahoo\n3. Outlook\nChoose your server : "))
SpeakText("Ok, we are sending your mail.")
SpeakText("You will be informed once the mail is sent.")
# Try to send the EMail through different service
if choose == 1:
# Try sending the mail through Gmail
try:
Sendmail('smtp.gmail.com', 587, sender, password, receiver, message)
# If not sent inform the user
except:
ShowError()
elif choose == 2:
# Try sending the mail through Yahoo
try:
Sendmail('smtp.mail.yahoo.com', 587, sender, password, receiver, message)
# If not sent inform the user
except:
ShowError()
elif choose == 3:
# Try sending the mail through Outlook
try:
Sendmail('smtp-mail.outlook.com', 587, sender, password, receiver, message)
# If not sent inform the user
except:
ShowError()
else:
print("\nInvalid Option\nThank You...")
SpeakText("We do not support any other services.")
time.sleep(1)
SpeakText("Thanks for using the Program.")
|
#! usr/bin/env python3
import numpy as np
import sys
#define a function that returns a value
def expo(x):
return np.exp(x)#return the np e^x function
#define a subroutine that does not return a value
def show_expo(n):
for i in range(n):
print(expo(float(i)))#call the expo function ensures that it is a float.
#define a main function
def main():
n=10#provide a default function for n
#check if there is a command line argument provided
if(len(sys.argv)>1):
n=int(sys.argv[1])#if an argument was provided, use it for n
show_expo(n)#call the show_expo subroutine
#run the main function
if __name__=="__main__":
main()
|
#Number of queens
print ("Enter the number of queens")
N = int(input())
#chesssol
#NxN matrix with all elements 0
sol = [[0 for i in range(N)]for j in range(N)]
def is_attack(i, j):
#checking if there is a queen in row or column
for k in range(0,N):
if sol[i][k]==1 or sol[k][j]==1:
return True
#checking diagonals
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if sol[k][l]==1:
return True
return False
def N_queen(n):
#if n is 0, solution found
if n==0:
for x in range(N):
for y in range(N):
print(sol[x][y], end=" ")
print()
return True
for i in range(0,N):
for j in range(0,N):
if (not(is_attack(i,j))) and (sol[i][j]!=1):
sol[i][j] = 1
#recursion
#wether we can put the next queen with this arrangment or not
if N_queen(n-1)==True:
return True
sol[i][j] = 0
return False
N_queen(N)
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
data = pd.read_csv("positions.csv")
# print(data.columns)
levels = data.iloc[:,1].values.reshape(-1,1)
salaries = data.iloc[:,2].values.reshape(-1,1)
regression = DecisionTreeRegressor()
regression.fit(levels,salaries)
plt.scatter(levels,salaries, color = "red")
x = np.arange(min(data.Level),max(data.Salary),0.01).reshape(-1,1)
plt.plot(x,regression.predict(x), color = "orange")
plt.xlabel("Level")
plt.ylabel("Salary")
plt.title("Decision Tree Model")
plt.show()
|
# Displays the game using turtle
import turtle
class Display:
def __init__(self):
# Turtle setup
# Screen
self.wn = turtle.Screen()
self.wn.title("Snake")
self.wn.bgcolor("black")
self.wn.setup(width=800, height=400)
self.wn.tracer(0)
# Snake head
self.head = turtle.Turtle()
self.head.turtlesize(0.5,0.5)
self.head.speed(0)
self.head.shape("square")
self.head.color("white")
self.head.penup()
self.head.goto(205,5)
self.head.direction = "stop"
# Snake food
self.food = turtle.Turtle()
self.food.turtlesize(0.5,0.5)
self.food.speed(0)
self.food.shape("square")
self.food.color("red")
self.food.penup()
# Snake segments
self.segments = []
self.buffer_segments = []
self.add_segments(3)
# Halfway line
self.line = turtle.Turtle()
self.line.speed(0)
self.line.setposition(0,200)
self.line.color("white")
self.line.right(90)
self.line.forward(400)
self.line.penup()
# All the texts
self.texts = []
self.text_descriptions = ["Score: ", "High Score: ", "Snakes Alive: ", "Species: #", "Generation: ", "Mode: "]
self.text_values = [0, 0, 0, 0, 1, "training (1)"]
for i in range(len(self.text_descriptions)):
text = turtle.Turtle()
text.speed(0)
text.color("white")
text.penup()
text.hideturtle()
# Position text, inserting gaps in certain areas
if i > 4:
text.goto(-300, 30+i*-30)
elif i > 1:
text.goto(-300, 60+i*-30)
else:
text.goto(-300, 90+i*-30)
text.write(self.text_descriptions[i] + "{}".format(self.text_values[i]), align="left", font=("Avenir Next", 24, "normal"))
self.texts.append(text)
# Create additional tail segments
def add_segments(self,num_segments):
buffers_used = 0
for i in range(num_segments):
if i < len(self.buffer_segments):
self.buffer_segments[i].goto(205, -5-10*i)
self.segments.append(self.buffer_segments[i])
buffers_used += 1
else:
new_segment = turtle.Turtle()
new_segment.turtlesize(0.5,0.5)
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
new_segment.goto(205,-5-10*i)
self.segments.append(new_segment)
self.buffer_segments = self.buffer_segments[buffers_used:]
# Hide extra tail segments
def hide_segments(self,num_segments):
for i in range(len(self.segments)-1, len(self.segments)-1-num_segments, -1):
self.segments[i].goto(1000,1000)
self.buffer_segments.append(self.segments[i])
self.segments = self.segments[:len(self.segments)- num_segments]
# Update screen
def update(self, head_position, food_position, segment_positions, text_values):
# Find how many segments are needed
needed_segments = len(segment_positions) - len(self.segments)
# Create more segments if needed
if needed_segments > 0:
self.add_segments(needed_segments)
# Hide segments if not needed
elif needed_segments < 0:
self.hide_segments(abs(needed_segments))
# Position head, food, and segments
self.head.goto(head_position)
self.food.goto(food_position)
for i in range(len(segment_positions)):
self.segments[i].goto(segment_positions[i])
# Update text
# For all values
for i in range(len(text_values)):
# Check that they are not the same as the currently displayed value
if self.text_values[i] != text_values[i]:
# Update currently displayed value
self.text_values[i] = text_values[i]
self.texts[i].clear()
if text_values[i] != -1:
self.texts[i].write(self.text_descriptions[i]+"{}".format(self.text_values[i]), align="left", font=("Avenir Next", 24, "normal"))
|
import numpy as np
import queue
import math
import time
import matplotlib.pyplot as plt
import matplotlib as mpl
# 新的矩阵可以变成1,也可以变成0
# 写一下不同函数,不同目标的接口
# 把图象写得好看一点,
class Maze:
def __init__(self,size,prob):
"""
Create a new maze
param size(int): the size of maze
param prob(double): the probability the cell to be occupied
return: a maze(n by n matrix) with cells being filled or empty
"""
self.size = size
self.prob = prob
# check if prob between 0 and 1
if prob < 0 or prob > 1:
raise ValueError('prob should between 0 and 1')
# create a uniform distribution matrix
self.maze = np.random.uniform(low=0,high=1,size=[size,size])
# generate maze matrix, '0':empty '1':filled
self.maze = (self.maze < prob).astype(int)
self.maze[0,0] = 0
self.maze[size - 1,size - 1] = 0
# dictionary of solution
self.solution = dict(
find_path_or_not='',
number_of_nodes_visited=0,
visited_nodes={},
path_length=0,
path=[],
max_fringe_size=0
)
def in_maze(self,node):
"""
check if neighbors are in the maze
param mode: the coordinate of the node
return: True or False
"""
return (0 <= node[0] < self.size) and (0 <= node[1] < self.size)
def if_empty(self,node):
"""
check if the node is empty
param node: the coordinate of the node
return: True of False
"""
return self.maze[node[0],node[1]] == 0
def neighbor(self,node):
"""
find neighbor nodes
param node: the coordinate of a node
return: neighbors of the input node
"""
# search directions: down > right > left > up
possible_neighbor = [(node[0] + 1,node[1]),(node[0],node[1] - 1),(node[0] - 1,node[1]),(node[0],node[1] + 1)]
neighbors = set()
for a_node in possible_neighbor:
if self.in_maze(a_node) and self.if_empty(a_node):
neighbors.add(a_node)
return neighbors
def print_maze(self):
"""
print the maze as a matrix
"""
print(self.maze)
def print_path(self):
"""
print path and visited nodes on the maze
2 means visited nodes and 3 means path
"""
_maze = self.maze.copy()
for node in self.solution['visited_nodes']:
_maze[node[0],node[1]] = 2
for node in self.solution['path']:
_maze[node[0],node[1]] = 3
# print(_maze)
self.show_maze(_maze)
def show_maze(self,maze):
"""
show maze as a colorful plot
:param maze:
:return:
"""
cmap = mpl.colors.ListedColormap(['white','black','pink','red'])
bounds = [-1,0.5,1.5,2.5,3.5]
norm = mpl.colors.BoundaryNorm(bounds,cmap.N)
plt.imshow(maze,interpolation='nearest',cmap=cmap,norm=norm)
plt.show()
class SolveMaze:
def __init__(self,maze):
self.maze = maze
self.start_point = (0,0)
self.end_point = (maze.size - 1,maze.size - 1)
def buildpath(self,parent):
"""
build a path form end to start
param parent: dictionary of parents
return: a path
"""
path = []
current_node = self.end_point
while current_node != self.start_point:
path.append(current_node)
current_node = parent[current_node]
path.append(current_node)
return path[::-1]
def dfs(self):
"""
using depth first search to find a path
store result in maze.solution dictionary
"""
i = 0
visited = set() # to record visited nodes
parent = {} # to record the parent of each visited node
path = []
stack = []
stack.append(self.start_point)
visited.add(self.start_point)
while stack:
if stack.__len__() > i:
i = stack.__len__()
curnode = stack.pop()
if curnode == self.end_point:
path = self.buildpath(parent)
# print(visited)
self.maze.solution = dict(find_path_or_not="YES",
number_of_nodes_visited=len(visited),
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=i)
return
direction = [(-1,0),(0,-1),(1,0),(0,1)]
for x,y in direction:
nextnode = (curnode[0] + x,curnode[1] + y)
if (self.maze.in_maze(nextnode) and nextnode not in visited and self.maze.if_empty(nextnode)):
# print(nextnode)
parent[nextnode] = curnode
stack.append(nextnode)
visited.add(nextnode)
self.maze.solution = dict(find_path_or_not="NO",
number_of_nodes_visited=0,
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=0)
return
def bfs(self):
"""
using breath first search to find a path
store result in maze.solution dictionary
"""
visited = set() # to record visited nodes
parent = {} # to record the parent of each visited node
path = []
i = 0
stack = []
stack.append(self.start_point)
# visited.add(self.start_point)
while stack:
if stack.__len__() > i:
i = stack.__len__()
curnode = stack.pop(0)
# visited.add(curnode)
if (curnode == self.end_point):
path = self.buildpath(parent)
# print(visited)
self.maze.solution = dict(find_path_or_not="YES",
number_of_nodes_visited=len(visited),
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=i)
return
direction = [(0,1),(1,0),(-1,0),(0,-1)]
for x,y in direction:
nextnode = (curnode[0] + x,curnode[1] + y)
if (self.maze.in_maze(nextnode) and nextnode not in visited and self.maze.if_empty(nextnode)):
parent[nextnode] = curnode
stack.append(nextnode)
visited.add(nextnode)
self.maze.solution = dict(find_path_or_not="NO",
number_of_nodes_visited=0,
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=0)
return
def a_star_euclidean(self):
"""
using A* with Euclidean Distance to be heuristic to find a path
store result in maze.solution dictionary
"""
visited = set()
parent = {}
path = []
_queue = queue.PriorityQueue()
current_cost = {}
i = 0
_queue.put((0,self.start_point))
visited.add(self.start_point)
current_cost[self.start_point] = 0
while not _queue.empty():
if _queue.qsize() > i:
i = _queue.qsize()
current_node = _queue.get()
coordinate_current_node = current_node[1]
if coordinate_current_node == self.end_point:
path = self.buildpath(parent)
self.maze.solution = dict(find_path_or_not="YES",
number_of_nodes_visited=len(visited),
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=i)
return
for child_node in self.maze.neighbor(coordinate_current_node):
next_cost = current_cost[coordinate_current_node] + 1
if child_node not in visited:
current_cost[child_node] = next_cost
parent[child_node] = coordinate_current_node
visited.add(child_node)
# cost so far + h
h = math.sqrt(
(child_node[0] - self.end_point[0]) ** 2 +
(child_node[1] - self.end_point[1]) ** 2
)
total_cost = h + next_cost
_queue.put((total_cost,child_node))
self.maze.solution = dict(find_path_or_not="NO",
number_of_nodes_visited=0,
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=0)
return
def a_star_manhattan(self):
"""
using A* with Manhattan Distance to be heuristic to find a path
store result in maze.solution dictionary
"""
visited = set()
parent = {}
path = []
_queue = queue.PriorityQueue()
current_cost = {}
i = 0
_queue.put((0,self.start_point))
visited.add(self.start_point)
current_cost[self.start_point] = 0
while not _queue.empty():
if _queue.qsize() > i:
i = _queue.qsize()
current_node = _queue.get()
coordinate_current_node = current_node[1]
if coordinate_current_node == self.end_point:
path = self.buildpath(parent)
self.maze.solution = dict(find_path_or_not="YES",
number_of_nodes_visited=len(visited),
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=i)
return
for child_node in self.maze.neighbor(coordinate_current_node):
next_cost = current_cost[coordinate_current_node] + 1
if child_node not in visited:
current_cost[child_node] = next_cost
parent[child_node] = coordinate_current_node
visited.add(child_node)
# cost so far + h
h = abs(child_node[0] - self.end_point[0]) + abs(child_node[1] - self.end_point[1])
total_cost = h + next_cost
_queue.put((total_cost,child_node))
self.maze.solution = dict(find_path_or_not="NO",
number_of_nodes_visited=0,
visited_nodes=visited,
path_length=len(path),
path=path,
max_fringe_size=0)
return
def run(self,method):
if method == "dfs":
print("dfs:")
# t0 = time.clock()
self.dfs()
print(self.maze.solution)
self.maze.print_path()
# print("consumed time:")
# print(time.clock() - t0)
elif method == "bfs":
print("bfs:")
# t0 = time.clock()
self.bfs()
# print(self.maze.solution)
self.maze.print_path()
print("consumed time:")
# print(time.clock() - t0)
elif method == "a_star_euclidean":
print("a_star_euclidean:")
t0 = time.clock()
self.a_star_euclidean()
print(self.maze.solution)
self.maze.print_path()
print("consumed time:")
print(time.clock() - t0)
elif method == "a_star_manhattan":
print("a_star_manhattan:")
t0 = time.clock()
self.a_star_manhattan()
print(self.maze.solution)
self.maze.print_path()
print("consumed time:")
print(time.clock() - t0)
else:
raise ValueError("wrong method")
if __name__ == "__main__":
maze1 = Maze(5, 0)
maze1.print_maze()
solution = SolveMaze(maze1)
solution.run("bfs")
print(maze1.solution)
|
# dogru isim ve telefon numaralarini alip ekrana ayzdiran dictionary
dic = { }#bos bir dictionary ve liste olusturdum.
liste=[]
while True :
while True: # while True dongusu ile isimler alip eger isimler sadece hadrflerden olusuyorsa kabul eden aksi halde yeni isim isteyen dongu
name = input( "Enter name of friend :-")
if (name.isalpha())==False: #burda sadece harflerden olusup olusmadigini kontrol ettim
print("Please enter the correct name of friend")
else:
break
while True: #burda yine bir dongu ile uygun telefon numaralarini istedim.
phone =( input("Enter phone number of friend :-" ))
if len(phone)!=10: # burda istenen numaranin 10 haneden olusup olusmadigini kontrol ettim
print("Please enter the correct phone number")
else:
break
a=input("Is this person important for you: Y/N") #kisinin onmeli olup olmadigini sordum
if a=="Y": # eger onemli ise bunu bos listenin icine numara ve isim ile eklemesini istedim.
liste.append([name,phone])
tup=tuple(liste) # bu isimleri ise tuple icinde guvenli bolge olusturdum. boylece silinmeyecek ve degismeyecek
dic [name] = phone #burda dictionary i olusturdum.
choise = input("Enter Q to quit otherwise N :-") #burda tekrar isim eklemek istemedigini sordum. Add bolumu
if choise == "Q" or choise == "q" : # hayir ise donguden cikacak
break
print(dic)# ekrana dictionary i yazdirdim
print(tup)#ekrana tuple i yazdirdim
name=input("Please enter the name of friend you want to delete : ")# delete menusu istedigi ismi silecek.
del dic[name]
print(dic)
name=input("Please enter the name of friend you want to edit or change number: ") #edit or change bolumu
phone=int(input("Enter the phone number of friend: "))
del dic[name]
dic[name]=phone
print(dic)
|
#Note that the script below is the module with the functions
#That will be used in the interface for the bulls & cows game
from random import randint
#The command above will import the randint built in Python function
#It will be needed in the function defined next
def generateSecretNumber ():
r = randint (0, 9999)
stringR = str(r)
l = len(stringR)
s = ((4-l)*"0" + stringR)
return s
#The defined function above will generate a random 4-digit number
#This number is converted to a string, the length is taken and zero is added if
#Need be
def findUniqueDigits (s):
uniqueDigits = []
for i in s:
if uniqueDigits.count(i)==0:
uniqueDigits.append(i)
return findUniqueDigits
#this function finds the unique numbers which are present in the
#random 4-digit number generate above. for loop is used here
def findBulls (secret, guess):
bulls = 0
for i in range(len(secret)):
if secret[i] == guess[i]:
bulls += 1
else:
bulls += 0
return bulls
#This function gives us the number of digits which are similar in number and position
#Between the generated and guessed numbers (Bulls)
def findCows (secret, guess):
bothBC = 0
secretUniDigits = str(findUniqueDigits (secret))
for i in secretUniDigits:
secretcount = secret.count(i)
guesscount = guess.count(i)
minimum = min(secretcount, guesscount)
bothBC += minimum
bulls = findBulls (secret, guess)
return (bothBC - bulls)
#This function gives out/returns the number of matched digits
#In numbers but not positions (Cows)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.