text stringlengths 37 1.41M |
|---|
# (1)
a = input('정수 1개를 입력 : ')
b = input('실수 1개를 입력 : ')
print(a + b)
# (2)
print(int(a) + float(b)) |
import sqlite3
conn = sqlite3.connect('ages.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Ages')
cur.execute('''
CREATE TABLE Ages (name VARCHAR(128), age INTEGER)''')
cur.execute('DELETE FROM Ages;')
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Mathilda', 14));
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Anayah', 26));
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Samiha', 29));
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Chu', 32));
cur.execute('INSERT INTO Ages (name, age) VALUES (?, ?)', ('Kaeden', 26));
conn.commit()
cur.execute('SELECT hex(name || age) AS X FROM Ages ORDER BY X')
for row in cur:
print(row)
cur.close()
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head, k):
if not head:
return None
size = 1
last = head
# get the size of LL
while last.next != None:
last = last.next
size += 1
last.next = head # head becomes circular list: 1 2 3 4 5 6 -->
# | <-----------|
k = k % size # in case k is greater thean size
first = head
for i in range(size - k - 1): # stop one element before the beginning of rotated part
first = first.next
# first = 4 5 6 1 2 3 4....
second = first.next # second = 5 6 1 2 3 4 ..
first.next = None # break circular list
# first = 4 None
# second = 5 6 1 2 3 4 None
return second
|
'''
Given a binary tree, return the preorder traversal of its nodes' values.
pre-order traversal:
1. visit root
2. go to left sub-tree
3. visit the entire left sub-tree with pre-order traversal
4. go to right sub-tree
5. visit the entire right sub-tree with pre-order traversal
pseudo code:
def preorder(node):
if node == None:
return
print(node)
preorder(node.left)
preorder(node.right)
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):# recursion method
self.nodes = []
self.traverse(root)
return self.nodes
def traverse(self, node):
if node == None:
return # go back to previous level
self.nodes.append(node.val)
self.traverse(node.left)
self.traverse(node.right)
'''iteration method:
def preorderTraversal(self, root):
res = []
stack = [root]
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
'''
|
'''
Given a string and a string list, find the longest string in the list that can be formed by deleting some characters of the given string.
If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]
Output:
"a"
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000.
The length of all the strings in the input won't exceed 1,000.
'''
class Solution:
def findLongestWord(self, s, d):
res = ''
for word in d: # longer result, update same length but smaller lexicographical order
if self.isWordInS(s, word) and (len(word) > len(res) or (len(word) == len(res) and word < res)):
res = word
return res
def isWordInS(self, s, word):
i, j = 0, 0
while i < len(s) and j < len(word):
if s[i] == word[j]:
i += 1
j += 1
else:
i += 1
return j == len(word) # word pointer reached end, meaning entire word can be found in s
|
'''
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter.
Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice.Start is always smaller than end.
There will be at most 104 balloons. An arrow can be shot up exactly vertically from different points along the x-axis.
A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot.
An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2
Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
'''
class Solution:
def findMinArrowShots(self, points):
L = len(points)
if L < 2:
return L
points.sort()
arrows = L # start with max number of arrows (one for each point)
curr_end = points[0][1]
for i in range(1, L):
if points[i][0] <= curr_end: # overlapping found
arrows -= 1 # one less arrow needed
curr_end = min(curr_end, points[i][1]) # keep the smaller end bc. there can be more than 2 overlaps
else:
curr_end = points[i][1] # non overlapped, update end
return arrows
|
'''
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
'''
class Solution:
'''
robber has two choices: 1.rob cur house 2. not rob cur house
1 --> its better to rob cur house than to rob prev house, add cur house value to cur-2 (prev of prev)
2 --> its better to rob prev house than cur house, keep prev house
'''
def rob(self, nums): # O(1) space
if not nums:
return 0
pre1 = 0 # the previous house
pre2 = 0 # the house before previous house
for i in range(len(nums)):
cur = max(pre2 + nums[i], pre1)
pre2 = pre1
pre1 = cur
return cur
''' O(N) space
def rob(self, nums):
if not nums:
return 0
dp = [0 for _ in range(len(nums)+1)] # dp[i] stores the max profit at the ith house
dp[0] = 0 # 0th house (doesnt exist)
dp[1] = nums[0] # first house
for i in range(2, len(dp)):
dp[i] = max(dp[i-2]+nums[i-1], dp[i-1]) # nums[i-1] --> cur house
return dp[-1]
'''
|
'''
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping.
A pattern is defined by its length and the number of repetitions.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.
Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
Example 4:
Input: arr = [1,2,3,1,2], m = 2, k = 2
Output: false
Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.
Example 5:
Input: arr = [2,2,2,2], m = 2, k = 3
Output: false
Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
'''
class Solution:
def containsPattern(self, arr, m, k):
pattern_len = 0 # stores the length of current pattern subarray
for i in range(len(arr) - m): # leave an entire pattern at the end
if arr[i] == arr[i+m]: # cur element exist in next repetition
pattern_len += 1
else:
pattern_len = 0 # pattern broken, start over
if pattern_len == (m * (k-1)):
'''
k-1 because algorithm checks m elements ahead, when m=3, len=6, there are 9 valid elements
'''
return True
return False
|
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
# dynamic programming
def maxSubArray(nums):
''' Demo
[0, 1, -3, 4, -1, 2, 1, -5, 4]
[0, 1, -2, 4, 3, 5, 6, 1, 5]
new new max
'''
dp = [nums[0]] # Each element is the sum of current subarray
res = nums[0]
for i in range(1, len(nums)):
if dp[i - 1] <= 0: # If the previous sum is negative or 0, break that subarray, start a new one
dp.append(nums[i])
else:
dp.append(nums[i] + dp[i - 1]) # add nums[i] to current subArray
res = max(res, dp[i]) # update result
return res
|
'''
A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).
Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.
Examples:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: True
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: False
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: True
Note:
sx, sy, tx, ty will all be integers in the range [1, 10^9].
'''
class Solution:
def reachingPoints(self, x1, y1, x2, y2):
'''
Reachable points can be represented as a binary tree, where root is (x1,y1)
(x,y)
/ \
(x+y,y) (x, x+y)
/ \
(x+y+y,y) (x+y,x+y+y)
Algorithm:
1. Start from the bottom node(x2,y2), there is only one way from bottom node to root
2. Go upwards by doing (x2,y2) --> (x2-y2-y2-y2..., y2) -->(x2%y2, y2)
--> up the tree along a straight path
'''
if x2 < x1 or y2 < y1:
return False
if x1 == x2: # x can be reached, need to check y
#return y2 % x1 == y1 # subtract x1 every layer, see if y2 remains
return (y2-y1) % x1 == 0
if y1 == y2:
#return x2 % y1 == x1
return (x2-x1)%y1==0
if x2 > y2: # (x+y,y)
x2 %= y2
else: # (x,x+y)
y2 %= x2
return self.reachingPoints(x1, y1, x2, y2)
|
'''
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
'''
class Solution:
def totalNQueens(self, n):
self.nSolution = 0
self.queenPos = [-1] * n
self.placeQueen(0)
return self.nSolution
def placeQueen(self, r): # Backtracking
if r == len(self.queenPos):
self.nSolution += 1
return
for c in range(len(self.queenPos)):
if self.isValid(r,c):
self.queenPos[r] = c
self.placeQueen(r+1) # go to the next row
self.queenPos[r] = -1
return
def isValid(self, r, c):
for rPrev, cPrev in enumerate(self.queenPos[0:r]):
if cPrev == c or c-r == cPrev-rPrev or c+r == cPrev+rPrev:
return False
return True
|
'''
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent,
with the colors in the order red, white and blue. Use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
come up with a one-pass algorithm using only constant space
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
'''
class Solution:
def sortColors(self, nums):
"""
Demo:
[2,0,2,1,1,0] front=0, pointer=0, end=5
[0,0,2,1,1,2] front=0, pointer=0, end=4
[0,0,2,1,1,2] front=1, pointer=1, end=4
[0,0,2,1,1,2] front=2, pointer=2, end=4
[0,0,1,1,2,2] front=2, pointer=2, end=3
[0,0,1,1,2,2] front=3, pointer=3, end=3
"""
front = 0 # the position where the next 0 is supposed to be
pointer = 0 # travels from 0 to end
end = len(nums) - 1 # the position where the next 2 is supposed to be
while pointer <= end:
if nums[pointer] == 0: # finds 0, move to front
nums[front], nums[pointer] = nums[pointer], nums[front]
front += 1
pointer += 1
elif nums[pointer] == 2: # finds 2, move to end
nums[end], nums[pointer] = nums[pointer], nums[end]
end -= 1
else: # finds 1, do nothing
pointer += 1
|
'''
Suppose you have a random list of people standing in a queue.
Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
'''
class Solution:
def reconstructQueue(self, people):
# sort the people in the order of descending h. If multiple people have same height, sort them in ascending k
# i.e. [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] --> [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
people = sorted(people, key = lambda x: (-x[0], x[1]))
res = []
for p in people:
res.insert(p[1], p) # insert p at position p[1]
'''
Tallest people are inserted first, and they will not affect the position of shorter people
because either h_cur < h_prev, or (h_cur=h_prev and k_cur>k_prev)
不管在哪里添加多少个矮的,都不会使高的人的位置变得不正确
[[7,0],[7,1]] ---> [[7,0],[6,1],[7,1]] or [[7,0],[7,1],[6,2]] or [[6,0],[7,0],[7,1]]
'''
return res
|
'''
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that
each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
'''
class Solution:
def partitionLabels(self, S): # Time: O(n), Space: O(1)
'''
Algorithm:
1. Create a dict with key=char, cal=[idx of 1st appear, idx of last appear]
2. Merge the overlapping intervals and put all into a list
3. Return the length of each interval in the list intervals
'''
dic = {} # At most 26 keys
for i, char in enumerate(S):
if char in dic:
dic[char][1] = i
else:
dic[char] = [i, i]
intervals = []
for key in dic:
if intervals == [] or dic[key][0] > intervals[-1][1]: # new interval
intervals.append(dic[key])
elif dic[key][0] < intervals[-1][1] < dic[key][1]: # update interval[1]
intervals[-1][1] = dic[key][1]
# return the length of each merged interval
return [interval[1]-interval[0]+1 for interval in intervals]
def optimized(self, S):
dic = {} # stores the idx of last appearance of each char
for i, char in enumerate(S):
dic[char] = i
res = []
start = 0 # start and end of cur interval
end = 0
for i, char in enumerate(S):
end = max(end, last[char])
if i == end:
res.append(end - start + 1)
start = i + 1 # move on to new interval
return res
|
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
'''
class Solution:
def numSquares(self, n):
nSquare = [x for x in range(n+1)] # nSquare[i] stores the least number of PSNs which sum to i
for i in range(2, len(nSquare)): # 0 and 1 are base cases
# try subtracking PSNs from cur number, find the PSN that is as large as possible without making remain negative
for j in range(1, i):
PSN = j * j
remain = i - PSN # one perfect square number used, count into result
if remain < 0:
break
else:
nSquare[i] = min(nSquare[i], nSquare[remain] + 1)
return nSquare[n] # last element corresponds to n
|
'''
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
'''
def findJudge(N, trust):
tScore = [0] * (N+1) # how likely each person is the town judge
for t in trust:
tScore[t[0]] -= 1 # if trust someome, less likely to be judge, decrease score
tScore[t[1]] += 1 # if trusted, more likely to be judge, increase score
for i in range(1, N+1):
if tScore[i] == N-1: # the judge will have N-1 trusts (everyone except himself)
return i
return -1
|
'''
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
'''
# 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 levelOrderBottom(self, root):
if not root:
return []
# deque is basically a list that supports adding and removing elements from either end
queue = deque([root]) # the first level must have only one node (root)
allLevelVals = []
while queue:
curLevelVals = [] # stores the values of current level, reset to [] every level
size = len(queue)
for i in range(size):
# pop all current level elements from queue, and append all next level elements to the queue
curNode = queue.popleft()
if curNode.left:
queue.append(curNode.left)
if curNode.right:
queue.append(curNode.right)
# fill curLevelVal with the left and right children of cur level nodes
curLevelVals.append(curNode.val)
allLevelVals.append(curLevelVals)
return allLevelVals[::-1]
|
'''
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
'''
class Solution:
def canFinish(self, numCourses, prerequisites):
self.state = [0 for _ in range(numCourses)] # 0:not visited 1: visited 2: being visited (current tree)
self.graph = [[] for _ in range(numCourses)] # graph[i] denotes the list of prereqs of course i
for [course, prereq] in prerequisites:
self.graph[course].append(prereq) # [[1,0],[0,2],[2,3],[3,4],[4,2]] --> [[2],[0],[3],[4],[2]]
for course in range(numCourses):
if not self.dfs(course):
return False
return True
def dfs(self, node):
# start from a node and look for cycles, i.e. [0,1], [1,2], [2,0]
if self.state[node] == 2: # if cur node is marked as being visited, then a cycle is found.
return False
if self.state[node] == 1: # if cur is visted, it (and its tree) is proven to be valid, return true
return True
self.state[node] = 2 # mark as being visited, means still in the current dfs tree, or the 'circle' that is not yet completed
for neighbour in self.graph[node]:
if not self.dfs(neighbour): # visit all the neighbours
return False
# At this point, all neighbours of cur node are visites and they are all valid
self.state[node] = 1 # mark all nodes in cur tree as visited and return True because they are valid
return True
|
'''
Given a string s and an int k, return all unique substrings of s of size k with k distinct characters.
Example 1:
Input: s = "abcabc", k = 3
Output: ["abc", "bca", "cab"]
Example 2:
Input: s = "abacab", k = 3
Output: ["bac", "cab"]
Example 3:
Input: s = "awaglknagawunagwkwagl", k = 4
Output: ["wagl", "aglk", "glkn", "lkna", "knag", "gawu", "awun", "wuna", "unag", "nagw", "agwk", "kwag"]
Explanation:
Substrings in order are: "wagl", "aglk", "glkn", "lkna", "knag", "gawu", "awun", "wuna", "unag", "nagw", "agwk", "kwag", "wagl"
"wagl" is repeated twice, but is included in the output once.
Constraints:
The input string consists of only lowercase English letters [a-z]
0 ≤ k ≤ 26
'''
class Solutions():
def distinctCharSubstr(self, string, k): # Time: O(n*k)
substrList = []
for i in range(len(string) - 2): # O(n)
substr = string[i:i+k]
# check if substr has k unique chars and not already added
if (len(set(substr)) == k) and (substr not in substrList): # O(k)
substrList.append(substr)
return substrList
def optimized(self, string, k): # Time: O(n)
idxDict = dict() # key = char, val = idx of char
subsets = set()
start = 0
for i in range(len(string)):
if string[i] in idxDict and i-idxDict[string[i]] < k: # Duplicate found, start new substring by moving start
start = idxDict[string[i]] + 1
idxDict[string[i]] = i
if i - start + 1 == k:
subsets.add(string[start:i + 1])
start += 1
#print(idxDict)
return list(subsets)
def slidingWindow(self, string, k):
window = set()
res = set()
start = 0
cur = 0
while cur < len(string):
while string[cur] in window:
window.remove(string[start])
start += 1
window.add(string[cur])
if len(window) == k:
res.add(string[start:cur+1])
window.remove(string[start])
start += 1
cur += 1
return list(res)
s = Solutions()
l1 = s.distinctCharSubstr("awaglknagawunagwkwagl",4)
l2 = s.optimized("awaglknagawunagwkwagl",4)
l3 = s.slidingWindow("awaglknagawunagwkwagl",4)
print(l1)
print(l2)
print(l3)
|
'''
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
'''
class Solution:
'''
repeatedly subtract divisor from dividend, until there is none enough left. Then the count of subtractions will be the answer. Yet this takes linear time and is thus slow. A better method is to subtract divisor in a more efficient way. We can subtract divisor, 2divisor, 4divisor, 8*divisor... as is implemented above.
'''
def divide(self, dividend, divisor):
isPositive = (dividend < 0) == (divisor < 0)
dividend = abs(dividend)
divisor = abs(divisor)
quotient = 0 # res
while dividend >= divisor: # if less, return 0
temp = divisor # the current divisor
i = 1 # number of divisors that get subtracted
while dividend >= temp:
dividend -= temp
quotient += i
i <<= 1 # *= 2
temp <<= 1 # *= 2
if not isPositive:
quotient = -quotient
return min(max(-2147483648, quotient), 2147483647)
|
'''
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
'''
class Solution:
'''
Algorithm: 1. If cur num not in correct position, swap it to the correct position
2. If the swap destination has the same number as cur, duplicate found
'''
def findDuplicates(self, nums): # Time = O(N), Space = O(1)
res = set()
i = 0
while i < len(nums):
if nums[i] != i+1: # not in correct position, i.e. 1 at idx=2
if nums[i] == nums[nums[i]-1]: # duplicate found, move on
res.add(nums[i])
i += 1
else: # keep swapping until cur is either duplicate or right position
# swap
temp = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
nums[i] = temp
else:
i += 1
return list(res)
|
'''
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list.
These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation:
The input multilevel linked list is as follows:
1---2---NULL
|
3---NULL
Example 3:
Input: head = []
Output: []
How multilevel linked list is represented in test case:
We use the multilevel linked list from Example 1 above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]
To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
[1,2,3,4,5,6,null]
[null,null,7,8,9,10,null]
[null,11,12,null]
Merging the serialization of each level and removing trailing nulls we obtain:
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Constraints:
Number of Nodes will not exceed 1000.
1 <= Node.val <= 10^5
'''
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flattenStack(self, head):
if not head:
return None
stack = [head]
prev = Node(0) # dummy node, put before head
while stack:
cur = stack.pop()
# connect cur and prev, if no child, this changes nothing
cur.prev = prev
prev.next = cur
prev = cur # move pre to cur
if cur.next:
stack.append(cur.next) # stack will store the next node of cur level while dealing whith child nodes
if cur.child:
stack.append(cur.child) # put child after next node so that child will be inserted after cur
cur.child = None
head.prev = None
return head
def flattenRec(self, head):
if not head:
return (None)
self.travel(head)
return head
def travel(self, cur):
while cur:
# store next node in case cur.next later points to child node. will use this to connect the child level back to current level
next = cur.next
if not next:
tail = cur # cur is last node in current level, assign it to 'tail' for return
if cur.child: # handle the child node's level and any more child nodes that it spawns
# connect cur and its child node
cur.child.prev = cur
cur.next = cur.child
child_tail = self.travel(cur.child) # returns tail after traversing the child node's level
if next: # if there exists a node in the prior level, connect its prev pointer to the child node's tail
next.prev = child_tail
child_tail.next = next # connect child_tail back to prior level's next node
cur.child = None # clear child pointers
cur = cur.next
return tail # return the tail node of cur level
|
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
def majorityElement(self, nums):
'''
the idea here is if a pair of elements from the
list is not the same, then delete both, the last
remaining element is the majority number
'''
count = 0
for num in nums:
if count == 0: # all previous numbers canceled out, fresh start
count += 1
major = num;
elif major == num: # current is major, add count
count += 1
else:
count -= 1 # cancel out major and current [1,1,1,2,2,2,...]
return major
|
'''
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
'''
class Solution:
'''One-Loop Method'''
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
numRow = len(matrix)
numCol = len(matrix[0])
left = 0
right = numRow*numCol - 1 # treat the matrix as a 1D array
while left <= right:
mid = (right - left)//2 + left
# change mid into r and c idx
r = mid //numCol
c = mid % numCol
if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
left = mid + 1
else:
right = mid - 1
return False
'''Two-Loop Method
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
rStart = 0
rEnd = len(matrix) - 1
rTarget = None
while rStart <= rEnd:
rMid = (rEnd - rStart)//2 + rStart
if matrix[rMid][0] <= target <= matrix[rMid][-1]:
rTarget = rMid
break
elif target < matrix[rMid][0]:
rEnd = rMid - 1
else:
rStart = rMid + 1
if rTarget is None:
return False
cStart = 0
cEnd = len(matrix[0])
while cStart <= cEnd:
cMid = (cEnd - cStart)//2 + cStart
if matrix[rTarget][cMid] == target:
return True
elif target < matrix[rTarget][cMid]:
cEnd = cMid - 1
else:
cStart = cMid + 1
return False
'''
|
from collections import defaultdict
class Cell(object):
remaining_values = {1, 2, 3, 4, 5, 6, 7, 8, 9}
final_value = None
def __init__(self, row, column, board, initial_value=0):
self.row = row
self.column = column
self.board = board
if initial_value:
self.final_value = initial_value
self.remaining_values = set()
def __repr__(self):
if self.final_value:
return str(self.final_value)
else:
return str(sorted(list(self.remaining_values)))
def _cells_in_row(self):
for cell in self.board[self.row]:
yield cell
def _cells_in_column(self):
for row in self.board:
yield row[self.column]
def _cells_in_square(self):
indices = ((0, 1, 2), (3, 4, 5), (6, 7, 8))
row_indices = indices[self.row / 3]
column_indices = indices[self.column / 3]
for r in row_indices:
for c in column_indices:
yield self.board[r][c]
def process(self):
self._update_possibilities()
self._check_loneliness()
if not self.final_value and len(self.remaining_values) == 1:
self.final_value = self.remaining_values.pop()
def _update_possibilities(self):
if self.final_value:
return
external_final_values = set(
[] # just for formatting, lol
).union(
set([x.final_value for x in self._cells_in_row() if x.final_value])
).union(
set([x.final_value for x in self._cells_in_column() if x.final_value])
).union(
set([x.final_value for x in self._cells_in_square() if x.final_value])
)
self.remaining_values = self.remaining_values - external_final_values
if len(self.remaining_values) == 1:
self.final_value = self.remaining_values.pop()
def _get_possibility_counts(self, cells):
counter = defaultdict(int)
for cell in cells:
for value in cell.remaining_values:
counter[value] += 1
return counter
def _check_loneliness(self):
row_counts = self._get_possibility_counts(self._cells_in_row())
column_counts = self._get_possibility_counts(self._cells_in_column())
square_counts = self._get_possibility_counts(self._cells_in_square())
for remaining_value in self.remaining_values:
if (
(row_counts[remaining_value] == 1) or
(column_counts[remaining_value] == 1) or
(square_counts[remaining_value] == 1)
):
self.final_value = remaining_value
self.remaining_values = set()
return
class Board(object):
def __init__(self, board):
# initialise rows to put cell objects in
self._cell_board = [[], [], [], [], [], [], [], [], []]
for row in xrange(9):
for column in xrange(9):
value = board[row][column]
cell = Cell(row, column, self._cell_board, value)
self[row].append(cell)
@property
def reached_contradiction(self):
return any(
(not cell.final_value and not cell.remaining_values)
for cell in self.cells
)
@property
def solved(self):
return all(cell.final_value for cell in self.cells)
@property
def cells(self):
for row in xrange(9):
for column in xrange(9):
cell = self[row][column]
yield cell
@property
def basic_representation(self):
rows = []
for row in self._cell_board:
rows.append([cell.final_value or 0 for cell in row])
return rows
def __getitem__(self, i):
return self._cell_board[i]
def __repr__(self):
line_format = "{} {} {} | {} {} {} | {} {} {}"
row_separator = "------+-------+------"
number_display = lambda x: x.final_value if x.final_value else ' '
lines = []
lines.append(line_format.format(*map(number_display, self[0][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[1][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[2][0]._cells_in_row())))
lines.append(row_separator)
lines.append(line_format.format(*map(number_display, self[3][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[4][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[5][0]._cells_in_row())))
lines.append(row_separator)
lines.append(line_format.format(*map(number_display, self[6][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[7][0]._cells_in_row())))
lines.append(line_format.format(*map(number_display, self[8][0]._cells_in_row())))
return '\n' + '\n'.join(lines) + '\n'
def find_smallest_guess(self):
# bit of an optimisation - if there's a cell with like 9 things you could guess that,
# that might take a while. So let's just find the cell with the fewest possibilities
# and pick one of those.
row = None
column = None
guesses = None
for cell in self.cells:
if not cell.remaining_values:
continue
if (guesses is None) or len(guesses) > len(cell.remaining_values):
row = cell.row
column = cell.column
guesses = cell.remaining_values
if not guesses:
print "wtf"
raise AssertionError
return row, column, guesses
@property
def is_valid(self):
# well this is an overly-onerous way of doing this, but screw it.
for cell in self.cells:
row_values = set(x.final_value for x in cell._cells_in_row())
column_values = set(x.final_value for x in cell._cells_in_column())
square_values = set(x.final_value for x in cell._cells_in_square())
all_equal = row_values == column_values == square_values == {1, 2, 3, 4, 5, 6, 7, 8, 9}
if not all_equal:
return False
return True
@property
def state(self):
# gives a string representation of the full state of the board
# including assumptions
return str(list(self.cells))
def solve(self, verbose=True, recursion_level=0):
if recursion_level > 5:
raise Exception
while True:
if verbose:
print self
state_0 = self.state
for cell in self.cells:
cell.process()
state_1 = self.state
if state_0 == state_1:
if self.solved:
if self.is_valid:
return self
return False
if self.reached_contradiction:
if verbose:
print "contradiction found."
return False
# stalemate, then - need to make a guess.
row, column, guesses = self.find_smallest_guess()
for guess in guesses:
basic_representation = self.basic_representation
basic_representation[row][column] = guess
new_board = Board(basic_representation)
if verbose:
print "Making assumption: row={row}, col={col}, value={guess}...".format(row=row, col=column, guess=guess)
print self
result = new_board.solve(verbose=verbose, recursion_level=recursion_level+1)
if result:
return result
return False
test_board_1 = [
[7, 5, 0, 0, 3, 8, 0, 0, 0],
[0, 0, 0, 5, 0, 0, 9, 0, 0],
[0, 9, 0, 0, 7, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 8, 2, 1],
[1, 3, 4, 0, 0, 0, 7, 5, 6],
[2, 8, 7, 0, 0, 0, 0, 0, 0],
[0, 0, 6, 0, 2, 0, 0, 3, 0],
[0, 0, 5, 0, 0, 3, 0, 0, 0],
[0, 0, 0, 4, 1, 0, 0, 9, 2],
]
test_board_2 = [
[0, 0, 0, 0, 0, 9, 0, 0, 0],
[0, 0, 8, 0, 6, 0, 0, 0, 0],
[7, 0, 5, 4, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 3, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 5, 0],
[5, 8, 7, 0, 0, 0, 2, 0, 0],
[4, 0, 0, 7, 0, 0, 9, 6, 0],
[9, 0, 0, 2, 0, 0, 0, 0, 0],
[0, 2, 6, 5, 0, 0, 4, 0, 0],
]
test_board_3 = [
[0, 0, 0, 5, 0, 4, 0, 0, 0],
[0, 0, 8, 0, 0, 0, 3, 0, 0],
[7, 5, 0, 0, 2, 0, 0, 0, 6],
[0, 0, 0, 7, 8, 0, 2, 6, 4],
[0, 6, 0, 0, 9, 0, 0, 0, 8],
[5, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 0, 5, 0, 3, 0, 9, 0, 7],
[0, 0, 2, 6, 0, 9, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 3, 0],
]
# The hardest button to button
test_board_x = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0],
]
#board = Board(test_board_x)
#board.solve()
|
#FOR LOOP challenges 05
#Clay Palmer
number = int(input("Enter a number between 1 and 12: "))
for i in range(1,13):
print(number*i)
|
#WHILE LOOP challenges 05
#Clay Palmer
compnum = 50
guess = int(input("Enter a number: "))
count = 1
anotherGuess = 'Y'
while guess != compnum:
while anotherGuess == 'Y':
if guess < compnum:
print("Your guess is too low")
anotherGuess = str(input("Do you want another guess? (Y/N): ")).upper()
guess = int(input("Enter another number: "))
count = count + 1
elif guess > compnum:
print("Your guess is too high")
anotherGuess = str(input("Do you want another guess? (Y/N): ")).upper()
guess = int(input("Enter another number: "))
count = count + 1
else:
anotherGuess = 'N'
print("")
print("Well done! You guessed the number in",count,"attempts.")
|
#String Slicing Challenges 05
#Clay Palmer
word = str(input("Enter any word: "))
word = (word).upper()
print(word)
|
#WHILE LOOP challenges 02
#Clay Palmer
number = 0
while number <= 5:
number = int(input("Enter a number: "))
print("The last number you entered was",number,)
|
"""
Lab 2
"""
#4.1
my_name = "tom"
print(my_name.upper())
#4.2
my_id = "123"
print(my_id)
#4.3
my_id=your_id=123
print(my_id)
print(your_id)
#4.4
my_id_str="123"
print(my_id_str)
#4.5
#print(my_name+my_id)
#4.6
print(my_name + my_id_str)
#4.7
print(my_name*3)
#4.8
print('hello world. This is my first python string.'.split('.'))
#4.9
#message = 'Tom's ID is 123'
#print(message)
|
def decode(encoded):
# Write your code here
# reverse string
encoded = encoded[::-1];
result = ""
i = 0
while(i < len(encoded) - 1):
currVal = encoded[i]
nextVal = encoded[i+1]
val = (int) (currVal + nextVal)
if(val == 32):
result += chr(val)
i = i + 2
#check if capital
elif(val >= 65 and val <= 99):
result += chr(val)
i = i + 2
else:
thirdVal = encoded[i+2]
val = (int) (currVal + nextVal + thirdVal)
result += chr(val)
i = i + 3
return result |
import os
import time
import numpy as np
import pandas as pd
from log import get_logger
logger = get_logger(__name__)
class MatchMaking:
"""
Implementation of a matchmaking algorithm to create balanced teams based on
a skill rating.
On initialization an initial seed is performed. When calling the `optimize`
function the algorithm to balance the teams is being run.
Initial seed
------------
As a first step, players are subdivided into skill tiers. The number of
skill tiers is the same as the team size.
The best player from the highest skill tier is matched with the worst
player from the lowest skill tier. For the next team the second best and
the second worst are chosen and so on. From the middle skill tiers random
players are chosen.
Balancing Algorithm
-------------------
The optimization tries to minimize the score. As a scoring function first
the average skill ratings of all teams are calculated. The score is
calculated from the maximum deviation a team has from the total average
skill rating.
In each iteration of the balancing algorithm two teams are chosen at
random or the minimum and the maximum scoring teams based on the
`min_max_pairing` flag). Single players are swapped between the two teams.
After swapping the new score is calculated. If the swapping improves the
overall score - the changes are kept.
As stopping criteria either the number of iterations is used or the number
of iterations without a change.
"""
def __init__(
self, df, teamsize=3, min_max_pairing=False, noise_size=10000, noise_digits=2
):
"""
Parameters
----------
df: pandas.DataFrame
Must contain a 'skill' columns.
teamsize: int
Size of the teams.
min_max_pairing: boolean
If true as swapping pairs the team with the maximum and the
minimum deviation are used. Not recommended as the algorithm can
quickly get stuck in a local minimum.
noise_size: int
Size of the Laplace noise, which is added.
noise_digits: int
Number of digits, which are used to round off the noised values.
"""
logger.info("... starting matchmaking")
self.num_iterations = 0
self.df = df
self.num_players = df.shape[0]
self.teamsize = teamsize
self.num_groups = self.num_players // self.teamsize
self._set_outputdir()
self.min_max_pairing = min_max_pairing
self._add_noise(noise_size, noise_digits)
self._set_bins()
self._init_teams()
def _set_outputdir(self):
"""
Create a subfolder `output` as subdirectory of the script.
"""
self.OUTPUTDIR = os.path.join(os.getcwd(), "output")
os.makedirs(self.OUTPUTDIR, exist_ok=True)
def _add_noise(self, noise_size, noise_digits):
"""
In order to avoid problems with binning by skill values in `set_bins` a
little Laplace noise is being added. If we have two or more players
with the exact same skillrating at a bin's edge this will lead to
uneven team sizes.
Parameters
----------
noise_size: int
Size of the Laplace noise, which is added.
noise_digits: int
Number of digits, which are used to round off the noised values.
"""
self.df["skill"] = np.round(
np.random.laplace(
self.df["skill"], self.df["skill"] / noise_size, self.df.shape[0]
),
noise_digits,
)
def _set_bins(self):
"""
Put players into skill tiers (bins). The number of bins depends on
`self.teamsize`.
"""
self.df["skill_bin"], self.bins = pd.qcut(
self.df.skill, self.teamsize, retbins=True, labels=False
)
self.max_bin = self.df.skill_bin.max()
self.min_bin = self.df.skill_bin.min()
def _init_teams(self):
"""
Intitial seeding for teams. The best player from the highest skill tier
is matched with the worst player from the lowest skill tier. For the
next team the second best and the second worst are chosen and so on.
From the middle skill tiers random players are chosen.
"""
self.df["team"] = -1
for team_num in range(self.num_groups):
logger.info(f"team_num: {team_num}")
_df = self.df[self.df["team"] == -1]
for skill_bin, group in _df.groupby("skill_bin"):
skill_tier = ""
if skill_bin == self.max_bin:
idx = group["skill"].idxmax()
self.df.loc[idx, "team"] = team_num
skill_tier = "BEST"
elif skill_bin == self.min_bin:
idx = group["skill"].idxmin()
self.df.loc[idx, "team"] = team_num
skill_tier = "MIN"
else:
idx = np.random.choice(group.index)
self.df.loc[idx, "team"] = team_num
skill_tier = "MEDI"
logger.info(
f"skill_tier: {skill_tier} skill_bin: "
+ "{skill_bin}, team_num: {team_num}"
)
self._update_team_means()
def _update_team_means(self):
"""
Update the average team deviation and update the overall score.
"""
self.team_means = self.calc_team_means(self.df)
self.score = self.calc_score(self.team_means)
self.num_iterations += 1
def swap_teams(self):
"""
The main optimization mechanism. Take two random teams (or the minimum
and the maximum scoring teams) and swap single players between them. If
the swapping improves the overall score - keep the changes.
"""
# get the groups with the highest and the lowest deviations
if self.min_max_pairing:
team_0 = self.team_means.idxmin()
team_1 = self.team_means.idxmax()
else:
team_ids = np.random.choice(list(self.team_means.index), 2, replace=False)
team_0 = team_ids[0]
team_1 = team_ids[1]
logger.info(f"try swapping team {team_0} and team {team_1}")
idxs_0 = list(self.df[self.df.team == team_0].index)
idxs_1 = list(self.df[self.df.team == team_1].index)
combos = self.get_idx_combos(idxs_0, idxs_1)
swapped = False
# swap members: if score gets smaller through swapping
# -> update everything
for combo in combos:
_df = self.df.copy()
_df.loc[combo[0], "team"] = team_0
_df.loc[combo[1], "team"] = team_1
team_means = self.calc_team_means(_df)
score = self.calc_score(team_means)
self.num_iterations += 1
if score < self.score:
self.score = score
self.team_means = team_means
self.df = _df
logger.info(f"{combo[0]} {combo[1]} new score: {score}")
swapped = True
return swapped
def optimize(self, max_iter=1000, max_counter=10):
"""
Run the optimization algorithm.
Parameters
----------
max_iter: int
Maximum number of iterations.
max_counter: int
Counter goes up with each iteration without an improvement. If
there hasn't been an improvement since `max_counter` number of
iterations, iteration will be aborted.
"""
counter = 0
iter_num = 0
while (counter < max_counter) & (iter_num < max_iter):
swapped = self.swap_teams()
iter_num += 1
if swapped:
counter = 0
else:
counter += 1
logger.info(f"Iteration {iter_num}, best score: {self.score}")
logger.info(f"Best result: {self.score}")
self._write_result()
def _write_result(self):
"""
Write the results of the optimization to a .csv file. Before storing
the table is being sorted by teams.
"""
self.df.sort_values("team", inplace=True)
self.df["mean_dev"] = self.df["team"].apply(lambda x: self.team_means[x])
self.df.to_csv(
os.path.join(self.OUTPUTDIR, f"et_groupsize_{self.teamsize}.csv")
)
logger.info("\n" + self.df.to_string())
@staticmethod
def get_idx_combos(idxs_0, idxs_1):
"""
Get all combinations of two sets of indices when swapping only one
member between the two sets.
"""
combos = []
for idx_0 in idxs_0:
for idx_1 in idxs_1:
_idxs_0 = idxs_0.copy()
_idxs_1 = idxs_1.copy()
_idxs_0.remove(idx_0)
_idxs_0.append(idx_1)
_idxs_1.remove(idx_1)
_idxs_1.append(idx_0)
combos.append((_idxs_0, _idxs_1))
return combos
@staticmethod
def calc_team_means(df):
"""
The team means are the differences of the team's player's mean skill to
the overall mean skill of all players.
"""
means = df.groupby("team")["skill"].mean()
return means - means.mean()
@staticmethod
def calc_score(means_dev):
"""
Calculate the score for the optimization function. The score is defined
as the maximum deviation a team's skill has from the total average
skill.
"""
return np.abs(means_dev).max()
|
import pandas as pd
from FileLoader import FileLoader
def youngestFellah(df, date):
m_min = df.loc[(df['Year'] == date) & (df['Sex'] == 'M')].min()['Age']
f_min = df.loc[(df['Year'] == date) & (df['Sex'] == 'F')].min()['Age']
min_age = {'m' : m_min , 'f' : f_min}
return (min_age)
f = FileLoader()
fl = f.load('../athlete_events.csv')
df = youngestFellah(fl, 2000)
print(df)
|
from recipe import Recipe
from book import Book
#print("What recipe do you want to add ?")
#name = input()
#print("What is its cooking level ?")
#lvl = input()
#print("What is the cooking time ?")
#time = input()
#print("What are the ingredients ?")
#ingr = input()
#print("What is the description ?")
#des = input()
#print("What is the recipe type ? starter, lunch or dessert ?")
#rec_type = input()
#print()
#rec_to_add = Recipe(name, lvl, time, ingr, des, rec_type)
#to_print = str(rec_to_add)
#print(to_print)
tourte = Recipe("Tourte", 2,25,"flour and dreams","C'est la base","lunch")
cookie = Recipe("Cookie",1,10,"sugard and love","Mmmmmh","dessert")
pasta = Recipe("Pasta",3,125,"pesto, tomatoes","I love pasta","lunch")
bread = Recipe("Bread and butter",1,1,"bread","","starter")
mybook = Book("Martine fait de la cuisine", 2015)
mybook.add_recipe(tourte)
mybook.add_recipe(cookie)
mybook.add_recipe(pasta)
mybook.add_recipe(bread)
mybook.add_recipe(1)
#if i == 1
#mybook.get_recipe_by_name(bread.name)
#mybook.get_recipe_by_name(cookie.name)
#mybook.get_recipe_by_name("miamm")
# if i == 2
# mybook.get_recipes_by_types("lunch")
# mybook.get_recipes_by_types("starter")
# mybook.get_recipes_by_types("pocahantas")
i = "0"
while i != "5":
i = input()
|
class Evaluator:
"""My evaluator"""
@staticmethod
def zip_evaluate(coefs, words):
if isinstance(coefs, list) == 0 or isinstance(words, list) == 0:
print("Both params should be lists")
elif len(coefs) != len(words):
print("Error, lists are not the same size")
else:
for coef in coefs:
if isinstance(coef, float) == 0:
print("Coefs should only be float")
return
for word in words:
if isinstance(word, str) == 0:
print("Words should only be string")
return
couple = zip(coefs, words)
res = 0
i = 0
for word in words:
res += couple[i][0] * len(couple[i][1])
i += 1
print(res)
@staticmethod
def enumerate_evaluate(coefs, words):
if isinstance(coefs, list) == 0 or isinstance(words, list) == 0:
print("Both params should be lists")
elif len(coefs) != len(words):
print("Error, lists are not the same size")
else:
for coef in coefs:
if isinstance(coef, float) == 0:
print("Coefs should only be float")
return
for word in words:
if isinstance(word, str) == 0:
print("Words should only be string")
return
coef = enumerate(coefs)
word = enumerate(words)
res = 0
for count, ele in enumerate(coefs):
res += ele * len(list(enumerate(words))[count][1])
print(res)
coef = [1.0,2.0,3.0,0.0,10.0]
word = ["je","o","al","coucou","ma"]
print("By zip:")
Evaluator.zip_evaluate(coef, word)
print("By enumerate:")
Evaluator.enumerate_evaluate(coef, word)
|
#Created by Kamil Krawczyk
#03/04/2020
#Problem 2
#This program asks the user for two numbers and tells the user if the sum of the numbers is greater than, less than, or equal to 10.
def num_equation():
print("Input the first number - ")
x = int(input())
print("Input the second number - ")
y = int(input())
num_calc = (x+y)
if num_calc > 10:
print(num_calc, " is greater than 10!")
elif num_calc < 10:
print(num_calc, "is less than 10!")
elif num_calc == 10:
print(num_calc, " is equal to 10!")
num_equation()
|
"""
Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
"""
revenue = int(input("Введите значение выручки: "))
costs = int(input("Введите значение издержек: "))
profit = revenue - costs
if profit > 0:
print("Фирма отработала с прибылью")
print(f"Рентабельность = {profit / revenue:.2f}")
employees = int(input("Введите число сотрудников: "))
print(f"Прибыль в расчете на одного сотрудника: {profit / employees:.2f}")
elif profit < 0:
print("Фирма отработала с убытком")
else:
print("Фирма отработала в ноль")
© 2020 GitHub, Inc.
Terms
Privacy
Security
Status
|
#!/usr/bin/env python
def quick_sort(unsorted, method='median'):
if len(unsorted) < 2:
return unsorted
piv = pivot(unsorted, method=method)
lesser = [i for i in unsorted if i < piv]
greater = [i for i in unsorted if i > piv]
piv_list = [i for i in unsorted if i == piv]
lesser = quick_sort(lesser, method=method)
greater = quick_sort(greater, method=method)
lesser.extend(piv_list)
lesser.extend(greater)
return lesser
def pivot(list_inp, method='median'):
"""Defines a pivot point for quicksort, method can be ['first', 'last',
'median']"""
if method.lower() == 'median':
med_list = [list_inp[0], list_inp[-1], list_inp[len(list_inp) // 2]]
med_list.remove(max(med_list))
med_list.remove(min(med_list))
return med_list[0]
if method.lower() == 'first':
return list_inp[0]
if method.lower() == 'last':
return list_inp[-1]
if __name__ == '__main__':
pass
|
import sys
for number in sys.stdin:
input_num=int(number)
n=0
max_in_the_group=1
while True:
if input_num<=max_in_the_group: print(n+1); break
else: n+=1; max_in_the_group+=(6*n)
|
n=int(input())
n_list=[]
for i in range(n):
n_list+=[int(input())]
n_list.sort()
for i in n_list:
print (i)
|
import random
cardarray = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
suits = ['Hearts', 'Clubs', 'Spades', 'Diamonds']
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def printcard(self):
self.cardlist = []
temp = ''
if self.value <= 10:
temp = self.value
if self.value == 11:
temp = 'Jack'
if self.value == 12:
temp = 'Queen'
if self.value == 13:
temp = 'King'
if self.value == 14:
temp = 'Ace'
self.cardlist.append("{} of {}".format(temp, self.suit))
return self.cardlist
class Deck(object):
def __init__(self):
self.deckcards = []
for s in suits:
for i in cardarray:
self.deckcards.append(Card(s, i))
self.decklength = len(self.deckcards)
def shuffle(self):
for i in range(self.decklength - 1):
idx = random.randint(0, self.decklength - 1)
temp = self.deckcards[i]
self.deckcards[i] = self.deckcards[idx]
self.deckcards[idx] = temp
return self
def draw(self):
yourdraw = self.deckcards.pop()
self.decklength -= 1
return yourdraw
def remove(self):
yourdraw = self.deckcards.pop()
self.decklength -= 1
return self
def addcard(self, card_to_add):
for i in range(len(self.deckcards) - 1, -1, -1):
self.deckcards[i] = self.deckcards[i - 1]
self.deckcards[0] = card_to_add
self.decklength += 1
return self
def printdeck(self):
print "The Deck of Cards is shuffled..."
for c in self.deckcards:
c.printcard()
class Player(object):
def __init__(self, name):
self.hand = []
self.name = name
def receive(self, deck):
temp = deck.draw()
self.hand.append(temp)
return self
def giveI(self, deckRef, idx):
if idx > len(self.hand) - 1:
idx = len(self.hand) - 1
swap = self.hand[idx]
self.hand[idx] = self.hand[len(self.hand) - 1]
self.hand[len(self.hand) - 1] = swap
self.hand.pop()
deckRef.addcard(swap)
return self
def showhand(self):
for card in self.hand:
card.printcard()
return self
class Table(object):
def __init__(self):
self.tabletop = []
self.p1score = 0
self.p2score = 0
self.points = 1
def addcard(self, card_to_add):
self.tabletop.append(card_to_add)
return self
def compare(self, deck, p1, p2):
for card in self.tabletop:
print card.printcard()
for card in self.tabletop:
if len(self.tabletop) != 2:
print "Table has: " + str(len(self.tabletop))
break
elif self.tabletop[0].value > self.tabletop[1].value:
self.p1score += self.points
self.points = 1
break
elif self.tabletop[0].value < self.tabletop[1].value:
self.p2score += self.points
self.points = 1
break
elif self.tabletop[0].value == self.tabletop[1].value:
deck.remove().remove().remove()
self.points += 3
break
print p1.name + " score: " + str(self.p1score)
print p2.name + " score: " + str(self.p2score)
self.tabletop = []
return self
def winner(self, p1, p2):
if self.p1score > self.p2score:
print str(p1.name) + " wins!"
elif self.p1score < self.p2score:
print str(p2.name) + " wins!"
else:
print "It's a tie!"
#game starts here
aDeck = Deck().shuffle()
aPlayer = Player('Vitali')
bPlayer = Player('Brandon')
t = Table()
print ''
print "5 CARD WAR!"
print ''
#fill player hands
aPlayer.receive(aDeck).receive(aDeck).receive(aDeck).receive(aDeck).receive(aDeck)
bPlayer.receive(aDeck).receive(aDeck).receive(aDeck).receive(aDeck).receive(aDeck)
#run the game
aPlayer.giveI(t, len(aPlayer.hand))
bPlayer.giveI(t, len(bPlayer.hand))
t.compare(aDeck, aPlayer, bPlayer)
print ''
aPlayer.giveI(t, len(aPlayer.hand))
bPlayer.giveI(t, len(bPlayer.hand))
t.compare(aDeck, aPlayer, bPlayer)
print ''
aPlayer.giveI(t, len(aPlayer.hand))
bPlayer.giveI(t, len(bPlayer.hand))
t.compare(aDeck, aPlayer, bPlayer)
print ''
aPlayer.giveI(t, len(aPlayer.hand))
bPlayer.giveI(t, len(bPlayer.hand))
t.compare(aDeck, aPlayer, bPlayer)
print ''
aPlayer.giveI(t, len(aPlayer.hand))
bPlayer.giveI(t, len(bPlayer.hand))
t.compare(aDeck, aPlayer, bPlayer)
print ''
#print winner
t.winner(aPlayer, bPlayer)
print ''
|
'''
This is the exercises from the book titled 'Deep Learning with Python Keras'
Chapter 3: Getting started with neural networks
Section 6.2: Understanding recurrent nerual networks
section 6.2.1: A first recurrent layer in keras
reimplymented by zhiwen
date: 21-Jul-2018
'''
from keras import models, layers, losses, optimizers, metrics
from keras.preprocessing import sequence
from keras.datasets import imdb
from keras.utils import plot_model
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
# set the results file path
sectionnum = '6_2'
cur_work_path = os.getcwd()
res_path = '{}/res_c{}'.format(cur_work_path,sectionnum)
if not os.path.exists(res_path):
os.mkdir(res_path)
# params
max_features = 10000 # number of words to condier as features
maxlen = 500 # cut texts after this number of words
batchsize = 32
# loading and prepare the data
print('loading data ...')
(input_train, y_train),(input_test, y_test) = imdb.load_data(num_words=max_features)
print('len of train: ', len(input_train))
print('len of test: ', len(input_test))
print('shape and type of input_train before padding: ', input_train.shape, type(input_train))
input_train = sequence.pad_sequences(input_train,maxlen=maxlen)
input_test = sequence.pad_sequences(input_test, maxlen=maxlen)
print('shape and type of input_train after padding: ', input_train.shape, type(input_train))
# crate the model
def CreateModel(rnn = layers.SimpleRNN, hiddensize=32):
model = models.Sequential()
model.add(layers.Embedding(max_features,32))
model.add(rnn(hiddensize))
model.add(layers.Dense(1,activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
return model
history_record=[]
rnnMethod = [layers.SimpleRNN, layers.LSTM, layers.GRU]
for rnn in rnnMethod:
model = CreateModel(rnn)
history = model.fit(input_train,y_train,epochs=10,batch_size=512,validation_split=0.2)
history_record.append(history)
def plot_on_axis(ax,history,rnnMode,key1='loss',key2='val_loss'):
value1 = history.history[key1]
value2 = history.history[key2]
epochs = range(1,len(value1)+1)
ax.plot(epochs, value1, 'b', label=key1)
ax.plot(epochs, value2, 'r', label=key2)
ax.legend()
ax.grid(True)
ax.set_ylabel(str(rnnMode))
plt.figure(figsize=(8,4*len(rnnMethod)))
gs = gridspec.GridSpec(len(rnnMethod),2)
for i, history in enumerate(history_record):
ax1 = plt.subplot(gs[i,0])
plot_on_axis(ax1,history,rnnMethod[i],key1='loss',key2='val_loss')
ax2 = plt.subplot(gs[i,1])
plot_on_axis(ax2,history,rnnMethod[i],key1='acc',key2='val_acc')
plt.savefig('{}/results_of_different_rnn_nets.png'.format(res_path))
plt.show()
#
|
print("What's your name")#
x = input()
print("Thats a great name for an indian!")
print("How old are you?")
age = int(input())
if age >= 20:
print("Way too old")
if age < 20:
print("Too old")
print("How tall are you in centimeters?")
height = int(input())
if height >= 170:
print("Must have an extra chromosome.")
else:
print("Must be a girl.")
print("How much do you weigh in pounds?")
print("If you dont know, go die.")
weight = int(input())
if weight >= 150:
print("Morbidly obese.")
else:
print("extremely underweight, anorexic.")
print("What colour are your eyes?")
eyes = input()
if eyes == 'brown':
print("plain.")
else:
print("im jelous.")
print("What colour is your hair?")
hair = input()
if hair == 'brown' or 'blonde' or 'grey':
print("plain.")
if hair == 'ginger':
print("HAHA poor ")
else:
("hmm, probably an emo")
|
def readias(r):
area=22//7*r**2
print(f"The area is:{area}")
p=int(input("Enter the redias:"))
readias(p) |
y=int(input("Enter the year"))
if y%4==0 and y%100!=0 or y%400==0:
print(f"The year {y} is leapyear")
else:
print(f"The year {y} is not leapyear")
|
#Equilateral ==
#Isosceles 2==
#Scalence !
def trang(a,b,c):
if a==b==c:
print("Equilateral")
elif a==b or b==c or a==c:
print("Isosceles")
else:
print("Scalence")
x=int(input("Enter 1st Side:"))
y=int(input("Enter 2nd Side:"))
z=int(input("Enter 3rd Side:"))
trang(x,y,z) |
# smallest element in ana array
from array import *
a=array('i',[])
n=int(input("Enter how many element:"))
for i in range(n):
a.append(int(input("Enter the element:")))
sm=a[0]
for i in range(1,len(a)):
if a[i]<sm:
sm=a[i]
print(f"The smallest element is:{sm}") |
def fac(n):
f=1
i=1
if n==0 or n==1:
return 1
else:
while i!=n:
f=f*n
n=n-1
return f
n=int(input("Enetr a number"))
ans=fac(n)
print(f"factorial={ans}")
"""
n=5-1=4-1=3-1=2-1=1
f=1*5=5*4=20*3=60*2=120
i=1""" |
# Exception Handling
# Errors
# Three types of errors
# 1) Compile time error
# compile time error ah chuan spelling te, semicolon dah hmaih te leh engemaw dah hmaih te khan a ni.
# 2) Logical error
# Logical error ah kha chuan run lai khan a hriat loh a run zawh a a output ah khan a hriat chauh a ni.
# Output dik lo te a thlen a ni.
# 3) Run time error
# Run time error ah hi chuan a user/ a run tu khan input dik lo a chhut luh khan a rawn lang dawn a ni.
# entirnan integer data type te kha enter tur ni se string te lo enter daih ta ila. a dik dawn lo a ni.
# Error kan lo hmachhawn dan tur chu.
a = 5
b = 2
try:
print(a/b)
except Exception as e: # helaia e hian error awm kha a rawn print thei dawn a ni.
print('Error a awm tlat mai', e) # error a awm chauhin hei chu a print ang.
finally: # finally hi chuan error a awm pawn awm loh pawn a rawn print dawn hrim hrim a ni.
print('success')
# entirna sei deuhin aw. a error a zir ang khan chi hrang hrang a tih theih a ni.
try:
i = int(input("Enter no. "))
j = int(input('No. '))
print(i)
print(i/j)
except ValueError as v: # tah hian value kan enter dik lo check na
print('I enter value hi',v)
except ZeroDivisionError as z: # zero divide a ni tih check na.
print('I divide na hi. ', z)
except Exception as e: # error hrim hrim check na.
print('hei hi error aw.', e)
finally:
print('Engkim check atanga hriat theih te an ni e.')
|
## Recursion - recursion chu function call itself
# def a():
# print('Hello recursive function\n')
# a()
# a()
## Recursion set limit
# import sys
# print(sys.getrecursionlimit())
# import sys
# sys.setrecursionlimit(2000)
# print(sys.getrecursionlimit())
# i = 0
# def greet():
# global i
# i += 1
# print("Hello", i)
# greet()
# greet()
# Factorial using recursion
def call():
n = int(input('Enter no you wanna factorial using recursion:'))
def a(n):
if n == 0:
return 1
return n * a(n-1)
result = a(n)
print(result)
call()
call() |
a = int(input('Enter any number less than 5: '))
if a == 1:
print('your entered no. is: 1')
elif a == 2:
print('your entered no. is 2')
elif a == 3:
print('your entered no. is 3')
elif a == 4:
print('your entered no. is 4')
elif a == 5:
print('your entered no. is 5')
else:
print('wrong input bitch')
|
# constructor and self
# object kan siam apiang khan space tharah a in allocate thin.
class New:
pass
c1 = New()
print(id(c1))
# update dan kan lo zir ang
class Update:
def __init__(self, name, age):
self.name = name
self.age = age
def update(self):
self.age = 25
print('name:',self.name, 'age:',self.age)
a = Update('Hpa', 20)
a.update()
# a dan dang chiin aw
class Exupdate:
def __init__(self):
self.name = 'rpa'
self.age = 29
def exup(self):
self.age = 30
print('name:',self.name, 'age:', self.age)
b = Exupdate()
b.name = 'John'
b.exup()
|
a = 12
b = 2
a = a^b
b = a^b
a = a^b
print('a:',a,'\nb:',b)
|
# Multithreading
# Task lianpui kha te reuh te te ah kan then a chu mi te reuh te te chu thread chu a ni.
class Hello:
def run(self):
for i in range(5):
print('Hello')
class Hi:
def run(self):
for i in range(5):
print('Hi')
a = Hello()
a.run()
b = Hi()
b.run()
# A rual chiah a run dan kha kan ti dawn a ni chu chu multithreading chu ani dawn ta a ni.
# thread ah kan siam dawn a ni.
# thread kan siam dawn chuan threading kan import a ngaia . chuan sleep kan dah tel nachhan chu a insu buai tur
# venna kha a ni.
# thread kha pathum a awm a, print() a hnuai bera kan dah kha a tawp bera print kan duh chuan a leh b hi kan join phawt
# a ngai dawn a ni.
# 1) main thread
# 2) a
# 3) b
from threading import * # threading import na kha a ni.
from time import sleep
class Hello(Thread):
def run(self):
for i in range(5):
print('Hello')
sleep(1)
class Hi(Thread):
def run(self):
for i in range(5):
print('Hi')
sleep(1)
a = Hello()
b = Hi()
a.start() # thread kan run dawn kha chuan start() hi a nih angai.
sleep(1) # collide a awm chuan. entirnan: HelloHi te lo ni rual ta se. sleep(1) kan dah hian a ti awm dwn lo a ni.
b.start() # tah pawh a nih tho hi.
# print() hi main thread a mi a ni a, a tawp bera print kan duh chuan thread a leh b hi kan join phawt a ngai dawn a ni.
a.join()
b.join()
print('bye')
|
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
text = open(file_path, "r")
text = text.read()
text = text.decode("utf-8")
text = text.replace("\n", " ")
text = text.replace("\r", " ")
text = text.replace("\t", " ")
text = text.split(" ")
words = []
for elem in text:
if len(elem) > 0:
words.append(elem.lower())
def makeFrequencyList(listOfWords):
#if you remove this function and paste it into another script
#please dont forget to decode utf-8 somewhere before this function
clean = []
num = []
for elem in words:
if elem not in clean:
clean.append(elem)
num.append(1)
else:
num[clean.index(elem)] += 1
frq = zip(clean, num)
frq.sort(key = lambda x: x[1], reverse=True)
frequency_list = open("frequency_list.txt", "w")
for n in range(len(frq)-1):
a = frq[n][0] + " " + str(frq[n][1]) + "\n"
a = a.encode("utf-8")
frequency_list.write(a)
frequency_list.close()
makeFrequencyList(words)
|
#!/usr/bin/env python3
# -*-coding:utf-8-*-
'''
测试生成器的send数据
'''
# def test():
# i = 1
# print('one line')
# temp = yield i
# i += 1
# print('two line', temp)
# yield i
#
# # 获取生成器
# gen = test()
#
# # one line
# next(gen)
#
# # 这个send的数据是发送给上一个yield点上进行接收的
# # two line haha
# gen.send('haha')
'''
测试 yeild from
'''
# def htest():
# i = 1
# while i < 4:
# print('i的值', i)
# n = yield i
# print('n的值', n)
# if i == 3:
# return 100
# i += 1
#
#
# def itest():
# val = yield from htest()
# print('val的值', val)
#
# t = itest()
#
# # i的值 1
# t.send(None)
#
# # n的值 haha
# # i的值 2
# t.send('haha')
#
# # n的值 here
# # i的值 3
# t.send('here')
# try:
# # n的值 hehe
# # val的值 100
# t.send('hehe')
# except StopIteration as e:
# # 异常了 None
# print('异常了', e.value)
class myTest(object):
def generator(self):
while True:
n = yield True
print('n的值', n)
i = 1
obj = myTest()
gen = obj.generator()
gen.send(None)
while i < 5:
gen.send('hahaha') |
import asyncio
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# yield b
# a, b = b, a + b
# n = n + 1
# return 'done'
# o = fib(6)
# print(o)
# for x in o:
# print(x)
def consumer():
r = 'a'
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produce(c):
a = c.send(None)
print(a)
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
# c = consumer()
# produce(c)
def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num1
num1, num2 = num2, num1+num2
current += 1
print('yield')
# 关键点
yield num
return 'edone'
ding = fib(5)
print(ding) |
import threading
import time
# from threading import Thread
# 法一——封装的思想
class User(threading.Thread):
count = 10 # 定义一个类属性(全局变量)
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
while User.count > 0:
mutex.acquire()
print('%s成功抢到%d号商品' % (self.name, User.count))
User.count -= 1
mutex.release()
time.sleep(0.1)
else:
print('很遗憾,没有了')
# 法二————多参数思想
# count = 10
#
#
# def user(name):
# global count
# while count > 0:
# mutex.acquire()
# print('%s成功抢到%d号商品' % (name, count))
# count -= 1
# mutex.release()
# time.sleep(0.1)
# else:
# print('很遗憾,没有了')
if __name__ == '__main__':
mutex = threading.Lock()
# u1 = threading.Thread(target=user, args=('zhang3',))
# u2 = threading.Thread(target=user, args=('li4',))
# u3 = threading.Thread(target=user, args=('wang5',))
u1 =User('zhang3')
u2 = User('li4')
u3 = User('wang5')
u1.start()
u2.start()
u3.start()
|
# 计算1~100的和
# sum = 0
# i = 1
# while i <= 10:
# sum = sum + i
# i = i + 1
# print("1~100的和为: %d" % sum)
# 计算1~n之间的和,n可以自己输入
sum = 0
i = 1
n=int(input('请输入:'))
while i <= n:
sum = sum + i
i += 1
print("1~%d的和为: %d" % (n,sum)) |
# # print("hello kitty")
# name = input("请输入姓名:")
# # print(name)
# a = 0
# if a > 0:
# print("aaa")
# else:
# print("bbb")
# """hel
# lo"""
# # "hel'lo"
# a = 1.5 * 3 + 2 # 乱写的
# a = 1.5 * 4 \
# + 3 - 2
#
#
# qqNum = 1234
# qqPsss = 3456
#
# print(qqNum)
# print(qqPsss)
str = "qwertyuiop"
a = str[1]
print(a)
# str[1]='3'
# print(str[1])
print(type(str)) |
# g1 = (a * a for a in range(1, 5)) # 创建生成器法一
#
# print(next(g1)) # 用next()方法获得生成器的值
# print(next(g1))
# print(next(g1))
# print(next(g1))
#
# # print(next(g1)) #会报错,因为超过4次,所以的元素都显示完
# print('-----1-----')
#
# g2 = (a * a for a in range(1, 5))
# for i in g2: # 用for循环可以防止获取值得过程中出现报错
# print(i)
# print('-----2-----')
#
#
# def func():
# yield (1) # yield()创建生成器法二
# yield (5)
# yield (6)
#
#
# f = func()
# print(type(f)) # 类型为生成器
# print(next(f))
# print(next(f))
# print(next(f))
#
# print('-----3-----')
# def func1(max):
# n, a, b = 0, 0, 1
# while n < max:
# print(b)
# a, b = b, a + b
# n += 1
# else:
# return 'done'
# func1(5)
print('-----4----')
def func2(max):
n, a, b = 0, 0, 1
while n < max:
yield(b)
a, b = b, a + b
n += 1
return 'done'
f2=func2(5)
print(next(f2))
print(next(f2))
print(next(f2))
print(next(f2))
print(next(f2))
print(next(f2))
|
class Base:
def __init__(self):
self.basename = 'basename' # 父类属性不需要从外界传入
def base_func(self):
print('base_func()')
class Sub(Base):
def __init__(self): # ctrl+o 调用父类属性的快捷键
super().__init__() # 继承父类的属性,若父类有从外界传入的属性如:name,则此处应该为__init__(name)
self.subname = 'subname' # 子类特有的属性
def sub_func(self):
super().base_func() # 类内调用父类方法
print('sub_func()')
if __name__ == '__main__':
b = Base()
s = Sub()
print(b.basename)
b.base_func()
print('*' * 40)
print(s.subname)
print(s.basename) # 调用父类的属性
print('*' * 40)
s.sub_func()
s.base_func() # 类外调用父类的方法(父类方法没有被重写时)
|
for n in range(3,100):
for i in range(2,n):
if (n%i)==0:
break
else:
print('%d'% n,end=" ")
# i = 2
#
# for n in range(3,100):
# while i<n:
# if (n%i)==0:
# break
# i+=1
# else:
# print("%d" % n, end=' ')
|
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '点的坐标为(%d,%d)' % (self.x, self.y)
class Circle:
def __init__(self, r, point):
self.r = r
self.o = point
def __str__(self):
return '半径为:%d,圆心为:(%d,%d)' % (self.r, self.o.x, self.o.y)
class App:
def peng(self):
a = c1.o.x - c2.o.x
b = c1.o.y - c2.o.y
if (a ** 2 + b ** 2) ** 0.5 > (c1.r + c2.r):
print('没有发生碰撞')
else:
print('碰撞')
if __name__ == '__main__':
p1 = Point(2, 3)
p2 = Point(4, 3)
print(p1)
print(p2)
c1 = Circle(3, p1)
c2 = Circle(4, p2)
print(c1)
print(c2)
print('*' * 40)
# a = c1.o.x - c2.o.x
# b = c1.o.y - c2.o.y
# if (a ** 2 + b ** 2) ** 0.5 > (c1.r + c2.r):
# print('没有发生碰撞')
# else:
# print('碰撞')
a1=App()
print(a1.peng())
|
d = {'name': 'zhang3', 'score': 34, 'age': 10}
print(type(d))
print(d)
print('-' * 40)
d1 = {'name': 'zhang3', 'name': 'zhang3', 'age': 10} # 若有重复的,后面的会覆盖前面的元素
print(type(d1))
print(d1)
print('-' * 40)
print(d['name']) # 使用字典,通过键而不是索引值
print(d['score'])
print(d['age'])
print('-' * 40)
d1['name'] = 'li4' # 修改值
print(d1)
d1['sex'] = '男' # 当键不存在时,会新增一个键值对
print(d1) |
a = None
def func():
if not a:
return True
else:
return False
def input_passward():
psw=input('请输入密码:')
if len(psw)>=8:
return psw
else:
ex=Exception('密码长度<8')
raise ex
if __name__ == '__main__':
# print(func())
# try:
# user_psw = input_passward()
# print(user_psw)
# except Exception:
# print('错误')
# except Exception as e:
# print(e)
# # input_passward()
g1=(4,6,9,10)
|
# list1 = [1, 2, 3]
# list2 = [1, 'abc', 3]
# list3 = [1, [2, 5], 3, True]
#
# list4=list3.copy()
#
#
#
# print(list1)
# print(list2)
# print(list3)
# print(list2[1])
#
# print(type(0.2)) # type显示该数据的类型
# print(type(123))
print(type(True))
# print(type('abc'))
#
num = ['a', 'b', 'c']
print(num)
num[1] = 'ABC'
print(num)
num.append('opk') # 在末尾加入
print(num)
num.insert(1, 'abnm') # 在中间某个位置加入
print(num)
# num.pop(1)
print(num.pop(1))
del (num[1])
del num[1]
# print(num)
#
l = [1, 1, 2, 3, 4, 5, 6]
l.remove(1)
print(l)
print(min(l))
# print('...........')
# l.remove(1)
# print(l)
#
# m = list('qwerty')
# print(m)
# print(type(m))
#
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'd', 'f']
# l2 = l1[:]
# print(l1)
# print(l2)
# print('-' * 40)
# l1.append(3)
# print(l1)
# l1.insert(1,6)
# print(l1)
print(l1.reverse())
l1.sort()
# print(l2)
#
# print('*'*40)
#
# l3 = [11, 22, 33, 44, 55]
# l4 = l3.copy()
# print(l3)
# print(l4)
# print('-' * 40)
# l3.append(66)
# print(l3)
# print(l4)
#
# print('-'*40)
# list5 = [1, [2, 5], 3, True]
# list6=list5.copy() # 因为list5中存在可变类型——列表,所以用copy得到的是浅拷贝
# print(list5)
# print(list6)
# print('-'*40)
# list5[1][1]=10
# print(list5)
# print(list6)
|
# ==============================================================================
#
# Use:
# decrypt("Svool Dliow!")
# => "Hello World!"
#
# ==============================================================================
def decrypt(initial):
output = ""
alphabet = {}
for i in range(26):
alphabet[chr(65+i)] = chr(90 - i)
alphabet[chr(97+i)] = chr(122 - i)
for char in initial:
if char in alphabet:
output += alphabet[char]
else:
output += char
return output
|
"""
You are required to write the code. You can click on compile & run anytime to check the compilation/ execution status of the program. The submitted code should be logically/syntactically correct and pass all the test cases.
Ques: The program is supposed to calculate the distance between three points.
For
x1 = 1 y1 = 1
x2 = 2 y2 = 4
x3 = 3 y3 = 6
Distance is calculated as : sqrt(x2-x1)2 + (y2-y1)2
ans:
"""
x1,y1 = 1,1
x2,y2 = 2,4
x3,y3 = 3,6
def sqrt(x,y,x1,y1):
res = (((y-x)**2) + ((y1-x1)**2))**0.5
return int(res)
print(sqrt(x1,y1,x2,y2),sqrt(x2,y2,x3,y3),sqrt(x3,y3,x1,y1))
# Write a program in C such that it takes a lower limit and upper limit as inputs and print all the intermediate pallindrome numbers.
x,y = 10,80
for i in range(x,y):
reverse = 0
temp = i
while (temp != 0):
remainder = temp%10
reverse = (reverse*10)+remainder
temp = temp // 10
if i == reverse:
print(reverse,end=" ")
# Problem: Write a program in C to display the table of a number and print the sum of all the multiples in it.
n = 5
table,total = [],0
for i in range(1,11):
table.append(i*n)
total+=(i*n)
print(*table)
print(total)
#You are required to input the size of the matrix then the elements of matrix, then you have to divide the main matrix in two sub matrices (even and odd) in such a way that element at 0 index will be considered as even and element at 1st index will be considered as odd and so on. then you have sort the even and odd matrices in ascending order then print the sum of second largest number from both the matrices
n = int(input("Enter the number: "))
odd,even = [],[]
for i in range(n):
temp = int(input("Enter the {} element".format(i)))
if i%2==0:
even.append(temp)
else:
odd.append(temp)
odd.sort()
even.sort()
print(*odd)
print(*even)
print(odd[-2]+even[-2])
#The function accepts 2 positive integer ‘m’ and ‘n’ as its arguments.You are required to calculate the sum of numbers divisible both by 3 and 5, between ‘m’ and ‘n’ both inclusive and return the same.
m = int(input())
n = int(input())
sum = 0
for i in range(m,n+1):
if i%3==0 and i%5==0:
sum+=i
print(sum)
#You have to find and return the number between ‘a’ and ‘b’ ( range inclusive on both ends) which has the maximum exponent of 2.
#a,b = int(input()), int(input())
a,b = 7,12
def expo(n):
temp = 0
while(n%2==0 and n!=0):
temp+=1
n//=2
return temp
max = 0
temp = 0
for i in range(a,b+1):
if expo(i)>temp:
temp = expo(i)
max = i
print(max)
#The function accepts 3 positive integers ‘a’ , ‘b’ and ‘c ‘ as its arguments. Implement the function to return.
c = int(input("Enter the choice 1 to 4: "))
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
def calc(c,a,b):
if c==1:return a+b
elif c==2:return abs(a-b)
elif c==3:return a*b
elif c==4:return a/b
else:return("Enter the option from 1 to 4")
print(calc(c,a,b))
#
|
import numpy as np
from loader import MNIST
import pandas as pd
#sigmoid function
def sigmoid(z):
return 1/(1+np.exp(-z))
#sigmoid gradient function
def sigmoidgradient(z):
sig = sigmoid(z)*(1-sigmoid(z))
return sig
#forwardpropagation
def forwardprop(Theta1,Theta2,X,Y):
a1 = np.hstack([np.ones((len(X),1)),X])
a2 = sigmoid((np.dot(a1,np.transpose(Theta1))))
a2 = np.hstack([np.ones((len(X),1)),a2])
a3 = sigmoid((np.dot(a2,np.transpose(Theta2))))
return a3
#cost function
def costfunc(Theta1,Theta2,X_train,Y_train,lamda,output_layer_size):
a3 = forwardprop(Theta1,Theta2,X_train,Y_train)
cost = (-1/len(Y_train))*np.sum(Y_train*np.log10(a3) + (1-Y_train)*np.log10(1-a3))
error = (lamda/(2*m))*(np.sum(Theta1[:,1:len(Theta1)]**2) + np.sum(Theta2[:,1:len(Theta2)]**2))
cost = cost + error
return cost
#backpropagation
def grad(X_train,Y_train,Theta1,Theta2,lamda,alpha,input_layer_size,hidden_layer_size,output_layer_size):
a1 = np.hstack([np.ones((len(X_train),1)),X_train])
a2 = sigmoid((np.dot(a1,np.transpose(Theta1))))
a2 = np.hstack([np.ones((len(X_train),1)),a2])
a3 = forwardprop(Theta1,Theta2,X_train,Y_train)
del1 = np.zeros(np.shape(Theta1))
del2 = np.zeros(np.shape(Theta2))
d3 = a3 - Y_train
k = np.dot(Theta1,np.transpose(a1))
k = np.reshape(k,(hidden_layer_size,len(X_train)))
l = np.dot(np.transpose(Theta2[:,1:len(Theta2[1])]),np.transpose(d3))
l = np.reshape(l,(hidden_layer_size,len(X_train)))
d2 = l*sigmoidgradient(k)
del1 = np.dot(d2,a1)
del2 = np.dot(np.transpose(d3),a2)
Theta1_grad = (1/len(Y_train))*del1
Theta2_grad = (1/len(Y_train))*del2
return [Theta1_grad,Theta2_grad]
#gradient descent
def gradientdescent(X,Y,Theta1,Theta2,alpha,maxiter,lamda,input_layer_size,hidden_layer_size,output_layer_size):
for i in range(0,maxiter):
[Theta1,Theta2] = grad(X,Y,Theta1,Theta2,lamda,alpha,input_layer_size,hidden_layer_size,output_layer_size)
Theta1 = Theta1 - alpha*Theta1
Theta2 = Theta2 - alpha*Theta2
return [Theta1,Theta2]
#predict function
def predict(X_val,Y_val,Theta1,Theta2):
output = forwardprop(Theta1,Theta2,X_val,Y_val)
output_Y = np.argmax(output,axis=1)
original_Y = np.argmax(Y_val,axis=1)
print(np.size(output))
print(np.size(Y_val))
print(np.shape(output_Y))
print(np.shape(original_Y))
A = (original_Y == output_Y)
acc = np.mean(A)*100
return acc
#model begins
print("This is a machine learning model.........")
print("This model identifies the character from a image........")
print("Loading data...........")
#Loading Data
mndata = MNIST("C:/Users/Prakhar Pande/Documents/mlwoc1")
images, labels = mndata.load_training()
test_images, test_labels = mndata.load_testing()
images1 = pd.DataFrame(images)
labels1 = pd.DataFrame([labels])
labels1= np.transpose(labels1)
images2 = pd.DataFrame(test_images)
labels2 = pd.DataFrame([test_labels])
labels2= np.transpose(labels2)
X_train = images1.iloc[0:60000,:].values
Y_train = labels1.iloc[0:60000,:].values
X_val = images2.iloc[0:10000,:].values
Y_val = labels2.iloc[0:10000,:].values
#Defining architecture of the network
input_layer_size = 784
hidden_layer_size = 50
output_layer_size = 10
Theta1 = np.random.rand(50,785)
Theta2 = np.random.rand(10,51)
#calculating cost and forward propagation
lamda = 0
Y_train = np.tile(np.arange(output_layer_size),(len(Y_train),1)) == np.tile(Y_train,(1,output_layer_size))
Y_train = Y_train*1
Y_val = np.tile(np.arange(output_layer_size),(len(Y_val),1)) == np.tile(Y_val,(1,output_layer_size))
Y_val = Y_val*1
cost = costfunc(Theta1,Theta2,X_train,Y_train,lamda,output_layer_size)
print(cost)
#calculating gradient using backpropagation
alpha = 0.001
#calculating gradient descent
maxiter = 200
[Theta1,Theta2] = gradientdescent(X_train,Y_train,Theta1,Theta2,alpha,maxiter,lamda,input_layer_size,hidden_layer_size,output_layer_size)
print(Theta1)
print(Theta2)
#predicting accuracy
accuracy = predict(X_val,Y_val,Theta1,Theta2)
print(accuracy) |
print()
# L1 How can we place a letter at the empty bottom right position
data = [
['O', 'X', 'O'],
['X', 'X', 'O'],
['X', 'O', '.']
]
# L2 How can we make the print board code above into a print board function we can re-use
# L3 How can we combine the data and the function into a Board class?
class Board:
# constructor
def __init__(self):
self.data = [
['O', 'X', 'O'],
['X', 'X', 'O'],
['X', 'O', '.']
]
# change mark
def change(self, row, col, mark):
self.row = row - 1
self.col = col - 1
self.mark = mark
self.data[self.row][self.col] = self.mark
# print new board
def print(self):
for line in self.data:
print(line)
new_board = Board()
new_board.change(1, 2, '.')
new_board.change(1, 1, '.')
new_board.print()
# L4 How can we say if X, O, or no-one has won? Can we |
""" Pour résoudre ce problème il est nécessaire de prendre le premier sous_mot
et de ce premier mot le découper en tous les sous_mots réalisable avec celui-ci
une fois que l'on a tous les sous mots possibles on regarde le plus long à l'intérieur
de tous les strings"""
import sys
N_word = int(input())
lines = []
for line in sys.stdin:
lines.append(line.rstrip("\n"))
def contains(s1, s2):
""" Returns True if s1 is in s2 """
if s1 == "":
return True
elif s2 == "":
return False
else:
if s1[0] == s2[0]:
return contains(s1[1:], s2[1:])
else:
return contains(s1, s2[1:])
def sous_mots(m):
if m == "":
return [""]
else:
aux = sous_mots(m[1:])
res = []
for e in aux:
res.append(m[0] + e)
return res + aux
result = ""
test_line = lines[0]
sous_mots = sous_mots(test_line)
for sous_mot in sous_mots:
exist = True
for line in lines:
if not contains(sous_mot, line):
exist = False
if exist and len(sous_mot) > len(result):
result = sous_mot
if result == "":
print("KO")
else:
print(result)
|
# coding:utf-8
'''
将华氏温度转换成摄氏温度
F = 1.8C + 32
Version:0.1
Author:不羡仙
Date:2019-5-30
'''
f = float(input("请输入华氏温度:"))
c = (f-32)/1.8
print("%.1f华氏度 = %.1f摄氏度" %(f,c)) |
# coding:utf-8
'''
打印三角形
Version:0.1
Author:不羡仙
Date:2019-5-30
* 3 1
*** 2 3
***** 1 5
******* 0 7
n =4
'''
n = 4
for i in range(1,n+1):
print(" "*(n-i),end='')
print("*"*(2*i-1),end='')
print()
|
names1 = ("Mg Mg","Aung Aung","Tun Tun","Su Su")
names2 = tuple(("Jhon Doe","Carrey","Robert","Plato")) # using Tuple Constructor
print(type(names1))
print(type(names2)) |
name = "Hello23123asd#fasd!fasDF"
print(name[len(name)-1]) # getting last index character
print(name[-10:-5]) # getting 5 character starting from last 10 t0 last 5 |
names = ["Mg Mg"]
names.append("Aung Aung") # ["Mg Mg","Aung Aung"]
names.append("Tun Tun") # ["Mg Mg","Aung Aung","Tun Tun"]
# ["Mg Mg","Aung Aung","Tun Tun"]
names.insert(0,"Su Su")
print(names[0])
print(names[1])
print(names[2])
print(names) |
class Main: # blueprint
name = "Mg Mg"
def change(self):
print(self.name)
m1 = Main() # Main().name
m1.name = "Aung Aung"
m1.change()
m2 = Main()
m2.name = "Tun Tun"
m2.change()
"""
to use properties or methods of a class, create its instance object
m1 => #x123123 => class Main: # blueprint
name = "Mg Mg"
def change(self):
print(self.name)
m2 => #x123124 => class Main: # blueprint
name = "Mg Mg"
def change(self):
print(self.name)
""" |
names1 = ("Mg Mg","Aung Aung")
names2 = ("Tun Tun","Su Su")
names = names1 + names2
name = '-'.join(names1) # from tuple make string value seperated by ,
namey = names1 * 4
print(names)
print(name)
print(namey) |
student = {
'name':'Mg Mg',
'age':20,
'heigh':5.11,
'city':'Rangoon',
'father':'U Hla',
'mother':'Dar Nu',
20:"He He"
}
print(student['name'])
print(student['age'])
print(student['city'])
print(student['heigh'])
print(student[20])
print(student)
"""
dictionary
-> use {} curley bracket
-> dictionary element has key:value
""" |
ceetee = list(("Rangoon","Mandalay")) # memoty address #123 # ["Rangoon","Mandalay"]
bt = ceetee #bt => memoty address #123 # Value pass by Refrence
# ceetee[0] = "Hsipaw"
# bt[1] = "Siggai"
bt = ceetee.copy() # by value
bt[0] = "Hsipaw"
print(bt)
print(ceetee) |
name = "Mg Mg"
age = 20
bol = name == "Mg Mg" and age == 20
bol = name == "Aung Aung" or age == 21
bol = not(name == "Mg Mg")
print(bol)
"""
and
-> operator true if only left and right value are true
ro
-> operator true if one/both of the left or right value is true
not
-> reverse the value
""" |
def avg(arr): # the function that finds the average of the even indices elements
total = 0 # this variable finds the total of the elements at even indices only
divisor = 0 # this variable counts the number of even indices
for i in range(len(arr)): # a loop that goes from 0 to the length of the array
if i % 2 == 0: # checks if the index is even or not
total += arr[i] # if the index is even, the value at that index is added to the total variable
divisor += 1 # the divisor is incremented by 1
average = total / divisor # the average is found by dividing the total by the divisor found out
return average # average is returned back
def main(): # main function to call above function
A = [] # a list or array is declared
A.append(12) # element added to list A
A.append(45) # element added to list A
A.append(4) # element added to list A
A.append(-98) # element added to list A
val = avg(A) # average function is called to give the avg at the even indices only
print(val) # value which is the avg is printed. In this case it is, A[0] + A[2] / 2 = (12 + 4) / 2 = 8.0
main() # calling the main function |
import random
def coinToss():
number = int(input("How many coin tosses? "))
heads = 0
tails = 0
toss = 0
for x in range(number):
toss = random.randint(0,1)
if toss == 0:
heads += 1
else:
tails += 1
print("Heads: {}".format(heads))
print("Tails: {}".format(tails))
|
import tkinter as tk
def decalage(lettre_message):
a=ord(lettre_message)
if (a > 90 and 97 > a) or 65 > a :
return chr(ord(lettre_message) + 0)
elif a > 122 or (97 > a and a > 90) :
return chr(ord(lettre_message) + 0)
if a == 90 :
return chr(ord('A'))
if a == 122 :
return chr(ord('a'))
else :
return chr(ord(lettre_message) + 1)
def dec_texte(texte):
texte_code = ""
t= 0
while len(texte_code) < len(texte):
texte_code += decalage(texte[t])
t = t + 1
return texte_code
def chiffre():
resultat.delete(0, tk.END)
resultat.insert(0, dec_texte(entree_texte.get()))
racine=tk.Tk()
racine.title("Cryptographie")
entree_texte = tk.Entry(racine, width = 50, font = ("helvetica", "20"))
entree_texte.grid(row = 0, column = 0)
label_texte = tk.Label(racine,font = ("helvetica", "20"), text = "Entrer le message ici.")
label_texte.grid(row = 0, column = 1)
bouton_coder=tk.Button(racine, text="Chiffrer texte",fg="black", width=15, command=chiffre)
bouton_coder.grid(row=2, column=0)
resultat=tk.Entry(racine,width = 50, font = ("helvetica", "20"))
resultat.grid(row=3,column=0)
label_res=tk.Label(racine,font = ("helvetica", "20"), text="Déchiffement ici.")
label_res.grid(row = 3, column=1)
racine.mainloop() |
from pymongo import MongoClient
# Establishing a connection
client = MongoClient() # connects to localhost by default
db = client["test"]
# Verifying connection to MongoDB
print("Total number of documents in the 'titanic' collection: ", db.titanic.count_documents({}))
print(db.titanic.find_one())
# Filtering
print("\n----------------Filtering--------------------")
# The most compelling question when it comes to Titanic - How many survivors?
print(db.titanic.count_documents({"survived":1}))
print(db.titanic.count_documents({"age":{"$lt":18}}))
print(db.titanic.count_documents({"$and":[{"survived":1}, {"age":{"$lt":18}}]}))
print(db.titanic.count_documents({"name":{"$regex":"Mrs"}}))
# Unlike relational databases, presence isn't compulsory in MongoDB.
# There's a filter to check for presence.
# Do all passengers have a ticket_number?
print(db.titanic.count_documents({"ticket_number":{"$exists":False}}))
# Distinct values
print("\n--------------Distinct Values----------------")
print(db.titanic.distinct("point_of_embarkation"))
print(db.titanic.distinct("class", {"fare_paid":0}))
# Projections
print("\n----------------Projections------------------")
# Counting documents is straightforward but on using the find() method, a cursor is returned.
print(db.titanic.find({"parents_children":{"$gte":5}}))
# We can send the cursor over to a list and slice the list to limit the results
print(list(db.titanic.find({"parents_children":{"$gte":5}}))[:3])
# This cursor can also be iterated over using a loop
from pprint import pprint
for doc in db.titanic.find({"parents_children":{"$gte":5}}):
pprint(doc)
# How do we limit the fields that we see in the results?
for doc in db.titanic.find({"parents_children":{"$gte":5}}, {"name":1, "age":1, "_id":0}):
print(doc)
# If we aren't excluding any fields in our projections, pymongo accepts another simpler format.
for doc in db.titanic.find({"parents_children":{"$gte":5}}, ["name", "age"]):
print(doc)
# Writing the above code in a single line using list comprehension
[print(doc) for doc in db.titanic.find({"parents_children":{"$gte":5}}, ["name", "age"])]
# Python's use in dealing with iterables like cursors and MongoDB's projection can be used to
# slim down the documents returned. Togther, they make for powerful querying!
# Sorting
print("\n----------------Sorting------------------")
for doc in db.titanic.find({"age":{"$lt":18}}, sort = [("class", 1)]):
print(doc["class"], doc["survived"])
for doc in db.titanic.find({"age":{"$lt":18}}, sort = [("class", 1), ("gender", 1)]):
print(doc["class"], doc["gender"], doc["survived"])
# Sorting in the Mongo shell is slightly different. Instead of tuples, they have to be entered
# as key-value pairs. Eg: {"class":1, "gender":1}
# Limiting and Skipping
print("\n------------Limiting & Skipping---------------")
for doc in db.titanic.find({"parents_children":{"$gte":5}}, skip = 3, limit = 3):
print("{name}: {survived}".format(**doc))
# Aggregation Pipeline
print("\n------------Aggregation Pipeline---------------")
print(db.titanic.count_documents({"age":{"$gte":70}}))
from collections import OrderedDict
cursor = db.titanic.aggregate([ \
{"$match":{"age":{"$gte":70}}}, \
{"$project":{"class":1, "gender":1, "survived":1}}, \
{"$sort":OrderedDict([("class", 1), ("gender", 1)])}, \
{"$limit":5}])
for doc in cursor:
print(doc["class"], doc["gender"], doc["survived"])
# Importing data into a dataframe
print("\n------------Importing into DataFrame---------------")
import pandas as pd
df = pd.DataFrame(list(db.titanic.find()))
print(df.info())
print(df.head())
# In a dataframe, blank/missing values are automatically assigned NaN. But empty strings can exist
# which would need to be replaced
assert df.iloc[1,2] == "" # asserting that an empty string exists
import numpy as np
df = df.replace("",np.nan)
print(df.info())
print(df.head())
# Data visualization
print("\n-------------Data visualization--------------")
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='darkgrid')
sns.catplot('class', 'survived', data=df, kind='point', hue='gender')
# sns.lmplot('age', 'survived', data=df)
# df.plot(x='age', y='class', kind='scatter')
plt.title('Titanic Survivors')
plt.show()
# # Display the box plots on 3 separate rows and 1 column
# fig, axes = plt.subplots(nrows=3, ncols=1)
# # Generate a box plot of the fare prices for the First passenger class
# titanic.loc[titanic['pclass'] == 1].plot(ax=axes[0], y='fare', kind='box')
# # Generate a box plot of the fare prices for the Second passenger class
# titanic.loc[titanic['pclass'] == 2].plot(ax=axes[1], y='fare', kind='box')
# # Generate a box plot of the fare prices for the Third passenger class
# titanic.loc[titanic['pclass'] == 3].plot(ax=axes[2], y='fare', kind='box')
# # Display the plot
# plt.show()
|
import math
import sys
'''
a "Weber Street" (2,-1) (2,2) (5,5) (5,6) (3,8)
a "King Street S" (4,2) (4,8)
a "Davenport Road" (1,4) (5,8)
g
'''
street = []
st_name = [] #to save all the unique street names
#vertices = []
coords = {} #Dictionary of {street name:2-d Coordinates}
EDGES = [] #list of all the edges
V = [] #Global list of vertices
V_DICT = {}
LINE_INERSECT = []
E = [] #global list of all the edges
E_FINAL = []
def print_dictionary(coords):
print("############ Printing the global dictionary ############")
for x in coords:
print (x,':',coords[x])
def str_2_coord(str_n):
str_lst = str_n.split(',')
#print("\n~~~~~~~~~~~~ str_lst i,j = "+str_lst[0][1:]+" , "+str_lst[1][:-1])
i = int(str_lst[0][1:])
j = int(str_lst[1][:-1])
return i,j
def coords_2_list(vertices):
coords = []
for j in range(0, len(vertices)):
i_list, j_list = str_2_coord(vertices[j])
coords.append([i_list, j_list])
#print(vertices[j])
return coords
def add_street(street_name, vertices):
print("-----------------adding street to global Dictionary-------------------")
coords[street_name] = coords_2_list(vertices)
#print(coords)
print("calling print_dictionary")
#print_dictionary(coords)
def remove_street(street_name):
#print("----------------Removing street name of global Dictionary---------------")
if street_name in coords:
#print("Removing the street")
del coords [street_name]
else:
sys.stderr.write("Error: Street not present in data base so can't remove it")
#print("Error: Street not present in data base so can't remove it")
#print_dictionary(coords)
def change_street(street_name, vertices):
print("----------------Changing street name of global Dictionary---------------")
if street_name in coords:
#print("Changing data base of street")
coords[street_name] = coords_2_list(vertices)
else:
sys.stderr.write("Error: Street not present in data base so can't change it")
#print_dictionary(coords)
def find_intersection_of_collinear_lines(c1, c2, c3, c4):
print("Finding the intersection of colinear point")
x1, y1 = c1[0], c1[1]
x2, y2 = c2[0], c2[1]
p1, q1 = c3[0], c3[1]
p2, q2 = c4[0], c4[1]
lst = [c1, c2, c3, c4]
unique_list1 = unique_list(lst)
line_lst1 = []
for i in range(0, len(unique_list1)):
line_lst1.append([unique_list1[i][0],unique_list1[i][1], i])
if (line_lst1[0][0] == line_lst1[1][0]):
# means parallel to y-axis
sorted_list = sorted(line_lst1, key=lambda l:l[1])
else:
# means parallel to y-axis
sorted_list = sorted(line_lst1, key=lambda l:l[0])
print(sorted_list)
if(len(sorted_list)==2):
#add vertices and edges here
V.append([sorted_list[0][0],sorted_list[0][1]])
V.append([sorted_list[1][0],sorted_list[1][1]])
E.append([[sorted_list[0][0],sorted_list[0][1]],[sorted_list[1][0],sorted_list[1][1]]])
elif(len(sorted_list)==3):
V.append([sorted_list[0][0],sorted_list[0][1]])
V.append([sorted_list[1][0],sorted_list[1][1]])
V.append([sorted_list[2][0],sorted_list[2][1]])
E.append([[sorted_list[0][0],sorted_list[0][1]],[sorted_list[1][0],sorted_list[1][1]]])
E.append([[sorted_list[1][0],sorted_list[1][1]],[sorted_list[2][0],sorted_list[2][1]]])
elif(len(sorted_list)==4):
print("Unique_list1 with 4 elements = ", unique_list1)
if((sorted_list[0][2] + sorted_list[1][2])== 1 or (sorted_list[0][2] + sorted_list[1][2])== 5):
print("No intersection between lines")
else:
print("Printing Edges")
V.append([sorted_list[0][0],sorted_list[0][1]])
V.append([sorted_list[1][0],sorted_list[1][1]])
V.append([sorted_list[2][0],sorted_list[2][1]])
V.append([sorted_list[3][0],sorted_list[3][1]])
E.append([[sorted_list[0][0],sorted_list[0][1]],[sorted_list[1][0],sorted_list[1][1]]])
E.append([[sorted_list[1][0],sorted_list[1][1]],[sorted_list[2][0],sorted_list[2][1]]])
E.append([[sorted_list[2][0],sorted_list[2][1]],[sorted_list[3][0],sorted_list[3][1]]])
'''
if (x1 == x2 and p1 == x1):
# means parallel to y-axis
sorted_list = sorted(line_lst, key=lambda l:l[0])
else:
# means parallel to y-axis
sorted_list = sorted(line_lst, key=lambda l:l[1])
unique_list1 = unique_list(lst)
'''
def list_to_dict(v):
v_dict = {}
for i in range(0, len(v)):
v_dict[i] = v[i]
return v_dict
# function to get unique values
def unique_list (list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
return unique_list
def process_intersect_matrix():
#find number of times line is appearing in the matrix
#create a new list [line1, line2, I1, I2 .... In]
#print("*********Inside Process _intersect Matrix***********")
#print("Matrix of intersection")
#for i in range (0, len(LINE_INERSECT)):
# print(LINE_INERSECT[i])
list1 = []
unique_list1 = []
line_intersect_matrix = []
#element = LINE_INERSECT[0][0]
#print(element)
for i in range(0, len(LINE_INERSECT)):
element = LINE_INERSECT[i][0]
list1.append(element)
#print("printing list1", list1)
unique_list1 = unique_list(list1)
#print("printing unique_list", unique_list1)
list_index = -1
for i in range(0, len(unique_list1)):
primary_key = unique_list1[i]
init_count = 0
for j in range(0, len(LINE_INERSECT)):
if(primary_key == LINE_INERSECT[j][0]):
#Check if line is already there in the list then add only intersection
#Otherwise add line and intersection
#print("Primary Key Matched")
if (init_count == 0):
#print("Adding the element for the first time to matrix")
line_intersect_matrix.append(LINE_INERSECT[j])
#print("***********Print intersect matrix************")
#print(line_intersect_matrix)
init_count = init_count + 1
list_index = list_index + 1
else:
#for k in range(0, len(line_intersect_matrix)):
#if (init_count == 1):
#if(primary_key == line_intersect_matrix[k]):
#print("Adding intersect to the matrix")
element = LINE_INERSECT[j][2]
line_intersect_matrix[list_index].append(element)
#print("***********Print intersect matrix************")
#for k in range (0, len(line_intersect_matrix)):
# print(line_intersect_matrix[k])
#print("****************************")
#print("***********Print intersect matrix************")
#for k in range (0, len(line_intersect_matrix)):
# print(line_intersect_matrix[k])
#print("****************************")
return line_intersect_matrix
def find_intersection(c1, c2, c3, c4):
#print("In find intersection of 2 lines")
x1, y1 = c1[0], c1[1]
x2, y2 = c2[0], c2[1]
p1, q1 = c3[0], c3[1]
p2, q2 = c4[0], c4[1]
dx1 = x2 - x1
dy1 = y2 - y1
dx2 = p2 - p1
dy2 = q2 - q1
#print (x1, y1, x2, y2)
#print (p1, q1, p2, q2)
det = ((-dx1)*dy2) + (dy1*dx2)
#print('det, math.fabs(det)= ', det, math.fabs(det))
##if determinet is less than 0.00000001 then lines are parallel
if(math.fabs(det) < 0.00000001):
#print("colinear points")
#lines are parallel check if they are colinear
#check the slope of 2 lines
slope_d1 = y2 - y1
slope_n1 = x2 - x1
slope_n2 = p1 - x1
slope_d2 = q1 - y1
if((slope_n1 == 0 and slope_n2 == 0) or ((slope_d1/slope_n1) == (slope_d2/slope_n2))):
#print("lines are colinear and are parallel to Y-axis")
find_intersection_of_collinear_lines(c1, c2, c3, c4)
#elif((slope_n2 != 0 and slope_n2 == 0) or (slope_n2 == 0 and slope_n1 != 0)):
# print("lines are not colinear")
#elif((slope_d1/slope_n1) == (slope_d2/slope_n2)):
# print("lines are colinear")
# find_intersection_of_colinar_lines(c1, c2, c3, c4)
#else:
# print("lines are not colinear")
else:
#find intersection
det_inv = 1.0/det
m1 = det_inv*((-dy2)*(p1-x1) + (dx2)*(q1-y1))
m2 = det_inv*((-dy1)*(p1-x1) + (dx1)*(q1-y1))
int_x = (x1 + m1*dx1 + p1 + m2*dx2)/2.0
int_y = (y1 + m1*dy1 + q1 + m2*dy2)/2.0
if((int_x>= min(x1,x2)) and (int_x <= max(x1,x2)) and (int_x >= min(p1,p2)) and (int_x <= max(p1,p2)) \
and (int_y >= min(y1,y2)) and (int_y <= max(y1,y2)) and (int_y >= min(q1,q2)) and (int_y <= max(q1,q2))):
#need to update vertices
#print("intesection point is in range")
#append all the points of intersecting lines
#check if points exist in the List
if c1 not in V:
V.append(c1)
if c2 not in V:
V.append(c2)
if c3 not in V:
V.append(c3)
if c4 not in V:
V.append(c4)
if [int_x, int_y] not in V:
V.append([int_x, int_y])
#c5 = [int_x,int_y]
LINE_INERSECT.append([c1, c2, [int_x, int_y]])
LINE_INERSECT.append([c3, c4, [int_x, int_y]])
#print("~~intesection point of line is", int_x, int_y)
#process_intesect_matrix()
##############----------------------------
#def get_line_points(point_list_2d):
##############----------------------------
def find_vertices():
streets_list = list(coords.keys())
total_streets = len(streets_list)
for i in range (0, (total_streets-1)):
primary_key = streets_list[i]
for j in range (i + 1, (total_streets)):
secondary_key = streets_list[j]
primary_key_points = coords[primary_key]
for k in range (0, len(primary_key_points) -1):
c1 = primary_key_points[k]
c2 = primary_key_points[k+1]
#c1 c2 are primary_line points. Now for each of primary_line calculate all secondary lines
secondary_key_points = coords[secondary_key]
for l in range (0, len(secondary_key_points) -1):
c3 = secondary_key_points[l]
c4 = secondary_key_points[l+1]
#print(str('*')*50)
#print(c1, c2, c3, c4)
find_intersection(c1, c2, c3, c4)
#process_intesect_matrix()
def edges_for_multi_intersect_lines(unique_list1):
length = len(unique_list1)
distance_list = [];
x1 = unique_list1[0][0]
y1 = unique_list1[0][1]
for i in range(2, len(unique_list1)):
element = unique_list1[i]
x2 = element[0]
y2 = element[1]
d = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
distance_list.append([d, x2, y2])
#distance
#print(distance_list)
sorted_list = sorted(distance_list, key=lambda l:l[0])
#print("**print sorted distance Matrix**")
#print(sorted_list)
#create edge to the first point
E.append([unique_list1[0], [sorted_list[0][1], sorted_list[0][2]]])
for i in range(0, len(sorted_list) -1):
E.append([[sorted_list[i][1], sorted_list[i][2]], [sorted_list[i+1][1], sorted_list[i+1][2]]])
last_index = len(sorted_list) - 1
p1 = unique_list1[1][0]
q1 = unique_list1[1][1]
E.append([[sorted_list[last_index][1], sorted_list[last_index][2]],[p1, q1]])
#find the multiple entries of vertices in the edge list E
#E is global list of edges
def find_edges(line_intersect_matrix):
unique_list1 = []
for i in range (0, len(line_intersect_matrix)):
unique_list1 = unique_list(line_intersect_matrix[i])
#print(unique_list1)
if (len(unique_list1)> 3):
#find order of the points and find edge
#print("line has more than one intersection")
edges_for_multi_intersect_lines(unique_list1)
else:
#there are 3 points on the line so directly find the intersections
E.append([unique_list1[0], unique_list1[2]])
E.append([unique_list1[1], unique_list1[2]])
def are_points_equal(p1,p2):
result = False
if p1[0] == p2[0]:
#print('step1')
if p1[1] == p2[1]:
#print('step2')
result = True
return result
def get_key_V(value):
#print("inside get_keey_V...........")
#for key, val_ in V_DICT.items():
for i in range (0, len(V)):
#print('for...................key,val')
if are_points_equal(V[i],value):
#print('YESSSSSSSSSSSSS')
return i
def print_V(V_DICT):
print("V = {")
for i in range(0, len(V_DICT)):
print("\t"+str(i)+":\t("+str(round(V_DICT[i][0],2))+","+str(round(V_DICT[i][1],2))+")")
print("}")
def print_E(E):
print("E = {")
for i in range(0, len(E)-1):
print("\t<"+str(E[i][0])+","+str(E[i][1])+">,")
if(len(E)>0):
print("\t<"+str(E[int(len(E)-1)][0])+","+str(E[int(len(E)-1)][1])+">")
print("}")
def proper_edges(E):
for i in range(0,len(E)):
k1 = get_key_V(E[i][0])
k2 = get_key_V(E[i][1])
E_FINAL.append([k1,k2])
print_E(E_FINAL)
def create_graph():
#print("--------------- Create Graph ------------------")
#find_vertices
#add all the coords to V
find_vertices()
V_DICT = list_to_dict(V)
print_V(V_DICT)
#finding edges
#print("--------------Finding Edges--------------------")
line_intersect_matrix = process_intersect_matrix()
find_edges(line_intersect_matrix)
#for i in range(0, len(E)):
# print(E[i])
proper_edges(E)
def process_input_data(line):
#check for correct code
#check count("(") == count(")")
code = line[0]
line = line[1:]
if line.count("(") != line.count(")"):
sys.stderr.write("Error: Incorrect input format")
return False
if code not in ['a', 'r', 'c', 'g']:
sys.stderr.write("ERROR::Not a valid input")
return False
#check for non-redundant street name
if code in ['a','c','r']:
st_name_temp = line[line.find("\"")+1:line.rfind("\"")].lower()
if ((st_name_temp=='') or (line.count("\"") != 2)):
sys.stderr.write("ERROR::Not a valid input")
return False
if code=='a':
if st_name_temp not in st_name:
st_name.append(st_name_temp)
else:
sys.stderr.write("ERROR::redundant street name")
return False
#check for coordinates properly given
if code in ['a','c']:
st_coords = []
line = line[line.find("("):]
while (line.count(")") != 0):
st_coord = line[line.find("(")+1:line.find(")")].split(",")
st_coord[0] = float(st_coord[0])
st_coord[1] = float(st_coord[1])
line = line[line.find(")")+1:]
st_coords.append(st_coord)
if(code=='a'):
coords[st_name_temp] = st_coords
else:
if st_name_temp not in st_name:
sys.stderr.write("Error: 'c' or 'r' specified for a street that does not exist.")
else:
coords[st_name_temp] = st_coords
elif(code == 'r'):
remove_street(st_name_temp)
elif code == 'g':
if(len(st_name)<=0):
sys.stderr.write("ERROR::Not a valid input.")
sys.exit(0)
else:
#print("Print graph")
create_graph()
def main():
### YOUR MAIN CODE GOES HERE
### sample code to read from stdin.
### make sure to remove all spurious print statements as required
### by the assignment
while True:
line = sys.stdin.readline()
#print(line=='\n')
if line == '':
break
print('read a line:', line)
success = process_input_data(line)
#if(success):
print('Finished reading input')
# return exit code 0 on successful termination
sys.exit(0)
if __name__ == '__main__':
main()
'''
find_intersection_of_collinear_lines([1,1], [2,2], [3,3], [4,4])
find_intersection_of_collinear_lines([1,1], [2,2], [2,2], [4,4])
find_intersection_of_collinear_lines([1,1], [3,3], [2,2], [4,4])
find_intersection_of_collinear_lines([4,4], [3,3], [2,2], [4,4])
a "Weber Street" (2,-1) (2,2) (5,5) (5,6) (3,8)
a "King Street S" (4,2) (4,8)
a "Davenport Road" (1,4) (5,8)
g
'''
|
def fat(valor):
resultado = 1
while valor > 1:
resultado = resultado * valor
valor-= 1
print(resultado if valor > 0 and valor == int(valor) else -1)
fat(int(input("Fatorial: "))) |
# Import dependencies
import numpy as np
import random
import operator
import pandas as pd
import matplotlib.pyplot as plt
# Part of python's Data Model
# Objects are python's abstraction of data and way to interact with other data
# Create City class
class City:
# Double under or dunder methods are pre existing methods in python classes like init
# These allow you to simulate the behaviour of built in types such as to string or len
def __init__(self, x, y): # init function automatically runs on initializing an object in this class and can replace 'self' with others also
self.x = x
self.y = y
# Object method to be called upon an object of this class
def distance(self, city):
xDis = abs(self.x - city.x)
yDis = abs(self.y - city.y)
distance = np.sqrt((xDis**2) + (yDis**2))
return distance
# Default print method in python for classes is unsatisfactory
# Use either repr for object representation or str
# Default inspection of object calls upon repr and the output is supposed to be unambiguous
def __repr__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
# str objective is to be readable
# Create fitness class as inverse of route distance
class Fitness:
def __init__(self, route):
self.route = route
self.distance = 0
self.fitness = 0.0
def routeDistance(self):
if self.distance == 0:
pathDistance = 0
for i in range(0, len(self.route)):
fromCity = self.route[i]
toCity = None
if i+1 < len(self.route):
toCity = self.route[i + 1]
else:
toCity = self.route[0]
pathDistance += fromCity.distance(toCity)
self.distance = pathDistance
return self.distance
def routeFitness(self):
if self.fitness == 0:
self.fitness = 1/float(self.routeDistance())
return self.fitness
# Create population which consists of multiple possible routes
# Create one object in the population
def createRoute(cityList):
route = random.sample(cityList, len(cityList))
return route
# Create the initial population
def initialPopulation(popSize, cityList):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList))
return population
# Determine fitness
def rankRoutes(population):
fitnessResults = {}
for i in range(0, len(population)):
# Creates key pair with i and the fitness score
fitnessResults[i] = Fitness(population[i]).routeFitness()
# Items returns tuples from dictionary
return sorted(fitnessResults.items(), key=operator.itemgetter(1), reverse=True)
# key needs a function and not value to apply on the inputs, itemgetter return the nth element from the input tuple or list; lambda can work just as well
# Python treats functions as first class citizens, they can be passed onto other functions as arguments or stored in variables
# Callable are objects that indicate if something can be called
# Selecting mating pool
# Two ways to do it
# 1. Fitness Proportionate Selection
# Fitness of each individual relative to population is used to assign a probability of selection(roulette wheel)
# 2. Tournament Selection
# A set number of population is randomly selected and the one with the highest fitness is selected as parent and repeated with second set
# Also use elitism which ensure best performing individuals will automatically carry over
def selection(popRanked, eliteSize):
selectionResults = []
df = pd.DataFrame(np.array(popRanked), columns=["Index", "Fitness"])
df['cum_sum'] = df.Fitness.cumsum()
df['cum_perc'] = 100*df.cum_sum/df.Fitness.sum()
for i in range(0, eliteSize):
selectionResults.append(popRanked[i][0])
for i in range(0, len(popRanked) - eliteSize):
pick = 100*random.random()
for i in range(0, len(popRanked)):
# iat is to access a single value by integer position, at for single value by label pair
if pick <= df.iat[i, 3]:
selectionResults.append(popRanked[i][0])
break
return selectionResults
# With the ids for mating pool extract the selected individuals
def matingPool(population, selectionResults):
matingpool = []
for i in range(0, len(selectionResults)):
index = selectionResults[i]
matingpool.append(population[index])
return matingpool
# Breeding
# Usually its 1/0, but in our case as all cities need to be included we will do an ordered crossover ensuring no repeated cities in routes
def breed(parent1, parent2):
child = []
childP1 = []
childP2 = []
geneA = int(random.random() * len(parent1))
geneB = int(random.random() * len(parent2))
startGene = min(geneA, geneB)
endGene = max(geneA, geneB)
for i in range(startGene, endGene):
childP1.append(parent1[i])
childP2 = [item for item in parent2 if item not in childP1]
#child = childP1 + childP2
# Edit based on comment
child = childP2[:startGene] + childP1 + childP2[startGene:]
return child
def breedPopulation(matingpool, eliteSize):
children = []
length = len(matingpool) - eliteSize
pool = random.sample(matingpool, len(matingpool))
for i in range(0, eliteSize):
children.append(matingpool[i])
for i in range(0, length):
child = breed(pool[i], pool[len(matingpool) - i - 1])
children.append(child)
return children
# Mutation
# Again its usually random swapping but here it will be swapping two cities randomly
def mutate(individual, mutationRate):
for swapped in range(len(individual)):
if(random.random() < mutationRate):
swapWith = int(random.random() * len(individual))
city1 = individual[swapped]
city2 = individual[swapWith]
individual[swapped] = city2
individual[swapWith] = city1
return individual
def mutatePopulation(population, mutationRate):
mutatedPop = []
for ind in range(0, len(population)):
mutatedInd = mutate(population[ind], mutationRate)
mutatedPop.append(mutatedInd)
return mutatedPop
# Repeat the whole process
def nextGeneration(currentGen, eliteSize, mutationRate):
popRanked = rankRoutes(currentGen)
selectionResults = selection(popRanked, eliteSize)
matingpool = matingPool(currentGen, selectionResults)
children = breedPopulation(matingpool, eliteSize)
nextGeneration = mutatePopulation(children, mutationRate)
return nextGeneration
#Evolution in motion
def geneticAlgorithm(population, popSize, eliteSize, mutationRate, generations):
pop = initialPopulation(popSize, population)
progress = []
print("Initial distance: " + str(1 / rankRoutes(pop)[0][1]))
for i in range(0, generations):
pop = nextGeneration(pop, eliteSize, mutationRate)
progress.append(1 / rankRoutes(pop)[0][1])
plt.plot(progress)
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.show()
print("Final distance: " + str(1 / rankRoutes(pop)[0][1]))
bestRouteIndex = rankRoutes(pop)[0][0]
bestRoute = pop[bestRouteIndex]
return bestRoute
# Running the GA
cityList = []
for i in range(0, 25):
cityList.append(City(x=int(random.random() * 200),
y=int(random.random() * 200)))
geneticAlgorithm(population=cityList, popSize=100,
eliteSize=20, mutationRate=0.01, generations=500)
|
# simple function
def my_function():
print("Hello From My Function!")
# my_function()
# function with argument
def my_function_with_args(username, greeting="Halo"):
print("Hello, %s , From My Function!, I wish you %s" % (
username, greeting)
)
# my_function_with_args("Mahrus", "JADI BARU")
# function with return value
def sum_two_numbers(a, b):
return a + b
# function with *args
def sum_numbers(*args):
print("args value: {}".format(args))
print("Type %s: " % (type(args)))
sum = 0
for i in args:
sum += i if type(i) is not str else 0
return sum
sum = sum_numbers(1,2,3,4)
# # sum = sum_numbers([1,2,3,4], (4,5), 3423)
# print(sum)
# function with *kwargs
def example_kwargs(**kwargs):
print("kwargs value: {}".format(kwargs))
print("Type: %s" % (type(kwargs)))
for key, item in kwargs.items():
print("Key: %s, Item: %s" % (key, item))
# example_kwargs(
# one="Satu",
# two="Dua",
# three="Tiga",
# four="Empat",
# five="Lima"
# )
def contoh(bahasa, *args, **kwargs):
print(bahasa)
print(args)
print(kwargs)
# contoh("Indonesia",4,5, nama="Mahrus", asal="Malang")
'''
EXERCISE
In this exercise you'll use an existing function,
and while adding your own to create a fully functional program.
Add a function named list_benefits()
that returns the following list of strings:
"More organized code",
"More readable code",
"Easier code reuse",
"Allowing programmers to share and connect code together"
Add a function named build_sentence(info)
which receives a single argument containing a string
and returns a sentence starting with the given string
and ending with the string " is a benefit of functions!"
Run and see all the functions work together!
'''
# # Modify this function to return a list of strings as defined above
def list_benefits():
return [
"More organized code",
"More readable code",
"Easier code reuse",
"Allowing programmers to share and connect code together"
]
# # Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
# is a benefit of functions
return benefit + "is a benefit of functions"
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
# name_the_benefits_of_functions()
datas = [
{'name': 'Mahrus', 'learn': 'python'},
{'name': 'Hadi', 'learn': 'php'},
{'name': 'Dani', 'learn': 'python'},
{'name': 'Ika', 'learn': 'java'},
{'name': 'Deni', 'learn': 'java'},
{'name': 'Dewi', 'learn': 'python'},
{'name': 'Rina', 'learn': 'php'},
{'name': 'Rina', 'learn': 'android'},
]
def grouping(datas):
new_data = {}
for data in datas:
if data['learn'] in new_data:
new_data[data['learn']].append(data)
else:
new_data[data['learn']] = [data]
print(new_data)
def searching(param, datas):
# new_data = []
# for data in datas:
# if data['learn'] == param:
# new_data.append(data)
new_data = [data for data in datas if data['learn'] == param]
return new_data
a = searching('python', datas)
print(a)
# grouping(datas)
# data2 = {
# 'python': [
# {'name': 'Mahrus', 'learn': 'python'},
# {'name': 'Dani', 'learn': 'python'}
# ],
# 'php': [],
# 'java': []
# }
|
import turtle
def random_fractal(t, x):
if ( x < 3 ):
t.fd(x)
return
else:
random_fractal(t, int(x/3))
t.lt(90)
random_fractal(t, int(x/3))
t.rt(90)
random_fractal(t, int(x/3))
t.lt(90)
random_fractal(t, int(x/3))
t.rt(90)
random_fractal(t, int(x/3))
bob = turtle.Turtle()
random_fractal(bob, 300)
|
import unittest
from main import to_upper
class MyTestCase(unittest.TestCase):
def test_to_upper(self):
name = "Shubham"
upper_name = to_upper(name)
self.assertEqual(upper_name, "SHUBHAM")
if __name__ == '__main__':
unittest.main()
|
# The goal of the agent is to navigate a frozen lake and find the Goal without falling through the ice the
# Using the Q-learning algorithm
import gym
import numpy as np
import matplotlib.pyplot as plt
env = gym.make('FrozenLake-v0') # environment
RENDER = False # Visualise training
STATES = env.observation_space.n # n of states
ACTIONS = env.action_space.n # up, down, right, left
Q = np.zeros((STATES, ACTIONS)) # Q table (matrix) with all 0 values - Random actions at the beginning of the training
EPISODES = 5000 # n of times running the env
MAX_STEPS = 100 # max n of steps allowed for each run of env. Could be stuck in a loop.
LEARNING_RATE = 0.81 # High - each update will introduce a large change to the current state-action value, Low - subtle
GAMMA = 0.96 # Discount factor - how much importance is put on the current and future reward
epsilon = 0.9 # start with a 90% chance of picking a random action
rewards = []
for episode in range(EPISODES):
state = env.reset()
for _ in range(MAX_STEPS):
if RENDER:
env.render()
# Randomly picking a valid action
if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample() # take random action
else:
action = np.argmax(Q[state, :]) # use Q table to pick the action with MAX value
next_state, reward, done, _ = env.step(action) # takes the action and returns values about it
# Q-learning algorithm - Using the current Q-Table to find the best action.
Q[state, action] = Q[state, action] + LEARNING_RATE * (reward + GAMMA * np.max(Q[next_state, :]) - Q[state, action])
state = next_state
if done:
rewards.append(reward)
epsilon -= 0.001 # Increasing the chance of using the trained Q table
break # reached goal
print(Q)
print(f"Average reward: {sum(rewards) / len(rewards)}:")
#%% lot the training progress and see how the agent improved over n of episodes
def get_average(values):
return sum(values)/len(values)
avg_rewards = []
for i in range(0, len(rewards), 100):
avg_rewards.append(get_average(rewards[i:i+100])) # from i to i+100
plt.plot(avg_rewards)
plt.ylabel('average reward')
plt.xlabel('episodes (100\'s)')
plt.show()
|
doc_list = ['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?']
keyword = 'casino'
response = []
for sentence in doc_list:
is_contained = False
word_list = sentence.strip().lower().split()
print(word_list)
for word in word_list:
if word == keyword.lower():
print("haitta")
is_contained = True
print(is_contained)
if is_contained == True:
response.append(doc_list.index(sentence))
print(response)
|
N = int(input())
dishes = [int(input()) for _ in range(N)]
dishes.reverse()
for i in range(N):
if dishes[i] > dishes[i + 1]:
print(dishes[i + 1])
break
else:
continue
|
A = input()
answer = ""
if A == "a":
answer = -1
elif len(A) == 1:
answer = "a"
else:
for i in range(len(A)-1):
answer += A[i]
print(answer)
|
#
# Tile 0, 1, X or W
#
TILE_TYPE = dict(EMPTY = 0, SHIP_HULL = 1, HIT = 2, MISS = 3, HIDDEN = 4)
class Tile(object):
'''One tile'''
#constructor
def __init__(self, type):
if type == TILE_TYPE['EMPTY']:
self.__m_type = ('0', TILE_TYPE['EMPTY'])
elif type == TILE_TYPE['SHIP_HULL']:
self.__m_type = ('1', TILE_TYPE['SHIP_HULL'])
elif type == TILE_TYPE['HIT']:
self.__m_type = ('X', TILE_TYPE['HIT'])
elif getType == TILE_TYPE['MISS']:
self.__m_type = ('W', TILE_TYPE['MISS'])
elif getType == TILE_TYPE['HIDDEN']:
self.__m_type = ('0', TILE_TYPE['HIDDEN'])
#rep for print
def __str__(self):
rep = ""
if self.getType == TILE_TYPE['EMPTY']:
rep = "0"
elif self.getType == TILE_TYPE['SHIP_HULL']:
rep = "1"
elif self.getType == TILE_TYPE['HIT']:
rep = "X"
elif self.getType == TILE_TYPE['MISS']:
rep = "W"
elif self.getType == TILE_TYPE['HIDDEN']:
rep = "0"
return rep
#sets
def setTile(self, type):
if type == TILE_TYPE['EMPTY']:
self.__m_type = ('0', TILE_TYPE['EMPTY'])
elif type == TILE_TYPE['SHIP_HULL']:
self.__m_type = ('1', TILE_TYPE['SHIP_HULL'])
elif type == TILE_TYPE['HIT']:
self.__m_type = ('X', TILE_TYPE['HIT'])
elif type == TILE_TYPE['MISS']:
self.__m_type = ('W', TILE_TYPE['MISS'])
elif type == TILE_TYPE['HIDDEN']:
self.__m_type = ('0', TILE_TYPE['HIDDEN'])
#gets
@property
def getType(self):
return self.__m_type;
|
# There're some illegal cases, it's unfair
import re
class Solution:
# Define the precedence of operators
__pre = {}
__fun = {}
def __init__(self):
pre_count = -1
self.__pre['('] = pre_count
pre_count += 1
self.__pre['+'] = pre_count
self.__pre['-'] = pre_count
pre_count += 1
self.__pre['*'] = pre_count
self.__pre['/'] = pre_count
self.__pre['%'] = pre_count
pre_count += 1
self.__fun['+'] = lambda x, y: x + y
self.__fun['-'] = lambda x, y: x - y
self.__fun['*'] = lambda x, y: x * y
self.__fun['/'] = lambda x, y: x / y
self.__fun['%'] = lambda x, y: x % y
# @param expression: a list of strings;
# @return: an integer
def evaluateExpression(self, expression):
if (len(expression) == 0):
return 0
num = []
op = []
for token in expression:
if re.match(r'[+\-]?\d+', token):
num.append(int(token))
elif token == '(':
op.append(token)
elif token == ')':
while op[-1] != '(':
self.__calculate(num, op)
op.pop()
else:
while len(op) > 0 and self.__pre[op[-1]] >= self.__pre[token]:
self.__calculate(num, op)
op.append(token)
while len(op) > 0:
self.__calculate(num, op)
return num.pop() if len(num) > 0 else 0
def __calculate(self, num, op):
n2 = num.pop()
n1 = num.pop()
single_op = op.pop()
num.append(self.__fun[single_op](n1, n2))
|
''' PyPoll Solution
Author: Surabhi Mukati
Notes: This script expects the data called election_data.csv to be in a Resources folder.
Purpose: This script calculates the total number of votes cast, a complete list of candidates who received votes,
the percentage of votes each candidate won, the total number of votes each candidate won and the winner of the election based on popular vote.
'''
import os
import csv
num_votes = [0,0,0,0]
total_votes = 0
unique_list = []
# Define the file path and read it line by line
csvpath = os.path.join("..","Resources","election_data.csv")
with open(csvpath,"r") as f:
next(f)
freader = csv.reader(f, delimiter = ",")
# For each row determine whether the candidate name is already on a unique list,
# if not, add the name to the unique list. Also, when the candidate from unique list is found
# then aggregate the number of votes
for row in freader:
candidate_name = row[2]
if candidate_name not in unique_list:
unique_list.append(candidate_name)
for i in range(len(unique_list)):
if unique_list[i] == candidate_name:
num_votes[i] += 1
total_votes += 1
# Display the formatted results on the terminal
print("Election Results")
print("-------------------------")
print(f"Total Votes: {total_votes}")
print("-------------------------")
for i in range(len(unique_list)):
print(f"{unique_list[i]}: {(num_votes[i]/total_votes):.3%} ({num_votes[i]})")
if num_votes[i] == max(num_votes):
winner = unique_list[i]
print("-------------------------")
print(f"Winner: {winner}")
print("-------------------------")
# store the results in a text file
txtpath = os.path.join("..","Resources","election_results.txt")
with open(txtpath, 'w') as txtfile:
txtfile.write("Election Results \n")
txtfile.write("------------------------- \n")
txtfile.write(f"Total Votes: {total_votes} \n")
txtfile.write("------------------------- \n")
for i in range(len(unique_list)):
txtfile.write(f"{unique_list[i]}: {(num_votes[i]/total_votes):.3%} ({num_votes[i]}) \n")
txtfile.write("------------------------- \n")
txtfile.write(f"Winner: {winner} \n")
txtfile.write("-------------------------")
|
x = ('Glen', 'Sally', 'Joseph')
print(x[2])
y = (1, 9 , 2)
print(y)
print(max(y))
for iter in y:
print(iter) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.