text
stringlengths
37
1.41M
#program to convert KM to miles import time flag = -1 while flag == -1: km = input('Enter the Km to convert to miles : ') km = float(km) m = km*0.62137 m = float(m) print('\n',km,'Kilometers are',m,'Miles') time.sleep(1.5) choice = input('\nIf you wanna quit press 1 else any number to conti...
# Write a program to solve a Sudoku puzzle by filling the empty cells. # # A sudoku solution must satisfy all of the following rules: # # Each of the digits 1-9 must occur exactly once in each row. # Each of the digits 1-9 must occur exactly once in each column. # Each of the the digits 1-9 must occ...
# Given a binary tree, check whether it is a mirror of itself # (ie, symmetric around its center). # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # # 1 # / \ # 2 2 # / \ / \ # 3 4 4 3 # But the following [1,2,2,null,3,null,3] is not: # # 1 # / \ # 2 2 # \ \...
# # Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original # BST is changed to the original key plus sum of all keys greater than the original key in BST. # # Example: # # Input: The root of a Binary Search Tree like this: # 5 # / \ # ...
# There are N rooms and you start in room 0. Each room has a distinct number in # 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. # # Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an # integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i...
# Find all possible combinations of k numbers that add up to a number n, # given that only numbers from 1 to 9 can be used and each combination # should be a unique set of numbers. # # Note: # # All numbers will be positive integers. # The solution set must not contain duplicate combinations. # # Exa...
# 225. Implement Stack using Queues import collections class MyStack(object): # initialize your data structure here. def __init__(self): self.stack = collections.deque([]) # @param x, an integer # @return nothing def push(self, x): self.stack.append(x) # @retu...
# https://leetcode.com/problems/my-calendar-i/solution/# # Actually My Calender II was asked in google ... # 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, ...
# Given an array of characters, compress it in-place. # The length after compression must always be smaller than or equal to the original array. # Every element of the array should be a character (not int) of length 1. # After you are done modifying the input array in-place, return the new length of the array. ...
# Tags: Array, Dymanic Programming, Amazon # On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). # Once you pay the cost, you can either climb one or two steps. You need to find minimum cost # to reach the top of the floor, and you can either start from the step with index 0, o...
# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. # # Example 1: # Input: num1 = "2", num2 = "3" # Output: "6" # # Example 2: # Input: num1 = "123", num2 = "456" # Output: "56088" class Solution(): # https://l...
# Given an unsorted array of integers, find the length of longest increasing subsequence. # Example: # Input: [10,9,2,5,3,7,101,18] # Output: 4 # Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. # --------------------------------------------------------------------------...
# Tags: Array, FB, MS, AWS, LinkedIn # =================================== # The idea is that for each element of the array, you would want to multiply all # the elements to the left and right. So in the first for loop you are cumulatively # multiplying all the previous elements to each other in each iteratio...
# http://book.pythontips.com/en/latest/debugging.html <==== Important Tips on Python # Iterating With Python Lambdas # https://caisbalderas.com/blog/iterating-with-python-lambdas/ # https://medium.com/@happymishra66/lambda-map-and-filter-in-python-4935f248593 # http://www.secnetix.de/olli/Python/lambda_...
# 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 left-out nodes in the # end should remain as it is. # # Example: # # ...
# Given an array, rotate the array to the right by k steps, where k is non-negative. # Example 1: # Input: [1,2,3,4,5,6,7] and k = 3 # Output: [5,6,7,1,2,3,4] # Note: # Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. # Could you do it in-place ...
# Count the number of prime numbers less than a non-negative number, n. # # Example: # # Input: 10 # Output: 4 # Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. # ------------------------------------------------------------------------- class Solution(object): def countPrimes(...
# https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58953/AC-Python-solution-using-defaultdict from collections import defaultdict class TrieNode(object): def __init__(self): self.children = defaultdict(TrieNode) # Easy to insert new node. self.isword = False # True for the e...
import collections class Solution(): # Accepted LC Solution def canPlaceFlowers_LC605(self, flowerbed, n): # All TC passes on LC. Accepted count = 0 flowerbed = [0] + flowerbed + [0] for i in range(1, len(flowerbed)-1): if flowerbed[i-1] == flowerbed[i] == flower...
# There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i]. # # Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules: # # Every worker in the paid group should be paid in the ratio ...
# You are given two non-empty linked lists representing two non-negative # integers. The most significant digit comes first and each of their nodes # contain a single digit. Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, except the # number...
# In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.) # # Now, we may change 0s to 1s so as to connect the two islands together to form 1 island. # # Return the smallest number of 0s that must be flipped. (It is guaranteed th...
from heapq import * from collections import Counter class Solution: # This is good solution, but in interview counter might not be accepted. def frequencySort(self, s): """ :type s: str :rtype: str """ chars = Counter(s) #print chars.items() ...
#Iterate through each of the cell and if it is an island, # do dfs to mark all adjacent islands, then increase the counter by 1. class Solution(): def numIslands(self, grid): if not grid: return 0 count = 0 for i in range(len(grid)): for j in range(len...
# Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous # subarray of which the sum ≥ s. If there is not one, return 0 instead. # # Example: # # Input: s = 7, nums = [2,3,1,2,4,3] # Output: 2 # Explanation: the subarray [4,3] has the minimal length under the pr...
class Solution(object): def addBinary(self, a, b): return bin(int(a,2)+int(b,2))[2:] # #convert int to binary string, Eg : bin(5)->'0b101' # https://leetcode.com/problems/add-binary/discuss/24622/Python-solution-bit-manipulation-(58-ms-not-the-best-though) def addBinary1(self, a, b): ...
# Given a sorted array and a target value, return the index if the target is found. If not, return # the index where it would be if it were inserted in order. # You may assume no duplicates in the array. # # Example 1: # # Input: [1,3,5,6], 5 # Output: 2 # # Example 2: # # Input: [1,3,5,6], 2 # Output...
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/139503/Python-solution-using-2-pointers-to-shrink-the-range # https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51249/Python-different-solutions-(two-pointer-dictionary-binary-search). class Solution(): # two-po...
# Given a non-negative index k where k <= 33, return the kth index row of the # Pascal 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 only O(k) extra space?
# Given an array of integers and an integer k, you need to find the total # number of continuous subarrays whose sum equals to k. # Example 1: # Input:nums = [1,1,1], k = 2 # Output: 2 import collections from collections import defaultdict class Solution(): # My Solution Brute-force def Total_Sub...
# Given a binary tree, return all duplicate subtrees. For each kind of duplicate # subtrees, you only need to return the root node of any one of them. # Two trees are duplicate if they have the same structure with same node values. # # Example 1: # # 1 # / \ # 2 3 # / / \ # ...
# Must See this KMP algorithm video for pattern search: # https://www.youtube.com/watch?v=GTJr8OvyEVQ # His equivalent Java code: https://github.com/mission-peace/interview/blob/master/src/com/interview/string/SubstringSearch.java class Solution(object): # My code based on understanding of Tushar Roy's video and...
# Given a string, your task is to count how many palindromic substrings in this string. # The substrings with different start indexes or end indexes are counted as different # substrings even they consist of same characters. # # Example 1: Input: "abc" ,Output: 3 # Explanation: Three palindromic strings: "a", "b...
# Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle # containing only 1's and return its area. # # Example: # # Input: # [ # ["1","0","1","0","0"], # ["1","0","1","1","1"], # ["1","1","1","1","1"], # ["1","0","0","1","0"] # ] # Output: 6 # ----------------------------...
# Given a pattern and a string str, find if str follows the same pattern. # # Here follow means a full match, such that there is a bijection between # a letter in pattern and a non-empty word in str. # # Example 1: # # Input: pattern = "abba", str = "dog cat cat dog" # Output: true # # Example 2: # # Inpu...
# Given a 2D binary matrix filled with 0's and 1's, find the largest square # containing only 1's and return its area. # # Example: # Input: # # 1 0 1 0 0 # 1 0 1 1 1 # 1 1 1 1 1 # 1 0 0 1 0 # # Output: 4 # Similar Problem: [85. Maximal Rectangle] # -----------------------------------------------------...
# You need to find the largest value in each row of a binary tree. # # Example: # # Input: # # 1 # / \ # 3 2 # / \ \ # 5 3 9 # # Output: [1, 3, 9] # ====================================================================== # Definition for a binary tree nod...
# Given a non-empty string s and a dictionary wordDict containing a list of # non-empty words, determine if s can be segmented into a space-separated sequence # of one or more dictionary words. # Note: # The same word in the dictionary may be reused multiple times in the segmentation. # You may assum...
# Input: # Tree 1 Tree 2 # 1 2 # / \ / \ # 3 2 1 3 # / \ \ # 5 4 7 # Output: # Merged tree: # 3 # / \ # ...
# https://www.programiz.com/python-programming/methods/built-in # https://www.programiz.com/python-programming/examples/ascii-character # Python abs() returns absolute value of a number # Python all() returns true when all elements in iterable is true # Python any() Checks if any Element of an Iterable is Tr...
# Python program to for tree traversals # https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ # https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/ # A class that represents an individual node in a # Binary Tree class TreeNode: def __init__(self, key): self.left = No...
# Given a 2D integer matrix M representing the gray scale of an image, you need to design # a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) # of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, # then use as many as you can. # Exa...
# Tags: Strings, Hash Table, FB, AWS, Uber # Given an array of strings, group anagrams together. # Note: An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, # typically using all the original letters exactly once. for example, the word binary can be rearranged into "b...
import sys import math class Point: def __init__(self, x, y, z): self.p = (x, y, z) def __str__(self): return '({0},{1},{2})'.format(self.p[0],self.p[1],self.p[2]) def __getitem__(self, i): return self.p[i] def __add__(self, p): return Point(self.p[0] + p.p[0], self.p...
# print hello world print("Hello, World!") # declare a variable name = "Sara" # print a variable print(name) # String concatenation print("Hello, " + name ) # `Hello ${name}` print(f'Hello {name}') ### Data Structures # List (In python, they are called lists, not arrays) p = [10, 60, 20, 5, "Banana"] print(p) # ...
#!/usr/bin/env python3 """[Module]""" import bcrypt from db import DB from user import User def _hash_password(password: str) -> bytes: """[summary] Args: password (str): [description] Returns: bytes: [description] """ return bcrypt.hashpw(str.encode(password), bcrypt.gensalt()) ...
#!/usr/bin/env python3 """[a simple module containing an asynchrounous coroutine]""" import asyncio import random async def wait_random(max_delay: int = 10) -> float: """[an asynchronous coroutine that takes in an integer argument (max_delay, with a default value of 10) named wait_random that waits for a ...
#!/usr/bin/env python3 """[simple module that contains a method]""" def to_str(n: float) -> str: """[takes a float n as argument and returns the string representation of the float.] Args: n (float): [a float number] Returns: str: [the string representation of n] """ return st...
# Assignment Two. A program capable of guessing your animal # Author: Nikolaus Ricker # ------------------------------------------------------ # Functions def yes_no(ans_): if ans_ == ('n' or 'N' or 'no' or 'No' or 'NO'): return False if ans_ == ('y' or 'Y' or 'yes' or 'Yes' or 'YES'): return T...
import sqlite3 from sqlite3 import Error def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_user(conn, user): sql = ''' INSERT INTO users(name,sender_id,emp_id) V...
import random from math import sqrt import matplotlib.pyplot as plt def weighted_choice(weights): ''' Chooses an element with probabilty given by its weight on a total of weights. Uses the "roulette method". Info at http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python''' ...
#!/usr/bin/env python3 """ https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/ Given a starting number, play the game of threes, printing your steps. For every number, add 0, 1, or -1 to make it divisble by 3, then divide by 3. Continue until you reach 1. """ def ga...
# Create the text search function - Felicia import pandas.io.sql as sqlio import pandas as pd import psycopg2 import mysql.connector import re def text_search(): #Start connection with database with open ('db_login.txt', 'r') as myfile: data = myfile.read() conn = psycopg2.connect(data...
# # @lc app=leetcode.cn id=116 lang=python3 # # [116] 填充每个节点的下一个右侧节点指针 # # https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/description/ # # algorithms # Medium (69.46%) # Likes: 461 # Dislikes: 0 # Total Accepted: 117.7K # Total Submissions: 169.4K # Testcase Example: '[1,2,3,4,5,6,7...
# # @lc app=leetcode.cn id=151 lang=python3 # # [151] 翻转字符串里的单词 # # https://leetcode-cn.com/problems/reverse-words-in-a-string/description/ # # algorithms # Medium (47.77%) # Likes: 361 # Dislikes: 0 # Total Accepted: 162.1K # Total Submissions: 337.3K # Testcase Example: '"the sky is blue"' # # 给你一个字符串 s ,逐个翻转字...
# # @lc app=leetcode.cn id=451 lang=python3 # # [451] 根据字符出现频率排序 # # https://leetcode-cn.com/problems/sort-characters-by-frequency/description/ # # algorithms # Medium (67.58%) # Likes: 312 # Dislikes: 0 # Total Accepted: 69.8K # Total Submissions: 98.9K # Testcase Example: '"tree"' # # 给定一个字符串,请将字符串里的字符按照出现的频率降...
# # @lc app=leetcode.cn id=2133 lang=python3 # # [2133] 检查是否每一行每一列都包含全部整数 # # https://leetcode-cn.com/problems/check-if-every-row-and-column-contains-all-numbers/description/ # # algorithms # Easy (56.64%) # Likes: 6 # Dislikes: 0 # Total Accepted: 6.3K # Total Submissions: 11.1K # Testcase Example: '[[1,2,3],[3...
# # @lc app=leetcode.cn id=508 lang=python3 # # [508] 出现次数最多的子树元素和 # # https://leetcode-cn.com/problems/most-frequent-subtree-sum/description/ # # algorithms # Medium (66.65%) # Likes: 109 # Dislikes: 0 # Total Accepted: 12.4K # Total Submissions: 18.6K # Testcase Example: '[5,2,-3]' # # 给你一个二叉树的根结点,请你找出出现次数最多的子...
# # @lc app=leetcode.cn id=54 lang=python3 # # [54] 螺旋矩阵 # # https://leetcode-cn.com/problems/spiral-matrix/description/ # # algorithms # Medium (38.08%) # Likes: 288 # Dislikes: 0 # Total Accepted: 38.2K # Total Submissions: 99.6K # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' # # 给定一个包含 m x n 个元素的矩阵(m 行, n 列)...
# https://leetcode-cn.com/problems/a-number-after-a-double-reversal/ # int的空就为0 # 小技巧:怎么判定小数点后面是否全为零,那就是数字本身-int(数字本身) class Solution: def isSameAfterReversals(self, num: int) -> bool: if num == 0 or num % 10 != 0: return True return False
import time import threading import random start_vent_thread_event = threading.Event() open_vent_event = threading.Event() close_vent_event = threading.Event() ##threads work by starting them. They dont really stop. You can create ##an event to start and stop by using set/clear/wait. set turns wait to true ##clear tur...
def avg(a, b): return x def x(v,y,z): a = 3 b = 1 c = (v * (y-z)) * (a - b)/2.0000 return abs(c * 1.000) def avge(a, b): return c def c(x, y): if x > y: print "The area of above equ: is", 22 else: print "The area of above equ: is not...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 11 16:23:56 2019 Application of iris dataset to logistic regression class (my_logistic_reg) @author: bkearney """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets import random from sklearn.linear_model import Logis...
from Submenu import Submenu class Menu(Submenu): """" Composite (Menu in our case) class Contains 'constructor', add method, remove method and print method """ def __init__(self, name): """" Init method for a new composite/Menu object Input parameter: the name of new class...
from utils.python.predef import * class Solution: def distinctNames(self, ideas: List[str]) -> int: mp = defaultdict(set) for i in ideas: mp[i[0]].add(i[1:]) return sum(len(sa - sb) * len(sb - sa) for sa, sb in itertools.combinations(mp.values(), 2)) * 2 if __name__ == '__mai...
from utils.python.predef import * class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: ans = [] for k, trim in queries: cur = [int(i[-trim:]) for i in nums] ans.append(sorted((cur[i], i) for i in range(len(cur)))[k - 1][1...
from utils.python.predef import * class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: counter = Counter(barcodes) barcodes.sort(key=lambda x: (-counter[x], x)) sp = len(barcodes) // 2 if len(barcodes) % 2 == 0 else len(barcodes) // 2 + 1 a, b = barcodes[:...
from utils.python.predef import * class Solution: def countQuadruplets(self, nums: List[int]) -> int: from sortedcontainers import SortedList n = len(nums) ans = 0 left = SortedList([nums[0]]) for j in range(1, n - 2): right = 1 if nums[n - 1] > nums[j] else 0 ...
from utils.python.predef import * class Solution: def largestPalindromic(self, num: str) -> str: counter = Counter(num) max_single = chr(0) ans = [] for i in reversed(string.digits): if i not in counter: continue cnt = counter[i] ...
from utils.python.predef import * class Solution: def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: dis = 0 while mainTank > 0: use = min(mainTank, 5) dis += use * 10 mainTank -= use if use == 5 and additionalTank > 0: ...
from utils.python.predef import * class Solution: def check(self, s): i, j = 0, len(s) - 1 while i < j: if s[i] != s[j]: return False i, j = i + 1, j - 1 return True def maxPalindromes(self, s: str, k: int) -> int: ans = 0 i = 0 ...
from utils.python.predef import * class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: counter = [0] * 5 for c in croakOfFrogs: c = 'croak'.index(c) if c == 0: if counter[4]: counter[4] -= 1 counter[0] += ...
from utils.python.predef import * class Solution: def minimumSum(self, n: int, k: int) -> int: ls = set() cur = 1 while len(ls) < n: if k - cur not in ls: ls.add(cur) cur += 1 return sum(ls) if __name__ == '__main__': print(Solution().m...
#!/usr/bin/env python3 # https://stackoverflow.com/questions/11313852/split-one-file-into-multiple-files-based-on-delimiter import os import sys import argparse # global settings start_delimiter = '- id:' end_delimiter = '' comment_delimiter = "#" # parse command line arguments parser = argparse.ArgumentParser() pars...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Description --------- Python3 code of simulated annealing algorithm. This algorithm is to get the argmin of any target function on any domain. We call the domain the space of "state" where "state" represents any abstract class. C.f. `../doc/simulated_annealing.tm`. ""...
import random import string def generate(): my_word = string.printable word_length =int(input("Enter size of password: ")) if (word_length < 8): print("This size of password will be weak!") generate() else: p = "".join(random.sample(my_word,word_length)) print(p) genera...
''' Created on 15/01/2013 @author: jaaby_000 ''' myfile = open("c:/Datalog3.txt", encoding="utf-8") myfile.readline() numberoflines = sum(1 for line in myfile) print(numberoflines)
import unittest #Importing the unittest module from locker import User, Credential # Importing the user and credential class class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviours. ''' def setUp(self): ''' set up method to run before e...
#!/usr/bin/env python # -*- coding: utf-8 -*- import string import uuid def base62_encode(n): alphabet = string.digits + string.ascii_letters ret = '' while n > 0: ret = alphabet[n % 62] + ret n //= 62 * 128 return ret def url62(): """ uuid2url62 prevent uuid in URL enco...
import math from collections import defaultdict sqrt_3_2 = round(math.sqrt(3) / 2, 3) half = 1.0 / 2 def convert(str): x = 0 y = 0 i = 0 while i < len(str): if str[i] == 'e': x += 1 i += 1 elif str[i] == 'w': x -= 1 i += 1 elif s...
import re from collections import defaultdict def read_input(filename): passports = [] with open(filename) as f: lines = f.readlines() passport = defaultdict(str) for line in lines: fields = line.split() if fields: for field in fields: ...
def read(filename): with open(filename) as f: rules = {} is_your_ticket = False is_nearby_ticket = False your_ticket = [] nearby_tickets = [] for line in f.readlines(): if 'or' in line: # class: 1-3 or 5-7 a = line.split(":"...
''' POLYMORPHISM -The ability to take or have various forms -Ex: The functionality of smarphone: Phone, Messaging, Camera, Mp3 player -Ex: Word "watch" can be "Verb" or "Noun" -Polymorphism allows us to define methods in child class with some name as methods in parent class, but doing di...
### Game of nuts ### ### Name: Thai Doan import random def main(): ### Variables ### min_nuts = 10 #Minimum number of nuts max_nuts = 100 #Maximum number of nuts min_take_nuts = 1 #Minimum number of nuts to take max_take_nuts = 3 #Maximum number of nuts to take intro_line = "Welcome ...
# Authors: # Max Llewellyn # Caroline Sullivan class CPU: """This class represents the CPU. It holds a process and will feed it to the IOSubsystem when it's done.""" def __init__(self, scheduling_algorithm, context_switch_time, round_robin_time_slice): self.current_proc = None self.ctx_swi...
# z=int(input("enter the charactor")) # i=1 # while i<=z: # a=1 # while a<=i: # print(chr(64+i),end=" ") # a=a+1 # print() # i=i+1 # n=int(input("enter the number")) # i=1 # while i<=n: # a=1 # while a<=i: # print(chr(64+a),end=" ") # a=a+1 # print() # i...
# *** guessing game *** # a=int(input("enter the number")) # i=1 # while i<=a: # if i==5: # print("is equal",i) # else: # print("it's not equal",i) # i=i+1 # *** guessing game *** # num=5 # guess=int(input("enter the number 1 to 10:-")) # while guess!=num: # print("your guess is incor...
# i=1 # g=0 # while i<=5: # guess=int(input("enter the number")) # if i<5: # print("try again,its low") # elif i>5: # print("try again, its high") # elif i==5: # print("congrats you have winer") # i=i+1 i=1 a=10 while i<=5: num=int(input("enter the number")) if ...
a=0 while a<6: b=0 while b<7: if (a==0 and b%3!=0) or (a==1 and b%3==0) or (a-b==2) or (a+b==8): print("*",end=" ") else: print(" ",end=" ") b=b+1 print() a=a+1
#布雷部分 import random def lay_mines(level,map1): if level == '低': a = 0 while a<10: x = random.randint(0,9) y = random.randint(0,9) map1[x][y] = '9' print('布雷功能运行正常') a = 0 for i in range(10): for j in range(10): if map1[i][j] == '9': a += 1 print(a) elif level == '中': a =...
#we can't perform array opeartions using normal array so we have to use NUMPY for doing operations from numpy import * """ 1) arr= array([1,2,5,6,8,9]) arr = arr + 1 print(arr) 2) a1 = array([1,2,5,6,8,9],int) # Syntax of array used in Numpy here type defined at last type is optional #arr = array('i',[...
"""1.Write a program which accept number from user and return the count of even digits. Input: 2395 Output: 1 Input: 1018 Output: 2 Input: -1018 Output: 2 Input: 8462 Output: 4 """ def checkEVEN(no): cnt = 0 while no != 0: r = int(no % 10) if int(r % 2) == 0: cnt += 1 ...
a,M=(int(input()),input().split()) c,N=(int(input()),input().split()) x=set(M) y=set(N) one = x.difference(y) two = y.difference(x) res = one.union(two) print ('\n'.join(sorted(res, key=int))) """ input: 4 2 4 5 9 4 2 4 11 12 output: 5 9 11 12 TASK: The term symmetric difference indicates those values that exist in...
"""Pattern Print Reverse **** *** ** * """ """---------------Using While------------------------ i=1 while i<=4 : j=4 while j>=i: print("*",end="") j-=1 print() i+=1 """ #--------------------Using For------------------------ for i in range(5): for j in range(5-i):...
"""1.Write a program which accept range from user and display all numbers in between that range. Input : 23 35 Output : 23 24 25 26 27 28 29 30 31 32 33 34 35 def checkrange(start,end): if start>end: print("Invalid range") for i in range(start,end+1): print(i," ",end="") start = int(i...
"""1. Accept number of rows and number of columns from user and display below pattern. Input : iRow = 4 iCol = 4 Output : 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 class ass16: def prog1(self,row,col): count=1 for i in range(row): for j in range(col): pri...
pos = -1 def LinearSearch(vals,valToSearch): for i in range(len(vals)): if vals[i] == valToSearch: globals() ['pos'] = i return True; else: return False; vals = [10,5,2,6,8,1] valToSearch = int(input("enter the no to be searched within list")) if LinearSearch(...
#All operations between complex numbers can be put in this file. class ComplexNumber: def add(self, number): return ComplexNumber(self.realValue + number.realValue, self.imaginaryValue + number.imaginaryValue) def getInverse(self): return ComplexNumber(-self.realValue, -self.imaginaryValue...
#!/usr/bin/env python #-*-coding:utf-8-*- import os,sys def de_bruijn_ize(st, k): """ generate the edges and nodes of the k-mer de_bruijn graph of string """ nodes = set() edges = [] for i in range(len(st)-k+1): edges.append( (st[i:i+k-1],st[i+1:i+k]) ) nodes.add(st[i:i+k-1]) n...
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given an array of integers where each element represents the max number of steps that can be made forward from that element. The task is to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cann...