text
stringlengths
37
1.41M
def isPrime(n): for i in range(2,int(pow(n,0.5))+1): if n%i==0: return False return True n,m=map(int,input().split()) prime=0 for i in range(n+1,m+1): if isPrime(i): prime=i break if prime==m: print("YES") else: print("NO")
# 1.6 Задача «Следующее и предыдущее» number = int(input()) nextnum = number + 1 prevnum = number - 1 dot = '.' print('The next number for the number', number, 'is', nextnum) print('The previous number for the number', number, 'is', prevnum)
# 6.13 Задача «Количество элементов, равных максимуму» i = int(input()) max_el = 0 amount = 1 while i != 0: if i > max_el: max_el = i amount = 1 elif i == max_el: amount += 1 i = int(input()) print(amount)
# 7.10 Задача «Переставить min и max» digits = [int(i) for i in input().split()] maxValue = max(digits) indexMax = digits.index(maxValue) minValue = min(digits) indexMin = digits.index(minValue) digits[indexMin], digits[indexMax] = digits[indexMax], digits[indexMin] print(' '.join([str(i) for i in digits]))
# 2.6 Сколько совпадает чисел # s = input().split() # for i in range(len(s)): # s[i] = int(s[i]) s = [] for i in range(3): s.append((input())) if s[0] == s[1] == s[2]: print(3) elif s[0] == s[1] or s[1] == s[2] or s[0] == s[2]: print(2) else: print(0)
# 3.1 Последняя цифра числа x = int(input()) print(x % 10)
# 3.4 Задача «Первая цифра после точки» from math import floor x = float(input()) f_x = floor(x) fractional_x = (x - f_x) * 10 print(floor(fractional_x))
# B351 final project # Author: Boqian Shi, Sophia Beneski, & Grant Dennany # Basic game rules and the function find the winner from itertools import combinations class Winner: ''' Takes 3 input lists: playerCards AICards, and middleCards and determines the winner example use: winner = Winner(playerCards, AICards, middleCards) print(winner) -> prints who won and each players hand winner.findWinner() -> returns "Player" if the human won or "AI" if the ai won ''' bestHands = { 10 : "Royal Flush", 9 : "Staight Flush", 8 : "Four of a Kind", 7 : "Full House", 6 : "Flush", 5 : "Straight", 4 : "Three of a Kind", 3 : "Two Pair", 2 : "One Pair", 1 : "High Card" } numbers = {'2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '10' : 10, 'J' : 11, 'Q' : 12, 'K' : 13, 'A' : 14} suits = {'Diamonds' : 1, 'Hearts' : 2, 'Spades' : 3, 'Clubs' : 4} def __init__(self, playerCards, AICards, middleCards): self.playerCards = playerCards self.AICards = AICards self.middleCards = middleCards self.return_number = -1 for card in self.middleCards: playerCards.append(card) AICards.append(card) def findWinner(self): playerBestScore, playerBestCards = self.GetBestHand(self.playerCards) AIBestScore, AIBestCards = self.GetBestHand(self.AICards) winner = "" if (playerBestScore > AIBestScore): winner = "Player" self.return_number = 0 elif (AIBestScore > playerBestScore): winner = "AI" self.return_number = 1 else: #tie case tieBreak = self.tie_breaker(list(playerBestCards), list(AIBestCards), AIBestScore) if tieBreak[1] == 1: winner = "Player" self.return_number = 0 elif tieBreak[1] == 2: self.return_number = 1 winner = "AI" else: winner = "tie" self.return_number = 2 return winner, playerBestCards, playerBestScore, AIBestCards, AIBestScore def GetBestHand(self, cards): possibleCombinations = list(combinations(cards, 5)) bestScore = 0 bestCombo = possibleCombinations[0] #runs all possible five card combinations through evaluateCards to get possible hand from 2 cards in hand plus middle cards for combo in possibleCombinations: score = self.evaluateCards(combo) if score > bestScore: bestScore = score bestCombo = combo elif score == bestScore: bestCombo = self.tie_breaker(list(bestCombo), list(combo), -1)[0] return bestScore, bestCombo def evaluateCards(self, cards): cardsConverted = [] for card in cards: tup = (self.suits[card.get_suit()], self.numbers[card.get_number()]) cardsConverted.append(tup) suits = [card[0] for card in cardsConverted] numbers = [card[1] for card in cardsConverted] if (self.check_royal_flush(suits, numbers)): return 10 elif (self.check_straight_flush(suits, numbers)): return 9 elif (self.check_four_of_kind(numbers)): return 8 elif (self.check_full_house(numbers)): return 7 elif (self.check_flush(suits)): return 6 elif (self.check_straight(suits, numbers)): return 5 elif (self.check_three_of_kind(suits, numbers)): return 4 elif (self.check_pairs(suits, numbers) == 2): return 3 elif (self.check_pairs(suits, numbers) == 1): return 2 else: return 1 def evaluate_score(self, cards): cardsConverted = [] for card in cards: tup = (self.suits[card.get_suit()], self.numbers[card.get_number()]) cardsConverted.append(tup) suits = [card[0] for card in cardsConverted] numbers = [card[1] for card in cardsConverted] if (self.check_royal_flush(suits, numbers)): return 649737 elif (self.check_straight_flush(suits, numbers)): return 72193 elif (self.check_four_of_kind(numbers)): return 4164 elif (self.check_full_house(numbers)): return 693 elif (self.check_flush(suits)): return 508 elif (self.check_straight(suits, numbers)): return 253 elif (self.check_three_of_kind(suits, numbers)): return 46 elif (self.check_pairs(suits, numbers) == 2): return 20 elif (self.check_pairs(suits, numbers) == 1): return 2 else: return 1 def check_royal_flush(self, suits, numbers): numbers.sort() if (self.check_flush(suits)): for i in range(0, 5): if not numbers[i] == 10 + i: return False return True return False def check_straight_flush(self, suits, numbers): numbers.sort() if (self.check_flush(suits)): for i in range(0, 4): if not numbers[i] + 1 == numbers[i + 1]: return False return True return False def check_four_of_kind(self, numbers): d = {number : numbers.count(number) for number in numbers} for i in d: if d[i] >= 4: return True return False def check_full_house(self, numbers): if (len(set(numbers)) == 2): return True return False def check_flush(self, suits): suits = set(suits) #gets only unique elements in suits list if (len(set(suits)) == 1): return True else: return False def check_straight(self, suits, numbers): if (len(set(numbers)) == 5): for i in range(0, 4): if not numbers[i] + 1 == numbers[i + 1]: return False return True def check_three_of_kind(self, suits, numbers): d = {number : numbers.count(number) for number in numbers} for i in d: if d[i] == 3: return True return False def check_pairs(self, suits, numbers): pairs = 0 d = {number : numbers.count(number) for number in numbers} for i in d: if d[i] == 2: pairs += 1 return pairs #this method handles tie cases and returns the tie-winning hand def tie_breaker(self, cards1, cards2, score): numbers1 = [] numbers2 = [] for i in range(0, 5): numbers1.append(cards1[i].get_number()) numbers2.append(cards2[i].get_number()) set(numbers1) set(numbers2) numbers1.sort(reverse = True) numbers2.sort(reverse = True) if score == 2: pair1 = 0 pair2 = 0 for i in range(0, len(numbers1) - 1): for j in range(i + 1, len(numbers1)): if self.numbers[numbers1[i]] == self.numbers[numbers1[j]]: pair1 = self.numbers[numbers1[i]] elif self.numbers[numbers2[i]] == self.numbers[numbers2[j]]: pair2 = self.numbers[numbers2[i]] if pair1 > pair2: return cards1, 1 elif pair1 < pair2: return cards2, 2 else: return cards1, -1 else: for i in range(0, len(numbers1)): if self.numbers[numbers1[i]] > self.numbers[numbers2[i]]: return cards1, 1 elif self.numbers[numbers2[i]] > self.numbers[numbers1[i]]: return cards2, 2 return cards1, -1 def __str__(self): results = self.findWinner() #out = "\n" * 100 out = "" ''' out += "Player:" for card in self.playerCards: out += " " + str(card) out += "\nAI:" for card in self.AICards: out += " " + str(card) out+= "\n\n\n" ''' ''' if results[0] == "Player": out += "Congratulations! You win this round.\n" elif results[0] == "AI": out += "You lose this round.\n" elif results[0] == "tie": out += "This round is a tie (both have identical best hands). \n" ''' out += "Your best hand: " + str(self.bestHands[results[2]]) + "," for i in range(0, 5): out += " " + str(results[1][i]) out += "\nThe AI's best hand: " + str(self.bestHands[results[4]]) + "," for i in range(0, 5): out += " " + str(results[3][i]) return out
# -*- coding: utf-8 -*- """ Created on Tue Jul 27 09:39:00 2021 @author: SOMDEB SAHA """ """ code for creating a simple animation for an aeroplane the motions are described in 2-D as: x = 800*t y = 200 """ #importing required libraries import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.gridspec as gridspec ########################################### # creating time array t0 = 0 #initial time t_end = 2 # final time dt = 0.005 #time interval or delta_t # np.arange ( start, stop, time_interval)... does not include stop variable t = np.arange(t0, t_end+dt, dt) ########################################### #creating 2-D x and y data x = 800 * t y = 200 * np.ones(len(t)) ################# animation ############################################ frame_amount = len(t) # this has to be kept same as time series length def update_plot(num): # This function will update the line object at every animation interval plane_trajectory.set_data(x[0:num], y[0:num]) return plane_trajectory, fig = plt.figure(figsize=(16,9), dpi=120, facecolor=(0.8,0.8,0.8)) #set up the figure proporties gs = gridspec.GridSpec(2, 2) # divide the figure into a matrix of (2,2) ax0 = fig.add_subplot(gs[0,:], facecolor=(0.9,0.9,0.9)) #assign the first plot an area same as first row plane_trajectory, = ax0.plot([], [], 'g', linewidth=2) #create a line object plane_trajectory which will be updated at every animation interval plt.xlim(x[0],x[-1]) plt.ylim(100,250) plane_ani = animation.FuncAnimation(fig, update_plot, frames=frame_amount, interval=20, repeat=True, blit=True) plt.show()
courses = ['Arts', 'Physics', 'Chemistry', 'Maths'] courses_supplementary = ['French', 'Hindi'] num_range = list(i for i in range(31)) # read course by index # 0,1 (2 not included) print(courses[0:2]) # num_list[-9:], read the part in the brackets as "9th from the end, to the end." or "-9, onwards" print(courses[-2:]) # to slice using step jumps sequence[start:stop:step] print(num_range[-10::2]) # we can also put slice in a variable. However the assignment needs to happen through the slice object. slice (stop) # first argument is stop: slice(stop); e.g. slice_object = slice(2) # prints stopping BEFORE 2 i.e. 0,1,2 e.g. print(courses[slice_object]) # if you want first argument to be start use slice(start, None) e.g. slice_object = slice(2, None) # prints 2 to end of list print(courses[slice_object]) # modifying a list courses.append("Comp Sci") # sort a list. Note that reverse attribute does the reverse sort. ** Note : case matters True (vs TRUE, true) courses.sort(reverse=True) # sorted does not mutate coureses while courses.sort will mutate courses. Acting on the object vs. passing data az_courses = sorted(courses) courses.pop() # adding a new list in a flat way to the new list. Note that append will add the new list as an element and not as a flat item list courses.extend(courses_supplementary) print(courses) print(az_courses) # get index of an item in a list print(courses.index('Chemistry')) print('Chemistry' in courses) # exists print('Philosophy' in courses) # does not exist # if we need to get both the index and the value from a list we can use enumerate. To have index start at 1 (instead of 0) use parameter start=1 for index, course in enumerate(courses, start=1): print(index, course) # to convert a list to a string use join with separator str_courses = ','.join(courses) print(str_courses) # to get back the list use split list_courses = str_courses.split(',') print(list_courses) # Lists (and dict) are mutable. list2 = list1 is assigns both pointers to be the same memory address so change in one changes the other. copy_courses = courses # To create a new list from contents but not share addresses create a new list by list() or slicing [:] new_courses = list(courses) # we can also use new_courses = courses[:] # verifying that one was a shared pointer and the other was a new copy courses[0] = "Engineering fundamentals" print("courses -- original ", courses, id(courses)) print("copy_courses -- shared pointer ", copy_courses, id(copy_courses)) print("new courses -- new list with content of original ", new_courses, id(new_courses))
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" shortest = min(strs, key=len) for i, ch in enumerate(shortest): for other in strs: if other[i] != ch: return shortest[:i] return shortest def longestCommonPrefix_1(self, strs): longest_pre = "" if not strs: return longest_pre shortest_str = min(strs, key=len) for i in range(len(shortest_str)): if all([x.startswith(shortest_str[:i+1]) for x in strs]): longest_pre = shortest_str[:i+1] else: break return longest_pre def longestCommonPrefix_2(self, strs): if not strs: return "" for i, letter_group in enumerate(zip(*strs)): if len(set(letter_group)) > 1: return strs[0][:i] else: return min(strs) if __name__=="__main__": solution = Solution() strs = ["flower","flow","flight",'for'] print(solution.longestCommonPrefix_2(strs))
class Solution(object): def uniquePaths(self, m, n): """ time O(mn) space O(mn0 :type m: int :type n: int :rtype: int """ if not m or not n: return 0 if m == 1 or n == 1: return 1 d = [[0] * n for _ in range(m)] for i in range(m): d[i][0] = 1 for j in range(n): d[0][j] = 1 for i in range(1, m): for j in range(1, n): d[i][j] = d[i - 1][j] + d[i][j - 1] return d[m-1][n-1] if __name__ == '__main__': solution = Solution() print(solution.uniquePaths(3,3))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 left_branch = self.maxDepth(root.left) + 1 right_branch = self.maxDepth(root.right) + 1 return max(left_branch,right_branch) def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if root.left is None and root.right is None: return 0 diameter = self.maxDepth(root.left) + self.maxDepth(root.right) + 2 diameter_left = self.diameterOfBinaryTree(root.left) diameter_right = self.diameterOfBinaryTree(root.right) return max(diameter, diameter_left, diameter_right)
def is_abecedarian(word): word = word.lower() for i in range(len(word) - 1): if word[i] > word[i + 1]: return False return True print(is_abecedarian('AbCA'))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSubtree(self, s, t): #mei xie chu lai """ 深度优先搜索暴力匹配 深度优先搜索枚举 sss 中的每一个节点,判断这个点的子树是否和 ttt 相等。如何判断一个节点的子树是否和 ttt 相等呢,我们又需要做一次深度优 先搜索来检查,即让两个指针一开始先指向该节点和 ttt 的根,然后「同步移动」两根指针来「同步遍历」这两棵树,判断对应位置是否相等 Time O(s * t) space:假设 s 深度为 ds,t 的深度为 dt,任意时刻栈空间的最大使用代价是 O(max{ds,dt})O。故渐进空间复杂度为 O(max{ds,dt}) :type s: TreeNode :type t: TreeNode :rtype: bool """ return self.dfs(s, t) def dfs(self, s, t): if not s: return False return self.check(s,t) or self.dfs(s.left, t) or self.dfs(s.right, t) def check(self, s, t): if not s and not t: return True if not s or not t or s.val != t.val: return False return self.check(s.left, t.left) and self.check(s.right, t.right) def isSubtree_preorder(self, s, t): #mei xie chu lai """ 假设 s 由两个点组成,1 是根,2 是 1 的左孩子;t 也由两个点组成,1 是根,2 是 1 的右孩子。这样一来 s 和 t 的深度优先搜索序列相同, 可是 t 并不是 s 的某一棵子树。由此可见「s 的深度优先搜索序列包含 t 的深度优先搜索序列」是「t 是 s 子树」的必要不充分条件, 所以单纯这样做是不正确的。 为了解决这个问题,我们可以引入两个空值 lNull 和 rNull,当一个节点的左孩子或者右孩子为空的时候,就插入这两个空值,这样深度优先搜索序列 就唯一对应一棵树。处理完之后,就可以通过判断「s 的深度优先搜索序列包含 t 的深度优先搜索序列」来判断答案 time O(m^2 + n^2 + m*n) space O(max(m, n)) :param s: :param t: :return: """ # trees = set() tree1 = self.preorder(s, True) tree2 = self.preorder(t, True) return tree2 in tree1 def preorder(self, t, left): if not t: if left: return 'lnull' else: return 'rnull' return '#' + t.val + " " + self.preorder(t.left, True) + ' ' + self.preorder(t.right, False)
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ return sorted(s) == sorted(t) def isAnagram1(self, s, t): dic1, dic2 = {}, {} for item in s: dic1[item] = dic1.get(item, 0) + 1 for item in t: dic2[item] = dic2.get(item, 0) + 1 return dic1 == dic2 def is_anagram(self,s, t): from collections import Counter c1 = Counter(s) c2 = Counter(t) return c1 == c2 if __name__=="__main__": solution = Solution() print(solution.isAnagram('anagram','nagaram')) print(solution.isAnagram('rat','cat'))
""" 冒泡排序 """ def bubbleSort(arr): for i in range(1, len(arr)): for j in range(0, len(arr) - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr def bubbleSort_opt(arr): for i in range(1, len(arr)): swap = False for j in range(0, len(arr) - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swap = True if not swap: break return arr """ 选择排序 """ def selectionSort(arr): for i in range(len(arr) - 1): minIndex = i for j in range(i + 1, len(arr)): if arr[j] < arr[minIndex]: minIndex = j if i != minIndex: arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr """ 插入排序 """ def insertionSort(arr): for i in range(1, len(arr)): preIndex = i - 1 current = arr[i] while preIndex >= 0 and arr[preIndex] > current: arr[preIndex + 1] = arr[preIndex] preIndex -= 1 arr[preIndex + 1] = current return arr """ 希尔排序 """ def shellSort(arr): import math gap = 1 while gap < len(arr) / 3: gap = gap * 3 + 1 while gap: for i in range(gap, len(arr)): temp = arr[i] j = i - gap while j >= 0 and arr[j] > temp: arr[j + gap] = arr[j] j -= gap arr[j + gap] = temp gap = math.floor(gap / 3) return arr def shellSort1(arr): import math length = len(arr) gap = math.floor(length / 2) while gap: for i in range(gap, length): j = i current = arr[i] while j - gap >=0 and current < arr[j - gap]: arr[j] = arr[j - gap] j = j - gap arr[j] = current gap = math.floor(gap / 2) return arr """ 归并排序 """ def mergeSort(arr): if len(arr) < 2: return arr middle = len(arr) // 2 left, right = arr[0:middle], arr[middle:] return merge(mergeSort(left), mergeSort(right)) def merge(left, right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) while left: result.append(left.pop(0)) while right: result.append(right.pop(0)) return result """ 快速排序 """ def quickSort(arr, left=None, right=None): left = 0 if not isinstance(left, (int, float)) else left right = len(arr) - 1 if not isinstance(right, (int, float)) else right if left < right: partitionIndex = partition(arr, left, right) quickSort(arr, left, partitionIndex - 1) quickSort(arr, partitionIndex + 1, right) return arr def partition(arr, left, right): pivot = left index = pivot + 1 i = index while i <= right: if arr[i] < arr[pivot]: swap(arr, i, index) index += 1 i += 1 swap(arr, pivot, index - 1) return index - 1 def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] """ 堆排序 """ def heapSort(arr): global arrLen arrLen = len(arr) buildMaxHeap(arr) for i in range(len(arr) - 1, 0, -1): arr[0], arr[i] = arr[i], arr[0] swap(arr, 0, i) arrLen -= 1 heapify(arr, 0) return arr def heapify(arr, i): left = 2 * i + 1 right = 2 * i + 2 largest = i if left < arrLen and arr[left] > arr[largest]: largest = left if right < arrLen and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, largest) def buildMaxHeap(arr): for i in range(len(arr) // 2, -1, -1): heapify(arr, i) """ 计数排序 """ def countingSort(arr, maxValue): bucketLen = maxValue + 1 bucket = [0] * bucketLen sortedIndex = 0 arrLen = len(arr) for i in range(arrLen): if not bucket[arr[i]]: bucket[arr[i]] = 0 bucket[arr[i]] += 1 for j in range(bucketLen): while bucket[j] > 0: arr[sortedIndex] = j sortedIndex += 1 bucket[j] -= 1 return arr """ 桶排序 """ def buckectSort(arr): min_num = min(arr) max_num = max(arr) bucket_range = (max_num - min_num) / len(arr) + 1 count_list = [[] for i in range(bucket_range)] for i in arr: count_list[(i - min_num) // len(arr)].append(i) arr.clear() for i in count_list: for j in sorted(i): arr.append(j) """ 基数排序 """ def radixSort(arr): n = len(str(max(arr))) for i in range(n): bucket_list = [[] for _ in range(10)] for j in arr: bucket_list[j // (10 ** i) % 10].append(j) arr = [b for a in bucket_list for b in a] return arr if __name__ == '__main__': print(countingSort([5,8,7,9,1,6,4,3,2,0, 4,3,2,1], 9))
class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.stack = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ self.stack.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ element = self.stack[0] self.stack = self.stack[1:] return element def peek(self): """ Get the front element. :rtype: int """ return self.stack[0] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ if len(self.stack) == 0: return True else: return False class MyQueue_twostacks(object): def __init__(self): """ Time O(1) Space O(1) Initialize your data structure here. """ self.input = [] self.output = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ self.input.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ self.peek() return self.output.pop() def peek(self): """ Get the front element. :rtype: int """ if self.output == []: while self.input != []: self.output.append(self.input.pop()) return self.output[-1] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return self.input == [] and self.output == [] # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
class Solution(object): def reverseString(self, s): """ Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ l = 0 r = len(s) - 1 while l < r: s[l], s[r] = s[r], s[l] l += 1 r -= 1 def reverseString_1(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ s.reverse() # return s[::-1] if __name__ == '__main__': solution = Solution() print(solution.reverseString(["h","e","l","l","o"]))
import re class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} #使用set更快 # vowels = set(list('aeiouAEIOU')) s = list(s) left, right = 0, len(s) - 1 while left < right: if s[left] not in vowels: left += 1 elif s[right] not in vowels: right -= 1 else: s[left], s[right] = s[right], s[left] left += 1 right -= 1 return ''.join(s) def reverseVowels_regex(self, s): """ :type s: str :rtype: str """ vowels = re.findall('(?i)[aeiou]', s) # (?i)表示忽略大小写 # repl参数每次返回一个值,用来替换s匹配pattern的字符。 return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) if __name__ == '__main__': solution = Solution() print(solution.reverseVowels('leetcode'))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def minDepth(self, root): #mei xie chu lai """ 方法一:深度优先搜索 首先可以想到使用深度优先搜索的方法,遍历整棵树,记录最小深度。 对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。 Time O(n) space O(logN) or O(n) :type root: TreeNode :rtype: int """ if not root: return 0 if not root.left and not root.right: return 1 min_depth = 10 ** 9 if root.left: min_depth = min(self.minDepth(root.left), min_depth) if root.right: min_depth = min(self.minDepth(root.right), min_depth) return min_depth + 1 def minDepth_bfs(self, root): #mei xie chu lai """ 当我们找到一个叶子节点时,直接返回这个叶子节点的深度。广度优先搜索的性质保证了最先搜索到的叶子节点的深度一定最小 time O(n) space O(n) 其中 N 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数 :param root: :return: """ import collections if not root: return 0 queque = collections.deque([(root, 1)]) while queque: node, depth = queque.popleft() if not node.left and not node.right: return depth if node.left: queque.append((node.left, depth + 1)) if node.right: queque.append((node.right, depth + 1)) return 0 def minDepth_1(self, root): #mei xie chu lai """ We need to add the smaller one of the child depths - except if that's zero, then add the larger one. :param root: :return: """ if not root: return 0 d = list(map(self.minDepth_1, (root.left, root.right))) return 1 + (min(d) or max(d)) # if root == None: # return 0 # if root.left == None or root.right == None: # return self.minDepth(root.left) + self.minDepth(root.right) + 1 # return min(self.minDepth(root.right), self.minDepth(root.left)) + 1
class Solution: def findLongestWord(self, s, dictionary) : dictionary = sorted(dictionary, key=lambda x: (-len(x), x)) print(dictionary) for word in dictionary: i = 0 for char in s: if i < len(word) and word[i] == char: i += 1 if i == len(word): return word return "" def findLongestWord_without_sorting(self, s, dictionary): """ Since sorting the dictionary could lead to a huge amount of extra effort, we can skip the sorting and directly look for the strings xxx in the unsorted dictionary ddd such that xxx is a subsequence in sss. If such a string xxx is found, we compare it with the other matching strings found till now based on the required length and lexicographic criteria. Thus, after considering every string in ddd, we can obtain the required result. :param s: :param dictionary: :return: """ maxstr = '' for word in dictionary: if self.issubsequence(word, s): if len(word) > len(maxstr) or (len(word) == len(maxstr) and word < maxstr): maxstr = word return maxstr def issubsequence(self, word, s): i = j = 0 while j < len(word): if i == len(s): break if word[j] == s[i]: j += 1 i += 1 return j == len(word) if __name__ == '__main__': solution = Solution() print(solution.findLongestWord(s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]))
""" 输入两个链表,找出它们的第一个公共节点。 如下面的两个链表: 在节点 c1 开始相交。 示例 1: 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。 示例 2: 输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 输出:Reference of the node with value = 2 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。 示例 3: 输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 输出:null 输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。 解释:这两个链表不相交,因此返回 null。 注意: 如果两个链表没有交点,返回 null. 在返回结果后,两个链表仍须保持原有的结构。 可假定整个链表结构中没有循环。 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 本题与主站 160 题相同:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ """ class Solution: def FindFirstCommonNode(self, pHead1, pHead2): if pHead1 is None or pHead2 is None: return None p = pHead1 q = pHead2 while p != q: p = pHead2 if p is None else p.next q = pHead1 if q is None else q.next return p
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res = {} ll = [] from collections import Counter n1 = Counter(nums1) n2 = Counter(nums2) for each in n1.keys(): if each in n2.keys(): res[each] = min(n1[each], n2[each]) for key in res.keys(): ll.extend([key] * res[key]) return ll def intersect_solution1(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import Counter return list((Counter(nums1) & Counter(nums2)).elements()) def intersect_solution2(self, nums1, nums2): """ two pointers :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1, nums2 = sorted(nums1), sorted(nums2) pt1 = pt2 = 0 res = [] while True: try: if nums1[pt1] > nums2[pt2]: pt2 += 1 elif nums1[pt1] < nums2[pt2]: pt1 += 1 else: res.append(nums1[pt1]) pt1 += 1 pt2 += 1 except IndexError: break return res def intersect_solution3(self, nums1, nums2): """ two pointers :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ import collections counts = collections.Counter(nums1) res = [] for num in nums2: if counts[num] > 0: res += num counts[num] -= 1 return res if __name__ == '__main__': solution = Solution() print(solution.intersect_solution1([1, 2, 2, 1], [2, 2])) print(solution.intersect_solution1([4, 9, 5], [9,4,9,8,4])) print(solution.intersect_solution1([1, 1], [1, 1, 2]))
""" 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 限制: 0 <= 节点个数 <= 5000 注意:本题与主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/ """ class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = None while head: cur = head head = head.next cur.next = prev prev = cur return prev
from pythonds.basic import Stack class Solution(object): def isValid_stack(self, s): #导入栈模块 """ :type s: str :rtype: bool """ opens = '([{' closes = ')]}' parstack = Stack() balance = True for each in s: if each in '([{': parstack.push(each) else: if parstack.isEmpty(): balance = False else: top = parstack.pop() if opens.index(top) != closes.index(each): balance = False if balance and parstack.isEmpty(): return True else: return False def isValid(self, s): #没有栈模块 """ :type s: str :rtype: bool """ # opens = '([{' # closes = ')]}' pairs = {'(':')', '[':']', '{':'}'} parstack = [] for each in s: if each in '([{': parstack.append(each) else: if len(parstack) == 0: return False else: # if opens.index(top) != closes.index(each): if pairs[parstack.pop()] != each: return False return len(parstack) == 0 if __name__=="__main__": solution = Solution() print(solution.isValid("{[]}"))
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if not s: return 0 substring = [s[0]] count_max = 1 for i in range(1, len(s)): if s[i] not in substring: substring.append(s[i]) else: count_max = max(count_max, len(substring)) index = substring.index(s[i]) substring = substring[index + 1:] substring.append(s[i]) return max(count_max, len(substring)) if __name__ == '__main__': solution = Solution() print(solution.lengthOfLongestSubstring('au')) print(solution.lengthOfLongestSubstring('pwwkew')) print(solution.lengthOfLongestSubstring('bbbbbb')) print(solution.lengthOfLongestSubstring('abcabcbb'))
""" 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。 示例1 输入 {67,0,24,58} 返回值 [58,24,0,67] """ class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): res = [] while listNode: res.append(listNode.val) listNode = listNode.next return res[::-1] def printListFromTailToHead_stack(self, listNode): """ time O(n) space O(n) :param listNode: :return: """ stack = [] while listNode: stack.append(listNode.val) listNode = listNode.next ans = [] while stack: ans.append(stack.pop()) return ans def printListFromTailToHead_recursion(self, listNode): """ time O(n) space O(n) :param listNode: :return: """ return self.printListFromTailToHead_recursion(listNode.next) + [listNode.val] if listNode else []
""" 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25 说明: -100.0 < x < 100.0 n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。 """ class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ def quickMul(N): if N == 0: return 1.0 y = quickMul(N // 2) return y * y if N % 2 == 0 else y * y * x return quickMul(n) if n >=0 else 1.0 / quickMul(-n)
class Solution(object): def majorityElement(self, nums): """ Hash Map Time O(n) Space O(n) :type nums: List[int] :rtype: int """ from collections import Counter dic = Counter(nums) max_val = max(dic, key=dic.get) return max_val def majorityElement_sorting(self, nums): """ Sorting Time O(nlogn) Space O(1) or O(n) :type nums: List[int] :rtype: int """ nums.sort() return nums[len(nums)//2] def majorityElement_boyermoore_voting(self, nums): """ Boyer-Moore Voting algorithm Time O(n) Space O(1) :type nums: List[int] :rtype: int """ count, candidate = 0, None for num in nums: if count == 0: candidate = num count += (1 if num == candidate else -1) return candidate if __name__ == "__main__": solution = Solution() print(solution.majorityElement([2,2,1,1,1,2,2]))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSameTree(self, p, q): """ Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a recursion stack. :type p: TreeNode :type q: TreeNode :rtype: bool """ if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) def isSameTree_iteration(self, p, q): """ iteration :param p: :param q: :return: """ from collections import deque def check(p, q): if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return True deq = deque([(p, q),]) while deq: p, q = deq.popleft() if not check(p, q): return False if p: deq.append((p.left, q.left)) deq.append((p.right, q.right)) return True
class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype """ for i in range(1, len(s)): if s[:i] * (len(s) // i) == s: return True return False def repeatedSubstringPattern_cool_solution(self, str): """ Basic idea: First char of input string is first char of repeated substring Last char of input string is last char of repeated substring Let S1 = S + S (where S in input string) Remove 1 and last char of S1. Let this be S2 If S exists in S2 then return true else false Let i be index in S2 where S starts then repeated substring length i + 1 and repeated substring S[0: i+1] Checking if S is a sub-string of (S+S)[1:-1] basically checks if the string is present in a rotation of itself for all values of R such that 0 < R < len(S) :type str: str :rtype: bool """ if not str: return False ss = (str + str)[1:-1] return ss.find(str) != -1 if __name__ == '__main__': solution = Solution() print(solution.repeatedSubstringPattern_cool_solution('abab')) print(solution.repeatedSubstringPattern('aba')) print(solution.repeatedSubstringPattern('abcabcabcabc'))
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x <0: return False reversed_number = int(str(x)[::-1]) if reversed_number == x: return True else: return False if __name__=="__main__": solution = Solution() solution.isPalindrome(-121)
class Solution(object): def containsDuplicate(self, nums): """ or seen method in hash map :type nums: List[int] :rtype: bool """ from collections import Counter if not nums: return False dic = Counter(nums) return not max(dic.values()) == 1 def containsDuplicate_sorting(self, nums): """ time O(nlogn) space O(1) :type nums: List[int] :rtype: bool """ nums.sort() for i in range(1, len(nums)): if nums[i] == nums[i -1]: return True return False def containsDuplicate_easy(self, nums): """ :type nums: List[int] :rtype: bool """ return True if len(set(nums)) < len(nums) else False if __name__ == '__main__': solution = Solution() print(solution.containsDuplicate([1, 2, 3, 4]))
# 함수 기간 주소록 관리 프로그램 import sqlite3 # Dao : Data Access Object class SqliteAddressDao: "Sqlite에 주소록 입출력을 담당하는 클래스" def __init__(self,filename): self.conn = sqlite3.connect(filename) self.cursor = self.conn.cursor() def __del__(self): self.cursor.close() self.conn.close() def intputAddress(self,tablename,address): sql = """ INSERT INTO {0}(name,age,addr) VALUES('{1}'.'{2}'.'{3}') """.format(tablename,address.name,address.age,address.addr) self.cursor.execute(sql) self.conn.commit() def searckAddress(self,tableName, name): sql = """ SELECT * FROM {0} WHERE name = '{1}' """.format(tableName,name) self.cursor.execute(sql) return self.cursor.fetchone() def deleteAddress(self, tableName, name): sql = """ SELECT * FROM {0} WHERE name = '{1}' """.format(tableName, name) self.cursor.execute(sql) self.conn.commit() def updateAddress(self,tableName,fname,address): sql = """ UPDATE {0} SET name='{1}', age='{2}', addr='{3}' WHERE name='{4}' """.format(tableName, address.name, address.age, address.addr, fname) self.cursor.execute(sql) self.conn.commit() def searchAddress(self,tableName): sql = """ SELECT * FROM {0} """.format(tableName) self.cursor.execute(sql) return self.curses.fetchall() class Address: "주소 객체를 생성할 클래스" def __init__(self,name,age,addr): self.name = name self.age = age self.addr = addr def showAddress(self,idx): print('+'*10,end='') print(idx,end='') print('name : ',self.name) print('age : ', self.age) print('addr : ', self.addr) def showMenu(): "메뉴 보여주는 함수" print('\n\n') print('*'*10,'Menu','*'*10) print('1.Input') print('2.Search') print('3.Delete') print('4.Update') print('5,SearchAll') print('6.Exit') def getSelectNum(): return int(input("select Menu >>")) def inputAddress(): "주소 입력 후 저장 함수" print('*** intput ***') name = input('name >>') age = input('age >>') addr = input('addr >>') address = Address(name,age,addr) g_SqliteAddressDao.intputAddress(tablename='address',address=address) def searchAddress(): "주소 검색 함수" print('***search***') name = input("find name >> ") addressOne = g_SqliteAddressDao.searckAddress(tableName='address',name=name) address = Address(addressOne[1],addressOne[2],addressOne[3]) address.showAddress(addressOne[0]) def deleteAddress(): "주소 삭제 함수" print('***delete***') name = input("delete name >> ") g_SqliteAddressDao.deleteAddress(tableName='address',name=name) def updateAddress(): "주소 변경 함수" print('***update***') uname = input("update name >> ") name = input('new name >>') age = input('new age >>') addr = input('new addr >>') address = Address(name,age,addr) g_SqliteAddressDao.updateAddress(tableName='address',fname=uname,address=address) def searchAllAddress(): "모든 주소 검색 함수" print('***searchAll***') addressList = g_SqliteAddressDao.searchAllAdress(tableName='address') for addr in addressList: address = Address(addr[1],addr[2],addr[3]) address.showAddress(addr[0]) def main(): "전체 시작 함수" while True: showMenu() num = getSelectNum() if num == 1: inputAddress() elif num == 2: searchAddress() elif num == 3: deleteAddress() elif num == 4: updateAddress() elif num == 5: searchAllAddress() elif num == 6: break else: print("메뉴를 잘 못 선택했습니다.") # ************************** 전역변수 start *********** g_SqliteAddressDao = SqliteAddressDao('address.db') # ************************** 전역변수 end ************* if __name__ == '__main__': main()
#this program RSA encrypts a message from the user from __future__ import print_function import math def gcd(x,y): a=max(x,y) b=min(x,y) while(b!=0): c=a%b a=b b=c return a def phi(x,y): phicount=1 phicount=x*y-x-y+1 return phicount def lin_soln(a,b): x=1 g=a v=0 w=b while w!=0: y=(g-a*x)/b t=g%w q=g//w #int(math.floor(g/w)) s=x-q*v x=v g=w v=s w=t y=(g-a*x)/b y=-y #make sure the chosen solution has positive x while x<0: x=x+b y=y+a return (x,y) def succ_square(a,k,m): b=1 while k>=1: if k%2!=0: b=(a*b)%m a=(a*a)%m k=k//2 #math.floor(k/2) b=b%m return b def alphabet(letter): letter=letter.replace('A','11') letter=letter.replace('B','12') letter=letter.replace('C','13') letter=letter.replace('D','14') letter=letter.replace('E','15') letter=letter.replace('F','16') letter=letter.replace('G','17') letter=letter.replace('H','18') letter=letter.replace('I','19') letter=letter.replace('J','20') letter=letter.replace('K','21') letter=letter.replace('L','22') letter=letter.replace('M','23') letter=letter.replace('N','24') letter=letter.replace('O','25') letter=letter.replace('P','26') letter=letter.replace('Q','27') letter=letter.replace('R','28') letter=letter.replace('S','29') letter=letter.replace('T','30') letter=letter.replace('U','31') letter=letter.replace('V','32') letter=letter.replace('W','33') letter=letter.replace('X','34') letter=letter.replace('Y','35') letter=letter.replace('Z','36') number=int(letter) return number def breakup(b,m): new=[] b=str(b) limit=len(str(m)) #(OR DELETE -1 IF YOU WANT IT EQUAL TO DIGITS OF M) i=0 while i<=len(b)-1:#len(b)-limit: if i%limit==0: if i+limit-1<=len(b): new.append(b[i:i+limit]) else: new.append(b[i:]) i=i+1 square=[] for i in range(len(new)): square.append(int(new[i])) return square def user_info_to_decode(int): if int==0: #use the test example p = 123456789012345681631 q = 7746289204980135457 k = 12398737 m = p * q message='WETHEPEOPLEOFTHEUNITEDSTATESINORDERTOFORMAMOREPERFECTUNIONESTABLISHJUSTICEINSUREDOMESTICTRANQUILITYPROVIDEFORTHECOMMONDEFENSEPROMOTETHEGENERALWELFAREANDSECURETHEBLESSINGSOFLIBERTYTOOURSELVESANDOURPROSTERITYDOORDAINANDESTABLISHTHISCONSTITUTIONFORTHEUNITEDSTATESOFAMERICA' else: #ask the suer for their message to decode p=input('What is the private key p?') q=input('What is the private key q?') k=input('What is the pubic key k relatively prime to phi(m)=phi(pq)?') m=p*q #obtain the message to decode message=input('What is the message to encode?') return p,q,k,m,message userinput=input('If you would like to use the test example, type 0. If you would like to enter in your own data, type 1.') p,q,k,m,message=user_info_to_decode(userinput) #compute phi(m) phim=phi(p,q) #verify gcd(phi(m),k)=1 if gcd(phim,k)!=1: print('cant use algorithm - gcd(phi(m),k) does not equal 1') #convert letters to numbers b=alphabet(message) #break up message into strings of digits that are equal to the digits of m square=breakup(b,m) print('The encoded message is: ') for i in range(len(square)): #verify gcd(b,m)=1 if gcd(square[i],m)!=1: print('cant use algorithm - gcd(b,m) does not equal 1') #use successive squares to calculate b^k y=succ_square(square[i],k,m) #encode message print(y)
#PART 1: Terminology #1) Give 3 examples of boolean expressions. #a) 1 == 1 #b) 2 >= 3 #c) "Hello" != "bye" # 3 points #2) What does 'return' do? # returns some form of output from a function # 0 points # # #3) What are 2 ways indentation is important in python code? #a) clearly separates different parts of code #b) tells us what code is in what function # 1 points # #PART 2: Reading #Type the values for 12 of the 16 of the variables below. # #problem1_a) -36 #problem1_b)negative the square root of 3 #problem1_c) 0 #problem1_d) -5 # 4 points #problem2_a) True #problem2_b) False #problem2_c) False #problem2_d) False # 3 points #problem3_a) 0.3 #problem3_b) 0.5 #problem3_c) 0.5 #problem3_d) 0.5 # 4 points #problem4_a) 24 #problem4_b) 6 #problem4_c) 1.5 #problem4_d) 5 # 4 points #PART 3: Programming #Write a script that asks the user to type in 3 different numbers. #If the user types 3 different numbers the script should then print out the #largest of the 3 numbers. #If they don't, it should print a message telling them they didn't follow #the directions. #Be sure to use the program structure you've learned (main function, processing function, output function) def compare(a, b, c): if a > b and a > c and b != c: return a elif b > a and b > c and a != c: return b elif c > a and c > b and a != b: return c else: return "Wrong" def output1(num): out = "The largest number was " + str(num) return out def output2(): out = "You didnt follow diections" return out def main(): #Input Section a = float(raw_input("Type in 3 different numbers (decimals are OK!)\nA: ")) b = float(raw_input("B: ")) c = float(raw_input("C: ")) #Processing compareres = compare(a, b, c) if compareres == "Wrong": res = output2() elif compareres == float(compareres): res = output1(compareres) #Output Section print res main() # +1 correct function headers (ALL MUST BE CORRECT) +1 # +1 correctly structured script: # (main function defined, process functions defined, process functions called +1 # in main, calls main) # +1 use if...elif...else or an equivalent structure +1 # +1 uses a boolean expression to test numbers +1 # +1 CORRECTLY determines and returns largest number +1 # +1 uses if...else or an equivalent structure +1 # +1 uses a boolean expression to test equality +1 # +1 CORRECTLY determines and returns if the numbers are all different +1 # +1 gets and converts 3 values correctly +1 # +1 uses conditional to give feedback if numbers are not all different +1
import unittest from .models import News,Sources class NewsTest(unittest.TestCase): ''' test instance to check the behavior of the news class ''' def setUp(self): ''' This method runs before every test ''' self.news1 = News("New York Times", "Trump is a genius", "I don't have DNA, I have USA", "12th October 2020" ) def test_instance(self): self.assertTrue(isinstance(self.news1,News)) class SourceTest: ''' test source class and its behaviours ''' def setUp(self): self.new_source = Source(123, 'preston', 'description', 'url') def test_instance(self): self.assertTrue(isinstance(self.new_source))
# Using int() and float() # a = input("Enter a string with letters,numbers,symbols") # b = int(a) # Returns an error # print(b) # b = int("5.39") # A string that is float # print(b) # Returns an error # b = int(5.39) # float value # print(b) # Returns the nearest integer smaller than or equal to the float # b = int("10.3+4.2") # A string that is an expression # print(b) # Returns an error # b = int(10.3+4.2) # float value expression # print(b) # Returns the nearest integer smaller than or equal to the float output # a = input("Enter a string with letters,numbers,symbols") # b = float(a) # Returns an error # print(b) # b = float("5") # A string that is an integer # print(b) # Returns a float value:5.0 # b = float(5) # integer value # print(b) # Returns a float value:5.0 # b = float("10+4") # A string that is an expression # print(b) # Returns an error b = float(10.3+4.2) # float value expression print(b) # Returns the float output
# for(start integer,stop integer,step for increment or decrement) for i in range(1, 20, 2): print(i)
ex_1 = (3.23*100+0.80*100)/100 ex_2 = 5/2 # Division ex_3 = 5*2 # Multiplication ex_4 = 5+2 # Addition ex_5 = 5-2 # Subtraction ex_6 = 5 % 2 # Modulo ex_7 = 5//2 # Floor-Division ex_8 = 5**2 # Exponentiation print(ex_1) print(ex_2) print(ex_3) print("Addition", ex_4) print(ex_5) print(ex_6) print(ex_7) print(ex_8) ex_9: float = 2.15 print("float", ex_9)
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 15:31:19 2021 @author: 57314 """ # Elaborar una función que reciba tres enteros y nos retorne el valor promedio de los mismos def retornar_promedio(v1,v2,v3): promedio=(v1,v2,v3)/3 return promedio # valor1=int(input("ingrese primer valor:")) valor2=int(input("ingrese segundo valor:")) valor3=int(input("ingrese tercer valor:")) print("promedio de los tres numeros ingresados:",retornar_promedio(valor1,valor2,valor3))
from math import sqrt def task_num_107(): """ Дано целое число m > 1 Получить наибольшое целое к, при котором 4^к < m """ m = int(input('\'Task 107\' Input your natural number : ')) counter = 1 a = 4 while a < m: a *= a counter += 1 return counter def task_num_243_a(): """ Дано натуральное число n. Можно ли представить его в виде суммы двух квадратов натуральных чисел? a) указать пару чисел х, у таких натуральных чисел, что n = x^2 + y^2 """ n = int(input("\'Task 243 a\' Input your natural number : ")) res = [] for x in range(int(sqrt(n)) + 1): for y in range(x, int(sqrt(n)) + 1): if x ** 2 + y ** 2 == n: pair = f'{x} {y}' res.append(pair) if len(res) == 0: return "This number can not be represented as the sum of two squares" return res[0] def task_num_243_b(): """ Дано натуральное число n. Можно ли представить его в виде суммы двух квадратов натуральных чисел? б) указать все пары чисел х, у таких натуральных чисел, что n = x^2 + y^2 """ res = [] n = int(input("\'Task 243 b\' Input your natural number : ")) for x in range(int(sqrt(n)) + 1): for y in range(x, int(sqrt(n)) + 1): if x ** 2 + y ** 2 == n: pair = f'{x} {y}' res.append(pair) if len(res) == 0: return "This number cannot be represented as the sum of two squares" return res
import searchProblem; import searchNode; import state; import cell; import PriorityW; import maze; import queue; class GCA(searchProblem.searchProblem): """description of class""" def __init__(self): self.myname = "GCA" def search(self, maz, strategy, visualize): print("ahmed"); """def switch(x): return { #'a': self.BFS(maze, visualize), 'b': self.Astar(maze, visualize), }[x] switch(strategy);""" #maze = [0 for x in range][]; #w, h = 10, 10; #m = [[0 for x in range(w)] for y in range(h)]; from maze import maze; m = maze(); m.randomize(); m.printMaze(); i = m.currentAgentPosition[0]; j = m.currentAgentPosition[1]; from cell import cell cell2 = m.map[i][j]; pokemons = m.pokemons; endX = m.endPosition[0]; endY = m.endPosition[1]; km = m.eggsKilometers; from PriorityW import PriorityW #q = PriorityQueue(); w = PriorityW(); from state import state; s = state(i, j, []); parent = None; operator = [0,0,0,0]; depth = 0; cost = 0; pokemonsRemaining = pokemons; from searchNode import searchNode; n = searchNode(s, parent, operator, depth, cost, pokemonsRemaining); w.put(n, 0); c = 0; goal = None; print("lesgo"); while w.qsize() != 0 : n = w.get(); x = n.state.x; y = n.state.y; cell2 = m.map[x][y]; #if n.state.seen[str(x)+","+str(y)] == True : # continue; if cell2.hasPokemon() and not str(x)+","+str(y) in n.state.seen : pokemonsRemaining = n.pokemonsRemaining - 1; n.state.seen.append(str(x)+","+str(y)); else: pokemonsRemaining = n.pokemonsRemaining; #n.state.seen[str(x)+","+str(y)] = True; print("currently at "+str(x)+" and "+str(y)); c = c + 1; # check if goal reached #if goalTest(m, x, y, pokemonsRemaining) : #if pokemonsRemaining == 0 and x == endX and y == endY and n.cost >= km : print("pokemonsremaininggca: "+ str(pokemonsRemaining)) if x == endX and y == endY and n.cost >= km and pokemonsRemaining == 0 : print("goal"); goal = n; break; #if visualize : #printMap(m, x, y); q = queue.Queue(); if cell2.surroundings[0] == 0 : s = state(x, y-1, n.state.seen); parent = n; operator = [1,0,0,0]; depth = n.depth + 1; cost = n.cost + 1; n1 = searchNode(s, parent, operator, depth, cost, pokemonsRemaining); q.put(n1); print("Left: "+str(n1.depth)); if cell2.surroundings[1] == 0 : s = state(x-1, y, n.state.seen); parent = n; operator = [0,1,0,0]; depth = n.depth + 1; cost = n.cost + 1; n1 = searchNode(s, parent, operator, depth, cost, pokemonsRemaining); q.put(n1); print("Up: "+str(n1.depth)); if cell2.surroundings[2] == 0 : s = state(x, y+1, n.state.seen); parent = n; operator = [0,0,1,0]; depth = n.depth + 1; cost = n.cost + 1; n1 = searchNode(s, parent, operator, depth, cost, pokemonsRemaining); q.put(n1); print("Right: "+str(n1.depth)); if cell2.surroundings[3] == 0 : s = state(x+1, y, n.state.seen); parent = n; operator = [0,0,0,1]; depth = n.depth + 1; cost = n.cost + 1; n1 = searchNode(s, parent, operator, depth, cost, pokemonsRemaining); q.put(n1); print("Down: "+str(n1.depth)); while q.qsize() != 0 : n1 = q.get(); if strategy == "BF" : w.put(n1, w.upper + 1); if strategy == "DF" : w.put(n1, w.lower - 1); if strategy == "UC" : w.put(n1, n1.cost); if strategy == "GR1" : w.put(n1, h1(n1)); if strategy == "GR2" : w.put(n1, h2(n1)); if strategy == "GR3" : w.put(n1, h3(n1)); if strategy == "AS1" : w.put(n1, n1.cost + h1(n1)); if strategy == "AS2" : w.put(n1, n1.cost + h2(n1)); if strategy == "AS3" : w.put(n1, n1.cost + h3(n1)); print("after hena"); print("after after hena"); if goal != None : print("solution"); solCost = goal.cost; nodeCount = c; moves = []; n = goal; while n.parent != None : if n.operator == [1,0,0,0] : moves.insert(0, "Left"); #moves = ["Left"] + moves; if n.operator == [0,1,0,0] : moves.insert(0, "Up"); if n.operator == [0,0,1,0] : moves.insert(0, "Right"); if n.operator == [0,0,0,1] : moves.insert(0, "Down"); n = n.parent; #moves.reverse; return [moves, solCost, nodeCount]; print("no solution"); return None; def h1(n1): return n1.depth; gca = GCA(); res = gca.search('', 'BF' , ''); print("he77"); print(res[0]); print(res[1]); print(res[2]);
""" Created by YASH MODI CST8333_351 Assignment 4 """ import Assign4_Controller choice = "" # Start the program Assign4_Controller.start() # loop for display menu while choice != "y": print("Coded by YASH MODI\n\n") print("A.Display data entries\n" + "B.Create data entries\n" + "C.Edit data entries\n" + "D.Delete data entries\n" + "X.Exit\n\n") value = input("Enter your choice: ") # The first option to display if value == "A" or value == "a": print("A.Display all data entries\n" + "B.Display filtered records\n" + "C.Display some data entries\n") option = input("Enter your option: ") if option == "A" or option == "a": Assign4_Controller.displayAll() elif option == "B" or option == "b": Assign4_Controller.display_with_filter() # Id = input("Please enter an id: ") # date = input("Please enter a date: ") # cases = input("Please enter number of cases: ") # deaths = input("Please enter number of deaths: ") # name_fr = input("Enter name of the country in french: ") # name_en = input("Enter name of the country in English: ") # data = Assign4_Controller.search(Id, date, cases, deaths, name_fr, name_en) # print(data) elif option == "C" or option == "c": number = input("How many entries do you want to display: ") Assign4_Controller.display(number) else: print("Choose from the given option........\n\n") # The second option to Create elif value == "B" or value == "b": Id = input("Please enter an id: ") date = input("Please enter a date: ") cases = input("Please enter number of cases: ") deaths = input("Please enter number of deaths: ") name_fr = input("Enter name of the country in french: ") name_en = input("Enter name of the country in English: ") Assign4_Controller.create(Id, date, cases, deaths, name_fr, name_en) # The third option to edit elif value == "C" or value == "c": Assign4_Controller.edit() # The forth option to Delete elif value == "D" or value == "d": Id = input("Please enter an id: ") date = input("Please enter a date: ") cases = input("Please enter number of cases: ") deaths = input("Please enter number of deaths: ") name_fr = input("Enter name of the country in french: ") name_en = input("Enter name of the country in English: ") Assign4_Controller.delete(Id, date, cases, deaths, name_fr, name_en) elif value == "X" or value == "x": choice = input("Are you sure you want to quit (y/n): ") if choice == 'y': Assign4_Controller.close() else: print("Choose from the given option........\n\n")
from tkinter import * #Raiz raiz = Tk() #Frame miFrame = Frame(raiz) miFrame.pack() #Label miLabel = Label(miFrame, text = "Nombre") miLabel.grid(row = 0 , column = 0 , padx = 10,pady = 10) #Texto miTexto = Entry(miFrame) miTexto.grid(row = 0 , column = 1, padx = 10,pady = 10) raiz.mainloop()
not_primes = [] def is_prime(number): if number in primes: return True for factor in range(2, number): if number % factor == 0: not_primes.append(number) return False primes.append(number) return True def Sieve_of_Eratsthenes(limit): primes = range(2, limit) for i in primes: not_primes = range(i*i, limit + 1 , i) for item in not_primes: if item in primes: primes.remove(item) return primes def try_by_divide(product): primes = Sieve_of_Eratsthenes(10000) index = -1 divider = 2 while divider < product / 2: if index < len(primes): index += 1 divider = primes[index] else: divider += 1 print(product) if product % divider == 0: product = product / divider index = -1 return product def largest_p_factor(product): primes = Sieve_of_Eratsthenes(product / 2) largest_prime = 0 for prime in primes: print("currently considering: " + prime) if product % prime == 0: if prime > largest_prime: largest_prime = prime return largest_prime
def sum_of_divisors(number): total = 0 for divisor in range(1, (number / 2) + 1): if number % divisor == 0: total += divisor return total def is_abundant_number(number): if sum_of_divisors(number) > number: return True abundant_list = [number for number in range(1, 28123) if is_abundant_number(number)] abundant_set = set() for number in range(1,28123): if is_abundant_number(number): abundant_set.add(number) #return the sum of all non-abundant numbers under the number 'under' def sum_of_non_abundants(under): total = 0 for number in range(1, under): sumable = True for digit1 in abundant_list: if (number - digit1) in abundant_set: sumable = False if sumable: total += number return total
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 1 10:18:38 2017 @author: carles """ from games import Game import random class Catch(Game): def __init__(self, frames_used): Game.__init__(self, 10, 10, frames_used) self.player_width = 3 # self.player_pos = self.grid_width // 2 - self.player_width // 2 self.player_pos = random.randint(0, self.grid_width - self.player_width) self.fruit_pos = [0, self.grid_width // 2]#random.randint(0, self.grid_width-1)] self.draw_player() self.grid[tuple(self.fruit_pos)] = 1 self.extra_info = 0 self.lose_r = -10 self.survive_r = 0 self.win_r = 10 def draw_player(self, tile = 1): for i in range(self.player_width): self.grid[self.grid_height - 1, self.player_pos + i] = tile def get_actions(self): return [0, 1, 2] # left, stay, right def tile_symbols(self, tile): return (" ", "#", "*")[tile] def transition(self, action): reward = self.survive_r # Erase player and fruit from the grid self.draw_player(0) self.grid[tuple(self.fruit_pos)] = 0 # Update fruit self.fruit_pos[0] += 1 # Update player if action == 0 and self.player_pos != 0: self.player_pos -= 1 if action == 2 and self.player_pos != self.grid_width - self.player_width: self.player_pos += 1 # Did the fruit get to the last row? if self.fruit_pos[0] == self.grid_height-1: # Did it catch the fruit? if (self.player_pos <= self.fruit_pos[1] and self.fruit_pos[1] <= self.player_pos + self.player_width - 1): reward = self.win_r else: reward = self.lose_r self.gameover = True # Replace fruit self.fruit_pos = [0, random.randint(0, self.grid_width-1)] self.draw_player() self.grid[tuple(self.fruit_pos)] = 1 return reward
#!/usr/bin/python def getSubStrings(s): startingPoint = 0 max = len(s) - 1 retVal = [] while startingPoint < max: for i in xrange(1,len(s)+1): substr = s[startingPoint:i] if substr: retVal.append(substr) startingPoint+=1 retVal.append(s[max]) return set(retVal) def reverseString(s): reversedString = '' sList = list(s) sList.reverse() for letter in sList: reversedString+=letter print reversedString getSubStrings('Teresa') reverseString('Michael')
def sum_square_diff(n=100): sq = [i**2 for i in range(1, n+1)] return sum(range(1, n+1))**2 - sum(sq) if __name__ == "__main__": res = sum_square_diff(100) print(res)
#!/usr/bin/env python # concatenate.py # Iterate over a range of values for num in range(1,10): # Use the modulo operator to get the remainder after division # If the remainder after dividing by 2 is zero, the number is even if num % 2 == 0: print(str(num) + ' is even') else: print(str(num) + ' is odd')
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ class MyString(str): def __str__(self): return self[::-1] print('Hello, World.') print('Hello, World.'.upper()) print('Hello, World.'.lower()) print('Hello, World.'.capitalize()) print('Hello, World.'.swapcase()) print('Hello, World.'.title()) print('Hello, World. {}'.format(42 * 7)) print(""" Hello, World. {} """.format(42 * 7)) s = "Hello, world! {}" print(s.format(42 * 7)) s = MyString("Hello, world!") print(s) # Concat a = "Mohammad" b = "Vahidalizadeh" print(a + " " + b) x = 42 y = 73 print("The numbers are {bb} {xx}.".format(xx=x, bb=y)) print("The numbers are {1} {0}.".format(x, y)) print("The numbers are {0} {1} {0}.".format(x, y)) print("The numbers are {0:>05} {1:+05} {0:<7}.".format(x, y)) x = x * 747 * 1000 print("The number is {:,}".format(x)) print("The number is {:,}".format(x).replace(",", ".")) print("The number is {:f}".format(x)) print("The number is {:.3f}".format(x)) x = 42 print(f"The number is {x:b}")
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ animals = ( 'bear', 'bunny', 'dog', 'cat', 'velociraptor' ) for pet in animals: print(pet, end = " ") print() for i in range(10): print(i, end = " ") print() for i in range(10): print(i, end = " ") if i == 5: break else: print("exited normally") print() for i in range(10): print(i, end = " ") else: print("exited normally")
#import numpy module import numpy as np #define numpy array as input x=np.array([1,2,3,4,5]) # define the no of column N =3 #Show vander array out put Method1 np.vander(x,increasing=True) #show Vander array out with Method2 np.column_stack([x**(N-1-i) for i in range(N)])
import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="2zkNKcz&EOZaRjc$",database="library") mycursor=mydb.cursor() BorrowersID=int(input("ENTER YOUR BORROWER_ID:- ")) mycursor.execute("INSERT INTO BOOKS [borrowers_ID] VALUES(BorrowersID)") bookID=input("ENTER THE BOOK'S ID:- ") mycursor.execute("INSERT INTO BOOKS [book_ID] VALUES(bookID)") bk_title=input("ENTER THE BOOK'S TITLE:- ") mycursor.execute("INSERT INTO BOOKS [bktitle] VALUES(bk_title)") stafforstudent=input("ARE YOU A STAFF MEMBER OR A STUDENT? (STAFF/STUDENT)") if stafforstudent.upper()=="STAFF": staffID=int(input("ENTER YOUR STAFF_ID:- ")) mycursor.execute("INSERT INTO BOOKS [staff_ID] VALUES(staffID)") stff_name=input("ENTER YOUR FIRST NAME:- ") mycursor.execute("INSERT INTO BOOKS [stff_name] VALUES(stff_name)") elif stafforstudent.upper()=="STUDENT": studID=int(input("ENTER YOUR STUDENT_ID:- ")) mycursor.execute("INSERT INTO BOOKS [stud_ID] VALUES(studID)") stf_name=input("ENTER YOUR FIRST NAME") mycursor.execute("INSERT INTO BOOKS [stf_name] VALUES(stf_name)") else: print("WRONG INPUT CHECK YOUR DATA AGAIN!!!")
""" This module tests the comment_validator methods """ import unittest from app.api.v1.utils.comments_validator import CommentsValidator class TestQuestionsValidator(unittest.TestCase): def setUp(self): """ Initializes app """ self.comment = { "comment": "This is a comment", } def test_invalid_data(self): validator = CommentsValidator("") self.assertEqual(validator.valid_comment(), "The comment field is required!")
from flask import Flask, render_template # use Flask to render a template from flask_pymongo import PyMongo # use PyMongo to interact with Mongo database import scraping # to use scraping code, convert Jupyter notebook to Python # Set up Flask app = Flask(__name__) # Use flask_pymongo to set up mongo connection app.config['MONGO_URI'] = "mongodb://localhost:27017/mars_app" mongo = PyMongo(app) # Define route for the HTML page @app.route("/") # tells Flask what to display when we're looking at the homepage def index(): # index.html is the default HTML file that we'll use to display the dontent we've scraped mars = mongo.db.mars.find_one() # uses PyMongo to find the mars collection in our database. assign that path to mars variable to use later return render_template("index.html", mars=mars) # tells Flask to return an HTML template using an index.html file. Use mars collection in MongoDB @app.route("/scrape") # defines the route that Flask will be using def scrape(): # scrapes new data using our scraping.py script mars = mongo.db.mars # assign a new variable that points to our Mongo database mars_data = scraping.scrape_all() # create a new variable to hold the newly scraped data mars.update({}, mars_data, upsert=True) # update the database. syntax .update(query_parameter, data, options) upsert tells Mongo to create a new document if it doesn't exist already. return "Scraping Successful!" # Run flask if __name__ == "__main__": app.run()
""" Name: Thomas Reus Student-id: 11150041 Project: dataprocessing This program does: - Creates a dictionary from a .csv file - Creates a .json file from the dictionary """ import csv import json # name of the input file INPUT_NAME = "Bodemgebruik_data" def create_dictionary(input_csv): """ Creates a dictionary from a .csv file. Input: .csv file (input_csv) Output: dictionary (csv_dict) """ # create empty csv dictionary csv_dict = {} # open CSV file and load into list dictionary = [] with open(input_csv, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for item in reader: dictionary.append(item) # create index names vars = [] for name in dictionary[0]: vars.append(name) # fill the csv dict with a dictionary per item for item in dictionary: csv_dict[item[vars[1]].split(" ")[0]] = {} for item in dictionary: province = item[vars[1]].split(" ")[0] csv_dict[province][item[vars[0]]] = {} for var in vars[2:]: csv_dict[province][item[vars[0]]][var] = item[var].strip() # return dictionary return csv_dict # main function if __name__ == "__main__": # create dictionary from csv file dictionary = create_dictionary(f"../data/{INPUT_NAME}.csv") # create json file from the dictionary with open(f"../data/{INPUT_NAME}.json", 'w') as fp: json.dump(dictionary, fp, indent=4)
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 13:14:04 2020 @author: Ryan.Worth """ #Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: ##1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ## add even fibonacci numbers to a list nums = [] a = 0 ##first position b = 1 ##second position limit = 4000000 while True: c = a + b if c >= limit: break if c % 2 == 0: nums.append(c) ## add to list if even a = b ## move positions along b = c print(nums) ## list of all even fibonacci numbers < 4000000 print(sum(nums)) ##sum them up ## answer = 4613732
from random import randint from time import clock class Ponto: def __init__(self): self.x = 0 self.y = 0 self.movs = [self.cima, self.direita, self.baixo, self.esquerda] def movimento(self, r = 0): #Gera um número aleatório para a direção self.movs[randint(0, 3)]() #Todos os movimentos têm um módulo de 25 def cima(self): self.y = (self.y + 1) % 25 def direita(self): self.x = (self.x + 1) % 25 def baixo(self): self.y = (self.y - 1) % 25 def esquerda(self): self.x = (self.x - 1) % 25 class Grid: def __init__(self): self.a = Ponto() self.b = Ponto() #Como só são 25 distâncias possíveis #Ao invés de guardar todas as distâncias obtidas #Guarda quantas vezes tal distância apareceu #Com isso conseguimos calcular qualquer coisa self.contagem = [0]*25 self.tempoInicial = 0 def rodar(self): #Guarda o tempo que o programa é iniciado self.tempoInicial = clock() pausa = 1 i = 0 #Roda 100 mil vezes o método de mover 10 mil vezes vezes = 100000 while i < vezes: self.dezmil() i += 1 #Nos 1m, 10m, 100m e 1b, faz um print dos dados if i == pausa: self.printarAtual(i) pausa *= 10 def printarAtual(self, numero): tempoAtual = clock() tamanho = numero*10000 media = 0 #Faz a média com um somatório, como Pedro calculava a Esperança for i in range(25): media += self.contagem[i] * i media /= tamanho print(str(tamanho), "iterações") print("Média = ", str(media)) print("Tempo = ", str(tempoAtual - self.tempoInicial) + "s") #Mostra a contagem de distâncias for i in range(25): print(str(i), "\t\t", str(self.contagem[i])) print() def dezmil(self): i = 0 vezes = 10000 for i in range(vezes): #Move ambos os pontos self.a.movimento() self.b.movimento() #E adiciona +1 na contagem certa self.contagem[self.distancia()] += 1 def distancia(self): ax = self.a.x ay = self.a.y bx = self.b.x by = self.b.y #ABS não e método de Grafo #Faz um módulo | | da subtração das coordenadas #25 - o valor é para simular uma espelhação deltax = min(abs(ax - bx), 25 - abs(ax - bx)) deltay = min(abs(ay - by), 25 - abs(ay - by)) return deltax + deltay ''' def distancia(self): bx = self.b.x by = self.b.y #Réplicas do meio, esquerda e direita #Com as réplicas do centro, cima e baixo todosB = [(bx, by), (bx, (by + 25)), (bx, (by - 25)), ((bx - 25), by), ((bx - 25), (by + 25)), ((bx - 25), (by - 25)), ((bx + 25), by), ((bx + 25), (by + 25)), ((bx + 25), (by - 25))] menor = 24 coordA = (self.a.x, self.a.y) #Calcula a distância do A para todos os Bs for i in range(len(todosB)): dist = self.calcularDistancia(coordA, todosB[i]) if dist < menor: menor = dist return menor def calcularDistancia(self, a, b): #ABS não e método de Grafo #Faz um módulo | | da subtração das coordenadas #|3 - 10| + |2 - 3| = 8 return abs(a[0] - b[0]) + abs(a[1] - b[1]) ''' ########################### g = Grid() g.rodar()
''' author: Ajay Tulsyan email: [email protected] last update: 03/07/2020 Intro: This is code contains three basic search algorithms such as Breadth First Search, Depth First Search, and Dijkstra, all the three algorithms are written as methods of a class Graph. The alogorithms are built using adjecency matrix. Note: """ PLEASE UPDATE THE PATH FOR IMAGES BEFORE RUNNING THIS CODE. THE LINES ON WHICH UPDATE IS NEEDFUL IS 19, 124, and 129. """ ''' from collections import deque from PIL import Image class Graph: def __init__(self, numberOfVertex): im = Image.open("Graph_Without_Weights.png") im.show() self.vertex = [] self.Queue = {} self.dict = {} self.path = [] self.currentSize = 0 self.capacity = numberOfVertex self._adjMatrix = [] self._adjMatrix = [ [0 for j in range(numberOfVertex)] for i in range(numberOfVertex)] self._adjMatrixWithWeight = [] self._adjMatrixWithWeight = [ [0 for j in range(numberOfVertex)] for i in range(numberOfVertex)] self._capacity = numberOfVertex def addVertex(self, data): self.vertex.append(data) if self.currentSize < self.capacity else print( 'Capacity full') self.currentSize += 1 def addEdge(self, source, target): s = self.vertex.index( source) if source in self.vertex else 'invalid source...does not exist in graph' t = self.vertex.index( target) if target in self.vertex else 'invalid target...does not exist in graph' if type(s) == int and type(t) == int: self._adjMatrix[s][t] = 1 self._adjMatrix[t][s] = 1 elif type(s) != int: print(source, '--', s) else: print(target, '--', t) def addEdgeWithWeight(self, source, target, weight): s = self.vertex.index( source) if source in self.vertex else 'invalid source...does not exist in graph' t = self.vertex.index( target) if target in self.vertex else 'invalid target...does not exist in graph' if type(s) == int and type(t) == int: self._adjMatrixWithWeight[s][t] = weight self._adjMatrixWithWeight[t][s] = weight elif type(s) != int: print(source, '--', s) else: print(target, '--', t) def findNeighbour(self, vertex): a = self.vertex.index(vertex) x = [self.vertex[i] for i in range(self.currentSize) if self._adjMatrix[a][i] == 1] print(x) def breadthFirstSearch(self, startVertex, endVertex=None): q = deque() result = [] temp = [] if startVertex in self.vertex: q.append(startVertex) temp.append(startVertex) while startVertex != endVertex: a = self.vertex.index(startVertex) for i in range(self.currentSize): if self._adjMatrix[a][i] == 1 and self.vertex[i] not in temp: q.append(self.vertex[i]) temp.append(self.vertex[i]) result.append(q.popleft()) startVertex = q[0] if len(result) != len( self.vertex) else endVertex if startVertex == endVertex: if endVertex in self.vertex: result.append(endVertex) print('***************************************************************') print('The result of BFS--', result) print('***************************************************************') else: print('Invalid start point') def depthFirstSearch(self, startVertex, endVertex=None): q = deque() result = [] if startVertex in self.vertex: q.append(startVertex) result.append(startVertex) while startVertex != endVertex: flag = 0 a = self.vertex.index(startVertex) for i in range(self.currentSize): if self._adjMatrix[a][i] == 1 and self.vertex[i] not in result: q.append(self.vertex[i]) result.append(self.vertex[i]) startVertex = self.vertex[i] flag += 1 break if flag == 0: q.pop() startVertex = q[len( q) - 1] if len(result) != len(self.vertex) else endVertex print('***************************************************************') print('The result of DFS--', result) print('***************************************************************') else: print('Invalid start point') def dijkstra(self, startVertex, endVertex=None): im = Image.open("GraphWithWeights.png") im.show() if startVertex == 'Ajay' and endVertex == 'Iowa': # This image is only a representation... # of cost and path for this specific start and goal im = Image.open("Graph_Ajay_Iowa.png") im.show() start_dump = startVertex value = "" vertexCost = {self.vertex[i]: 500000 for i in range(len(self.vertex))} if startVertex in self.vertex: vertexCost[startVertex] = 0 visited = set() while startVertex != None: visited.add(startVertex) a = self.vertex.index(startVertex) for i in range(self.currentSize): if self._adjMatrixWithWeight[a][i] != 0 and self.vertex[i] != visited: cost = self._adjMatrixWithWeight[a][i] + \ vertexCost.get(startVertex) if cost < vertexCost.get(self.vertex[i]): vertexCost[self.vertex[i]] = cost self.Queue[self.vertex[i]] = cost self.dict[self.vertex[i]] = startVertex if self.Queue != {}: startVertex = min(self.Queue.keys(), key=(lambda k: self.Queue[k])) self.Queue.pop(startVertex) else: startVertex = None print('***************************************************************') print('Cost for all the vertex in the graph starting from', start_dump, 'is--', vertexCost) print('***************************************************************') if endVertex in self.dict: self.path.append(endVertex) value = self.dict[endVertex] while vertexCost[value] != 0: self.path.append(value) value = self.dict[value] self.path.append(start_dump) self.path.reverse() print('***************************************************************') print('The Shortest path from vertex', start_dump, 'to end vertex', endVertex, 'is ---', self.path, 'with cost', vertexCost[endVertex]) print('***************************************************************') else: print('Invalid start point') if __name__ == "__main__": # Here you can the number of vertex in the graph, for the explanation sake # I have taken a graph with 11 vertices. g = Graph(11) g.addVertex('Ajay') g.addVertex('Beckham') g.addVertex('Carlo') g.addVertex('Denim') g.addVertex('Eagle') g.addVertex('Fradel') g.addVertex('Gorden') g.addVertex('Hooker') g.addVertex('Iowa') g.addVertex('Joe') g.addVertex('Kevin') g.addEdge('Ajay', 'Beckham') g.addEdge('Ajay', 'Eagle') g.addEdge('Ajay', 'Fradel') g.addEdge('Fradel', 'Beckham') g.addEdge('Hooker', 'Beckham') g.addEdge('Carlo', 'Fradel') g.addEdge('Carlo', 'Gorden') g.addEdge('Carlo', 'Denim') g.addEdge('Denim', 'Eagle') g.addEdge('Denim', 'Gorden') g.addEdge('Fradel', 'Joe') g.addEdge('Hooker', 'Iowa') g.addEdge('Iowa', 'Joe') g.addEdge('Iowa', 'Kevin') # Here you can customize your graphs edges and its weights g.addEdgeWithWeight('Ajay', 'Beckham', 10) g.addEdgeWithWeight('Ajay', 'Eagle', 15) g.addEdgeWithWeight('Ajay', 'Fradel', 5) g.addEdgeWithWeight('Fradel', 'Beckham', 8) g.addEdgeWithWeight('Hooker', 'Beckham', 12) g.addEdgeWithWeight('Carlo', 'Fradel', 18) g.addEdgeWithWeight('Carlo', 'Gorden', 3) g.addEdgeWithWeight('Carlo', 'Denim', 9) g.addEdgeWithWeight('Denim', 'Eagle', 7) g.addEdgeWithWeight('Denim', 'Gorden', 6) g.addEdgeWithWeight('Fradel', 'Joe', 14) g.addEdgeWithWeight('Hooker', 'Iowa', 5) g.addEdgeWithWeight('Iowa', 'Joe', 11) g.addEdgeWithWeight('Iowa', 'Kevin', 2) print(g._adjMatrix) print('*************************************************************') # Here you can choose to provide end vertex or not, Like in the examples... # below, end vertex is provied, but you even skip to choose end vertex. g.breadthFirstSearch('Ajay', 'Gorden') g.depthFirstSearch('Carlo', 'Ajay') g.dijkstra('Ajay', 'Iowa')
import string import random from PyDictionary import PyDictionary def getPasswordLen(): length = int(input("How long do you want your password: ")) return length def useDigits(): answer = input("Do you want to use digits? True or False") return answer.strip() def useUpperLetters(): answer = input("Do you want to use upper letters? True or False") return answer.strip() def useLowerLetters(): answer = input("Do you want to use lower letters? True or False") return answer.strip() def usePunctuation(): answer = input("Do you want to use punctuation? True or False") return answer.strip() def repeatCharacters(): answer = input("Do you allow to repeat characters? True or False") return answer.strip() #users choise if use upper case,lowercase,digits,etc for thier password def generatePassword(choises_list, length): characters = [] if choises_list[0] == 'True': characters = string.digits if choises_list[1] == 'True': characters += string.ascii_uppercase if choises_list[2] == 'True': characters += string.ascii_lowercase if choises_list[3] == 'True': characters += string.punctuation if choises_list[4] == 'True': str = ''.join(random.choices(characters, weights=None, cum_weights=None, k=length)) return str elif choises_list[4] != 'True': str = ''.join(random.sample(characters,length)) return str def generateRandomPassword(): length = getPasswordLen() list = [] list.append(useDigits()) list.append(useUpperLetters()) list.append(useLowerLetters()) list.append(usePunctuation()) list.append(repeatCharacters()) password = generatePassword(list, length) return password def shuffleSentence(): sentence = input("Please Enter Your Sentence to Be Shuffled: ") l1 = list(sentence) random.shuffle(l1) result = ''.join(l1) return result def enterSentence(): sentence = input("Please Enter Your Sentence For Creating Password: ") l1 = sentence.split(' ') random.shuffle(l1) result = '' for i in range(len(l1)): letter = l1[i][0] result += letter return result def dictionaryMethod(): dictionary = PyDictionary() sentence = input("Please Enter Random Word: ") meaning = dictionary.meaning(sentence) value = str(meaning.values()) l1 = value.split(' ') num = int(input(" How Many Words Do You Want to Use? ")) l2 = [] for i in range(num): word = random.choice(l1) l2.append(word) random.shuffle(l2) result = '' for i in range(len(l2)): letter = l2[i][0] result += letter return result if __name__ == '__main__': print("Welcome to Password Generator!!!") print ("Option 1:Generate Random Password \nOption 2 : Enter Sentence to Shuffle \n" + "Option 3: Enter Sentence For Creating Password \n "+ "Option 4: Dictionary Method For Creating Password ") option = int(input(" Choose one of the options: ")) password = '' if option == 1: password = generateRandomPassword() if option == 2: password = shuffleSentence() if option == 3: password = enterSentence() if option == 4: password = dictionaryMethod() print ("Your Password is : ",password)
def quick_sort(L,low,high): i=low j=high if i>=j: return L key=L[i] while i!=j: while i<j and L[j]>=key: j=j-1 L[i]=L[j] while i<j and L[i]<=key: i=i+1 L[j]=L[i] L[i]=key quickSort(L,low,i-1) quickSort(L,j+1,high) return L if __name__=='__main__': print(quick_sort([3,7,24,56,5,9,10,2,7],0,8))
#Print a singly linked list from tail to head. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: #运用栈“后进先出” def printLinkedList1(self,head): stack=[] while head: stack.append(head.val) head=head.next while stack: print(stack[-1]) stack.pop() #递归调用 def printLinkedList2(self,head): if head: if head.next: self.printLinkedList2(head.next) print(head.val) if __name__=='__main__': head=ListNode(1) p1=ListNode(4) p2=ListNode(3) p3=ListNode(5) head.next=p1 p1.next=p2 p2.next=p3 s=Solution() s.printLinkedList1(head) s.printLinkedList2(head)
import nltk import re import string import pandas as pd import numpy as np # NKTK from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize # Gensim import gensim import gensim.corpora as corpora from gensim.utils import simple_preprocess def convert_col_to_list(df, col='Question and Answer'): """ takes in a column from a dataframe and returns a list of text Args: df (Pandas DataFrame): col (str): column name. Default to "Question and Answer" Returns: a list of strings, where each column entry is one string to be tokenized later """ text = df[col].values.tolist() return text def make_stopwords(filepath='stopwords.txt'): """ Read in a list of stopwords from a .txt file and extend the nltk stopwords by this list. Return a list of stopwords created from nltk and the .txt file """ sw = open(filepath, "r") my_stopwords = sw.read() my_stopwords = my_stopwords.split(", ") sw.close() all_stopwords = stopwords.words('english') all_stopwords.extend(my_stopwords) return all_stopwords def remove_hyphens(text): """ Remove hyphens from a text as a list of strings """ return re.sub(r'(\w+)-(\w+)-?(\w)?', r'\1 \2 \3', text) # tokenize text def tokenize(text): """ Tokenize a list of strings """ wt = nltk.RegexpTokenizer(pattern=r'\s+', gaps=True) tokens = wt.tokenize(text) return tokens def remove_characters(tokens): """ Remove characters from a list of tokenized text """ pattern = re.compile('[{}]'.format(re.escape(string.punctuation))) no_char_tokens = filter(None, [pattern.sub('', token) for token in tokens]) return no_char_tokens def lowercase(tokens): """ Lowercase all text from tokenized text """ return [token.lower() for token in tokens if token.isalpha()] def remove_stopwords(tokens): """ Remove any stopwords from tokenized text """ stopword_list = make_stopwords() no_stop_tokens = [token for token in tokens if token not in stopword_list] return no_stop_tokens def lemmatized_words(tokens): """ Lemmatize any words from tokenized text """ lemmas = [] for word in tokens: lemma = wn.morphy(word) if lemma: lemmas.append(lemma) else: lemmas.append(word) return lemmas def remove_short_tokens(tokens): """ Remove tokens that are smaller than 3 characters long """ return [token for token in tokens if len(token) > 3] def remove_non_wordnet(tokens): """ Remove any tokens that are a part of the synsets library """ return [token for token in tokens if wn.synsets(token)] def apply_lemmatize(tokens, wnl=WordNetLemmatizer()): """ Lemmatize tokens using nltk's WordNetLemmatizer() """ return [wnl.lemmatize(token) for token in tokens] def token_by_lemma(text): """ Tokenize and lemmatize text in one function Potentially a tokenizer to call as a parameter in NMF model ------- Args: text (string): a string to be tokenized Returns: a list of strings: tokenized words that have been lemmatized """ lemmatizer = WordNetLemmatizer() word_list = word_tokenize(text) lemmatized_wrds = [lemmatizer.lemmatize(w) for w in word_list] return lemmatized_wrds def clean_text_clues(texts): """ Read in a text as a list of strings and clean the text according to the chosen cleaning functions ------- Args: texts (list of strings): each string has multiple words separated by whitespace or hyphens which need to be processed and cleand Returns: list of strings of tokenized and processed text as cleaned_words """ clean_clues = [] for clues in texts: clue = remove_hyphens(clues) clue = tokenize(clue) clue = remove_characters(clue) clue = lowercase(clue) clue = remove_stopwords(clue) clue = lemmatized_words(clue) clue = remove_short_tokens(clue) clue = remove_non_wordnet(clue) clue = apply_lemmatize(clue) clean_clues.append(clue) return [' '.join(item) for item in clean_clues] if __name__ == "__main__": pass
""" This module provides a listbox with dynamic content that can be updated by calling it's update function. """ from ..ui import create_listbox class DynamicListBox(object): """ A listbox with dynamic content. """ def __init__(self, update_func, _listbox): """ @param update_func: function used to update the content of the listbox @param listbox: the listbox to show the contents on. """ self._update_func = update_func self._listbox = _listbox self._list = [] def update(self): """ Update the content of it's list and it's listbox. """ self._list = self._update_func() self._listbox.update_options(self._list) @property def selections(self): """ Get a list of all items under selection. """ index_list = self._listbox.get_selected_index_list() selection_list = [self._list[index] for index in index_list] return selection_list
# Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z]. You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times. # # You may assume that the list describe a correct sequence of bookings in chronological order; that is, only free rooms can be booked and only booked rooms can be freeed. All rooms are initially free. Note that this does not mean that all rooms have to be free at the end. In case, 2 rooms have been booked the same number of times, return the lexographically smaller room. # # You may assume: # # N (length of input) is an integer within the range [1, 600] # each element of array A is a string consisting of three characters: "+" or "-"; a digit "0"-"9"; and uppercase English letter "A" - "Z" # the sequence is correct. That is every booked room was previously free and every freed room was previously booked. # Example: # # Input: ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"] # Output: "1A" # Explanation: 1A as it has been booked 2 times. from collections import defaultdict data = ["+1A", "+3E", "-3E", "+4F", "+3E", "-3E"] tracker = defaultdict(int) max_booked = data[0][1] for el in data: key = el[1:] if el[0] == '+': tracker[key] += 1 if tracker[key] > tracker[max_booked]: max_booked = key elif tracker[key] == tracker[max_booked]: max_booked = min(key, max_booked) print(max_booked)
# Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string keyboard of length 26. Initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is abs(j - i). # # Given a string keyboard that describe the keyboard layout and a string text, return an integer denoting the time taken to type string text. # # Example 1: # # Input: keyboard = "abcdefghijklmnopqrstuvwxy", text = "cba" # Output: 4 # Explanation: # Initially your finger is at index 0. First you have to type 'c'. The time taken to type 'c' will be abs(2 - 0) = 2 because character 'c' is at index 2. # The second character is 'b' and your finger is now at index 2. The time taken to type 'b' will be abs(1 - 2) = 1 because character 'b' is at index 1. # The third character is 'a' and your finger is now at index 1. The time taken to type 'a' will be abs(0 - 1) = 1 because character 'a' is at index 0. # The total time will therefore be 2 + 1 + 1 = 4. # Constraints: # # length of keyboard will be equal to 26 and all the lowercase letters will occur exactly once; # the length of text is within the range [1..100,000]; # string text contains only lowercase letters [a-z]. def gettime(text): time = 0 char = ord('a') for i in range(0, len(text)): next_char = ord(text[i]) time += abs(next_char - char) char = next_char return time text = input() time = gettime(text) print(time)
def intersection(st, ave): """Represent an intersection using the Cantor pairing function.""" return (st+ave)*(st+ave+1)//2 + ave def street(inter): return w(inter) - avenue(inter) def avenue(inter): return inter - (w(inter) ** 2 + w(inter)) // 2 w = lambda z: int(((8*z+1)**0.5-1)/2) def taxicab(a,b): return abs(street(a)-street(b))+abs(avenue(a) - avenue(b))
def g(n): if n <= 3: return n else: return g(n-1) + 2 * g(n - 2) + 3 * g(n - 3) def g_iter(n): if n <= 3: return n else: i = 4 a,b,c = 1,2,3 while i <= n: a,b,c = b,c,(c + 2 * b + 3 * a) i += 1 return c
import cv2 import numpy as np def detect_finger_by_hsv(frame, l_hsv, u_hsv): """ detect the color set by the arguments l_hsv and u_hsv. this function mask out the color outside the range and return the filtered image :param frame: :param l_hsv: list of lower HSV values :param u_hsv: list of upper HSV values :return: a masked image that only shows color in the set range """ hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) l_b = np.array([l_hsv[0], l_hsv[1], l_hsv[2]]) u_b = np.array([u_hsv[0], u_hsv[1], u_hsv[2]]) mask = cv2.inRange(hsv, l_b, u_b) res = cv2.bitwise_and(frame, frame, mask=mask) # cv2.imshow("frame", frame) # cv2.imshow("mask", mask) # cv2.imshow("res", res) return res, mask
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not (board and board[0]): return False for r, row in enumerate(board): for c, val in enumerate(row): if val == word[0]: if self.search(board, r, c, word): return True return False def search(self, board: List[List[str]], r: int, c: int, word: str) -> bool: '''Search for word starting from index (r, c).''' if not word: return True if r < 0 or r >= len(board) or c < 0 or c >= len(board[0]) or board[r][c] != word[0]: return False temp = board[r][c] board[r][c] = '' found = any(self.search(board, r+dr, c+dc, word[1:]) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1))) board[r][c] = temp return found
class Solution: def isValid(self, s: str) -> bool: ls = [] for char in s: if char == '(' or char == '[' or char == '{': ls.append(char) elif char == ')': if len(ls) == 0 or ls[-1] != '(': return False else: ls.pop() elif char == ']': if len(ls) == 0 or ls[-1] != '[': return False else: ls.pop() else: if len(ls) == 0 or ls[-1] != '{': return False else: ls.pop() return len(ls) == 0
class Solution: def isUgly(self, num: int) -> bool: if num <= 0: return False x = num while x % 2 == 0: x /= 2 while x % 3 == 0: x /= 3 while x % 5 == 0: x /= 5 return x == 1
class Solution: def isPalindrome(self, s: str) -> bool: front = 0 end = len(s) - 1 while end > front: while front < end and not s[front].isalnum(): front += 1 while end > front and not s[end].isalnum(): end -= 1 if s[front].lower() == s[end].lower(): front += 1 end -= 1 else: return False return True
import sys import readline from atexit import register from interpreter.builtins import namespace from interpreter.money import Currency from interpreter.parser import Parser register(Currency.save) def interpret(expression): try: parser = Parser(expression) node = parser.parse() result = node.traverse() namespace.set("_", result) return result except KeyError as key_error: print("Error: name {} is not defined".format(key_error)) except Exception as exception: print("{}: {}".format(type(exception).__name__, str(exception))) def from_file(filename): with open(filename, "r") as f: result = interpret(f) if result: print(result) def interactive(prompt="foney> "): while True: try: expression = input(prompt) result = interpret(expression) if result: print(result) except (EOFError, KeyboardInterrupt): break def main(): if len(sys.argv) < 2: interactive() else: from_file(sys.argv[1]) if __name__ == '__main__': main()
import math, numpy as np,random as rand from tkinter import * from tkinter import messagebox from tkinter.filedialog import askopenfilename np.set_printoptions(precision=15) root = Tk() canvas = Canvas(root, width=500, height=500) # ------------------------------------------------------------------------------ # Function to calculate the nth Plot algorithm # ------------------------------------------------------------------------------ def nthPlot(data,n): count = 0 newdata = [] for i in range(len(data)): if i % n == 0: count = count + 1 temp = [count, float(data[i][1]), float(data[i][2])] newdata.append(temp) return newdata #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Function to calculate the Distance algorithm #------------------------------------------------------------------------------ def Distance(data, mindist): count = 1 newdata = [] lastKept = float(data[0][1]), float(data[0][2]) temp = [count, float(data[0][1]), float(data[0][2])] newdata.append(temp) for i in range(1, len(data)): current = float(data[i][1]), float(data[i][2]) if EucledeanDistance(lastKept, current) >= mindist: count = count + 1 temp = [count, float(data[i][1]), float(data[i][2])] lastKept = float(data[i][1]), float(data[i][2]) newdata.append(temp) return newdata #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Function to calculate the EucledeanDistance algorithm #------------------------------------------------------------------------------ def EucledeanDistance(lastKept, current): return math.sqrt(math.pow((current[0] - lastKept[0]), 2) + math.pow((current[1] - lastKept[1]), 2)) #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This functions reads the plugins.txt file and lists all the algorithms available #------------------------------------------------------------------------------ def generate_algorithm_plugins(input_file_name): output_list = [] with open(input_file_name) as current_file: next(current_file) for each_line in current_file: output_list.append(each_line) return output_list #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This function loads the input data and retuns a numpy Array #------------------------------------------------------------------------------ def load_input_data(file_name): return np.genfromtxt(file_name, delimiter=',') #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Test function to make sure file menu events are triggers. To be replaced! #------------------------------------------------------------------------------ def open_menu_file_loader(): my_file = open('temp_file_name.txt', 'w') # print('test') my_main_input_file = (askopenfilename().split('/')[-1]) my_file.write(my_main_input_file) my_file.close() generate_open_map() return my_main_input_file #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This function generates the label text based on the list item selected #------------------------------------------------------------------------------ def get_label_text(my_selected_listbox_value): # print(my_selected_listbox_value) if my_selected_listbox_value == 'Distance': my_dynamic_label_name.set('min distance') elif my_selected_listbox_value == 'nthPoint': my_dynamic_label_name.set('n = ') else: my_dynamic_label_name.set('Select a list item') #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This function captures the list item selection change event #------------------------------------------------------------------------------ def get_listbox_selection(listbox_event): my_widget = listbox_event.widget index = int(my_widget.curselection()[0]) value = my_widget.get(index).rstrip('\r\n') get_label_text(value) my_entry_box.delete(0, END) # print(value) return value #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This is a callback function which triggers the button click event #------------------------------------------------------------------------------ def generate_open_map(): with open('temp_file_name.txt', 'r') as my_file: my_file_to_load = my_file.readline() my_data = np.array(load_input_data(my_file_to_load)) my_long = list(my_data[:, 1]) my_lat = list(my_data[:, 2]) my_lat_min = min(my_lat) my_lat_max = max(my_lat) my_long_min = min(my_long) my_long_max = max(my_long) # print(my_lat, my_long) my_converted_list = [] for my_index in range(0, len(my_lat)): my_converted_list.append((my_long[my_index] - my_long_min) * (400 / (my_long_max - my_long_min)) + 50) my_converted_list.append((400 - (my_lat[my_index] - my_lat_min) * (400 / (my_lat_max - my_lat_min))) + 50) # canvas.create_polygon([50, 150, 150, 50, 250, 150, 150, 250], outline ="black", fill = "green") canvas.delete("all") canvas.create_polygon(my_converted_list, outline ="black", fill = "red") #------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # This is a callback function which triggers the button click event #------------------------------------------------------------------------------ def generate_map_button_click(): with open('temp_file_name.txt', 'r') as my_file: my_file_to_load = my_file.readline() # print(my_file_to_load) try: my_current_list_selection = my_listbox.get(my_listbox.curselection()).rstrip('\r\n') except Exception as e: messagebox.showinfo("Alert!", "Please select a algorithm") return None my_input_box_value = float(my_entry_box.get()) if my_current_list_selection == 'Distance': my_data = np.array(Distance(load_input_data(my_file_to_load), my_input_box_value)) # print(len(my_data)) # print(my_data[:10]) elif my_current_list_selection == 'nthPoint': my_data = np.array(nthPlot(load_input_data(my_file_to_load), my_input_box_value)) # print(len(my_data)) # print(my_data[:10]) else: my_data = np.array(nthPlot(load_input_data(my_file_to_load), my_input_box_value)) my_long = list(my_data[:, 1]) my_lat = list(my_data[:, 2]) my_lat_min = min(my_lat) my_lat_max = max(my_lat) my_long_min = min(my_long) my_long_max = max(my_long) my_converted_list = [] for my_index in range(0, len(my_lat)): my_converted_list.append((my_long[my_index] - my_long_min) * (400 / (my_long_max - my_long_min)) + 50) my_converted_list.append((400 - (my_lat[my_index] - my_lat_min) * (400 / (my_lat_max - my_lat_min))) + 50) # canvas.create_polygon([50, 150, 150, 50, 250, 150, 150, 250], outline ="black", fill = "green") canvas.delete("all") canvas.create_polygon(my_converted_list, outline ="black", fill = "red") #------------------------------------------------------------------------------ my_frame = Frame(root) my_frame.grid() my_menubar = Menu(root) my_file_menu = Menu(my_menubar, tearoff=0) my_file_menu.add_command(label="Open", command=open_menu_file_loader) my_file_menu.add_command(label="Save", command=open_menu_file_loader) my_file_menu.add_command(label="Close", command=open_menu_file_loader) my_file_menu.add_command(label="Exit", command=root.quit) my_menubar.add_cascade(label="File", menu=my_file_menu) root.config(menu=my_menubar) my_dynamic_label_name = StringVar() my_dynamic_label_name.set('Select a list item') my_label_01 = Label(text="Select Method") my_label_02 = Label( textvariable=my_dynamic_label_name) my_entry_box = Entry(bd=1, width = 6) my_listbox_items = generate_algorithm_plugins('plugins.txt') my_listbox = Listbox(root, height=len(my_listbox_items) + 1) my_button = Button(text = "Process", command = generate_map_button_click) my_list_value = 1 for list_item in my_listbox_items: my_listbox.insert(my_list_value, list_item) my_list_value = my_list_value + 1 my_listbox.bind('<<ListboxSelect>>', get_listbox_selection) my_label_01.grid(row = 0, column = 0) my_listbox.grid(row = 0,column = 1, padx=10) my_label_02.grid(row=0, column=2, padx=5, sticky=E) root.grid_columnconfigure(2, minsize=125) my_entry_box.grid(row = 0, column = 3) my_button.grid(row=0, column = 4) canvas.grid(row = 1, column = 1, columnspan = 5) root.mainloop() # Use inheritence and allow users to import new simplification algorithm # Use the point class to store the data. Someone might load the Z value # Scaling should be to display the map but don't change the data # Read the plugins.txt to get list of algorithms # Use GUIconnection.py file classes. Don't add any new class and use the existing class. # Make sure error handling is coded when something correct is not typed # 400 - x or 400 - y # Lock the window size # Main file is linesimplificationq
#Please run the program directly. There is a print statement for each function. # Notes: Followed modular approach where one function is passed into other functions student=['adam','john','james','alice','sarah'] module=['cs','maths','geography','english'] mark=[[90,-1,70,85],[-1,90,50,60],[40,70,-1,60],[75,80,60,70],[80,60,50,-1]] def my_registered_marks(element): return element >= 0 and element <= 100 def my_func_avg_table_row_2_1(my_table, my_row_num): my_student_marks = my_table[my_row_num] my_registered_student_scores = list(filter(my_registered_marks, my_student_marks)) return round(sum(my_registered_student_scores)/len(my_registered_student_scores),2) def my_func_avg_table_column_2_2(my_table, my_column_num): my_subject_marks = [] for my_row in my_table: if(my_row[my_column_num] >= 0 and my_row[my_column_num] <= 100): my_subject_marks.append(my_row[my_column_num]) return round(sum(my_subject_marks)/len(my_subject_marks),2) def my_func_avg_student_marks_2_3(my_table, my_student_name): try: my_student_index_num = student.index(my_student_name) return my_func_avg_table_row_2_1(my_table,my_student_index_num) except ValueError: return 'There is no such student' def my_func_avg_module_marks_2_4(my_table, my_module_name): try: my_module_index_num = module.index(my_module_name) return my_func_avg_table_column_2_2(my_table,my_module_index_num) except ValueError: return 'There is no such module' def my_func_student_report_2_5(my_table): student_average = [] for each_student_name in student: student_average.append([each_student_name, my_func_avg_student_marks_2_3(my_table, each_student_name)]) student_average = sorted(student_average, key=lambda x: x[1], reverse=True) print('\n', '2.5: Printing Student Report') print('\t', 'Student Name', '\t', 'Average Marks') for my_row in student_average: print('\t', my_row[0], '\t', '\t', '\t', my_row[1]) print('\n') return student_average def my_func_module_report_2_6(my_table): module_average = [] for each_module_name in module: module_average.append([each_module_name, my_func_avg_module_marks_2_4(my_table, each_module_name)]) module_average = sorted(module_average, key=lambda x: x[1], reverse=True) print('\n', '2.6: Printing Module Report') print('\t', 'Module Name', '\t', '\t','Average Marks') for my_row in module_average: print('\t', my_row[0], '\t', '\t', '\t', '\t', my_row[1]) print('\n') return module_average #################################################################################### print('2.1: Row Average: ', my_func_avg_table_row_2_1(mark, 4)) # First parameter table name and second parameter row number print('2.2: Column Average: ', my_func_avg_table_column_2_2(mark, 3)) # First parameter table name and second parameter column number print('2.3: Student Search: ', my_func_avg_student_marks_2_3(mark, 'test')) # Correct student names: ['adam','john','james','alice','sarah'] print('2.4: Module Search: ', my_func_avg_module_marks_2_4(mark, 'accounting')) # Correct module names: ['cs','maths','geography','english'] print('2.5: Student Report: ', my_func_student_report_2_5(mark)) # Displays student report as table (list of list) in descending order print('2.6: Module Report: ', my_func_module_report_2_6(mark)) # Displays module report as table (list of list) in descending order ####################################################################################
class Solution(object): def nextPermutation(self, nums): """ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ def swap(n, i, j): temp = n[i] n[i] = n[j] n[j] = temp def reverse(n, i): j = len(n) - 1 while i < j: swap(n,i,j) i += 1 j -= 1 i = len(nums) - 2 while nums[i+1] <= nums[i] and i >= 0: i -= 1 if i >= 0: j = len(nums) - 1 while j >= 0 and nums[j] <= nums[i]: j -= 1 swap(nums, i, j) reverse(nums, i + 1)
# import math n = int(input('Enter number of teams: ')) passengers = n*15 # num_small = int(math.ceil(passengers/10)) #number of small buses # math.ceil(x) returns the smallest integer not less than x. small = 0 big = 0 cost = 0.0 min_num_small = small # to keep track of number of small buses which gives minimum cost min_num_large = big #to keep track of number of large buses which gives minimum cost min_cost = small*95 #initial cost assuming all small buses while(n>=0): if(n>20):# small bus capacity of 10 passengers cost = cost+200 n = n-48 # big bus capacity of 48 passengers big = big+1 elif(n<=20): cost=cost+95 n=n-10 small+=1 if cost<min_cost: min_cost = cost min_num_large = big min_num_small = small print('Book',min_num_small,'small buses and',min_num_large,'large buses') print('The minimum cost is = $', min_cost) # while(n>=0): # if(n>20):# small bus capacity of 10 passengers # cost = cost+200 # n = n-48 # big bus capacity of 48 passengers # big = big+1 # elif(n<=20): # cost=cost+95 # n=n-10 # small+=1 # print("Hire", big, "big buses and", small, "small buses. Cost = $", cost)
# script : printVertical.py # declare and call a function # with an argument, but no return value def printVertical(x): """Print x vertically""" for c in str(x): print(c) printVertical("String") printVertical(42)
# function returns list of all elements that occur multiple times in both lists def multiple_elements(list1,list2): result=[] for i in list1: #for each item in list1 if list1.count(i)>1 and list2.count(i)>1 and i not in result:#each item that occurs more than once result.append(i) #add item to result return list(set(result)) quit = "" while True: # sentinel pattern list_elements=input('Lists: ') # print(list_elements) #temp list_elements=list_elements.split(';') # use string split method() to specify semicolon to split list (normally whitespace) # returned value from map() can be passed to functions like list() (to create a list), set() (to create a set) list1=list(map(int,list_elements[0].split())) # list1 [0] is list before semicolon list2=list(map(int,list_elements[1].split())) # list2 [1] is list after semicolon if str == quit: # exit the loop break # print("List1: ", list1) #temp # print("List2: ", list2) #temp print(multiple_elements(list1,list2))
# 13_marks.py # Prompt for the number of marks and read them. # Print the number of marks entered and the average (arithmetic mean) of marks # Print the highest and lowest marks # use definite loop - for loop n = int(input("How many marks to be entered: ")) if n > 0: # only print average if n > 0 mark = float(input("Enter a mark: ")) highest = mark lowest = mark total = mark for i in range(n - 1): mark = float(input("Enter a mark: ")) total += mark if mark > highest: highest = mark if mark < lowest: lowest = mark print("The number of marks: ", n) print("The average mark is: ", total/ n) print("The lowest mark is: ", lowest) print("The highest mark is: ", highest)
# palindrome program to check if reverse and original of string are same or not. quit = "" while True: # run this loop until user enters blank sentence = input("Enter a string: ") # ask user to enter string input string1 = sentence.upper() # convert string to upper case to compare mirror = string1[::-1] # function which returns reverse of a string print("Reverse string in upper case: ", mirror) if(sentence == quit): # check if entered string is empty break if string1 == mirror: # compare strings print("It is a palindrome!") else: print("It is not a palindrome.")
# 스택 2개로 큐 자료구조 구현하기 class Queue(): # __변수명 : private / __변수명__ : public / _변수명 : protected __stack1 = [] # private __stack2 = [] # private def __init__(self): self.__stack1 = [] self.__stack2 = [] def push(self,data): self.__stack1.append(data) def pop(self): if self.__stack2: return self.__stack2.pop() else: while self.__stack1: self.__stack2.append(self.__stack1.pop()) return self.__stack2.pop() q = Queue() q.push(3) q.push(5) print(q.pop()) # 3 q.push(6) print(q.pop()) # 5 q.push(1) q.push(2) q.push(4) print(q.pop()) # 6 print(q.pop()) # 1 q.push(5) print(q.pop()) # 2 print(q.pop()) # 4 print(q.pop()) # 5
import numpy as np import math import random import time def select_algorithm(): algorithm = input("Select the algorithm you wish to use: " + '\n' + "1. Forward Selection" + '\n' + "2. Backwards Elimination" + '\n' + "3. Propinqua Algorithm" + '\n' ) # "Propinquus" is latin for "near/neighboring" # print("Please hold while the data is normalized.") # normalize_data() return algorithm def normalize_data(data): print("Please hold while data is normalized.") data = (data - np.mean(data)) / np.std(data) print("... Done!") return data def forward_selection(data): curr_set_of_features = [] global_best_acc = 0.0 # global best accuracy overall_best_feat_set = [] # global best feature start_time = time.time() for i in range(1, len(data[0])): # acts as a multiplier; how many times to run the inner loop feat_to_add = 0 local_best_acc = 0.0 # best recorded accuracy for local levels for k in range(1, len(data[0])): # runs through the features and calculates accuracy based on the current set with the new addition if k not in curr_set_of_features: print("--Considering adding feature ", k) acc = find_accuracy(curr_set_of_features, data, k, 1) if acc > local_best_acc: local_best_acc = acc feat_to_add = k curr_set_of_features.append(feat_to_add) # appends feature selected by inner for loop print("On level ", i, " feature ", feat_to_add, " was added to the current set") print("With ", len(curr_set_of_features), " features, the accuracy is: ", local_best_acc * 100, "%") if local_best_acc >= global_best_acc: # check for decrease in accuracy global_best_acc = local_best_acc overall_best_feat_set = list(curr_set_of_features) end_time = time.time() print("Set of features used: ", overall_best_feat_set, "at accuracy: ", global_best_acc * 100, '\n', "Elapsed time: ", end_time - start_time) return def backwards_elimination(data): global_best_acc = 0.0 # global best accuracy overall_best_feat_set = [] curr_set_of_features = [i for i in range(1, len(data[0]))] start_time = time.time() for i in range(1, len(data[0]) - 1): feat_to_pop = 0 local_best_acc = 0.0 # best recorded accuracy for local levels for k in range(1, len(data[0]) - 1): if k in curr_set_of_features: print("--Considering adding feature ", k) acc = find_accuracy(curr_set_of_features, data, k, 2) if acc > local_best_acc: local_best_acc = acc feat_to_pop = k if feat_to_pop in curr_set_of_features: curr_set_of_features.remove(feat_to_pop) # removes feature selected by inner for loop print("On level ", i, " feature ", feat_to_pop, " was removed from the current set") print("With ", len(curr_set_of_features), " features, the accuracy is: ", local_best_acc * 100, "%") if local_best_acc >= global_best_acc: # check for decrease in accuracy global_best_acc = local_best_acc overall_best_feat_set = list(curr_set_of_features) end_time = time.time() print("Set of features used: ", overall_best_feat_set, "At accuracy: ", global_best_acc * 100, '\n', "Elapsed time: ", end_time - start_time) return def propinqua(data): #forward selection with pruning print("You have selected the custom Propinqua Algorithm. Please note that only the best feature tests will be printed.") curr_set_of_features = [] global_best_acc = 0.0 # global best accuracy overall_best_feat_set = [] # global best feature start_time = time.time() for i in range(1, len(data[0])): # acts as a multiplier; how many times to run the inner loop feat_to_add = 0 local_best_acc = 0.0 # best recorded accuracy for local levels for k in range(1, len(data[0])): # runs through the features and calculates accuracy based on the current set with the new addition if k not in curr_set_of_features: acc = find_accuracy(curr_set_of_features, data, k, 1) if acc > local_best_acc: local_best_acc = acc feat_to_add = k if local_best_acc <= global_best_acc: if k == len(data[0]) - 1: # if the addition of any feature not yet included results in a decrease in accuracy, the best set has been found; break out of loop break if local_best_acc > global_best_acc: # check for decrease in accuracy curr_set_of_features.append(feat_to_add) # appends feature selected by inner for loop global_best_acc = local_best_acc overall_best_feat_set = list(curr_set_of_features) print("Set of current features (algorithm still in progress): ", curr_set_of_features) print("Accuracy at current level: ", local_best_acc * 100, "%") end_time = time.time() print("Set of features used: ", overall_best_feat_set, "At accuracy: ", global_best_acc * 100, "%", '\n', "Elapsed time: ", end_time - start_time) return def read_in_data(filename): return np.loadtxt(filename) def find_accuracy(set_of_features, data, test_feature, algorithm): test_feat_set = list(set_of_features) if algorithm == 1: #forward selection; Forward's Propinqua test_feat_set.append(test_feature) if algorithm == 2: #backwards elimination test_feat_set.remove(test_feature) num_correct_classifications = 0 local_shortest_distance = math.inf result = 0 # will be either 1 or 2 for i in data: local_shortest_distance = math.inf for h in data: if not np.array_equal(h, i): #checks if h and i are not the same row distance = 0 for j in test_feat_set: distance += pow((i[j] - h[j]), 2.0) # n-space Euclidean distance formula if math.sqrt(distance) < local_shortest_distance: local_shortest_distance = math.sqrt(distance) result = h[0] # the result "guessed" by the algorithm if result == i[0]: num_correct_classifications += 1 return num_correct_classifications / (len(data) - 1) def main(): filename = input("Type in the name of the file to test: ") algorithm = select_algorithm() if algorithm == "1": forward_selection(normalize_data(read_in_data(filename))) if algorithm == "2": backwards_elimination(normalize_data(read_in_data(filename))) if algorithm == "3": propinqua(normalize_data(read_in_data(filename))) return if __name__ == '__main__': main()
#aprimore o desafio 093 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador. #leia o nome do jogador e quantas partidas ele jogou, depois leia a quantidade de gols feitos em cada partida, salve o total de gols print('\033[34m') jogador = dict() jogadores = list() while True: jogador.clear() jogador['nome'] = str(input('Nome: ')).capitalize() partidas = int(input('Total de partidas: ')) jogador['gols'] = list() jogador['total'] = 0 for c in range(0, partidas): jogador['gols'].append(int(input(f'Quantidade de gols na {c+1}° partida: '))) for i, v in enumerate(jogador['gols']): jogador['total'] += v jogadores.append(jogador.copy()) c = str(input("Continuar[S/N]: ")).upper() if c == "N": break print('-='*30) print(f'{"N°":<5} {"Nome":<15} {"Gols":<15} {"Total":<15}') for i,j in enumerate(jogadores): print(f'{i+1:<5}',end=' ') for v in j.values(): print(f'{str(v):<15}',end=' ') print() while True: while True: b = int(input("Mostrar dados de qual jogador(999 stop): ")) if b <= len(jogadores) or b == 999: break if b == 999: break print(f'Dados : {jogadores[b-1]["nome"]}') for i,g in enumerate(jogadores[b-1]['gols']): print(f'Partida {i+1}: {g} Gols')
#simulando um caixa eletronico utilizando notas de R$50,20,10,1 print(f'\033[32m-='*20) print('{:^40}'.format('BANCO')) print(f'-='*20,'\033[m') valor = int(input('Quanto você gostaria de sacar? R$ ')) dinheiro = 50 dintotal = 0 while True: if dinheiro <= valor: valor -= dinheiro dintotal += 1 else: if dintotal > 0: print(f'\033[32m{dintotal} notas de {dinheiro}\033[m') if dinheiro == 50: dinheiro = 20 elif dinheiro == 20: dinheiro = 10 elif dinheiro == 10: dinheiro = 1 dintotal = 0 if valor == 0: break
#Par ou impar com o PC from random import randint print('Eae vamos jogar par ou impar') cont = 0 while True: jogador = str(input('Par ou impar? ')).strip().upper(), int(input('Diga um numero: ')) computador = randint(0,10) total = jogador[1] + computador if total % 2 == 0: resultado = 'PAR' else: resultado = 'IMPAR' if resultado == jogador[0]: print(f'\033[32mVoce jogou {jogador[1]} e o computador {computador}. total {total} = {resultado}') print('Parabéns você venceu\033[m') cont += 1 else: print(f'\033[31mVoce jogou {jogador[1]} e o computador {computador}. total {total} = {resultado}') print('GAME OVER\nQue pena você perdeu\033[m') print(f'Total de vítorias: {cont}') break
#crie um programa que mostre o seu dobro e o seu triplo n = int(input('Digite um numero: ')) dobro = n * 2 triplo = n * 3 raiz = n ** (1/2) print('O numero que você digitou é: {}' .format(n)) print('O dobro dele é: {}' .format(dobro)) print('O triplo dele é: {}' .format(triplo)) print('A raiz quadrada dele é: {:.2f}' .format(raiz))
# leia o comprimento de três retas. Diga ao usuario se elas podem formar um triângulo cores = { 'azul': '\033[34m', 'verde': '\033[32m', 'vermelho': '\033[31m', 'branco': '\033[7m', 'reset': '\033[m', } reta1 = float(input('Digite o valor da reta1: ')) reta2 = float(input('Digite o valor da reta2: ')) reta3 = float(input('Digite o valor da reta3: ')) if reta1 < reta2 + reta3 and reta2 < reta1 + reta3 and reta3 < reta1 + reta2: print(cores['azul'], 'Suas retas podem formar um triângulo') else: print(cores['vermelho'], 'Suas retas não podem formar um triângulo')
#Conversor de moedas #Real para dolar real = float(input('Digite um valor: R$')) dolar = real/ 5.29 print('Real: R${:.2f} \nDollar: ${:.2f}' .format(real,dolar))
# calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento p = float(input('Valor do produto: ')) c = str(input('Forma de pagamento\n1 - Dinheiro\n2 - Cartão\n: ')) if c == '1' or c.lower == 'dinheiro': print('Seu produto tem 10% de desconto e será {}'.format(p - (p * 10 / 100))) elif c == '2' or c.lower == 'cartão': x = int(input('Em quantas vezes gostaria de pagar: ')) if x == 1: print('Seu produto tem 5% de desconto e saira por R$ {:.2f}'.format( p - (p * 5 / 100))) elif x == 2: print('2x de R$ {}'.format(p / 2)) print('Seu produto vai sair por R$', p) elif x >= 3: print('{}x de {}'.format(x, p / x)) print('Seu produto vai sofrer juros e vai sair por R$ {:.2f}'.format(p + (p *20 / 100))) else: print('Digite uma das opções acima')
#Mostre a ficha de um jogador def ficha(nome="<Desconhecido>", gols=0): print(f'\033[34mO jogador {nome} marcou {gols} gols') a = str(input('Nome: ')).capitalize() b = str(input('Gols: ')) if b.isnumeric(): b = int(b) else: b = 0 if a.strip() == '': ficha(gols=b) else: ficha(a,b)
#leia uma frase e mostre #quantas vezes a letra "a" aparece #em que posição ela aparece a primeira vez #em que posição ela aparece a ultima vez frase = str(input('Digite uma frase = ')).upper().strip() print('A letra "A" aparece: {} vezes'.format(frase.count('A'))) print('A letra "A" aparece pela primeira vez na posição: {}'.format(frase.find('A')+1)) print('A letra "A" aparece pela ultima vez na posição: {}'.format(frase.rfind('A')+1))
print('\033[34m') #leia 5 valores e guarde em uma lista: valores = [] for c in range(0,5): valores.append(int(input('Digite um valor: '))) #mostre qual o maior e o menor e suas posições na lista if c == 0: maior = menor = valores[c] else: if valores[c] > maior: maior = valores[c] if valores[c] < menor: menor = valores[c] print(f'Entre os valores: {valores}') print(f'O maior é: {maior}', end=' ') for i,v in enumerate(valores): if valores[i] == maior: print(f'na {i} posição', end=' ') print(f'\nO menor é: {menor}', end=' ') for i,v in enumerate(valores): if valores[i] == menor: print(f'na {i} posição', end=' ') print('\033[m')
#ler uma quantidade indeterminada de numeros e somar n = c = s = 0 n = int(input('Digite um número [999 Stop]: ')) while n != 999: c += 1 s += n n = int(input('Digite um número [999 Stop]: ')) print('Digitos: {}'.format(c)) print('Soma: {}'.format(s)) print('FIM\n')
#cadastre varios valores em uma lista print('\033[34m') valores = [] while True: n = (int(input('Digite um valor: '))) if n in valores: print('Este numero já foi adicionado') else: valores.append(n) while True: continuar = str(input('Quer continuar [S/N]: ')).strip().upper() if continuar in 'SN': break if continuar in 'N': break print(f'Valores na sua lsita: {sorted(valores)}')
#verifique se o mesmo numero de parentes que abre também estão fechando print('\033[34m') expressão = str(input('Digite uma expressão com parenteses: ')) par = [] for l in expressão: if l == "(": par.append(l) elif l == ")": if len(par) == 0: par.append(l) break else: par.pop() if len(par) == 0: print('Sua expressão é valida') if len(par) > 0: print('Sua expressão é invalida')