text stringlengths 37 1.41M |
|---|
if __name__ == '__main__':
#n = int(input())
# your code here
ip=[2,1,3,5,6,9,7]
ip=sorted(ip)
x=ip[0]
y=ip[0]
for i in ip:
if i >y:
x=y
y=i
print(x)
|
import numpy as np
class Node(object):
""" A node in a real-valued decision tree.
Set all the attributes properly for viewing the tree after training.
"""
def __init__(self, leaf=True, left=None, right=None, samples=0, feature=None, theta=0.5, misclassification=0,label=None):
"""
P... |
"""
Auxiliary methods on ranges (intervals)
"""
import six
def complementary_ranges(ranges, start_index, end_index):
"""
Returns complementary ranges from range (start_index, end_index)
For start_index = 0, end_index = 20 goes as follows:
ranges -> complementary_ranges
[(1, 5), (10, 15)] -> [(0, ... |
# Created Dec 2 2013
# This scripts creates specific number of files within min and max limit across many folders
import os
import random
import math
import sys
size1 = int(input('Enter minimum size of file: '))
size2 = int(input('Enter maximum size of file: '))
totalFiles = int(input('Total files: '))
max... |
## urllib turns a URL into a file
import urllib
from BeautifulSoup import *
url = input("Enter URL - ")
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('span')
for tag in tags:
print(tag.get('href', None))
|
a = int(input("dime el año"))
m = int(input("dime el mes"))
d = int(input("dime el dia"))
def comprobar_fecha(a, m, d,):
#Array que almacenara los dias que tiene cada mes (si el ano es bisiesto, sumaremos +1 al febrero)
dias_mes = [31, 28, 31, 30,31, 30, 31, 31, 30, 31, 30, 31]
if((a%4 == 0 and a%100... |
h = int(input('ingrese el numero de horas'))
vh = int(input('ingrese el valor de una hora pagada en dolares'))
t = vh * h
T = (t * 10) / 100
Td = t - T
if (Td < 300):
td2 = (Td * 2) / 100
print("el sueldo de el empleado es " +str(td2))
else:
print("el sueldo del empleado es " + td)
|
import array as arr
mang = arr.array('i')
print("Nhap n:")
t = 0
n = int(input())
for x in range(n):
mang.append(int(input()))
t += mang[x]
td = t/n
print("Gia tri trung binh la:" + str(td))
|
print("Nhap 2 canh hinh chu nhat: ")
print("Chieu dai:")
a=int(input())
print("Chieu rong:")
b=int(input())
c=a*b
d=2*(a+b)
print("Dien tich:"+str(c))
print("Chu vi:" + str(d)) |
# https://leetcode.com/problems/valid-boomerang/
# A boomerang is a set of 3 points that are all distinct and not in a straight line.
# Given a list of three points in the plane, return whether these points are a boomerang.
# Example 1:
# Input: [[1,1],[2,3],[3,2]]
# Output: true
# Example 2:
# Input: [[1,1],[2,2... |
# https://leetcode.com/problems/next-greater-node-in-linked-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
lists,stack = [],[]
cur_no... |
# https://leetcode.com/problems/relative-sort-array/
# Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
# Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be place... |
# https://leetcode.com/problems/peak-index-in-a-mountain-array/
# 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, retur... |
# https://leetcode.com/problems/first-missing-positive/
# Given an unsorted integer array, find the smallest missing positive integer.
# Example 1:
# Input: [1,2,0]
# Output: 3
# Example 2:
# Input: [3,4,-1,1]
# Output: 2
# Example 3:
# Input: [7,8,9,11,12]
# Output: 1
# Note:
# Your algorithm should run in O(n) ... |
# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# Your algorithm's runtime complexity must be in the order of O(log n).
# If the target is not found in t... |
# https://leetcode.com/problems/longest-harmonious-subsequence/
# We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
# Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subseque... |
# https://leetcode.com/problems/missing-number/
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
# Example 1:
# Input: [3,0,1]
# Output: 2
# Example 2:
# Input: [9,6,4,2,3,5,7,0,1]
# Output: 8
# Note:
# Your algorithm should run in linear runtim... |
# https://leetcode.com/problems/find-all-duplicates-in-an-array/
# Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
# Find all the elements that appear twice in this array.
# Could you do it without extra space and in O(n) runtime?
# Example:
# Input:
... |
# https://leetcode.com/problems/top-k-frequent-words/
# Given a non-empty list of words, return the k most frequent elements.
# Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
# Example 1:
# Input: ["... |
# https://leetcode.com/problems/single-number-iii/
# Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
# Example:
# Input: [1,2,1,3,2,5]
# Output: [3,5]
# Note:
# The order of the result is not... |
# https://leetcode.com/problems/degree-of-an-array/
# Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
# Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums... |
'''
Read an integer .
Without using any string methods, try to print the following:
Note that "" represents the values in between.
'''
from aetypes import end
if __name__ == '__main__':
n = int(input())
def name(input_number):
for i in range(1,input_number+1):
print(i, end(''))
name(n) |
def braces(value):
brackets = {'{':'}', '(':')', '[':']'}
active_brace = [value[0]]
for c in value[1:]:
if c in brackets:
active_brace.insert(0, c)
elif c != brackets[active_brace[0]]:
return False
else:
active_brace.pop(0)
if len(active_brace)... |
__author__ = 'Jun'
# solution to http://www.codechef.com/problems/TSORT
'''
Now I could have used the simple list.sort() function that python provides,
but I wanted to implement merge sort in python because I've done it for every
other language I've learned. Unfortunately merge sort takes too much time for such
a lim... |
from pta import *
print("<==== Testing positions ====>")
print("Instance creation: {p}".format(p=Position(1, 2, 3)))
p = Position()
print("Recognizing empty position: p = {p}, empty? = {empty}".format(p=p, empty=p.is_root()))
p1 = Position(1, 2)
p2 = Position(1, 2, 3)
p3 = Position(1, 3)
print("{x} <= {y} <= {z}? {che... |
#This is my first code
line = ('Printing this 3 times')
for x in range (0,3):
print(line) |
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
fast = head
slow = head
# find the middle (slow)
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# reverse second half
prev = None
wh... |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ""
for i in range(len(strs[0])):
for s in strs:
if i == len(s) or s[i] != strs[0][i]:
return res
res += strs[0][i]
return res
|
num = int(input("input integer" + "\n"))
binaries = []
while num >= 1:
div, mod = divmod(num, 2)
binaries.insert(0, mod)
num = div
print("".join(map(str, binaries)))
|
class City:
def __init__(self, cid, cname, cstate, pop, cases, left=None, right=None):
self.cid = cid # city id
self.cname = cname # city name
self.cstate = cstate # state name relating to city
self.pop = pop # population of city
... |
from tkinter import Tk
from tkinter import Frame
from tkinter import Label
from tkinter import Entry
from tkinter import Button
import pickle
import json
from buscainformacoes import BuscaInformacoes
from processadados import ProcessaDados
from preprocessamento import PreProcessamento
from fazrelat import FazRelat
cl... |
from Simulator import Simulator
import Sprites
from Sprites import BrainVehicle, Light
import numpy as np
import random
import math
import matplotlib.pyplot as plt
def make_random_brain():
"""
Creates a random brain depending on the genome scale and genome length.
:return: the random brain
"""
# m... |
#!/bin/python3
import sys
from os import path
from math import floor
def fuel(weight):
total = 0
fuelReq = floor(weight / 3)
while True:
if fuelReq <= 0:
break
else:
fuelReq = fuelReq - 2
if fuelReq <= 0:
break
else:
... |
class Employee:
empCount=0
def __init__(self, name, salary):
self.name=name
self.salary=salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d " % Employee.empCount)
def displayEmp(self):
print("Name:%s, Salary:%d" % (self.name, self.sal... |
def steps(n):
for i in range(1, n+1):
print(''.join(['#' for j in range(0, i)]) + ''.join([' ' for j in range(i, n)]))
|
import unittest
from .main import is_anagram
class TestAnagrams(unittest.TestCase):
def test_anagrams(self):
self.assertTrue(is_anagram('hello', 'llohe'))
self.assertTrue(is_anagram('Whoa! Hi!', 'Hi! Whoa!'))
self.assertFalse(is_anagram('One One', 'Two two two'))
self.assertFalse(is_anagr... |
import matplotlib.pyplot as plt
import random
n = 13
V = []
V = range(n)
points = []
x = 0
y = 0
for i in V:
x = random.randint(0, 20)
y = random.randint(0, 20)
points.append((x, y))
points.append(points[0])
xs, ys = zip(*points)
points.clear()
plt.figure()
plt.plot(xs, ys)
plt.show()
|
#!/usr/bin/env python
"""
Aufgabe 2: Pythonskripts
"""
# Eingabe der Länge und Breite mittels input() und einer Typkonvertierung
L = int(input("Geben Sie die Länge ein: "))
B = int(input("Geben Sie die Breite ein: "))
# Flächeninhalt und Umfang als Variablen definieren
A = L*B
U = 2*(L+B)
# Ausgabe eines Antwortsatz... |
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
print "My name is %s and weight is %d kg!" % ('Zara', 21) #!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
t... |
places=['delhi','agra','ttd','madhura','mumbai','kolkata']
len(places)
print("here is the original list of places")
print(places)
print("here is the sorted list of places")
places=sorted(places)
print(places)
print("here is the original list again")
print(places)
print("here is the sorted list of places in reverse alph... |
names={'Rithika':'36','Rajeswar':'63','Girija':'90','Raju':'9','Rithurajeswar':'369'}
print("Rithika's favorite Number is " + names['Rithika'].title() + ".")
print("Rajeswar's favorite Number is " + names['Rajeswar'].title() + ".")
print("Girija's favorite Number is " + names['Girija'].title() + ".")
print("Raju's f... |
number = input("How many people are there in the dinner group : ")
number = int(number)
if number >=8:
print("Can you please wait for some time!")
else:
print("\n Your Table is ready!") |
#Sum all the items in the list [1, 2, 3, 4, 5, 6, 7] without built-in methods.
sum_list = [1, 2, 3, 4, 5, 6, 7]
result = 0
for i in sum_list:
result = result + i
print(result)
# Remove odd number from [1, 2, 3, 4, 5, 6, 7] list
all_list = [1, 2, 3, 4, 5, 6, 7]
for i in all_list:
if (i%2 ==0):
continue
... |
"""
This is my first python project.
A simple calculator, that adds, subtracts, multiply and divide.
"""
#declartion of variable operation, this wil define the
#operation to carry out
def addition_operation(a,b):
return a + b
def subtraction_operation(a,b):
return a - b
def multiplication_operation(a,b):
... |
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
bill_payer_1 = len(names)
bill_payer_2 = random.randint(0, bill_payer_1)
bill_payer = names[bill_payer_2 - 1]
print(f"{bill_payer} is going to pay the bill today") |
text = input()
punc_remove = [",", ".", "!", "?"]
for i in punc_remove:
text = text.replace(i, "")
print(text.lower())
|
clave = input("ingrese clave: ")
while True:#controlo que se ingrese un valor valido
paso = int(input ("ingrese paso entre 1 y 25: "))
if paso < 25 and paso > 1:
break
print( "ha ingresado un valor invalido")
code= " "
listacesar= list(clave)
for letra in listacesar:
if not letra.isalpha():#qui... |
from flask import Flask, jsonify
import datetime as dt
import numpy as np
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
engine = create_engine("sqlite:///hawaii.sqlite")
Base = automap_base()
"ths f... |
## importing socket module
import socket
#To get the physical address of the device we use getmac module of Python.
from getmac import get_mac_address as Mac_Address
#We import sys to terminate the terminal in case something goes wrong
import sys
#To get external IP address we use requests module
from requests impo... |
import sqlite3
bookstore=sqlite3.connect("bookstore.db")
curstore=sqlite3.connect("bookstore.db")
curstore=bookstore.cursor()
curstore.execute("INSERT INTO books (title , author , price ) VALUES ('think python','allen b drowney',450);")
curstore.execute("INSERT INTO books (title , author , price ) VALUES ('harry potter... |
import queue
from copy import deepcopy
class Solver:
def __init__(self, graph):
self.graph = graph
self.len = len(graph)
self.x, self.y = self.coor_zero(graph)
def is_solved(self, graph):
prev = graph[0][0]
for i in range(self.len):
for j in range(self.len):... |
def FahrToCelsius(Fahrenheit):
C = (F - 32) * (5/9)
return C
def CelsiusToFahr(Celsius):
F = C * (9/5) + 32
return F
F = input("Convert Fahrenheit to Celsius: ")
F = float(F)
print(FahrToCelsius(F))
C = input("Convert Celsius to Fahrenheit: ")
C = float(C)
print(CelsiusToFahr(C))
|
# Print a string using qoutation marks within the string
quote = '"I have a dream" - MLK Jr.'
print(quote)
# Print a string using apostrophes inside the string
words = "These are some 'words'"
print(words)
# Print string that spans multiple lines
paragraph = """This string is going to span
multiple lines. It will be ... |
desserts = ['ice cream', 'cookies']
desserts.sort()
print(desserts)
print(desserts.index('ice cream'))
food = []
food.extend(desserts)
food.extend(['broccoli', 'turnips'])
print(desserts)
print(food)
food.remove('cookies')
print(food)
print(food[:2])
cookies = "cookies, cookies, cookies"
breakfast = []
breakfast... |
# Print result of tring to 'find()' the substring "a" in "AAA" in one line.
#results should be -1
print("AAA".find("a"))
# Find first occurrence of a number in a string, store number as float initially
v = "version 2.0"
vCheck = 2.0
print(v.find(str(vCheck)))
# Takes input and prints the result of finding a particula... |
# Ask for user input until condition is met then break from loop.
while True:
userQuit = input("type 'q' to quit program: ")
if userQuit.lower() == 'q':
break
# Print all numbers except multiples of 3 using continue
for i in range(1, 51):
if i % 3 == 0:
continue
print(i)
|
def climbing(n):
'''
Problem:
Climbing stairs
You are climbing a stair case.It takes n steps to reach the top
Each time you can either climb 1 or 2 steps
In how many distinct ways can you climb to the the top
1.Define the objective function
f(i) --> nu of distinct ways to reach the ... |
def compare(version1,version2):
# split where there are ,
# then loop through both of them
# if v1 > v2 return 1
# if v1 < v2 return -1
# otherwise return 0
v1 = version1.split(".")
v2 = version2.split(".")
v1 = [int(i) for i in v1]
v2= [int(i) for i in v2]
if len(v1) > l... |
def get_middle(s):
word_lenght = len(s)
split_word = list(s)
if word_lenght % 2 == 0:
first_index_of_middle = int(word_lenght/ 2 -1)
second_index_middle = first_index_of_middle + 1
two_letters = split_word[first_index_of_middle] + split_word[second_index_middle]
retu... |
def palindrome(str):
if len(str) == 0:
return True
str = str.lower()
str = str.split(,")
newArr = []
print(str)
for i in str:
print(i[::-1])
palindrome("A man, a plan, a canal: Panama")
|
def min(strArr):
stringN = strArr[0]
print(strArr[0])
# for i in range(len(stringN)):
# print(stringN[0:i+1])
i = 1
while i < len(stringN):
# stringN[i]
print(i)
i=+1
# print(stringN[0:i+1])
# code goes here
return strArr
|
# given an array rotate it k times to the right
def rotate(A,K):
# first I'd rotate the array once
# so how do we rotate the array
# we move the last element to the firs place and
# the rest follow suit
# moving elements to the right in an array
# [3,8,9,7,6]
# 3 ---> 0 now 3 ---> 1
... |
print("What is your name ?")
# prompts user to pass input
name = input()
print (" How old are you ?")
age = int(input())
print(name,age)
|
def three(str):
strings = str.split(' ')
print(strings)
three("2hell6o3 wor6l7d2") |
# how a binary tree works is the smaller numbers are
# on the left
def search(root,val):
print(search([4,2,1,7,3],5)) |
# 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
# base case if root is empty count = 0
class Solution:
def countNodes(self, root: TreeNode) -> int:
# base case
if ro... |
def brackets(S):
# "{[()()]}"
stack = []
for i in S:
stack.append()
print(brackets("([)()]"))
|
# Note in python an empty value will considered to be false
for i in range(0,7):
print("I would love" + str(i) + "cookies")
|
# given an array rotate it k times to the right
def rotate(arr,k):
# first I'd rotate the array onc
rotate([1,2,3,4],4)
|
def BinaryReversal(s):
n = bin(int(s))
print(n[2:])
n=n[2:]
if len(n)%8 == 0:
N = len(n)//8
print('N',N)
else:
N = len(n)//8+1
print('N',N)
k=str()
print('n at this point',n)
for i in range(len(n)):
k+=n[-i-1]
print('k',k)
while len(k)<N*8:
k+="0"
print("k in whil... |
def romanToInt(param):
totalValue = 0
romans = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for i in range(len(param)-1):
if i+1 == len(param)-1:
totalValue += romans[param[i+1]]
if romans[param[i]] < romans[param[i+1]]:
totalValue -= romans[param[i]]
... |
def wavesort(arr):
# sort the numbers first
numbers = sorted(arr)
# swap the numbers
n = len(numbers)
i = 0
print(numbers)
# while i < n-1:
# temp = numbers[i]
# numbers[i] = numbers[i+1]
# numbers[i+1] = temp
# i+=2
for i in range(0,n-1,2):
num... |
'''
You are given a non-empty, zero-indexed array A of n (1 � n � 100 000) integers
a0, a1, . . . , an−1 (0 � ai � 1 000). This array represents number of mushrooms growing on the
consecutive spots along a road. You are also given integers k and m (0 � k, m < n).
A mushroom picker is at spot number k on the road and sh... |
import stringcase
def to_jaden_case(string):
jaden_case = string.camelcase()
print(jaden_case)
return jaden_case
to_jaden_case("how aren't you today?") |
def remove(str):
stackA = []
stackB = []
total = 0
for i in range(0,len(str)//2):
stackA.append(str[i])
for i in range(len(str)//2,len(str)):
stackB.append(str[i])
print('A',stackA)
print(stackB)
while stackA !=[] and stackB !=[]:
if stackA[-1] != stackB[-1]:
stack... |
def duplicate(str):
# brute force approach
# is storing the substring and checking how many times they
# occur
# dictionary key is the substring and occurrences is how many
# times its occurred
words ={}
# pointers
left = 0
right = 0
while left < len(str) and right
|
def string(str):
print(len(str) // 2)
for i in range(len(str)//2,0,-1):
a = str[:i]
print(a)
count = 2
b =''
# since its a substring
while len(b) < len(str):
b = a
string("abcababcababcab") |
# coding:utf8
"""
选择排序和冒泡排序的区别在于:
选择排序的前提是:找到最大值的位置,最后才进行1次交换
而冒泡排序:相邻的值进行交换,一共进行n次交换
"""
def selection_sort(l):
length = len(l)-1
while length:
index = length
# 第一个数字,和后面每一个数字进行对比
for j in range(length):
if l[j] > l[index]:
index = j
l[length], l[i... |
from cs50 import get_float
if __name__ == "__main__":
while True:
cash = get_float("Change owed: ")
cash *= 100
if cash > 0:
break
coins = 0
while cash >= 25:
cash -= 25
coins += 1
while cash >= 10:
cash -= 10
coins += 1
while cash... |
def add_two():
start = float(input("Starting at?"))
terms = int(input("Number of terms? (excluding starting number)"))
counter = 0
print(start)
while counter < terms:
start += 2
print(start)
counter+= 1
add_two() |
def add():
start = float(input("Starting at?"))
terms = int(input("Number of terms? (excluding starting number)"))
number = float(input("You want to add by..."))
counter = 0
print(start)
while counter < terms:
start += number
print(start)
counter+=... |
import string
import random
import time
possibleCharacters = string.ascii_lowercase + string.digits +string.ascii_uppercase + ' ., !?;:'
p = int(input("Enter the lenght of code to generate :"))
t = ''.join([random.choice(possibleCharacters) for n in range(p)])
attemptThis = ''.join(random.choice(possibleCharacters)
... |
import pg8000
#jessica's username is jessicayang, and her password is testing09876
#gloria's username is gloriama, password is testing445566
conn = pg8000.connect(user="michaelnestler", password="testing54321", database="thingamajig", host="cs437dbinstance.cpa1yidpzcc3.us-east-1.rds.amazonaws.com")
conn.autocommit = ... |
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
t = 'Toms' in d
print(t)
b = d.get('Bob')
print(b) |
def heapify(a,n,i):
parent=i
left=2*i+1
right=2*i+2
if(left<n and a[left]>a[parent]):
parent=left
if(right<n and a[right]>a[parent]):
parent=right
if(i!=parent):
a[i],a[parent]=a[parent],a[i]
heapify(a,n,parent)
def heapsort(a,n):
for i in range(n/... |
"""
This file contains YAML-related operation functions.
"""
import yaml
def read_yaml(yaml_path):
"""
Read YAML file on given path.
Args:
yaml_path (str): YAML file path
Returns:
Data structure represented by YAML file
"""
with open(yaml_path, "r") as stream:
try:
... |
"""
https://www.urionlinejudge.com.br/judge/pt/problems/view/1016
URI Online Judge | 1016
Distância
Adaptado por Neilor Tonin, URI Brasil
Timelimit: 1
Dois carros (X e Y) partem em uma mesma direção. O carro X sai com velocidade constante de 60 Km/h e o carro Y sai com velocidade constante de 90 Km/h.
Em uma hora (6... |
"""
https://www.urionlinejudge.com.br/judge/pt/problems/view/1020
URI Online Judge | 1020
Idade em Dias
Adaptado por Neilor Tonin, URI Brasil
Timelimit: 1
Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias
Obs.: apenas para facilitar o cálculo, considere todo ano com... |
"""
https://www.urionlinejudge.com.br/judge/pt/problems/view/1013
URI Online Judge | 1013
O Maior
Adaptado por Neilor Tonin, URI Brasil
Timelimit: 1
Faça um programa que leia três valores e apresente o maior dos três valores lidos seguido da mensagem “eh o maior”. Utilize a fórmula:
Entrada
O arquivo de entrada co... |
"""Just a bunch of Codes"""
from done.String import multiple_replace, createTranslationTable
def unbinary(text):
"""Change string of ones and zeroes into the actual string"""
return ''.join(chr(int(i, 2)) for i in text.split())
def binary(text, to_binary=True):
"""Change string into binary bytes (actua... |
import re
class StringConditionsException( Exception ):
pass
def array_has_any( any, array ):
matched = False
for a in any:
if a in array:
matched = True
return matched
def array_has_all( all, array ):
for a in all:
if a not in array:
return False
return True
def remove_values_from_list( the_lis... |
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o primeiro número: "))
resul = n1 + n2
print("A soma entre {} e {} é de {}" .format(n1,n2,resul)) |
n1 = float(input("Digite um número: "))
print("O sucessor de {} é {} e o seu antecessor é de {}" .format(n1,n1+1,n1-1)) |
from math import trunc
n1 = float(input("Digite um valor qualquer: "))
print("o número {} tem a parte inteira {}" .format(n1,trunc(n1))) |
import nltk
nltk.download('stopwords')
import sys
import os
import string
import math
FILE_MATCHES = 1
SENTENCE_MATCHES = 1
def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python questions.py corpus")
# Calculate IDF values across files
files = load_files(... |
from cs50 import get_int
# getting a number
while True:
print("Give a positive integer not greater then 8")
n = get_int()
if n > 0 and n < 9:
break
# printing bloxx
for i in range(n):
for j in range(n - i - 1):
print(" ", end="")
for k in range(i + 1):
print("#", end="")
... |
from sys import argv
from cs50 import get_string
if not len(argv) == 2:
print("Usage: ./caesar key")
exit(1)
else:
key = int(argv[1])
message = get_string("plaintext: ")
cyphertext = ""
for c in range(len(message)):
if message[c] >= 'a' and message[c] <= 'z':
cyphertext +=... |
"""
LeetCode Problem 20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
"""
class Solution(object):
def isVal... |
"""
LeetCode 4. Median of two sorted arrays
Given two sorted arrays, return the median.
"""
The overall run time complexity should be O(log (m+n)).
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
... |
'''
LeetCode 62. Unique paths
A robot is located in top-left corner of m x n grid. How many unique paths are there to
opposite corner?
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.