text
stringlengths
37
1.41M
import random def get_non_prize_door(host, num_doors, player_choice): i = 1 while (i == host or i == player_choice): i = (i + 1) % (num_doors) return i def switch_function(shown_door, num_doors, player_choice): i = 1 while (i == shown_door or i == player_choice): i = (...
class Car(): def __init__(self, name, model, year): self.name = name self.model = model self.year = year class Battery (): def __init__(self, battery_size = 90): self.battery_size = battery_size def upgrade_battery(self): if self.battery_size != 85: self.battery_size = 85 print('Battery upgraded to'...
# http://www.cs.bilkent.edu.tr/~atat/473/lecture05.pdf # bu linkteki syf 5 ve 21 deki pseudo'lar kullanılmıştır def lomuto(arr, p, r): pivot = arr[r] i = p-1 j = p while j < r: if arr[j] <= pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] j = j+1 arr[i+1],arr[r] = arr[r],arr[i+1] return i+1 ...
#!/usr/bin/env python fst = lambda ab: ab[0] snd = lambda ab: ab[1] head = lambda xs: xs[0] tail = lambda xs: xs[1:] def is_inter(a, b): """ Integer -> Integer -> Bool""" return a == b - 1 or a == b def list_sort(data): """ :: set -> [Integer], where the result is sorted """ return sorted(li...
# DNA Matching Algorithm def char2base4(S): """ Convert gene sequence to base 4 string """ c2b = {} c2b['A'] = '0' c2b['C'] = '1' c2b['G'] = '2' c2b['T'] = '3' L = '' for s in S: L += c2b[s] return L def hash10(S, base): """Convert list S to base-10 number where ...
# -*- coding: utf-8 -*- """Contain game-calc logic.""" from random import randrange, choice from operator import add, mul, sub DESCRIPTION = "What is the result of the expression?" OPERATORS = [('+', add), ('-', sub), ('*', mul)] def logic(): """Define logic for brain-calc game, re...
#!/usr/bin/python import sys def generate_parentheses(n): if n is None: return n if n is 1: return ['()'] prev = generate_parentheses(n - 1) return _add_new_parenthesis(prev) def _add_new_parenthesis(prev): curr1 = ['()' + x for x in prev] curr2 = ['(' + x + ')' for x in prev]...
# ------------------------------ # 687. Longest Univalue Path # # Description: # Given a binary tree, find the length of the longest path where each node in the path has the same value. # This path may or may not pass through the root. # # Note: The length of path between two nodes is represented by the number of ed...
# ------------------------------ # 206. Reverse Linked List # # Description: # Reverse a singly linked list. # # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # # Follow up: # A linked list can be reversed either iteratively or recursively. Could you implement both? # # Version: 3.0 # 11/10/19...
# ------------------------------ # 105. Construct Binary Tree from Preorder and Inorder Traversal # # Description: # Given preorder and inorder traversal of a tree, construct the binary tree. # Note: # You may assume that duplicates do not exist in the tree. # # For example, given # preorder = [3,9,20,15,7] # inorder...
# ------------------------------ # 77. Combinations # # Description: # Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. # # For example, # If n = 4 and k = 2, a solution is: # [ # [2,4], # [3,4], # [2,3], # [1,2], # [1,3], # [1,4], # ] # # Version: 1.0 # 01/20/18 ...
# ------------------------------ # 539. Minimum Time Difference # # Description: # Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes # difference between any two time points in the list. # # Example 1: # Input: ["23:59","00:00"] # Output: 1 # # Note: # The number of time p...
# ------------------------------ # 47. Permutations II # # Description: # Given a collection of numbers that might contain duplicates, return all possible unique permutations. # # For example, # [1,1,2] have the following unique permutations: # [ # [1,1,2], # [1,2,1], # [2,1,1] # ] # # Version: 1.0 # 11/03/17 ...
# ------------------------------ # 135. Candy # # Description: # There are N children standing in a line. Each child is assigned a rating value. # You are giving candies to these children subjected to the following requirements: # Each child must have at least one candy. # Children with a higher rating get more candie...
# ------------------------------ # 459. Repeated Substring Pattern # # Description: # Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length wi...
# ------------------------------ # 150. Evaluate Reverse Polish Notation # # Description: # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # # Note: # Division between two integers should truncate towar...
# ------------------------------ # 69. Sqrt(x) # # Description: # Implement int sqrt(int x). # Compute and return the square root of x. # x is guaranteed to be a non-negative integer. # # Example 1: # # Input: 4 # Output: 2 # # Example 2: # # Input: 8 # Output: 2 # Explanation: The square root of 8 is 2.82842..., ...
# ------------------------------ # 526. Beautiful Arrangement # # Description: # Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array # that is constructed by these N numbers successfully if one of the following is true for # the ith position (1 <= i <= N) in this array: # # The nu...
# ------------------------------ # 623. Add One Row to Tree # # Description: # Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. # The adding rule is: given a positive integer depth d, for each NOT null tree nodes N...
# ------------------------------ # 25. Reverse Nodes in k-Group # # Description: # Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. # k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then l...
# ------------------------------ # 87. Scramble String # # Description: # Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings # recursively. # Below is one possible representation of s1 = "great": # great # / \ # gr eat # / \ / \ # g r e at #...
# ------------------------------ # 448. Find All Numbers Disappeared in an Array # # Description: # Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. # Find all the elements of [1, n] inclusive that do not appear in this array. # Could you do it witho...
# ------------------------------ # 128. Longest Consecutive Sequence # # Description: # Given an unsorted array of integers, find the length of the longest consecutive elements sequence. # Your algorithm should run in O(n) complexity. # # Example: # Input: [100, 4, 200, 1, 3, 2] # Output: 4 # Explanation: The longest...
# ------------------------------ # 40. Combination Sum II # # Description: # Given a collection of candidate numbers (candidates) and a target number (target), find # all unique combinations in candidates where the candidate numbers sums to target. # # Each number in candidates may only be used once in the combinati...
# ------------------------------ # 504. Base 7 # # Description: # Given an integer, return its base 7 string representation. # Example 1: # Input: 100 # Output: "202" # # Example 2: # Input: -7 # Output: "-10" # Note: The input will be in range of [-1e7, 1e7]. # # Version: 1.0 # 07/12/18 by Jianfa # ----------------...
# ------------------------------ # 530. Minimum Absolute Difference in BST # # Description: # Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. # Example: # Input: # 1 # \ # 3 # / # 2 # Output: # 1 # Explanation: # The minimum ...
# ------------------------------ # 117. Populating Next Right Pointers in Each Node II # # Description: # Given a binary tree # struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; # } # Populate each next pointer to point to its next right node. If there is no next right node...
# ------------------------------ # 500. Keyboard Row # # Description: # Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. # # Example 1: # Input: ["Hello", "Alaska", "Dad", "Peace"] # Output: ["Alaska", "Dad"] # Note: # You...
# ------------------------------ # 284. Peeking Iterator # # Description: # # Version: 1.0 # 09/30/18 by Jianfa # ------------------------------ # Below is the interface for Iterator, which is already defined for you. # # class Iterator: # def __init__(self, nums): # """ # Initializes an iterator...
# ------------------------------ # 173. Binary Search Tree Iterator # # Description: # Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. # Calling next() will return the next smallest number in the BST. # Note: next() and hasNext() should run in avera...
# ------------------------------ # 417. Pacific Atlantic Water Flow # # Description: # Given an m x n matrix of non-negative integers representing the height of each unit cell in a # continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic # ocean" touches the right and bottom ed...
# ------------------------------ # 105. Construct Binary Tree from Preorder and Inorder Traversal # # Description: # Given preorder and inorder traversal of a tree, construct the binary tree. # # Note: # You may assume that duplicates do not exist in the tree. # # For example, given # # preorder = [3,9,20,15,7] # i...
# ------------------------------ # 19. Remove Nth Node From End of List # # Description: # Given a linked list, remove the nth node from the end of list and return its head. # # For example, # Given linked list: 1->2->3->4->5, and n = 2. # # After removing the second node from the end, the linked list becomes 1->2...
# ------------------------------ # 244. Shortest Word Distance II # # Description: # Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly...
# ------------------------------ # 212. Word Search II # # Description: # Given a 2D board and a list of words from the dictionary, find all words in the board. # Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same ...
# ------------------------------ # 721. Accounts Merge # # Description: # Given a list accounts, each element accounts[i] is a list of strings, where the first # element accounts[i][0] is a name, and the rest of the elements are emails representing # emails of the account. # # Now, we would like to merge these acco...
# ------------------------------ # 124. Binary Tree Maximum Path Sum # # Description: # Given a non-empty binary tree, find the maximum path sum. # For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at l...
# ------------------------------ # 729. My Calendar I # # Description: # Implement a MyCalendar class to store your events. A new event can be added if adding # the event will not cause a double booking. # # Your class will have the method, book(int start, int end). Formally, this represents a # booking on the half...
# ------------------------------ # 61. Rotate List # # Description: # Given a list, rotate the list to the right by k places, where k is non-negative. # Example: # Given 1->2->3->4->5->NULL and k = 2, # return 4->5->1->2->3->NULL. # # Version: 1.0 # 01/15/18 by Jianfa # ------------------------------ # Definition fo...
# ------------------------------ # 95. Unique Binary Search Trees II # # Description: # Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. # Example: # Input: 3 # Output: # [ # [1,null,3,2], # [3,2,null,1], # [3,1,null,null,2], # [2,1,3], # [1,null,2,n...
# ------------------------------ # 434. Number of Segments in a String # # Description: # Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. # Please note that the string does not contain any non-printable characters. # Example: # Input: "Hello, my...
# ------------------------------ # 253. Meeting Rooms II # # Description: # Given an array of meeting time intervals consisting of start and end times # [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. # # Example 1: # Input: [[0, 30],[5, 10],[15, 20]] # Output: 2 # # Example 2...
# ------------------------------ # 289. Game of Life # # Description: # According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton # devised by the British mathematician John Horton Conway in 1970." # # Given a board with m by n cells, each cell has an initial state l...
# ------------------------------ # 450. Delete Node in a BST # # Description: # Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. # # Basically, the deletion can be divided into two stages: # Search for a node t...
# ------------------------------ # 15. 3Sum # # Description: # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. # # Note: The solution set must not contain duplicate triplets. # For example, given array S = [...
# ------------------------------ # 113. Path Sum II # # Description: # Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. # Note: A leaf is a node with no children. # Example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ #...
# ------------------------------ # 240. Search a 2D Matrix II # # Description: # Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from...
# ------------------------------ # 236. Lowest Common Ancestor of a Binary Tree # # Description: # Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. # # According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the low...
# ------------------------------ # 215. Kth Largest Element in an Array # # Description: # Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. # Example 1: # Input: [3,2,1,5,6,4] and k = 2 # Output: 5 # # Example 2: # Input: [3,...
# ------------------------------ # 228. Summary Ranges # # Description: # Given a sorted integer array without duplicates, return the summary of its ranges. # # Example 1: # Input: [0,1,2,4,5,7] # Output: ["0->2","4->5","7"] # Example 2: # Input: [0,2,3,4,6,8,9] # Output: ["0","2->4","6","8->9"] # # Version: 1.0 # 1...
# ------------------------------ # 259. 3Sum Smaller # # Description: # Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n # that satisfy the condition nums[i] + nums[j] + nums[k] < target. # # For example, given nums = [-2, 0, 1, 3], and target = 2. # R...
# ------------------------------ # 201. Bitwise AND of Numbers Range # # Description: # Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. # Example 1: # Input: [5,7] # Output: 4 # # Example 2: # Input: [0,1] # Output: 0 # # Version: 1.0 # 08/27/18 b...
# ------------------------------ # 271. Encode and Decode Strings # # Description: # https://leetcode.com/problems/encode-and-decode-strings/description/ # # Version: 1.0 # 11/10/17 by Jianfa # ------------------------------ class Codec: def encode(self, strs): """Encodes a list of strings to a single s...
# ------------------------------ # 111. Minimum Depth of Binary Tree # # Description: # Given a binary tree, find its minimum depth. # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # Note: A leaf is a node with no children. # Example: # Given binary ...
# ------------------------------ # c696. Count Binary Substrings (Weekly Contest 54) # # Description: # Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's # and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. # # Substrings that...
# ------------------------------ # 119. Pascal's Triangle II # # Description: # Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. # Note that the row index starts from 0. # Example: # Input: 3 # Output: [1,3,3,1] # # Follow up: # Could you optimize your algorithm to use onl...
# ------------------------------ # 315. Count of Smaller Numbers After Self # # Description: # You are given an integer array nums and you have to return a new counts array. The counts # array has the property where counts[i] is the number of smaller elements to the right of nums[i]. # # Example: # # Input: [5,2,6,...
# ------------------------------ # 89. Gray Code # # Description: # The gray code is a binary numeral system where two successive values differ in only one bit. # # Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray # code. A gray code sequence must begin wit...
# ------------------------------ # 58. Length of Last Word # # Description: # vGiven a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length # of last word in the string. # If the last word does not exist, return 0. # # Note: A word is defined as a character sequence consi...
# ------------------------------ # 118. Pascal's Triangle # # Description: # Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. # In Pascal's triangle, each number is the sum of the two numbers directly above it. # Example: # Input: 5 # Output: # [ # [1], # [1,1], # [1,2...
# ------------------------------ # 397. Integer Replacement # # Description: # Given a positive integer n and you can do operations as follow: # # If n is even, replace n with n/2. # If n is odd, you can replace n with either n + 1 or n - 1. # What is the minimum number of replacements needed for n to become 1? # # ...
# ------------------------------ # 29. Divide Two Integers # # Description: # Divide two integers without using multiplication, division and mod operator. # # If it is overflow, return MAX_INT. # # Version: 1.0 # 12/18/17 by Jianfa # ------------------------------ class Solution(object): def divide(self, divide...
# ------------------------------ # 153. Find Minimum in Rotated Sorted Array # # Description: # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # # Find the minimum element. # You may assume no duplicate exists...
# ------------------------------ # 242. Valid Anagram # # Description: # Given two strings s and t , write a function to determine if t is an anagram of s. # # Example 1: # Input: s = "anagram", t = "nagaram" # Output: true # # Example 2: # Input: s = "rat", t = "car" # Output: false # Note: # You may assume the str...
# ------------------------------ # 103. Binary Tree Zigzag Level Order Traversal # # Description: # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). # For example: # Given binary tree [3,9,20,null,n...
# ------------------------------ # 34. Search for a Range # # Description: # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # You are given a target value to search. If found in the array return its index, otherwise ...
# ------------------------------ # 75. Sort Colors # # Description: # Given an array with n objects colored red, white or blue, sort them in-place so that # objects of the same color are adjacent, with the colors in the order red, white and # blue. # # Here, we will use the integers 0, 1, and 2 to represent the col...
# ------------------------------ # 406. Queue Reconstruction by Height # # Description: # Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height grea...
class bin_heap: def __init__(self): self.heapsize = 0 self.heaplist = [0] def heapify(self, i): largest = i l = 2*i + 1 r = 2*i + 2 # print('larg = ', largest, self.heaplist[largest]) # print('l = ', l, self.heaplist[l]) # print('r = ', r, self....
def main(): v, e = map(int, input('Введите через пробел количество вершин и ребер: ').split()) A = [[0] * (v) for i in range(v)] # создаем матрицу V на V for i in range(e): a, b = map(int, input('Введите ребро номер ' + str(i) +' из ' + str(e) + ': ').split()) A[a][b] = 1 A[b][a] =...
#--------------iteration algo------------------ N = [i for i in range(100)] def binary_s(N, A): M = 0 while M != A: n = len(N)//2 M = N[n] N_left, N_right = N[:n], N[n+1:] # постоянно забываю что сюда передаем не переменную, а ее положение в списке if A == M: pri...
G = {0: [1, 6], 1: [2, 3], 2: [1], 3: [1, 4], 4: [3, 5], 5: [4, 6], 6: [5, 0] } n = len(G.keys()) print(n) s = 0 #начало пути visited = [False] * n # массив посещенных вершин # аглоритм прохода в глубину определяет колличество вершин в данном компоненте связности def dfs(v): ...
import random import unittest from recur_binary_search import binary_search from random import choice class TestCase(unittest.TestCase): # def test_true_recursion(self): # array = [1, 2, 7, 12, 43, 44, 54, 100, 124, 147] # n = choice(array) # print(f"Random numbers: {n}") # resul...
import random def Quotes(): QUOTE_DICT = {"patience" : [["\"Patience, grasshopper\", said Maia. \"Good things come to those who wait.\" \"I always thought that was \'Good things come to those who do the wave\'\", said Simon. \"No wonder I\'ve been so confused all my life.\"", "Cassandr...
__arglist__ = {'2選1:(關數請寫1,卡片數請寫2)': 'x', '其數量': 'card', '時間': 'time'} def __invoke__(arg): Time = float(arg["time"]) Card = int(arg["card"]) Choice = int(arg["x"]) if Choice==1: if Card <= 35: Card = Card + Card // 5 * 2 + (Card+2) // 5 else: Card = 56 + (Card-35) * 2 + (Card-35)//2 * 4 Cardpertime = f...
#!/usr/bin/env python import turtle class Window: """Provides methods for manipulating the tkinter/turtle window/screen""" def __init__(self, bounds, bg): """Initialize the tkinter/turtle window/screen for interfacing.""" self.screen = turtle.Screen() assert isinstance(bounds, tuple)...
#using boolean #is_male = input(" Enter True or False: Are you male? :") #is_tall = input(" Enter True or False: Are you male? :") is_male=False is_tall=False if is_male and is_tall: print("You are male and tall") elif is_male and not is_tall: print("You are a short male") elif not is_male and is_tall: p...
#檔案的讀取、寫入 #Open("檔案路徑", mode= "開啟模式") # 絕對路徑 Ex: C:/Users/didd4/OneDrive/文件\python # 相對路徑 以程式的位置做延伸 ex: 123.txt # mode = "r" 讀取 # mode = "w" 複寫 # mode = "a" 在原先的資料後寫東西 file = open("123.txt",mode="a",encoding="utf-8") # for line in file: # print(line) file.write("\n蔡陰魂") file.close()
# for 迴圈 # for 變數 in 字串OR列表: # 要重覆執行的程式碼 #for letter in "我是皮卡丘": # print(letter) #for num in[0,1,2,3,4]: # print(num) #for num in range(2,7): # print(num) def power(base_num,pow_num): result = 1 for index in range(pow_num): result = result * base_num return result print(power(2,5))...
class Cards: def __init__(self, hand_one=[], hand_two=[]): self.player_1 = hand_one self.player_2 = hand_two def deal(self, data): player_1 = data[0].split('\n')[1:] player_2 = data[1].split('\n')[1:] self.player_1 = list(map(int, player_1)) self.player_2 = l...
# Problem for Cracking the Coding Interview: Chapter 1 # 1.6 # String Compression: # Implement a method to perform basic string compression using the counts of repeated characters. # For example, the string aabcccccaaa would become a2b1c5a3. # If the "compressed" string would not become smaller than the original strin...
# "Maximum Substring With Non-Repeating Characters" from SWE Careers # Given a string, find the length of the longest substring without repeating characters. # Example 1: # Input: "abcabcbb" # Output: 3 # Explanation: The answer is "abc", with the length of 3. # Example 2: # Input: "bbbbb" # Output: 1 # Explanation: ...
from disassembler import * def factorial(n): if n==0: return 1 return n*factorial(n-1) def main(): x = int(input("Please enter an integer: ")) y = factorial(x) print("Factorial of", x, "is", str(y)+".") print(type(x)) print(type(factorial)) z = type(factorial) pri...
import disassembler def factorial(n): if n==0: return 1 return n*factorial(n-1) def main(): print(factorial(5)) #main() disassembler.disassemble(factorial) disassembler.disassemble(main)
class PlayerStats: """ Statistics on a basketball team """ #def __init__ (self, total_num_players, num_guards, num_forwards, num_centers, avg_years_played): _player_manager = None def __init__(self, player_manager): self._player_manager = player_manager def get_total_num_players(self): ...
# Анализатор текста # Демонстрирует работу функции len() и оператора in # всё просто msg = input('Введите текст: ') print('\nДлина введенного вами текста составляет:', len(msg)) new_msg = '' for letter in msg[::-1]: new_msg += letter print('Создана новая строка:', new_msg) input('\n\nНажмите Enter, что бы выйт...
"""Можно конечно просто без вариативно написать, переменню цитаты и кто сказал""" favorite_quote = None # всё так же как и в предыдущей задаче while not favorite_quote: favorite_quote = input('Ваша любимая цитата?') # дотех пор пока нет вводе будет повторяться до бесконечности name = input('Автор?') # если...
import numpy as np def rolling_window(a, window, step): """ Make an ndarray with a rolling window of the last dimension with a given step size. Parameters ---------- a : array_like Array to add rolling window to window : int Size of rolling window step : int Size o...
''' @autor: Vanderson Andrade @data: 00/00/2019 @versão: 1.0 @descrição: Ler a velocidade de um carro e diz se ele foi multado por velocidade e mostra o valor da multa ''' kmPermitido = 80 velocidadeCarro = float(input('Qual a velocidade do Carro em KM/H: ')) if velocidadeCarro > kmPermitido: valorMulta = (veloci...
''' @autor: Vanderson Andrade @data: 00/00/2019 @versão: 1.0 @descrição: emprestimo bancario para compra de uma casa ''' nome = str(input('Nome: ')) salario = float(input('Salário: R$')) vcasa = float(input('Valor do emprestimo: R$')) tempoano = int(input('Quantos anos para pagar: ')) prestacao = vcasa / (tempoano*15...
''' @autor: Vanderson Andrade @data: 00/00/2019 @versão: 1.0 @descrição: ler tres segmentos e dizer se é posivel forma um triangulo ''' print('\033[32;1m-=\033[m'*13) print(' \033[36;1mDesafio do Triangulo\033[m ') print('\033[32;1m-=\033[m'*13) s1 = float(input('Digite o primeiro segmento: ')) s2 = float(input('D...
''' @autor: Vanderson Andrade @data: 00/00/2019 @versão: 1.0 @descrição: Reajuste salarial ''' salario = float(input('Quanto está recebendo hoje? ')) if salario > 1250.00: reajuste = (salario * 0.10) + salario print('Reajuste de: \033[1;4;36mR${:.2f}\033[m'.format(salario * 0.10)) print('Novo salário: \...
''' @autor: Vanderson Andrade @data: 00/00/2019 @versão: 1.0 @descrição: ''' ''' simples: if condição: bloco verdadeiro else: bloco falso simples(simplificada) 'bloco verdadeiro' if condição else 'bloco falso' ''' #Exemplos: tempo = int(input('Quantos anos tem seu carro: ')) if tempo <= 3 : print(...
class Game(object): """Class Game""" def __init__(self, name, release, developer, rating): self.name = name self.release=release self.developer = developer self.rating = rating def __str__(self): return self.name def full_info(self): game_str = self.name + "| Release Date: "+self.release +" | Deve...
#!/usr/bin/env python import os ##从文件中读数据 def file_write_read(): """ 文件读、写,的步骤: 1.打开文件 2.读/写 3.关闭文件 """ fn = open("名单","rb") print(fn.read()) fn.seek(0) content = fn.readlines() ## 读取所有行并返回列表 print(content) for i in content: print(i.decode("utf-8").strip()) ...
smallest = None largest = None my_list = [] while True: numb = input("Enter Number:") if numb == ("done"): break try: my_list.append (int(numb)) except: print('Invalid input') continue for i in my_list: if largest is None: largest = i elif i > largest:...
# French Cards # French Cards have two states: hidden and visible. # Choose 1 or 2 to flip that card between hidden and visible. # Every time you hide a card, it's replaced with a # random card from the rest of the deck. # Game is over when all cards have been shown and then hidden. import random # hidden and deck...
""" This program computes maximum number of edges that can be inserted in a bipartite graph without violating its bipartite property. """ print("No. of vertices: ") n = int(input()) print("No. of edges: ") e = int(input()) adjlst = {} print("Enter edges - enter 'a b' if there is an edge between a and b :") fo...
def shortestPath(ar,previndex=0,i=0): m = i+1 if len(ar)==0: return 0 if(i>= len(ar)): return 0 if(i==0): return ar[i][0] + shortestPath(ar,0,1) if(previndex == 0 ): result = min(ar[i][0],ar[i][1]) index = ar[i].index(result) return res...
def common_sub(str1,str2): if(len(str1)==1 or len(str2)==1): return 1 if(str1[-1]==str2[-1]): count=common_sub(str1[:-1],str2[:-1])+1 else: count=max(common_sub(str1[:-1],str2),common_sub(str1,str2[:-1])) return count str1="abcdaf" str2="acbcf" com=common_sub(str1,str2) p...