text
stringlengths
37
1.41M
# ============================ # Lowest Common Ancestor in BST # ============================ from BST import * def findResult (root,a,b): if root.value > a and root.value < b: return root elif root.value <a and root.value < b: findResult(root.right,a,b) elif root.value >a and root.value > ...
from BST import * def findMin(root): ''' Iterates to left most node and returns it's value! ''' if root is not None: tmp = root while(tmp.left!=None): tmp= tmp.left return tmp.value def findMax(root): ''' Iterates to right most node and returns it's ...
x=int(input("enter x")) y=int(input("enter y")) if(x>y): print("x",x,"is greater than y",y) else: print("y",y,"is greater than x",y)
class User: def __init__(self, username, password, is_admin): self.__username = username self.__password = hash(password) self.__is_admin = is_admin self.__roles = set() def check_password(self, password): return self.__password == hash(password) def add_role(self...
from datatracker import * class DataPrinter(): '''Prints a DataTracker's data. Takes a structure containing strings representing data from a DataTracker (specificaly, the output of DataTracker.get_strings()) and produces a readable string output. ''' def __init__(self, name, strings, line_width=60): ...
import concurrent.futures import time start = time.perf_counter() def do_something(seconds): print(f'Sleeping {seconds} seconds(s)...\n') time.sleep(seconds) return 'Done Sleeping...'+str(seconds) #Using concurrent.futures I can create a pool of threads with concurrent.futures.ThreadPoolExecutor() as exec...
def ispalindrome(word): #Eliminates spaces wordNoBlanks='' for letter in word: if letter == ' ': continue wordNoBlanks+=letter #Reverse Word wordlist=list(wordNoBlanks) wordlist.reverse() word2="".join(wordlist) #Compare words if wordNoBlanks==...
#! /usr/bin/env python def generate(arr, i, s, length,filename): if (i == 0): f = open(filename + ".txt", "a") f.write(s+"\n") f.close() return for j in range(0, length): appended = s + arr[j] generate(arr, i - 1, appended, length,filename) return def Range(...
class Table(object): # t = Table(1,2,3) # vars(t) def __init__(self, l, w, h): print "Init" self.l = l self.w = w self.h = h # Static variable # class A(object): # a = 1 # # def __init__(self): # A.a += 1 # print A.a # # def f(self): # ...
"""Implementation of Binary Search Tree.""" from collections import deque import random import time import io class Node(object): """Binary Search Tree.""" def __init__(self, val=None, left=None, right=None, parent=None): """Initialize BST.""" self.val = val self.left = left s...
# -*- coding: utf-8 -*- """Module to test parenthetics of string input.""" import sys def parenthetics(input_str): """Method to test for unmatched parenthesis.""" counter = 0 for i in input_str: if i is ')': counter -= 1 elif i is '(': counter += 1 if count...
# _*_ coding:utf-8 _*_ """A module to create a queue data structure.""" from Node import Node class Queue(object): """Queue data structure object creator.""" def __init__(self, head=None, tail=None): """Queue object constructor.""" self.head = head self.tail = tail self.lengt...
# -*- coding: utf-8 -*- """ Created on Fri Nov 29 18:15:34 2019 @author: CEC """ def isPrime(num): if num <= 1: return False for i in range (2,num): print(num, i, num%i) if (num%i == 0): return False return True while True: x = input("Ingrese un núme...
def bigger(a,b): if a>b: return a else: return b def biggest(a,b,c): return bigger(a,b,c) def median:(a,b,c): big - biggest(a,b,c) if big == a: return bigger(b,c) if big == b: return bigger(a,c) else: return bigger(a,b) def lesser(a,b): if a<b: ...
# coding: utf-8 # 一.已经字符串 # s = "i,am,lilei", 请用两种办法取出之间的“am”字符。 s = "i,am,lilei" print s.split(',')[1] print s[2:4] # # 二.在python中,如何修改字符串? # # 三.bool("2012" == 2012) # 的结果是什么。False print bool("2012" == 2012) # # 四.已知一个文件 # test.txt,内容如下: # # ____________ # 2012 # 来了。 # 2012 # 不是世界末日。 # 2012 # 欢乐多。 # _____________...
# coding: utf-8 # Author: lee_zix def test(): for i in range(4): print 'test1: %d' % i yield i print 'test: %d' % i def fblq_num(num): """斐波拉切数列""" ls = [0, 1] result = ls[-1] + ls[-2] while num >= result: ls.append(result) result = ls[-1] + ls[-2] ...
# coding: utf-8 # Author: lee_zix import types # 今天习题: # # 1 定义一个方法get_fundoc(func),func参数为任意一个函数对象,返回该函数对象的描述文档,如果该函数没有描述文档,则返回"not found" def get_fundoc(func): if isinstance(func, types.FunctionType): desc = func.__doc__ if isinstance(desc, types.NoneType) or len(desc) == 0: return 'n...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: xxx def main(): tup = (1,2,3,4) #取值 print tup[2]#记得这里要打中括号[],和列表一样下标从0开始,不能同时取两个0,1,想要同时取多个值只能用切片 # 切片 print tup[0:1]#切片左边是闭区间,右边是开区间,即右边的实际取值会比写出来的下标少一位 print tup[2:]#右边什么都不写,默认取到最后一位 print tup[:3]#左边什么都不写,默认从第一位开始数 # 是否存在某值 print (1 in tup) #存在,...
import matplotlib.pylab as plot import numpy as np n=np.linspace(0,199,200) ; y=np.linspace(0,199,200) x=eval((input("Write an equation for x(n):"))) i=0 while i in range(0,200): if i==199: y[i]=(1.5*x[i])-(2*x[i-1])+(0.5*x[i-2]) elif i==0: y[i]=(-1.5*x[i])+(2*x[i+1])-(0.5*x[i+...
""" This program uses the trained keras model to predict images and visualize the output of intermediate layers. Use the following command to execute the code python train.py """ import numpy as np import os, glob, cv2 import tensorflow as tf import tensorflow.keras from tensorflow.keras.models import Sequential, lo...
n = int(input("Enter the nth term")) f = [] a = 0 b = 1 f.append(a) f.append(b) for i in range(2,n): c = a + b f.append(c) a = b b = c print("The nth term is:",f[n-1])
import unittest class TestCalculadora(unittest.TestCase): def setUp(self): self.cal = Calculadora() def test_sumar_2_mas_2(self): resultado = self.cal.suma(2, 2) self.assertEqual(4, resultado) def test_sumar_3_mas_3(self): resultado = self.cal.suma(3, 3) self.a...
if __name__ == '__main__': x = [1, 2, 3]; y = [1, 2, 3]; #创建一个没有重复元素当tuple print([(xx, yy) for xx in x for yy in y if xx != yy]) # expected output: # [{'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}, # {'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'}, # {'name': 'nanc...
for a in 'MHMSM': print('hello') # بعد از فور ها می توان از esle استفاده کرد b=[1,2,8,56,100] for c in b: print(c) else: print('adad tamom shod ') #break شکستن حلقه #continue ادامه می دهد #pass for c in 'string': if(c=='i'): continue#با درسیدن به این جا این قمست فور را انجام نمی ده...
def run(): my_list = [1, 'Hi', True, 4.5] my_dicc = { "firstname": "abraham", "lastname": "garcia", "age": 22, } super_list = [ { "firstname": "abraham", "lastname": "garcia", "age": 22, }, { "firstna...
#GuessTheWord.py #Karl Pearson #10/27/2014 import random print("Welcome to Guess the Word: Legend of Zelda Edition") print("You will have 5 tries to guess the word") tries=7 WORDS=("Link","Hyrule","Zelda","Epona","Ocarina","Triforce") count=1 answer=random.choice(WORDS) print("The word has", len(answer),"letters in...
numero = input('Digite um número: ') if numero.isdigit(): numero = int(numero) if numero % 2 == 0: print('Número par') elif numero % 2 != 0: print('Numero ímpar') else: print('Isso não é um número inteiro')
#Tensorflow course #Chapter 1 #Q1 import constant from TensorFlow from tensorflow import constant # Convert the credit_numpy array into a tensorflow constant credit_constant = constant(credit_numpy) # Print constant datatype print('\n The datatype is:', credit_constant.dtype) # Print constant shape print('\n The ...
student_score = int(input()) maximum_score = int(input()) score_percentage = (student_score / maximum_score) * 100 if score_percentage < 60: print('F') elif score_percentage < 70: print('D') elif score_percentage < 80: print('C') elif score_percentage < 90: print('B') else: print('A')
from xml.dom.minidom import parse, parseString import os class NotTextNodeError: pass def getTextFromNode(node): """ scans through all children of node and gathers the text. if node has non-text child-nodes, then NotTextNodeError is raised. """ t = "" for n in node.childNodes: ...
l1 = [1, 'Two', 3.00, True, False] l2 = ['a', 'x', 'l', 'b', 'n','a'] print(l1) print(l2.count('a')) print(len(l1)) print(l1[1:]) l1.append('FOUR') print(l1) print(l1.pop()) # pops last element in the list and prints it. Here by default the index is -1. print(l1) l1.pop(2) # pops at index 1 permamently... l2.sort() ...
d1 = {'k1': 'Val1', "key2": 200} print(d1) print(d1["key2"]) # Note that key is always a string # NESTED DICTIONARIES d2 = {'k1': 105, 'k2': [105, 106, 109], 'k3': {'innerkey': 1000},'k4':['a','b','c','d']} print(d2) print(d2['k2']) print(d2['k2'][2]) # prints element at 2nd index of the list at key= k2..ALSO .upper...
d =dict(a=1,b=2,c=3) for k in d.keys(): print(d[k], end=" ") print() for v in d.values(): print(v,end=" ") print() for kv in d.items(): print(kv, end=" ") print() for k, v in d.items(): print(k, v) vo = d.items() for kv in vo: print(vo,end=" ") for k, v in vo: d[k] += 2 print() for k, v ...
class Account: def __init__(self, aid, abl): self.aid = aid self.abl = abl def __add__(self, m): self.abl += m print("__add__") def __iadd__(self, m): self.abl += m print("__iadd__") return self def __sub__(self, m): self.abl -= m p...
class Person: def __init__(self, n, a): self._name = n self._age =a def __str__(self): return "{0}:{1}".format(self._name, self._age) def add_age(self, a): if(a<0): print("나이 정보 오류") else: self._age += a p = Person("Kavin", 22) p.len =178 p.ad...
from collections import namedtuple Tri = namedtuple("Tiangle", ["bottom","height"]) t = Tri(3,7) print(t[0], t[1]) print(t.bottom, t.height) def show(n1, n2): print(n1, n2) t = Tri(3,8) show(*t)
# class Course: # """asd""" # def __init__(self, code, name, points): # """asd""" # self.code = code # self.name = name # self.points = points # def to_dictionary(self): # """asd""" # result ={'code': self.code, 'name': self.name, 'points': self.points} # ...
"""Demonstrate event binding and variable tracing, this time with a clean OO design. """ from tkinter import * from tkinter.ttk import * class GreetingGui: """The GUI class""" def __init__(self, window): """Setup the label and button on given window""" self.click_count=0 self.he...
# Program to add two matrices using nested loop X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[...
"""File for creating Person objects""" class Person: """Defines a Person class, suitable for use in a hospital context. Data attributes: name of type str age of type int weight (kg) of type float height (metres) of type float Methods: bmi() ...
print("fera") v= area() print v def area(b,h): a=1/2*b*h print(a) #pandas Machine Learning SMP Numpy Assignment Questions Assignment I 1. 2. 3. 4. 5. Extract the integer part of a random array using 5 different methods 6. Write a Python program to check two random arrays are equal or not. 7. ​ Write a Python p...
# # @lc app=leetcode.cn id=20 lang=python # # [20] 有效的括号 # class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for i in s: if len(stack) == 0: stack.append(i) continue ...
#Del Castillo, Mary Abigail V. #2014-23666 #Galois Field Calculator def pad_poly(poly,len_a,len_b): pad = len_a - len_b for x in range(pad): poly.insert(0,0) return poly def pad_poly_str(poly,len_a,len_b): pad = len_a - len_b for x in range(pad): poly.insert(0," ") return poly def del_zeroes(a): new_a=a ...
import logging from Heap import BinaryHeap import Random import sys def Djikstra(G, v1, v2=None): """ Single Source shortest path Implement the Djikstras algorithm starting from node v1 Return the edges """ minNodes = BinaryHeap() minNodes.add(0, v1) for key in G.vertices.keys(): ...
# Implement a mathod to perform basic string compression using the counts # of repeated characters. For example, the string aabccccaaa would become # a2b1c5a3. If the 'compressed' string would not become smaller than the # original string, your method should return the original string. You can assume # the string has ...
# Declaring tuple tup = (2, 4, 6, 8) # Displaying value print(tup) # Displaying Single value print(tup[2]) # Updating by assigning new value # tup[2] = 22 # Displaying Single value # print(tup[2]) # Traceback (most recent call last): # File "C:/Users/DattatrayaTembare/PycharmProjects/python-examples/src/python_basi...
import os print(f"{'*' * 10}Execute the command in a subshell{'*' * 10}") for i in range(2, 6): input_string = "python --version " + str(i) os.system(input_string) print(f"{'*' * 10}Execute the command in a subshell{'*' * 10}") print(f"{'*' * 10}Use of format{'*' * 10}") name = "Datta" lname = "Tembare" greet...
def sort_array(my_list): """sort array or bubble array,""" for j in range(len(my_list) - 1): for i in range(len(my_list) - j - 1): if my_list[i] > my_list[i + 1]: # temp = my_list[i] # my_list[i] = my_list[i + 1] # my_list[i + 1] = temp ...
# PYTHON: 3.8.2 # AUTHOR: Alex Moffat # PURPOSE: Code Challenge # Requirement: You are given an array of positive numbers from 1 to n, such that all numbers from 1 to n are present except one number (x). You have to find x. The input array is not sorted. # ===============================================================...
import numpy as np from math import log from numba import jit from matplotlib import pyplot import time """ Here is a Numba accelerated implementation of the Gillespie's algorithm that simulates stochastic processes with an example of its use on the SIR epidemiology model. SIR is a model simulating how many ...
# coding: utf8 ''' 奇偶调序: 输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为O(n)。 ''' # 设置头尾两个指针, 分别从前往后和从后往前遍历数组, 当遇到头指针为偶数, 尾指针为奇数时交换它们 def odd_even_sort1(nums): n = len(nums) if n <= 1: return nums left, right = 0, n - 1 while left < right: while nums[left] & 1 == 1: ...
''' LintCode: http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array-ii/ 160. 寻找旋转排序数组中的最小值 II 假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。 你需要找到其中最小的元素。 数组中可能存在重复的元素。 样例: 给出[4,4,5,6,7,0,1,2] 返回 0 ''' # 跟 findMin I 类似 # 因为可能存在重复的元素,所以在判断 num[left] >= num[mid] 之后 # 需要判断 left - mi...
""" 4. Hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [...
""" 967. A binary tree is univalued if every node in the tree has the same value. Return true if and only if the given tree is univalued. Easy """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isUnivalTree(self, root):...
""" 946. Validate Stack Sequences Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack. Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We m...
""" """ from math import sqrt class Solution: """ @param n: a integer @return: return a 2D array """ def getFactors(self, n): def dfs(num, start): res = [] for f in range(start, int(num)+1): if f ** 2 > num: break ...
""" 739. Daily Temperatures Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatures T = [73, 74,...
""" 873. Length of Longest Fibonacci Subsequence Medium 1st: 2020-08-30 """ from typing import List from collections import defaultdict class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int: inds = {x:i for i, x in enumerate(A)} dp = defaultdict(lambda: 2) ans = ...
""" 841. Keys and Rooms 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 k...
""" 665. Non-decreasing Array Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify ...
""" 131. Palindrome Partitioning Medium Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] """ from collections import defaultdict class Solution: def p...
""" 572. Easy Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. Example 1: Given tree s: ...
""" 350. Easy Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result ...
""" 211. """ class TrieNode: def __init__(self): self.children = {} self.endofword = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word: str) -> None: """ Inse...
""" 20. Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid...
""" 852. Peak Index in a Mountain Array Easy Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is definitely a mountain, return any i such that A[0] < A[...
""" 501. Find Mode in Binary Search Tree Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtre...
""" 695. Max Area of Island Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no ...
""" 152. Medium Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, b...
""" 21. Merge Two Sorted Lists (Easy) Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ # Definition for singly-linked list. class ListNode: def __init__(se...
""" 220. medium Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3, t = 0 Output: true Example ...
""" 1425. Hard Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some...
""" 81. Search in Rotated Sorted Array II Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums =...
""" 1428. Medium 1425. Constrained Subsequence Sum 1358. Number of Substrings Containing All Three Characters 1248. Count Number of Nice Subarrays 1234. Replace the Substring for Balanced String 1004. Max Consecutive Ones III 930. Binary Subarrays With Sum 992. Subarrays with K Different Integers 904. Fruit Into Ba...
""" LC-460 Hard Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key...
""" 496 You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does n...
""" 973. K Closest Points to Origin Medium We have a list of points on the plane. Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean distance.) You may return the answer in any order. The answer is guaranteed to be unique (except for the order that ...
""" 282. Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Example 1: Input: num = "123", target = 6 Output: ["1+2+3", "1*2*3"] Example 2: Input: num = "232", target = 8 O...
""" 1286. Medium Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographical order. A function hasNext()...
#!/usr/bin/python3 import re def main(): with open("./input.txt", 'r') as file: sum = 0 for line in file: sum += int(line) print(sum) if __name__ == "__main__": main()
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 print("number of even numbers:",count_even) print("number of odd numbers:",count_odd) number of even numbers: 0 number of odd number...
# Creating a Sets. # Normal Set Declaration farm_animals = {"Cow", "Sheep", "Buffalo"} print(farm_animals) for animals in farm_animals: print(animals) print("*" * 80) # Set Constructor Method to Declare Sets wild_animals = set(["lion", "tiger", "panther", "Deer"]) # We can pass there tuple, tuple and range print(w...
locations = {0: "You are sitting in front of a computer learning Python", 1: "You are standing at the end of a road before a small brick building", 2: "You are at the top of a hill", 3: "You are inside a building, a well house for a small stream", 4: "You are in a val...
import tkinter from tkinter import * from tkinter import messagebox import tkinter.filedialog as tkabrir import os import math global n def regla_traprecio(h, n, f): return (h/2) * (f[n-1] + f[n]) def sim38(h, f0, f1, f2, f3): return (3/8) * h * (f0 + (3 * f1) + (3 * f2) + f3) def sim13mul(h, n, f): su...
from tkinter import * import tkinter import tkinter.filedialog as tkabrir from tkinter import messagebox import os import math global n def sim38(h, f0, f1, f2, f3): return (3/8) * h * (f0 + (3 * f1) + (3 * f2) + f3) def sim13mul(h, n, f): sum = f[0] for i in range(1, n-1, 2): sum = sum + (4 * ...
n = int(input("Enter the number")) s = 0 num = n while n > 0: s += n % 10 n //= 10 if num % s == 0: print('Harshad no.') else: print(" Not Harshad no.")
import hashlib import string s=input("Enter hash form") s.encode('utf-8') g=open(indian-passwords,'r') line = g.readline( ) wordlist = string.split(line) for word in wordlist: if hashlib.md5(word).digest()==s: print(word)
n = int(input("Enter rhe first no.")) num = int(input("Enter the second no.")) s1 = s2 = 0 for i in range(1, n // 2 + 1): if n % i == 0: s1 += i for i in range(1, num // 2 + 1): if num % i == 0: s2 += i if s1 == num and s2 == n: print("Amicable no.s") else: print("Not amicable no.s")
import math as m n = input("Enter the number") l = int(len(n)) n = int(n) s, num = 0, n while n > 0: s += int(m.pow(n % 10, l)) n //= 10 l = l - 1 if s == num: print("Disarium no.") else: print("Not disarium no.")
n = int(input()) a = list() for i in range(n): x = int(input()) a.append(x) a.sort(reverse=True) print(a.index(x)+1)
def binsearch(a, x, l, u): mid = (l + u) // 2 if l > u: return False if a[mid] == x: return True if x < a[mid]: return binsearch(a, x, l, mid - 1) else: return binsearch(a, x, mid + 1, u) a = list(map(int, input("Enter numbers :").split())) a.sort() x = int(input("E...
import sys class Node: def __init__(self, item, next): self.item = item self.next = next # Note, these are methods "A method is a function that is stored as a class attribute" class LinkedList: def __init__(self): self.head = None def add(self, item): self.head = Node(item...
class nim(): help_text = "Nim is a two player game where the players " \ "take turns removing elements from heaps, the " \ "player to play last loses" move_explanations = (("Which heap to take from?", int), ("How much to take?", int)) ply = 5 d...
import sys def main(rotval): try: rotval = int(rotval) % 26 except ValueError: print("ERROR: argument not an integer") return 1 if rotval < 0: print("ERROR: Please enter a non-negative integer") return 1 plaintext = input("plaintext: ") ciphertext = [] ...
a=input() b=input() l=list() if(len(a)!=len(b)): print(max(len(a),len(b))) elif(len(a)==len(b)): if(a!=b): print(max(len(a),len(b))) else: print("-1")
from collections import namedtuple Entry = namedtuple("Entry", ["chrom", "start", "end", "name", "qual", "strand"]) def pair_pair(first, second): assert first.chrom==second.chrom, (first, second) assert first.name[:-1]==second.name[:-1], (first, second) start = min(int(first.start), int(second.start)) ...
#The | character is called a pipe. You can use it anywhere you want to match one #of many expressions. import re heroRegex = re.compile(r'Batman|Tina Frey') #When both Batman and Tina Fey occur in the searched string, the first #occurrence of matching text will be returned as the Match object. heroName = heroRegex.s...
import model import tkinter as tk window = tk.Tk() import time window.geometry("1300x700") canvas = tk.Canvas(window, width=300, height=600, background="orange") zvet = [model.siniy] #цвет игрока def draw(): canvas.delete(tk.ALL) #рисует поле for i in range(10): for j in rang...
class Animal: def __init__(self,name,color,size,age): self.name=name self.color=color self.size=size self.age=age def print_all(self): print(self.name) print(self.color) print(self.size) print(self.age) def sleep(self): print(self.name, "is sleeping") def eat(self,food): print(self.name, "is ea...
def inside(x, a, b): if a == b: return True if a < b: if a < x and x <= b: return True else: return False else: if b < x and x <= a: return False else: return True def inside2(x, a, b, incl=True): if a == b: ...