text stringlengths 37 1.41M |
|---|
'''
*Question
Given Binary Search Tree, design an algorithm which creates a linkedlist of all nodes at each depth
'''
class llNode:
def __init__(self,item):
self.val = item
self.next= None
class bstNode:
def __init__(self,item):
self.val = item
self.left=None
self.right... |
'''
*Anagram: whether it is permutation to each other
Method1: Sort 2 strings and Compare
Method2: Use HashMap as data structure
*Extra Consideration
1) upper/lower case
2) space inbetween
3) space in each end side of string
* Python
1) str.lower() : string to lower case. no return
2) str.upper() : string to upper ca... |
# https://labs.spotify.com/2014/02/28/how-to-shuffle-songs/
# import sys
# import codecs
# sys.stdin= codecs.getreader("utf-8")
# # (sys.stdin.detach())
# sys.stdout = codecs.getwriter("utf-8")
# (sys.stdout.detach())
from random import randint
import random
def shuffle(songs, artists):
n = len(songs)
info =... |
'''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
1) The left subtree of a node contains only nodes with keys "less than" the node’s key.
2) The right subtree of a node contains only nodes with keys "greater than" the node’s key.
3) Both the left and rig... |
'''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is... |
'''
1) preorder traverse (vLR)
When use preorder?
: When there are multiple servers,
send tree structure of one certain server to another server in preorder.
2) inorder traverse(LvR)
Time complexity : O(n)
3) postorder traverse(LRv)
'''
class Node:
def __init__(self,item):
self.val = item
self.le... |
'''
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
In... |
'''
Given a non-empty array of integers, every element appears "twice" except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
class Solution... |
'''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
You need to do this in place.
Note that if you end up using an additional array, you will only receive partial score.
Example:
If the array is
[
[1, 2],
[3, 4]
]
Then the rotated array becomes:
[
[3, 1... |
nombre = 5
type(nombre) # <class 'init>
nombre1 = "Juan"
type(nombre1) # <class 'str'>
nombre2 = 5.2
type(nombre2) # <class 'float'>
mensaje = """Esto es un mensaje
con tres saltos
de linea """
print(mensaje)
numero3 = 5
numero4 = 7
if numero3>numero4:
print("el numero 3 es mayor")
else:
print("el n... |
midiccionario={"Alemania":"Berlin","Francia":"Paris","Reino Unido":"Londres","Mexico":"Ciudad de Mexico"} #"palabra":"significado"
midiccionario["Italia"]="Lisboa" #aniade un nuevo elemento al diccionario
print(midiccionario) #imprime todo el diccionario
print(midiccionario["Francia"]) #la funcion imprime lo que se... |
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = []
queue.append((root, root))
# queue = collections.deque([(root, root)])
while queue:
t1, t2 = queue.pop(0)
if not t1 and not t2:
continue
elif not t1 or not t2:
... |
from collections import deque
class Solution:
def maxAreaOfIsland(self, grid):
R, C = len(grid), len(grid[0])
size_max = 0
for i in range(R):
for j in range(C):
if grid[i][j] == 1:
print("find", i, j)
grid[i][j] = 0
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
# left_correct = (not root.left or root.val == root.left.val
# an... |
class Solution:
def maxDepth(self, root: 'Node') -> int:
queue = collections.deque()
if root:
queue.append((root, 1))
depth = 0
while queue:
root, curr_depth = queue.popleft()
if root:
depth = max(depth, curr_depth)
... |
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
height, width = len(matrix), len(matrix[0])
row = height - 1
col = 0
... |
from collections import deque
import collections
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findClosestLeaf(self, root: TreeNode, k: int) -> int:
graph = collections.... |
# 2-line Recursion. In most tree problems, try recursion first.
class Solution(object):
def maxDepth(self, root):
if not root: return 0
return 1 + max(map(self.maxDepth, root.children or [None]))
# BFS (use a queue, the last level we see will be the depth)
class Solution(object):
def maxDept... |
class RecentCounter(object):
def __init__(self):
self.q = collections.deque()
def ping(self, t):
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
"""
input
["RecentCounter","ping","ping","ping","ping"]
[[],[1],[100],[3001... |
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
return ''.join(self.nextSequence(n, ['1', 'E']))
def nextSequence(self, n, prevSeq):
if n == 1:
return prevSeq[:-1]
nextSeq = []
prevDigit = prevSeq[0]... |
class Solution:
def countSubstrings(self, S: str) -> int:
N = len(S)
ans = 0
for center in range(2*N - 1):
left = int(center / 2)
right = int(left + center % 2)
while left >= 0 and right < N and S[left] == S[right]:
ans += 1
... |
class Solution(object):
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
def count(word):
ans = [0]*3
for ch in word:
ans[ord(ch) - ord('x')] += 1
return ans
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
def dfs(no... |
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
M, N, p = len(grid), len(grid[0]), 0
for m in range(M):
for n in range(N):
if grid[m][n] == 1:
if m == 0 or grid[m-1][n] == 0: p += 1
if n == 0 or grid[m][... |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
dic = {}
for num in nums2:
while stack != [] and num > stack[-1]:
dic[stack.pop()] = num
stack.append(num)
res = []
for num in nu... |
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.is_sorted = False
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.nums.append(number)
... |
class Persona:
def __init__(self,nombre,apellidos,sexo,edad,altura,color_ojos,color_cabello):
self.nombre = nombre
self.apellidos = apellidos
self.sexo = sexo
self.edad = edad
self.altura = altura
self.color_ojos = color_ojos
self.color_cabello = color... |
"""
Finds the closest distance between a given location and the node locations found within data
Author: Henry Dikeman
Email: dikem003@umn.edu
Date: 07/15/21
"""
import math
def closest_distance(point, data):
min_dist = 1000
for i in data:
lon_dist = abs(point.lon - i.lon)
lat_dis... |
"""
Selection function for training/evaluation. When a specific model architecture is selected, it is passed into this function where the appropriate dataset is curated for further use
Author: Henry Dikeman
Email: dikem003@umn.edu
Date: 07/15/21
"""
from LSTM_GenFuncs import *
def trainerModelSelect(mod... |
import re
import unittest
# "Any word or phrase that exactly reproduces the letters in another order is an anagram." (Wikipedia).
# Add numbers to this definition to be more interest.
# The challenge is to write the function isAnagram
# to return True if the word test is an anagram of the word original and False if not... |
# Determine if the string has a uniqe characters
def uniqe_char2(s):
output = ''
for i in s:
if i in output:
return False
output += i
return True
def uniqe_char(s):
return len(s) == len(set(s))
print(uniqe_char('abcde'))
print(uniqe_char('aabcde'))
|
# https://www.codewars.com/kata/5629db57620258aa9d000014/train/python
# Given two strings s1 and s2, we want to visualize how different the two strings are.
# We will only take into account the lowercase letters (a to z).
# First let us count the frequency of each lowercase letters in s1 and s2.
# s1 = "A aaaa bb c", s... |
from collections import defaultdict
# The Trie itself containing the root node and insert/find functions
class Trie:
def __init__(self):
# Initialize this Trie (add a root node)
self.root = TrieNode()
def insert(self, word):
# Add a word to the Trie
node = self.root
fo... |
import operator
import unittest
# Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
#
# For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14.
#
# For your convenience, the input is formatted such that a... |
def path_finder(maze):
start = (0, 0)
maze_list = maze.split('\n')
target = len(maze_list)-1, len(maze_list[0])-1
# stack.append(start)
stack = add_or_replace([], start, 0)
explored = set()
# print(stack)
#
while len(stack):
# print('c')
# node = stack.pop(0)
... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
def quicksort(array, start, stop):
if stop - start > 0:
pivot, l... |
# Entries are (h, m) where h is the hour and m is the minute
sleep_times = [(24,13), (21,55), (23,20), (22,5), (24,23), (21,58), (24,3)]
def bubble_sort_2(l):
start = len(sleep_times) - 1
while start:
for time in range(1, len(sleep_times)):
prev_time, current_time = sleep_times[time-1], sle... |
# Solve the problem using simple recursion
def fib_rec(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib_rec(n-1) + fib_rec(n-2)
# print(fib_rec(10))
# Implement the function using dynamic programming to store results (memoization).
memo = {}
def fib_dyn(n):
if n ... |
class Node:
def __init__(self, value=None, key=None):
self.prev = None
self.next = None
self.key = key
self.value = value
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def push_head(self, node):
... |
import unittest
# Write a method that takes an array of consecutive (increasing) letters as
# input and that returns the missing letter in the array.
# You will always get an valid array.
# And it will be always exactly one letter be missing.
# The length of the array will always be at least 2.
# The array will always... |
import math
for reeks in range(11):
n = reeks
root5 = math.sqrt(5)
a = (1 + root5)**n
b = (1 - root5)**n
c = 2**n * root5
answer = int((a-b)/c)
print("When n is", reeks, "the Fibonacci number is:", answer)
print("Done :)") |
from queue import PriorityQueue
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
compnodeq= PriorityQueue()
for index, node in enumerate... |
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) == 0:
return -1
start = 0
end = len(nums) - 1
if target >= nums[0]: # target on the left
while start <= end:
mid = (start + end) // 2
... |
class Solution(object):
"""
https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/
"""
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left_max = {}
right_max = {}
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if TreeNode == None:
return True
line = []
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
res = head
reverseStack = []
i = 1
while i < m:
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
headnode = head
tailnode = head
prevnode = None
count = 1
wh... |
def remove_tail(self):
if not self.head:
return None
if self.head is self.tail:
value = self.head.get_value()
self.head = None
self.tail = None
return value
current = self.head
while current.get_next() is not self.tail:
current = current.get_next()
value = self.tail.get_value()
self.tail = current... |
print('Crie um programa que leia duas notas do aluno e mostre sua média e uma mensagem de acordo com a média\n'
'Média abaixo de 5.0: Reprovado'
'Média entre 5.0 e 6.9: Recuperação'
'Média 7.0 ou superior: Aprovado')
print('\033[33m *** Resolução do Exercicio *** \033[m')
nota1 = float(input('Inform... |
print('----- Bem vindo ao exercicio 63 ---')
print('Escreva um programa que leia um número n inteiro qualquer e mosstre na tela os n primeiros elementos de uam sequencia de fibonacci'
'exemplo: 0->1->1->2->3->5->8')
n = int(input('Informe a quantidade de termos que você quer mostrar'))
t1 = 0
t2 = 1
print('~'*3... |
print('\033[31m Bem vindo ao exercicio 56 \033[m')
print('Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: A média de idade do grupo, Qual é o nome do homem mais velho, Quantas mulheres tem menos de 20 anos')
media = 0
totalidade = 0
hvelho = 0
C=0
namevelho = ''
mulher... |
print('Bem vindo ao 53')
print('Crie um programa que leia uma frase qualquer e diga se ela é um palindromo')
# Palavra que é lida tanto na frente quanto atrás e dá igual
frase = str(input('Informe uma frase')).strip().upper()
palavras = frase.split() # Aqui ela divide todas as palavras
juntas = ''.join(palavras)
inv... |
print('\033[32m ** Bem vindo ao Exercicio 37 **')
print('\033[31m ** Escreva um programa que leia um número inteiro qualquer e peça para o usuario escolher qual será a base de conversão\n'
'1- para binário, 2- para octal, 3- para hexadecimal')
print('\033[33m *** Resolução do Exercicio ***\033[m')
numero = int... |
"""
PROBLEM 3 Objective
Fit a linear regression model with new features to predict # of tweets in the next
hour, from data in the PREVIOUS hour.
New Fetures from the paper in the preview:
1. number of tweets
2. number of retweets
3. number of followers
4. max numbber of followers
5. time of the data (24 hours represen... |
# coding: utf-8
import sqlite3
import csv
# connecting to the db and checking whether db exists: if not creates one (initiate_connection function)
conn = sqlite3.connect('url_data.db')
def initiate_connection():
try:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS url... |
# def cube_find(num):
# cube={}
# for i in range(1,num):
# cube[i]=i**3
# return cube
# print(cube_find(8))
#task5
user={}
name=input("what is your name : ")
age=input("what is your age : ")
gender=input("what is your gender : ")
fav_movie=input("what are your fav movie : ").split(",")
fav_song=in... |
# #oop style of real project:
# class Person:
# def __init__(self,firstname,lastname,address,age):
# print("init called class")
# self.first_name=firstname
# self.last_name=lastname
# self.address=address
# self.age=age
# person1=Person('manisha','dhakal','bhairahawa',100)
# ... |
class Circle:
pie=3.14
def __init__(self,radius):
# self.pi=pi
self.radius=radius
def circumtance(self):
return 2*Circle.pie*self.radius
circle1=Circle(5)
circle2=Circle(6)
print(circle1.circumtance())
print(circle2.circumtance())
|
# name=['manisha','cristina','manish']
# def function(l,target):
# for position,names in enumerate(l):
# if names==target:
# return position
# return -1
# print(function(name,'cristina'))
num=[1,2,3,4,5]
def power(a):
return a**2
# new_power=list(map(power,num))
new_power=list(map(lam... |
username=input("enter your number")
username=int(username)
total=0
i=1
while i<=username:
total+=i
i+=1
print(f"this is your number:{total}")
|
'''
write a python program to find those numbers which is divisbile
by 7 abd multiple of 5, between 1500 and 2700 (both included)
'''
number=[]
for i in range(1700,1500):
number.append(i/7)
number.append(i*5)
print(number)
#write a python program to construct the following pattern,using a nested
#for loop(
'... |
# def sum(a,b):
# if (type(a) is int) and (type(b) is int):
# return a+b
# raise TypeError('this is type error please input valid type')
# print(sum('1','2'))
class Animal:
def __init__(self,name):
self.name=name
def sound(self):
raise NotImplementedError('not implemented define... |
print "I will now count my blessings"
# adds 25 and 30 divides by 6
print "Good Vibes", 25.0 + 30.0 / 6.0
# 100 minus 25 times 3 with 4 remaining
print "Good People", 100.0 - 25.0 * 3.0 % 4.0
print "Now I will count Karma:"
#
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
print "Is it true that 3.0 + 2.0 < ... |
import unittest
from string_101 import *
class TestString(unittest.TestCase):
def test_rot1(self):
self.assertEqual(str_rot_13('abc'), 'nop')
def test_rot2(self):
self.assertEqual(str_rot_13('roof'), 'ebbs')
def test_rot3(self):
self.assertEqual(str_rot_13('gnat'), 'tang')
def test_trans... |
def square_all(a):
return [x*x for x in a]
def add_n_all(a, n):
new_list = []
for i in a:
new_list.append(i + n)
return new_list
def even_or_odd_all(a):
new_list = []
index = 0
while index < len(a):
if a[index] % 2 == 0:
new_list.append(True)
else:
new... |
"""
Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%.
"""
print("Enter Q to quit, enter any other key to calculate bonus.")
choice = input(">>> ").upper()
while choice != 'Q':
sales = float(input("Ente... |
# Task 1
name = input("Enter user's name: ")
out_file = open('names.txt', 'w')
print(name, file=out_file)
out_file.close()
# Task 2
in_file = open('names.txt', 'r')
username = in_file.read()
in_file.close()
print("Your name is", username)
# Task 3
in2_file = open('numbers.txt', 'r')
num1 = int(in2_file.readline())
nu... |
class Auto:
# конструктор
def __init__(self, color):
self.brand = 'Opel'
self.model = 'Omega'
self.color = color
# деструктор
def __del__(self):
print(self.brand, self.model, '- удалено c памяти')
def info(self):
print(f'Бренд: {self.brand}\nМодель: {self.m... |
# Matrix Transpose
import numpy
m = numpy.mat([[1, 2], [3, 4]])
print("Matrix.Transpose:")
print(m.T)
''' Output:
Matrix.Transpose:
[[1 3]
[2 4]]
''' |
"""Simple autoencoder with generator
This is a simple autoencdoer (it has only one compressed layer). It uses a
generator to iterate over the data in an online fashion. This allows two
interesting things:
1. Changing the size of the samples easily; and
2. a method for data augmentation (look for the step ar... |
num1=int(input("Enter The First Number :: "))
num2=int(input("Enter The Second Number :: "))
reminder=0
if num1>num2:
reminder=num1%num2
else:
reminder=num2%num1
temp=reminder
while reminder!=0:
temp=reminder
if num1>num2:
reminder=num2%reminder
else:
reminder=num1%reminde... |
num = input("Enter the number : ")
sum1 = 0
for itr in range(1,num+1):
sum1=0
for jtr in range(1,itr/2+1):
if itr%jtr==0:
sum1 = sum1 + jtr
if itr == sum1 or itr ==1:
print(itr)
|
"""*Program 3: Write a Program to print table of 2.
Output: 2 4 6 8 10 12 14 16 18 20"""
for itr in range(1,11):
print(itr*2)
|
'''
Problem Statement
Write a Program to calculate Velocity of particle in the space having Distance & Time Entered By User
'''
dist = int(input("Enter distance in metres \n"))
time = int(input("Enter time in seconds \n"))
vel = dist//time
print("The Velocity of a Particle roaming In space is ",vel," m/s")
|
''' Program 3: Write a Program to calculate Velocity of particle in the space having
Distance & Time Entered By User.'''
Distance = int(input("Distance : "))
Time = int(input("Time : "))
Velocity = Distance/Time
print("The Velocity of particle moving in space ",Velocity, " m/s") |
try:
n = int(input("Enter Size "))
except ValueError as e:
exit(0)
if(n <= 0):
exit(0)
for i in range(1,n+1):
for j in range(1,n-i+2):
print(chr(64 + i), end = "\t")
print()
|
'''
Problem Statement
Write a Program that accepts Two integers from user and prints the series of factorial of all numbers between those two inputs
A factorial is calculated by multiplying all the numbers including the number itself till 1
Example Factorial of 4 = 4*3*2*1 = 24
'''
start = int(input("Enter start valu... |
''' Run this program with python3'''
try:
a = int(input("Enter Size : "))
except ValueError:
print('Not a Number')
exit(0)
if a < 0:
print("Not allowed");
else :
for i in range(1 , a * a + 1):
if i % a == 0 :
print(0)
else:
print(0, end="\t")
|
"""
/*
*
Program 1: Write a Program to Find Maximum between two numbers
Input: 1 2
Output: 2 is Max number among 1 & 2
*
*/
"""
a = 2
b = 3
if a>b:
print(str(a)+" is greater then "+str(b))
else:
print(str(b)+" is greater then "+str(a))
|
num = 1;
for i in range(4):
for j in range(i + 1):
print(num * num, end = " ")
num += 1;
print()
|
'''Program 5: Write a Program that accepts Two integers from user and prints
maximum number from them.'''
num1, num2 = [int(i) for i in input("Input : ").split()]
if(num1 > num2):
print("Max : ", num1)
elif(num1 == num2):
print("Equal")
else:
print("Max : ", num2)
|
''' Program 4: Write a Program that accepts an integer from user and print table
of that number.'''
tableof = int(input("Enter a Number : "))
for num in range(1,11):
print(tableof * num,end =" ")
print()
|
var1=int(input("enter first integer "))
var2=int(input("enter second integer "))
mul=var1*var2
print("Multiplication is ",mul)
if(var1 > var2):
div=var1//var2
print("Division is ",div)
elif(var2>var1):
div=var2//var1
print("Division is ",div)
|
fact = 1
num1 = int(input("Input : "))
for i in range(num1):
fact *= i + 1
print("Fact : ", fact) if num1 >= 0 else print("Enter valid num.")
|
"""
Program 4 : Write a Program to print First 50 Even Numbers
Output: 2 4 6 . . . 100
"""
print("First 50 even numbers")
for itr in range(101):
if itr%2==0:
print(itr)
|
'''
Write a Program to that prints series of Even numbers in reverse
order from the limiting number entered by user.
'''
num=int(input("Enter the number:"))
for x in range(num,-1,-1):
if(x % 2 == 0):
print(x,end=" ")
print()
|
''' Program 3: Write a Program to Print following Pattern.
A A A A A
B B B B
C C C
D D
E
'''
a = 64
for i in range(1,6):
a+=1
for j in range(1,6):
if i + j >= 7:
print(" ",end=" ")
else:
print(chr(a),end=" ")
print() |
'''
Program 1: Write a program that accepts two integers from user and prints
addition & Subtraction of them.
{Note: checks for greater number to subtracts with while subtracting numbers}
Input: 10 20
Output:
Addition is 20
Subtraction is 10
'''
var1=int(input("enter first integer "))
var2=int(input("enter second... |
def gcd(n1 : int, n2: int)-> int:
if(n2 != 0):
return gcd(n2, n1 % n2)
else:
return n1
try:
n1 = int(input("Enter Number : "))
n2 = int(input("Enter Number : "))
except ValueError as e:
exit(0)
if(n1 < 0 or n2 < 0):
exit(0)
print("The GCD of {} and {} is {}".format(n1,n2,gcd(n1, n2)))
|
''' Program 4: Write a Program to Print following Pattern.
1
8 27
64 125 216
343 512 729 1000 '''
a = 1
for i in range(1,5):
for j in range(1,5):
if j <= i:
print(a * a * a,end=" ")
a+=1
print() |
"""
Program 3: Write a Program to Find whether the number Is Even or Odd
Input: 4
Output: 4 is an Even Number!
"""
a = 8
if a%2==0:
print(str(a)+" is even number")
else:
print(str(a)+" is odd number")
|
num = int(input("Input : "))
sum = 0
for i in range(num):
sum += i + 1
print("Sum : ", sum)
|
"""
Program 2: Write a Program to check whether the number ins Negative,
Positive or equal to Zero.
Input: -2
Output: -2 is the negative number
"""
a = -2
if a<0:
print(str(a)+" is negative")
else:
print(str(a)+" is positive")
|
n = 0
try:
n = int(input("Enter Size : "))
if(n < 0):
print("Enter Positive Number")
exit(0)
except ValueError as e:
print("Enter valid Number")
pass
flag = 1
for i in range(n, 0, -1) :
for j in range(0, n-i+1):
print(flag*flag, end = "\t")
flag+=1;
print()
|
''' Program 3: Write a Program to that accepts two integers from user and
calculates the Quotient & Reminder from their division '''
a,b = input("Input : ").split()
c = int (a)
d = int (b)
print("Quotient : ",c/d)
print("Remainder : ",c%d) |
'''
Problem Statement
Write a Program that accepts an integer from user and prints its second successor and second predecessor.
'''
num = int(input("Enter a number \n"))
print("The Second Predecessor = ",num-2)
print("The Second Successor = ",num+2)
|
try:
a = int(input("Enter Size : "))
except ValueError as e:
print("Invalid")
exit(0)
pass
k = 1
for i in range(1, a + 1):
for j in range(1, i + 1):
print(k, end = ' ')
k+=1
print()
|
try:
l = int(input("Enter length : "))
b = int(input("Enter breadth : "))
except ValueError as e:
exit(0)
if(l < 0 or b < 0 or l < b):
exit(0);
print("Area Of Rectangle = ",l * b, "sq unit")
|
"""
/*Program 5: Write a C program to calculate the factorial of a given number.
Input: 5
Output:
The Factorial of 5 is: 120*/
"""
num = 5
fact = 1
for itr in range(2,num+1):
fact = fact*itr
print("The Factorial of 5 is "+str(fact))
|
'''Run using python3'''
for i in range(3,101) :
if(i % 4 == 0 and i % 7 == 0):
print(i, end = ' ')
print() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.