text stringlengths 37 1.41M |
|---|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def twoSumBSTs(self, root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool:
set... |
class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
height, width = len(grid), len(grid[0])
nums = sum([grid[i][j] == 1 for i in range(height) for j in range(width)])
dis_count, visit_count = [[0]*width for... |
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
ind = 0
while ind < len(word):
if word[ind] == ch: break
ind += 1
return word[0:ind+1][::-1] + word[ind+1:] if ind != len(word) else word |
class Solution(object):
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
s = set()
for a in A:
even_chars = sorted([a[i] for i in range(0, len(a), 2)])
odd_chars = sorted([a[i] for i in range(1, len(a), 2)])
... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
ret = 0
... |
class Solution:
def averageWaitingTime(self, customers: List[List[int]]) -> float:
currtime = 0
total_wait = 0
for (arrivetime, preparetime) in customers:
if currtime <= arrivetime:
currtime = arrivetime + preparetime
total_wait += preparetime
... |
class WordDistance(object):
def __init__(self, words):
"""
:type words: List[str]
"""
self.dic = {}
for i,w in enumerate(words):
if w in self.dic:
self.dic[w].append(i)
else:
self.dic[w] = [i]
def shortest(self, wor... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root):
if root == None:
return True
l = self.helper(root.left)
r = s... |
val1 = float(input("Enter first number: "))
val2 = float(input("Enter second number: "))
opr = float(input("Please Select the operation numbere:\n 1: Sum \n 2: Subtract \n 3: Multiply \n 4: Divide \n 5: Reminder \n Enter the number of the Operation: "))
sum = float(val1 + val2)
sub = float(val1 - val2)
mul = floa... |
# SYSC 1005 Fall 2018
from Cimpl import *
def blur(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a new image that is a blurred copy of image.
original = load_image(choose_file())
blurred = blur(original)
show(blurred)
"""
target = copy(image)
# Recall that the x ... |
''' Swedish rövarspråket language.
In Sweden, children often play using a
language a little bit special, called "rövarspråket", which means "
the language of rogues ": consists in doubling
each consonant of a word and insert an "o" in the middle.
For example, the word "eat" becomes "momanongogiarore".
Write a function... |
''' This is a function that, at the user's choice,
calculate the area of: - a circle - a square - a rectangle - a triangle '''
# FUNCTION 'controlla_numero_decimale' starts
def controlla_numero_decimale (valore_in_ingresso) :
l=len(valore_in_ingresso)
for i in range(0,l,1) :
if valore_in_ing... |
import numpy as np
def minimumEditDistance(s1,s2):
if len(s1) > len(s2):
s1,s2 = s2,s1
distances = range(len(s1) + 1)
for index2,char2 in enumerate(s2):
newDistances = [index2+1]
for index1,char1 in enumerate(s1):
if char1 == char2:
newDistances.append(di... |
number1 = range(1,101)
number2 = []
for value in number1:
if value % 3 == 0:
number2.append(value)
else:None
print(list(number1))
print(number2) |
import math
import operator as op
from .mapping import *
Symbol = str # A Scheme Symbol is implemented as a Python str
Number = (int, float) # A Scheme Number is implemented as a Python int or float
Atom = (Symbol, Number) # A Scheme Atom is a Symbol or Number
List = list # A Scheme ... |
def zero(num):
return len(())
def one(num):
return oneSec(list((num, num)))
def oneSec(listF):
listF.pop()
return len(listF)
def two(num):
return len((num, num))
def three(num):
return len((num, num, num))
def four(num):
return len((num, num, num, num))
def five(num):
return len((n... |
def is_on_list(days, date):
if date in days:
return True
else:
return False
def get_x(days, num=int()):
return days[num]
def add_x(days, date):
days.append(date)
return days
def remove_x(days, date):
days.remove(date)
return days
days = ["Mon", "Tue", "Wed", "Thu", "Fr... |
# Numbers are created in the same way that strings are created, except they don't need quotes surrounding them
number = 123
print(number)
# Numbers can be used to do calculations for instance
amountOfSpam = 2
amountOfEggs = 3
totalSpamAndEggs = amountOfSpam + amountOfEggs
print(totalSpamAndEggs)
# The symbols used... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 10:59:51 2020
@author: Sharonvy
"""
import random
def get_min_max(ints):
n = len(ints)
if not isinstance(ints, list):
print("Invalid input data type")
return None
if n == 0:
print("Empty list")
... |
def deleteDuplicates(self, head: ListNode) -> ListNode:
#checking if head is None
if head == None:
return head
# making nodes for traversing
current = head.next
prev = head
# traversing through the linkedList
while current != None... |
#!/usr/bin/python
#
# Course: CCPS 109
# Lab: 3 File IO and Modules
# Due Date: Mar 16th @ 23:00 hrs
#
# Student: Sivatma Maharaj
# Student ID: 501043693
import weatherstat
month = {"1":"JAN","2":"FEB","3":"MAR","4":"APR","5":"MAY","6":"JUN"}
weather = {}
weather_avg = {}
weather_maxmin = {... |
sum = 0
for i in range(7, 10):
sum =sum + i
print('my sum:',sum)
#=============
sum = 0
for i in range(7, 10):
sum =sum + i
print('my sum:',sum)
#=================
sum = 0
for i in range(5, 11, 2):
sum += i
print("my sum:*",sum)
#---------------- |
#error student: fix it
fruits = ['Apple', 'Banana','Papaya','Durian','Mango','Peach','Organge']
for x in fruits:
if x == "Banana":
print('inside for loop')
print(x)
break
print('outside for loop')
#---------------- |
"""
Handles starting a game, registering players, making sure there are enough players to start a game.
"""
import json
class Game(object):
"""
Tracks game states.
States: Register game --> Players join --> Players ready --> Play game --> Game Over
Game starts with one player - the creator. Then anoth... |
"""
二叉树的list实现
表示例如:
['A', ['B', None, None],
['C', None, None]]
"""
class BinTree:
def __init__(self, data, left=None, right=None):
self._tree = [data, left, right]
def __str__(self):
return self._tree.__str__()
def is_empty(self):
return self._tree is None... |
#Ask user for name and print it
name = input ("Please enter your name: ")
print ("Welcome", name)
|
# http://www.geeksforgeeks.org/print-all-jumping-numbers-smaller-than-or-equal-to-a-given-value/
def findJumping(num, X):
queue = []
queue.append(num)
while len(queue) != 0:
N = queue.pop(0)
if N <= X:
print(N)
lastDigit = N%10
if lastDi... |
def maxProductSubArray(arr, N):
globalMax = 1
localMax = 1
start = end = 0
localStart = localEnd = 0
for i in range(len(arr)):
if arr[i] > 0:
localMax *= arr[i]
if localMax > globalMax:
globalMax = localMax
start = localStart
... |
# https://leetcode.com/problems/odd-even-linked-list/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
oddDummy = ListNode(None)
evenDummy =... |
# https://www.interviewbit.com/problems/largest-number/
'''
Given a list of non negative integers, arrange them such that they form the largest number.
For example:
Given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.... |
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
dummy = ListNode(None)
... |
# https://leetcode.com/problems/add-two-numbers-ii/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
prevNode = nextNode = None
currNode = h... |
x = 7
r = x % 2
if (r==0):
print("Even")
if (x>5):
print("Greater")
else:
print("Lesser")
else :
print("Odd")
|
def reverse_elements(number_list, current_position, length):
if length <= 1:
return number_list
elif current_position + length <= len(number_list):
sub_list = number_list[current_position:current_position + length]
reversed_sublist = list(reversed(sub_list))
return number_list... |
import pygame as game
import random, math
## to start the module it is mandatory (constructor call)
game.init()
WIDTH = 800
HEIGHT = 600
def start_randomly():
global ballxch, ballych
sign = [1,-1]
# Randomly initialization of ball movement and speed
ballxch = (random.uniform(0.3,1.1)*4) * ... |
def stripKB():
# Odstrani presledke in/ali vejice na koncu KB.
new_line = ""
f = open("KB.txt", "r")
lines = f.readlines()
for line in lines:
if ", " in line[-3:-1]:
new_line += line[:-3] + "\n"
elif ", " in line[-2:]:
new_line += line[:-2] + "\n"
... |
import PyPDF2
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
STRING1 = "The Imperviousness of Literature to War."
STRING2 = "Readers and Writers."
#write a for-loop to open many files -- leave a comment if you'd #like to learn how
filename = 'newage18.pdf'
#open allows you to ... |
# https://open.kattis.com/problems/nodup
words = sorted(input().split())
repeat = False
count = len(words)
i, j = 0, 0
for i in range(count):
for j in range(i+1, count):
if words[i] == words[j]:
repeat = True
j += 1
i += 1
if repeat:
print('no')
else:
print('yes')
|
# https://open.kattis.com/problems/mia
def game(dices_line):
one = int(dices_line[0] + dices_line[1])
two = int(dices_line[1] + dices_line[0])
if one > two:
first_player = one
else:
first_player = two
one = int(dices_line[2] + dices_line[3])
two = int(dices_line[3] + dices_lin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/5/11 19:11
# @Author : Ian_Zhou
# @Email : zhoujian_2008@msn.com
# @File : lesson2_practise_private.py
# @Function:
# @Software: PyCharm
# https://api.github.com/search/repositories?q=languages:python
import requests
import time
api_info = "https... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 11:59:20 2020
@author: Vladimir
"""
import math
class MaterialPoint_Linear():
def __init__(self, pos, acc, direct):
self.position = pos
self.acceleration = acc
self.direction = direct
self.step_num = 1
self.average_speed = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project 5:
# Name:Steven Kordell
# Date: 04/21/2015
# Mailbox number: 663
#Diffie Hellman Key Exchange
import random
import hashlib
if __name__ == "__main__":
random.seed(12345)
#A 1023-bit prime number (when doubled this will be 1024-bits)
... |
import numpy as np
from sys import argv, stdin
def file_parser():
max_slices, nb_pizza = input().split(" ")
arr_pizza = input().split(" ")
arr_pizza = [int(pizza_str) for pizza_str in arr_pizza]
return int(max_slices), int(nb_pizza), arr_pizza
def select_pizzas(max_slices, nb_pizza, arr_pizza):
... |
"""
Given two strings, one is a subsequence if all of the elements of the first string
occur in the same order within the second string. They do not have to be contiguous
in the second string, but order must be maintained. For example, given the string
'I like cheese', the words ('I', 'cheese') are one possible subse... |
import torch
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
model = torch.nn.Sequential(
torch.nn.Linear(D_in,H),... |
# O MESMO PROFESSOR DO DESAFIO ANTERIOR QUER SORTEAR A ORDEM DE APRESENTAÇÃO DE TRABALHOS DOS ALUNOS.
# FAÇA UM PROGRAMA QUE LEIA O NOME DOS QUATRO ALUNOS E MOSTRE A ORDEM SORTEADA.
import random
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input(... |
# FAÇA UM PROGRAMA QUE LEIA UM ÂNGULO QUALQUER E MOSTRE O VALOR DO SENO, COSSENO E TANGENTE
import math
ang = math.radians(float(input('Digite um ângulo qualquer:')))
sen = math.sin(ang)
cos = math.cos(ang)
tan = math.tan(ang)
print('Seno: {:.2f}'.format(sen))
print('Cosseno: {:.2f}' .format(cos))
print('Tangente: ... |
'''CRIE UM PROGRAMA QUE LEIA O NOME COMPLETO DE UMA PESSOA E MOSTRE:
- O NOME COM TODAS AS LETRAS MAIÚSCULAS
- O NOME COM TODAS AS LETRAS MINÚSCULAS
- QUANTAS LETRAS AO TODO (SEM CONTAR OS ESPAÇOS)
- QUANTAS LETRAS TEM O PRIMEIRO NOME'''
nome = str(input('Digite seu nome completo: ')).strip()
#nome_ = ''.join(nome.sp... |
# FACA UM PROGRAMA QUE LEIA A ALTURA E LARGURA DE UMA PAREDE EM METROS, CALCULE SUA ÁREA E INFORME QUANTOS LITROS
# DE TINTA SERÃO NECESSÁRIOS PARA PINTAR A PAREDE, SABENDO QUE CADA LITRO DE TINTA PINTA UMA ÁREA DE 2 METROS QUADRADOS
h = float(input('Qual a altura da parede em metros ? '))
l = float(input('Qual a larg... |
# MS(CS) 2017-AG-3677
# ASSIGNMENT NO 2
import numpy as np
import matplotlib.pyplot as plt
X1 = np.array([10, 30 , 20,25,30,15 ,5])
print(" X = ", X1)
X2 = np.array([5,8,2,4,9,2,4])
print(" X = ", X2)
Y = np.array([2 ,3, 6, 9, 12,9,14])
print(" Y = ", Y)
# Mean of X1 , X2 , Y
meanX1 = sum(X1)/len(X1)
p... |
import sys
input_file = 'input'
rel_base = 0
# Simple integer input
# No prompt and no error message for bad input
def get_int():
x = input()
while True:
try:
d = int(x)
except ValueError:
x = input()
continue
break
return d
# Addition and mult... |
#-----------------------------------------------------------------------------
# Runtime: 60ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def isMatch(self, s: str, p: str) -> bool:
i = j = 0
len_s, len_p = len(s), len(p)
... |
#-----------------------------------------------------------------------------
# Runtime: 28ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def searchInsert(self, nums: list, target: int) -> int:
lo, hi = 0, len(nums)
while... |
#-----------------------------------------------------------------------------
# Runtime: 32ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def sortColors(self, nums: [int]) -> None:
"""
Do not return anything, modify nums ... |
#-----------------------------------------------------------------------------
# Runtime: 32ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def simplifyPath(self, path: str) -> str:
if not path or not path.strip():
retu... |
#-----------------------------------------------------------------------------
# Runtime: 40ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
import sys
sys.path.append('LeetCode')
from ListNode import ListNode
class Solution:
def mergeTwoLists(self, l1: ... |
#-----------------------------------------------------------------------------
# Runtime: 36ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
import sys
sys.path.append('LeetCode')
from ListNode import ListNode
class Solution:
def rotateRight(self, head: ... |
unsorted_list = [14, 1, -1, 0, 7, 3, 21, 100, 10, 3, 5, 14, 11, 9, 8, -6]
#FOR VERSION
for passnum in range(len(unsorted_list) - 1, 0, -1):
#Loop from len(unsorted_list) until len(unsorted_list)=0
#with len(unsorted_list) -1 each loop
for i in range(passnum):
if unsorted_list[i] > unsorted_list[i + 1]:
... |
def topological_order(adj, root):
visited = {}
for i in adj.keys():
visited[i] = False
result = dfs(root, adj, visited)
for node in visited.keys():
if(not visited[node]):
result = dfs(node, adj, visited) + result
return result
def dfs(node, adj, visited):
if(visite... |
from random import randint
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0,2)]
player = False
while player == False:
player = input("Rock, Paper, Scissors?")
if player == computer :
print ("Tie")
elif player=="Rock":
if computer =="Paper":
print("You lose because of ", computer , "covers",... |
print("=============")
print("Algoritma DDA")
print("=============")
x1 = 3
y1 = 6
x2 = 14
y2 = 10
Dx = x2 - x1
Dy = y2 - y1
r = 0
if(Dx > Dy):
r = Dx
else:
r = Dy
Xr = Dx / r
Yr = Dy / r
str = "Dx : {0} \nDy : {1} \nr : {2} \nXr : {3} \nYr : {4}"
print(str.format(Dx, Dy, r, Xr, Yr))
x = x1 + Xr
y = y1... |
# Authors: Matthew Backes, Daniel Janis, Keenan Andrea, Mohamad Sumren
# This program utilizes Pygame to display information about binary trees. For all versions of this program,
# we use two objects, Master and Node, to either create a binary tree or allow the user to create their own binary
# tree, and then use sear... |
''' A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.'''
# Program to display the Fibonacci sequence up to n-th term where n is pr... |
import csv
import numpy as np
def parse_data(open_file, labels_col, label_val):
"""Reads data from an open data file and parses out the binary labels and features.
Args:
open_file (csv.reader): An open file containing the data
labels_col (int): The column index containing the labels
... |
########################################## HOME PAGE ##########################################
homepage = "GET ESTIMATED COST OF FUEL BEFORE GOING ON TRIP".center(120)
p = '==' * 56
print()
print(p)
print(homepage)
print(p)
########################################## HOME PAGE #################################... |
i = 1
j = 60
print('I={} J={}'.format(i, j))
for c in range(12):
i += 3
j -= 5
print('I={} J={}'.format(i, j))
|
salario = float(input())
if salario <= 400:
percentual = 15
reajuste = salario * percentual / 100
total = reajuste + salario
elif salario <= 800:
percentual = 12
reajuste = salario * percentual / 100
total = reajuste + salario
elif salario <= 1200:
percentual = 10
... |
def modularSum(arr,n,m):
if(n>m):
return True
DP = [False for i in range(m)]
for i in range(n):
if (DP[0]):
return True
temp = [False for i in range()]
for j in range(m):
if (DP[j] == True):
if (DP[(j + arr[i]) % m] == False):
... |
# can't call cough directly but as python doesn't have prototypes like C have, we defined a main (which can be called anything)
# and calling it at the bottom
def main():
cough(3)
def cough(n):
for i in range(n):
print("cough")
main() |
# Saves names and numbers to a CSV file
import csv # csv package (libraries are called packages in Python)
from cs50 import get_string
# Get name and number
name = get_string("Name: ")
number = get_string("Number: ")
# Open CSV file (don't have to worry about closing file if you're using with syntax)
with open("phon... |
print("Titanic érettségi feladat")
print("\n-------------------------------------------------------------\n")
print("1.Feladat: Beolvasás")
titanic_adatok=[]
db=0
with open("titanic.txt","r", encoding="utf-8") as titanicAdatok:
for egySor in titanicAdatok:
egyTitanic=egySor.strip().split(";")
... |
class Singleton:
__conn = None
def __init__(self, name, age):
if Singleton.__conn is None:
self.name = name
self.age = age
Singleton.__conn = self
else:
raise Exception('We cannont create class')
@staticmethod
def getInstance():
i... |
# Implement a program that prints out a double half-pyramid of a specified height
while True: # If a numerical value isn't entered, the program will run again until a numerical value set within the condition is passed
try:
height = int(input("Height: "))
if height > 0 and height < 9:
br... |
import random;
def numberGuess():
printNow("I am thinking of a number from 1-10")
guess = 0
randNum = random.randrange(1,11)
guess = int(input("Try to guess the number:"))
print(randNum)
while guess != randNum
if (guess == randNum):
print "You got it"
if (guess > randNum):... |
import heapq
input_=[3,2,1,5,6,4]
k=2
def findKthLargest(nums, k):
#solution 1
heap=[]
for i in range(len(nums)):
heapq.heappush(heap, -nums[i])
answer=0
for i in range(k):
answer=heapq.heappop(heap)
return -answer
#solution 2
#heapq.heapify(nums)
#for _ in range... |
intervals=[[1,3],[2,6],[8,10],[15,18]]
#[[1,4],[4,5]]
def merge(intervals):
intervals=sorted(intervals, key=lambda x:x[0])
merged=[]
for inter in intervals:
if merged and inter[0]<=merged[-1][1]:
merged[-1][1]=max(merged[-1][1], inter[1])
else:
merged+=inte... |
num=8
def numberOfSteps(num):
cnt=0
while num:
if num%2==0:
num/=2
cnt+=1
else:
num-=1
cnt+=1
return cnt
print(numberOfSteps(num))
|
nums=[1,2,3,4]
#given an array nums of n integers where n>1,
#return an array output
#such that output[i] is equal to the product of all the elements of nums except nums[i]
ans=[]
right=[]
mid=1
ans.append(mid)
for i in range(len(nums)-1):
mid*=nums[i]
ans.append(mid)
print(ans)
mid=1
for i... |
#s="1+(2*3)/(2-1)"
s="(1)+((2))+(((3)))"
#s="(1+(2*3)+((8)/4))+1"
def maxDepth(s):
cnt=0
depth=0
for s1 in s:
if s1=="(":
cnt+=1
elif s1==")":
cnt-=1
else:
continue
depth=max(cnt, depth)
return depth
print(maxDepth(s))
|
arr=[12,21,11,22]
pieces=[[12,21],[1,2]]
def canFormArray(arr, pieces):
answer = True
while pieces:
p = pieces.pop(0)
#len(piece[i])==1
if len(p) == 1 and p[0] in arr:
continue
else:
#len(piece[i])>=2
l=len(p)
if p[0... |
S=")()"
def minAddtToMakeValid(S):
stack=[]
no_=0
yes_=0
S=list(S)
while S:
s=S.pop(0)
if s=="(":
stack.append(s)
else:
if len(stack)==0:
no_+=1
else:
stack.pop()
yes_+=2
... |
s="Let's take LeetCode contest"
def reverseWords(s):
split_s=s.split(' ')
split_s=[s[::-1] for s in split_s]
return ' '.join(split_s)
print(reverseWords(s))
|
mat=[[1,2,3],[4,5,6],[7,8,9]]
def diagonalSum(mat):
#solution 2
ans=0
for i in range(len(mat)):
ans+=mat[i][i]+mat[i][-(i+1)]
if len(mat)%2!=0:
m=len(mat)//2
ans-=mat[m][m]
return ans
#soltuion 1
#ans=0
#for i in range(len(mat)):
# for j in ra... |
A=[0,1,2,4]
def sortArrayByParity(A):
# solution 1.
even = []
odd = []
for num in A:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
return even + odd
'''
#solution 2.
l=len(A)
start, end=0, l-1
while start<end:
if A[sta... |
print('ingresa tu nombre')
name = input()
if name == 'caro':
print('hola caro')
else:
print('tu no eres caro')
|
def rev_num(num):
if num >= 2**31-1 or num <= -2**31: return 0
else:
str_num=str(num)
if num >= 0 :
rev_num = str_num[::-1]
else:
temp = str_num[1:]
temp2 = temp[::-1]
rev_num = "-" + temp2
if int(r... |
from .structures import NestedClass
class Validator(NestedClass):
"""
When called with a dictionary, the validator runs all methods
matching its keys with their values as parameter. When a method
returns a string, it is added to a dictionary of error messages.
The special cases before and after ar... |
def pattern1(n):
for i in range(1,(n+1)):
for j in range(1,(i+1)):
print("@ ",end="")
print("\r")
#pattern1(10)
def pattern2(n):
k=2*n-2
for i in range(0,n):
for j in range(0,k):
print(end=" ")
k=k-1
for j in range(0,i+1):
... |
import unittest
import datetime
import requests
from blockchain import Block, Chain, Node
class BlockTests(unittest.TestCase):
"""A block records transactions in a blockchain. Thus a block is like a
page of a ledger or record book. Each time a block is 'completed', it
gives way to the next block in the b... |
lista1 = []
pos_max = []
pos_min = []
for i in range(0,5):
lista1.append(int(input('Digite o {} valor: '.format(i+1))))
val_max = max(lista1)
val_min = min(lista1)
print('A lista digitada eh {}'.format(lista1))
print('O maior valor da lista eh {}'.format(val_max))
print('O menor valor da lista eh {}'.format(val_min))
... |
numero = 'ZERO', 'UM', 'DOIS', 'TRES', 'QUATRO', 'CINCO', 'SEIS', 'SETE', 'OITO', 'NOVE', 'DEZ', 'ONZE', 'DOZE', 'TREZE', 'QUATORZE', 'QUINZE', 'DEZESSEIS', 'DEZESSETE', 'DEZOITO', 'DEZENOVE', 'VINTE'
while True:
num = int(input('Digite um numero: '))
if num > 0 and num < 20:
break
for i in range(0,20):
if num ==... |
import math
num = float(input('Digite um numero: '))
num_int = math.trunc(num)
print('O numero {} tem a parte inteira {}'.format(num, num_int)) |
nome = nome_prod = choose = ''
preco = prod = prod_barato = totmil = subtot = i = 0
cond = True
while cond == True:
nome = str(input('Digite o nome do produto: ')).strip().upper
preco = float(input('Digite o preco do produto: '))
choose = ' '
while choose not in 'SN':
choose = str(input('Deseja ... |
s = 0
print('A soma dos numeros imapres, multiplos de 3, no intervalo de 1 a 500 eh: ', end=' ')
for i in range (1,501):
if i % 2 == 1 and i % 3 == 0:
s += i
print(s) |
import math
co = float(input('Digite a dimensao do cateto oposto: '))
ca = float(input('Digite a dimensao do cateto adjacente: '))
hip1 = math.sqrt(math.pow(co,2) + math.pow(ca,2)) #CALCULO DE FORMA MATEMATICA
hip2 = math.hypot(co,ca) #CALCULO USANDO MODULOS
print(... |
# sexo = str(input('Digite o sexo da pessoa: [M/F]: ')).strip().upper()
# while sexo != 'M' and sexo != 'F':
# print('Opcao invalida! Por favor insira os dados corretamente')
# sexo = str(input('Digite o sexo da pessoa: [M/F]: '))
# print('O sexo da pessoa eh {}'.format(sexo))
# -=-=-=-=-=-=-=-=-=-=-=-=-OUTRA ... |
lista = []
for i in range(0,5):
num = int(input('Digite um numero: '))
if i == 0 or num > lista[-1]:
lista.append(num)
print('Adicionado ao final da lista!')
else:
pos = 0
while pos < len(lista):
if num <= lista[pos]:
lista.insert(pos, num)
print('Adicionado na posicao {}'.format(pos))
break
... |
import math
ang_graus = int(input('Digite um angulo: '))
ang = math.radians(ang_graus) #FUNCAO USADA PARA CONVERTER ANGULO DE GRAUS PARA RADIANOS
sen = math.sin(ang)
cos = math.cos(ang)
tan = math.tan(ang)
print(ang)
print('O valor do seno do angulo {:.1f} eh {:.2f}'.format... |
print ("Guess The Number X")
#number of Guesses 9
#number is 18
#number of guesses left
# print game over
i = 0
n = 18
while(i<9):
if i==0:
print("you have 9 guesses")
else:
print("you have",9-i,"guesses left")
x= int(input("Enter your digit : "))
if x>n:
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.