text
stringlengths
37
1.41M
#Familiarizing text editor,IDE,code analysis tools. print("Enter your address") n=input("Enter your name : ") hname=input("Enter your house name : ") p=input("Enter your place : ") pin=int(input("Enter your pincode: ")) d=input("Enter your district : ") print("Address details :") print("Name :",n) print("Housename :",hname) print("Place : ",p) print("pincode : ",pin) print("District : ",d)
#Program to find the factorial of a number a=int(input("Enter the number:")) fact=1 for x in range(1,a+1): fact=fact*x print("The factorial",fact)
#Generate a list of four digit numbers in a given range with all their digits even and the number is a perfect square. a=int(input("Enter the lower digit:")) b=int(input("Enter the upper digit:")) import random print(random.randint(a,b)) c=[] c=[x for x in range(a,b)if(int(x**0.5)**2==x and int(x%2==0))] print(c)
#List of color names entered by user and display first and last color c=[] x=int(input("Enter limit: ")) for i in range(1,x+1): a=input() c.append(a) print(c) print(c[0],c[-1])
#Program to check whether a number is positive or negative a=int(input("Enter the number:")) if a>0: print("The given number is positive") elif a==0: print("The given number is zero") elif a<0: print("The given number is negative")
#Program to check whether the given number is palindrome or not a=int(input("Enter the number:")) temp=a rev=0 while a > 0: d=a%10 rev=rev*10+d a//=10 if temp==rev: print("The given number is Palindrome") else: print("The given number is not palindrome")
class BinarySearch(list): def __init__(self,a,b): self.a = a # a is length of ist to be created self.b = b # b is the step between consequtive numbers self.li = [i for i in range(b,a+1)] self.length = len(self.li) def search(self,item): self.count =0 self.index = 0 self.first = 0 self.last = len(li)-1 self.found = False while self.first <= self.last and not found: self.count+=1 midpoint = (self.first + self.last)//2 if li[midpoint] == self.item: self.found = True else: if item < self.li[midpoint]: self.last = midpoint-1 else: self.first = midpoint+1 return dict([(self.count,self.li.index(found))])
def remove_parentheses(s): level = {s} while True: res = [] for cur in level: if is_valid(cur): res.append(cur) if res: return res new_level = set() for cur in level: for i in range(len(cur)): new_level.add(cur[:i] + cur[i+1:]) level = new_level def is_valid(s): cnt = 0 for c in s: if c == '(': cnt += 1 elif c == ')': if cnt == 0: return False else: cnt -= 1 return cnt == 0
def max_swap(num): digits = list(str(num)) res = 0 for i in range(len(digits)-1): for j in range(i+1, len(digits)): c_digits = digits[:] c_digits[i], c_digits[j] = c_digits[j], c_digits[i] if int("".join(c_digits)) > res: res = int("".join(c_digits)) return num
from typing import List from collections import defaultdict from queue import Queue class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: positions = defaultdict(list) self._dfs(root, x=0, y=0, positions=positions) res = [] for _, vals in sorted(positions.items()): res.append([val for _, val in sorted( vals, key=lambda x: (-x[0], x[1]))]) return res def _dfs(self, root, x, y, positions): if not root: return positions[x].append((y, root.val)) self._dfs(root.left, x-1, y-1, positions) self._dfs(root.right, x+1, y-1, positions) class Solution2: """ BFS method """ def vertical_traversal(self, root): q = Queue() q.put((root, 0, 0)) positions = defaultdict(list) while not q.empty(): cur, x, y = q.get() positions[x].append((y, cur.val)) if cur.left: q.put((cur.left, x-1, y-1)) if cur.right: q.put((cur.right, x+1, y-1)) res = [] for _, vals in sorted(positions.items()): res.append([val for _, val in sorted( vals, key=lambda x: (-x[0], x[1]))]) return res """ 3 / \ 9 20 / \ 15 7 dfs(3, 0, 0, {}) {0: [(0, 3)]} dfs(9, -1, -1, pos) {0: [(0, 3)], -1: [(-1, 9)]} 9 done dfs(20, 1, -1, pos) {0: [(0, 3)], -1: [(-1, 9)], 1: [(-1, 20)]} dfs(15, 0, -2, pos) {0: [(0, 3), (-2, 15)], -1: [(-1, 9)], 1: [(-1, 20)]} 15 done dfs(7, 2, -2, pos) {0: [(0, 3), (-2, 15)], -1: [(-1, 9)], 1: [(-1, 20)], 2: [(-2, 7)]} 7 done 20 done 3 done """
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def rob(self, root): cache = {} return self._rob(root, cache) def _rob(self, root: TreeNode, cache) -> int: """ The definition of this function is the maximum value when rob from the root. There are two cases based if the root is robbed. 1. root is robbed, the result = root.val + root's grandchild if they exist. 2. root is not robbed, the result = root's children's rob value. The final result the maximum of these two. """ if not root: return 0 if root in cache: return cache[root] c1 = self._rob(root.left, cache) + self._rob(root.right, cache) c2 = root.val if root.left: c2 += self._rob(root.left.left, cache) c2 += self._rob(root.left.right, cache) if root.right: c2 += self._rob(root.right.right, cache) c2 += self._rob(root.right.left, cache) cache[root] = max(c1, c2) return cache[root] def rob_2(self, root): return max(self._rob_2(root)) def _rob_2(self, root) -> List[int]: """ We can redefine the function such that it returns a list of two elements: the first value is with the root robbed, and the second value is with the root not robbed. """ if not root: return [0, 0] left_vals = self._rob_2(root.left) right_vals = self._rob_2(root.right) # if we rob the current node, then it's left and # right child cannot be robbed. rob = root.val + left_vals[1] + right_vals[1] # if we don't rob the current node, we can choose if we want # to robber the left and right children based on the profit. not_rob = max(left_vals) + max(right_vals) return [rob, not_rob]
# dummy class class BinaryMatrix(object): def get(self, row: int, col: int) -> int: return 1 def dimensions(self) -> list: return [] class Solution: def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: n_row, n_col = binaryMatrix.dimensions() j = n_col - 1 found = False for i in range(n_row): if binaryMatrix.get(i, j) == 1: found = True while j > 0 and binaryMatrix.get(i, j-1) == 1: j -= 1 break while i < n_row-1: while j > 0 and binaryMatrix.get(i+1, j-1) == 1: j -= 1 i += 1 return j if found else -1 def left_most_column_with_one_clean(self, binaryMatrix): n_row, n_col = binaryMatrix.dimensions() res = -1 j = n_col - 1 i = 0 while i < n_row and j >= 0: if binaryMatrix.get(i, j) == 1: res = j j -= 1 else: i += 1 return res """ 0 0 0 1 0 0 1 1 0 1 1 1 n_row = 3, n_col = 4, j = 3 i = 0, j = 2, i = 1 """
from typing import List, Set class Solution: def count_components(self, n, edges: List[List[int]]) -> int: if n == 0: return 0 graph = self._create_adjacent_list(n, edges) visited = set() res = 0 for v in range(n): if not v in visited: self._dfs(v, visited, graph) res += 1 return res def _create_adjacent_list(self, n: int, edges: List[List[int]]) -> List[List[int]]: """ Helper function to generate a map between a nod and its neighbors. """ res = {i: [] for i in range(n)} for e in edges: v, w = e res[v].append(w) res[w].append(v) return res def _dfs(self, v: int, visited: Set[int], graph: List[List[int]]) -> None: visited.add(v) for w in graph[v]: if not w in visited: self._dfs(w, visited, graph)
def max_diff(root): res = [0] dfs(root, 0, 100000, res) return res[0] def dfs(node, max_val, min_val, res): """ Top-down approach. Keep track of the max and min encountered when going down. When reaching a leaf, the max diff is max_val - min_val. Since dfs covers all the path, the max diff path is included. """ if not node: res[0] = max(res[0], max_val - min_val) return dfs(node.left, max(max_val, node.val), min(min_val, node.val), res) dfs(node.right, max(max_val, node.val), min(min_val, node.val), res)
from collections import Counter import heapq class Word: def __init__(self, w, c): self.w = w self.c = c def __lt__(self, other): if self.c < other.c: return True elif self.c == other.c: return self.w > other.w else: return False def __eq__(self, other): return self.c == other.c and self.w == other.w def top_frequent(words, k): cnt = Counter(words) hq = [] for w, v in cnt.items(): heapq.heappush(hq, Word(w, v)) if len(hq) > k: heapq.heappop(hq) res = [] while hq: res.append(heapq.heappop(hq).w) return res[::-1]
from queue import Queue def is_bipartite(graph): colors = dict() # store nodes and its color q = Queue() for i in range(len(graph)): if i not in colors: q.put(i) colors[i] = 0 while not q.empty(): cur = q.get() for v in graph[cur]: if v in colors and colors[v] == colors[cur]: return False elif v not in colors: colors[v] = 1 - colors[cur] q.put(v) return True
from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ Using the BST property, we can the value range to determine if the current node is done. Comparing with serialize and deserialize a BT, we don't need to add indicator for empty nodes. """ class Codec: def serialize(self, root: TreeNode) -> str: res = [] _serialize(root, res) return ','.join(res) def deserialize(self, data: str) -> TreeNode: return _deserialize(deque(data.split(',')), -float('inf'), float('inf')) def _deserialize(q, low, high): if not q: return None val = int(q[0]) if (val < low or val > high): return q.popleft() root = TreeNode(val) root.left = _deserialize(q, low, val-1) root.right = _deserialize(q, val+1, high) return root def _serialize(root, res): if not root: return res.append(str(root.val)) _serialize(root.left, res) _serialize(root.right, res)
import heapq from typing import List class Solution: def k_smallest_pairs_brutal_force(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: """ Time complexity O(m*n*log(k)) Space complexity O(k) """ if not nums1 or not nums2: return [] heap = [] for n1 in nums1: for n2 in nums2: element = (-(n1 + n2), [n1, n2]) # maintain a max heap if len(heap) == k and (-(n1 + n2) > heap[0][0]): heapq.heapreplace(heap, element) elif len(heap) < k: heapq.heappush(heap, element) res = [] while len(heap) > 0: _, element = heapq.heappop(heap) res.append(element) return res def k_smallest_pairs_efficient(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: """ Form a matrix where the i-j element is the sum of nums[i], nums[j]. The next smallest element can either be (i+1) - j or i-(j + 1). Maintain a min_heap to keep track of possible candidates. Time complexity: O(k * log(k)) Space complexity: O(k) """ if not nums1 or not nums2: return [] heap = [] res = [] visited = set() heapq.heappush(heap, (nums1[0] + nums2[0], 0, 0)) visited.add((0, 0)) while len(heap) > 0 and len(res) < k: _, m, n = heapq.heappop(heap) res.append([nums1[m], nums2[n]]) self._add_element(heap, visited, nums1, nums2, m+1, n) self._add_element(heap, visited, nums1, nums2, m, n+1) return res def _add_element(self, heap, visited, nums1, nums2, i, j): if i < len(nums1) and j < len(nums2) and (not (i, j) in visited): heapq.heappush(heap, (nums1[i] + nums2[j], i, j)) visited.add((i, j))
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ Flatten the tree using in-order traversal and check if the array is sorted. """ def isValidBST(self, root: TreeNode) -> bool: result = [] self._in_order_traversal(root, result) if len(result) < 2: return True for i in range(len(result) - 1): if result[i] >= result[i+1]: return False return True def _in_order_traversal(self, node: TreeNode, result: List[int]): if not node: return self._in_order_traversal(node.left, result) result.append(node.val) self._in_order_traversal(node.right, result) class SolutionTopDown: """ Given the parent node, the range of left and right subtrees can be specified. """ def isValidBST(self, root: TreeNode) -> bool: low = float('-inf') high = float('inf') return self._validate(root, low, high) def _validate(self, root: TreeNode, low: float, high: float) -> bool: if not root: return True if root.val <= low or root.val >= high: return False return self._validate(root.left, low, root.val) and self._validate(root.right, root.val, high)
from typing import List class Solution: def length_of_lis(self, nums: List[int]) -> int: """ maintain a array dp whose i-th element is the length of the longest increasing substring in nums[:i+1] and must contain nums[i], the dynamic programming relation is: dp[i] = max(dp[j]) + 1 where j < i and nums[j] < nums[i] """ if not nums: return 0 dp = [0] * (len(nums)) dp[0] = 1 for i in range(1, len(nums)): cur_max = 0 for j in range(i, -1, -1): if nums[i] > nums[j]: cur_max = max(cur_max, dp[j]) dp[i] = cur_max + 1 return max(dp)
# Definition for a binary tree node. from queue import Queue class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class CodecPreOrder: def serialize(self, root): """ Use pre-order traversal to serialize the tree """ res = [] self._serialize(root, res) res = ','.join(str(e) for e in res) return res def _serialize(self, root, res): if not root: res.append('#') return res.append(root.val) self._serialize(root.left, res) self._serialize(root.right, res) def deserialize(self, data): """ """ if not data: return None root = self._deserialize(iter(data.split(','))) return root def _deserialize(self, data): cur = next(data, None) if not cur: return None if cur == '#': return None parent = TreeNode(int(cur)) parent.left = self._deserialize(data) parent.right = self._deserialize(data) return parent class CodecPostOrder: def serialize(self, root): res = [] self._serialize(root, res) return ','.join(res) def _serialize(self, root, res): if not root: res.append('#') return self._serialize(root.left, res) self._serialize(root.right, res) res.append(str(root.val)) def deserialize(self, data): if not data: return None data = data.split(',') root = self._deserialize(data) return root def _deserialize(self, data): if not data: return None cur = data.pop() if cur == '#': return None root = TreeNode(int(cur)) root.right = self._deserialize(data) root.left = self._deserialize(data) return root class CodecLevelOrder: """ Serialize the binary tree level-by-level. """ def serialize(self, root): if not root: return '' res = [] q = Queue() q.put(root) while not q.empty(): cur = q.get() if cur: res.append(str(cur.val)) q.put(cur.left) q.put(cur.right) else: res.append('#') return ','.join(res) def deserialize(self, data): if not data: return None data = data.split(',') root = TreeNode(int(data[0])) q = Queue() q.put(root) i = 1 while not q.empty(): # or using i < len(data), they are compatible parent = q.get() if data[i] != '#': parent.left = TreeNode(int(data[i])) q.put(parent.left) i += 1 if data[i] != '#': parent.right = TreeNode(int(data[i])) q.put(parent.right) i += 1 return root """ i = 1, parent = 1, data[1] = 2, q = [2] i = 2, data[2] = 3, q = [2, 3] i = 3, parent = 2, data[3] = '#', q = [3] i = 4, parent = 2, data[4] = '#', q = [3] i = 5, parent = 3, data[5] = 4, q = [4] i = 6, parent = 3, data[6] = 5, q = [4, 5] """
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: cur1 = l1 cur2 = l2 dummy = ListNode(0) cur = dummy carry = 0 while cur1 or cur2 or carry: if not cur1: cur1_val = 0 else: cur1_val = cur1.val if not cur2: cur2_val = 0 else: cur2_val = cur2.val carry, cur_val = divmod(cur1_val + cur2_val + carry, 10) cur.next = ListNode(cur_val) cur = cur.next if cur1: cur1 = cur1.next if cur2: cur2 = cur2.next return dummy.next class SolutionRecursive: def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: return self._add_two_numbers(l1, l2, 0) def _add_two_numbers(self, l1, l2, carry): if (not l1) and (not l2): if carry == 1: return ListNode(1) else: return None if not l1: if carry == 1: return self._add_two_numbers(l2, ListNode(1), 0) else: return l2 if not l2: if carry == 1: return self._add_two_numbers(l1, ListNode(1), 0) else: return l1 l1_val = l1.val + l2.val + carry if l1_val >= 10: l1_val -= 10 carry = 1 else: carry = 0 l1.val = l1_val l1.next = self._add_two_numbers(l1.next, l2.next, carry) return l1 class SolutionRecursive2(): """ Simpler base case. """ def add_two_numbers(self, l1, l2): if (not l1) and (not l2): return None if not l1: return l2 if not l2: return l1 cur_val = l1.val + l2.val head = ListNode(cur_val % 10) head.next = self.add_two_numbers(l1.next, l2.next) if cur_val >= 10: head.next = self.add_two_numbers(head.next, ListNode(1)) return head
def product(nums): front = [1] for num in nums[:-1]: front.append(front[-1] * num) end = [1] for num in nums[::-1][:-1]: end.append(end[-1] * num) end = end[::-1] res = [] for i in range(len(nums)): res.append(front[i] * end[i]) return res def product_space_efficient(nums): res = [1] for num in nums[:-1]: res.append(res[-1] * num) cur = 1 for i in range(len(nums)-2, -1, -1): cur *= nums[i+1] res[i] *= cur return res
def is_sorted(words, order): n_order = 'abcdefghijklmnopqrstuvwxyz' map_dict = {} for c1, c2 in zip(order, n_order): map_dict[c1] = c2 n_words = [] for w in words: temp = [] for c in w: temp.append(map_dict[c]) n_words.append(''.join(temp)) for i in range(len(words)-1): if n_words[i] > n_words[i+1]: return False return True
from typing import List class Solution: def max_sub_array(self, nums: List[int]) -> int: """ maintain an array dp and dp[i] is the maximum subarray that ends with nums[i]. Thus: dp[i+1] = nums[i+1] if dp[i] <= 0 = nums[i+1] + dp[i] if dp[i] > 0 """ if not nums: return 0 dp = [0] * len(nums) dp[0] = nums[0] for i in range(1, len(nums)): if dp[i-1] < 0: dp[i] = nums[i] else: dp[i] = nums[i] + dp[i-1] return max(dp) def max_sub_array_less_space(self, nums: List[int]) -> int: if not nums: return 0 max_sum = nums[0] pre = nums[0] for cur in nums[1:]: if pre < 0: pre = cur else: pre = cur + pre max_sum = max(max_sum, pre) return max_sum def max_sub_array_clean(self, nums): if not nums: return 0 pre = 0 # optimal sum up to current number (inclusive) opt = -float('inf') # optimal sum over all for num in nums: pre = max(num + pre, num) opt = max(opt, pre) return opt """ [-2, 1, -3, 4] num = -2, pre = -2, opt = -2 num = 1, pre = 1, opt = 1 num = -3, pre = -2, opt = 1 nums = 4, pre = 2, opt = 2 """
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # class ListNode: def partition(head, x): left_head = ListNode(None) right_head = ListNode(None) left = left_head right = right_head cur = head while cur: if cur.val < x: left.next = ListNode(cur.val) left = left.next else: right.next = ListNode(cur.val) right = right.next cur = cur.next left.next = right_head.next return left_head.next
class Solution: def insert(self, intervals, new_interval): res = [] new_low, new_high = new_interval for i in range(len(intervals)): if intervals[i][1] < new_low: res.append(intervals[i]) elif intervals[i][0] > new_high: res.append([new_low, new_high]) res += intervals[i:] return res else: new_low = min(new_low, intervals[i][0]) new_high = max(new_high, intervals[i][1]) res.append([new_low, new_high]) return res """ intervals = [[1, 5]], new_interval = [2, 3] new_low = 2, new_high = 3 i = 0 intervals = [[1, 3], [6, 9]], new_interval = [2, 5] new_low = 2, new_high = 5 i = 0, new_low = 1, new_high = 5 i = 1, res = [[1, 5], [6, 9]] """
def is_equal(nums): if len(nums) < 7: return False n_sum = [nums[0]] for i in range(1, len(nums)): n_sum.append(n_sum[-1] + nums[i]) for j in range(3, len(nums)-3): # it is possible there are more than one sum value # 2, 1, -1, 2, 1, remove -1, we have 3, remove 1, we have 2 seen = set() for i in range(1, j-1): if n_sum[i-1] == (n_sum[j-1] - n_sum[i]): seen.add(n_sum[i-1]) for k in range(j+2, len(nums)-1): if (n_sum[k-1] - n_sum[j]) == (n_sum[-1] - n_sum[k]) and (n_sum[k-1] - n_sum[j]) in seen: return True return False
#!/bin/python name = "Alli" print(name) if len(name) >=5: print("name is long") elif len(name) == 4: print("name is average") else: print("name is short") print("Condition successul")
#16진수로 입력된 정수 한 개를 8진수로 바꾸어 출력하는 프로그램을 작성해보자. #따로 생각나는 방법이 없어서 일단 10진수로 변경후, 다시 8진수로 변경하는 방법을 사용하였다. num = int(input(), 16) nums = oct(num)[2:] print(nums) ''' 다른 사람의 풀이 a=input() n=int(a, 16) print('%o' % n) 다음엔 꼭 이 방법으로 풀어봐야지.. '''
#정수가 순서대로 입력된다. 0이 아니면 입력된 정수를 출력하고 0이 입력되면 출력을 중단해보자. #이전에 있던 문제랑 무엇이 다른지요..? #아무튼 다시 풀었습니다. a = input().split() for i in range(len(a)): if a[i] != '0': print(a[i]) else: print(a[i]) break
#단어를 하나 입력받는다. 입력받은 단어(영어)의 각 문자를 한줄에 한 문자씩 분리해 출력한다. #'B''o''y' 이런 식으로 문제에서는 답을 원해서.. 어떤 방법으로 할까 하다가.. 그냥 프린트에 ""를 포함해서 출력해주었다. #다른 방버이 있었을 지도.. word = list(input()) for i in range(len(word)): print("'"+word[i]+"'")
#두 정수 사이의 합 #https://programmers.co.kr/learn/courses/30/lessons/12912 #두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. #예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. def adder(a, b): sum = 0 if a < b: for i in range (a, b+1): sum += i else: for i in range(b, a+1): sum += i return sum #다른 사람의 풀이 #if a > b: a, b = b, a ==> 만약 a>b라면, a,b 가 아니고 b,a #sum(): 합쳐주는 함수 def adder(a, b): if a > b: a, b = b, a return sum(range(a,b+1))
#정수 한 개가 입력되었을 때, minus(음)/plus(양) even(짝)/odd(홀)을 출력해보자. #첫 줄에 minus(음) 나 plus(양) 를 출력하고, 두번째 줄에 odd(홀) 나 even(짝) 을 출력한다. num = int(input()) if num > 0: print("plus") else: print("minus") if num%2 == 0: print("even") else: print("odd")
#입력된 두 정수 a, b 중 큰 값을 출력하는 프로그램을 작성해보자. #(단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.) #삼항 연산자: 항이 3개인 형태일 때 a, b = input().split(" ") a = int(a) b = int(b) c = a if a>b else b print(c) #파이썬의 3항 연산자 #(조건을 충족할 때) if (맞는 조건) else (조건을 충족하지 않을 때) #ex: a if a>b else b
# 나의 풀이 def solution(s): answer = '' numbers_english = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] curr = '' for i in s: if i.isalpha(): curr += i if curr in numbers_english: answer += str(numbers_english.index(curr)) curr = '' else: answer += i return int(answer) ### 다른 사람의 풀이 num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"} def solution(s): answer = s for key, value in num_dic.items(): answer = answer.replace(key, value) return int(answer)
#정수 한 개가 입력되었을 때 카운트다운을 출력해보자. num = int(input()) while num>0: print(num) num = num -1
#x만큼 간격이 있는 n개의 숫자 #https://programmers.co.kr/learn/courses/30/lessons/12954 #함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다.\ #다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요. #나의 풀이 def solution(x, n): answer = [] for i in range(1, n+1): answer.append(x*i) return answer #answer라는 리스트에 1부터 n+1까지의 숫자들을 곱한 값들을 append하는 식으로 만들었습니다.
# 큰 수 만들기 - 그리디 알고리즘 # https://programmers.co.kr/learn/courses/30/lessons/42883 def solution(number, k): stack = [number[0]] for num in number[1:]: while len(stack) > 0 and stack[-1] < num and k > 0: k -= 1 stack.pop() stack.append(num) return ''.join(stack[:len(stack) - k]) # 문자열로 풀려고 했는데 이런 문제는 역시 stack을 이용해서 푸는 것이 정답인 것 같다. # 마지막 return할 때 slicing 해주는 이유는 # 제거 횟수가 남았을 경우에 뒷 부분을 자르기 위해서이다. (12번 케이스에서 걸린다...) # 12번 테스트케이스는 같은 숫자가 반복될 경우인데 # 입력값: "1111111111", 3 && 기댓값: "1111111" 인 경우이다. # pop 되지 않고 모두 append 되기에 길이가 원했던 것보다 더 길게 나올 것이다. # 이럴 경우를 대비해 뒷 부분을 잘라주게 된다.
#정수 두 개(a, b)를 입력받아 합, 차, 곱, 몫, 나머지, 나눈값을 자동으로 계산해보자. #정수 두 개(a, b)가 공백을 두고 입력된다. ''' 출력 기준 첫 줄에 합 둘째 줄에 차(a-b) 셋째 줄에 곱, 넷째 줄에 a를 b로 나눈 몫, 다섯째 줄에 a를 b로 나눈 나머지, 여섯째 줄에 a를 b로 나눈값(실수, 소수점 셋째 자리에서 반올림해 둘째 자리까지 출력) 을 출력한다. ''' a, b = input().split(" ") a = int(a) b = int(b) print(a+b) print(a-b) print(a*b) print(a//b) print(a%b) print('%.2f' %(a/b)) #처음에 마지막 문장을 print(round(a/b,2))로 작성했는데 작동되지 않았다. #어떤 경우에는.. 둘째짜리 까지 출력이 안되기 때문이었다. #'%.2f' <- 로 형식을 정해두고 값에 넣.기 소숫점 둘째 자리까지니까 .2f 인 것이다.
#문자열 내 마음대로 정렬하기 #https://programmers.co.kr/learn/courses/30/lessons/12915 #문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. # 예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1의 문자 u, e, a로 strings를 정렬합니다. #나의 풀이 def solution(strings, n): for i in range(len(strings)): #그냥 n번째 거 맨 앞에 붙여서 정렬 하면 되는 거 아녀? strings[i] = strings[i][n] + strings[i] strings.sort() #출력할 때 [1:]로 하면 첫번째 글자는 빼고 출력한다. for i in range(len(strings)): strings[i] = strings[i][1:] return strings #다른 사람의 풀이 def strange_sort(strings, n): return sorted(strings, key=lambda x: x[n]) #lambda 는 무엇일까? 파이썬 공식문서 https://docs.python.org/3/howto/sorting.html #사용하는 방법 #sort(key = lambda x: x[n]) : x중에서 n번째 것을 비교한다.
#입력된 세 정수 a, b, c 중 가장 작은 값을 출력하는 프로그램을 작성해보자. #(단, 조건문을 사용하지 않고 3항 연산자 ? 를 사용한다.) #짜잔 세 개의 수를 비교하려면 삼항연산자 안에 삼항연산자를 넣어야 합니다. #삼항연산자 이렇게 썼으니 안 잊어먹기를 #a i f (a<b) else b .. 혹시 모르니까 연습 a, b, c = input().split(" ") a = int(a) b = int(b) c = int(c) small = a if (a<b and a<c) else (b if (b<c and b<a) else c) print(small)
command = input('Console command: ').upper() started = False while command != 'QUIT': if command != 'HELP': print('Command not recognized.') command = input('Console command: ').upper() else: print(''' Type "Start" to start the car. Type "Stop" to stop the car. Type "Quit" to terminate program. ''') while True: command = input('Console command: ').upper() if command == 'START': if started: print('The Car already started.') else: started = True print('The engine started.') elif command == 'STOP': if not started: print('Car is already Stopped.') else: started = False print('Car already Stopped.') elif command == 'QUIT': break else: print('Command not recognized.') command = input('Console command: ').upper() else: print('Program Terminated. Goodbye.')
def find_max(elements): # Redefining 'list' thru new variable numbers = elements # Set highest number based from 1st element in list. high = numbers[0] # Working Equation for x in numbers: if x > high: high = x # Value Returned to main.py return high
import random # For generating any number: print(random.random()) # Example No.01: for x in range(10): print(random.random()) # Example No. 02: # For generating any number but within specific range: for x in range(3): print(random.randint(10, 20)) # For generating any string based from a certain list: members = ['Alex', 'Bason', 'Wil', 'Arvin', 'Robert', 'Bronia', 'Quinto', 'Cocoy', 'Mikko'] print(f'Treat will be paid by: {random.choice(members)}.')
a = input('What is your weight? ') b = input("Press 'L' for lbs (pounds) or 'K' for kgs (kilograms) with respect to the unit of your inputted weight: ") if b == 'l' or b == 'L': c = float(a) / 2.2 print(f'You are {c} kgs.') elif b == 'k' or b == 'K': c = float(a) * 2.2 print(f'You are {c} lbs.') else: print('Wrong input.')
""""A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.""" listx = [] listy = [] listz = [] for x in range(100,1000): listx.append(x) for y in range(100,1000): listy.append(y) for z in listx: product = y * z if product == int(str(product)[::-1]): listz.append(product) print(listx) print("") print(listy) print("") print(listz) print("") print(max(listz))
# https://leetcode-cn.com/problems/rotate-list/submissions/ # 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: ListNode, k: int) -> ListNode: # step 1: corner cases: # 1. 如果 head 为空 # 2. 如果 k == 0 # 3. 如果 链表仅有一个元素 # 都返回 head if (not head) or (k==0) or (not head.next): return head # step 2: 遍历得到链表元素总个数 # 1 > 2 > 3 > 4 > 5 n = 1 cur = head while cur.next: cur = cur.next n += 1 # 如果 k 是 n 的倍数,那么其实就是原状 if k % n == 0: return head # n = 5 # k = 2 # step 3: # 此时 cur = node(5), # 再将链表闭拢成环 5 > 1 cur.next = head # 并从 clip_n 处切断 clip_n = n - k % n # clip_n = 3 # step 4: # 遍历个数至 clip_n 个元素 while clip_n: cur = cur.next clip_n -= 1 # 返回 node(4), 4 > 5 > 1 > 2 > 3 clip_head = cur.next # 3 > None clip_tail = cur clip_tail.next = None return clip_head
# filter(関数, イテレータ) def is_even(n): return n % 2 == 0 print(list(filter(is_even, range(10)))) print(list(filter(lambda n: n % 2 ==0 , range(10))))
# Miguel Angel Montoya # montoya5@purdue.edu # ID: 0031152048 # A* algorithm for the cannibals-missionaries problem # For python 2.7 import Queue as Q right = "Right" left = "Left" # Abstraction of priority queue. It lets the insertion of objects with priority. class MyPriorityQueue(Q.PriorityQueue): def __init__(self): Q.PriorityQueue.__init__(self) def put(self, item, priority): Q.PriorityQueue.put(self, (priority, item)) def get(self): _, item = Q.PriorityQueue.get(self) return item # State object. Contains values of missionaries and cannibals on each side and boat position. # It also contains overrides for object manipulation class State: def __init__(self, mLeft, cLeft, mRight, cRight, boat): self.mLeft = mLeft self.cLeft = cLeft self.mRight = mRight self.cRight = cRight self.boat = boat def __cmp__(self, other): if(isinstance(other, State)): res = cmp(self.mLeft, other.mLeft)\ and cmp(self.cLeft, other.cLeft)\ and cmp(self.mRight, other.mRight)\ and cmp(self.cRight, other.cRight)\ and cmp(self.boat, other.boat) return res return -1 def __eq__(self, other): if(isinstance(other, State)): return self.mLeft == other.mLeft\ and self.cLeft == other.cLeft\ and self.mRight == other.mRight\ and self.cRight == other.cRight\ and self.boat == other.boat return False def __ne__(self, other): if(isinstance(other, State)): return not self.__eq__(other) return False def __str__(self): return "Left: Missionaries=" + str(self.mLeft) + " Cannibals=" + str(self.cLeft) + "\n"\ + "Right: Missionaries=" + str(self.mRight) + " Cannibals=" + str(self.cRight) + "\n"\ + "Boat=" + self.boat + "\n" # To identify as equal two states with different id, but with the same values, # we combine the values of the object as strings, and hash that string. # This only works when comparing keys inside a dictionary def __hash__(self): return hash(str(self.mLeft) + str(self.cLeft) + str(self.mRight) + str(self.cRight) + self.boat) # Heuristic function def h(state): return (state.cLeft + state.mLeft)/2.0 # A* function def aStar(): # Definition of initial and goal states initialState = State(3,3,0,0,left) goal = State(0,0,3,3,right) # Priority queue for future node exploring queue = MyPriorityQueue() queue.put(initialState, 0) # Dictionary that stores the best parent for a node parent = {} parent[initialState] = None # Stores the action the parent realized to get to the state actionFromParent = {} actionFromParent[initialState] = 0 # Stores the total cost so far until the node g = {} g[initialState] = 0 # Explore nodes until queue is empty while not queue.empty(): # Get current node for exporation currentNode = queue.get() # Print path if the current node is the goal if currentNode == goal: # Find path that leaded to goal node. Store path in array backtrack = [] backtrack.append((currentNode, actionFromParent[currentNode])) while currentNode != initialState: backtrack.append((parent[currentNode], actionFromParent[parent[currentNode]])) currentNode = parent[currentNode] # Print states and actions that lead to next state print "INITIAL STATE" print backtrack[len(backtrack)-1][0] for i in range(len(backtrack)-2, -1, -1): node, action = backtrack[i] if abs(action) == 1: print "Moved 2 missionaries", elif abs(action) == 2: print "Moved 1 missionary", elif abs(action) == 3: print "Moved 2 cannibals", elif abs(action) == 4: print "Moved 1 cannibal", elif abs(action) == 5: print "Moved 1 missionary and 1 cannibal", if action < 0: print "from right to left\n" else: print "from left to right\n" if i == 0: print "GOAL STATE" print node break # Successor calculation. # Negative action type origin from the right. Positive form the left. The number determines the number of # entities transported from the side. successors = [] # If boat is currently on the left. if currentNode.boat == left: # States if missionaries exist if currentNode.mLeft >= 2: successors.append((State(currentNode.mLeft-2, currentNode.cLeft, currentNode.mRight+2, currentNode.cRight, right), 1)) if currentNode.mLeft >= 1: successors.append((State(currentNode.mLeft-1, currentNode.cLeft, currentNode.mRight+1, currentNode.cRight, right), 2)) # States if cannibal exist if currentNode.cLeft >= 2: successors.append((State(currentNode.mLeft, currentNode.cLeft-2, currentNode.mRight, currentNode.cRight+2, right), 3)) if currentNode.cLeft >= 1: successors.append((State(currentNode.mLeft, currentNode.cLeft-1, currentNode.mRight, currentNode.cRight+1, right), 4)) # If both sxist if currentNode.cLeft >= 1 and currentNode.mLeft >= 1: successors.append((State(currentNode.mLeft-1, currentNode.cLeft-1, currentNode.mRight+1, currentNode.cRight+1, right), 5)) # If boat is currently on the right. else: # States if missionaries exist if currentNode.mRight >= 2: successors.append((State(currentNode.mLeft+2, currentNode.cLeft, currentNode.mRight-2, currentNode.cRight, left), -1)) if currentNode.mRight >= 1: successors.append((State(currentNode.mLeft+1, currentNode.cLeft, currentNode.mRight-1, currentNode.cRight, left), -2)) # States if cannibal exist if currentNode.cRight >= 2: successors.append((State(currentNode.mLeft, currentNode.cLeft+2, currentNode.mRight, currentNode.cRight-2, left), -3)) if currentNode.cRight >= 1: successors.append((State(currentNode.mLeft, currentNode.cLeft+1, currentNode.mRight, currentNode.cRight-1, left), -4)) # If both sxist if currentNode.cRight >= 1 and currentNode.mRight >= 1: successors.append((State(currentNode.mLeft+1, currentNode.cLeft+1, currentNode.mRight-1, currentNode.cRight-1, left), -5)) # Calculate cost for child nodes nextCost = g[currentNode] + 1 # Iterate trought all possible child nodes for (next, type) in successors: # If next it's an invalid end state, skip it. if(next.mRight!= 0 and next.cRight > next.mRight) or (next.mLeft != 0 and next.cLeft > next.mLeft): continue # If the node hasn't been explored # or it has been explored but the path to arrive to that node is cheaper than the stored if next not in g or nextCost < g[next]: # Store new cost g[next] = nextCost # Put node in queue for exploring queue.put(next, nextCost + h(next)) # Store new parent parent[next] = currentNode # Store action that lead parent to node actionFromParent[next] = type def main(): aStar() if __name__ == '__main__': main()
__author__ = 'gopalindians' #Operators a=3 b=3 print(a+b) print(a-b) print(a*b) print(a/b) print(a%b) print(a**b) print(a//b) #Assignment operator a+=2; print("Now a is :" , a);
__author__ = 'gopalindians' #Lists (Like arrays) val=[1,2,3,4,5,6,7,8] print(val[0]) #v2 using for loop for a in val: print(a) #v3 using index print(val[1:5]) #prints [2 3 4 5] #Common operations on List print(val) # List before appending val.append(12) print(val) #List after appending
""" Simulates a pandemic using pygame """ import pygame as pg from environment import Environment from organisms import Organism, Health import random, math, itertools, time, pickle # plotting import matplotlib.pyplot as plt from scipy import asarray as ar,exp import numpy as np # size of window (width, height) = (1000, 666) # parameters duration = 120 population = 100 #1000 sick_initial = 1 # HEX-colours RED = (255,0,0) WHITE = (255,255,255) GREY = (230,230,230) BLUE = (0,0,255) BLACK = (0,0,0) environment = Environment((width, height), restriction=0.5) environment.add_organisms(population) #pygame pg.init() screen = pg.display.set_mode((width, height)) # display text pg.display.set_caption('Pandemic 1.0') #basicfont = pg.font.Font(None, 32) #text_string = '' #header = basicfont.render(text_string, True, RED, WHITE) #headerRect = header.get_rect() #headerRect.center = (50, 40) pg.init() start_time = time.time() current_time = time.time() i = 0 s = 0 x = ar([]) y_healthy = ar([]) y_infected = ar([]) y_contageous = ar([]) y_sick = ar([]) y_healed = ar([]) while current_time - start_time < duration: pg.init() # draw background screen.fill(environment.colour) environment.update() #print(f"{current_time} ({current_time}) {duration}") for o in environment.organisms: #print(f"c:{o.colour}, ({o.x},{o.y}), {o.size}, {o.thickness}") pg.draw.circle(screen, o.colour, (int(o.x), int(o.y)), o.size, o.thickness) pg.draw.line(screen, o.colour, (int(o.x), int(o.y)), (int(o.x)+(o.size+4)*math.sin(math.pi/2 - o.angle),int(o.y)+(o.size+4)*math.cos(math.pi/2 - o.angle)), 6) pg.draw.line(screen, o.colour, (int(o.x), int(o.y)), (int(o.x)+(o.size+4)*math.sin(3*math.pi/2 - o.angle),int(o.y)+(o.size+4)*math.cos(3*math.pi/2 - o.angle)), 6) #pg.draw.circle(screen, ) for event in pg.event.get(): if event.type in (pg.QUIT, pg.KEYDOWN): print("Key pressed") #screen.blit() pg.display.flip() current_time = time.time() time_elapsed = int(round((current_time - start_time)*1000)) environment.time_elapsed = time_elapsed if s <= math.floor(current_time - start_time): # data for plotting x = np.append(x, s) ov = environment.health_overview() #print(ov) y_healthy = np.append(y_healthy, ov[Health.healthy]+ov[Health.infected]+ov[Health.contageous]) #y_infected = np.append(y_infected, ov[Health.infected]) #y_contageous = np.append(y_contageous, ov[Health.contageous]) y_sick = np.append(y_sick, ov[Health.sick]) y_healed = np.append(y_healed, ov[Health.healed]) s = math.floor(current_time - start_time) i+=1 print(i) # stack plot #y = np.vstack([y_healed, y_sick, y_contageous, y_infected, y_healthy]) #labels = ["Healed", "Symptoms", "Contageous", "Infected", "Healthy"] #colours = [(26,204,80), (198,18,18), (255,239,0), (0,0,0), (150,150,150)] #colours = [tuple(map(lambda x: x/255, c)) for c in colours] y = np.vstack([y_sick, y_healed, y_healthy]) labels = ["Sick", "Healed", "Healthy"] colours = [(198,18,18), (26,204,80), (150,150,150)] colours = [tuple(map(lambda x: x/255, c)) for c in colours] fig, ax = plt.subplots() #ax.stackplot(x, y_healed, y_sick, y_contageous, y_infected, y_healthy, labels=labels, colors=colours) ax.stackplot(x, y_sick, y_healed, y_healthy, labels=labels, colors=colours) ax.legend(loc='upper left') plt.show() # normal plot #fig, ax = plt.subplots() #plt.plot(x,y_contageous,'ro:',label='contageous') #plt.plot(x,y_sick,'bo:',label='sick') #plt.plot(x,y_healed,'go:',label='healed') #plt.legend() #plt.show() #pg.draw.line(screen, p.colour, (int(p.x), int(p.y)), (int(p.x)+p.distance_front*math.sin(angle),int(p.y)+p.distance_front*math.cos(angle))) #screen.blit(header, headerRect) # infinite loop that stops on key press #def main(): # while 1: # for event in pg.event.get(): # if event.type in (pg.QUIT, pg.KEYDOWN): # return # #if __name__ == "__main__": # main()
import random import turtle # Returns a random color! from turtle import Turtle def get_random_color(): return "#%06X" % (random.randint(0, 0xFFFFFF)) def get_next_color(i): return colors[i % len(colors)] # ====================== DO NOT EDIT THE CODE ABOVE =========================== if __name__ == '__main__': window = turtle.Screen() window.bgcolor('black') window.setup(width=0.75, height=0.9, startx=0, starty=0) colors = ('hotpink', 'pink', 'purple', 'blue', 'white', 'light blue') # Make a new turtle blob = turtle.Turtle() # type: Turtle # Make the turtle shape 'turtle', .shape('turtle') blob.shape('turtle') # Set the turtle speed to max (0) blob.speed(0) # Set the turtle width to 1 blob.width(1) # Create a variable to hold the number of sides in a pentagon penta = 4 # Create a variable to be the angle of 360 divided by the sides variable angle = 360/4 # Use a for loop to repeat ALL the following lines of code 360 times. for i in range(900): if i==100: blob.width(2) if i==200: blob.width(3) blob.color(get_next_color(i)) blob.forward(i) blob.right(angle+1) blob.hideturtle() # If the loop variable (i) is equal to 100, set the turtle width to 2 # If the loop variable (i) is equal to 200, set the turtle width to 3 # Use the get_next_color function to set the turtle pencolor, # *hint .pencolor(get_next_color(i)) # Move the turtle forward by the loop variable, *hint .forward(i) # Turn the turtle to the right by the angle variable + 1 # Hide your turtle so you can see the pattern. # Check the pattern against the picture in the recipe. If it matches, you are done! # Variations: # *Make the pattern really huge # *Change the colors # *Experiment with different shapes # Call the turtle.done() method turtle.done()
a=[] def even_number(x): for i in range(0,100): if i%2==0: x.append(i) print(x) even_number(a)
# https://adventofcode.com/2015/day/5 import sys import re from pathlib import Path path = Path(__file__).parent / "input/inputDay5.txt" vowels = "AaEeIiOoUu" pairs=["ab","cd","pq","xy"] f = open(path) def Check_Vow(string, vowels): final = [each for each in string if each in vowels] return final niceCount=0 while True: line=f.readline() if not line: break # check if 3 or more vowels if len(Check_Vow(line,vowels))>=3: #check if there's a double letter e.g. 'dd' prevLetter=line[0] doubleMatch=False for letter in range(len(line)-1): thisLetter=line[letter+1] if prevLetter==thisLetter: doubleMatch=True prevLetter=thisLetter #check for letter pairs prevLetter=line[0] pairMatch=False if doubleMatch==True: for letter in range(len(line)-1): thisLetter=line[letter+1] if prevLetter+thisLetter in pairs: pairMatch=True prevLetter=thisLetter if pairMatch!=True: niceCount+=1 f.close() print("Part 1 Answer: "+ str(niceCount)) # Part 2 f = open(path) lines=[] while True: line=f.readline() if not line: break line.strip() lines.append(line) f.close() # https://www.reddit.com/r/adventofcode/comments/3viazx/day_5_solutions/ technojamin print("Part 2 Answer: " + str(len([s for s in lines if (re.search(r'(..).*\1', s) and re.search(r'(.).\1', s))])))
# coding: utf-8 from Tkinter import * import time import math root=Tk() root.title("画图") running=1 #c=circle_color,d_c=dot_color c=d_c='red' #r=rectangle_fill_color,l_c=line_color,r_o_c=rectangle_outline_color r=l_c=r_o_c=c_o_c='blue' #l=line_width,d=dot_width,e=erase_width,r_o_w=rectangle_outline_width l=d=e=r_o_w=c_o_w=5 i=j=p=0 new_c=Canvas(root,width=640,height=480,bg='white') x,y=int(new_c['width'])/2,int(new_c['height'])/2 rcolor=StringVar() ccolor=StringVar() line_width=IntVar() dot_width=IntVar() def new_canvas(): new_c.create_rectangle(0,0,640,480,fill='white') def quit_(): global running running=0 root.destroy() def place_shape(event): global x,y global i,j,p global x_prior global y_prior x_prior=x y_prior=y x,y=event.x,event.y if(shape_val==0): new_c.create_oval(x,y,x,y,width=d,outline=d_c) if(shape_val==1): p=p+1 new_c.create_oval(x,y,x,y,width='3',outline=r_o_c) if(shape_val==1)and(p%2==0): new_c.create_oval(x_prior,y_prior,x_prior,y_prior,width='3',outline='white') new_c.create_rectangle(x_prior,y_prior,x,y,fill=r,width=r_o_w,outline=r_o_c) if(shape_val==2): j=j+1 new_c.create_oval(x,y,x,y,width='3',outline=c_o_c) if(shape_val==2)and(j%2==0): new_c.create_oval(x_prior-math.sqrt((x_prior-x)**2+(y_prior-y)**2), y_prior-math.sqrt((x_prior-x)**2+(y_prior-y)**2), x_prior+math.sqrt((x_prior-x)**2+(y_prior-y)**2), y_prior+math.sqrt((x_prior-x)**2+(y_prior-y)**2), fill=c,width=c_o_w,outline=c_o_c) if(shape_val==3): i=i+1 if(i%2==1): new_c.create_oval(x,y,x,y,width=l,outline=l_c) if(shape_val==3)and(i%2==0): new_c.create_oval(x_prior,y_prior,x_prior,y_prior,width=l,outline='white') new_c.create_line(x_prior,y_prior,x,y,width=l,fill=l_c) root.bind('<Button-1>',place_shape) def erase_shape(event): global x,y x,y=event.x,event.y new_c.create_oval(x,y,x,y,width=e,outline='white') root.bind('<Button-3>',erase_shape) def set_erase(): erase=Tk() erase.title("erase") erase_label=Label(erase,text='width:').pack() entry_e=Entry(erase,width=30) entry_e.pack() erase_button=Button(erase,text='submit', command=lambda:set_e(entry_e.get(),erase)) erase_button.pack() def set_e(val1,val2): global e if(val1!=''): e=int(val1) val2.destroy() def set_shape_0(): global shape_val shape_val=0 dot=Tk() dot.title("dot") dot_label_1=Label(dot,text='width:').pack() entry_d1=Entry(dot,width=30) entry_d1.pack() dot_label_2=Label(dot,text='color:').pack() entry_d2=Entry(dot,width=30) entry_d2.pack() dot_button=Button(dot,text='submit', command=lambda:set_int(entry_d1.get(),entry_d2.get(),dot)) dot_button.pack() def set_int(val1,val2,val3): global d,d_c if(val1!=''): d=int(val1) if(val2!=''): d_c=str(val2) val3.destroy() def set_shape_1(): global shape_val shape_val=1 rectangle=Tk() rectangle.title("矩形") rec_label_1=Label(rectangle,text='fill_color:').pack() entry_r1=Entry(rectangle,width=30) entry_r1.pack() rec_label_2=Label(rectangle,text='outline_width:').pack() entry_r2=Entry(rectangle,width=30) entry_r2.pack() rec_label_3=Label(rectangle,text='outline_color:').pack() entry_r3=Entry(rectangle,width=30) entry_r3.pack() rec_button=Button(rectangle,text='submit', command=lambda:set_r(entry_r1.get(),entry_r2.get(),entry_r3.get(),rectangle)) rec_button.pack() def set_r(val1,val2,val3,val4): global r,r_o_c,r_o_w if(val1!=''): r=str(val1) if(val2!=''): r_o_w=int(val2) if(val3!=''): r_o_c=str(val3) val4.destroy() def set_shape_2(): global shape_val global ccolor shape_val=2 circle=Tk() circle.title("圆") cir_label=Label(circle,text='color:').pack() entry_c1=Entry(circle,width=30) entry_c1.pack() cir_label_2=Label(circle,text='outline_width:').pack() entry_c2=Entry(circle,width=30) entry_c2.pack() cir_label_3=Label(circle,text='outline_color:').pack() entry_c3=Entry(circle,width=30) entry_c3.pack() cir_button=Button(circle,text='submit', command=lambda:set_c(entry_c1.get(),entry_c2.get(),entry_c3.get(),circle)) cir_button.pack() def set_c(val1,val2,val3,val4): global c,c_o_c,c_o_w if(val1!=''): c=str(val1) if(val2!=''): c_o_w=int(val2) if(val3!=''): c_o_c=str(val3) val4.destroy() def set_shape_3(): global shape_val shape_val=3 line=Tk() line.title("line") line_label_1=Label(line,text='width:').pack() entry_l_1=Entry(line,width=30) entry_l_1.pack() line_label_2=Label(line,text='color:').pack() entry_l_2=Entry(line,width=30) entry_l_2.pack() line_button=Button(line,text='submit', command=lambda:set_l(entry_l_1.get(),entry_l_2.get(),line)) line_button.pack() def set_l(val1,val2,val3): global l global l_c if(val1!=''): l=int(val1) if(val2!=''): l_c=str(val2) val3.destroy() #创建一个菜单栏 menubar = Menu(root) menubar.add_command(label='clear',command =new_canvas) menubar.add_command(label='dot',command=set_shape_0) menubar.add_command(label='line',command=set_shape_3) menubar.add_command(label='rectangle',command=set_shape_1) menubar.add_command(label='circle',command=set_shape_2) menubar.add_command(label='erase',command=set_erase) menubar.add_command(label='quit',command=quit_) root.config(menu = menubar) shape_val=0 while running: new_c.pack() time.sleep(0.01) new_c.update()
# -*- coding: utf-8 -*- # 所有名片记录的列表 cards_list = [] def show_menu(): """显示菜单""" print('*' * 50) print('欢迎使用【名片管理系统】V1.0') print('') print('1.新建名片\n' '2.显示全部\n' '3.查询名片\n' '\n' '0.退出系统') print('*' * 50) def new_card(): """新建名片""" print('-' * 50) print('功能:新建名片') # 提示用户输入名片信息 name_card = input('请输入姓名:') phone_card = input('请输入电话:') qq_card = input('请输入QQ号码:') email_card = input('请输入邮箱地址:') # 将用户信息保存到一个字典 card_dict = {'name': name_card, 'phone': phone_card, 'qq': qq_card, 'email': email_card} # 将用户字典添加到名片列表 cards_list.append(card_dict) print(card_dict) # 提示添加成功信息 # ! print('成功添加到%s的名片' % card_dict['name']) def show_all(): """显示全部""" print('-' * 50) print('功能:显示全部') # 判断是否有名片记录 if len(cards_list) == 0: print('当前暂无名片信息,请选择其他操作') # !return之下代码都不执行,返回调用函数的位置 return print('姓名\t\t电话\t\tQQ\t\t邮箱\t\t') print('=' * 50) for card_dict in cards_list: # ! print('%s\t\t%s\t\t%s\t\t%s\t\t' % (card_dict['name'], card_dict['phone'], card_dict['qq'], card_dict['email'])) print('-' * 50) def search_card(): """搜索名片""" print('-' * 50) print('功能:搜索名片') # 1.输入要搜索的姓名 find_name = input('请输入您要查找的姓名:') # 2.遍历字典 for card_dict in cards_list: if card_dict['name'] == find_name: print('姓名:%s 电话:%s QQ:%s 邮箱:%s' % (card_dict['name'], card_dict['phone'], card_dict['qq'], card_dict['email'])) print('-' * 50) # 对搜索到的名片进行下一步操作 deal_card(card_dict) break # ! else: # ! print('木有找到%s' % find_name) def deal_card(find_dict): """ 操作搜索到的名片 :param find_dict:名片字典 """ action_deal = int(input('请输入对名片的操作:1.修改 2.删除 0.返回上级菜单')) if action_deal == 1: find_dict['name'] = card_input(find_dict['name'], '请输入新的姓名(回车不修改)') find_dict['phone'] = card_input(find_dict['phone'], '请输入新的电话号码(回车不修改)') find_dict['qq'] = card_input(find_dict['name'], '请输入新的qq号码(回车不修改)') find_dict['email'] = card_input(find_dict['name'], '请输入新的邮箱地址(回车不修改)') print('%s名片修改成功!' % find_dict['name']) elif action_deal == 2: cards_list.remove(find_dict) print('删除名片成功!') else: pass def card_input(dict_value, tip_message): """修改名片信息 1 提示用户输入内容 2 针对用户的输入进行判断: 1.1 如果用户输入了内容,直接返回结果 1.2 如果用户没有输入内容,返回字典中原有的值 """ # 输入要修改的信息 user_input = input(tip_message) if len(user_input) > 0: return user_input else: return dict_value
class HouseItem(object): """家具类""" def __init__(self, name, area): # 家具名称 self.name = name # 家具占的面积 self.area = area def __str__(self): """输出对象时显示的信息""" return '家具名称:%s 占用面积:%s平米' % (self.name, self.area) class House(object): """房类""" def __init__(self, house_type, area): """ :param house_type: 房型 :param area: 总面积 """ self.house_type = house_type self.area = area # 剩余面积,默认为总面积 self.free_area = area # 家具列表,默认为空 self.item_list = [] def __str__(self): """输出对象时显示的信息""" return '户型:%s 总面积:%.2f平米 剩余面积:%.2f平米 家具列表:%s' % \ (self.house_type, self.area, self.free_area, self.item_list) def add_item(self, item): """添加家具 :param item:对象(一个对象的属性可以使另一个类创建的对象) """ print('开始添加%s家具' % item.name) # 判断家具面积是否大于剩余面积 if item.area > self.free_area: print('空间不足') return # 家具名称追加到家具列表 self.item_list.append(item.name) # 计算剩余面积 self.free_area -= item.area print('添加成功') # 创建家具 bed = HouseItem('席梦思', 4) chest = HouseItem('衣柜', 2) table = HouseItem('餐桌', 1.5) # 创建户型 home_1 = House('两室一厅', 100) print(home_1) home_1.add_item(bed) home_1.add_item(chest) home_1.add_item(table) print(home_1.item_list) print(home_1)
# 动态规划:将大问题分解为小问题,先解决小问题,再逐步解决大问题 # 1.当给定约束条件下优化某种指标 # 2.问题可分解为离散子问题 # 绘制表格:每个单元格都是一个子问题,将每个子问题作为一列,单元格中的值就是要优化的值,每次迭代,更新子问题中的优化值 # 背包问题 # 约束条件:背包大小4 # 优化值:背包中物品总价值 # 将4背包分解成小背包作为列 # 每次迭代小背包,更新小背包中能存放的最大价值 # 单元格中的值: # cell[i][j] = max(cell[i-1][j], value+cell[i-1][j-当前商品重量]) # 上一单元格的值/当前商品价值+当前剩余空间的最大价值 # 注意事项: # 1.表格各行的排列顺序无关紧要 # 2.动态规划没法处理相互依赖的情况,只能处理问题可以分解为彼此独立且离散的子问题的情况
import socket if __name__ == '__main__': # 1. 创建服务端套接字对象 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置端口号服用:程序退出时立即释放端口号 # SOL_SOCKET:当前套接字 # SO_REUSEADDR:复用选项 tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) # 2. 绑定端口号 socket.bind((host,port)) tcp_server_socket.bind(('', 9090)) # 3. 设置监听:知道客户端想要连接 socket.listen(backlog) # backlog:最大等待建立连接的个数 # listen后的这个套接字是被动套接字:只负责接收客户端连接请求,不能收发消息,收发消息使用返回的新套接字来完成 tcp_server_socket.listen(128) # 4. 等待接受客户端连接请求 socket.accept() # 只有客户端和服务端建立连接成功代码才会解阻塞,代码才能继续往下执行 # 返回(socket object, address info) # socket object:专门和客户端通信的套接字,返回一个新的套接字目的是用于服务端程序可以服务于多个客户端 # address info:(客户端IP,端口号) new_socket, ip = tcp_server_socket.accept() print('[服务端]已接受连接:', ip) # 5. 接受数据 socket.recv(buffersize) recv_data = new_socket.recv(1024) # 获取数据长度 # 当客户端的套接字调用close后,服务器端的recv会解阻塞,返回的数据长度为0,服务端可以通过返回数据的长度来判断客户端是否已经下线,反之服务端关闭套接字,客户端的recv也会解阻塞,返回的数据长度也为0。 # = 客户端close后,服务端接收到数据长度为0 recv_date_len = len(recv_data) if recv_date_len == 0: print('[服务端]接受到的数据长度', recv_date_len) new_socket.close() else: recv_content = recv_data.decode('utf-8') print('[服务端端]接受到内容:', recv_content) # 6. 发送数据 send_content = input('[服务端]请输入要发送的内容:') send_date = send_content.encode('utf-8') new_socket.send(send_date) # 7. 关闭套接字 # 关闭服务于客户端的套接字,终止与客户端通信的服务 new_socket.close() # 关闭服务端的套接字,终止和客户端提供建立连接请求的服务 tcp_server_socket.close() ''' 小结: 1. 创建服务端套接字 (设置端口号复用) 2. 绑定端口号 3. 设置监听 4. 等待客户端建立连接(服务器套接字变为被动套接字,只负责建立连接,返回专门和客户端通信的新套接字) 5. 接收数据 6. 发送数据 7. 关闭通信套接字 8. 关闭服务器套接字 '''
# 单元格中的优化值:两个字符串都包含的最长子串的长度 # 子问题:比较两个字符串的子串 # 坐标轴:两个单词 # 答案:网格中最大的数字 import numpy as np def dynamic(str1, str2): str_index = (0, 0) num = 0 cell = np.zeros((len(str1), len(str2)), dtype=int); for i in range(len(str1)): for j in range(len(str2)): if str1[i] == str2[j]: # 两个字母相同 if i==0 or j==0: cell[i][j] = 1 else: cell[i][j] = cell[i-1][j-1] + 1 else: cell[i][j] = 0 if cell[i][j] > num: num = cell[i][j] str_index = i return num print(dynamic("hish", "fish"))
class A: a=222 def method1(self): self.a=123 self.b=345 @classmethod def method2(cls): print(cls.a) class B: def method3(self): self.a=999 self.b=777 s1=A() s1.method1() print(self.a,self.b,s1.a,s1.b) A.method2() s2=B() s2.method3()
''' Realiza un programa que reciba una cantidad de minutos y muestre por pantalla a cuantas horas y minutos corresponde. Por ejemplo: 1000 minutos son 16 horas y 40 minutos. ''' tiempo = int(input("Introduzca minutos a convertir: ")) horas = tiempo // 60 minutos = tiempo % 60 print(tiempo, " minutos, equivalen a ", horas, "horas y ", minutos, "minutos")
import math '''Dados dos números, mostrar la suma, resta, división y multiplicación de ambos.''' num1 = int(input('Introduzca primer número: ')) num2 = int(input('Introduzca segundo número: ')) print("La suma es = ",num1 + num2, "\nLa resta es = ",num1-num2, "\nLa multiplicación es = ",num1*num2, "\nLa división es = ", num1/num2)
def next_number(fibonacci_sequence): # item -2 (penultimate) or 1 penultimate_item = fibonacci_sequence[-2] if len(fibonacci_sequence) > 1 else 0 # item -1 (last) or 1 last_item = fibonacci_sequence[-1] if bool(fibonacci_sequence) else 1 return penultimate_item + last_item def fibonacci(n): if not isinstance(n, int) or n < 0: return print(f"{n} ({type(n).__name__}) 🤨 ? C'mon dude! Give me a positive number, please!") aux = 0 fibonacci_sequence = [] while (aux < n): fibonacci_sequence.append(next_number(fibonacci_sequence)) aux += 1 print(fibonacci_sequence)
#!/usr/bin/python3 hrs = input("Enter Hours:")# enter the hours h = float(hrs)#after converting it to float rate = input("Enter rate:")#enter the hours r = float(rate) def computepay(h,r): if h <= 40: pay = h * r elif h > 40: pay = 40 * r + (h-40) * r * 1.5 return pay print(computepay(h,r))
import copy def combination(arr, r): a=[] def generate(chosen): if len(chosen) == r: print(chosen) b=copy.deepcopy(chosen) a.append(b) return start = arr.index(chosen[-1]) + 1 if chosen else 0 for nxt in range(start, len(arr)): chosen.append(arr[nxt]) generate(chosen) chosen.pop() generate([]) return a b=combination('ABCDE', 2) print(b) c=combination([1, 2, 3, 4, 5], 3) print(c)
# add numbers x = 0 def func(): b =eval(input("enter the number")) for i in range(b+1): if i % 2 == 0: global x x = i + x print (x) else: print("Try next") func()
class a(): def __init__(self): self.x = 0 print ("hai i am in cons of a") def foo(self): print ("hai a") class b(): def __init__(self): self.x = 10 print ("i am in cons of b") def foo(self): print ("hai b") class c(b,a): def __init__(self): print ("i am in cons of c ") a.__init__(self) b.__init__(self) def foo(self): print ("hai i am in c" ) def main(): obj = c() obj.foo() print (obj.x) print (obj.x) main()
class abc(): count = 0 def __init__(self,var1 =1,var2 ="pop") self.arg1 = var1 self.arg2 = var2 abc.count = abc.count + 1 print ("in constructor") def print_obj(self): print("object" , self.arg1) print ("object", self.arg2) def __del__(self): print ("destructor called") abc.count = abc.count - 1 def main() obj1 =abc(l1,"pop") print(abc.count) obj2 = abc(12,"lol") print(abc.count) main()
e = 1 som = 0 while e != 0: e = int(input(" entrer le montant : ")) som = som + e print(" vous devez : ", som , "euros")
#project_title專題題目 #name_list成員名字 name=['林郁婷','陳妤瑄','林嘉欣','甘庭銨','游佳樺','蔡柏薪','林昱承','簡郁虹','王子維'] #number_list成員學號 number=['A109260010','A109260028','A109260036','A109260038','A109260042','A109260044','A109260046','A109260074','A109260096'] #duty_list分工內容 duty=['聊天內容','程式碼'] #load_list分工比重 load=['5%','10%'] #code程式碼 print('專題題目:聊天機器人') print('成員名單:') for a in range (6,6,6) print(a+1,'.'name[a],number[a],'`',end='')
# 1. Определение количества различных подстрок с использованием хеш-функции. # Пусть на вход функции дана строка. # Требуется вернуть количество различных подстрок в этой строке. import hashlib def subs(str): sub = set() for i in range(len(str)): for j in range(len(str), i, -1): hash_str = hashlib.sha1(str[i:j].encode('utf-8')).hexdigest() sub.add(hash_str) return len(sub) - 1 str = input('Введите строку, состоящую из маленьких латинских букв:') print(subs(str))
# 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). # Выведите на экран исходный и отсортированный массивы. import random SIZE = 10 MIN_ITEM = -100 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] def bubble_sort(arr): n = 1 while n < len(arr): for i in range(len(arr) - 1): if arr[i] < arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] n += 1 return arr print(array) print(bubble_sort(array))
# 1. В диапазоне натуральных чисел от 2 до 99 определить, # сколько из них кратны каждому из чисел в диапазоне от 2 до 9. array = [0]*8 for i in range(2,100): for j in range(2,10): if i%j == 0: array[j-2] += 1 i = 0 while i < len(array): print(f'Числу {i+2} кратны {array[i]}') i += 1
# Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. # Проанализировать результат и определить программы с наиболее эффективным использованием памяти. # В данной задаче массив генерируется рандомно, но присутствуют переменные, задающие его параметры. # Задача - найти максимальный отрицательный элемент в массиве. import random, sys SIZE = 10 MIN_ITEM = -15 MAX_ITEM = 25 arr = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(arr) i = 0 index = -1 while i < SIZE: if arr[i] < 0 and index == -1: index = i elif 0 > arr[i] > arr[index]: index = i i += 1 print(f'Максимальное отрицательное число:{arr[index]}.\nЕго индекс в массиве:{index}') print('*************************************************') def show(x): print(f'{type(x)=}, {sys.getsizeof(x)=}, {x=},') if hasattr(x, '__iter__'): if hasattr(x, 'items'): for key, value in x.items(): show(key) show(value) elif not isinstance(x, str): for item in x: show(item) show(arr) print('***') show(SIZE) print('***') show(MAX_ITEM) print('***') show(MIN_ITEM) print('***') show(i) print('***') show(index) #type(x)=<class 'list'>, sys.getsizeof(x)=92, x=[-11, -11, -3, 15, 1, 15, 24, 23, 1, 3], #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=-11, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=-11, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=-3, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=15, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=1, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=15, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=24, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=23, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=1, #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=3, #*** #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=10, #*** #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=25, #*** #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=-15, #*** #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=10, #*** #type(x)=<class 'int'>, sys.getsizeof(x)=14, x=2,
import pandas as pd import matplotlib.pyplot as plt data = { # python dictionary 'apples': [3,2,0,1], 'oranges':[0,3,7,2] } purchases_dataframe = pd.DataFrame(data) print(purchases_dataframe) dataset = pd.read_csv('data/ml-assessment-dataset.csv') print(dataset.head(10)) # displays the header and top half of the dataset print(dataset.tail(10)) print(dataset.shape) print(dataset.info()) print(dataset.describe()) print(dataset['Class'].describe(),"\n") print(dataset['Total mark'].describe(),"\n") print(dataset['Class'].value_counts()) # gets the numbers of distribution of features dataset['L4 mean mark'].plot(kind="hist", title='Level 4 mean mark distribution'); dataset.plot(kind='scatter', x='L4 mean mark', y='Total mark', title='Level 4 mean mark vs unit mark'); dataset['Class'].value_counts().plot(kind='bar', title='Class distribution'); i = 0 for row in dataset['Total mark']: if row > 39: i+=1 print("Students passed:",i) # Data analysis #6.1 #How many instances are there in the dataset? - 60 #Is the class balance equal? - Yes, 30,30 #Which class is the MOST represented in the dataset? - idk #How many students passed? - 31
""" makes a parenthesis input valid by removing necessary characters for example: input: (2 + 4) * ((34 + 5) output: (2 + 4) * (34 + 5) """ def makeValid(s): paraStack = [] openStack = [] for i in range(len(s)): if s[i] == "(" or s[i] == ")": paraStack.append({"type":s[i], "idx" : i}) for i in range(len(paraStack)): char = paraStack[i] if char["type"] == '(': openStack.append(char) elif char["type"] == ')': if len(openStack) <= 0: return makeValid(s[:paraStack[i]["idx"]] + s[paraStack[i]["idx"]+1:]) else: openStack.pop() for openPara in openStack: s = s[:openPara["idx"]] + s[openPara["idx"] +1 : ] return s # not len(openStack) > 0 import sys print(makeValid(sys.argv[1]))
import tkinter from tkinter import * from PIL import Image, ImageTk def capture(): window = Tk() window.geometry("1280x800") window.title("DSL") window.configure(bg="#969696") background_intro = tkinter.PhotoImage(file="Pics\capture_bckgrnd.png") background_label = tkinter.Label(window, image=background_intro) background_label.PhotoImage = background_intro background_label.place(x=0, y=0) background_label.pack() ext = Image.open("Pics/Hopstarter-Sleek-Xp-Basic-Close-2.ico") extBut = ImageTk.PhotoImage(ext) bck = Image.open("Pics/capture_back.png") bckBut = ImageTk.PhotoImage(bck) def back(): print("back button pressed") def exit1(): exit() bckBut = Button(window, image=bckBut, bg="#73c3ff", width=98, height=102, relief=FLAT, command=back) bckBut.place(x=17, y=75) buttonExit = Button(window, image=extBut, bg="#73c3ff", width=70, height=70, relief=FLAT, command=exit1) buttonExit.place(x=1170, y=20) window.mainloop()
class Solution: def isValid(self, s: str) -> bool: stack = [] open_brackets = ["(", "{", "["] closed_brackets = [")", "}", "]"] for char in s: if char in open_brackets: stack.append(char) elif char in closed_brackets: if len(stack) == 0: return False stack_head = stack[-1] open_check = open_brackets.index(stack_head) closed_check = closed_brackets.index(char) if open_check == closed_check: stack.pop() else: return False if len(stack) != 0: return False else: return True
n = int(input("Enter number of columns ")) for i in range(n) : print("*", end='')
word = input('Enter your word ') characters = list(word) from random import choice n = len(characters) i = 0 while i < n : random_characters = choice(characters) print(random_characters, end=' ') characters.remove(random_characters) i = i + 1 count = 0 loop = True while loop and count < 8 : guess = input("Your answer ") if guess.lower() == word : print("Winner Winner Chicken Dinner") loop = False else : print("Guess Again") print("You have", 7 - count, "turns left") count = count + 1 print("You lose")
# n = int(input("n ")) # for i in range(0, n, 2): # # range(start, stop, step) # print(i, end=', ') n = int(input("n ")) for i in range(n): # i la bien gan voi cac gia tri cua n if i % 2 == 0 : print("Fizz") elif i % 3 == 0 : print("buzz") else i % 2 % 3 == 0 : print("Fizzbuzz")
print("The area of a circle") r = float(input("Enter radius")) if r < 0 : print("The radius input must > 0") else : s = 3.14 * r**2 print("The area of a circle is s = {0}".format(s),"unit area")
''' Class: CPSC 427 Team Member 1: Robert Brajcich Team Member 2: Damon George Submitted By Damon George GU Username: dgeorge2 File Name: proj6.py Uses breadth-first search to list states while finding goal state of given eight puzzle initial state Usage: python proj6.py Date: 22 February 2019 ''' from copy import deepcopy from collections import deque #for implementing fast queues #displays the given state def display(state): for row in state: print row print "" #returns (row,col) of value in state def find_coord(value, state): for row in range(3): for col in range(3): if state[row][col] == value: return (row,col) #returns list of (row, col) tuples which can be swapped for blank #these form the legal moves of the given current state def get_new_moves(cur_state): row, col = find_coord(0, cur_state) #get row, col of blank moves = [] if col > 0: moves.append((row, col - 1)) #go left if row > 0: moves.append((row - 1, col)) #go up if col < 2: moves.append((row, col + 1)) #go right if row < 2: moves.append((row + 1, col)) #go down return moves def gen_child_states(cur_state): #get legal moves move_lst = get_new_moves(cur_state) #blank is a tuple, holding coordinates of the blank tile blank = find_coord(0, cur_state) children = [] #tile is a tuple, holding coordinates of the tile to be swapped #with the blank for tile in move_lst: #create a new state using deep copy #ensures that matrices are completely independent child = deepcopy(cur_state) #move tile to position of the blank child[blank[0]][blank[1]] = child[tile[0]][tile[1]] #set tile position to 0 child[tile[0]][tile[1]] = 0 #append child state to the list of children children.append(child) return children # performs breadth-first search on the 8-puzzle given as start # on its journey towards the 8 puzzle arrangement given in goal. def breadth_first(start, goal): # init queues open = deque([]) closed = deque([]) children = deque([]) #for tracking number of states we've checked cur_state_step_no = 1; # add starting state to open queue and begin search open.append(start) while (len(open) > 0): # get next item in open queue cur = open.popleft() #print step # and state print("Step " + str(cur_state_step_no)) cur_state_step_no += 1 display(cur) # if this is the goal state, be done if (cur == goal): return True #should be in closed states after analyzing closed.append(cur) # add each child of cur to queue for child in gen_child_states(cur): # moving left to right children.append(child) # dequeue each child of cur from queue, add to open if not already # analyzed or waiting to be analyzed while(len(children) > 0): child = children.popleft() if (child not in open and child not in closed): open.append(child) return False def main(): #nested list representation of 8 puzzle. 0 is the blank. start_state= [[2,8,3], [1,6,4], [7,0,5]] # goal state we are trying to obtain goal_state = [[1,2,3], [8,0,4], [7,6,5]] # perform search and print states along the way breadth_first(start_state, goal_state) main()
INFINITY = float('inf') #class Node(): # def __init__(self, x, y, distance): # self.x = x # self.y = y # self.distance = distance def isInsideGrid(x, y): return 0<=x<ROW and 0<=y<COLUMN # Moves x = [-1, 0, 1, 0, 1, -1, 1, -1] y = [0, 1, 0, -1, 1, 1, -1, -1] def dijkstrasAlgo(mat, ROW, COLUMN): # Initialisation queue=[] queue.append((mat[0][0], 0, 0)) dist=[[INFINITY for i in range(COLUMN)] for j in range(ROW)] dist[0][0]=mat[0][0] # visited=[] while len(queue)!=0: curr = heappop(queue) for i in range(len(x)): rows = curr[1] + x[i] cols = curr[2] + y[i] # If the coordinates are valid: if isInsideGrid(rows, cols): # Checks if neighbouring nodes are smaller (or bigger) than the previous node and current node: if dist[rows][cols]>dist[curr[1]][curr[2]]+mat[rows][cols]: # If the distance is not equal to INFINITY, then we remove the node from the queue: if dist[rows][cols] != INFINITY: queue.remove((dist[rows][cols],rows, cols)) # Update the distance matrix: dist[rows][cols]=dist[curr[1]][curr[2]]+mat[rows][cols] # Append the current node to the queue: heappush(queue, (dist[rows][cols],rows, cols)) #visited.append((curr.x, curr.y)) return(dist[ROW-1][COLUMN-1]) # Read keyboard input import operator from sys import stdin from heapq import heappush, heappop n, m = stdin.readline().split() n, m = int(n), int(m) grids=[] while n!=0 and m!=0: mat=[[0 for i in range(m)] for j in range(n)] for i in range(n): node_value=stdin.readline().strip().split() mat[i]=list(map(int, node_value)) mat.reverse() grids.append(mat) n, m = stdin.readline().split() n, m = int(n), int(m) for mat in grids: ROW=len(mat) COLUMN=len(mat[0]) print(dijkstrasAlgo(mat, ROW, COLUMN))
# To get file name print('Enter file name') filename = str(input()) #To check File Name if(filename == "" or filename=="con" or filename == "aux"): print('Error in your file name \n You cant use file names like con or aux'); else: # To get maximum number print("\nEnter maximum number") outputNumber = int(input()) # To check number if(outputNumber==0 or outputNumber > 20000): print('Error in your number. \n Make Sure you have not used 0 or number maximum than 20000') else: # Main Logic f = open(filename + '.txt', "w") for i in range(0, outputNumber): f.write(str(i+1) + '\n') f.close()
#Multiplication table a = 1 while a < 11: b = 1 while b < 11: print('%d X %d = %d' % (a, b, (a * b))) b += 1 a += 1
from Question import Question question_prompts = [ "What's the capital of Brazil?\n(a) Rio de Janeiro\n(b) Brazilia\n(c) Sao Paolo\n\n", "What's the capital of Australia?\n(a) Canberra\n(b) Sydney\n(c) Perth\n\n", "What's the capital of Pakistan?\n(a) Lahore\n(b) Islamabad\n(c) Karachi\n\n" ] questions = [ Question(question_prompts[0], "b"), Question(question_prompts[1], "a"), Question(question_prompts[2], "b"), ] def run_test(questions): score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print("You got " + str(score) + "/" + str(len(questions)) + " Correct.") run_test(questions)
# Ecommerce Purchases Exercise # # In this Exercise you will be given some Fake Data about some purchases done through Amazon! # Just go ahead and follow the directions and try your best to answer the questions and complete the tasks. Feel free to reference the solutions. # Most of the tasks can be solved in different ways. For the most part, the questions get progressively harder. # # Please excuse anything that doesn't make "Real-World" sense in the dataframe, all the data is fake and made-up. # # Also note that all of these questions can be answered with one line of code. # # ** Import pandas and read in the Ecommerce Purchases csv file and set it to a DataFrame called ecom. ** import pandas as pd econ = pd.read_csv("Ecommerce Purchases") #Check the head of the DataFrame. print(econ.head()) print('\n') # ** How many rows and columns are there? ** print(econ.info()) print('\n') # ** What is the average Purchase Price? ** print(econ['Purchase Price'].mean()) print('\n') # ** What were the highest and lowest purchase prices? ** print(econ['Purchase Price'].max()) print(econ['Purchase Price'].min()) print('\n') # ** How many people have English 'en' as their Language of choice on the website? ** print( econ[ econ['Language'] == 'en' ].count() ) print('\n') #** How many people have the job title of "Lawyer" ? ** print( econ[ econ['Job'] == 'Lawyer' ].count() ) print('\n') #** How many people made the purchase during the AM and how many people made the purchase during PM ? ** print( econ[ econ['AM or PM'] == 'PM' ]['AM or PM'].value_counts() ) print( econ[ econ['AM or PM'] == 'AM' ]['AM or PM'].value_counts() ) print('\n') # ** What are the 5 most common Job Titles? ** print( econ['Job'].value_counts().head(5) ) print('\n') #** Someone made a purchase that came from Lot: "90 WT" , what was the Purchase Price for this transaction? ** print( econ[ econ['Lot'] == '90 WT' ]['Purchase Price'] ) print('\n') #** What is the email of the person with the following Credit Card Number: 4926535242672853 ** print( econ[ econ['Credit Card'] == 4926535242672853 ]['Email'] ) print('\n') #* How many people have American Express as their Credit Card Provider *and made a purchase above $95 ?** print( econ[ (econ['CC Provider'] == 'American Express') & (econ['Purchase Price'] > 95) ].count() ) print('\n')
class Board: def __init__(self): self.board = self.initialize_pieces( [[" " for i in range(8)] for j in range(8)]) self.move_list = [] def initialize_pieces(self, board) -> list: board[1] = ['P' for i in range(8)] board[6] = ['p' for i in range(8)] board[0] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'] board[7] = [i.lower() for i in board[0]] return board def get_rowcol(self, move: str) -> tuple: return ord(move[0])-97, int(move[1])-1 def make_move(self, move: str) -> list: self.move_list.append(move) (ci, ri), (cf, rf) = self.get_rowcol( move[0:2]), self.get_rowcol(move[2:4]) # Promotions if len(move) == 5: self.board[ri][ci], self.board[rf][cf] = \ " ", \ move[4] if self.board[ri][ci].islower() else move[4].upper() # Castling elif (move in ('e1g1', 'e1c1', 'e8g8', 'e8c8')) and \ (self.board[ri][ci] in ("K", "k")): self.board[ri][ci], self.board[rf][cf] = " ", self.board[ri][ci] if move == 'e1g1': self.make_move('h1f1') self.move_list.pop() elif move == 'e1c1': self.make_move('a1d1') self.move_list.pop() elif move == 'e8g8': self.make_move('h8f8') self.move_list.pop() elif move == 'e8c8': self.make_move('a8d8') self.move_list.pop() # En Passant elif (self.board[ri][ci] in ("p", "P") and (ci != cf) and (self.board[rf][cf] == " ")): self.board[ri][cf] = " " self.board[ri][ci], self.board[rf][cf] = " ", self.board[ri][ci] # Normal moves else: self.board[ri][ci], self.board[rf][cf] = " ", self.board[ri][ci] return self.move_list def get_actual_board(self) -> str: res = [] for i in range(8): res.append(self.board[i]) return res def get_actual_board_black(self) -> str: res = [] for i in range(8): res.append(self.board[i][::-1]) return res def get_pretty_board(self) -> list: res = [] for i in range(7, -1, -1): res.append(self.board[i]) return res def __str__(self) -> str: res = [] for i in range(7, -1, -1): res.append(" ".join(self.board[i])) return "\n".join(res) if __name__ == "__main__": b = Board() print("Board: ", str(b), sep="\n") print("Actual Board: ", b.get_actual_board(), sep="\n") print(b.make_move('e2e4')) print(b.make_move('e7e5')) print(b.make_move('g1f3')) print(str(b))
import math a=10 print(type(a)) print(a) print("-------------") b=10.9 print(type(b)) print(b) print("-------------") c=5+6j print(type(c)) print(c) print("-------------") d=0B1010 print(type(d)) print(d) print("-------------") e=0XFF print(type(e)) print(e) print("-------------") f=0O77 print(type(f)) print(f) print("-------------") g=True print(type(g)) print(g) print("-------------") h=int(b) print(type(h)) print(h) print("-------------") i=float("22.3") print(type(i)) print(i) print("-------------") print(hex(10)) print(oct(10)) print(bin(10)) print(10/3) print(10//3) print(10%3) print(10**3) #round function is used to convert the decimal no to nearest integer print(round(4.5)) #Abs is used to print the absolute function print(abs(-4.6)) #Smallest integer function--> Ceil function print(math.ceil(4.1)) print(math.ceil(-4.1)) #Greatest integer function --> floor function print(math.floor(4.1)) print(math.floor(-4.1)) # Type Conversion
# How to simulate animation #required import pygame pygame.init() #create a surface gameDisplay = pygame.display.set_mode((800,600)) #initialize with a tuple #lets add a title, aka "caption" pygame.display.set_caption("Movement!") pygame.display.update() #only updates portion specified #create colors white = (255,255,255) black = (0,0,0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) #position vars x_pos = 0 y_pos = 0 gameExit = False while not gameExit: gameDisplay.fill(white) for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True # Detecting any keyboard input if event.type == pygame.KEYDOWN: # Specifies anctions based on keyboard arrows if event.key == pygame.K_LEFT: x_pos -= 10 if event.key == pygame.K_RIGHT: x_pos += 10 if event.key == pygame.K_UP: y_pos -= 10 if event.key == pygame.K_DOWN: y_pos += 10 gameDisplay.fill(blue, rect=[x_pos,y_pos, 20,20]) pygame.display.update() #required pygame.quit() quit() #exits python
import pygame pygame.init() Display = pygame.display.set_mode((600,300)) pygame.display.set_caption("Bar Graph") pygame.display.update() white = (255,255,255) black = (0,0,0) red = (255, 0, 0) green = (0, 255, 0) yellow = (255, 255, 0) # You will be visualizing this data. # (Label, Color of the bar, Length of the bar) data = [('Apple',red,15), ('Banana',yellow,45), ('Melon',green,28)] # Design your own Class # The class should be initialized with the label, color, and length of each item in the 'data' list. # The class should have a function(or multiple functions) to draw a bar graph. class Bar: def __init__ (self, name, color, num, y_coord): self.name = name self.color = color self.length = num self.y = y_coord # display parameter is same for all 3 bars # for making rectangle: pygame.draw.rect(Surface, color, Rect, width=0) # "Rect" param == [x-coord start, y-coord start, rect width, rect height] def drawGraph(self, display): pygame.draw.rect(display, self.color, [100, self.y, self.length * 10, 60]) loopCond = True while loopCond: Display.fill(white) bar_y = 20 text_y = 45 for item in data: fruitBar = Bar(item[0], item[1], item[2], bar_y) fruitBar.drawGraph(Display) bar_y += 80 f = pygame.font.Font (None, 25) # select text font and font size text = f.render(fruitBar.name, False, black) # (text contents, anti-alias ???, color) Display.blit(text, (20, text_y)) # put the text on the screen! text_y += 80 # Write the codes to draw a graph based on 'data' list. pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: loopCond = False pygame.quit() quit()
""" 다음 행렬과 같은 행렬이 있다. m = np.array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) 1.이 행렬에서 값 7 을 인덱싱한다. 2.이 행렬에서 값 14 을 인덱싱한다. 3.이 행렬에서 배열 [6, 7] 을 슬라이싱한다. 4.이 행렬에서 배열 [7, 12] 을 슬라이싱한다. 5.이 행렬에서 배열 [[3, 4], [8, 9]] 을 슬라이싱한다. """ import numpy as np a = np.array(range(15)).reshape(3,5) print(a[1,2]) print(a[2,4]) print(a[1,1:3]) print(a[1:,2]) print(a[:2,3:])
myList=[0, -5, 8, 10, 200, -100] print(myList.index(200)) print(myList.count(0)) sortList=sorted(myList) print(myList.reverse()) print((myList.remove(10))) print(len(myList)) print(copyList = myList.copy()) myList.extend([4,1,3]) myList.pop() myList.index(-5)
num= int(input("숫자입력==>")) if (num % 2 == 0) : print("짝수") else : print("홀수")
import numpy as np import matplotlib.pyplot as plt A = np.array([[1,2],[3,4],[5,6]]) print(A.shape) #(3, 2) # 행렬의 내적 A = np.array([[1,2],[3,4]]) B = np.array([[5,6],[7,8]]) print(np.dot(A,B)) A = np.array([[1,2,3],[4,5,6]]) #2*3 B = np.array([[1,2],[3,4],[5,6]])#3*2 print(np.dot(A,B)) #2*2 # A가 2차원,B가 1차원일때도 차원의 원소 수를 일치 (3*2) (2,) = 3 A = np.array([[1,2],[3,4],[5,6]])#(3*2) B = np.array([7,8]) #(2,) print(np.dot(A,B)) #(3,) x = np.array([1,2]) #(2,) w = np.array([[1,3,5],[2,4,6]]) #(2,3) 총 6개의 가중치를 갱신해 감 y = np.dot(x,w) #(3,) print(y) # Neural Network:forward propagation def sigmoid(x): return 1/(1+np.exp(-x)) X = np.array([1.0, 0.5]) W1 = np.array([[0.1,0.3,0.5], [0.2,0.4,0.6]]) b1 = np.array([0.1,0.2,0.3]) A1 = np.dot(X,W1)+b1 Z1 = sigmoid(A1) print(A1) print(Z1) W2 = np.array([[0.1,0.4],[0.2,0.5],[0.3,0.6]]) b2 = np.array([0.1,0.2]) print(Z1.shape, W2.shape, b2.shape) A2 = np.dot(Z1,W2)+b2 #Z1이 바로 이전 노드(계층)의 출력값=A1 Z2 = sigmoid(A2) W3 = np.array([[0.1,0.3],[0.2,0.4]]) b3 = np.array([0.1,0.2]) A3 = np.dot(Z2, W3)+b3 print(A3)
money, c50000, c10000, c5000, c1000 = 0, 0, 0, 0, 0 money = int(input("지폐로 교환할 돈은 얼마?")) c50000 = money // 50000 money %= 50000 c10000 = money // 10000 money %= 10000 c5000 = money // 5000 money %=5000 c1000 = money // 1000 money %=1000 print("\n5만원짜리==>%d장"% c50000) print("1만원짜리==>%d장"% c10000) print("5천원짜리==>%d장"% c5000) print("1천원짜리==>%d장"% c1000) print("지폐로 바꾸지 못한 돈 ==>%d원\n"% money)